text:
Q: Azure Pipelines, iterate through files In azure build pipeline, I'm trying to iterate through all the files that have extension .hex. The aim is to use every file the same way, but not knowing how many are there.
I receive an error from Azure :

Encountered error(s) while parsing pipeline YAML:
/azure-pipelines.yml (Line: 11, Col: 3): Unexpected symbol: '*'. Located at position 26 within expression: $(Build.SourcesDirectory)*.hex.

The Pipeline has been reduced to the minimum possible :
trigger: none

pool:
  name: "LabelManagementPool"
steps:
- ${{ each filename in $(Build.SourcesDirectory)\*.hex}}:
  - script: echo ${{ filename }}

What am I missing here ? Is what I want to achieve possible ?

A: Unfortunately it is not possible to do it this way as when the pipeline kicks of it will compile into a structure with all stages, jobs, etc defined. Since this path doesn't exist yet it can't be compiled.
The workaround would be to use another programming language, such as python or powershell, to obtain the list of files that match the decription. And then use it to loop over each file and perform whatever action you want it to run.
As an example, you could use the following in PowerShell to find all hex files and then would need to write additional code for looping over it and performing your desired task.
# Obtain list of all files that are hex
$files = Get-ChildItem "C:\repos\python" -Filter *.hex -Recurse | % { $_.FullName }

# Loop over every file
Foreach ($file in $files)
    {echo $file}

The yaml would be this
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      # Obtain list of all files that are hex
      $files = Get-ChildItem "$(Build.SourcesDirectory)" -Filter *.hex -Recurse | % { $_.FullName }

      # Loop over every file
      Foreach ($file in $files)
        {echo $file}


text:
Q: Abort execution of remaining task if certain condition is failed I want to abort execution of remaining task if certain condition is failed.
and display proper error message.
So instead of skipping remaining task I want to show error message and stop execution of ansible playbook.
Lets say I am running below command
$ ansible-playbook playbook.yml -e "param1=value1 param2=value"

My playbook look like this:-
playbook.yml:-
---
    - hosts: local
      user: roop
      gather_facts: no

      vars: {param1: "", param2: ""}

      tasks:

        #check whether param1 defined
        - name: 'Check for valid param1'
          shell: echo {{ param1 }}
          register: isValidParam1
          when: param1 !=""

        #check if param1 is null or invalid
        - name: 'check if param1 is null or invalid'
          debug: msg="Please enter correct param1"
          when: param1 == ""

        #check whether param2 defined
        - name: 'Check for valid param2'
          shell: echo {{ param2 }}
          register: isValidParam2
          when: param2 != ""

        #check if param2 is null or invalid
        - name: 'check if param2 is null or invalid'
          debug: msg="Please enter correct param2"
          when: param2 == ""

        #check params is valid and defined
        - name: 'Check for valid params'
          shell: echo "param1={{ param1 }} param2={{ param2 }}
          register: validParams
          when: isValidParam1 is defined and isValidParam2 is defined

        #check if params are invalid then abort below all tasks.
        - name: 'check if validParams is null or invalid'
          debug: msg="Please enter correct Params"
          when: validParams is not defined

         # based on validParams, and different value of param1 more than
          10 task executing.

As I have mentioned in my last task comment. I am executing more than 10 task based on validParams and param1 different value. What I need here
if validParams is undefined then abort all execution and show error messages.
Is there any efficient way to do this . Please suggest me.

A: You can use

*

*assert
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/assert_module.html

*or fail
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/fail_module.html
It will go along with something like this
        #check if params are invalid then abort below all tasks.
        - name: 'check parm is null or invalid'
          fail: msg="Please enter correct Params"
          when: "param1 is not defined or param2 is not defined " ## whatever condition you want

A: So in Ansible 2.2+ there is the meta module: http://docs.ansible.com/ansible/latest/meta_module.html
So

meta: end_play

stops the playbook with a non failing status

A: Ansible >= 2.0 has a block feature that allows you to logically group tasks. This allows you to apply a when to a group of tasks.
The main difference between this and the fail or assert modules is that the task isn't marked as failed; it's just skipped. Whether this is better depends on your use case. For example I have some tasks that write to a log that's later parsed for failures; it's easier to do this if only "real" failure conditions are logged.
Example code:
- block:

    # task 1

    # task 2

    # task 3

  when: "param1 is defined or param2 is defined"

# otherwise output a message
- block:

    debug: msg="Missing params"

  when: "param1 is not defined or param2 is not defined"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I reference an instance method when I declare a block in objective-c I have an instance method that I'd like to invoke directly using the callback param from a block in objective-c. I prefer this approach when I need to do more than a simple 1 liner in the callback.
Here is the basic setup...
I init a class w/ some type of call back so I can parse json after the http request lets say
- (void)initFooAndDoStuff {
    Foo *foo = [[Foo alloc] initWithCallback:^(NSData * response){
        // do stuff
    }];
}

//this is the instance method I'd like to invoke instead of an inline function
- (void)callBackWithHttpResponse:(NSData *)response {
    // do stuff ... assuming it's more complex than a 1 liner that is
}

I can setup a call back that does something inline (but again more complex stuff would be better in a stand alone instance method perhaps)
Foo *foo = [[Foo alloc] initWithCallback:^(NSData * response){
    NSLog(@"foo");
}];

I can use the instance method like below but it feels a little long winded. Any way I can cut this down (the syntax that is).
Foo *foo = [[Foo alloc] initWithCallback:^(NSData * response){
    [self callBackWithHttpResponse:response];
}];

A: If you're going to put the implementation in a method, you might as well just have the method return the entire block:
-(void (^)(NSData *))httpResponseHandler {
    return ^(NSData *responseData){
        // do something with responseData
    };
}

Then the places you use it would be a bit more succinct:
Foo *foo = [[Foo alloc] initWithCallback:[self httpResponseHandler]];

A: Foo *foo = [[Foo alloc] initWithCallback:^(NSData * response){
    [self callBackWithHttpResponse:response];
}];

OK -- pretty darned readable as it is.
Now, go in the other room and hit yourself in the head 3 times with a brick to simulate not having looked at this project in 6 months to a year.
Now, read the code again.
Still readable, isn't it?
There is nothing wrong with a bit of verbosity when that verbosity says exactly what the code is doing.  You could go with a target/action pattern as Ken Thomases suggested, but that would require additional complexity elsewhere.
Instead of callback, I would change it to be even more specific.  I.e. if the callback was really a completion handler:
Foo *foo = [[Foo alloc] initWithHTTPResponseCompletionHandler:^(NSData * response){
    [self httpResponseCompletionHandler:response];
}];


text:
Q: Redirect all but one sub domain to https? This post is very close to what I am looking for. But what I am looking for is
letsencrypt.example.com   should always be http
          *.example.com   should always be https

Using the solution from this post I can rewrite all http to https by
server {
  listen 80;
  server_name test.example.com;
  rewrite     ^   https://$http_host$request_uri? permanent;
}

and then onwards do
server {
  listen 443 ssl;
  ...

Question
But how can I make sure that letsencrypt.example.com remains at http port 80?

A: You should use an explicit server for letsencrypt.example.com and then use a catch-all server for the redirection.
Your port 80 server blocks would look Like this:
server {
    listen 80;
    server_name letsencrypt.example.com;
    ...
}
server {
    listen 80 default_server;
    return 301 https://$http_host$request_uri;
}

See this documentation for details.


text:
Q: User is not eligible for this purchase Android inApp I am going through a problem while doing inapp android purchases. I have tried everything I can but it seems to be stuck on the error user is not eligible to this purchase. Please guide me through what i'm doing wrong. Below are the steps I followed

*

*signed apk uploaded to play store

*inapp product in published state

*user is on test device

*version code and version name are same as uploaded apk to store

Thanks!

A: This error comes when everything you done is perfect, you have used signed APK with the proper product id, but you have to note that the account that you are using might don't have proper valid credit card details.
So whenever you want to buy any product even with test account, that account should have valid credit details.
You have to specify test account in Edit profile of your publisher account
Licensing & In-app Billing
Test Accounts box

A: I thought I share mine too.
I have had the same issue with my test device. I have done all the stuff noted in many documents until by accident I tested it on different device with SIM card and everything was fine.
My test device doesnt have a SIM card and just Wireless Internet. So Google can't verify it. I can buy any app I want from the Google Play though.
My other test device is with different test account + it has a Proper SIM card with data plan.
Hope this help someone.

A: Took me 2 days to find out that you not only have to create the app under console v2, but upload it under v2, too.
My problem was that, under v2, I could not upload anything (no pictures, no APK)... so I switched back to v1, and did all the uploads there.
(Just to note: v2 console doesn't tell you all the details on what is needed to have a 'draft' or publish the app. So I switched back and forth...)
So, after having all that "User not eligible" trouble, I finally decided to do the whole process again, and found out that with Google Chrome the upload doesn't work. :D
Finally, with Firefox the upload did work, and I never saw that error again ;)

A: I have got the same issue for 2 days. Finally, I have discovered that there was a problem with  my credit card currency. I used Amex for my test account, and it didn't allow billing in Euros, only in dollars. The problem was solved when I used an european credit card.
The best is to try to purchase some existing stuff with your google play test account to be sure that the issue does not come from your account configuration.

A: Just to clear what was my problem was that my test IAP purchase worked fine in my game but i couldn't purchase actual IAP game products.
Finally i found this worked having trying for 2 months. There were many things i tried and could be the possible reason seeing all this. But the important one that seems to me a lot problematic, i tried to purchase IAP products through american based credit card while sitting in pakistan. As many times i tried to purchase, i first get a purchase successful email and then sudden after that i receive a cancellation of the purchase email from google. So i went to try this purchase by my friend in USA and it worked.
Last thing, i want to mention is this could not be the only reason behind seeing these alerts as i couldn't remember all stuff that i gone through to make this work.
Thanks every one for all the efforts!

A: There are only two reasons for this error:
1> Signed in account in Play Store App doesn't not have testing permission . Add this account to test accounts on Google play
2> Publisher can't buy their own products . In-Apps or even paid apps


text:
Q: Why is applicationDidFinishLaunching NOT being called in my macOS document based app with a storyboard? I'm working on a Swift document based app for macOS and I discovered that the appDelegate method applicationDidFinishLaunching is never called. The app delegate is being set correctly and I can see in the debugger that the NSApplication object has the delegate set. Why isn't this method being called when the application launches?
Note: my storyboard has an entry point set to a 'welcome window' controller (in case that has anything to do with this problem).

A: Resolved: my method signature was wrong.  It was:
applicationDidFinishLaunching(aNotification: NSNotification)

When it should have been:
applicationDidFinishLaunching(_ aNotification: Notification)

This probably happened wile converting to the current Swift syntax.


text:
Q: Implementing undo functionality in JavaScript How do I implement a ctrl z in javascript?
After numerous google searches, I stumbled upon the execCommand:
I'm using document.execCommand("undo", false, null), but it doesn't work
with Firefox.
I put in the 2nd and 3rd parameters even though they are optional in Firefox.
Any ideas, insights, suggestions, examples, etc?

A: Since this hasn't been officially answered I wrote this if this helps at all
Its extends jquery so that it detects ctrl + z. and can be used like this:
$('input').disableUndo();

or if you want it to do something when the user tries to undo
$('input').disableUndo(function(element){
    // do custom stuff
});

jsFiddle Demo


text:
Q: Random Order of an IEnumerable I have got an IEnumerable collection as follows
var result1 = GetResult1() // Returns 2,4,5,6

I have to juggle the elements and create another collection in a random way which should result as follows:
var result2 = GetResult2(result1) // Returns 2,4,5,6 in a random order.
// An example output would be 4,6,2,5 in the resultant collection.

I have done this by the following means:
var result1 = GetResult1();
var random = new Random();
var result2 = result1.OrderBy(order=>random.Next());

However the issue with this is that if I access result2 the elements in result2 gets shuffled again, i.e if I output the results of result2 to a console twice, the elements are juggled again.
Can you please advice how to keep this uniform. i.e once I juggle the collection, it should remain the same way thereafter. I have to use lazy evaluation though, since the results are very huge in size.

A: You are looking for a shuffle algorithm.
See following SO threads to provide nice extensions method to do the job:
Is using Random and OrderBy a good shuffle algorithm?
An extension method on IEnumerable needed for shuffling

To answer your question "why is that shuffled again?", it's because of how OrderBy works (lazy execution). You could try:
var result2 = result1.OrderBy(order=>random.Next()).ToList();

A: I see you require lazy evaluation for the results, if that is the case, what you can do is this:
var randomNumbers = result1.Select(r => random.Next()).ToArray();
var orderedResult = result1.Zip(randomNumbers, (r, o) => new { Result = r, Order = o })
    .OrderBy(o => o.Order)
    .Select(o => o.Result);

By calling ToArray() on the random numbers, these will not change. When you finally desire the items in result1, you can zip the items with the random numbers, OrderBy the random number and Select the result.
As long as the items in result1 come in the same order, the result in orderedResult should be the same each time.

A: You can use ToList() like this:
var result2 = result1.OrderBy(order=>random.Next()).ToList();


text:
Q: Call recording using iOS core telephony framework I am making an emergency app. In which user can tap on call button, in case of emergency. I have used core telephony for getting call events as described by apple and AVFoundation framework for recording call audio. Here is my code:
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupCallRecorder()
    }

