How to calculate the probability value of multiple probabilities

Question: The question arises from baffled curiosity. I have consulted stats textbooks, e.g. Agresti & Franklin, Statistics, but don't know which heading to look under. My precise question is this. Suppose an event, X, is witnessed by five independent witnesses the relability of each of whose testimony is <.5. Say : .2, .3. .3. 4. .4. I have a sense - excuse my naivety - that the combination of these probabilities, given the independence of the witnesses, could be = .5 or >.5.
I'd appreciate someone's doing the calculation for me and (so that I can make my own headway) directing me to the relevant area of stats. My interests are legal and historical. But I sure need some maths help.
Comment: So you want something like "What is the probability the event occurred, given the reliability of each individual"? Sorry I didn't quite understand what you want.
Comment: @Tony Hellmuth. Thanks for comment. You have the point exactly. The probability of each independent witness' testimony is >.5. I wondered if the joint probability of the independent witnesses' testimony was higher than .4. Best : GT
Comment: Well it does depend on how you define the event that a witness is reliable. Say if $Y_i=1$  if witness i was right and  $Y_i=0$ if witness i was wrong, perhaps we can say $P(Y_1=1 \cap Y_2=1 \cap ... \cap X_n=1 )=P(Y_1=1)P(Y_2=1) \cdot ... \cdot P(Y_n=1)$ for n witnesses. If each has say probability of $P(Y_i=1)=0.9$, then we have probability of all witnesses being right of $0.9^5=0.59049>0.5$
Comment: @Tony Hellmuth. Thank you very much. If I may tax your patience just a little more, what is the probablity of all witnesses being wrong ? Final question, I promise. Best- GT
Comment: You can ask me anything you want! It's why I'm here :) So essentially, our random variable $Y_i$ takes value 0 if the witness is wrong. Similar to above we find $P(Y_1=0 \cap Y_2=0 \cap ... \cap X_n=0 )=P(Y_1=0)P(Y_2=0) \cdot ... \cdot P(Y_n=0)$. Again assuming probability of each witness being right is $P(Y_i=1)=0.9$ then $P(Y_i=0)=1-P(Y_i=1)$ under our definition of $Y_i$. So we get $0.1^5$ which is 1 in 100,000. However this will not be the case. Usually we want a scenario where we want to know the probability that at least one of them is right. $P(Y_1=1 \cup Y_2=1 \cup ... \cup X_n=1 )$
Comment: @Tony Hellmuth. Many thanks indeed. Best : GT
Answer: The real difficulty with this problem is to find the appropriate way to model this question to fit the idea of "reliability".
Let $\{Y_i\}$ be a sequence of Bernoulli random variables indicating eyewitness testimony. Let $X$ be a Bernoulli random variable indicating whether or not the event in question happened. Suppose that without any eyewitness testimony, we would assume it had happened with probability $q$.
Clearly $\{Y_i\}$ are not i.i.d. because they are all jointly influenced by whether or not the event in question happened. However, we can assume that they are conditionally independent given $X$. That is, once we know that the event happened, the witnesses all choose to lie about the event or tell the truth about it independently.
So now let's define reliability. Roughly speaking, reliability is a measure of how likely a given person's statement is to be true. In reality, they could be more or less reliable for any number of reasons. In this case, let's say each eyewitness either lies or tells the truth. Furthermore, they tell the truth with probability given by the reliability assigned to them (.2,.3,.3,.4 and .4 respectively). Suppose $Y_i$ has reliability $p_i$. Then in mathematical notation, this boils down to
$$\mathbb{P}(Y_i = j|X=j) = p_i \text{ for } j \in \{0,1\}$$
Now we can do some simple Bayesian statistics.
$$\mathbb{P}(X=1|Y_1=\cdots=Y_n=1) = \mathbb{P}(Y_1=\cdots=Y_n=1|X=1)\frac{\mathbb{P}(X=1)}{\sum_{j=0}^1 \mathbb{P}(X=j)\mathbb{P}(Y_1=\cdots=Y_n=1|X=j)} = \prod_{i=1}^np_i\frac{q}{q\prod_{i=1}^np_i + (1-q)\prod_{i=1}^n(1-p_i)}$$
Let's go back to the original question. Since there was no information regarding $X$, we can probably assume that $q=1/2$. Plugging everything in,
$$\mathbb{P}(X=1|Y_1=\cdots=Y_5=1) = 0.02$$
So it was very likely that the event did not happen. Why is this? Keep in mind that an eyewitness that was equally likely to tell the truth or lie would have a reliability of $0.5$. These eyewitnesses with reliability below 0.5 are more likely to lie than tell the truth. If several of them all claim an event happened, then it probably didn't.
Just to test our model out, now assume all five witnesses are assigned a reliability of 0.6. Then,
$$\mathbb{P}(X=1|Y_1=\cdots Y_5=1) = 0.88$$
So when eyewitnesses are even slightly more likely to tell the truth than lie, the fact that five of them agree it happened adds significant weight. In this case, we can now say $X$ happened with probability 0.88.
Comment: Good answer, but the assumption of conditional independence of the eyewitnesses' testimony should be carefully scrutinized in any real world  situation.  There are many ways it might fail.


UITableViewCell content not filling up whole cell

Question: I am trying to implement custom UITableViewCells in my app. I want to add a UIScrollView with several subviews to each UITableViewCell and enable horizontal scrolling. I was mostly able to do it except with the height and grouping. Check out my code and screenshot below. I am not able to change the UIScrollView's height to a number greater than 44 points.
How can I add a UIScrollView, with a height greater than 44, to my custom UITableViewCell?
#import "HomeViewController.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Home Scroll Cell";
    homeScrollCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[homeScrollCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    NSLog(@"Cell: %f", cell.bounds.size.height);

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100.0;
}

@end

UITableCell class
#import "homeScrollCell.h"

@implementation homeScrollCell

//- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
//{
//
//}

-(id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 100)];
        NSInteger viewcount= 3;
        for(int i = 0; i< viewcount; i++) {

            CGFloat x = i * self.bounds.size.width;
            HomeTodayView *view = [[HomeTodayView alloc] initWithFrame:CGRectMake(x, 0,self.bounds.size.width, self .bounds.size.height)];
            view.backgroundColor = [UIColor greenColor];

            [scrollView addSubview:view];

        }
        scrollView.contentSize = CGSizeMake(self.bounds.size.width *viewcount, 100);
        scrollView.pagingEnabled = YES;
        scrollView.bounces = NO;
        [self addSubview:scrollView];

        NSLog(@"Height: %f", self.bounds.size.height);
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
  //  [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

Answer: Set the UIScrollView's frame to be the tableViewCell's bounds (or frame, I never remember off the top of my head):
scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];

Then set it's height to autoResize
scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

You shouldn't have to manually change the cell's height within the actual cell. The height should all be managed in your TableViewController's delegate methods.
Comment: Thanks, I think I got it! I needed to autoresize the subview too, so it fits.
Answer: You aren't setting frame of the cell
Have you tried checking in line where you init the HomeTodayView what is the return value of self.bounds.size.height?
Maybe you could make another initializer for your cell with another parameter - frame? Start it like this:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier frame:(CGRect)frame
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.frame = frame;

        /* rest of the init method you already have goes here */

Basically, just add self.frame = frame; at the start of the 'if'.
Comment: 2013-07-24 16:06:34.842 EDM[11833:c07] Height: 44.000000
2013-07-24 16:06:34.843 EDM[11833:c07] Cell: 44.000000
2013-07-24 16:06:34.844 EDM[11833:c07] Height: 44.000000
2013-07-24 16:06:34.845 EDM[11833:c07] Cell: 44.000000

Here is the NSLog I do, height is from Cell class, Cell is from View Controller
Comment: in your initWithStyle(...) method frame isn't set to what you want, so you could try making another init method -(id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier frame:(CGRect)frame,     where you set the frame of the cell
Comment: And how should I use the frame parameter?
Comment: Edited my answer with setting the frame
Answer: initial size of UItableViewcell is 44.0f You Check it after calling
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

You need to make you scrollView height stretchable.
scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight;

It helps for me.
Comment: http://i.imgur.com/VXvEwYR.png It increased the size of the scroll view, but it did not fill it.
Answer: Just use
        CGFloat x = i * self.bounds.size.width;
        HomeTodayView *view = [[HomeTodayView alloc] initWithFrame:CGRectMake(x, 0,self.bounds.size.width, scrollView.bounds.size.height)];
        view.backgroundColor = [UIColor greenColor];

Or replace your whole code with
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width,self.bounds.size.height)];
        [scrollView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
        NSInteger viewcount= 3;

        for(int i = 0; i< viewcount; i++)
        {
            CGFloat x = i * self.bounds.size.width;

            HomeTodayView *view = [[HomeTodayView alloc] initWithFrame:CGRectMake(x, 0,self.bounds.size.width,scrollView.bounds.size.height)];
            view.backgroundColor = [UIColor greenColor];

            [scrollView addSubview:view];
        }

        scrollView.contentSize = CGSizeMake(self.bounds.size.width *viewcount, 100);
        scrollView.pagingEnabled = YES;
        scrollView.bounces = NO;
        [self addSubview:scrollView];

        // Initialization code
    }
    return self;
}

Even if u didn't understand whats the problem was, then have a look at following lines
Your problem got here
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 100)];

You are setting scrollView height to constant value so scrollView does not resize when HeightForRowAtIndex path resizes height of cell.
And setting [scrollView setAutoresizingMask:UIViewAutoresizingFlexibleHeight]; will allow scrollView to resize when its container resizes and also allows its contents to be resized.
Check this Demo
Comment: Thanks man, my internet was going up and down and I didn't see your answer!Much appreciated!
Comment: Actually, it still limits it to the 44. Here is the screenshot. I set the HeightForRow to 500 and added red as scrollview background.

http://i.imgur.com/tCgac71.png
Comment: need to send u demo right? @user2067051 check demo uploaded in answer


Syndras E - Force of Will with Iverns R- Daisy

Question: I know that there are some special interactions when Syndra uses her E ability with neutral monster like blue buff or red buff and throws it on enemies.
Is there a similar interaction when she grabs Daisy, the ult of Ivern?
Answer: No. The special interactions are unique to Ancient Golem and Lizard Elder.

