text:
Q: Display attributes of feature with clustering I have one KML layer that has roughly 900 features and I added OpenLayer.Cluster.Strategy to help the layer display a little quicker.
My KML displays the attributes when clicked on before clustering was enabled, but now the bubble displays 'undefined, undefined'.
How did the clustering change the extractAttributes property?
            var state = new OpenLayers.Layer.Vector("State Probation", {
            projection: map.displayProjection,
            strategies: [new OpenLayers.Strategy.Fixed(), new OpenLayers.Strategy.Cluster()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "state.kml",
                format: new OpenLayers.Format.KML({
                    extractStyles: true,
                    extractAttributes: true
                })
            })
        });

        select = new OpenLayers.Control.SelectFeature([sample, state],
            {
                clickout: true, toggle: false,
                multiple: true, hover: false,
                toggleKey: "ctrlKey", // ctrl key removes from selection
                multipleKey: "shiftKey" // shift key adds to selection
            });

        sample.events.on({
            "featureselected": onFeatureSelect,
            "featureunselected": onFeatureUnselect
        });

        state.events.on({
            "featureselected": onFeatureSelect,
            "featureunselected": onFeatureUnselect
        });

        map.addControl(select);
        select.activate();

        map.addControl(new OpenLayers.Control.LayerSwitcher());

    function onPopupClose(evt) {
        select.unselectAll();
    }

    function onFeatureSelect(event) {
        var feature = event.feature;
        var selectedFeature = feature;
        var popup = new OpenLayers.Popup.FramedCloud("chicken",
            feature.geometry.getBounds().getCenterLonLat(),
            new OpenLayers.Size(100,100),
            "
"+feature.attributes.name + "
" + feature.attributes.description,
            null, true, onPopupClose
        );
        feature.popup = popup;
        map.addPopup(popup);
    }
    function onFeatureUnselect(event) {
        var feature = event.feature;
        if(feature.popup) {
            map.removePopup(feature.popup);
            feature.popup.destroy();
            delete feature.popup;
        }
    }

A: When working with clusters, OpenLayers creates an array of attributes to store the attributes of all features in the cluster. When your points are in a cluster you need to access the array instead of the attribute directly. Example (untested):
function onFeatureSelect(event) {
    var feature = event.feature;
    var selectedFeature = feature;
    var text = ""
    if(feature.cluster) {
        for(var i=0; i<feature.cluster.length; i++) {
            text += "
"+feature.cluster[i].attributes.name + "
" +
                   feature.cluster[i].attributes.description + "\n";
        }
    } else {
        text = "
"+feature.attributes.name + "
" + feature.attributes.description;
    }

    var popup = new OpenLayers.Popup.FramedCloud("chicken",
        feature.geometry.getBounds().getCenterLonLat(),
        new OpenLayers.Size(100,100),
        text,
        null, true, onPopupClose
    );
    feature.popup = popup;
    map.addPopup(popup);
}

A: this works for me:
function onFeatureSelect(event) {
    var feature = event.feature;
    var layerName = event.feature.layer.name;
    var content = "unInitialized";
    // alert ('selected this feature='+feature.id+ '
Atributos: '+feature.attributes.description);
    if ( (feature.attributes.name > '') || (feature.attributes.description > '') ) {
        content = feature.attributes.name + '
'+feature.attributes.description;
    } else {
        if (feature.cluster) {
            content = feature.attributes.count + ' ' + layerName ;
            for (var i = 0; i < feature.attributes.count; i++) {
                    var feat = feature.cluster[i];
                    content += '
'+feat.attributes.name;
            }
        } else {
            content = 'NOT a cluster either';
        }
    }

    popup = new OpenLayers.Popup.FramedCloud("chicken",
                             feature.geometry.getBounds().getCenterLonLat(),
                             new OpenLayers.Size(100,100),
                             content,
                             null, true, onFeatureUnselect);
    popup.setBackgroundColor('white');
    feature.popup = popup;
    map.addPopup(popup);
    // GLOBAL variable, in case popup is destroyed by clicking CLOSE box
    lastfeature = feature;
    // alert ('select'+lastfeature.name);
}


text:
Q: When validation correct do On the shipping step in checkout I want to add a class to a form field if the validation of that field is successful but i'm not sure in what JS file I need to add this or where I should add a custom JS file. Can anyone point me in the right direction.
I'm trying to do something like this:

A: Default validation js file is validation.js located in lib/web/mage
Add custom js file
Create checkout_index_index.xml under /app/design/frontend///Magento_Checkout/layout/ folder and add the follwing:
<head>
   <link src="<url of your js file>"/>
 </head>

Also read this topic maybe it's helpful
How to add custom js on checkout page Magento 2?

A: I ended up creating a new js file and adding it in the define in shipping.js.
In the js I check if the field's parents have an _error classes, if so the border turns red otherwise it gets a green border after the minimum length is reached.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can i display images in uitableviewcells using Asyncronous concept in ios I have to show some post blogs into a UITableView. When I have retreived all web service data.
This is my sample code.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
NSError *err;
NSString *strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"response is %@",strResponse);
dit=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&err];

NSArray *arrResults = [dit valueForKey:@"classifieds_mst"];

listOfObjects = [NSMutableArray array];

for(dictRes in arrResults)

{

 Attributes *at = [[Attributes alloc]init];
 at.classimage=[dictRes valueForKey:@"image_name"];
 [listOfObjects addObject:at];

 }

[tableView reloadData];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier=@"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"identifier"];
}
classifiedimage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 80)];
[cell.contentView addSubview:classifiedimage];
Attributes *att = [listOfObjects objectAtIndex:indexPath.row];
NSString *str;
str=att.classimage;
classifiedimage.image = [UIImage imageNamed:str];
return cell;

}

My requirement is i want to display images in uitableviewcells using json parser.I wrote the above code.But the images are not displayed in uitableviewcells.I want to use to display images in uitableviewcells using Asyncronous concept.Please give me any idea.I am new to the programming.Thanks in advance.
This is my json data.
{"classifieds_mst":[{"classified_id":83,image_name":"1389006378_butterfly.jpeg"},
{"classified_id":82,"image_name":"ttt.jpj"},{"classified_id":83,"image_name":"ttttt.jpj"}

A: imageNamed is used to load image from local bundle (in app).
imageWithData:dataWithURL is used to load images from url's.

A: By referring to your JSON data, it just contain the image_name only. So first of all, you need to build the actual image url.  (copy paste that actual url in browser to make sure image is available in server).
Once you have the image url, then you can use AsyncImageView instead of UIImageView in your cell. It will handle the asynchronous thing for you as you just need to set the image url only. Thats the way to go.
One more suggestion is to recheck you cellForRowAtIndexPath, as the code always creating imageView's and adding to cell each time the cell is created. That's not required when you are reusing a cell. You just need to create the image view once when cell is allocated and just assign a tag to imageview and then get the imageview based on this tag and then use it. Just for your reference, I'm posting a sample code:
if(cell == nil){
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"identifier"];
    AsyncImageView *imgView= [[[AsyncImageView alloc]init]autorelease];
    imgView.tag = 1000;
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    [cell.contentView addSubview:imgView];
}
 AsyncImageView *imgView= (AsyncImageView*)[cell.contentView   viewWithTag:1000];
 contactImgView.frame = CGRectMake(0, 0, 300, 80);

 //imgUrl is the actual url of image that is available in datasource
 [contactImgView setImageURL:imgUrl];

Hope it is clear.

A: You have to append domain name in your image name: (image_name":"1389006378_butterfly.jpeg), so that you can get URL of the image which is stored on server, now you can use below code:
 [cell.yourImageView setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:yourImageNameHere]]]];

A: if you are using the AFNetworking then use it to download your image like
    NSArray *keys = @[@"UserID", ];
    NSArray *objects = @[@(userId)];

    NSDictionary *parameter = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:
                                [NSURL URLWithString:BaseURLString]];
    [httpClient setParameterEncoding:AFJSONParameterEncoding];
    [httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                            path:@"UserService.svc/GetUserInfo"
                                                      parameters:parameter];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSError* error = nil;
        id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }];

    [operation start];

and for image use this
[cell.userImage setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:userBasicInfo.imageUrl]]
                                  placeholderImage:[UIImage imageNamed:@"facebook-no-user.png"]
                                           success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
                                               weakCell.userImage.image = image;
                                               [weakCell setNeedsLayout];

                                               } completion:^(BOOL success, NSError *error) {
                                                   NSLog(@"%@",[error localizedDescription]);
                                               }];

                                           }
                                           failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
                                           }];

A: You Create a subclass of UITableViewCell (can call it blogTableViewCell) for your cell and use that in the table.
Initialize blogTableViewCell with the JSON data (you could have an NSDictionary store the JSON info)
In blogTableViewCell create a function that loads image data on another thread (so the main thread can continue its course) and once the image is loaded, update the uiimageview on the cell to display it (This should be done on the main thread as it is a UI update)

A: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    //cell.textLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"name"];
    cell.detailTextLabel.text = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"designation"];
    cell.imageView.image=[UIImage imageNamed:[[resultArray objectAtIndex:indexPath.row] valueForKey:@"image"]] ;

    //[cell.imageView setImageWithURL:[NSURL URLWithString:[[resultArray objectAtIndex:indexPath.row] objectForKey:@"image"]]];
  //  NSURL *url = [NSURL URLWithString:[resultArray objectAtIndex:indexPath .row]];
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[resultArray objectAtIndex:indexPath.row] valueForKey:@"image"] ]];
    cell.imageView.image = [UIImage imageWithData:imageData];

    return cell;
}


text:
Q: Adding 2nd element of a list of lists I want to add the total stake from each list. I have been searching on here for 2 hours but can't get it:
inputs = []

while True:

    add_selection =raw_input("Would you like to add a selection?")
    if add_selection == "Yes":

        selection = raw_input('Horse: ')
        print selection

        stake = float(raw_input('Stake: '))
        print stake

        odds = float(raw_input('Odds: '))
        print odds

        result = (raw_input('Result: '))
        if result == "Win":
            print stake * odds
            winnings = stake * odds
        elif result == "Lose":
            print 0
        elif result == "Refund":
            print stake

        book = raw_input('Book: ')
        print book

        my_list=[selection,stake,odds,result,book]

        **sum([my_list(1) for my_list in inputs])**

        inputs.append(my_list)

        def looks_good(inputs):
            for i in inputs:
              print i
    elif add_selection == "No":
        break

    looks_good(inputs)