func callConnected() {
        print("callConnected")
        self.audioRecorder?.record()
    }
    func callDisconnected() {
        print("callDisconnected")
        self.audioRecorder?.stop()
    }
    func setupCallRecorder() {

        let audioSession:AVAudioSession = AVAudioSession.sharedInstance()

        //ask for permission
        if (audioSession.respondsToSelector("requestRecordPermission:")) {
            AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
                if granted {
                    print("granted")

                    //set category and activate recorder session
                    try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
                    try! audioSession.setActive(true)

                    //get documnets directory
                    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
                    let soundFilePath = NSString(format: "%@/sound.caf", documentsDirectory)
                    let soundFileURL = NSURL.fileURLWithPath(soundFilePath as String)

                    //create AnyObject of settings
                    let settings: [String : AnyObject] = [
                        AVFormatIDKey:Int(kAudioFormatAppleIMA4), //Int required in Swift2
                        AVSampleRateKey:44100.0,
                        AVNumberOfChannelsKey:2,
                        AVEncoderBitRateKey:12800,
                        AVLinearPCMBitDepthKey:16,
                        AVEncoderAudioQualityKey:AVAudioQuality.Max.rawValue
                    ]

                    //record
                    try! self.audioRecorder = AVAudioRecorder(URL: soundFileURL, settings: settings)

                } else{
                    print("not granted")
                }
            })
        }

        let callCenter = CTCallCenter();
        callCenter.callEventHandler = { (call:CTCall!) in

            switch call.callState {
            case CTCallStateConnected:
                print("CTCallStateConnected")
                self.callConnected()
            case CTCallStateDisconnected:
                print("CTCallStateDisconnected")
                self.callDisconnected()
            default:
                //Not concerned with CTCallStateDialing or CTCallStateIncoming
                break
            }
        }
    }

But when call (iOS default call feature) is initiated from the app, my app goes to background and call event handler blocks are not called. I have read somewhere that call/audio recording will only work when your app is in foreground, so I have also tried by bringing my app to foreground once call is started, but even then its not working. Now I have following questions/concerns:

*

*Is it something that apple does not allow us to do?

*Apps can only record VOIP/SIP calls and not default calls?

*Is this possible to record calls in iOS without using any server tricks?

Note: This app is not for jail break devices and I want my app to upload on app store.

A: *

*It is something that many countries do not allow. Apple don't allow it at all and doesn't even have any private APIs to do that

*Apps can record their own stuff all they want given that they notify the user about it. Cellular network is completely different thing

*No. Even with jailbreak you have to inject your code into lower level parts of iOS audio stack and work with raw audio streams that go through the system.

Thus, there is no way you can get something like that into the AppStore.


text:
Q: node js cant post unauthorised i have been facing this error of 401 unauthorized error when i tried to mount my isLoggedinMiddlware.js, and even when i can manage to print the token stored, it stil says its
authorised. Any advice or help would be appreciated! Have a nice day.
this is my isLoggedinMiddleware.js
const jwt = require("jsonwebtoken");
const JWT_SECRET = process.env.JWT_SECRET;

module.exports = (req, res, next) => {
  const authHeader = req.headers.authorization;
  if (authHeader === null || authHeader === undefined || !authHeader.startsWith("Bearer ")) {
    res.status(401).send();
    return;
  }
  const token = authHeader.replace("Bearer ", "");
  jwt.verify(token, JWT_SECRET, { algorithms: ["HS256"] }, (error, decodedToken) => {
    if (error) {
      res.status(401).send();
      return;
    }
    req.decodedToken = decodedToken;
    next();
  });
};

this is my post api
app.post("/listings/",isLoggedInMiddleware,(req,res)=>{
  listings.insert(req.body,(error,result)=>{
    if(error){
      console.log(error)
      console.log(req.body)
      console.log(isLoggedInMiddleware)
      res.status(500).send('Internal Server Error')
      return;
    }
    console.log(result)
    res.status(201).send({"Listing Id":result.insertId})
  })
})

This is my front end
   const baseUrl = "http://localhost:3000";
const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
const token = localStorage.getItem("token")
console.log(token)

if(token === null || isNaN(loggedInUserID)){
    window.location.href = "/login/"
}else{

    $('#logoff').click(function(){
    event.preventDefault();
    localStorage.removeItem('token')
    localStorage.removeItem('loggedInUserID')
    window.alert('Logging out now')
    window.location.href = "/login/"
    })
         $(document).ready(function () {
        $('#submitbtn').click((event) => {
            const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
            // middleware =  {headers:{'Authorization':'Bearer '+token},data:{id: loggedInUserID}}

            event.preventDefault();
            const itemName = $("#itemName").val();
            const itemDescription = $("#itemDescription").val();
            const price = $('#price').val();
            const image = $('#image').val();
            const requestBody = {
                itemName: itemName,
                itemDescription: itemDescription,
                price: price,
                fk_poster_id: loggedInUserID,
                imageUrl: image
            }
            console.log(requestBody);
            axios.post(`${baseUrl}/listings/`,{headers:{'Authorization':'Bearer '+token},data:{id: loggedInUserID}}, requestBody)
                .then((response) => {
                    window.alert("successfully Created")
                })
                .catch((error) => {
                    window.alert("Error")
                    console.log(requestBody)

                })
        })
    })

}

i can managed to get the token i stored when i log in, however, it stills say 401 unauthorised.


text:
Q: Add product to cart programatically is not updating totals I want to add product to cart from a external file
Here is my code
require_once 'app/Mage.php';
Mage::app();

$session = Mage::getSingleton('customer/session');

Mage::getSingleton('checkout/cart')->getQuote();

$productId = 123;
$productQuantity = 1;
$productModel = Mage::getSingleton('catalog/product');
$productObj = $productModel->load($productId);

if (!$quoteObj) {
    $quoteObj = new Mage_Sales_Model_Quote();
}

$store_id = 1;
$storeObj = $quoteObj->getStore()->load($store_id);
$quoteObj->setStore($storeObj);

$quoteItem = Mage::getModel('sales/quote_item')->setProduct($productObj);
$quoteItem->setQuote($quoteObj);
$quoteItem->setQty($productQuantity);
$quoteItem->setStoreId($store_id);

$quoteObj->addItem($quoteItem);
$quoteObj->setStoreId($store_id);
$quoteObj->collectTotals();
$quoteObj->setCustomerId(null);
$quoteObj->save();
$quoteId = $quoteObj->entity_id;

$quote1 = Mage::getModel('sales/quote')->setStoreId($store_id)->load($quoteId);
print_r($quote1->getData());

Printed info.
    [grand_total] => 0
    [base_grand_total] => 0
    [subtotal] => 0
    [base_subtotal] => 0
    [subtotal_with_discount] => 0
    [base_subtotal_with_discount] => 0

Here what i found the it is not updating the totals.
why what is wrong with my code ?

A: You are saving the quote but I am not sure it is enough. You should try saving the cart. And try to collectTotals before printing getData :
$cart = Mage::getSingleton('checkout/cart');
$quote = $cart->getQuote();

Your code ....

$cart->save();

$quote = Mage::getModel('sales/quote')->setStoreId($store_id)->load($quoteId);
$quote->setTotalsCollectedFlag(false)->collectTotals();
print_r($quote->getData());


text:
Q: Apache strips down "Authorization" header I'm having a little issue with my Apache 2.2.15 Server.
I'm running a Django app on top of it with mod_wsgi. I activated WSGIPassAuthorization On, which made the Basic auth working well. But I recently implemented OAuth2.0 to secure my API (Implicit Grant), and I think Apache won't let it pass since it is of the form "Authorization: Bearer token". The "Bearer" is the issue I guess, though I don't know how to avoid that.
I tried :
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

In the httpd.conf, .htaccess (after setting AllowOverride All), and in my vhost. Nothing to do, doesn't work.
I've crawled the Internet all day long, and didn't find anything but those two solutions.
Thank you in advance !
EDIT:
OS : RedHatEL6.4
Apache : 2.2.15
Django: 1.6.6 w/ django-oauth-toolkit
Python: 2.7.8