Force of Will has additional effects when targeting the Ancient Golem and Lizard Elder. Throwing the former will refund 10 mana to Syndra upon cast and will reduce the cooldown of Force of Will by 1 second, while throwing the latter will apply the Blessing of the Lizard Elder burn to any affected units in the area of effect.

Regarding pets:

Enemy pets that passively have an effect on their surroundings will continue to affect the area around them while they are being held. For example, Annie's Tibbers will continue to inflict burn damage on surrounding units while in stasis.

Source
More information on the Stasis effect:

A unit that is in stasis is unable to control movement, declare attacks, cast abilities, activate items or use any summoner spell for the duration, while also being invulnerable and untargetable for the duration.


Shopify API - Select all the customer based on tags?

Question: We have defined all the customers in our shopify store with different tags like "Price Level 1",  "Price Level 2", "Price Level 3" ---- so on till "Price Level 16" and new customer are without any tag. Through the shopify API I want to fetch customers based on there tag, I tried different URL
https://apikey:password@hostname/admin/customers.json?tags:Price Level 1
https://apikey:password@hostname/admin/customers.json?tags="Price Level 1"
https://apikey:password@hostname/admin/customers.json?query=Price Level 1

but all the URL give me the same Result i.e customer with any tag. Please guide me with the best way through which I can fetch the customer based on exact tag name and also how can I fetch the customer without any tag.
Answer: To apply a query you need to use the search endpoint:
 https://store.myshopify.com/admin/customers/search.json?query=%27Price%20level%201%27

Note when your tags have spaces you have to include quotes in the query. If you are using Node then the easiest way to get this is
escape("'Price Level 1'");

Comment: Thanks for your reply . Its work perfect , I'm getting all the customer who have "Price Level 1" . How can I search if the tags element is empty. i.e "tags": "",
Comment: I don't think you can do that.
Comment: Thanks for the reply one more question . Can I add Tag Using API ?
Comment: Yes of course but you should make it a new question


MongoDB backup after schema was changed

Question: I have created dump for foo collection, after that I have changed foo schema (added additional documents and fields), so is it possible in MongoDB to restore old data and keep current schema? Please suggest me some solutions.
Comment: What do you mean by keep current schema? There is no fixed schema in MongoDB so if you restore data from a dump it won't inherit any new fields written in a document. That said you can definitely restore your old data into a collection with a new schema and they can live side by side. See the following for a MongoDB data modeling overview: http://docs.mongodb.org/manual/core/data-modeling/#data-modeling-considerations-for-mongodb-applications
Answer: MongoDB does not enforce a schema. You can easily restore your old documents into the same collection as your new ones. You can write your application to expect old-style or new-style documents when you query them. Or you could use update with operators like set or rename to update the old-style documents and make them conform to the new schema.

MongoDB backup after schema was changed


Can't get a fixed value on a final hashmap in android

Question: I am developing a an android app that uses service discovery over wifi direct,based on the provided google sample code, the problem is i can't get a fixed value of the advertised TXT record even though i'm using a final hashmap to store the value, the Hashmap is modified every time the onDnsSdTxtRecordAvailable callback is called, even though i'm using a final hashmap declared globally to store the first value, it gets replaced by null. here is the code i'm using. thanks
<code>  private WifiP2pManager manager;

        private final IntentFilter intentFilter = new IntentFilter();
        private Channel channel;
        private BroadcastReceiver receiver = null;
        private WifiP2pDnsSdServiceRequest serviceRequest;
        private TextView statusTxtView;
        private TextView services;
        private Button register;
        private Button broadcast;
        private LocationManager locationManager;
        final HashMap<String, String> buddies = new HashMap<String, String>();
        private TextView locationTxt;
        public String value1;
        private Button loc;
        private final String name = new String();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            statusTxtView = (TextView) findViewById(R.id.status);
            services = (TextView) findViewById(R.id.services);
            register = (Button) findViewById(R.id.discover);
            broadcast = (Button) findViewById(R.id.bd);
            locationTxt = (TextView)findViewById(R.id.location);

            loc = (Button)findViewById(R.id.loc);
            intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
            intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
            intentFilter
                    .addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
            intentFilter
                    .addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

            manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
            channel = manager.initialize(this, getMainLooper(), null);
            startRegistrationAndDiscovery();
            register.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startRegistrationAndDiscovery();
                }
            });

            broadcast.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    discoverService();
                }
            });

            loc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    doIt();
                }
            });

        }

@Override
        public void onResume() {
            super.onResume();
            receiver = new MyReceiver(manager, channel, this);
            registerReceiver(receiver, intentFilter);
        }

        @Override
        public void onPause() {
            super.onPause();
            unregisterReceiver(receiver);
        }

        public void appendStatus(String status) {
            String current = statusTxtView.getText().toString();
            statusTxtView.setText(current + "\n" + status);
        }

        //service discvery handllng methods
        private void startRegistrationAndDiscovery() {
            Map<String, String> record = new HashMap<String, String>();
            record.put(TXTRECORD_PROP_AVAILABLE, "visible");
            WifiP2pDnsSdServiceInfo service = WifiP2pDnsSdServiceInfo.newInstance(
                    SERVICE_INSTANCE, SERVICE_REG_TYPE, record);
            manager.addLocalService(channel, service, new ActionListener() {

                @Override
                public void onSuccess() {
                    appendStatus("Added Local Service");
                }

                @Override
                public void onFailure(int error) {
                    appendStatus("Failed to add a service");
                }
            });

            discoverService();

        }

        private void discoverService() {
           /*
             * Register listeners for DNS-SD services. These are callbacks invoked
             * by the system when a service is actually discovered.
             */

            manager.setDnsSdResponseListeners(channel,
                    new DnsSdServiceResponseListener() {

                        @Override
                        public void onDnsSdServiceAvailable(String instanceName,
                                                            String registrationType, WifiP2pDevice srcDevice) {

                            // A service has been discovered. Is this our app?

                            if (instanceName.equalsIgnoreCase(SERVICE_INSTANCE)) {

                                // update the UI and add the item the discovered
                                // device.

                                   /* WiFiP2pService service = new WiFiP2pService();
                                    service.device = srcDevice;
                                    service.instanceName = instanceName;
                                    service.serviceRegistrationType = registrationType;*/
                                //put data to textview here
                                services.setText(srcDevice.status+" Instance name " + instanceName + " type " + registrationType);
                                Log.d(TAG, "onBonjourServiceAvailable "
                                        + instanceName);
                                Http_client http_client = new Http_client(SERVICE_INSTANCE);
                                appendStatus("data sent to server successfully");

                            }

                        }
                    }, new DnsSdTxtRecordListener() {

                        /**
                         * A new TXT record is available. Pick up the advertised
                         * buddy name.
                         */
                        @Override
                        public void onDnsSdTxtRecordAvailable(String fullDomainName, Map<String, String> record,WifiP2pDevice device) {
                            Log.d(TAG, device.deviceName + " is " + record.get(TXTRECORD_PROP_AVAILABLE));
                           buddies.put("mm",record.get(TXTRECORD_PROP_AVAILABLE));

                            Toast.makeText(getBaseContext(),record.get(TXTRECORD_PROP_AVAILABLE),Toast.LENGTH_LONG).show();
                            //
                        }
                    });

            // After attaching listeners, create a service request and initiate
            // discovery.
            serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
            manager.addServiceRequest(channel, serviceRequest,
                    new ActionListener() {

                        @Override
                        public void onSuccess() {
                            appendStatus("Added service discovery request");
                        }

                        @Override
                        public void onFailure(int arg0) {
                            appendStatus("Failed adding service discovery request");
                        }
                    });
            manager.discoverServices(channel, new ActionListener() {

                @Override
                public void onSuccess() {
                    appendStatus("Service discovery initiated");
                }

                @Override
                public void onFailure(int arg0) {
                    appendStatus("Service discovery failed");

                }
            });
        }
        public void doIt(){
            buddies.put("mm","value1");
            Toast.makeText(getBaseContext(),buddies.get("mm"),Toast.LENGTH_LONG).show();
            buddies.put("mm","value2");
            Toast.makeText(getBaseContext(),buddies.get("mm"),Toast.LENGTH_LONG).show();

        }
</code>
Comment: A final hashmap variable buddies, means that the variable buddies cannot point to a different hashmap, but the values within the hashmap can be changed at any time.
Comment: How can i fix the value it gets at first, because the first value is replaced by null, and i need the first value to be stored for later use
Answer: A final variable will not help you, as I have commented. Based on your question, what you need to do is to always check if the value is set in your hashmap, before saving the new returned variable. Something like
<code>if (!buddies.containKey("mm"))
    buddies.put("mm", .....)
</code>


How can I pass a param to a promise inside usePromise React hook

Question: I created an usePromise React Hook that should be able to resolve every kind of javascript promise and returns every result and state: data, resolving state and error.
Im able to make it work passing the function without any param, but when I try to change it to allow a param, I get an infinite loop.
const usePromise = (promise: any): [any, boolean, any] => {
  const [data, setData] = useState<object | null>(null);
  const [error, setError] = useState<object | null>(null);
  const [fetching, setFetchingState] = useState<boolean>(true);

  useEffect(() => {
    setFetchingState(true);
    promise
      .then((data: object) => {
        setData(data);
      })
      .catch((error: object) => {
        setError(error);
      })
      .finally(() => {
        setFetchingState(false);
      });
  }, [promise]);

  return [data, fetching, error];
};

const apiCall = (param?: string): Promise<any> => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({ response: `Response generated with your param ${param}.` });
    }, 500);
  });
};

const App = (): React.Element => {
  // How can I pass an argument to apiCall?
  const [response, fetching, error] = usePromise(apiCall(5));
  console.log("render"); // This logs infinitely
  return
{JSON.stringify({ response, fetching, error })}
;
};