I tried the line I highlighted, it gives me an error. I thought about appending my_list with the stake + the stake from the iteration before to keep a running total of the stake but I don't know how I would do this.
Thank you!


text:
Q: Print table footer at very bottom of last page only at footer section I am trying to make footer stick to the bottom of the very last page only at the footer section of the print preview
The page content is dynamic so i dont know which is my last page.
I have tried the below code and it makes the footer appears at the last page of the preview but not in footer section of the last page.currently the footer section prints at the page 2 which is immediate next to the body section but i want footer section to be printed at page 2 of the footer section

    <title></title>
    <meta charset="utf-8" />

    <button onclick="myFunction()"> Print this page</button> <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" /> >

  PAGE HEADER

                        content
 content
 content
 content
 content
 content

                        content
 content
 content
 content
 content
 content

                        content
 content
 content
 content
 content
 content

                        content
 content
 content
 content
 content
 content

                        content
 content
 content
 content
 content
 content

                        content
 content
 content
 content
 content
 content

                        content
 content
 content
 content
 content
 content

                        content
 content
 content
 content
 content
 content

 Sample

Please refer to my attached screenshot for reference

A: You can change this code:

 Sample

To this:

 Sample

You can change the value of margin-top to other value.


text:
Q: How do quantum fluctuations make up vacuum energy? Quantum fluctuations are thought to be the reason why we have energy even if there is nothing in a region of space. My question is if quantum fluctuations give back what they got from nothing using Heisenberg's uncertainty principle $\Delta Ε \cdot \Delta t \geq \frac{h}{2}$, how do they result in a sum of energy $> 0$?
An answer that I came up with, though don't know if correct is: if you freeze time then you will catch quantum fluctuations in the in-between phase when they have not returned their energy back. And if you add all those in a region of space such as a cubic then the sum ends up being $10^{113}\text{ J/m}^3$ although the observed cosmological constant is $1.5 \cdot 10^{-9}\text{ J/m}^3$, but that's the cosmological constant problem a completely different topic.
Also when the 2 particles remerge don't they emit photons? If so photons have energy $E=hf$. But if quantum fluctuations emit photons in the end and photons have energy then how is the energy given back?
Don't be afraid to include math to your answer especially if math makes your answer more correct and complete.


text:
Q: How to deploy sensenet website in sub folder I set default site's URL in edit default site page, add an URL localhost/cms in URL list, when click save button, there is an error "Invalid site URL: 'localhost/cms'.", how to work around this error or are there any other way?

A: Currently this is not possible, mainly because of the virtualization technique sensenet uses. It basically takes over the url and serves everything from the db. Maybe there is some kind of url rewriting trick that operators can do, but I don't know of a working example.
So you have to deploy sensenet to an application root, it cannot live in a virtual directory or subfolder.


text:
Q: C++: Pointer value changed exiting a function I need to wrap a string vector from an unmanaged C++ library, and to do so I have to convert a vector<string> to a char***. For this conversion, I'm using a function. However, even if it seems right inside it, once out pointer values changed to be invalid.
Here is a simple example of it:
int main() {
    cout << "Start of the program" << endl;

    vector<string> vStr = vector<string>();
    vStr.push_back("ABC");
    vStr.push_back("DEF");
    vStr.push_back("GHI");
    vStr.push_back("JKL");
    vStr.push_back("MNO");
    vStr.push_back("PQR");

    char*** pStr = new char**();
    int* pLength = new int();

    cout << " > before export" << endl;

    exportVector(vStr, pStr, pLength);

    cout << " < after export" << endl;

    cout << "\t pLength value = " << *pLength << endl;

    for (unsigned int i = 0 ; i < vStr.size(); i++)
    {
        cout <<"\t pStr "<< i << ": " << vStr[i] << " to ";
        for(unsigned int j = 0; j < 3; ++j)
        {
            cout << "-" << pStr[0][i][j];
        }
        cout << "-"<< endl;
    }

    cout << "End of the program" << endl;

    delete pStr;
    delete pLength;

    return 0;
}

void exportVector(vector<string> vect, char*** pData, int* pSize)
{
    vector<char*> charVect = vector<char*>(vect.size());
    //cout << "\t charVect.size() = " << charVect.size() << endl;

    // Copy and cast elements of given vector into chars
    for(unsigned int i = 0; i < vect.size() ; i++)
    {
        charVect[i] = const_cast<char*>(vect[i].c_str());
    }

    *pData = &charVect[0];
    *pSize = vect.size();

    cout << "\t pSize = " << *pSize << endl;
    for (unsigned int i = 0 ; i < vect.size(); i++)
    {
        cout <<"\t pData "<< i << ": ";
        for(unsigned int j = 0 ; j < 3 ; ++j)
        {
            cout << "-" << pData[0][i][j];
        }
        cout << "-"<< endl;
    }
}

And I'm getting in console:
Start of the program
 > before export
     pSize = 6
     pData 0: -A-B-C-
     pData 1: -D-E-F-
     pData 2: -G-H-I-
     pData 3: -J-K-L-
     pData 4: -M-N-O-
     pData 5: -P-Q-R-
 < after export
     pLength value = 6
     pStr 0: ABC to -Ä- -i-
     pStr 1: DEF to - - -i-
     pStr 2: GHI to -G-H-I-
     pStr 3: JKL to -J-K-L-
     pStr 4: MNO to -M-N-O-
     pStr 5: PQR to -P-Q-R-
End of the program

How to explain the difference of values inside exportVector function and outside it? How to correct it?
Thanks a lot.

A: You are passing the vector by value to the exportVector function! The vector gets destructed after the function returns, and your char* pointers get orphaned, pointing to memory locations which probably are reused for other purposes afterwards...
Also, your const_cast should ring a lot of alarm bells already! Never do a const_cast (except for very rare occasions where you know it is safe to do so - and this is not one of them)!
But those things are not the only problems in your code. What do you think char*** pStr = new char**(); is doing?
What it does is that it reserves space for one pointer to a pointer to a char (usually 4-8 byte). You seem to think that somehow magically allocates space for a multitude of character arrays?

A: You need to pass your vector by reference
void exportVector(vector<string> &vect, char*** pData, int* pSize)

,also you should use strdup here:
charVect[i] = const_cast<char*>(vect[i].c_str());
//should be
charVect[i] = strdup(vect[i].c_str());

finally,
vector<char*> charVect = vector<char*>(vect.size());
*pData = &charVect[0];

will segfault cause charVect will be destroyed at the end of the function,
you need to remove those line and do something like this:
(*pData) = new char*[vect.size()];
// Copy and cast elements of given vector into chars
for(unsigned int i = 0; i < vect.size() ; i++)
{
    (*pData)[i] = strdup(vect[i].c_str());
}


text:
Q: How to return json data from endpoint within backend I am attempting to run a axios request through my front end to hit my backend, in which it will do a req.get to return a json object, this is what the axios code looks like:
import axios from 'axios';

const api = axios.create({
    baseURL: "http://localhost:5000"
});

export const stockQuote = symbol => {
    return api.get(`/stock/${symbol}`);
}

and from that it will hit my backend which looks like this:
const express = require("express");
var router = express.Router();

router.get(`/stock/:symbol`, async(req, res) => {
    const data = req.get(`https://sandbox.iexapis.com/stable/tops?token=Tsk_938206aef2a646dasdfe4ddf024b02f4&symbols=aapl`);
    console.log(data);
    res.send(data);
})

module.exports = router;

I want to work through my backend so the users cannot look at the specific api endpoints i am hitting, but for some reason the console.log(data) is returning undefined. What am i doing wrong here as im relitevly new to these features?
Edit: Here is my server.js
const express = require("express");
const app = express();
const cors = require("cors");
// const pool = require("./db");
const PORT = 5000;

//Parser for JSON objects passed through server
app.use(cors());
app.use(express.json());

var iex = require('./routes/iex');

app.listen(PORT, () => {
  console.log(`Backend listening at http://localhost:${PORT}`)
})

app.get(`/stock/:symbol`, iex);

A: install body parser in your backed and access data like:
const data = req.body
and then
console.log(data);


text:
Q: How to change permissions to mysql pid file By default mysql creates pid file as -rw-rw---- mysql:mysql mysql.pid. Is there any way to change those permissions? I need o+r for monitoring purposes.
Of course I could add sticky bit for directory above and change group ownership but if it could be changed somewhere in settings it would be the cleanest solution.
I'm running mysql 5.5 if that matters.

A: There's no need. You can check the existence of the file without changing the permissions:
if [ -f /var/run/mysqld/mysqld.pid ]; then     echo "mysqld running"; fi

If that's not good enough you can check the pid (i.e. the contents of the file) directly:
ps -U mysql | grep mysqld | cut -f1 -d' '


text:
Q: split a string with multiple alphabets and letters - android Very new to android java and I have a simple question. I have string for example like this :
P:38,AS:31,DT:231,AR:21

I want to split this into 4 different lists in the form :
P(list)  = 38
AS(list) = 31
DT(list) = 231
AR(list) = 21

I tried split but it didnt get the job done ...

A: As long as the keys are always letters and the values are always integers, you can use regular expressions to parse these strings:
Hashtable<String, int[]> result = new Hashtable<String, int[]>();
Pattern pattern = Pattern.compile("([A-Z]+):(\\d+(?:,\\d+)*)");
Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
    String key = matcher.group(1);
    String[] fields = matcher.group(2).split(",");

    int[] values = new int[fields.length];
    for (int i=0; i<values.length; i++)
        values[i] = Integer.parseInt(fields[i]);

    result.put(key, values);
}

Edit
"([A-Z]+):(\\d+(?:,\\d+)*)" is a regular expression that matches at least one uppercase letter ([A-Z]+) followed by a colon (:) followed by one more numbers separated by commas (\\d+(?:,\\d+)*). A single number is composed of one more digits (\\d+). The additional parentheses allow us to later access the individual parts of the input string using the group(int) method calls.
The java.util.regex.Matcher class allows us to iterate through the individual parts of the input string that match our regular expression. The find() method returns true as long as there is another substring in our input string that matches the regular expression. So with the input string "P:38,45,AS:31,DT:231,345,678,AR:21" the while loop would execute four times and the matcher variable would point to the following four substrings of the input string:

*

*P:38,45