A: I solved my problem, which finally was totally unrelated to my Apache configuration. So if you found this topic looking for an answer to the same problem, one of the solutions below should fix it :
Config WSGI :
WSGIPAssAuthorization On

Config .htaccess :
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

You can put both of those into your httpd/conf.d/project.conf file !

A: Several modules will strip the Authorization header to try to enhance security by preventing scripts from seeing usernames, passwords, etc... unless the developer explicitly enables this.  Many of these modules will allow this header if you simply add the following line to .htaccess: CGIPassAuth on (source: Apache docs and StackOverflow)

A: To solve this problem, I just add WSGIPassAuthorization On to /etc/apache2/sites-available/mySite.conf file, as follows:
        ...
                </Files>
        </Directory>

        WSGIPassAuthorization On

        WSGIScriptAlias / /home/X/wsgi.py
        WSGIDaemonProcess sepanta_dev python-path=/home/X python-home=/home/X/venv
        ...


text:
Q: get last entry for each date in timeseries dataframe I have a dataframe that contains a column called date_and_time, and an associated value column. I would like to take the last entry for each date in the dataframe. Of course, groupby isn't very useful because there is no df.groupby('date_and_time').last() function.
Here is an example dataframe:
    date_and_time   value
07/01/2019 09:52    41998
07/01/2019 09:57    21183
07/01/2019 10:02    29730
07/01/2019 10:07    27855
07/01/2019 10:12    29359
08/01/2019 10:17    42057
08/01/2019 10:22    27307
08/01/2019 10:27    37205
08/01/2019 10:32    10969
08/01/2019 10:37    14085
09/01/2019 10:42    23218
09/01/2019 10:47    18972
09/01/2019 10:52    11286
09/01/2019 10:57    36341
09/01/2019 11:02    16913
10/01/2019 11:07    12131
10/01/2019 11:12    46921
10/01/2019 11:17    22412
10/01/2019 11:22    28503
10/01/2019 11:27    33918

and here is what I would like to have at the end:
date_and_time   value
07/01/2019 10:12    29359
08/01/2019 10:37    14085
09/01/2019 11:02    16913
10/01/2019 11:27    33918

A: Convert first column to datetimes by to_datetime:
df['date_and_time'] = pd.to_datetime(df['date_and_time'], format='%d/%m/%Y %H:%M')

If necessary sorting:
df = df.sort_values('date_and_time')

And then aggregate by date:
df = df.groupby(df['date_and_time'].dt.date).last().reset_index(drop=True)

Or use boolean indexing with duplicated and inverting mask by ~:
df = df[~df['date_and_time'].dt.date.duplicated(keep='last')]

Last if need same format use strftime:
df['date_and_time'] = df['date_and_time'].dt.strftime('%d/%m/%Y %H:%M')

Solutions with no converting to datetimes - split by whitespace and select first values - here dates:
df = df.groupby(df['date_and_time'].str.split().str[0]).last().reset_index(drop=True)

df = df[~df['date_and_time'].str.split().str[0].duplicated(keep='last')]


text:
Q: Metadata for Read-only from layout! I was wondering how do i get if a particular field is set to read-only on the layout using Metadata APIs? The reason is, i am designing a lightning component and i wanted to still adhere to those read-only rules specified in the layout.
Any ideas?


text:
Q: passing function pointer in c with a pointer argument Here, I have defined two function pointers func1 and func2, and I guess this a way to use function pointers in c.But my question is when I call
executor(func1);
executor(func2);

How can I allocate memory for uint8_t * and pass it as an argument for either func1 and func2, so that I can use it back in main()
typedef int (*FUNC_PTR)(uint64_t, uint8_t*);

void executor(FUNC_PTR func)
{
   uint64_t opts = 0x0000010;
   uint8_t val = 0;
   res = func(opts, &val);
}

int func1(uint64_t a, uint8_t* b)
{
   //do some stuff

}

int func2(uint64_t a, uint8_t* b)
{
//do some stuff
}

void main()
{
   executor(func1);
   executor(func2);
}

A: Just add it to the argument list of executor.
void executor(FUNC_PTR func, uint8_t* b)
{
   uint64_t opts = 0x0000010;
   res = func(opts, b);
}

You can allocate the memory on the stack or heap in main.
void main()
{
   uint8_t mem1, mem2;
   executor(func1, &mem1);
   executor(func2, &mem2);
}


text:
Q: Array Search key and Replace value php I have an array like
[{"detail":"33,putih","sku":"123","price":"500000","stok":"8"},{"detail":"33,hitam","sku":"123","price":"500000","stok":"5"},{"detail":"43,hitam","sku":"123","price":"1000000","stok":"1"}]

i have to json_decode it.
i want to change stok = 2 from detail "33,hitam".
but i'm seriously confused to use array search first and use array replace.

A: You could do it like this :
$stringarray = '[{"detail":"33,putih","sku":"123","price":"500000","stok":"8"},{"detail":"33,hitam","sku":"123","price":"500000","stok":"5"},{"detail":"43,hitam","sku":"123","price":"1000000","stok":"1"}]';
$array = json_decode($stringarray);
var_dump($array);
$replaced = replaceInObject($array, "detail", "33,hitam", "stok" , "2");
var_dump($replaced);

function replaceInObject($array, $field, $searchvalue, $valuefield, $newvalue){
    foreach($array as $element){
        if($element->$field == $searchvalue){
            $element->$valuefield = $newvalue;
        }
    }
    return $array;
}

A: You can use array_map to achieve this
$data = '[{"detail":"33,putih","sku":"123","price":"500000","stok":"8"},{"detail":"33,hitam","sku":"123","price":"500000","stok":"5"},{"detail":"43,hitam","sku":"123","price":"1000000","stok":"1"}]';
$json = json_decode($data, true);

$result = array_map(function($e) {
                        if ($e['detail'] == "33,hitam") $e['stok'] = "2";
                        return $e;
                    }, $json);


text:
Q: Exclude a function's return value from [[nodiscard]] I want to mark a class as nodiscard, but exclude the return value of a certain function from the nodiscard requirement. This is my goal:
enum class [[nodiscard]] Result {
  OK1,
  OK2,
  ERROR,
};

[[ok-to-discard]] // This attribute is made up to illustrate my need.
Result doSomethingThatCannotFail() {
  // The function can return OK1 or OK2, but the caller may or may not care.
  // The function cannot return ERROR.
  // Therefore, it's OK to discard this particular Result return value,
  // even though in general Result should not be ignored.
}

I do not believe it's a good idea to add ok-to-discard at every call site (which is covered by
How can I intentionally discard a [[nodiscard]] return value?):

*

*There are many callsites. It would be nice to avoid adding ok-to-discard everywhere.

*Maybe one day I'll change the function, and it will no longer be OK to discard. It would be preferable to keep the ok-to-discard instruction with the function so that I can drop it when that happens (and get compiler warnings/errors).


text:
Q: System function in C language - creating user from CodeBlocks (C) program I have a problem, i wanted to do a program which will be used to make an account on PC. I write from keyboard name and password which is used to create new user. Everything was okey to the time when i wanted to write command in code, I used "system("net user xxx /add")" where xxx == name of the new user, yes it is working like that, but i want to change xxx to the variable which is written from the keyboard. I mean that, the name of the new user which is creating, the user of program will choose. Any help?
int main()
{

char login;

printf("Login of the new user:");

scanf("%s",&login);

system("net user xxx /add");

return 0;
}

A: You can use the function sprintf to build a string. It works similar to printf but produces its output in a character array rather than as output to stdout.
For example:
char buffer[100], login[100];
printf("Login of the new user: ");
scanf("%s", login); // notice there is no & operator here
sprintf(buffer, "net user %s /add", login);
system(buffer);

Safer code would use snprintf, which also takes the length of the destination character array as a parameter to ensure that it does not overflow.  Also, I'd use fgets rather than scanf as it is inherently safer for the same reason that snprintf is safer than sprintf.
As a side note, for what you're trying to do (add a new user on a Windows system), there are Windows APIs specifically designed for that purpose that you should use rather than calling the net command from system, because these methods will indicate success and failure of attempting to add the user. I concede that there is a very steep learning curve to the Windows API, but if it lets you avoid using the system function, it really is the way to go.