You can check the working code (without params) at: https://codesandbox.io/s/react-typescript-fl13w
And the bug at (The tab gets stuck, be adviced): https://codesandbox.io/s/react-typescript-9ow82
Note: I would like to find the solution without using a usePromise single function library from NPM or similar
Comment: does your code handles , promises.all type of response ? if not then remove the [promise] as dependency and make call like () => apiCall(5)  inside usePromise
Answer: Custom hooks might be executed multiple times. You should design it that way, that everything you want to do just once (e.g. the API call) is inside a useEffect hook. That can be achieved by taking a callback that gets then called in a hook.
Also, slightly more typesafe:
 const usePromise = <T>(task: () => Promise<T>) => {
   const [state, setState] = useState<[T?, boolean, Error?]>([null, true, null]);

   useEffect(() => {
       task()
         .then(result => setState([result, false, null])
         .catch(error => setState([null, false, error]);
  }, []); // << omit the condition here, functions don't equal each other²

  return state;
};

// Then used as
usePromise(() => apiCall(5));

² yes, thats generally a bad practice, but as task is not supposed to change here, I think that's fine

Upon request, here's a version that I use in some of my projects:
 export function useAPI<Q, R>(api: (query: Q) => Promise<R | never>) {
  const [state, setState] = useState<{ loading?: true, pending?: true, error?: string, errorCode?: number, result?: R }>({ pending: true });

  async function run(query: Q) {
    if(state.loading) return;
    setState({ loading: true });

    try {
        const result = await api(query);
        setState({ result });
    } catch(error) {
        if(error instanceof HTTPError) {
            console.error(`API Error: ${error.path}`, error);
            setState({ error: error.message, errorCode: error.code });
        } else {
            setState({ error: error.message, errorCode: NaN });
        }
    }
  }

  function reset() {
     setState({ pending: true });
  }

  return [state, run, reset] as const;

}

Comment: That's difficult. What should happen to the currently ongoing API call? Make sure to get cancellation right, and also be careful with the parameters. Objects are compared by reference in react.
Comment: the reason being ```useEffect``` has  dependency ```promise``` which is a function which contains ```setTimeOut```/ ```promise``` and everytime the component renders , a new setTimeout is being pushed to the callbackQueue from the apis section , thereby infinite async and causing re-rendering
Comment: Hey @Jonas thank you very much for your answer. I found out that, if the component is mounted and the param of `apiCall` changes, the `usePromise` result is not updated. I think that it should receive the params of the function as the hook comparator (second param of the `useEffect`). What do you think? https://codesandbox.io/s/react-typescript-bgqrp
Comment: Yeah, thats a good point! If you have any `usePromise` or generic solution better than mine, please share. Thank you very much!
Comment: @rashomon Yeah, I do have one that I use often, not sure if it fits to your usecase exactly.


Which collection class to use for a rolling period timeseries of data?

Question: I want to imlpement a c# class (.NET 4.6.1) which contains time series data as follows :

the timeseries is a collection keyed on DateTime, each with an associated value (eg an array of doubles)
the points will be added strictly in time order
there will be a rolling time period - e.g. 1 hour - when adding a new point, any points at the start older than this period will be removed
the key issues for performance will be quickly adding new points, and finding the data point for a particular time (a binary search or better is essential). There will be 100k's of points in the collection sometimes.
it has to be thread safe
it has to be relatively memory efficient - e.g. it can't just keep all the points from the beginning of time - as time moves on the memory footprint has to be fairly stable.

So what would be a good approach for that in terms of underlying collection classes? Using Lists will be slow - as the rolling period means we will need to remove from the start of the List a lot. A Queue or LinkedList would solve that - but I don't think they provide a fast way to access the nth item in the collection (ElementAt just iterates so is very slow).
The only solution I can think of will involve storing the data twice - once in a collection thats easy to remove from the start of - and again in one thats easy to search in (with some awful background process to prune the stale points from the search collection somehow).
Is there a better way to approach this?
Thanks.
Comment: Why would List be slow, remove item at end should be O(1)
Comment: But to prune the stale data I will have to remove items from the start of the List - which I believe is slow when the list is large.
Comment: My bad - it's O(Count) not O(count) :-)
Comment: You might want to look in to [`SortedList`](https://msdn.microsoft.com/en-us/library/ms132319(v=vs.110).aspx), you will just need to wrap it up with a [`ReaderWriterLockSlim`](https://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim(v=vs.110).aspx) on every read or write access to make it thread safe.
Comment: The trouble with SortedList is that its also slow to remove items from the start of the list - ie its O(n) - so very slow when there are 100k+ items in the collection.
Answer: When I first saw the question I immediately thought of a queue, but most built-in queues do not efficiently allow indexed access, as you've found.
Best suggestion I can come up with is to use a ConcurrentDictionary. Thread-safe, near-constant access time by key, you can key directly to DateTimes, etc. it's everything you need functionally, except the behavior to manage size/timeline. To do that, you use a little Linq to scan the Keys property for keys more than one hour older than the newest one being added, then TryRemove() each one (you can derive from ConcurrentDictionary and override TryAdd() to do this automatically when adding anything new).
Only other potential issue is it's not terribly memory-efficient; the HashSet-based implementation of .NET Dictionaries requires a two-dimensional array for storage based on the hash of the key, and that array will be sparsely populated even with 100k items in the collection.
Comment: Thanks for the quick reply - I'll give ConcurrentDictionary a try. I will probably have to keep a seperate collection of the keys - since I want to also be able to lookup on not exact key values and return the previous value. However this will be a lot better than my previous idea.
Comment: The Keys collection in the Dictionary is essentially a ReadOnlyCollection; you can do Linq queries and other list-based read operations on it, including finding the maximum key value less than an example timestamp. It's thread-safe, but to do that, they have to clone the actual Dictionary's key array, so operations made on the "fringes" of the expected key values may not be reliable if you're constantly inserting and deleting keys in other threads.
Comment: I thought referencing Keys on a dictionary would involve creating a new collection of the keys from scratch each time? If not this would be perfect. Can you confirm this isn't what it does?
Comment: That is essentially what it does; the Keys property returns an `ICollection` generated by cloning the underlying Dictionary's Keys property. It's the fastest and easiest way to make this operation thread-safe. To come up with something better, you'll have to implement a locking system that allows multiple enumerations of a collection in-place but blocks on concurrent access to each element. That will inevitably produce deadlocks when different threads enumerate the collection at different speeds or in different orders, which you'll have to detect and resolve.
Comment: If you really need to do all that, I would recommend interfacing with a database engine; SQLite or just an instance of SQL Server Express would be more efficient and concurrency-tolerant than anything you could come up with in the next week of development. Write a simple class to perform the tasks you need, which will interface with the SQL engine to do those things, and you're done.


Preowned/Used Games for PS4

Question: As much as the answer is known to be a "Yes", I want to understand the following:

Can I buy a preowned (used-very good/like new) game to use in PS4?
What should I not be expecting from a used/pre-owned PS4 game?

The question behind this is the Call of Duty: Advanced Warfare which I believe has gone down to an affordable range and I think I can buy one. But wasn't sure if I can actually play it normally?
Comment: About preowned game, only make sure about the DLC codes, if they are included but used, you can't use it again.
Answer: As DGarvanski has already covered, there isn't any weird checking if you want to use pre-owned games on PS4. Like most pre-owned games however, if there was any additional content that was unlocked by the use of downloadable content, or passes or something similar, the likelihood of this still being available for a pre-owned game is unlikely, as they are only one-time use.
For future reference, Playstation have released an official guide for sharing/using pre-owned games on the Playstation 4 system:
Comment: Love the video, so detailed and thorough!
Comment: Specifically, if highlighted the difference between how Sony and Microsoft were approaching this console generation.  MS was going to make a console that didn't allow used games and had a number of other dumb mistakes.  Sony capitalized upon these mistakes, and even though MS changed policies before launch, the PS4 came out with an early lead that it never lost.
Comment: @MonkeyZeus This video is one of the reasons that Sony is winning the current console war.  Well, not this video itself, but what it represented.
Answer: Yes, you can play it normally.
The PS4 allows the use of pre-owned games without any online checks or weird DRM. I've checked and Call of Duty: AW has no "Online Pass" system in place so you wouldn't have to buy anything extra in order to play. The only thing that will be different is if you buy a special edition since you wouldn't have access to the DLC that comes with that edition unless you buy it separately . However, the PS4 will not have any problems with you playing a used copy.

Preowned/Used Games for PS4


Solution to a system of symmetric equations: $(x+y)^2 + (x+z)^2 = \frac{2}{3} \lambda x$ etc.

Question: After applying the Lagrange multiplier method, I got the following system of equations, which is quite symmetric:
$$(x+y)^2 + (x+z)^2 = \frac{2}{3} \lambda x$$
$$(y+x)^2 + (y+z)^2 = \frac{2}{3} \lambda y $$
$$(z+x)^2 + (z+y)^2 = \frac{2}{3} \lambda z$$
It is claimed that this system of equations is satisfied only when $x=y=z$. Could anyone explain why?
Answer: Obviously, $x=y=z$ leads to the solutions $x = y = z = 0$ and $x = y = z = \frac {\lambda}{12}$. Now, let's assume $x \ne y \ne z$. Subtract second equation from first, third from first and third from second, so you'll get equivalent system
$$
\begin{align}
(x-y)(x+y+2z) &= \frac 23 \lambda (x-y)\\
(x-z)(x+2y+z) &= \frac 23 \lambda (x-z)\\
(y-z)(2x+y+z) &= \frac 23 \lambda (y-z)
\end{align}
$$
or
$$
\begin{align}
x+y+2z &= \frac 23 \lambda\\
x+2y+z &= \frac 23 \lambda\\
2x+y+z &= \frac 23 \lambda
\end{align}
$$
since we assumed that $x \ne y \ne z$.
Comparing first and second, one may conclude that
$$
x+y+2z = x+2y+z
$$
or equivalently
$$
y = z
$$
Considering other two pairs one may conclude
$$
x = y = z
$$
which is in contradiction with initial assumptions. So the only solutions are those when $x = y = z$.
Update
As it was pointed out, one also may check case when $x = y$ but $z \ne x,y$. In this case consider first and third equations
$$
\begin{align}
4x^2 + (x+z)^2 &= \frac 23 \lambda x \\
2(z+x)^2 &= \frac 23 \lambda z
\end{align}
$$
Subtract first from second
$$
(z-x)(z+3x) = \frac 23 \lambda (z-x)
$$
Since we're assuming $z \ne x$, then
$$
z+3x = \frac 23 \lambda
$$
or explicitly
$$
z = \frac 23 \lambda - 3x
$$
Substitute it to the any of previous two, let's say second equation
$$
\left(\frac 23 \lambda - 2x\right)^2 = \frac 13 \lambda \left( \frac 23 \lambda  -3x\right)
$$
and if you solve it, you'll get complex values for $x$. So, contradiction.
In the same manner you can assume $z=y$, $x \ne y,z$ and $z=x$, $y \ne x,z$.
Comment: This does not cover the case that only two out of three are equal (e.g. $x=y$, $z\neq x$, $z \neq y$).
Comment: @WimC you're right, it doesn't. I'll fix it in a minute.
Answer: Interpreted as $3$-vectors, the left hand side and the right hand side (without the $\lambda$-factor) must be dependent.  That means that all $2 \times 2$ minors of the matrix
$$\begin{pmatrix} (x+y)^2+(x+z)^2 & x\\
(y+x)^2+(y+z)^2 & y\\
(z+x)^2+(z+y)^2 & z
\end{pmatrix}
$$
must vanish (or in other words the cross product of the colums must be zero).  Let's consider the first one:
$$ 0 = y \left( (x+y)^2 + (x+z)^2 \right) - x \left((y+x)^2 + (y+z)^2 \right) = (y-x)(x^2 + xy + y^2 + z^2).
$$
So either $x=y$ or $x^2 + xy + y^2 + z^2 = 0$.  The latter implies that $x=y=z=0$ since the quadratic form is positive definite over $\mathbb{R}$.  In either case $x=y$.  Other equalities follow similarly from the other minors.
One way to show that the quadratic form is positive definite is to write it as a positive combination of squares:
$$x^2 + xy + y^2 + z^2 = \frac{1}{2}\left(x + \frac{1-\sqrt{3}}{2} y\right)^2 + \frac{1}{2} \left(x + \frac{1+\sqrt{3}}{2} y\right)^2 + z^2$$
Comment: @MichaelNgelo Added the matrix explicitly.
Comment: What do you mean by "all 2×2 minors must vanish"? What matrix are you considering?


multiple image uploading nodejs reactjs multer

Question: I'm trying to make a upload image feature in my website. I've worked on uploading a single image and it worked how do I change my code to make it upload multiple images at same time code below:
Server Side:
// img storage confing
var imgconfig = multer.diskStorage({
    destination: (req, file, callback) => {
        callback(null, "./uploads");
    },
    filename: (req, file, callback) => {
        callback(null, `image-${Date.now()}.${file.originalname}`)
    }
});

// img filter
const isImage = (req, file, callback) => {
    if (file.mimetype.startsWith("image")) {
        callback(null, true)
    } else {
        callback(null, Error("only image is allowd"))
    }
}

var upload = multer({
    storage: imgconfig,
    fileFilter: isImage
})

// register userdata
app.post("/insertImage", upload.single("photo"), (req, res) => {
    const { filename } = req.file;

    console.log(req.file)
});
Client Side:

  const [file, setFile] = useState("");

  const setimgfile = (e) => {
    setFile(e.target.files[0])
  }

  const addUserData = async (e) => {
    e.preventDefault();

    var formData = new FormData();
    formData.append("photo", file)

    const config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    }

    const res = await Axios.post("/insertImage", formData, config);

    if (res.data.status == 201) {
      console.log("NO error")
    } else {
      console.log("error")
    }
  }

REACT JSX
Here is my input file and multiple is added here
What should i do?? Please help me

Upload file:

            <input type="file" name='photo' onChange={setimgfile} multiple/>
            <button onClick={addUserData}>submit</button>

Answer: UI:
const [files, setFile] = useState("");

const setimgfile = (e) => {
  setFile(e.target.files)
}

const addUserData = async (e) => {
  e.preventDefault();

  var formData = new FormData();

  for (const file of files) {
    formData.append('files', file)
  }

  const config = {
    headers: {
      "Content-Type": "multipart/form-data"
    }
  }

  const res = await Axios.post("/insertImage", formData, config);

  if (res.data.status == 201) {
    console.log("NO error")
  } else {
    console.log("error")
  }
}

Upload file:

  <input type="file" name='photo' onChange={setimgfile} multiple />
  <button onClick={addUserData}>submit</button>

BACKEND:
import multer from 'multer';
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // Uploaded files destination
    cb(null, "uploads/");
  },
  filename: (req, file, cb) => {
    const newFilename = `${new Date().getDate()}-${new Date().getMonth() + 1}-${new Date().getFullYear()}-${file.originalname}`;
    cb(null, newFilename);
  }
});