*AS:31

*DT:231,345,678

*AR:21
We can then use the matcher's group(int) method to access the individual parts of each substring. matcher.group(1) accesses the text that was captured by the first parentheses of our regular expression (([A-Z]+)) which corresponds to "P", "AS", "DT", and "AR" in the individual loop iterations. Analogously, matcher.group(2) corresponds to the second parentheses of the regular expression ((\\d+(?:,\\d+)*)) which would return "38,45", "31", "231,345,678", and "21". So in the first iteration of the while loop key would hold "P" and fields would hold an array of strings ["38", "45"]. We can then parse the fields into actual integer values using Integer.parseInt(String) and store the key and the values in a Hashtable so that we can later retrieve the values for the individual keys. For example, result.get("DT") would return an array of integers with the values [231, 345, 678].

A: As @pobybolek said, you can use his method which he wrote to take the string and convert it into a hashtable, which uses the key and then the int values after it. The int values are stored in an array and the key is a string.
                        String input = master_string;
                        Hashtable<String, int[]> result = new Hashtable<String, int[]>();
                        Pattern pattern = Pattern.compile("([A-Z]+):(\\d+(?:,\\d+)*)");
                        Matcher matcher = pattern.matcher(input);

                        while (matcher.find())
                        {
                            String key = matcher.group(1);
                            String[] fields = matcher.group(2).split(",");

                            int[] values = new int[fields.length];
                            for (int pqr=0; pqr<values.length; pqr++)
                            {
                                values[pqr] = Integer.parseInt(fields[pqr]);
                                // values[pqr] = fields[pqr];
                            }
                            result.put(key, values);
                        }

the above code splits the given string into its keys and the values after the key into an integer array, this can also be changed into a String key, String[] array as seen in the second line of my code.


text:
Q: Query post types based on timestamp So I have a method where I'm setting a value in the database as a timestamp, so this property:
'azure_picture_expiration' => $profile->set_azure_picture_expiration(strtotime('+7 days')),

Sets the following timestamp for example 1605047781, which is GMT: Tuesday, November 10, 2020 10:36:21 PM (So 7 days from today).
What I'm attempting to achieve:
I have the following WP_Query that queries through my profile post type, and looks for all the azure_picture_expiration and azure_picture_big_expiration values.
How could I query through and pull in all profiles that will expire in 2 days? Is it possible to query through and pull profiles that will expire within 2 days?
Here is my query:
$profiles = Profile::get([
    'post_status' => [
        'publish', 'draft', 'pending', 'private'
    ],
    'posts_per_page' => 4,
    'meta_query' => [
        'relation' => 'OR',
        [
            'key' => 'azure_picture_expiration',
            'value' => '',
            'compare' => '',
        ],
        [
            'key' => 'azure_picture_big_expiration',
            'value' => '',
            'compare' => '',
        ],
    ],
]);

All help would be appreciated, I don't have the compare filled in, because I wasn't sure how to determine the time.

A: This seemed to work, please let me know if you have a better method:
$profiles = Profile::get([
    'post_status' => [
        'publish', 'draft', 'pending', 'private'
    ],
    'posts_per_page' => -1,
    'meta_query' => [
        'relation' => 'OR',
        [
            'key' => 'azure_picture_expiration',
            'value' => strtotime('+2 days'),
            'compare' => '<=',
        ],
        [
            'key' => 'azure_picture_big_expiration',
            'value' => strtotime('+2 days'),
            'compare' => '<=',
        ],
    ],
]);


text:
Q: Regexp: Identify a string with Name Sourname Hello I have written a regular expression for swapping a name and sourname:
find \"([A-Z][a-z]+)\s([A-Z][a-z]+)\" replace "\2 \1"

However I have now discovered that I should not swap everything I find inside brackets but only particoular candidate names such as:

*

*John Doe

*Jayne Eyre

For example if I find Jayne Doe it should not be swapped (so \"(Eyre|Doe)\s(John|Jayne)\" is excluded from the possible solutions).
Any advice. Thanks?

A: Assuming the number of names to be switched is fairly small, this might work for you:
(?: (?John)\s(?Doe) | (?Jayne)\s(?Eyre) | (?\w+)\s(?\w+) )

I have included white space for readability; be sure to take it out or use the regex option that ignores it. I used Expresso, so the regexes are in the .Net syntax, but I think you can tweak it as needed.
The replacement regex is:
${B} ${A}

The regex has 3 alternatives; 2 (or more) for the names that we want to switch, and one for all other names that should not be switched. The name parts are defined with named capture groups (A & B) that are used by the replacement regex to do the switching. The trick is just that in the third alternative, we swap the named capture groups so that names that we do not want to switch are actually switched, but to no effect.
More complicated name variations (John C. Reilly, Olivia Newton-John) will not work, but as your original regex kept it simple, I followed suit.
Updated answer......
It seems Flex regexes do not support named groups in the replacement regex. After experimenting, I have come up with a variation of my original idea that only uses numbered capture groups and seems to work:
(John)\s(Doe)|(Jayne)\s(Eyre)|(\w+)\s(\w+)

The replacement regex is:
$2$4$5 $1$3$6

This is quite a bit more of a hack than the original, but again, if the number of names to be switched is reasonable, it might be workable. In my testing, given above regex and replacement regex and the following input:
John Doe
Jayne Eyre
Bob Smith

I got the following output:
Doe John
Eyre Jayne
Bob Smith


text:
Q: how to ignore all slicers except date slicer and get count in power BI I would like to get count of order number and I have multiple slicers which would slice down the value . for one calculation .I would need to ignore all the other slicers except date slicer and get the count of orders.could you please help.

A: If you want to ignore all the slicers, you can create a measure using the DAX function ALL. And if you want to ignore all the slicers except one, you can use ALLEXCEPT. Those two function will calculate your count based on all the values.

A: If you have a visual that only shows the count you are referring to, there is another way. You can stop slicers from interacting with the visual you want your count to appear on. So, you can select the slicer, go to Format and the click Edit Interactions and clik the circle (None interaction). Do the same for all slicers you don't want to affect the visual with your count.


text:
Q: Getting NullPointerException when connecting to Cisco WLC with JSch Since years I use JSch to connect to Cisco Switches. Today I tried to connect to a Cisco WLC the same way I did with the Switches. Nothing works!

Exception: com.jcraft.jsch.JSchException: java.lang.NullPointerException

The difference between WLC and a switch is, if you try to login with PuTTY in a WLC at first the WLC ask for a "login as:". Here you can write fooBar or nothing. After that the WLC is asking for user and password!
Here is the code I use:
java.util.Properties configuration = new java.util.Properties();

configuration.put("kex", "diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256");
configuration.put("StrictHostKeyChecking", "no");

final JSch jsch = new JSch();
final Session session = jsch.getSession(TELNET_USER, outletWLC.getIp(),22);

session.setPassword(TELNET_PASSWORD);
session.setConfig(configuration);
session.connect();      // Here I get the Exception!
if (!session.isConnected()) {
   throw new RuntimeException("cannot connect session");
}

final ChannelShell channelShell = (ChannelShell) session.openChannel("shell");
final ByteArrayInputStream toSwitchStream =
    new ByteArrayInputStream(commandString.getBytes());

final ByteArrayOutputStream fromSwitchStream = new ByteArrayOutputStream();
final int available = toSwitchStream.available();
channelShell.setInputStream(toSwitchStream);
channelShell.setOutputStream(fromSwitchStream);

channelShell.connect();

Is there someone around who solved the problem?
com.jcraft.jsch.JSchException: java.lang.NullPointerException
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:544)
    at com.jcraft.jsch.Session.connect(Session.java:291)
    at com.jcraft.jsch.Session.connect(Session.java:154)
    at de.mediamarkt.indira.server.services.MSVorfPasswServiceImpl.readWLC(MSVorfPasswServiceImpl.java:169)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at de.mediamarkt.indira.server.remote.IndiraProxyServlet.service(IndiraProxyServlet.java:93)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1097)
    at de.mediamarkt.indira.server.filter.IndiraMultiPersistenceUnitTransactionFilter.doFilter(IndiraMultiPersistenceUnitTransactionFilter.java:23)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1088)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:360)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
    at org.mortbay.jetty.handler.HandlerList.handle(HandlerList.java:49)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:324)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
    at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: java.lang.NullPointerException
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:540)
    ... 26 more

JSch log:
INFO: Connecting to 10.3.xxx.xxx port 22
INFO: Connection established
INFO: Remote version string: SSH-2.0-CISCO_WLC
INFO: Local version string: SSH-2.0-JSCH-0.1.44
INFO: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
INFO: aes256-ctr is not available.
INFO: aes192-ctr is not available.
INFO: aes256-cbc is not available.
INFO: aes192-cbc is not available.
INFO: arcfour256 is not available.
INFO: SSH_MSG_KEXINIT sent
INFO: SSH_MSG_KEXINIT received
INFO: kex: server->client aes128-ctr hmac-sha1 none
INFO: kex: client->server aes128-ctr hmac-sha1 none
INFO: Disconnecting from 10.3.xxx.xxx port 22

A: now I found the hidden place where my inherited project loads the wrong Version of JSch.
I fixed it and suprise, suprise, it works!! Many, many thanks to Martin for the support!
INFO: Connecting to 10.3.xxx.xxx port 22
INFO: Connection established
INFO: Remote version string: SSH-2.0-CISCO_WLC
INFO: Local version string: SSH-2.0-JSCH-0.1.54
INFO: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
INFO: aes256-ctr is not available.
INFO: aes192-ctr is not available.
INFO: aes256-cbc is not available.
INFO: aes192-cbc is not available.
INFO: CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
INFO: CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
INFO: SSH_MSG_KEXINIT sent
INFO: SSH_MSG_KEXINIT received
INFO: kex: server: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
INFO: kex: server: ssh-rsa,rsa-sha2-512,rsa-sha2-256
INFO: kex: server: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
INFO: kex: server: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
INFO: kex: server: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
INFO: kex: server: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
INFO: kex: server: none,zlib@openssh.com,zlib
INFO: kex: server: none,zlib@openssh.com,zlib
INFO: kex: server:
INFO: kex: server:
INFO: kex: client: diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256
INFO: kex: client: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
INFO: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc
INFO: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc
INFO: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
INFO: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
INFO: kex: client: none
INFO: kex: client: none
INFO: kex: client:
INFO: kex: client:
INFO: kex: server->client aes128-ctr hmac-sha1 none
INFO: kex: client->server aes128-ctr hmac-sha1 none
INFO: SSH_MSG_KEXDH_INIT sent
INFO: expecting SSH_MSG_KEXDH_REPLY
INFO: ssh_rsa_verify: signature true
WARN: Permanently added '10.3.xxx.xxx' (RSA) to the list of known hosts.
INFO: SSH_MSG_NEWKEYS sent
INFO: SSH_MSG_NEWKEYS received
INFO: SSH_MSG_SERVICE_REQUEST sent
INFO: SSH_MSG_SERVICE_ACCEPT received