A: Firstly, you do notscanf towards a variable which is only 1 byte (login). This will just result in buffer overflow and application crash. Since I have the feeling that this is a homework kind of assignment I recommend using an array of chars with help from Since we have snprintf, why we don't have a snscanf?. Otherwise, this answer: C - scanf() vs gets() vs fgets() will give some good directions on how to read (more) safely from the stdin.
Secondly you will need another buffer for creating the net add ... command. For this I recommend using snprintf (https://msdn.microsoft.com/en-us/library/2ts7cx93.aspx) in order to achieve the desired result in a safe manner.
Intentionally I do not post code here to solve this problem, in order to not to hinder your learning, feel free to ask more questions.


text:
Q: How to get trending tweets about a location I need to get trending tweets about a location. I am currently getting trending tweets from a given location using woeid but this is not what I need. I need to get trending tweets about a city like Paris. Can anyone please help me?

A: Here is the WOEID (Where On Earth ID) for Paris: 615702.
Also, the WOEID for France is 23424819. Read the official twitter documentation on "GET trends/place." It explains what you need to know.


text:
Q: Ag Grid getModel I have a React project with rowModelType = 'serverSide'.
I also have a custom component for filtering.
And I have an external button that should clear this filter
When I click on the button the function is triggered - gridApi.setFilterModel(null);
Next, the setModel function is called in the component
Where
assigned to this.setState({checkedFilters: []})
Next, the gridApi.getFilterModel() method is called;
Next, the getModel() method is called where this.state.checkedFilters is equal to the old value i.e. [1,2]
Maybe somebody will prompt in what a problem of obtaining of old value?
**Component state =
this.state = {
checkedFilters: [1,2]
};**


text:
Q: Модальное окно в модальном окне Задача состоит в том, что нужно открывать модальное окно в модальном окне.
Теперь о проблеме:
Использую fancybox 2. Первое модальное окно открывается нормально, но при клике на ссылку в этом модальном окне нужно открывать еще одну модалку, а предыдущую скрывать.
Я делал все по аналогии как и на первой модалке, т.е. давал ссылке во внутреннем модальном окне href="#block-id", но при клике вместо открытия окна, выдает окно с ошибкой.
Подскажите пожалуйста в чем моя тупость и как решить проблему.

A:

*{
margin:0;
padding:0;
}
html,body{
height:100%;
}
.main{
width:100%;
height:100%;
position:relative;
background:white;
}
.mdl{
position:absolute;
top:50%; left:50%;
width:800px;
height:400px;
background:#fefefe;
margin:-200px -400px;
display:none;
z-index:11;
}
.btn1,.btn2{
display:block;
width:200px;
padding:8px 0;
background:lightgreen;
margin:0 40px;
text-align:center;
cursor:pointer;
}
.js{
position:fixed;
top:0; left:0;
width:100%;
height:100%;
background:rgba(0,0,0,.3);
z-index:10;
display:none;
}
.mdl1{
width:300px;
height:150px;
background:pink;
position:absolute;
left:50%; margin-left:-150px;
top:50%; margin-top:-75px;
display:none;
}

Открыть первое окно

   Открыть второе окно

X

Вот так собственно это делается , код прозрачен и всё достаточно ясно


text:
Q: Points in Excel Charts (VBA) Is there a way in VBA to identify a point in a chart with something else than its number reference?
When placing the pointer above a section of the chart, it displays the serie number and also some narrative. Is this the "Name" of the point?
Ex: Serie 1 Point "Europe" Value: 12 (51%)
I am trying to move away from:
Worksheets(1).ChartObjects(1).Chart. _
    SeriesCollection(1).Points(3).MarkerStyle = xlDiamond
and writing:
Worksheets(1).ChartObjects(1).Chart. _
    SeriesCollection(1).Points("Europe").MarkerStyle = xlDiamond

A: The name does not refer to the point, that has a given name such as S1P1.
What you could do is to store the names and indexes of the XValues in a collection, then use that
Dim myValues As Collection
Dim xv As Variant
Dim i As Long

    Set myValues = New Collection

    With Worksheets(1).ChartObjects(1).Chart.SeriesCollection(1)

        For Each xv In .XValues

            i = i + 1
            myValues.Add i, xv
        Next xv

        .Points(myValues.Item("Europe")).MarkerStyle = xlDiamond
    End With

A: There may be a better way to do this, but AFAIK and remember from my experience, this is the only way to test for Category Axis Labels when looping through charts and act upon the series based on the Category Axis Label.
I have commented the code heavily in order to make it as clear as possible:
Sub LoopAxisLabels()

Dim ws As Worksheet
Dim c As ChartObject
Dim sc As SeriesCollection

Set ws = Worksheets(1)
Set c = ws.ChartObjects(1)
Set sc = c.Chart.SeriesCollection

Dim aForm() As String
aForm() = Split(sc.Item(1).Formula, ",")
'^^^
'|||get formula (chart data source) for the series collection (Item(1) denotes first series collection on chart
'   assumes only 1 collection on chart)
'   places formula into array separate by comma, based on =SERIES(Sheet1!$F$3,Sheet1!$E$4:$E$8,Sheet1!$F$4:$F$8,1) as example

Dim rLabel As Range, cel As Range
Set rLabel = Range(aForm(1)) 'set the label range (Sheet1!$E$4:$E$8 in the example)

Dim i As Long

For Each cel In rLabel 'loop through actual cells of label and test for label values

    i = i + 1 'use counter to refer to specific chart points (since points will be in order of data listed in range

    Select Case cel.Value2

        Case Is = "Europe": sc.Item(1).Points(i).MarkerStyle = xlDiamond 'Points(i) matches the relative range reference

        Case Is = "...":

        'continue with other Cases...

    End Select

Next

End Sub


text:
Q: Qual a forma mais adequada de armazenar uma referência em um objeto? Suponhamos que eu queira criar uma biblioteca, onde um objeto deve receber outro objeto adicionado pelo usuário e armazenar para uso posterior.
Ex:
//header.h
class Caixa{
private:
   Botao botoes[5];
public:
   void addBotao(Botao botao){
      int i;
      while(botoes[i]!=NULL)
         i++;
      botoes[i] = botao;
   }
   Botao getBotao(int i){
      return botoes[i];
   }
}

class Botao{
private:
   char nome[10];
public:
   void Botao(char texto[10]){
      nome = texto;
   }
}

//main.cpp
void main(){
   Caixa caixa1 = Caixa();
   Botao botao1 = Botao("clique");
   caixa1.addBotao(botao1);
}

Por questões de economia de memória seria interessante passar esse objeto por referência. Mas, considerando que referências devem ser referenciadas na inicialização, me parece que não seria possível armazenar a referência no objeto, certo ?
Usando ponteiros para fazer a passagem, eu não teria segurança de que a variável ainda estaria ali quando eu fosse usar. Podem me dizer qual a forma mais adequada de resolver esse problema ?

A: Você quer aprender do jeito certo ou do jeito gambiarra? Vou pelo certo.
Então modernizei seu código usando C++11/14. Não misture C com C++. E se vai usar C++, use o recursos mais modernos a não ser que tenha uma restrição no projeto que está trabalhando (o que não parece ser o caso).
Algumas coisas podem ser um pouco diferentes dependendo da intenção. Provavelmente eu evitaria o shared_ptr e tentaria usar o unique_ptr ou reference_wrapper. E provavelmente eu usaria o emplace_back() no lugar do push_back, assim não precisaria criar o objeto separadamente, mas depende do que quer.
É possível armazenar a referência, mas provavelmente seria um erro. Com ponteiros brutos é um problema, mas com ponteiros gerenciados dá para ter "segurança".
#include <string>
#include <vector>
#include <memory>
using namespace std;

class Botao {
private:
   string nome;
public:
   Botao(string texto) {
      nome = texto;
   }
};

class Caixa {
private:
   vector<shared_ptr<Botao>> botoes;
public:
   void addBotao(shared_ptr<Botao> botao) {
      botoes.push_back(botao);
   }
   shared_ptr<Botao> getBotao(int i) {
      return botoes[i];
   }
};

int main() {
   auto caixa1 = Caixa();
   auto botao1 = make_shared<Botao>("clique");
   caixa1.addBotao(botao1);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


text:
Q: Treat URL path as virtual host using Apache The problem is that I have only one domain name on which three different products need to be run (two of them PHP based and one python). So I need to treat the path in the URL as a different virtual host; i.e.:
www.domain.com/first_URL/
www.domain.com/second_URL/
www.domain.com/third_URL/

Where the first to third will act as separate virtual hosts.
How can I do this?

A: A "virtual host" in Apache works on domain names only, not on parts of the path. You cannot achieve what you want.

A: This example explains how to assign a different PHP version per directory. It can also be adapted to add Python support by running the Python interpreter as fast_cgi on a particular port.
For the purpose of the example, I assume there is a separate directory for each PHP version and they are named according to the PHP version that runs them, but this can be adjusted.
mkdir /home/user/www
mkdir /home/user/www/5.6.5
mkdir /home/user/www/7.0.2
mkdir /home/user/www/7.0.4
mkdir /home/user/www/7.0.6

Create symbolic links to directories that should be handled by different PHP versions:
sudo ln -s /home/user/www/7.0.2/ /var/www/html/7.0.2
sudo ln -s /home/user/www/7.0.4/ /var/www/html/7.0.4
sudo ln -s /home/user/www/7.0.6/ /var/www/html/7.0.6

Then add the following lines to /etc/apache2/sites-enabled/000-default.conf in default virtual host *:80
(For your needs, you can set up one more FastCGI handler here for the website that requires Python). I assume PHP 5.6.5 runs on port 9999, 7.0.2 runs on port 9998, etc.
DirectoryIndex index.html index.php
ProxyPassMatch ^/5.6.5/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9999/var/www/html/
ProxyPassMatch ^/7.0.2/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9998/var/www/html/
ProxyPassMatch ^/7.0.4/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9997/var/www/html/
ProxyPassMatch ^/7.0.6/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9996/var/www/html/

Assuming your server is pointed by example.com, you can test it on:
http://example.com/5.6.5/
http://example.com/7.0.2/
http://example.com/7.0.4/
http://example.com/7.0.6/

A: This can be achieved by using the Alias or AliasMatch directive:
Alias /first_url/ /var/www/first_url_resources

More details can be found in Apache Module mod_alias.

A: You probably want to do something with the apache-config directives, since you're asking for a virtualhost solution. Apache can only work with virtualHosts as actual domains, as cweiske explained.
The solution in this case would be to either use a .htaccess file in the sub-directories you're working in, or to set up a <Directory "/web/root/subdir">..</Directory> block within your current (virtual-)host configuration.
You could also choose to host them on different sub-domains if you per se want to run them as VirtualHosts ('app1.domain.org').


text:
Q: How to find current folder size in linux When I type df -h it shows a folder of size 200GB, but when I try to find the size of any of the sub-directories by du -sch /path the folder size is 10kB. I know that certain sub-folder should be of size 100GB.
How do I find the size of the current folder/directory in Linux?

A: Use: du -sh * , this will give you the size of all the directories, files etc in the pwd in a readable format (you can get rid of the * if you wish obviously to get the size of just the pwd).
Read man du , also this has some very nice examples.

A: When you run du -sch /abc it doesn't show the size of hidden files (the files/directories that have the prefix dot(.) in their names) in the abc .
To check the size of all the files you can run, assuming you are in the directory abc
for i in `ls -a`; do du -sh $i ; done | sort -h

This will also sort the list.


text:
Q: grant select in just one DMV instead of grant VIEW SERVER STATE Is there some way to grant select in just one sys.table.. for example select in sys.dm_hadr_availability_group_states without to grant VIEW SERVER STATE?

A: I think you can wrap the select against the specific DMV in a stored procedure and then use Execute As to elevate the permissions.
whether you choose to sign the SP with a certificate, execute as SA or as Owner is something you will need to determine according to your own security needs.


text:
Q: command + Y to delete the entire line is not working in Intellij Idea 2017 version Previously COMMAND + Y shortcut key is used to delete the entire line in IntellIj Idea 2016.
Currently the same shortcut is not working in latest version 2017.
What is the new key for this.

A: The delete line action is definitely supported in Intellij 2017.2.1
You can check the key binding from Preferences > Keymap.
Here's a screenshot showing the binding for the Mac OS X 10.5+ keymap on Intellij v2017.2.1

Yours may differ, depending on what keymap you have chosen but you can use this approach to identify the key mapping for your setup.

A: Instead of using Command + Y just type Command + delete key it will delete the line in IntellIj.


text:
Q: Parametric Linear Program: Continuous Solution? Consider the parametric linear problem
$$ x^*(\theta) := \min_{Y , \ Z }  \left\| Z \right\|_1 $$
$$ \text{sub. to: } \ \theta A + B Y = \theta C Z.$$
where $Y \in \mathbb{R}^{m \times s} $, $Z \in \mathbb{Z} := \{M \in (\mathbb{R}_{\geq 0})^{s \times s} \mid \left\| M \right\|_1 \leq 1  \}$; $\ A \in \mathbb{R}^{n \times s}$, $B \in \mathbb{R}^{n \times m}$, $C \in \mathbb{R}^{n \times s}$ are given non-null matrices; $\underline{1}^\top = (1,1,...,1) \in \mathbb{R}^s$.
Let $\theta \in [\epsilon,1]$ for some $\epsilon>0$.
Is the function $\theta \mapsto x^*(\theta)$ continuous?
Edit: Say what happens if $Y \in \mathbb{Y}$, being $\mathbb{Y} \subset \mathbb{R}^{m \times s}$ a compact set.
Note: this question is simpler than this one.

A: Since $\theta > 0$, we may divide the first constraint by $\theta$
to obtain $A + \theta^{-1} B Y = C Z$.  Since $Y$ is unrestricted except for that constraint,
we can replace $\theta^{-1} Y$ by $Y$.  So $x^*(\theta)$ is not only continuous, it is constant.
EDIT:
In the revised problem, here's a counterexample.  Take $s=m=n=1$, $\epsilon = 1/2$,
$A = -1$, $B=1$, $C=1$, ${\mathbb Y} = \{1/2, 1\}$.
 Thus the constraint is $- \theta + Y = \theta Z$.  $Y = 1/2$ allows the first constraint
to be satisfied if and only if $\theta = 1/2$, in which case $Z = 0$.  On the other hand, $Y=1$ allows the
first constraint to be satisfied for all $\theta \in [1/2,1]$ with $Z =  1/\theta-1$.  Thus $x^*(\theta) = 1/\theta - 1$ for $\theta > 1/2$ but $0$ for $\theta = 1/2$.


text:
Q: NGINX Stream Module URL Path to Upstream server? I have the below nginx.conf file which works if I am using dns. However, I wanted to see if there was a way using ssl-pass through to use a single ip that could map to different hosts based on the url path similar to how reverse-proxy's location configuration works?
For example, if users were coming in on 10.0.0.3/example1 or 10.0.0.3/example2 it would pass through the ssl request to the appropriate upstream server based on the route...
stream {
  map $ssl_preread_server_name $selected_upstream {
    example1.org upstream_1;
    example2.org upstream_2;
  }

  upstream upstream_1 { server 10.0.0.1:443; }
  upstream upstream_2 { server 10.0.0.2:443; }

  server {
    listen 443;
    proxy_pass $selected_upstream;
    ssl_preread on;
  }
}


text:
Q: Angular mat-menu I want to make a big matmenu (95 items) but it goes over the page.
see my code :

<mat-menu #departements="matMenu">
    <button mat-menu-item (click)="choix_du_departement(01)" >01</button>
    <button mat-menu-item (click)="choix_du_departement(02)" >02</button>
    <button mat-menu-item (click)="choix_du_departement(03)">03</button>
...
    <button mat-menu-item (click)="choix_du_departement(95)">95</button>
</mat-menu>

I tried to manage via .scss
with

 .mat-menu{
   max-height: 50px;
 }

but nothing change
I tried to modify .mat-menu-item too but some it goes off the page

A: If I understand, you need to set the height of the button
 .mat-menu-item{
   max-height: 50px;
 }

A: You have two options either give your mat-menu element a mat-menu class
Or change your CSS selector to  mat-menu instead of  .mat-menu

A: I struggled with getting this css applied also, instead I wrapped the content in a div with a custom class and set the height of that div.

A: ::ng-deep .cdk-overlay-pane {
        max-height: 350px !important;
      }


text:
Q: Xamarin Native: How to connect to google drive and save a file I'm working on Xamarin Native app ( Not xamarin.Forms ) and I want the app to be able to connect to the google drive of any email e.g johndoe@gmail.com and save some files. I have searched to no avail but can't find an explicit example which uses Xamarin native to achieve that. Does anyone have some suggestions?
As suggested in the comment, I am not trying to connect to any email address, I'm trying to connect to the email address of the phone on which the app is running.
I installed the nuget package google.services.drive but I can't find any example of how to use the package. The one example i saw was using visual studio components which has now been depreciated in visual studio 2017/2019

A: I think you can use Google Drive API: https://developers.google.com/drive/api/v3/about-sdk


text: Q: Настройка запросов от пользователей к администратору Django Пользователь в личном кабинете заполняет определенную форму и тем самым создает объект, у которого один из параметров по умолчанию False. Требуется реализовать механизм, по которому пользователь одновременно с созданием объекта запрашивает у администратора изменение параметра на True (возможно запрос отправляется на почту админа). А администратор, в свою очередь через админку или же без нее исправляет параметр на True.


text:
Q: Random variable for sum of probability densities. Given two Random Variables: $X$ with probability density $f_X(x)$ and $Y$ with probability density $f_Y(y)$, I want to understand the random variable $Z$ such that $Z$ has probability density $f_X(z) + f_Y(z)$. Here, I'm allowing for negative probability densities, and $f_X$ and $f_Y$ do not necessarily integrate to 1.
NB: I'm not looking for the formula for the pdf of $Z = X+Y$, which was answered many times in other posts.
I want to know if there is a way to express $Z$ in terms of $X$ and $Y$. For example, can I find constants $c_{ij}$ to say $Z = \sum_{ij} c_{ij} X^iY^j$?
Thank You!
EDIT: After reading some comments, it seems like posing this question in terms of $X$ and $Y$ as random variables doesn't really make sense if $f_X(x)$ and $f_Y(y)$ are not always positive and do not integrate to 1. So I want to ask the simpler version of this question. If $f_X(x)$ and $f_Y(y)$ are proper probability density functions, and we have some random variable $Z$ with pdf: $pf_X(z) + (1-p)f_Y(z)$ where $p \in [0,1]$, is there a way to express $Z$ in terms of $X$ and $Y$ (like $Z = \sum_{ij} c_{ij} X^iY^j$)?
($X$ and $Y$ are independent)

A: The edited question is amenable to standard probability theory: $Z$ is a mixture of $X$ and $Y$. More precisely, let $B$ be Bernoulli with parameter $0<p<1$, independent of $X$ and $Y$. If $X$ and $Y$ have PDFs $f_X$ and $f_Y$ respectively, then $Z=BX+(1-B)Y$ has PDF $f(z)=pf_X(z)+(1-p)f_Y(z)$.
(Though it may not be what you desired to have the coefficients $c_{ij}$ themselves random...)

A: Note that the distribution or density functions of a function of your $\ X\ $ and $\ Y\ $ will, in general, depend not merely on their individual density functions, $\ f_X\ $ and $\ f_Y\ $, but on their joint distribution or density function, $\ f_{XY}\ $, assuming that this latter exists.  With that qualification, if $\ \varphi:\mathbb{R}\times\mathbb{R}\rightarrow\mathbb{R}\ $ is any function at all such that $\ \varphi(X,Y)\ $ has a density $\ f_\varphi\ $, then the random variable
$$
\int_{-\infty}^{\varphi(X,Y)}f_\varphi(t)dt
$$
will be uniformly distributed.
I have to confess that I have no idea what it means for a random variable $\ Z\ $ to have a density function $\ f_X+f_Y\ $ which integrates to a value of $2$, rather than $1$, but if you define
$$
F_\text{zinv}(y)=\inf \left\{x\left| \int_{-\infty}^x\left(f_X(t)+f_Y(t)\right) dt\ge 2y\right.\right\}\ ,
$$
then the random variable
$$
Z=F_\text{zinv}\left(\int_{-\infty}^{\varphi(X,Y)}f_\varphi(t)dt\right)
$$
will have density function $\ \frac{f_X+f_Y}{2}\ $.


text:
Q: iphone coredata removing records between two entities connected by relation ship I'm implementing core data in my iphone app. It has two entities.
Entity1: LatestData
Entity2: LatestDetailedData
LatestData has URL, publishedDate, heading
LatestDetailedData has URL, NewsDescription, PublishedDate, Author
Both entities have same URL for a record.
Both the entities are connected with inverse relation ship. And the relation ship is "delete->Cascaded"
What I want: If I remove a record in LatestData, I want the record with same URL in LatestDetailedData must also be deleted.
How?

A: If I am understanding you correctly, you are using a relationship and it has an inverse.  If that is the case then when you delete one then Core Data will automatically delete the other and you don't need to do anything extra.
What are you seeing that suggests that is not happening?
Update
Since you are using multiple threads, are you using one NSManagedObjectContext per thread?  If so, are you updating all of the threads when a save occurs?  I suspect one of those two is not occurring and therefore causing your issue.

A: when you create the entities you need to create the relationship too

LatestDetailedData * entity2 = [[NSEntityDescription insertNewObjectForEntityForName:@"LatestDetailedData" inManagedObjectContext:context];
entity1.lastestdetail=entity2;

if you are just relying on a URL field, then thats bad practice. Set up the relationship in coredata and the cascaded deletes will take care of themselves.


text:
Q: Get phone number from google map marker I working with google map on android device , i am fetch information from markes , i am able to get marker title and maker snippet, but unable to get phone number information, please help me, thanks in advance.
package com.avion.mapdemo;

public class MainActivity extends Activity implements OnInfoWindowClickListener {
// Google Map
private GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
GPSTracker gps;
Address adrs;

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

    try {
        // Loading map

        initilizeMap();

        // my location...
        googleMap.setMyLocationEnabled(true);

        // room setting from 2(min) to 21 (max)..
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(10.0f));

        // get my location address......

        myLocation();

    } catch (Exception e) {
        e.printStackTrace();
    }

    // marker information tab clicked...........

    googleMap.setOnInfoWindowClickListener(this);

}

// method my location
private void myLocation() {

    // TODO Auto-generated method stub

    // for logitude and latitude..........

    gps = new GPSTracker(MainActivity.this);

    // check if GPS enabled
    if (gps.canGetLocation()) {

        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();

        //double latitude = 40.71958;
        // double longitude = -74.09595;

        // Toast.makeText(getApplicationContext(),latitude
        // +"--"+longitude,Toast.LENGTH_SHORT).show();

        // for address..........
        Geocoder geocoder;
        List<Address> addresses = null;
        geocoder = new Geocoder(this, Locale.getDefault());
        try {
            addresses = geocoder.getFromLocation(latitude, longitude, 1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String address = addresses.get(0).getAddressLine(0);
        String city = addresses.get(0).getAddressLine(1);
        String country = addresses.get(0).getAddressLine(2);

        Toast.makeText(getApplicationContext(),
                address + "" + city + "" + country, Toast.LENGTH_LONG)
                .show();

        Log.e("strite", address);
        Log.e("city", city);
        Log.e("country", country);
        // search string.....
        // String addr="Hotel "+address
        // +" "+city+" "+country;

        String addr = "Bar" + " " + city + " " + country;

        // call async task for load bars.....

        new GeocoderTask().execute(addr);

    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

/**
 * function to load map. If map is not created it will create it for you
 * */
private void initilizeMap() {
    if (googleMap == null) {
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

@Override
protected void onResume() {
    super.onResume();
    initilizeMap();
}

// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {

    @Override
    protected List<Address> doInBackground(String... locationName) {
        // Creating an instance of Geocoder class
        // Geocoder transforming a street address or other description of a
        // location
        // into a (latitude, longitude) coordinate.
        Geocoder geocoder = new Geocoder(getBaseContext());
        List<Address> addresses = null;

        try {
            // Getting a maximum of 10 Address that matches the input text
            addresses = geocoder.getFromLocationName(locationName[0], 10);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return addresses;
    }

    @Override
    protected void onPostExecute(List<Address> addresses) {

        if (addresses == null || addresses.size() == 0) {
            Toast.makeText(getBaseContext(), "No Bar found",
                    Toast.LENGTH_SHORT).show();
        }

        // Clears all the existing markers on the map
        googleMap.clear();

        // Adding Markers on Google Map for each matching address
        for (int i = 0; i < addresses.size(); i++) {

            // address Strings describing a location
            adrs = (Address) addresses.get(i);

            // Creating an instance of GeoPoint, to display in Google Map
            // latLng class representing a pair of latitude and longitude
            // coordinates,

            latLng = new LatLng(adrs.getLatitude(), adrs.getLongitude());

            // latLng = new LatLng(40.71958,-74.09595);

            String addressText = String.format("%s, %s", adrs
                    .getMaxAddressLineIndex() > 0 ? adrs.getAddressLine(0)
                    : "", adrs.getCountryName());

            // markerOptions to add property to marker

            markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title(adrs.getAddressLine(0));
            markerOptions.snippet(adrs.getAddressLine(1) + ", "
                    + adrs.getAddressLine(2) + ", "
                    + adrs.getPhone());

            /*
             * getAddressLine(0) location name .
             * getAddressLine(1) local address .
             * getAddressLine(2) city,state .
             * getAddressLine(3) country .
             */
            googleMap.addMarker(markerOptions);

            // Locate the first location
            if (i == 0)
                googleMap.animateCamera(CameraUpdateFactory
                        .newLatLng(latLng));
        }
        // end of loop.....
    }
}

// on marker info tab click..
@Override
public void onInfoWindowClick(Marker marker) {

    Toast.makeText(this, marker.getTitle() + "--" + marker.getSnippet(),
            Toast.LENGTH_LONG).show();

}

}

A: You should split your Snippet Marker text and extract all the details.
see below
public void onInfoWindowClick(Marker marker) {

String[] str2 = marker.getSnippet().split(",");
String Addressline1=str2[0]; //Addressline 1
String Addressline2=str2[1]; //Addressline 2
String phone=str2[2]; //Phone

Toast.makeText(this, marker.getTitle() + "--" + marker.getSnippet()+"-- "+phone,
        Toast.LENGTH_LONG).show();
}


text:
Q: cURL to C# webrequest I am trying to convert a cURL script to a C# script.
If I want to POST an image do I have to convert it to a string?
When I try running my script I get an exception from the target machine. Unfortunately I don't have access to see the code on the target machine.
$ch = curl_init();
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Expect:"));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($ch, CURLOPT_USERPWD, "user:pwd");
curl_setopt($ch, CURLOPT_URL, 'http://192.168.1.105/upload.php');
$data = array('type' => 'upload', 'student' => 'Peter', 'class' => '101', 'fotograf'          => 'Jane', 'file' => '@/pictures/image1.jpg');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);

This is what I have come up with:
WebRequest request = WebRequest.Create("http://192.168.1.105/upload.php");

request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
string authInfo = "usr:pwd";
request.Headers["Authorization"] = "Basic " + authInfo;
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("type=upload&student=Peter&calss=101&fotograf=Jane&file=/pictures/image1.jpg");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();

WebResponse response = request.GetResponse();

Any ideas?

A: Possibly there is problem with the Authorization header and replacing:
string authInfo = "usr:pwd";
request.Headers["Authorization"] = "Basic " + authInfo;

with:
request.UseDefaultCredentials = false;
request.Credentials = new NetworkCredential(user, pwd);

might solve the problem.

A: Before writing the buffer into the stream, make sure to convert it to a base64 string:
string result = System.Convert.ToBase64String(buffer);


text:
Q: JCombobox Listener how to enable it when item is selected? I have a JComboBox that displays Name From database Patients_Details
public void ComboItem() {

chooser.removeAllItems();
chooser.addItem("Please Select...");
try {
         String sql="select * from Patients_Details";
         pst = conn.prepareStatement(sql);
         rs=pst.executeQuery();
        while (rs.next()) {
            String id = rs.getString("Patient_ID"); // Get the Id
            String name = rs.getString("Name"); // Get the Name

            ComboItem comboItem = new ComboItem(id, name); // Create a new ComboItem
            chooser.addItem(comboItem); // Put it into the ComboBox
            String tmp=comboItem.getid();
        }
    } catch (SQLException sqle) {
        System.out.println(sqle);
    }
}

This is from comboitem class that only returns the name and not the id
  public String toString() {
    return this.name  ;
   }

My question is how do I get the selecteditem so that this action can be performed I have no clue how to do this I have been trying all bunch of code for almost 2 hours
any help will be much appreciated
NB I am Java beginner
  private void chooserPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {

    try{
      String sql="select * from Patients_Details where Patient_ID=? ";
      pst=conn.prepareStatement(sql);
      rs=pst.executeQuery();
      if(rs.next()){
      String add1=rs.getString("Patient_ID");
      txtpatientid.setText(add1);
      String add2=rs.getString("Name");
      txtname.setText(add2);
      String add3=rs.getString("Age");
      txtage.setText(add3);
      String add4=rs.getString("Gender");
      txtgender.setText(add4);
      String add5=rs.getString("Date");
      txtdate.setText(add5);
       }
  }
  catch(Exception e) {
    JOptionPane.showMessageDialog(null,e );
  }
}

A: Simply add an ActionListener to the combo box. When actionPerformed is called, you can look up the selected value and call what ever methods you need to.
For example:
chooser.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        Object selectedValue = chooser.getSelectedValue();
        // carry on with what ever you need
    }
});

Have a look at ...

*

*How to write action listeners

*How to use combo boxes
For more details


text:
Q: flutter runes , inside text Controller �� Good day Comunnity
I am using a text Controller , I want to store the emoji + text value in MySQL database,
I am using this code ,
TextEditingController nameController =
new TextEditingController(text: "");
Runes encoded = new Runes (nameController.text);
var name = new String.fromCharCodes(encoded);
print (name);

but the result it's not that I expected.
It's printing some like
John Doe   �
any idea how to achieve it?
thank you very much!
cheers.

A: You can use StringEscapeUtils Apache Library https://commons.apache.org/proper/commons-lang/download_lang.cgi
For saving the unicodes in database you have to encode them. So send your unicodes to server by encoding like
StringEscapeUtils.escapeJava(/* string message*/)

For displaying the encoded unicode in android
StringEscapeUtils.unescapeJava(/* string message*/)


text:
Q: Does this geometry question have a proper solution? This question is from a family friend's 11th grade geometry homework:

If $BC$ is the bisector of the angle $A\hat{B}D$ , use the following information to determine the missing values: Measurment of angle $\hat{ABD}= 7x+9 $, measurement of angle $\hat{CBD} = 3x+5$ , $x=$ ?. Also determine the values for the measurements of angles $\hat{ABC}, \hat{CBD} $, and $\hat{ABD}$ .

I may be overthinking it, but is this question flawed? There is no other information that would allow for the application of the Angle Bisector Theorem, unless I am misunderstanding.

A: $\angle ABD=2\angle CBD$ or $7x+9=2(3x+5)$. This yields $x=1$. Then $\angle ABD=7\cdot1+9=16$ and $\angle ABC=\angle CBD=8$

A: $\angle ABD = 7x + 9$
$\angle CBD = 3x + 5$
Since BC is the angle bisector of $\angle ABD$, we have:
$\angle ABC = \angle CBD$
Also, $\angle ABD$
$$= \angle ABC + \angle CBD$$
$$= \angle CBD + \angle CBD$$
$$= 2 \angle CBD$$
Thus we have $7x + 9 = 2 (3x + 5)$.
On solving this, you'll get $x = 1$.
So we have $\angle(ABD) = 7*1 + 9 = 16 $degrees
$\angle CBD = 3*1 + 5 = 8$ degrees
$\angle ABC = \angle CBD = 8 $degrees

A: It is very simple since $BC$ is bisector of $\angle ABD $ so It's twice as much as  $\angle CBD $ . So $$7x+9=2(6x+10)$$ or $$x=1$$. Can you can calculate rest ?


text:
Q: Rxjs timer is completing too early on react-native/android Ok, in order to ask my question here's a little context:
I have a react-native project that uses the react-native-ble-plx library in order to access the device's bluetooth. The library has a startDeviceScan method that takes a callback, and so I wanted to use rxjs in order to scan for devices for a period of time and then collect them all in an array, returning the result as a promise. I'm doing this through a combination of bufferTime and take pipe operators, though I managed to do it with takeUntil(timer()) as well. This is the code for scanning(note: I'm using typescript as well):
  async lookForNearbyDevices(timeout = 5000): Promise<Device[]> {
    if (timeout < 1) {
      throw new Error('Erro: lookForNearbyDevices requer um timeout')
    }

    return new Promise<Device[]>((resolve, reject) => {
      const scanReader = new Observable<Device>(obs => {
        this.manager.startDeviceScan(
          [ServiceUUIDs],
          { allowDuplicates: false },
          (err, dvc) => {
            if (err) {
              obs.error(err)
              return
            } else if (!dvc) {
              // Unreachable code
              return
            }

            if (!protocolNameMatches(dvc.name)) {
              // not what I'm looking for
              return
            }

            obs.next(dvc)
          },
        )
      }).pipe(
        distinct(dvc => dvc.id),
        bufferTime(timeout),
        take(1),
      )

      let dvcs: Device[] = []
      scanReader.subscribe({
        next: result => (dvcs = result),
        error: err => {
          console.debug(err)
          reject(err)
        },
        complete: () => {
          this.manager.stopDeviceScan()
          resolve(dvcs)
        },
      })
    })
  }

The problem is that, when executing it on my device(Android 8.0), bufferTime(and even timer) is emitting ~2900ms too early, regardless of the value of timeout. This is a problem because I don't want to finish my scan too early; Right now I can "deal" with this by adding 3s to the timeout, but I'd rather figure out the underlying issue than to rely on this type of patchwork.
Trying to figure this out, I decided to try a minimalist example:
const obs = timer(6000)
console.time('timerRXJS')
obs.subscribe({
  complete() {
    console.timeEnd('timerRXJS')
  },
})

...and this example also completes about 2900ms too early.
Is there any reason that bufferTime(and timer) would emit early like that? Note that I haven't changed anything on rxjs Schedulers and whatnot, since I don't really understand how they work. Maybe there's something there to figure out?
Any help at all would be appreciated.


text:
Q: How would I use base addressing mode to save character into variable? I'm new to Assembly and learning the basics, but i've been stuck for a while on this and don't know how to get past it. The code below works, but not using the required base addressing mode.
I have to copy the fifth character from String into the variable N, using the base addressing mode. The way I went about it (not using base addressing mode) is by using base with offset. I'm not sure how I would achieve this doing base addressing mode, any help would be appreciated.
;Initialized data
section .data
msg1: db "Input a string: ",10
msg1_L: equ $-msg1      ;calculate size of msg1
n_line DB 0AH,0DH,"$"

;Uninitialized data
section .bss
String resb 128
N resb 1

section .text
global _start:
_start:
;Print message
mov eax, 4        ;sys_write
mov ebx, 1        ;stdout
mov ecx, msg1     ;message to write
mov edx, msg1_L   ;message length
int 80h

;input message and save
mov eax, 3
mov ebx, 0
mov ecx, String
mov edx, 256
int 80h

;Copy 5th character to N, using base addressing mode
;This is where my problem is
mov bx, [String+4]
mov [N], bx
mov eax, 4      ;sys_write
mov ebx, 1      ;stdout
mov ecx, N      ;message to write
mov edx, 1      ;message length
int 80h

;Print new line
mov eax, 4        ;sys_write
mov ebx, 1        ;stdout
mov ecx, n_line   ;message to write
mov edx, 1        ;message length
int 80h

A: ;This is where my problem is
mov bx, [String+4]
mov [N], bx

Obviously only ASCII characters in the String are expected, because you reserved 1 byte with N resb 1.  You should use one-byte register to copy 5th byte of String to the variable N. Use bl or al instead of bx.
Or, if you insist on employing register-addressing mode, you can use any GPR in 32bit programs, for instance
 mov esi,String   ; Put address og String to esi.
 mov ebx,4        ; Put index of 5th byte to ebx.
 mov al,[esi+ebx] ; Load 5th byte to al.
 mov [N],al       ; Store al to the variable.

Other minor issues:
You have reserved 128 bytes fo String but you asked sys_read to read up to 256 bytes.
n_line DB 0AH,0DH,"$" Dollar-terminated strings are not used in Linux, 0AH is enough to make a new line.
You should let your program terminate gracefully with sys_exit.


text:
Q: Element is found but not clickable I'm trying to find an element by it's id, click on it and download a file.
driver.get(url);
driver.implicitly_wait(60);
time.sleep(3)
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "ContentPlaceHolder1_a1")))
href = element.get_attribute('href')
value = href.split('/')[-1]
print(value);
element.click(); # Error

Error
element click intercepted: Element is not clickable at point (110, 1003)
I've tried Xpath, and CSS path too. All give the same error. If I check for the visibility then it times out. But I can manually see that the element is visible
element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//a[contains(text(), 'text of the link')]")))

At last, I tried this code.
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "ContentPlaceHolder1_a1")))
ActionChains(driver).move_to_element(element).click().perform()