const upload = multer({ storage }).array('files');

app.post("/insertImage", upload, (req, res) => {
  console.log('success')
});


how can I fix a removed studs, on wall in basement above stairs?

Question: I had my basement waterproofed, and some studs had to be cut to drill for the drainage pipe. They also cut the bottom plate, which I cut a piece of PT wood and set it in place where the section was removed.
I can't remove the existing cut studs, because the drywall behind it is attached to them.  The stringers are secured to the basement ground, and one stringer attached to the brick wall on other side, I think the studs might attach to them also, but I'm not 100% sure.
How do I make this to code?  Or ... if not possible any longer, how do I make this structurally strong.
Comment: I don't think it's bearing load, could I just sister in a stud next to the second cut stud from the left?  then call it good?
Comment: Almost anyway you want for a non load bearing wall.  Studs there are mostly for nailing/screwing wall covering to.  The stud on the left side shows one way, but I like more surface.  I would try to mark(pencil, tape) the floor and/or ceiling if the studs are sifted over.  Nothing worst than screwing drywall to a stud and half way down find the stud missing.  Load bearing wall studs do need specific ways of repair and probably need an engineer before and after.
Comment: Non load bearing can do almost anything, sistering probably the easiest.  Someway to remember where studs change places would help in future.  Expecting a stud at 16 OC but is at 18 OC is nice to know for nailing/screwing.
Comment: why would you want to replace them if as you say they are not needed for the structure, if for drywall you can use horizontal studs
Comment: So I see from the edit you deleted the load bearing part in the title. Are you sure this isn't a load bearing wall? If it isn't load bearing, fixing is easy. If it is load bearing, you really want to add studs where they were cut.
Comment: It's not load bearing for the house, but the stringers are fastened to to some of the studs.  I just sistered the second cut stud from the left, seems much better to me this way.... I don't know what that first stud, that is two pieces in differing places, really was adding anyway.
Comment: Could you get us a better focused and lit picture of the wall, please. Also, include more of the top of the studs and what they're supporting. It does appear that these studs are simply there to hang the drywall from, but I wouldn't want to commit to that statement. If it _is_ a load bearing wall, your waterproofing contractor should be shot for just cutting up a load bearing wall like that, then held responsible for a proper replacement/repair.
Comment: @FreeMan I'll take some more pictures, I'm pretty sure it's not load baring because the wall was not present at the time the house was built in 1921.   I can tell by the studs, which are all in post 1964 sizes, my guess it that it was built sometime after mid 80s.  A door was added to the basement entry, which was why the wall was initially built, but i removed it.  It's not load bearing for the house.
Comment: @FreeMan, OK I've taken more pictures with light and even one looking down on the stairs.  The drywall is the white colored wall in that picture.  I don't believe it's load bearing for the house,... but there could have been a prior wall, that got rotted out, and was replaced.  I also sistered a stud in place, which you'll now see in the pictures.
Answer: It meets code as is. It's not habitable space, so it doesn't require an outlet. It's not a fire wall, so it doesn't even need drywall. It doesn't support the house nor the staircase. (load bearing walls generally don't run the same direction as the joists... and no stringer ever counts on the wall next to it to do anything)
It can exist as is, or completely not be, with both an outlet and drywall being optional.
Cut the rest of the studs out, drywall the wall and the underside of the staircase. Now you can put crap there, and there isn't a mystery zone of, I wonder what's happening under there after that last flood we had....
Comment: The staircase in my modern house relies on the walls immediately adjacent.  The engineer even wanted to see the nails penetrating through the walls to ensure the proper length nails were used.


How to call a function associated with a dropdown by firing change event on it

Question: I want to call a function on a change of a dropdown and change event will be fired with jquery........................................................................................................................................................................................................................................
<!DOCTYPE html>

    <select id="sel" >
        <option>A</option>
        <option>B</option>
        <option>C</option>
    </select>

    <button type="button">Change</button>

Comment: any error on console?
Answer: If I understand you correctly, you're looking to set the value of a <select> and trigger its change event?  That would simply be this:
$('#sel').val('B').trigger('change');

Or, if you prefer to keep it on two lines as in your current attempt:
$('#sel').val('B');
$('#sel').trigger('change');

The former is generally preferred and consumes slightly less resources, but if you personally prefer two explicit statements as you learn then there's no real harm in the latter.
Answer: use the following way to fire  events of on other element
$("#sel").trigger("change");


replace a region with whitespace

Question: is there a keystroke to replace a region (series of characters, whatever) with a another character (for example whitespace)?
I am not searching for c, because it deletes the existing characters and lets me enter new ones, which may be less or more characters. I want to replace exactly the deleted characters with another char as with R.
For example I have this:
one two three four

and want to replace it with:
one two ----- four

If the cursor is on the beginning of three, I'd like to enter a keystroke, a region (for a example w for end-of-word) and a replacing char (in this case -) to let vim replace all characters in that region with the given replacing char.
Answer: you could try:
ver-

to replace selected part with -
same, if you want to replace / fill the "region" with space, you do:
verspace
Comment: Thanks, that was easy. :-) I knew of `v`, but didn't have the idea of using it with `r`.

replace a region with whitespace


How can I make vim use html and markdown syntax highlighting on the same file?

Question: I use remark to make html slides from markdown code in vim.
Remark requires to use an html template containing both html and markdown code in it.
How can I make vim use both html and markdown syntax highlighting on the same html file?
Answer: The default Markdown syntax plugin (by Tim Pope) that ships with Vim already includes HTML syntax. From <code>$VIMRUNTIME/syntax/markdown.vim</code>:
<code>" Vim syntax file
" Language:     Markdown
" Maintainer:   Tim Pope <email@example.com>
" Filenames:    *.markdown
" Last Change:  2013 May 30

[7 lines deleted]

runtime! syntax/html.vim
unlet! b:current_syntax
</code>
Comment: Tim Pope's markdown also supports [fenced code blocks](http://www.reddit.com/r/vim/comments/2x5yav/markdown_with_fenced_code_blocks_is_great/). Sadly this is not documented.