text:
Q: Can bluetooth trigger a certain action in an app? I am planning to start an ios application and was wondering if there is a way to trigger certain action such as finding location using google map on bluetooth connection (or disconnection)?
I know an apple map application has similar feature where it shows where your car is parked. Any references would be appreiciate.
Thanks.

A: You can try this in your viewController where you want to check:
var manager: CBCentralManager!

 override func viewDidLoad(){
     super.viewDidLoad()
     manager = CBCentralManager()
     manager.delegate = self
 }

//CBCentralManager Delegate method

func centralManagerDidUpdateState(_ central: CBCentralManager) {

  switch central.state {
       case .poweredOn:
           //poweredOn
       case .resetting:
           //resetting
       case .unauthorized:
           //unauthorized
       case .unknown:
           //unknown
       case .unsupported:
           //UnSupported
       case .poweredOff:
          //Bluetooth is not Connected.Please Enable it
  }

the status in delegate will tell you what's the status of your Bluetooth.
Hope it helps!

A: Well there delegate methods which get fired after different states of connection. The best way I suggest you to do is implement the following delegate methods.
func centralManager(_ central: CBCentralManager,
                  didConnect peripheral: CBPeripheral) {

}

func centralManager(_ central: CBCentralManager,
     didDisconnectPeripheral peripheral: CBPeripheral,
                       error: Error?) {
}

And call a function to get your location in these cases. Additionally there are other delegate methods such as
func centralManagerDidUpdateState(_ central: CBCentralManager) {
    }
func centralManager(_ central: CBCentralManager,
            didFailToConnect peripheral: CBPeripheral,
                       error: Error?) {
}

But these cases does not cover the all the cases of connection and disconnection. But depending on your requirement you can implement either one. These are CBCentralManagerDelegate delegates.
CBCentralManager
CBCentralManagerDelegate


text:
Q: Sass Placeholders from Mixins I want to create Sass placeholders on the fly using arbitrary values passed from a style block:
@mixin example-mixin($arg) {
    %placeholder-#{$arg} {
        property: $arg;
    }
    @extend %placeholder-#{$arg};
}

Calling the mixin:
.classname {
    @include example-mixin('value');
}

This almost works, but for some reason in the CSS output the .classname is given twice as though it's a descendant selector:
.classname .classname {
    property: value;
}

I'm not seeing the logic behind the duplicate class names - can anyone see what I'm doing wrong and/or suggest a workaround?

A: Let's look at what happens if you use real classes instead of extend classes
.a {
    .b {
        color: blue;
    }

    @extend .b;
}

Output:
.a .b, .a .a {
  color: blue;
}

The only reason I could imagine you wanting to do this is so you can use the extend class for purposes of extending instead of .classname like so:
.c {
    @extend .b;
}

You'll see that the output probably isn't what you want at all:
.a .b, .a .a, .a .c {
  color: blue;
}

The .a .a doesn't make a whole lot of sense to me either, but it's harmless.  What you're actually wanting to do is something like this:
%placeholder-name, .classname {
    property: name;
}

.foo {
    @extend %placeholder-name;
}

And the output will be like this:
.foo, .classname {
  property: name;
}


text:
Q: Google Universal Analytics Enhanced Link Atrribution I'm using UA on our company's in-house software to help understand how our users use it, and part of that is learning what they click when they click and so on.
Enhanced Link Attribution seems to be the best choice for this, but per the Developer Docs:

Tag your page for enhanced link attribution
In order to implement this additional tagging for enhanced link
  attribution, you have to use the asynchronous version of the Analytics
  tracking code.

The problem I'm seeing is that currently, I'm using Universal Analytics which uses analytics.js whereas the Asynchronous version of GA uses ga.js. So now I'm confused because the option is available in my property settings in the Admin section in our GA account.
Univeral Analytics
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-CODE-HERE', 'SITE_URL');
    ga('send', 'pageview');

  </script>

Asynchronous Code
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

Since the two versions of GA are not compatible, can I still use Enhanced Link Attribution? If so, what steps would I take? I can't seem to find the answers in the Google Analytics docs related to ELA with UA.
Edit
Is it at all possible or advised to use both versions of Google Analytics on the same page/site/property? Assuming I set up another GA property for the standard version and use both JS snippets on the site?

A: To answer the original question:
No, enhanced link attribution is not yet supported by Universal Analytics. Though this and many other features will be rolled out soon enough. Universal Analytics is still very beta, but it's been established that this is the future for google analytics.
Yes, the new code is asynchronous just like the old code, and I really couldn't imagine a situation where you would want to turn this off. Asynchronous loading in this case means that when the analytics javascript fires, your web page continues loading regardless of whether the javascript has finished loading or not. Before the asynchronous snippet update, it was best practice for the analytics code to be loaded in the footer to prevent the entire page from hanging due to the script not being asynchronous in nature. Though this was changed because on long/slow pages, the user would often interact with the website before the footer/javascript had a chance to load, and in turn caused major discrepancies in the data.
Wikipedia:

In computer programming, asynchronous events are those occurring
  independently of the main program flow. Asynchronous actions are
  actions executed in a non-blocking scheme, allowing the main program
  flow to continue processing.

I also wouldn't suggest changing the object name as Concept Rat suggests, as I believe that would only apply if you were implementing multiple "universal analytics" trackers to different web properties within the same snippet.
https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#snippet:

Renaming the Global Object
In some cases the ga variable name might already be used by an
  existing object on your page. To avoid overriding your existing
  object, you can rename the ga function, for example to __gaTracker. To
  do this, simply replace the ga parameter in the snippet above:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new
  Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','__gaTracker');
Then you can use __gaTracker instead of ga when calling commands:
__gaTracker('create', 'UA-XXXX-Y');
  __gaTracker('send', 'pageview');

If renaming the variable were necessary to load both snippets, I don't believe Google would say this:
https://developers.google.com/analytics/devguides/collection/analyticsjs/:

The analytics.js snippet is part of Universal Analytics, which is
  currently in public beta. New users should use analytics.js. Existing
  ga.js users should create a new web property for analytics.js and dual
  tag their site. It is perfectly safe to include both ga.js and
  analytics.js snippets on the same page.

Also please note, if you want to try out universal analytics you should run it concurrently with your existing implementation, as they should eventually release a migration tool to remain backwards compatible allowing you to keep your existing data. To be perfectly clear:
You should only fully implement universal analytics if you're are creating a brand new account with no existing data in place.

A: I've been researching this same problem. As of November 2012, Google said the following in response to a support question: "In-Page Analytics support for analytics.js is not yet implemented. This is one of the features we'll be working on and introducing later in the beta. Other features not currently supported include Remarketing and AdSense reporting." As you know, Enhanced Link Attribution is a feature of In-Page Analytics.
I have not found any new references to this issue since that post, so I can only assume they Universal Analytics is still not ready for prime time. If you can, I would try using Asynchronous Code until Universal Analytics is working properly.

A: FYI:  Universal Analytics is out of Beta testing and Enhanced Link Attribution is now supported:
https://support.google.com/analytics/answer/2558867?hl=en

A: For your reference the Universal Analytics is, or does support, asyncronous mode.  You can see it in the Universal JS code third line down under the "script" tag "a.async=1;".
You can also run both the standard GA code and Universal at the same time.  Just setup a separate property for the Universal code and make sure to change the object name "ga" that you see on the fourth line "//www.google-analytics.com/analytics.js','ga')" to say "gau" (just has to be unique on the page for scripts).  Then use "gau(" instead of "ga(" for setting things, etc.  Remember this is just for the Universal code not the standard GA.
Once you've done this you can continue to track things using the standard GA and have the Universal GA logging underneath the new property.  Once you're happy with things you can switch to using only the Universal one.


text:
Q: How to sort LI's based on their ID Trying a bunch of solutions with no workable results. I have code that takes the value of the span and creates an ID for the LI. I then want to sort these LI's DESCENDING based on the LI's ID. Help? Thanks!
<!DOCTYPE html>

cello2987

zello1723

aello3476

A: jAndy beat me to the punch. Here's mine.
$(function() {
  $("li").sort(function(left, right) {
    return parseInt($(left).attr("id")) - parseInt($(right).attr("id"));
  }).each(function() { $("ul").append($(this)); });
});