But it gives error
selenium.common.exceptions.MoveTargetOutOfBoundsException: Message: move target out of bounds

A: While identified the element, page is still loading, may be the reason it is clicking on somewhere else.
Scroll down to the element and then wait for 1 to 2 seconds and then click.
It is working perfectly for me.
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "ContentPlaceHolder1_a1")))
element.location_once_scrolled_into_view #scroll down to element
time.sleep(2) # wait for 2 seconds , 1 sec working as well
element.click()


text:
Q: Why does Bluecove require libbluetooth-dev package installed to run I'm just setting up Bluecove on an Ubuntu system and I see buried down in the wiki for the Linux BlueZ stack that it requires a dev package to be installed for it to work correctly.
I understood that a dev package is only required if I need the headers for compiling my own C/C++ code to use the Bluecove native library. If I'm only compiling Java code then surely the development package is not needed? (It's effectively seen as an application using the Bluecove native library). Is this correct?

A: It seems as though the package libbluetooth3 doesn't include the .so link to the specific library when it is installed. (Use dpkg-query).
The Bluecove JARs contain JNI libraries that are linked against the the .so file (confirmed using ldconfig). I found that only libbluetooth-dev contains the .so so for would be the only way for the uninitiated to get Bluecove to work.
I resolved the issue by creating the soft-link manually, the package libbluetooth3 installed.