How To Secure Elasticsearch When using ajax

Question: I am new to webapps, so I apologize if this question seems naive, just looking to learn. I'm looking into using elasticsearch for autocomplete. All of the examples that I've seen show some form of jquery/ajax/angularjs that exposes the elasticsearch url to the user which seems like poor practice. What is the proper way of safeguarding the servers url, while still allowing ajax to make a call (even if indirectly) to it?
Comment: Nothing is secure with js, all is visible, you can only try to make it harder to decode. Best way is calling your own server with ajax, which calls the elasticSearch url and returns the result. That is if you just don´t want elasticsearch url to be show, only your server url will be
Answer: In the AJAX world, there is no way to secure the server URL. And that's ok; security by obscurity is not a good practice anyway. What you need to do is make sure your server can't be hacked through that URL.  A couple of tips:

Disable scripting in ES. The newer versions of ES have it disabled by default out of the box.
Don't expose your bare ES server to the world. By default ES is available on port 9200, which means anyone can run any query (or do anything else they want). Make sure that port is blocked from external access.  As one commenter pointed out, the Javascript should be calling your server, which should in turn be calling the ES server as localhost (again, be sure localhost:9200 is blocked from external access) or behind a firewall.
Clean up all input queries before passing them to ES.  ES is less vulnerable than SQL to "injection" attacks, but it is still critical to filter out any nasty characters such as \ { " : and so forth, to limit string lengths to something reasonable, etc.

Good luck!


Slow boot on Ubuntu 16.04 ... issue with pam_kwallet5.so

Question: I'm trying to find the cause of my slow boot time and so I checked the log file and found this from the time of restart:
Feb  4 00:54:17 blackbird3460 lightdm: PAM unable to dlopen(pam_kwallet.so): /lib/security/pam_kwallet.so: cannot open shared object file: No such file or directory
Feb  4 00:54:17 blackbird3460 lightdm: PAM adding faulty module: pam_kwallet.so
Feb  4 00:54:17 blackbird3460 lightdm: PAM unable to dlopen(pam_kwallet5.so): /lib/security/pam_kwallet5.so: cannot open shared object file: No such file or directory
Feb  4 00:54:17 blackbird3460 lightdm: PAM adding faulty module: pam_kwallet5.so
Feb  4 00:54:17 blackbird3460 lightdm: pam_unix(lightdm-greeter:session): session opened for user lightdm by (uid=0)

What is that?
Comment: Please format the question
Comment: I formatted the question, so can you give a thumbs up now?
Answer: According to this bug report
the issue with pam_kwallet5.so occurs because you don't have kwallet installed (it's optional, and not necessary). From my own experience, it is possible to have this annoying and misleading error message without having a slow boot problem.
I think you need to look elsewhere for the cause of your slow boot problem. Try systemd-analyze blame or any other boot processes analyzers in order to find the real cause of your slow boot problem.


What questions should I ask of a structural engineer about these cracks in my brick walls?

Question: My house was constructed in 1992 and we still have not completed the finishing work. Our roof is wood, there is no tie-beam or mullion at all in this house and there are some lintels above the windows & doors.
Cracks have appeared in the masonry walls starting from 2 years after construction in some areas, and in other areas some years later. Here is a picture of one of the cracks (click for full size):

I have been advised to consult a structural engineer. What can I expect from this consultation? Are there any specific questions I must ask the engineer?
I want to know if we can continue the construction as per proper standard or if I have to demolish the house and build it again.
Our land is loose soil and there is no concrete footing on this house. If this is a soil settlement issue, there are three options as per my understanding:

Continuous appearance of cracks in different areas
Cracks in a certain area with width increasing gradually
There is no new crack formation  or growth after some year

Here are some additional pictures (click for full size):
Comment: It is very important that you understand that any advice offered by any of the users on this site carries no guarantee of being correct.  To properly assess the structural integrity of your building an on-site inspection would be required.  You should really consider contacting a professional engineer/firm before deciding how to proceed.
Comment: Specific advice on this is beyond what we can and should reasonably provide here.  There were probably corners cut or mistakes made when the house was built, particularly in making sure the foundation had something stable to sit on.  You need to consult a structural engineer.
Comment: An important question is how long those cracks have been there. Did they develop shortly after the construction and then stop growing? Are they still growing? Did they only start appearing recently?
Comment: Welcome to engineering SE. Most likely the foundation is not stable. It might be still settling.
Comment: Our land is loose soil, there is no concrete footing on this house. The cracks start from after 2 years some area then cracks appear in different place after some year.
Firstly, soil settlement issue,
1. Continuous crack in different area
2. Cracks width increase gradually
3. There are no crack after some year and no more width increasing
I need the recommendation for these three option or if there any possibility via soil settlement.
Our roof is made by wood, there is no tie-beam or mullion at all this house and there are some lintel above the windows & doors.
Comment: Any slight earth tremor and this is likely to pancake. There's no structural integrity and the lack of foundation is breaking the structure apart.
Comment: Thanks for your advice. Mr. Wasabi, the cracks developed shortly after the construction and now stopped growing.
Comment: Out of curiosity where is this? I'm assuming it's outside the US as I can't imagine any jurisdiction approving this construction in 1992.
Answer: Get a reputable professional structural engineer in there ASAP -- it looks like the wall is severely cracked and would fail at that point when subject to shear loads.
I'm sure that the eyeballs of said engineer will tell a story when he sees a wall that's cracked that badly.
Also,
WHO THE HELL BUILDS WALLS ATOP LOOSE EARTH?
Comment: +1 to that. for 99,9% it's a foundation problem. also - a serious hazard of collapsing. I would gtfo this house, or at least try to find another place to live.
Answer: When the use of a proper foundation is avoided, the earth under the house WILL settle. It will settle unevenly, causing structural damage. The solution is to do extensive construction to build a support system for the weight of the house. Building without foundation is illegal by the International Builders Code.
SECTION R403 FOOTINGS
R403.1 General. All exterior walls shall be supported on continuous solid or fully grouted masonry or concrete footings, crushed stone footings, wood foundations, or other approved structural systems which shall be of sufficient design to accommodate all loads according to Section R301 and to transmit the resulting loads to the soil within the limitations as determined from the character of the soil. Footings shall be supported on undisturbed natural soils or engineered fill. Concrete footing shall be designed and constructed in accordance with the provisions of Section R403 or in accordance with ACI 332.


how to get surrogate variables in rpart

Question: I have looked everywhere I can, but I couldn't find answer to my question regarding rpart package.
I have built a regression tree using rpart, I have around 700 variables. I want to get the variables actually used to build the tree including the surrogates. I can find the actual variables used using tree$variable.importance, but I also have to get the surrogates because I need them to predict on the test set data I have. I do not want to keep all the 700 variables in the test set as I have a very big data (20mil observations) and I am running out of memory.
Answer: The list variable.importance in an rpart object does show the surrogate variables, but it only shows the top variables limited by a minimum importance value.
The matrix splits in an rpart object lists all of the split variables and their surrogate variables along with some other data like index, the value on which it splits (for continuous variable) or the categories that are split (for categorical variable), count how many observations are that split applies to. It doesn't give a hierarchy of which surrogates apply to which split, but it does list every variable. To get the hierarchy, you have to do summary(rpart_object).

how to get surrogate variables in rpart


What is the most recommended way to capture TCP Server's output to an Akka Stream queue?

Question: I am experimenting with Akka Streams, with a view of understand exactly how one is supposed to consume what a TCP Server receives from a client (the server doesn't need to respond to client).
Here's a standard TCP server implementation (after applying what I understand from @heiko-seeberger 's succinct explanation here):
def runServer(system: ActorSystem, address: String, port: Int, collectingSink: Sink[ByteString,NotUsed]): Unit = {
    implicit val sys = system
    import system.dispatcher
    implicit val materializer = ActorMaterializer()

    val handler = Sink.foreach[IncomingConnection] { conn =>
      conn.handleWith(
        Flow[ByteString]
          .via(JsonFraming.objectScanner(maximumObjectLength = 400))
          .alsoTo(collectingSink)
          .map(b => ByteString.empty)
          .filter(_ == false)
      )
    }

    val connections = Tcp().bind(address, port)
    val binding = connections.to(handler).run()

    binding.onComplete {
      case Success(b) =>
        println("Server started, listening on: " + b.localAddress)
      case Failure(e) =>
        println(s"Server could not bind to $address:$port: ${e.getMessage}")
        system.terminate()
    }
  }

The value that I pass as collectingSink parameter to the runServer() function is constructed this way:
import akka.stream.scaladsl.{Flow, JsonFraming, Sink}
import akka.util.ByteString
import play.api.libs.json.Json

object DeviceDataProcessor {

      case class Readings (
                     radiationLevel: Double,
                     ambientTemp: Double,
                     photoSensor: Double,
                     humidity: Double,
                     sensorUUID: String,
                     timestampAttached: Long)

      val xformToDeviceReadings = Flow[ByteString]
        .via(JsonFraming.objectScanner(maximumObjectLength = 400))
        .map(b => {

            val jsonified = Json.parse(b.utf8String)
            val readings  =  Readings(
                           (jsonified \ "radiation_level")         .as[Double],
                           (jsonified \ "ambient_temperature")     .as[Double],
                           (jsonified \ "photosensor")             .as[Double],
                           (jsonified \ "humidity")                .as[Double],
                           (jsonified \ "sensor_uuid")             .as[String],
                           (jsonified \ "timestamp")               .as[Long]
            )
            readings
        })
        .to(Sink.queue())

    }

Finally, this is how I run my Driver:
object ConsumerDriver extends App {
       val actorSystem = ActorSystem("ServerSide")
       TCPServer.runServer(actorSystem,"127.0.0.1", 9899,DeviceDataProcessor.xformToDeviceReadings)
}

I am failing to grasp the reasoning behind two things here:
1) The type of xformToDeviceReadings is derived as
Sink[ByteStream,NotUsed]