I'll add that you need
$(function() {

for your IE6 users because IE6 will crash if you try to remove elements from the dom before their parent elements load.
Also, .remove() is redundant because .append() takes care of that.

A: Let's assume your li nodes had ids.

blub

blaaah

hmmmm

one more

Then you could just call javascripts native array .sort() method, since jQuery wrapped sets are hold in Arrays:
$(function(){
    var elems = $('#test').children('li').remove();
    elems.sort(function(a,b){
        return parseInt(a.id) > parseInt(b.id);
    });
    $('#test').append(elems);
});

Working example: http://www.jsfiddle.net/3uYUq/


text:
Q: Scrollbar track thinner than thumb I am trying to style a scrollbar using CSS. I want to achieve the following look (ignore the background):

In other words, I want the thumb to be thicker than the track, which I only want to be a line.
I have researched this and found solutions for people wanting to do the opposite. That is a thumb smaller than the track, but no way of achieving what I want.
As an alternative option, I have thought of using the border-right property with negative offset, but again no luck. The only outline has offset and outline four-sided.
Any suggestions will be appreciated.

A: ::-webkit-scrollbar-track{background-image:url("https://i.imgur.com/s19YkhR.png");background-position:center}
::-webkit-scrollbar-track:horizontal{background-repeat:repeat-x}
::-webkit-scrollbar-track:vertical{background-repeat:repeat-y}

This solution is based on @Nizar's approach but works for both Horizontal and Vertical scrollbars using 1 image.
The image is a 2x2 which is reduced from a 8x2 from Nizar's approach.
This utilizes :horizontal and :vertical selectors. But do note there may be browser incompatibility i'm unsure.
The image can be any size, 2x2, 1x1, e.t.c it essentially defines the size of the line. A 2x2 will just be a 2 pixel depth line.

A: Here is nearly matching code with css. You just have to change the color or add image in  ::-webkit-scrollbar-thumb try small image if you want and you may also need to adjust the position.

 .container {
      margin: 40px auto;
      width: 1000px;
      height: 200px;
      overflow-y: scroll;
    }
    .container::-webkit-scrollbar {
      width: 20px;
    }
    .container::-webkit-scrollbar-track {
      background: tomato;
      border-left: 9px solid white;
      border-right: 9px solid white;
    }
    ::-webkit-scrollbar-thumb {
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);

         /*background-image:url( http://i.imgur.com/ygGobeC.png);*/
    }
    .container .item {
      height: 20px;
      margin-bottom: 5px;
      background: silver;
    }
    .container .item:last-child {
      margin-bottom: 0;
    }
    .container {
        direction:rtl;
      }

A: Pure css solution

    .item-container::-webkit-scrollbar {
         background-image: linear-gradient(to right,white 50%, grey 50%,white 51%);
    }

    .item-container::-webkit-scrollbar-thumb {
        background-color: grey;
        border-radius: 10px;
    }

    .item-container{
      overflow: auto;
      height: 200px;
      width: 200px;
    }

    .item-container div{
      height: 100px;
    }

item

item

item

item

item

item

item

item

item

item

item

item

item

A: A css-only solution that does not use any images involves using the scrollbar borders to produce the desired effect. The trick is to match the scrollbar element's border colors to your container's background color. However, this won't work on complex backgrounds, like the OP's.
Example: https://jsfiddle.net/vsj6qb8c/6/
body {
  --container-background-color: #C7C7C7;
}

.outer {
    height: 150px;
    overflow-y: scroll;
  background-color: var(--container-background-color);
}

.force-overflow {
    min-height: 450px;
}

::-webkit-scrollbar {
    width: 20px;
  border-width: 5px;
}

::-webkit-scrollbar-track-piece {
    background-color: #757575;
  border-color: var(--container-background-color);
  border-width: 2px 9px 2px 9px;
  border-style: solid;
}

::-webkit-scrollbar-thumb {
    border-radius: 7px;
    background-color: #51545E;
  border-color: var(--container-background-color);
  border-style: solid;
  border-width: 1px 7px 1px 7px;
}

A: Simple CSS solution to show handle thicker than track. It works fine in Chrome only.
It may help for someone who needs this.
/* To set scrollbar width */
::-webkit-scrollbar {
  width: 5px;
}

/* Track */
::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 9px;
  border: 2px solid white;  /* Use your background color instead of White */
  background-clip: content-box;
}

/* Handle */
::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 9px;
}

/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
  background: #555;
}

A: I believe I found an answer. I had the same issue today; I was tempted to use Javascript. I am that CSS type of guy though...
If you wish to know what each part of the scrollbar associates to which part of the css; then you might first of all want to check the CSS Tricks post for Custom Scrollbars. (That helped me a lot)
The trick here is to give the scrollbar the same width as your "thumb".
Then you will want to give the "track" a transparent background, with a background image. Repeat the background image vertically, and you'll have yourself a good looking scroll bar.
To demonstrate that, I have this image that is 8 pixels wide and 1 pixel tall.
Only the middle 2 pixels are colored blue. You can find the image here.

Please note that the image is 8 pixels because in my css, the scrollbar is 8 pixels wide.

Now the CSS needs to come into play. So we're gonna do the following.
::-webkit-scrollbar,
::-webkit-scrollbar-thumb,
::-webkit-scrollbar-track {
    width: 8px;
    border: none;
    background: transparent;
}

::-webkit-scrollbar-button,
::-webkit-scrollbar-track-piece,
::-webkit-scrollbar-corner,
::-webkit-resizer {
    display: none;
}

::-webkit-scrollbar-thumb {
    border-radius: 6px;
    background-color: #1A5FAC;
}

::-webkit-scrollbar-track {
    background-image: url("https://i.imgur.com/GvV1R30.png");
    background-repeat: repeat-y;
    background-size: contain;
}

To help with demonstration, I arranged a small snippet. Note that I restricted the scrollbar to divs and for that, you'll only need to remove the div before every ::. ( ^ Or just use the CSS above ^ )

::-webkit-scrollbar,
::-webkit-scrollbar-thumb,
::-webkit-scrollbar-track {
    width: 8px;
    border: none;
    background: transparent;
}

::-webkit-scrollbar-button,
::-webkit-scrollbar-track-piece,
::-webkit-scrollbar-corner,
::-webkit-resizer {
    display: none;
}

::-webkit-scrollbar-thumb {
    border-radius: 6px;
    background-color: #1A5FAC;
}

::-webkit-scrollbar-track {
    background-image: url("https://i.imgur.com/GvV1R30.png");
    background-repeat: repeat-y;
    background-size: contain;
}

/* CUSTOM STYLING HERE - IGNORE */

div {
    width: 500px;
    height: 160px;
    margin: auto auto;
    overflow-x: hidden;
    overflow-y: auto;
}