text:
Q: _GLIBCXX_USE_C99 is not defined, to_wstring not available I've run into a very serious (IMO) problem. I am using the native cross platform tools in visual studio 2015.
Since several implementations of the standard library were downloaded by visual studio

C:\ProgramData\Microsoft\AndroidNDK\android-ndk-r10e\sources\cxx-stl\

I was surprised when I started finding stl classes that were not compiling.
I wrote off std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> not being available as a quirk of gnu-libstdc++.
I tried to set the stl to others to see if they were better. This was done in the visual studio project properties window.

No combination of toolset or STL made std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> available.
I moved on, saying "If I have to implement that one function myself it's not the end of the world."
However shortly afterward I tried to use to_wstring. Again the function was not recognized even though wstring was.
This was a step too far so I checked to see if gnu-libstdc++ had in fact implemented anything at all. In fact they had, see 21.5 of the standard is Y.
I was very confused now. I did some googling and found nothing more substantial than "set it to c++ 11."
Unless Visual Studio isn't doing anything with the following setting I assume GCC is being called correctly.

Eventually I opened up basic_string.h in visual studio to make sure that the function was actually there.
It was, line 3000:
inline wstring
to_wstring(int __val)
{ return __gnu_cxx::__to_xstring<wstring>(&std::vswprintf, 4 * sizeof(int), L"%d", __val); }