Shouldn't the mapped type Readings appear here?
2) How do I begin to read from this queue and pass the elements into another upstream flow? Should I have to materialize first and then use the materialized queue as my new Source?
I have gone through the documentation at Akka site. But, I will be happy to be redirected to any specific portion of this document, or other posts on SO.
Please help me plug the gap in my concept.
Answer: 1) the type is Sink[ByteString,NotUsed] as Akka Streams is left biased when composing materialized values. This means that the materialized value exposed by your combined sink (xformToDeviceReadings) is the one coming from its first stage (a map, which materializes to NotUsed).
To expose the materialized value you want you need to change to
...
.toMat(Sink.queue())(Keep.right)

Note that the type of your Sink now changes to Sink[ByteString, SinkQueueWithCancel[Readings]]
2) to interact with your queue of Readings you need to run your stream, hence obtaining your materialized value (the queue) and start pulling items from it. This could happen in the connection handling:
val handler: Sink[IncomingConnection, Future[Done]] = Flow[IncomingConnection]
  .map { conn =>
    conn.handleWith(
      Flow[ByteString]
        .via(JsonFraming.objectScanner(maximumObjectLength = 400))
        .alsoToMat(collectingSink)(Keep.right)
        .map(_ => ByteString.empty)
        .filter(_ == false)
    )
  }
  .mapAsync(1){ queue ⇒
    queue.pull()
  }
  .toMat(Sink.foreach(println))(Keep.right)

Note that the solution above is not ideal, especially because the materialized queue is most likely not thread safe. If your purpose is to plumb these Readings to some other downstream flow, you better directly connect a Sink fit for the purpose, instead of going through a queue.
Comment: many thanks for the explanation. The *left-biased* is a key piece of information I was unaware of.
Comment: many thanks for the explanation. The *left-biased* is a key piece of information I was unaware of. However, I am a bit confused about the point of thread-unsafe nature of the queue. Your point on the requirement of downstream plumbing, is correct. I intend to pass a 'Sink' as a parameter to runServer(), which should work as a piece of hand-off mechanism: queue, to me, is a natural choice. Now, going by your words of caution, I am exploring other possibilities. But, when people use queues, what do they do?
Comment: I don't know what you ultimately want to do with these `Readings` so a queue might as well be a good choice in your case. Just keep in mind, if you're choosing this Sink, to always use the queue from the same thread.


Hide address bar not working - bulletproof approach needed

Question: At the moment I am writing some kind of web app and I want to hide the address bar on iOS devices and preferably also on Android devices.
Normally I do this with
window.addEventListener( 'load', function () {
  setTimeout( function () {
    window.scrollTo( 0, 1 );
  }, 0 );
});

but this won't work now because the page hasn't enough content to scroll.
Now I know this is a common problem and I know that there are multiple solutions, but I would prefer a small, bulletproof solution.
Actually I was quite happy when I found this question: http://stackoverflow.com/questions/9678194/cross-platform-method-for-removing-the-address-bar-in-a-mobile-web-app
where this code was posted:
function hideAddressBar()
{
  if(!window.location.hash)
  {
      if(document.height < window.outerHeight)
      {
          document.body.style.height = (window.outerHeight + 50) + 'px';
      }

      setTimeout( function(){ window.scrollTo(0, 1); }, 50 );
  }
}

window.addEventListener("load", function(){ if(!window.pageYOffset){ hideAddressBar(); } } );
window.addEventListener("orientationchange", hideAddressBar );

Unfortunately, this doesn't work for me. I see that something happens because some elements that have padding-top set in percentages move down, but the address bar stays.
Of course I also did a Google search and tried many snippets I found. Some did nothing, some just moved the elements with padding-top down a bit.
The only working code I found is this:
var page = document.getElementById('page'),
    ua = navigator.userAgent,
    iphone = ~ua.indexOf('iPhone') || ~ua.indexOf('iPod'),
    ipad = ~ua.indexOf('iPad'),
    ios = iphone || ipad,
    // Detect if this is running as a fullscreen app from the homescreen
    fullscreen = window.navigator.standalone,
    android = ~ua.indexOf('Android'),
    lastWidth = 0;

if (android) {
  // Android's browser adds the scroll position to the innerHeight, just to
  // make this really difficult. Thus, once we are scrolled, the
  // page height value needs to be corrected in case the page is loaded
  // when already scrolled down. The pageYOffset is of no use, since it always
  // returns 0 while the address bar is displayed.
  window.onscroll = function() {
    page.style.height = window.innerHeight + 'px'
  }
}
var setupScroll = window.onload = function() {
  // Start out by adding the height of the location bar to the width, so that
  // we can scroll past it
  if (ios) {
    // iOS reliably returns the innerWindow size for documentElement.clientHeight
    // but window.innerHeight is sometimes the wrong value after rotating
    // the orientation
    var height = document.documentElement.clientHeight;
    // Only add extra padding to the height on iphone / ipod, since the ipad
    // browser doesn't scroll off the location bar.
    if (iphone && !fullscreen) height += 60;
    page.style.height = height + 'px';
  } else if (android) {
    // The stock Android browser has a location bar height of 56 pixels, but
    // this very likely could be broken in other Android browsers.
    page.style.height = (window.innerHeight + 56) + 'px'
  }
  // Scroll after a timeout, since iOS will scroll to the top of the page
  // after it fires the onload event
  setTimeout(scrollTo, 0, 0, 1);
};
(window.onresize = function() {
  var pageWidth = page.offsetWidth;
  // Android doesn't support orientation change, so check for when the width
  // changes to figure out when the orientation changes
  if (lastWidth == pageWidth) return;
  lastWidth = pageWidth;
  setupScroll();
})();

Source
But I am not really happy with this solution as I am not a friend of UA sniffing.
Do you have any suggestions what I could try to make it work without UA sniffing? Can it be my HTML that causes problems with some scripts I posted?
Answer: Don't know if it's bulletproof, but it works on a bunch of devices. If you find caveat, let me know.
if (((/iphone/gi).test(navigator.userAgent) || (/ipod/gi).test(navigator.userAgent)) &&
    (!("standalone" in window.navigator) && !window.navigator.standalone)) {
    offset = 60;
    $('body').css('min-height', (window.innerHeight + offset) + 'px');
    setTimeout( function(){ window.scrollTo(0, 1); }, 1 );
}

if ((/android/gi).test(navigator.userAgent)) {
    offset = 56;
    $('html').css('min-height', (window.innerHeight + offset) + 'px');
    setTimeout( function(){ window.scrollTo(0, 1); }, 0 );
}

Comment: Hey, thanks for your answer - Better late than never, huh ;-) Unfortunately, I haven't found a *really* satisfying solution for this. The biggest caveat at the moment is iOS 7 I think, there its not possible anymore to hide the address bar if I am not mistaken, which would render any solution posted here useless.


(C++) How to check whether or not an input string is an integer?

Question: I want this code to check whether the input is an int or not, and it works fine until I enter a float type number. I need a program that won't let through float numbers.
bool error;
int x;
string s;
do
{
    cout <<"number: ";
    cin >> x;
    error=cin.fail();
    if(error)
    {
        cout << "error" <<endl;
        cin.clear();
    }
    getline(cin,s);
}while(error);
cout << x;

Comment: Read as a string, attempt to [convert to an integer](http://en.cppreference.com/w/cpp/string/basic_string/stol)?
Comment: It be work fine until entered line begins with sequence of digits.
Comment: But I need it to return error whenever a float number is typed in
Comment: @Bako Read in complete whitespace separated chunks and use `std::stoi()` for conversion. Invalid inputs will throw an exception.
Answer: std::istream& operator(std::istream&, int) will read a valid integer number up to any non matching character like '.', and no error state is set for the stream up to this point.
You better should read complete (whitespace separeated) chunks as std::string, and inspect them if these contain the desired format (e.g. using std::regex).
std::stoi() should also fail with an exception, if you're trying to convert the chunk.
Answer: I think, you are looking for something like this (C++11):
auto s = std::string{};

std::cin >> s;

if( std::all_of(std::begin(s), std::end(s),
                [](char c) -> bool {
                    return c <= '0' && c <= '9';
                }) ) {
    std::cout << "you have entered an integer" << std::endl;
}

Somehow I thought, that the standard library contains a predicate that checks if a given char is a digit, but I could not find it now. Such a hypothetic is_digit() would allow make the code more readable:
if( std::all_of(std::begin(s), std::end(s), std::hypothetic::is_digit) ) {
    std::cout << "you have entered an integer" << std::endl;
}

Answer: Read in all of the user's input line as a string, then convert the string to an integer with std::stoi.
Unfortunately std::stoi will happily stop converting when it hits the end of convertible characters, but it allows you to pass in a pointer to a position to be updated with the character that ended the conversion. If this position is not the end of the string, there was garbage on the line.
bool error = true; // assume user input is wrong
while (error)
{
    if (std::getline(std::cin, s)) // grab the whole line
    {
        std::size_t end;
        try
        {
            x = std::stoi(s, &end);
            if (end == s.length()) // converted all user input
            {
                error == false; // good data
            }
        }
        catch(std::invalid_argument &) // user input is complete garbage
        {
        }
        catch(std::std::out_of_range &) // converted user input is too big for int.
        {
        }
    }
}
                                  ^

I recommend turning the input loop into a function. 1) It's easily reusable should you need to convert an int again. 2) It gets rid of some of the logic above because you can return when the input is tested and good.
int gimmieInt(std::istream& in) // Me eat input stream! Om nom nom nom!
{
    std::string s;
    int x;

    while (true) // consider instead using a maximum number of retries.
                 // This increases complexity, so consider it *after* you have
                 // the basic version working
    {
        if (std::getline(in, s))
        {
            std::size_t end;
            try
            {
                x = std::stoi(s, &end);
                if (end == s.length())
                {
                    return x;
                }
            }
            catch(std::invalid_argument &) // user input is complete garbage
            {
            }
            catch(std::std::out_of_range &) // user input is too big for int.
            {
            }
        }
    }
}


mount issue in ubuntu 12.10

Question:
Possible Duplicate:
"The location is not a folder" error when opening files

I'm having issue with latest Ubuntu 12.10. Let me make it more clear.
I'm having the following partitions in my Laptop.
  Device Boot      Start         End      Blocks   Id  System
/dev/sda1            2048    39997439    19997696   83  Linux
/dev/sda2   *    40001850    81947564    20972857+  83  Linux
/dev/sda3        81947565   123877214    20964825   83  Linux
/dev/sda4       123887614   976773119   426442753    5  Extended
/dev/sda5       123887616   333602815   104857600   83  Linux
/dev/sda6       333604864   543320063   104857600   83  Linux
/dev/sda7       543322112   753037311   104857600   83  Linux
/dev/sda8       753039360   976773119   111866880   83  Linux