hr {
    width: 450px;
    height: 160px;
    border: none;
    margin: 0 auto;
    background-color: #FFFFFF;
}
  hr:nth-of-type(1) { background-color: #5BC0EB; }
  hr:nth-of-type(2) { background-color: #FDE74C; }
  hr:nth-of-type(3) { background-color: #9BC53D; }
  hr:nth-of-type(4) { background-color: #E55934; }
  hr:nth-of-type(5) { background-color: #FA7921; }

A: I know it's an old thread, but I had same issue and since my background isn't solid color and scrollbar is to be used on multiple pages with different backgrounds I needed another solution. And I figured it out.
.scrollbar::-webkit-scrollbar {
  width: 7px; //Needed scrollbar thumb width to be 7px, so had to define whole scrollbar to be 7px wide.
};

.scrollbar::-webkit-scrollbar-thumb {
  background: brown;
};

.scrollbar::-webkit-scrollbar-track {
  background: black;
  border-left: 3px solid transparent;
  border-right: 3px solid transparent;
  background-clip: padding-box;
};

The trick is hidden in the "background-clip" part. Background-clip lets you define how much background is going to extend, and with padding-box it will let background extend up to border and not let it go under, so when you use transparent border, you're not getting the background color that is defined, but parent element background.
Hope this helps someone!

A: There are 7 different scrollbar options to use:
::-webkit-scrollbar {/ * 1 - scrollbar * /}
::-webkit-scrollbar-button {/ * 2 - button * /}
::-webkit-scrollbar-track {/ * 3 - track * /}
::-webkit-scrollbar-track-piece {/ * 4 - the visible part of the track */}
::-webkit-scrollbar-thumb {/ * 5 - slider * /}
::-webkit-scrollbar-corner {/ * 6 - corner * /}
::-webkit-resizer {/ * 7 - resizing * /}

For what you're trying to achieve, you can do this:
::-webkit-scrollbar {
    width: 12px;
}

::-webkit-scrollbar-track {
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);
    border-radius: 10px;
}


text:
Q: Sum consecutive numbers in a String of integers I need to write a function when given a String of integers, it returns a String of integers where all consecutive integers are replaced with the sum of those integers.
For example:
When given: String = "144404331" the function returns "40461". You might think it would be "1120461" however we need to continue the process until there are no consecutive digits.
My solution to this is extremely long and was wondering if anyone had a recursive / intuitive solution that could be completed in a reasonable amount of time.
Method header:
String consecutiveSum(String number) {}

A: Yes, you can use recursive solution e.g. (c# code):
    private static string consecutiveSum(string text)
    {
        StringBuilder sb = new StringBuilder(text.Length);

        bool wantRecursiveCall = false;
        char prior = '\0';
        int sum = -1;

        foreach (var c in text)
        {
            if (c != prior)
            {
                if (sum >= 0)
                    sb.Append(sum);

                sum = 0;
            }
            else
                wantRecursiveCall = true;

            sum += c - '0';
            prior = c;
        }

        sb.Append(sum);

        return wantRecursiveCall ? consecutiveSum(sb.ToString()) : sb.ToString();
    }


text:
Q: How to extract tables from a pdf with PDFMiner? I am trying to extract information from some tables in a pdf document. Consider the input:
Title 1
some text some text some text some text some text
some text some text some text some text some text

Table Title
| Col1          | Col2    | Col3    |
|---------------|---------|---------|
| val11         | val12   | val13   |
| val21         | val22   | val23   |
| val31         | val32   | val33   |

Title 2
some more text some more text some more text some more text
some more text
some more text some more text some more text some more text

I can get the outlines/titles as such:
path='myFile.pdf'
# Open a PDF file.
fp = open(path, 'rb')
# Create a PDF parser object associated with the file object.
parser = PDFParser(fp)
# Create a PDF document object that stores the document structure.
# Supply the password for initialization.
document = PDFDocument(parser, '')
outlines = document.get_outlines()
for (level,title,dest,a,se) in outlines:
    print (level, title)

This gives me:
(1, u'Title 1')
(2, u'Table Title')
(1, u'Title 2')

Which is perfect, as the levels are aligned with the text hierarchy. Now I can extract the text as follows:
if not document.is_extractable:
    raise PDFTextExtractionNotAllowed
# Create a PDF resource manager object that stores shared resources.
rsrcmgr = PDFResourceManager()
# Create a PDF device object.
laparams = LAParams()
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Process each page contained in the document.
text_from_pdf = open('textFromPdf.txt','w')
for page in PDFPage.create_pages(document):
    interpreter.process_page(page)
    layout = device.get_result()
    for element in layout:
        if isinstance(element, LTTextBox):
            text_from_pdf.write(''.join([i if ord(i) < 128 else ' '
                                            for i in element.get_text()]))

Which gives me:
Title 1
some text some text some text some text some text some text some text
some text some text some text some text some text some text some text
Table Title
Col1
val11
val12
val13
Col2
val21
val22
val23
Col3
val31
val32
val33
Title 2
some more text some more text some more text some more text
some more text
some more text some more text some more text some more text

Which is a bit weird as the table is extracted in a column-wise fashion. Would it be possible for me to get the table row by row? Moreover, how can I identify where a table begins and ends?

A: If you only want to extract tables from PDF documents, then look at this answer: How to extract table as text from the PDF using Python?
From that answer, I have tried tabula-py which worked for me with tables of figures spread over multi-page PDF. tabula-py skipped properly all the headers and footers. Previously I had tried PDFMiner on this same type of document, and I had the same problem you mentioned, and sometimes even worse.

A: Use camelot for extracting tables from pdfs


text:
Q: UITextField data isn't uploading to firebase I'm wanting this activity of my app to get what is entered into the UItextfield and save it to Firebase.
Xcode is showing no errors when I run my app but the text isn't uploading to firebase
import UIKit
import Firebase

class Admin_events: UIViewController {

@IBOutlet weak var event_text: UITextField!

var ref : DatabaseReference!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    ref=Database.database().reference()
}
@IBAction func sendtofirebase(_ sender: Any) {
    let event = event_text.text
ref?.child("Events").setValue(event)
    NSLog("Uploading...")
}
}

A: didReceiveMemoryWarning is only called when the system is running low on memory. Under most common circumstances, this won't even be called at all, meaning your ref property will remain nil.
Try setting the property somewhere else. viewDidLoad is called very early on (and only once) during the view controller's lifecycle, so it's a good place to do this type of setup.
import UIKit
import Firebase

class Admin_events: UIViewController {

    @IBOutlet weak var event_text: UITextField!

    var ref : DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        // One-time setup is commonly done here.
        // This is a good time to create your database reference.

        ref = Database.database().reference()
    }

    @IBAction func sendtofirebase(_ sender: Any) {
        let event = event_text.text
        ref?.child("Events").setValue(event)
        NSLog("Uploading...")
    }
}


text:
Q: Inline javascript not working with WebView I have this html content stored in my strings.xml
<string name="html">
            <![CDATA[

Hello

            ]]></string>

This should change the div with id content to "Changed" and it works fine if you try it in a browser. Problem is tho, it does not work in a WebView even if we have setJavascriptEnabled(true)
Here is my activity:
...
WebView view = (WebView) findViewById(R.id.web_webView1);
        WebSettings settings = view.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setPluginsEnabled(true);
        settings.setDomStorageEnabled(true);

  view.loadData(getString(R.string.html), "text/html", "utf-8");
...

I have no idea why its not working? Any clue? :)

A: I had a similar issue with HTML that had inline javascript not working in a WebView loaded via loadData with the console error kept saying:
SyntaxError: Unexpected Identifier

Turns out the problem was with my inline javascript syntax being too loose, you must be strict with your end-of-line markers, ;.
For example, this is broken:

Where as THIS works:

Notice the addition of 2 semi-colons, both are required to fix the syntax error.

A: I see that you are loading the html using view.loadData(), did you know you can pass javascript to loadUrl() and it will execute directly? Also, have you checked to make sure the string is arriving in that method exactly as you want it?
Is it doing anything at all in your current approach? I would suggest starting with a simpler string and see if it does what you expect. loadData() is a little weird about executing javascript. Somethings that work from within other browsers just don't work with webview via loadData().


text:
Q: Shell commands as root I was trying to execute Runtime.getRuntime().exec("taskkill /PID ... /F");, but I keep getting permission denied on error stream. I know it normally requires opening cmd as root, but I was wondering if there's a way to achieve that with code (something in Windows like adding sudo in the beginning).

A: I'd suggest you to use the runas functionality in Windows.

Runas allows a user to run specific tools and programs with different
permissions than the user's current logon provides.

Please try something like:
Runtime.getRuntime().exec("cmd /c \"runas /savecred /user:theDomain\\administrator yourCommand\"")

Runas Documentation

A: You can open CMD with administrator privileges and run your Java program with Administrator privileges too. When invoking to shell it should inherit those permissions and be able to exec with Administrator privileges.


text:
Q: python, lxml or etree to get a parent of a node containing some text how can i proceed to get the parent node of a node containing a piece of text?
moreover can i use some regexp mecanism as the matched element for searching/filtering, below searching from re.compile("th[ei]s? .ne") for example?
say this one
html = '''
<title></title>

1a	2a	3a	4a	5a	6a

1b	2b	3b	4b	5b	6b

1c	2c	3c	4c	5c	6c this one

1A	2A	3A	4A	5A	6A

1B	2B	3B	4B	5B	6B

1C	2C	3C	4C	5C	6C

this one

'''

i would like to have an iterator that return:
6c this one

and then:

1A	2A	3A	4A	5A	6A

1B	2B	3B	4B	5B	6B

1C	2C	3C	4C	5C	6C

this one

i tried:
import lxml.html
root = lxml.html.document_fromstring(html)
root.xpath("//text()[contains(., one)]")

and
import xml.etree.ElementTree as ET
for e in ET.fromstring(html).getiterator():
    if e.text and e.text.find('one') != -1:
        print "Found string %r, element = %r" % (e.text, e)

but the best i can have is the node containing this one itself... while i am looking for the parent containing this text. notice that div or table are only for example, i really need to go backward to the parent after finding "this one" rather than filtering xml element containing this one because i will not know that this is a div, a table or anything before finding what it contains.
(notice also that it is html and not well formated xml, as i suppose que the second this one should have been wrapped in a xml tag)
EDIT:
>>> root.xpath("//*[contains(child::*/text(), 'one')]") # why empty parent?
[]
>>> root.xpath("//*[contains(text(), 'one')]") # i expected to have a list with two elements td and div
[<Element td at 0x280b600>]
>>> root.xpath("//*[child::*[contains(text(), 'one')]]") # if parent: expected tr and div, if not parent expected table or div, still missing one
[<Element tr at 0x2821f30>]

BTW, using the last is ok:
import xml.etree.ElementTree as ET
import lxml.html
#[... here add html = """...]
root = lxml.html.document_fromstring(html)
for i, x in enumerate(root.xpath("//text()[contains(., 'one')]/parent::*")):
    print "%s => \n\t" % i, ET.tostring(x).replace("\n", "\n\t")

produce:
0 =>
    6c this one
1 =>

1A	2A	3A	4A	5A	6A

1B	2B	3B	4B	5B	6B

1C	2C	3C	4C	5C	6C

this one

A: Based on your example output it seems like you want to get the element which contains the specified text one. Your description says you want the parent of this node.
Based on this assumption you can get the desired nodes using the following XPath:
//*[contains(text(), 'one')]

If you really want the parent of this node, you can do
//*[child::*[contains(text(), 'one')]]

By the way, as you can see I used a predicate to get the node, so I filtered the XML nodes. In my opinion, this is the more logical and readable approach, as it basically say Give me all the nodes which fulfill the given condition rather than saying Give me the output of my condition and from this point on search for the actually desired output. But you could also do something like the following, which would better match your proposed solution:
//text()[contains(., 'one')]/parent::*

A: >>> root.xpath("//*[contains(child::*/text(), 'one')]") # why empty parent?
[]

This XPath expression selects every element for which the first grandchild text node contains 'one'. The first argument to contains() is expected to be a string, so XPath takes the first node in the result of child::*/text() and takes its string value. Since no element has a text node containing "one" as its first grandchild, the answer is an empty nodelist.
>>> root.xpath("//*[contains(text(), 'one')]")
# i expected to have a list with two elements td and div
[<Element td at 0x280b600>]

For the same reason, this XPath expression selects all elements whose first text node child contains 'one'. That's why the  is selected, but the
 isn't: the div's child text node containing 'one' is not its first child text node.
>>> root.xpath("//*[child::*[contains(text(), 'one')]]")
# if parent: expected tr and div,
# if not parent expected table or div, still missing one
[<Element tr at 0x2821f30>]

This faces the same limitation as the previous expression.
Have you tried the last solution that @dirkk proposed,
//text()[contains(., 'one')]/parent::*

That should avoid your problem with passing multiple nodes as the first argument to contains().


text:
Q: How do I make a button that plays a song whenever I press it stop the song as soon as I press it again? i have a button that when pressed, plays a mp3 file that it gets from firebase storage, the problem is that if i press the button twice the audio overlaps. how do I make the audio pause when I press the button again? i'm sorry if this question was answered before but i'm new and it's hard for me to understand if its not in my individual case.
 button2=findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    MediaPlayer player = new MediaPlayer();
                    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    player.setDataSource("https://firebasestorage.googleapis.com/v0/b/yovoicest2.appspot.com/o/songs%2FDeath.mp3?alt=media&token=925d52c3-e5a7-4b2c-a598-e83a97730a24");
                    player.prepare();
                    player.start();
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        });```

A: Define the Media Player as a Member variable and check.
MediaPlayer player = new MediaPlayer();
button2=findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(player != null && player.isPlaying()) {
            // Handle the playing like changing the button Text/Image
            player.stop();
        } else {
            // Handle the stop like changing the button Text/Image
            //Do your thing. Initialize it again with whatever file you want.
        }
    }
});


text:
Q: As you get further in difficulties will Diablo/evils change color? I'm just curious will they ever change color like in D2, I always though that was a pretty cool addition to show the difficulty, and with the graphical changes it would be kinda cool to see a blue/purple diablo in d3 so I was curious if they would ever change color in this one.

A: Unfortunately, they don't - though there's already the Phase 2 Shadow of Diablo, who's a pretty sweet black/blue coloring.


text:
Q: Does this proof need the axiom of choice? I tried to prove this statement for a non-empty set $A$

$$A ~~\text{finite or countably infinite} ~\Leftrightarrow~ \exists\varphi : \mathbb{N} \rightarrow A ~~\text{surj}.$$

The $\Rightarrow$ is pretty straight forward and does not involve my question, so I will only go over what I came up with for the other direction.
Proof  (by contradiction)  We know that there exists a surjection $\varphi : \mathbb{N} \rightarrow A$ . So for every $a \in A$ the set $\varphi^{-1} (a)$ is non-empty. Since, by assumption, $A$ is not finite,  the axiom of choice is needed to choose one element out of every $\varphi^{-1} (a)$ . Collecting those and putting them into $N \subset \mathbb{N}$ , $\varphi$ induces a bijection $N \rightarrow A$ which contradicts $A$ not being countably infinite (or finite).
Now I have 3 questions (aside from is the proof correct?)

*

*Is the usage of the axiom of choice correct?

*Is the axiom needed to get one element out of every  $\varphi^{-1} (a)$ ?

*Is there a proof of this statment that does not rely on the axiom of choice?

A: No choice is needed here.
The reason is that the natural numbers are well ordered. So every surjection from the natural numbers can be split: choose the least integer from each fiber.
Finally, by enumerating a set of natural numbers we get that every subset of the natural numbers is finite or countable. And so the result follows.


text:
Q: How to completely turn off vim's abilty to recode files? Every encodings related question I've found is about how to recode files.
However, mine is quite contrary one - is it possible to make vim not to recode files at all? (and how, if so?)
Sometimes it is writing [converted] at the status line, and always miss. However, I have my terminal set at the same encoding as edited file, so, I don't need no recoding at all.

A: Use
vim -b "myfile.type"

to edit in binary mode. You can also set
:set binary

or if you're lazy like me
:se bin

before editing a file in vim (applies to the current buffer)
:he `binary`

                     *'binary'* *'bin'* *'nobinary'* *'nobin'*
'binary' 'bin'      boolean (default off)
            local to buffer
            {not in Vi}
    This option should be set before editing a binary file.  You can also
    use the |-b| Vim argument.  When this option is switched on a few
    options will be changed (also when it already was on):
        'textwidth'  will be set to 0
        'wrapmargin' will be set to 0
        'modeline'   will be off
        'expandtab'  will be off
    Also, 'fileformat' and 'fileformats' options will not be used, the
    file is read and written like 'fileformat' was "unix" (a single <NL>
    separates lines).
    The 'fileencoding' and 'fileencodings' options will not be used, the
    file is read without conversion.

A: If you are editing binary files you want what sehe suggests, binary.
If you're editing text files, then you probably need to change fileencodings, or if the problem is that vim hasn't detected the terminal encoding correctly, encoding.


text:
Q: How to call different associated resource variables in their controllers? I am a beginner learning Ruby on Rails.  Apologies if this question is very obvious...
I have two resources:
books and book_pages
A book has several pages and I have set up the belongs_to and has_many associations within the models.  In the controller for book pages, how do I create a new book_page under this association?  I currently have:
class BookPagesController < ApplicationController
...

def new
  @book_page = BookPage.new

   end
end

...

Also, how would I need to set up the corresponding view to create a new page?

A: Generally speaking, you would need to use a code like this:
book = Book.find(book_id)
book.book_pages.create(page_number: 1, footnote: "yey")

But note that you need to have the book id somehow in your request.
I strongly advise you to stop muddling through and read the rails guides, because rails uses convention over configuration which can be very confusing if you are not up to read the documentation.

A: I encourage you to test things on rails console, it's really useful for debugging. ActiveRecord::Base models can be initialized with associations like this:
Book.create(
  title: "TITLE",
  book_pages: [
    { text: "blabllblablalblab", number: 1) },
    { text: "kasdhfkjahwkqjrgs", number: 2) }
    # ....
  ]
)

@fotanus answer is equally valid. http://api.rubyonrails.org/classes/ActiveRecord/Base.html


text:
Q: Word for the blackness of charred wood, that emphasizes it comes from charring? What is a word to describe the blackness of charred wood called with a word that emphasizes that it comes from charring?
Of course it is technically usually identical to jet-black, but is there a word which also stresses that the color actually comes from charred wood? I would like something like char-black, but this does not seem to be a correct term.

A: How about charcoal? It can be used as an adjective meaning "a dark grey colour", probably this kind of grey:

Coal-black could also work: it doesn't specifically suggest charred wood, but it definitely has connotations of burning.

A: Coal black may suggest the idea:

*

*a pure black colour.

Cambridge Dictionary


text:
Q: How can I cache WordPress Rest API Response I'm using WordPress rest API for developing my Android application. But I can not cache the response.
How can I add required headers to REST API response so that my app can save the response for offline reading?

A: You should create a new instance from WP_REST_Response to set the Cache-Control value.
<?php
register_rest_route('wp/v2', '/your_endpoint', array(
    'methods' => 'GET',
    'callback' => 'function_callback',
));

function function_callback($data) {
  $response = array(
    1,2,3,4,5,6,7,8
  );

  $result = new WP_REST_Response($response, 200);

  // Set headers.
  $result->set_headers(array('Cache-Control' => 'max-age=3600'));

  return $result;
}

Click here to get more info about directives.


text:
Q: Swift ios sometimes setNavigationBarHidden is ignored when i push to the VC I am hiding y navigation bar for a specific view by calling self.navigationController?.setNavigationBarHidden(true, animated: true) in viewDidLoad
But sometimes the navigation bar does not get hidden when I push to that VC. I have no idea whats causing this so it makes it really hard to debug. It happens once every 20 times or so..
So any ideas why self.navigationController?.setNavigationBarHidden(true, animated: true) sometimes does not work?
Worth mentioning: When I exit the VC I show the navigation bar again by:
func backBtnDidToucH() {
popViewcontroller...
self.navigationController?.setNavigationBarHidden(false, animated: true)
}

I dont do it in viewwilldissapear since the animation does not look as good as when I do it in the function above


text:
Q: Change or convert only text of label without changing their values in form This is my code below:
<form name="mainform" id="mainform" class="form_step" action="" method="post" enctype="multipart/form-data">

You are: *

Expected code:
<form name="mainform" id="mainform" class="form_step" action="" method="post" enctype="multipart/form-data">

I am: *

I just want to convert or change only "You are:" text to "I am:" text from label tags without changing their values that too with immediate effect on page loading.
Anyone plz helpme..

A: Get the anchor and the textNode will be the nextSibling :
$('#mainform label a').each(function() {
    this.nextSibling.nodeValue = this.nextSibling.nodeValue.replace('You are', 'I am');
});

FIDDLE


text:
Q: Cubic Bézier spline multiple split I have a cubic Bézier spline with four points: P1, C1, C2 and P2. I'm using De Casteljau method to split the spline to two parts at a given point x, 0 <= x <= 1.
The question is, can I use the same algorithm to split the spline twice? Say, that I want to split spline in points x1 = 0.25 and x2 = 0.75. First I split the spline S to S1 and S2 at the point 0.25. Next, I re-evaluate x2, since now it's on the segment [0.25, 1]. If I then subtract 0.25 from everything, I get 0.5 on [0, 0.75], which, scaled up to [0, 1] gives me x2'=0.(6). Then I split S2 on point x2 to get another two splines and the center one is the one I'm seeking.
Is the re-calculation of split point on the second spline valid? I mean, will 0.(6) on the second spline will match the original 0.75 on the initial one?

A: Your approach will work, but you can actually run two instances of the de Casteljau algorithm at the same time, which will save you some computations and make the construction clearer.
The best way to explain this is by using the concept of "blossoming". This was actually the technique used by de Casteljau himself, in the 1960s, though it didn't become popular until much later. Nowadays, it's easy to find descriptions on the internet.
Among other things, blossoming gives us a nice way to label the points that arise during the de Casteljau algorithm. The labels make it clear how the points are calculated as convex combinations of previous ones.
Here is the blossom diagram for a cubic curve, split into three pieces by splitting at the parameter values $a= \tfrac14$ and $b=\tfrac34$.

The original curve has control points $000, 001, 011, 111$.
The first segment has control points $000, 00a, 0aa, aaa$.
The second segment has control points $aaa, aab, abb, bbb$.
The third segment has control points $bbb, bb1, b11, 111$.
All the points in the diagram are computed as convex combinations, so ...
P_00a = (1-a)*P_000 + a*P_001
P_00b = (1-b)*P_000 + b*P_001
P_01a = (1-a)*P_001 + a*P_011
...
P_0aa = (1-a)*P_00a + a*P_01a
...

and so on.

A: You can use De Casteljau's algorithm, yes.
Let's say you wish to split $t_1$ to $t_2$ into a new cubic Bézier, with $0 \le t_1 \lt 1$ and $t_1 \lt t_2 \le 1$.
You first split at $t_1$, and keep the final point in the initial curve as the final point, last subdivision point at each subdivision step as the control point, and the point De Casteljau's algorithm ends up as the starting point.
That gives us the intermediate curve.  We split this one, noting that the split point is not $t_2$, but $(t_2 - t_1) / (1 - t_1)$, because the split point is relative to the curve at hand; and this intermediate curve starts at $t_1$ in the original curve. (For $t_1 = 1/4 = 0.25$ and $t_2 = 3/4 = 0.75$, the second split point is at $2/3 \approx 0.667$. By $0.(6)$, OP refers to $2/3$ too, so we are in agreement.)
For the resulting curve, you use the starting point from the intermediate curve, first subdivision points as the control points, and the point De Casteljau's algorithm ends up with as the final point.

There is a direct algebraic formula for the coefficients, too, but it isn't as numerically stable as De Casteljau's algorithm.  However, it can be useful in some cases.
In vector notation, a cubic Bézier curve from $\vec{p}_0$ to $\vec{p}_3$ with control points $\vec{p}_1$ and $\vec{p}_2$ for $0 \le t \le 1$ is described by the vector-valued function
$$\vec{p}(t) = (1 - t)^3 \vec{p}_0 + 3 (1 - t)^2 t \vec{p}_1 + 3 (1 - t) t^2 \vec{p}_2 + t^3 \vec{p}_3$$
Let's say you wish to extract $t_1 \le t \le t_2$ from a cubic Bézier curve into a separate curve $\vec{q}(t)$.  Calculate
$$\begin{aligned}
\vec{q}_0 &= c_{00} \vec{p}_0 + c_{01} \vec{p}_1 + c_{02} \vec{p}_2 + c_{03} \vec{p}_3 \\
\vec{q}_1 &= c_{10} \vec{p}_0 + c_{11} \vec{p}_1 + c_{12} \vec{p}_2 + c_{13} \vec{p}_3 \\
\vec{q}_2 &= c_{20} \vec{p}_0 + c_{21} \vec{p}_1 + c_{22} \vec{p}_2 + c_{23} \vec{p}_3 \\
\vec{q}_3 &= c_{30} \vec{p}_0 + c_{31} \vec{p}_1 + c_{32} \vec{p}_2 + c_{33} \vec{p}_3 \\
\end{aligned}$$
where
$$\begin{aligned}
c_{00} &= \displaystyle \frac{ -t_2^3 }{(t_1 - t_2)^3} \\
c_{01} &= \displaystyle \frac{ 3 t_1 t_2^2 }{(t_1 - t_2)^3} \\
c_{02} &= \displaystyle \frac{ -3 t_1^2 t_2 }{(t_1 - t_2)^3} \\
c_{03} &= \displaystyle \frac{ t_1^3 }{(t_1 - t_2)^3} \\
c_{10} &= \displaystyle \frac{ t_2^2 - t_2^3 }{(t_1 - t_2)^3} \\
c_{11} &= \displaystyle \frac{ 3 t_1 t_2^2 - t_2^2 - 2 t_1 t_2 }{(t_1 - t_2)^3} \\
c_{12} &= \displaystyle \frac{ - 3 t_1^2 t_2 + t_1^2 + 2 t_1 t_2 }{(t_1 - t_2)^3} \\
c_{13} &= \displaystyle \frac{ t_1^3 - t_1^2 }{(t_1 - t_2)^3} \\
\end{aligned} \quad \quad \begin{aligned}
c_{20} &= \displaystyle \frac{ -t_2^3 + 2 t_2^2 - t_2 }{(t_1 - t_2)^3} \\
c_{21} &= \displaystyle \frac{ 3 t_1 t_2^2 - 2 t_2^2 - 4 t_1 t_2 + 2 t_2 + t_1 }{(t_1 - t_2)^3} \\
c_{22} &= \displaystyle \frac{ -3 t_1^2 t_2 + 2 t_1^2 + 4 t_1 t_2 - t_2 - 2 t_1 }{(t_1 - t_2)^3} \\
c_{23} &= \displaystyle \frac{ t_1^3 - 2 t_1^2 + t_1 }{(t_1 - t_2)^3} \\
c_{30} &= \displaystyle \frac{ -t_2^3 + 3 t_2^2 - 3 t_2 + 1 }{(t_1 - t_2)^3} \\
c_{31} &= \displaystyle \frac{ 3 t_1 t_2^2 - 3 t_2^2 - 6 t_1 t_2 + 3 t_1 + 6 t_2 - 3 }{(t_1 - t_2)^3} \\
c_{32} &= \displaystyle \frac{ -3 t_1^2 t_2 + 3 t_1^2 + 6 t_1 t_2 - 6 t_1 - 3 t_2 + 3 }{(t_1 - t_2)^3} \\
c_{33} &= \displaystyle \frac{ t_1^3 - 3 t_1^2 + 3 t_1 - 1 }{(t_1 - t_2)^3} \\
\end{aligned}$$
(Let $\vec{p}\bigl(t_1 + t (t_2 - t_1) \bigr) = \vec{q}(t)$, and solve for the corresponding coefficients of $t$; you have four unknowns and four equations.  Sort the coefficients, and the above pop out.  I used wxMaxima to do the grunt work.)


text:
Q: How do I refactor this block of code to make it dry How do I go about making this code block dry?
I understand that dry means dont repeat yourself but I don't see any obvious opportunity for refactoring.
Index, show, edit, and create seem like basic/necessary methods. They appear to be pretty dry to me.
The methods after I am not sure about.
I haven't tried anything other than googling so far.
class UsersController < ApplicationController

  def index
    @users = User.all
  end

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
  end

  def edit
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end

    Slack.notify_channel
  end

  def update
    @user = User.find(params[:id])

    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end

    Slack.notify_channel
  end

  def destroy
    @user = User.find(params[:id])

    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end

    Slack.notify_channel
  end

  private
    def user_params
      params.require(:user).permit(:username, :email)
    end
end

There is no rails backend attached to this code snippet. I am assuming it is just theoretical - wanting us to refactor the code to make it shorter.

A: IMHO you can do something like that.
class UsersController < ApplicationController
  include ExceptionHandling
  before_action :load_user, only: [:show, :edit, :update, :destroy]
  after_action :slack_notify_channel, only: [:create, :update, :destroy]

  def index
    @users = User.all
  end

  def new
    @user = User.new
  end

  def create
    @user = User.create!(user_params)
    respond_to do |format|
      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render :show, status: :created, location: @user }
    end
  end

  def update
    @user.update!(user_params)
    respond_to do |format|
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { render :show, status: :ok, location: @user }
    end
  end

  def destroy
    @user.destroy!
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

  def load_user
    @user = User.find(params[:id])
  end

  def slack_notify_channel
    Slack.notify_channel
  end

  def user_params
    params.require(:user).permit(:username, :email)
  end
end

I would recommend you to create a concern to manage exceptions and render each specific error by exception. Then you can avoid having two ways in each action to render a good and bad case.

A: I have to guess a bit about what's in your ApplicationController and User classes. But the obviously repeated code is @user = User.find(params[:id]). Your show and edit methods both just run this line. So, they do exactly the same thing, which they oughtn't to do. One method for one thing.
Also, once you resolve show and edit into a single method, your create, update and destroy methods should call it instead of repeating the line.
Next, I wouldn't use new as a method name, since it is already used by BasicObject::new. I tested a few things and it gets pretty unclear:
class Test
  attr_reader :test
  def initialize
    @test = 'test'
  end
end

class Test2
  attr_reader :test2
  def new
    p 'test2new'
    @test2 = Test.new
  end
end

testx = Test2.new
p testx.new.test
p testx.test2.test

=> "test2new"
=> "test"
=> "test"

It takes extra effort to see when you're calling your own new method and when you're calling BasicObject::new. So, I'd change that to new_user or something, if you even need it at all — I don't see why you need both it and your create method. (If you don't need it, get rid of it.)
Finally, @user = User.find(params[:id]) doesn't imply either showing or editing, so understanding what you're trying to do and coming up with a name that reflects it (e.g. set_user_id) is something that ought to be done as well.


text:
Q: Str.contain in Pandas for a column with all values NaN I'm going through a Dataframe generated from reading a PDF file. When reading the file, it may happen that one of the columns contains only NaN values.
I need to search for a string in all column, but running str.contains on the column with all NaN results in AttributeError: Can only use .str accessor with string values!
The code below results in the error. Change one of the NaN values to a string though, and it works. How do I get around this?
d = {'col': [np.nan, np.nan, np.nan, np.nan, np.nan]}
df = pd.DataFrame(data=d)
df['col'].str.contains('Total Due This Invoice - USD', na=False)

A: One idea is replace missing values to some non match string value, e.g. here empty string:
m = df['col'].fillna('').str.contains('Total Due This Invoice - USD')
print (m)
0    False
1    False
2    False
3    False
4    False
Name: col, dtype: bool


text:
Q: My Dell Laptop is not connecting with wifi router One of my Dell laptop is not connecting with wifi network, once i troubleshot, then it show message to restart your WIFI router, but after restarting the router its not connecting.
Earlier, this laptop was connecting perfectly with WIFI. My Dell laptop configuration is Windows 7 OS and  processor is Core i5.
I don't think the problem is related to WIFI router, because my another laptop and mobile device is connecting successfully with WIFI.
Can anyone help me on this.

A: its my last night problem look at here
what exactly happens when you try to connect
and what exactly you have done tease days like installing new programs new drivers updates or etc ... ?
the simple way to solve this is to remove driver and uninstall it from device manager (mark uninstall driver) and let windows install it with its own driver it will work if your wifi channel be less than 12
maybe your wireless channel goes to 12 ,13 or 14 there are hard ways to access these channels but you can go to your modem panel under wireless settings change channel to 1 to 11 or if you set it on automatic set your country to USA
if you cant change wifi channel you should to try so much things

*

*first of all try to go device manager > properties of your wifi adapter >advanced >location>put it on JP or EU

*sometimes with upgrading wifi driver you can access wifi channels 12 to 14 try this too

*you may need to change your location in windows to JP or EU but its a week way

*you can add location to your wifi adapter from registry like here
i suggest you to know what channel your modem is and then try to do any thing you can use android apps like (wifi Analyzer) or another


text:
Q: Writing a SQL Query into VBA using a IFF statement, Get missing expression error I have been trying to figure this out for days, and not having any luck. I am trying to write a SQL line command inside of VBA.
I am getting the "ORA-00936: misssing expresson error"
strSql4 = "SELECT FWLOTID, ENDDATETIME, ENDCODE, DRAW, IIF([ENDCODE]=""6"", ""MSNAG"",""0"") "    ' Or ENDCODE='10' Or ENDCODE='11' Or ENDCODE='12' Or ENDCODE='14'"

strSql3 = "FROM EVENTS.ODSWIND WHERE ENDDATETIME > to_date('" & Format(dtEndDate, "MM/dd/yyyy") & "','MM/DD/YYYY') "

        On Error Resume Next
        rsPRC.Close
        On Error GoTo ErrorHandler
        rsPRC.CursorLocation = adUseClient
        rsPRC.CursorType = adOpenStatic
        rsPRC.LockType = adLockOptimistic
        rsPRC.Open strSql4 & strSql3, cnPRC

A: Check your data type for [ENDCODE].  If it is a text field then try this:
strSql4 = "SELECT FWLOTID, ENDDATETIME, ENDCODE, DRAW, IIF([EVENTS].[ODSWIND].[ENDCODE]=""6"", ""MSNAG"",""0"") as IsItSix "

If [ENDCODE] is numeric, then try this:
strSql4 = "SELECT FWLOTID, ENDDATETIME, ENDCODE, DRAW, IIF([EVENTS].[ODSWIND].[ENDCODE]=6, ""MSNAG"",""0"") as IsItSix "

Also, let us know what database you are sending this code to.  Is it an Access Jet database?  An Access Ace database?  A SQL Server database?  All the extra info you give can let us help you better.
EDIT
Also... IIF will only work with an Access Sql query.
Your error looks like an Oracle error.
Assuming you are sending to Oracle, try this:
strSql4 = "SELECT FWLOTID, ENDDATETIME, ENDCODE, DRAW, CASE WHEN [ENDCODE]= '6' THEN 'MSNAG' ELSE '0' END as IsItSix "

EDIT AGAIN
Try this:  (if it doesn't work, let me know the exact error message.)
strSql4 = "SELECT FWLOTID, ENDDATETIME, ENDCODE, DRAW, CASE ENDCODE WHEN '6' THEN 'MSNAG' ELSE '0' END AS ISITSIX "

A: Try it like this and see if this works:
strSql4 = "SELECT FWLOTID, ENDDATETIME, ENDCODE, DRAW, IIF(""ENDCODE""='6', 'MSNAG','0') "    ' Or ENDCODE='10' Or ENDCODE='11' Or ENDCODE='12' Or ENDCODE='14'"