Then I saw by the shading that it was being omitted by the preprocessor. Behold line 2847:
#if ((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
     && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))

The problem was not __cplusplus nor _GLIBCXX_HAVE_BROKEN_VSWPRINTF. _GLIBCXX_USE_C99 was not defined.
Searching for this problem yielded a couple of stack overflow questions.
Most of the comments seemed to think the problem would be fixed with a new release of GCC. For instance GCC 4.4.5. However since visual studio downloaded 4.9... I don't think this is merely a problem with versions.
I followed the link there to a three year old bug report which contained the statement:

It's not possible to fix in GCC without extraordinary effort for a
  single target, which is not going to happen. If a given target wants
  to support C++11 features then it needs to provide the necessary C99
  features. This is not a GCC issue.

Well, in visual studio I had set the C standard to C99, for the record C11 didn't make any difference.
I am really not sure how to proceed from here. It seems to me that somehow Visual Studio is not communicating to GCC what is or is not available. That is just a theory though.
I am opposed to trying to manually change a distribution on the stl. That defeats the purpose of a stl. At the same time this project I am undertaking may well be impossible without the standard library (given the time constraints). I am afraid to continue lest I find more critical functionality hidden due to lack of C library functions.
I have this insane hope that there is something I could change in visual studio, some setting or command line override that would fix this.
P.S. I have looked into developing the android part in eclipse or android studio. The NDK documentation mentions eclipse often, but the android SDK has scary messages about the ADT no longer being supported. On top of that I had issues out of the box debugging the native code (but those are beyond the scope). The android studio build system (gradle) doesn't seem friendly to custom folder structures in the least. All of our source is in TFS and I can't change that at this point.

A: This is known problem of Google's Android NDK - C++ Standard Library is broken there, unless you're using just small subset of C++ functionality. Macro _GLIBCXX_USE_C99 is defined (or not defined) in $NDK/sources/cxx-stl/gnu-libstdc++/4.9/libs/$ABI/include/bits/c++config.h at the moment when GNU libstdc++ is building (i.e. on Google's side, when they build NDK). Unfortunately, it's built on top of very limited libc (Google's Bionic), so GNU libstdc++ configuration scripts detect it and disable some parts (in particular, std::to_wstring), depending on that absent functionality in libc.
This is one of the main reason why I've started CrystaX NDK - alternative native development kit for Android. In CrystaX NDK, we pay special attention to completeness of libc, libstdc++, and conformance to standards in general. CrystaX NDK works as a drop-in replacement for Google's Android NDK, so most likely it will just work with Visual Studio too.


text:
Q: Is there anyway to confirm configuration settings are set On iPhone once IT admin push the configuration file ( mobileconfig ), is there anyway a iphone client can confirm if this configue file is installed on phone?
Thanks,

A: Yes, on the iPhone go to Settings -> General -> Profiles, it will list all the configuration profiles (.mobileconfig) and provisioning profiles (.mobileprovision) on the phone.


text:
Q: poisson distribution always produces same instances at each run I am trying to generate random arrivals via poisson distribution for my project. The code part:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <random>
#include <ctime>
int nextTime(double lambda,int timeslots,int PU_number);

int main()
{
    srand(time(0));
    //some code
    nextTime(4,time_slots,PU_number);
}
int nextTime(double lambda,int timeslots,int PU_number)
{
    int mat[PU_number][timeslots];
    std::default_random_engine generator;
    std::poisson_distribution<int> distribution(lambda);
    int number;
    int total=0;
    for(int i=0; i< PU_number;i++)
    {
        total=0;
        for(int j=0;j<timeslots;j++)
        {
            number = distribution(generator);
            total+=number;
            mat[i][j]=total;//another matrix, not relevant here
            cout<<number<<" ";
        }
        cout<<endl;
    }
    return 0;
}

Above code always produces same numbers. what is wrong here?

A: srand seeds rand, not your std::default_random_engine. To seed this, use
std::default_random_engine generator(std::random_device{}());
                                     ^^^^^^^^^^^^^^^^^^^^^^
                                     e.g., any seed can go here


text:
Q: Recycler view is not update when using carrousel manager library I'm trying to pull image data into Recycler view (each sub item is a PagerSnapHelper element) but faced below problem
1 - recycler view is not getting update when first time load, sub elements seems to be misalignment.
2 - i have to slide or touch the screen to reload the view, all elements is showing ok then.
the faulty one, when the first time load Recycler view

the correct one, after i swipe the view

In Activity
override fun onGetDataSuccess(obj: RESP_DetailDiscover.ObjectDetailDiscover) {
        if (obj.gallery_popup.isNullOrEmpty()) {
            adapterPopup.setListData(mutableListOf())
        } else {
            adapterPopup.setListData(obj.gallery_popup)
        }
}

adapterPopup = PopupAdapter(applicationContext)
        val layoutManager = ZoomCenterCardLayoutManager(this)
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL)
        val snapHelper = PagerSnapHelper()
        snapHelper.attachToRecyclerView(rcvPopup)

        rcvPopup.addOnScrollListener(CenterScrollListener())
        rcvPopup.getViewTreeObserver().addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                rcvPopup.getViewTreeObserver().removeOnGlobalLayoutListener(this)
                val range = this@DetailDiscoverActivity.getResources().getDimension(R.dimen.width_item_horizontal_popup).toInt()
                val margin = this@DetailDiscoverActivity.getResources().getDimension(R.dimen.margin_item_horizontal_popup).toInt()
                val extent = (rcvPopup.getWidth() - range) / 2 - margin
                rcvPopup.setPadding(extent, 0, extent, 0)
                rcvPopup.setClipToPadding(false)
            }
        })
        rcvPopup.layoutManager = layoutManager
        rcvPopup.adapter = adapterPopup
        layoutManager.smoothScrollToPosition(rcvPopup, null, 0)
        rcvPopup.addItemDecoration(LinePagerIndicatorDecoration())