I have also two users named "ms" and abc. Here ms is for administrative tasks and abc for my friends. When I mount any drive under "abc" user, I cannot access it under my other user "ms".  Same as in the case with "ms" user. I found possible reason behind the issue. When I mount any drive under "abc" user, Ubuntu will try to mount it under "/media/abc/volume_name" instead of "/media/volume_name" . Same as in the case with "ms" user.
# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        19G   11G  7.5G  59% /
udev            1.5G  4.0K  1.5G   1% /dev
tmpfs           599M  896K  598M   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            1.5G  620K  1.5G   1% /run/shm
none            100M   92K  100M   1% /run/user
/dev/sda2        20G  172M   19G   1% /media/abc/TEST
/dev/sdb1       466G  353G  114G  76% /media/abc/F088F74288F7063E
/dev/sdb2       466G  318G  148G  69% /media/abc/New Volume
/dev/sda5        99G   94G  323M 100% /media/abc/Songs
/dev/sda6        99G   31G   63G  34% /media/ms/Films

Here, you can see that "TEST" was mounted under "/media/abc/TEST". When I try to access the already mounted partition named  '/media/abc/TEST" in my "ms" session I'm getting the following error.

How to fix this error? Is it a bug? Is there any way to fix this without modifying the underlying file-system structure?
Comment: Seems like it is the intended behavior, not a bug http://askubuntu.com/questions/203841/ubuntu-12-10-the-location-is-not-a-folder
Comment: I had to edit your question. It was poorly formatted. For the next time please read http://askubuntu.com/editing-help . Thanks!
Comment: i found a possible workaround. Try to chmod 777 /media/user/  will  fix the issue.
Answer: I found a possible workaround. Try to chmod 775 /media/user/ will fix the issue. Ie:
Normally, in  Ubuntu 12.10 it will try to mount volumes in the following format.
drwx------ root root /media/user
This is the reason why you are not able to browse the volumes under different user. So, please try to change the permission to "chmod 775 /media/user".
Answer: the only workaround i found for now is using gksudo nautilus, this way i can access my partitions
Comment: Please note that if you're going to run Nautilus as `root`, it is preferable to use `gksu nautilus` or `gksudo nautilus` and **not** `sudo nautilus`, for the reasons [explained here](https://help.ubuntu.com/community/RootSudo).

mount issue in ubuntu 12.10


Debugging C++ library with Android Studio

Question: I'm working on an Android project which uses a Java class that is a wrapper on a C++ library. The C++ library is a company internal library and we have access to its source code, but in the Android project it is only dynamically linked, so it is used only in the form of headers (.h) and shared objects (.so). Having access to the library source code, is it possible to specify to Android Studio the path to the source code so I can step inside the library using the debugger?
The debugger works, I can step inside the Java_clory_engine_sdk_CloryNative_nativeInit function, but I would also like to further debug the library corresponding to the Clory::Engine class which, as I mentioned, is an internal library we have source code access to.

For example, Clory::Engine::instance is part of the library and I would like to specify to Android Studio the location of the CloryEngine.cpp file so I can step inside Clory::Engine::instance with the debugger, thus debugging this static member function.
I am using Android Studio 3.1.4.
Is this possible?
EDIT:
The clory-sdk.gradle file specifies the CMakeLists.txt file which configures the C++ layer.
externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
}

So I am using an internal application which uses the Clory SDK. Inside the app.gradle file I use:
dependencies {
...
    compile project(':clory-sdk-core')
    compile project(':clory-sdk')
...
}

so I don't think we're using the aars for the app.gradle project. The aars are shipped to the client, but we are using app.gradle project to test our little SDK functionalities before doing that. The JNI layer is inside clory-sdk-core project.
EDIT 2:
Here is the CMakeLists.txt which handles the JNI layer:
cmake_minimum_required(VERSION 3.4.1)

set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_BUILD_TYPE Debug)

add_library(
    clory-lib
    SHARED
    # JNI layer and other helper classes for transferring data from Java to Qt/C++
    src/main/cpp/clory-lib.cpp
    src/main/cpp/JObjectHandler.cpp
    src/main/cpp/JObjectResolver.cpp
    src/main/cpp/JObjectCreator.cpp
    src/main/cpp/DataConverter.cpp
    src/main/cpp/JObjectHelper.cpp
    src/main/cpp/JEnvironmentManager.cpp
)

find_library(
    log-lib
    log
)

target_compile_options(clory-lib
    PUBLIC
        -std=c++11
)

# Hardcoded for now...will fix later...
set(_QT_ROOT_PATH /Users/jacob/Qt/5.8)

if(${ANDROID_ABI} MATCHES ^armeabi-v7.*$)
    set(_QT_ARCH android_armv7)
elseif(${ANDROID_ABI} MATCHES ^x86$)
    set(_QT_ARCH android_x86)
else()
    message(FATAL_ERROR "Unsupported Android architecture!!!")
endif()

set(CMAKE_FIND_ROOT_PATH ${_QT_ROOT_PATH}/${_QT_ARCH})

find_package(Qt5 REQUIRED COMPONENTS
    Core
    CONFIG
)

target_include_directories(clory-lib
    PUBLIC
        ${CMAKE_CURRENT_LIST_DIR}/src/main/cpp
)

set(_CLORYSDK_LIB_PATH ${CMAKE_CURRENT_LIST_DIR}/src/main/jniLibs/${ANDROID_ABI})

target_link_libraries(clory-lib
    ${log-lib}
    -L${_CLORYSDK_LIB_PATH}
    clorysdk
    Qt5::Core
)

The library clorysdk is actually our internal library I was talking about, which contains e.g. Clory::Engine::instance I would like to step into with the debugger. It was built with qmake and is built in debug mode (CONFIG+=debug was added in the effective qmake call).
EDIT 3:
In the LLDB session which has opened after it hit the Java_clory_engine_sdk_CloryNative_nativeInit breakpoint, I got the following:
(lldb) image lookup -vrn Clory::Engine::instance
2 matches found in /Users/jacob/.lldb/module_cache/remote-android/.cache/6EDE4F0A-0000-0000-0000-000000000000/libclorysdk.so:
        Address: libclorysdk.so[0x0001bb32] (libclorysdk.so..text + 8250)
        Summary: libclorysdk.so`Clory::Engine::instance(Clory::Engine::Purpose)
         Module: file = "/Users/jacob/.lldb/module_cache/remote-android/.cache/6EDE4F0A-0000-0000-0000-000000000000/libclorysdk.so", arch = "arm"
         Symbol: id = {0x0000005e}, range = [0xcb41eb32-0xcb41ebc0), name="Clory::Engine::instance(Clory::Engine::Purpose)", mangled="_ZN4Clory2Engine8instanceENS0_7PurposeE"
        Address: libclorysdk.so[0x0001b82c] (libclorysdk.so..text + 7476)
        Summary: libclorysdk.so`Clory::Engine::instance(Clory::RuntimeConfiguration const&, Clory::Engine::Purpose)
         Module: file = "/Users/jacob/.lldb/module_cache/remote-android/.cache/6EDE4F0A-0000-0000-0000-000000000000/libclorysdk.so", arch = "arm"
         Symbol: id = {0x000000bd}, range = [0xcb41e82c-0xcb41e970), name="Clory::Engine::instance(Clory::RuntimeConfiguration const&, Clory::Engine::Purpose)", mangled="_ZN4Clory2Engine8instanceERKNS_20RuntimeConfigurationENS0_7PurposeE"

(lldb) settings show target.source-map
target.source-map (path-map) =

First of all, there was no CompileUnit section in the result of the command image lookup -vrn Clory::Engine::instance. How is this possible to have no source-map defined(second lldb command) if the libclorysdk.so was built in Debug mode? Is it possible to explicitly set it so that the debugger would search there for the library's source files?
EDIT 4:
After searching more I found out that the process of creating the APK actually strips the *.so libraries from their debugging symbols. libclorysdk.so built in debug mode has about 10MB while the libclorysdk.so file which I extracted after unarchiving the generated *.apk file is just 350KB.
As stated here, running greadelf --debug-dump=decodedline libclorysdk.so on the debug version outputs references to the source files, but if the command is run on the *.apk extracted library, it outputs nothing.
Is there a way to stop Android Studio from stripping the *.sos? I tried How to avoid stripping for native code symbols for android app but didn't have any effect, *.apk file is the same size as before and debugging the native libraries still doesn't work.
I'm using Gradle 3.1.4.
EDIT 5:
The stripping solution works, but in my case, it needed a Clean & Build before hitting the breakpoints in the library. Deploying *.sos which are not stripped is allowing you to have debugging sessions and step inside the native libraries.
Note:
If the libraries are built using the Qt for Android toolchain, the *.sos deployed to $SHADOW_BUILD/android-build are also stripped(where $SHADOW_BUILD is the build directory usually starting with build-*). So in order to debug those you should copy them from outside the android-build directory where each *.so is generated.
Comment: I did a little test myself, and stepping into code within a prebuilt shared library from another project worked fine for me. However, I've only tested this with both projects being built on the same machine. Perhaps the project structure looks different on your machine compared to the machine that build the shared library? You can try running `readelf --string-dump=.debug_str mylib.so` to see where the source files are expected to exist.
Comment: Are you using a debug build of the prebuilt shared library? If so, stepping into code within that library should work.
Comment: @Michael I am using a debug build of the prebuilt shared library. But the source code is not within the project which uses the shared library. So it can't know where to search for the source code (I assume) unless I tell it where to search. And I don't know how to do that. I remember if you want to step inside a library in Visual Studio you get a dialog box that lets you browse for the source file corresponding to the function you're stepping into, like so: https://i.imgur.com/doPgOs4.png
I would expect some sort of functionality that gives you something similar...
Comment: @Michael Thank you very much for the answer. Hmmm...I will build tonight a small project with which I will try to reproduce my scenario on a smaller scale and let you know what I found.
Comment: Do you have `ndk` or `cmake` configuration for your project? Or is the lib you're using packaged as an `aar`?
Comment: @ahasbini Thank you for your answer, I have edited my question to provide the information you're asking for. Please ask if it is not clear, I will provide further information.
Comment: Could you post the `CMakeLists.txt`? As for further clarity and correct me if I'm wrong, your project contains `app` module is a regular app with `plugin: 'com.android.application'` defined in the `app.gradle`. The `clory-sdk-core` and `clory-sdk` are also project modules which have the their `gradle` files containing `plugin: 'com.android.library'` with the only difference is `clory-sdk` containing `CMakeLists.txt` file and C/C++ code.
Comment: @ahasbini Thank you very much for your questions. What you described is exactly the case, with just one exception: `clory-sdk-core` contains `CMakeLists.txt`, and _NOT_ `clory-sdk`. So `clory-sdk-core.gradle` contains `externalNativeBuild {cmake {path "CMakeLists.txt"}}` while `clory-sdk` has `clory-sdk-core` as a dependency: `dependencies {compile project(':glas.ai-sdk-core')`.
I have posted an edit and I added the `CMakeLists.txt` for more clarity.
Comment: I have a test application that uses/tests an apk. This apk library is dependent on a .so file. I want to be able to add breakpoints and debug into the .so file. I built all of the projects in debug mode with the "donot strip" packaging option but still I am not able to step into the library. Can you help?
Answer: The debug info records the location of the source files when they were built.
(lldb) image lookup -vrn Clory::Engine::instance

The CompileUnit line shows the source file. Suppose it says:
"/BuildDirectory/Sources/Clory/CloryEngine.cpp"

Let's assume you have the source on your machine here:
"Users/me/Sources/Clory"

So you can tell lldb: find the source file rooted at /BuildDirectory/Sources/Clory in Users/me/Sources/Clory instead.
(lldb) settings set target.source-map /BuildDirectory/Sources/Clory Users/me/Sources/Clory

You can use these commands in the lldb console of Android Studio or put into a .lldbinit file for general use.
Comment: It seems that the libclorysdk.so has no debug information. Try to rebuild the sdk with debug info or use the debug version of the sdk if it's available. Use these lldb commands in Android Studio. Set a breakpoint in the `Java_clory_engine_sdk_CloryNative_nativeInit` function. Start the debuging. When you stop at the breakpoint use the lldb window of Android Studio to run the lldb commands above.
Comment: Thank you very much for your answer! I ran `$ lldb libclorysdk.so` and after that I ran `(lldb) image lookup -vrn Clory::Engine::instance` I get only 4 sections: `Address`, `Summary`, `Module` and `Symbol`. It looks something like this: https://pastebin.com/2wBrD1nJ
Any idea why I don't get the `CompileUnit` information? My libraries are all built in debug mode.
Answer: If there no debug symbols available, you might have to build the referenced library in debug mode.
Either with -DCMAKE_BUILD_TYPE=DEBUG:
defaultConfig {
    externalNativeBuild {
        cmake {
            arguments "-DANDROID_TOOLCHAIN=gcc", "-DCMAKE_BUILD_TYPE=DEBUG"
            cppFlags "-std=c++14 -fexceptions -frtti"
        }
    }
}

externalNativeBuild {
    cmake {
        path file('src/main/cpp/CMakeLists.txt')
    }
}

Or add this to the CMakeLists.txt of the library:
set(CMAKE_BUILD_TYPE Debug)

See the CMake documentation and Symbolicating with LLDB.
Elsewhere it explains (lldb) settings set target.source-map /buildbot/path /my/path:

Remap source file path-names for the debug session. If your source files are no longer located in the same location as when the program was built --- maybe the program was built on a different computer --- you need to tell the debugger how to find the sources at their local file path instead of the build system's file path.

There's also (lldb) settings show target.source-map, to see what is mapped.
(lldb) set append target.source-map /buildbot/path /my/path seems rather suitable, in order not to overwrite existing mappings.
Comment: @zwcloud you need to add the `arguments` into `defaultConfig > externalNativeBuild > cmake > arguments`... and the path to `CMakeLists.txt` outside of the `defaultConfig`. I've updated my answer to make this more clear.
Comment: Thank you so very much for your answer! I added `set(CMAKE_BUILD_TYPE Debug)` to my `CMakeLists.txt` in my android project which handles the JNI layer. I also made sure that all my libraries are built in Debug mode as the library is built with `CONFIG+=debug`(i'm using `Qt 5.8` with `GCC 4.9` - I don't think it matters tough as, I read, debugging `gcc` compiled code should be possible with `lldb`).
Now I'm new to bridging C++ and Java in Android and I may make stupid mistakes and ask stupid questions. Here's what I'm doing: in the Android Studio terminal I run `$ lldb libclorysdk.so`.
Comment: The problem is that when I run and then `(lldb) settings show target.source-map` I get the following message: `target.source-map (path-map) =`. This means that no path is associated with that variable(I suppose). Now I tried `settings set target.source-map "" /Users/jacob/Work/clory/sdk/native/sdk/base`(_base_ folder is the location of the project which generates my `libclorysdk.so` library i.e. location of the qmake _.pro_ project file) and when I run `(lldb) settings show target.source-map` I get `target.source-map (path-map) = [0] "" -> "/Users/jacob/Work/clory/sdk/native/sdk/base"`.
Comment: In this point I still couldn't enter inside `Clory::Engine::instance` with the debugger. I also tried to set the key(value before "->") to be the path to my `libclorysdk.so`(located inside the android project) and the value(value after "->") to be the path to my _clory_ library sdk source code; so when I ran `(lldb) settings show target.source-map` I get `target.source-map (path-map) = [0] "/Users/jacob/Work/clory/sdk/android/clory-sdk-core/src/main/jniLibs/armeabi-v7a" -> "/Users/jacob/Work/clory/sdk/native/sdk/"`.
Comment: At this point when I ran the debugger I still couldn't enter inside `Clory::Engine::instance`. Another i think important thing is that when I exit `lldb` with `(lldb) exit` and I run `$ libclorysdk.so` againe, all the mappings ar gone; so the operations are not persistent. What could I be doing wrong?
Comment: When you run `$ lldb libclorysdk.so` you create a separate new lldb session. The command what you type here will be valid for that session. After `(lldb) exit` the session will be closed.
Use lldb console of Android Studio instead of the command line tool as I mentioned at my answer.
Comment: @Peter Thank you again! Please see _Edit 3_ section, where I explained the outcome of what you suggested. Could there be a further solution I could try?
Comment: I got `ERROR: Could not find method arguments() for arguments` after modifying build.gradle.


Java GUI application

Question: I am working on a Java graphical interface (Swing , AWT) . The data entry in my application is supposed to be done via a JFrame. In fact I have 10 entities that necessitate 10 JFrames. I used a for loop but JFrames don't seem to wait until data entry.
I used Thread.sleep() but in vain. Any help?
Here is some of my code:
for (int i=0; i < VMnumber; i++) // VMnumber : number of virtual machines to instantiate
{
    mips=0;
    frame=new VMcaracteristics(); // VMcaracteristics is a JFrame to enter VMs caracteristics
    frame.setVisible(true);
    while (!VMcaracteristicsFlag) // Current frame is still open
    {
        Thread.sleep(100);
    } // create a VM correspondent to the current frame
    vm = new Vm(vmid, brokerId, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
    vmlist.add(vm);
}

Comment: Can we get a bit of the code? Perhaps the initialization and the part involving the loops?
Comment: Are you looking for a "submit" button, or something that detects any change to a configuration as it happens? I don't think that this is answerable right now without more code/details as to what exactly you want to happen, and what is currently happening.
Comment: What did you try? Any code example?
Comment: I would use just one JFrame and either have the entry fields for all the data present on the one GUI view (one JPanel), or use CardLayout to swap JPanel views after each section of data entry has been complete. This is a lot less jarring than throwing bunches of windows at the user.
Answer: You are looking for JOptionPane.
String data = JOptionPane.showInputDialog(
    null, //parent window
    "Hi! Enter some data, please:", //text
    "Input", //title
    JOptionPane.PLAIN_MESSAGE //icon?
);

Explore the documentation to find the best method for your needs.
Edit: JOptionPane actually blocks, so you can loop:
String[] data = new String[10];
for(int i = 0; i < 10; i++) {
    data[i] = JOptionPane.showXXX(...);
}

Answer: Your underlying question (in my mind) is not so much how to display 10 windows, one after the other, but rather, how to get multiple bits of information from the user in an easy and straightforward way, both for you the coder and the user. If you are dead set about throwing a bunch of windows at the user, then yes, use J4v4's solution of multiple JOptionPanes (1+ to his answer), or modal JDialogs (which JOptionPane is in fact one variant of). If you want a better user experience, though consider showing the user all input fields, perhaps in a multi-row JTable or in several JPanels held in a GridLayout container held in a JScrollPane. If you absolutely need to display 10 views sequentially, consider using one CardLayout using JPanel that then displays 10 view "card" JPanels sequentially.
Also, you never want to call Thread.sleep(...) or while (true) on the Swing event thread as this will block this important thread, one that is needed for all Swing drawing and user interaction, and will effectively put your whole application to sleep.

Java GUI application


How to locate an element with respect to a variable within a xpath using Selenium and Python

Question: size = '19'

driver.find_element_by_xpath('//a[@title="Sélectionner Taille:" + size]').click()

this is my code, but it doesn't work as the ' stuck the variable into a simple quotation
so I don't know how to do, please help me
I use selenium with python into chrome driver
Answer:
try this it will help you.

driver.find_element_by_xpath("//a[@title="Sélectionner Taille:"'" + size + "']").click()

You can also refer to this answer as well: link
Answer: Without the HTML it is not clear about the number of white spaces between Sélectionner Taille: and 19. So discounting all the white spaces to invoke click() on the element with respect to the variable using Selenium and python you need to to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using variable in XPATH:
size = '19'
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(@title, 'Sélectionner Taille') and contains(@title, '" +size+ "')]"))).click()

Using %s in XPATH:
size = '19'
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(@title, 'Sélectionner Taille') and contains(@title, '%s')]"% str(size)))).click()

Using format() in XPATH:
size = '19'
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(@title, 'Sélectionner Taille') and contains(@title, '{}')]".format(str(size))))).click()

Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Reference
You can find a couple of relevant discussions in:

How to find an element with respect to the user input using Selenium and Python?