A: Whenever you set list data you have to notifyDataSetChange() on your adapter . In that way you will tell your program that : "Hey , I have updated something , show it to me !"
fun setListData(list: ArrayList<GalleryPopupObjectOrSomethingLikeThat>) {
  yourAdapterList = list
  notifyDataSetChange()
}


text:
Q: Expected length of arc containing a point You are given a circle $C$ of unit radius and a point $M$ on it. Now, three points are chosen at random on the circle $C$ which divides it into three arcs. What is the expected length of the part that contains $M$?
My doubt is whether we should consider $M$ fixed or not.

A: We may consider $M$ fixed without loss of generality. $M$ cuts the circle into a line, which we take as having length 1 (scaling to the real circumference of $2\pi$ will happen at the end). The three random points on $C$ are then random variables $U_1,U_2,U_3\sim U(0,1)$ and
$$E(\text{length of arc containing }M)=E(U_{(1)})+(1-E(U_{(3)}))=E(\mathrm B(1,3+1-1))+1-E(\mathrm B(3,3+1-3))=E(\mathrm B(1,3))+1-E(\mathrm B(3,1))=\frac14+1-\frac34=\frac12$$
where $U_{(i)}$ are order statistics and $\mathrm B$ is the beta function. Thus, on the unit circle, the expected length of the segment containing $M$ is $\frac12\cdot2\pi=\pi$.


text:
Q: Combine SQL Select Lines into "Groups" I have the following problem,
I have an audit system, which saves the ID of at most three companies for each Audit onde the database line, but it is possible to have up to 15 companies in an audit.

Criteria to determine if group audit
IF

*

*A record has data in Audited_Company2 AND/OR Audited_Company3
THEN
Find additional records where:

*Auditor_ID AND Audit_Type AND Audit_Date all match the record found above AND
IF
Records matching criteria are found:
1.Take Audited_Company1-3 from all other matching records and insert them into Audited_Company4-15

*Do not show any audits that have had Audited_Company fields merged into another record in the view

However, I have no idea how to I merge 2 or more SQL Lines n a select result like they asked

A: You can use UNPIVOT to normalize your data and then PIVOT to denormalize it again. Below is a sample query that combines the two. It uses ROW_NUMBER() with appropriate partitioning and ordering conditions to assign sequence numbers to the data for use in the final pivot.
DECLARE @Unnormalized TABLE (Id INT, Value1 VARCHAR(100), Value2 VARCHAR(100), Value3 VARCHAR(100))
INSERT @Unnormalized
VALUES
    (1, 'A', 'B', 'C'),
    (1, 'Z', 'Y', NULL),
    (1, 'X', NULL, NULL),
    (2, 'Red', 'Green', NULL),
    (2, 'Blue', NULL, NULL)

SELECT P.Id, Value1 = P.[1], Value2 = P.[2], P.[3], P.[4], P.[5], P.[6], P.[7], P.[8], P.[9]
FROM (
    SELECT U.Id, U.Value, Sequence = ROW_NUMBER() OVER(PARTITION BY U.ID ORDER BY U.Value)
    FROM (SELECT * FROM @Unnormalized) D
    UNPIVOT (Value FOR Col IN (Value1, Value2, Value3)) U
) A
PIVOT (MAX(Value) FOR Sequence IN ([1],[2],[3],[4],[5],[6],[7],[8],[9])) P

Results:

Id
Value1
Value2
3
4
5
6
7
8
9

1
A
B
C
X
Y
Z
NULL
NULL
NULL

2
Blue
Green
Red
NULL
NULL
NULL
NULL
NULL
NULL

You should be able to expand on the above to suit your specific needs.
For more information, take a look at the documentation at FROM - Using PIVOT and UNPIVOT.


text:
Q: How do I convert a wParam to a CString? I have a pMsg->wParam from a WM_KEYDOWN message, and I want to convert it into a CString. How can I do that?
I have tried the following code:
TCHAR ch[2];
ch[0] = pMsg->wParam;
ch[1] = _T('\0');
CString ss(ch);

but it does not work for high ASCII characters.

A: According to the documentation, WM_CHAR sends a character code in wParam. The first paragraph in the Remarks section says that the code is indeed a Unicode UTF-16 codepoint. This is true whether you are compiling your code for 8 or 16 bit TCHAR.
CodyGray's comment is correct in the part that CString supplies a variety of constructors. The one you are looking for is that which takes a wchar_t as its first argument (the second argument, the repetition count, is set to 1 by default). Therefore, to construct a CString out of a WPARAM, you cast the value to wchar_t. The following sample prints "0", confirming that the constructed string is indeed what it is expected to be.
#include <stdio.h>
#include <Windows.h>
#include <cstringt.h>
#include <atlstr.h>
int main ()
{
  WPARAM w = 0x222D;
  CString cs ((wchar_t)w);
  printf ("%d", cs.Compare (L"\x222D"));
}

It will work the same in both _UNICODE and ANSI compilation modes, and is portable across 32 and 64 bitness.

A: The problem is that wParam contains a pointer to an array of characters. It is not a single character, so you can't create the string yourself by assigning it to ch[0] as you're trying to do here.
The solution turns out to be a lot easier than you probably expected. The CString class has a constructor that takes a pointer to a character array, which is precisely what you have in wParam.
(Actually, it has a bunch of constructors, one for pretty much everything you'll ever need...)
So all you have to do is:
CString ss(pMsg->wParam);

The constructor will take care of the rest, copying the string pointed to by wParam into the ss type.


text:
Q: ListView Item Added Event Is there an event that I could use that occurs when an Item is added to a listView?

A: Don't think so.
I have used this listview replacement in the past.  I'm fairly sure it has an event for when an item is added.


text:
Q: Where/how does log4j look for a log4j.properties file? I'm trying out log4j in a simple test app. I create a new Java project in eclipse and add the log4j JAR (v1.2.16) to my build path. I then create a simple class that prints Hello World. Then I use the log4j Logger class to log a info message. When I run the app, I see the log message, using what I assume is the default appender and layout. Great. What I'm having trouble with is adding my own configuration. This is what I've done:
Created a log4j.properties file with a custom appender and log level and placed it into the src folder (which upon compilation gets copied to the bin folder). Run the app - no change.
I try adding PropertyConfigurator.configure("log4j.properties"). Run the app - no change. No errors, but no change.
What do I have to do to get log4j to load my configuration file?

A: Argh. I discovered the problem was that eclipse had imported the wrong Logger class. It had imported java.util.logging.Logger which of course has it's own configuration that is different from log4j. Oh well, hope somebody else does this and gets it solved by reading this question.

A: You can enable log4j internal debugging by setting the log4j.debug system property. Among other things, this will cause log4j to show how it is configuring itself.
You can try explicitly setting the URL to the configuration file with the log4j.configuration system property.
See also: this question.

A: The problem may be in the classpath, if the classpath was defined.
The reason it wasn't loading (in my case): There was a conflicting log4j.properties file in one of my jars, and it was overloading the one in my classpath.
In short, if your log4j.properties file isn't loading, there might be another one somewhere else overriding it.
Just thought I'd throw this in too, in case anyone else runs into this. I just spent the last 5 hours trying to figure out why my default log4j.properties wouldn't load.

A: Look in the manual under the heading Default Initialization Procedure, where you'll find the following:

The exact default initialization algorithm is defined as follows:

*

*Setting the log4j.defaultInitOverride system property to any other value than "false" will cause log4j to skip the default
  initialization procedure (this procedure).

*Set the resource string variable to the value of the log4j.configuration system property. The preferred way to specify
  the default initialization file is through the log4j.configuration
  system property. In case the system property log4j.configuration is
  not defined, then set the string variable resource to its default
  value "log4j.properties".

*Attempt to convert the resource variable to a URL.

*If the resource variable cannot be converted to a URL, for example due to a MalformedURLException, then search for the resource from the
  classpath by calling
  org.apache.log4j.helpers.Loader.getResource(resource, Logger.class)
  which returns a URL. Note that the string "log4j.properties"
  constitutes a malformed URL. See
  Loader.getResource(java.lang.String)
  for the list of searched locations.

*If no URL could not be found, abort default initialization. Otherwise, configure log4j from the URL. The
  PropertyConfigurator
  will be used to parse the URL to configure log4j unless the URL ends
  with the ".xml" extension, in which case the
  DOMConfigurator
  will be used. You can optionaly specify a custom configurator. The
  value of the log4j.configuratorClass system property is taken as the
  fully qualified class name of your custom configurator. The custom
  configurator you specify must implement the Configurator interface.

A: log4j.properties should be in your classpath. The "src folder" which is copied to the "bin folder" (I assume you are speaking of a Eclipse setup here), normally belongs to your classpath, so it should be found (are you placing it at the top of the "src" folder, right?)

A: I know this is a couple of months old, but I feel the need to point out that the scr folder isn't "copied" to the bin folder, nor is it part of your runtime classpath....(build path is not runtime classpath!). Eclipse compiles the source files in the src folder to the bin (or whatever you like) folder. It's the bin folder that is part of your runtime classpath.
Just wanted to point this out as these threads are often read by very junior programmers as well, and I'm always frustrated that most of them don't grasp the finesse of the Java classpath, and hence make avoidable mistakes against it.

A: Just throwing it out there to anyone who is struggling to get log4j.properties filed loaded.
I fixed mine by adding the following line:
-Dlog4j.defaultInitOverride=TRUE

Turns out using that JVM parameter, it possible to tell Log4j not to use the Default Initialization Procedure and create your own.
I struggled with mine. I did from clean JAR build to entire REPO pull, nothing work. Combination of that and clean up of class file made it work.