text:
Q: How to check for a valid session in JSF application? Before I explain the situation, I'll preface it by saying that the application I'm working on is old, outdated, needs to be rewritten, etc. but the company I work for doesn't care and is just looking for a quick bandage to this problem. Also, I'm just some random dude who they gave this app to and, despite knowing next to nothing about all this, they somehow consider me the subject matter expert.
I have a .xhtml page that users go to in order to pay bills. We use SiteMinder to control access to the application, and through this there has been set a two hour inactivity timeout limit for the application. However, we have recently implemented some new payment features from a third party vendor that make use of modal windows. If a user sits on this .xhtml page for an hour and fifty nine minutes, invokes the modal window (via a button click), and goes to complete various actions in the modal, then when they're done the third party vendor considers the action successful (since they are unaware of our timeout) but we do not receive any responses from them since the session has timed out on our end. This is a problem, because users can schedule future payments, and if we do not get a response from the vendor, we have nothing to store in our database which we eventually use to trigger the scheduled payment.
How can I determine if the user's session is still valid when they click to invoke the third party modal window? Here's what one of the buttons looks like:
<p:commandButton id="makePaymentButton"
    value="Make Payment" onclick="makePayment(/*args*/);"
</p:commandButton>

Basically, instead of immediately invoking the modal window, I want to first check and ensure that the user's session is still valid. Since is there is not page navigation or server interaction when this button is clicked, the modal simply renders whether or not the user's session has expired.

A: If you use standard render Kit use :
<h:commandButton id="makePaymentButton"
                 value="Make Payment"
                 actionListener="your action listener which may return an exception if the session control fails">
    <f:ajax onevent="makePayment(/*args*/)" />
</h:commandButton>

If you use Primefaces use "oncomplete", "onsuccess" :
<p:commandButton id="makePaymentButton"
                 value="Make Payment"
                 actionListener="your action listener which may return an exception if the session control fails"
                 onsuccess="makePayment(/*args*/)" />

Then, in the actionListener you can get the session :
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);

Caution : the session reference might be null, then check what you need with it.
Dont forget to place <f:view transient="true"> ... </f:view> in order to disable the automatic creation of a JSESSIONID.

A: To know if the session is still valid, you'd need to ask the server. But you have to be careful, so that your "asking" request wouldn't automatically create a new session itself. The most surefire way is to ditch JSF altogether and create a simple Servlet.
public class CheckSessionServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain");

        HttpSession session = request.getSession(false);
        if (session == null) {
            // no session, let's respond 404
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else {
            // session exists - return a succesful status
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    }

}

Do an AJAX POST request with JS to this servlet, and then act on the request outcome.
In order to prevent session timing out while the user if filling out the 3rd party dialog, you may want to touch the session to bump its timeout:
        } else {
            // session exists - bump timeout & return a succesful status
            session.setAttribute("someUnusedAttribute", 123);
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }

And if the session is expired then you can refresh the page (with JS) to allow user to start anew. Or show a simple message to user, explaining that the session is gone and he needs to start again.
You can do all this without touching the legacy JSF stuff.


text:
Q: How to plot distribution of final grade by sex? I'm working on predicting student performance based on various different factors. This is a link to my data: https://archive.ics.uci.edu/ml/datasets/Student+Performance#. This is a sample of the observations from the sex and final grade data columns:
sex G3
F   6
F   6
F   10
F   15
F   10
M   15
M   11
F   6
M   19
M   15
F   9
F   12
M   14

I'm looking at the distribution of my target variable (final grade):
ax= sns.kdeplot(data=df2, x="G3", shade=True)
ax.set(xlabel= 'Final Grade', ylabel= 'Density', title= 'Distribution of Final Grade')
plt.xlim([0, 20])
plt.show()

Screenshot of Distribution of Final Grade

And now I want to find out how the distribution of final grades differ by sex:
How can I do this?

A: Considering the sample data.
df2 = pd.DataFrame({'sex': ['F','F','F','F','F','M','M','F','M','M','F','F','M'], 'grades': [6,6,10,15,10,15,11,6,19,15,9,12,14]})

sex G3
F   6
F   6
F   10
F   15
F   10
M   15
M   11
F   6
M   19
M   15
F   9
F   12
M   14

We use the seaborn countplot function as follows.
sns.countplot(x="grades", hue='sex', data=df2)

To get the following plot.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wso2 IS Clustering (LoadBalancing/Failover) I am looking into clustering of the Wso2 IS in here.

*

*Does it really serve the Failover case?

*How many nodes are needed for a minimum load-balance scenario?

*As per the documentation, clustering is configuration between 5.1 & 5.2. Isn't it possible to achieve with same versions / much older versions?

A: Documentation explains how to create two node cluster with active state (both nodes are active) and fronted by a load balancer.
If you need a failover scenario, you can have a node in active state (assuming one node can serve all of your requests) and one node in passive state. If active node fails, load balancer has to direct the traffic to the passive node. So this will serve the failover scenario. You don't need to do any configuration changes in IS level for this. This can be configured in the load balancer level.
Documentation explains clustering for IS 5.1.0 and 5.2.0 versions, but not between these 2 versions. Cluster can be created with only 1 version of server nodes, but not with nodes of different versions.


text:
Q: Securing storage account with remote tfstate How to disable public access to Azure storage account but still accessible from cloudshell.
What I have and works:

*

*Az-storage account that contains "terraform.tfstate" with public access

*main.tf file in my "Azure Cloudshell" with "backend" config for remote statefile

terraform {
  required_version = ">= 1.2.4"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 2.98.0"
    }
  }

 # To store the state in a storage account
 # Benefit=working with team and if local shell destroyed -> state=lost)

  backend "azurerm" {
    resource_group_name  = "RG-Telco-tf-statefiles"
    storage_account_name = "telcostatefiles"
    container_name       = "tf-statefile-app-1"
    key                  = "terraform.tfstate"
  }
}

This works perfectly.
But if I restrict public access in the storage account, my "Azure Cloudshell" has no permission to the statefile anymore.
How can I make it work and what are the best security best practices in this case?

A: I think this is what you need.
After you set this, you can make a network restriction rule and you can allow the cloud shell virtual network.
Some other best practices:

*

*The storage account that stores the state file should be in a separate resource group and have a delete lock on it.

*1 SAS token per user renewed every 6 months with a scope at the folder level, one container per project, and per environment

*Storage with redundancy in a paired region for reading access in case of issues


text:
Q: Cannot insert data to MySQL Server - error 111 When I try to insert data in my server I get the following error:

Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on 'sg2nlddb5002-03.shr.prod.sin2.secureserver.net' (111) in /home/content/02/11649702/html/dbcon.php on line 2
Could not connect: Can't connect to MySQL server on 'sg2nlddb5002-03.shr.prod.sin2.secureserver.net' (111)

It works fine on my localhost. I am using php and mysql.
This is the link on my server that gives this error: http://spectrumenglishcourse.com/FRM_Words.php
I have spent the last two hours trying everything from trying to edit my.cnf and what not. Pleaaase help


text:
Q: How can I loop through a directory and adjust file names I want to write a ksh script that loops through a directory and changes the names of files to include a 001_DTS (where DTS is a date time stamp), 002_DTS, 003_DTS, etc
and remove the aa, ab, etc because I want to use this with the split function (the files created from that function).

A: prefix="x"   # the default 'split' prefix, change to suit yourself
count=1
dts=$(date +%Y%m%d%H%M%S)

for f in "$prefix"[a-z][a-z]; do
  mv "$f" "$(printf "%s%03d_%s" "$prefix" $count $dts)"
  (( count++ ))
done

A: how about this, not a shell specific (ksh/bash)
cd /path/to/dir
for file in *
 do
  mv $file ${file}_$(date +%Y%m%d%H%M%S) && echo "file moved" || echo "unable to move"
done

If you want to fix the value of DTS before the loop just assign the variable like other posts.

A: first, run bash :-) and then solve it:
bash # :-)
J=1
for I in * ; do
    mv -i $I `printf '%03d' $J`_DTS
    J=$((J+1))
done


text:
Q: 'no member nameType' error implementing NSLinguisticTagger in a in Swift 3.2 project I'm trying to use NSLinguisticTagger in a Swift 3.2 project for macOS.
This code works fine in Swift 4
let tagger = NSLinguisticTagger(tagSchemes: [.nameType], options: 0) // edited

But, gives the error:

Type 'String' has no member 'nameType' // edited

in the Swift 3.2 project. I tried to follow old NSLinguisticTagger tutorials but I can't find a replacement for the '.name' part. Is possible to fix this or I have to update the project to Swift 4?
NSLinguisticTagger Docs
NSHipster NSLinguisticTagger 2012 Tutorial

A: First of all, I need to apologize that I first wrote an answer without confirming my settings are really right. The following descriptions updated based on the settings which I believe correct.
(Xcode 9.2, target Swift Version set to 3.2. Changing the project Swift Version does not affect the target Swift Version, oh, my shame...)

When you want to work with old Swift versions, some Swift-friendly wrapper types are not available and APIs and constants are imported from Objective-C world with simple rules. In such cases, you need to re-interpret Objective-C versions of references with such rules in mind.
NSLinguisticTagScheme
As you see in the linked article above, NSLinguisticTagScheme as just a typealias of String and the constants are named as NSLinguisticTagSchemeNameType as in the article in your question's link. They are imported as-is in old Swift versions.
So, this compiles in Swift 3.2:
let tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagSchemeNameType], options: 0)

(Still, I strongly recommend you to move to Swift 4. As Apple's official references are based on the latest version of Swift, it's Swift 4.)


text:
Q: split paragraph into array javascript I had code like below
return fetch(URI + 'api/brewing/1')
      .then((response) => response.json())
      .then((responseJson) => {

          var parsedResponse = JSON.parse(responseJson["data"][0]["steps"]);
          var stringData = JSON.stringify(parsedResponse);
          })
      .catch((error) => {
        console.error(error);
      });
    }

And get data like below
After soaking your filter in a warm water bath for at least five minutes, drop it into the bottom of your siphons top component, or hopper, and hook to the bottom of the hoppers glass tubing.,Fill your siphon bottom component.,Insert the hopper, filter and all.
I want to split the paragraph after dot and comma delimiter into an array so I can loop all the data. How can I do that? Thanks.

A: try str.split(/[,.]+/); to split the paragraph after dot and comma delimiter into an array

let str ="After soaking your filter., in a warm water bath for at least five minutes, drop it into the bottom of your siphons top component, or hopper,. and hook to the bottom of the hoppers glass tubing.,Fill your siphon bottom component.,Insert the hopper, filter and all.";

let splittedArray = str.split(".,");

console.log(splittedArray);

A: I believe you want to split the string by dot followed by comma:

var s = 'After soaking your filter in a warm water bath for at least five minutes, drop it into the bottom of your siphons top component, or hopper, and hook to the bottom of the hoppers glass tubing.,Fill your siphon bottom component.,Insert the hopper, filter and all.'
s = s.split('.,');
console.log(s);

OR: Using RegEx

var s = 'After soaking your filter in a warm water bath for at least five minutes, drop it into the bottom of your siphons top component, or hopper, and hook to the bottom of the hoppers glass tubing.,Fill your siphon bottom component.,Insert the hopper, filter and all.'
s = s.split(/(?:\.\,)/g);
console.log(s);


text:
Q: array_keys() expects parameter 1 to be array, boolean given I recently moved the cpanel hosting and I have the following error that I can not solve if you can help me. thank you
File: /public_html/admin/users.php
Line: 180
Message: array_keys() expects parameter 1 to be array, boolean given

Call stack:

File: /public_html/admin/users.php (Line: 180)
Function: array_keys

LINE 180:
 <?php echo implode('	', array_keys(current($recruits))); ?>

A: The error says itself. Aparently, you want to concatenate the array keys with th element, but please take a look at what current and array_keys actually does and requires to function properly, the documentation is self-explanatory but I'll write some examples below in hopes to help you understand.

http://php.net/manual/en/function.array-keys.php

array_keys will extract the keys from an Associative array, e.g.:
$mySpecialArray = ["key1" => "value1", "key2" => "value 2"];
$keys = array_keys($mySpecialArray);
//$keys will contain "key1", "key2"

//I feel you're new to php, so I'm going to write an example of implode aswell

$implodeStringWithComma = implode(',', $keys);
//$implodeStringWithComma will result in a string like this -->  "key1,key2"

$implodeStringWithTh = implode('	', $keys)
//$implodeStringWithTh will result in a string like this -->  "key1	key2"

Your error states that what is inside the array_keys is not an array, that is because what is inside array_keys is  current($recruits) and the error is telling you that  current($recruits) is a boolean. So, what does current do?

http://php.net/manual/en/function.current.php

"The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer.
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. "
Without futher explanation on what's inside $recruits and the purpose, can't help you more, but I'm guessing you're going from result to result in $recruits. I believe the $recruits is an Multidimensional array, something among these lines:
$recruits[0] => ["key1" => "value1", "key2" => "value2", "key3" => "value3"];
$recruits[1] => ["key4" => "value4", "key5" => "value5", "key6" => "value6"];
.
.
.

And I'm also guessing you're using the internal pointer to loop from array to array (When you use current($recruits), it gives the equivalent of $recruits[0], when you do next($recruits) and again current($recruits), the current will give you the next array, equivalent of $recruits[1], end($recruits) for example will give you the last array of $recruits). Most likely, your code is pointing (as documentation says) to something that is beyongdthe array, or the array being empty.


text:
Q: POST Request in Objective-C with Lyft API Access Token I'm encountering an issue in retrieving my access token for the Lyft API via an Objective-C POST request (I'm pretty new to POST requests). The Lyft API documentation details this as an example request:
POST /oauth/token HTTP/1.1
Authorization: Basic base64(client_id:client_secret)
Content-Type: application/json;charset=UTF-8

{
  "grant_type": "authorization_code",
  "code": "<authorization_code>"
}

This is the curl request from their documentation:
curl -X POST -H "Content-Type: application/json" \
     --user "<client_id>:<client_secret>" \
     -d '{"grant_type": "authorization_code", "code": "<authorization_code>"}' \
     'https://api.lyft.com/oauth/token'

How would I implement this in Objective-C? This is my code right now:
    NSString *post = [[NSString alloc] initWithFormat: @"{grant_type: client_credentials, scope: public}"];
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSURL *lyftURL = [NSURL URLWithString: @"https://api.lyft.com/oauth/token"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:lyftURL];

    [req setHTTPMethod:@"POST"];
    [req addValue: @"application/json" forHTTPHeaderField: @"Content-Type"];

    NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"UK83N70T5vBx", @"6Fw8SnbIXPJ9v9_OnBRczvP1DIXqD1H2"];
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64Encoding]];
    [req setValue:authValue forHTTPHeaderField:@"Authorization"];

    [req setHTTPBody: postData];

    [NSURLConnection sendAsynchronousRequest: req queue: [NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError)
            NSLog(@"ERROR");
        else {
            NSLog(@"DATA: %@", data);

            NSError* error;
            NSDictionary* lyftJSON = [NSJSONSerialization JSONObjectWithData:data
                                                                       options:kNilOptions
                                                                         error:&error];
            NSLog(@"JSON: %@", lyftJSON);

        }
    }];

I'm getting the following error: 'Could not find or parse grant_type, did you set the Content-Type header correctly?'
Here is the link to the Lyft documentation: [https://developer.lyft.com/docs/authentication][1]
It would be great if I could know where my issue lies in my code.


text:
Q: Repository Pattern with Linq to SQL: Many-to-Many relationships I am working on a project following the suggested repository pattern in Steven Sanderson's excellent book "Pro ASP.NET MVC 2 Framework".
Take the following example: I have a table for "Products" and for "Images". Both have an own repository that creates a new DataContext in the constructor. Now, I want to establish a many-to-many relationship between the two entities called "ImagesForProducts".
Should I create a separate repository for the ImagesForProducts entities? If so, how can I share the DataContext between all the entities? In that case I have to instantiate my ProductController with two repositories (for Products and for ImagesForProducts), right?
I'd rather access the images using my product instances, so that I can write myProduct.AddImage(img). But how can I persist the relation in the database using the ProductRepository?
As you can see, I am not sure about the overall architecture and would highly appreciate a basic code example.
Thanks in advance!

A: After some careful research and consideration, I decided to let the repositories handle image attachments instead of the product instances (mostly because the instances shouldn't deal with any database related stuff).
I already got an ImagesForProducts entity because I am using Linq-to-SQL mapping. I therefore added a Table of that type to my product repository which I can initiate with the current DataContext of the product repository. That way, both instances always use a shared DataContext and I can simply implement a method "AttachImageToProduct" like this:
public class MsSqlProductsRepository : MsSqlRepository<Product>, IProductsRepository
{
    protected Table<ImagesForProducts> imageRelationsTable { get; set; }

    public MsSqlProductsRepository(string connectionString)
        : base(connectionString)
    {
        imageRelationsTable = DataContext.GetTable<ImagesForProducts>();
    }

    public void AttachImageToProduct(Image image, Product product)
    {
        if (imageRelationsTable.First(r => r.ImageId == image.Id && r.ProductId == product.Id) != null)
            return;

        ImagesForProducts rel = new ImagesForProducts();
        rel.ImageId = image.Id;
        rel.ProductId = product.Id;

        imageRelationsTable.InsertOnSubmit(rel);
        entitiesTable.Context.SubmitChanges();
    }
}

Do you have any general concerns about this solution?

A: The repository pattern should be used to represent an in-memory store for your domain objects. Since you want your domain model to be ignorant of the persistence internals and also have everything designed around aggregate roots, then it does not make sense to have a ImagesForProducts entity and thus doesn't make sense to have a separate repository for ImagesForProducts entities.
First of all I Would recommend building your domain model with POCO objects that can be used in any persistence scenario (LINQ to SQL, EF, Stored Procedures..).
You should have only two repositories (ProductRepository and ImageRepository) and resolve the many to meny relation as "relational" properties in both domain objects. For example you can add an Image collection to the Product domain object and a Product collection to the Image domain object. Once you build your POCO objects, then you can handle mappings to the specific persistence store inside your repositories (preferrably in the constructor).
Once you implement the plubming, you can and add an image to the product:
product.Images.Add(image);

Then you can call your repository like this:
productRepository.Add(product);


text:
Q: How to assign multidimensional array in PHP 7.4? I am trying to assign a multi-dimensional array in PHP 7.4. I am switching from PHP 7.2 to 7.4 and not sure how I can fix this.
$model->a = $model->a ?? [];
$model->a->b = $model->a->b ?? [];

I am getting the error:

Attempt to assign property 'b' of non-object.

A: If $model->a doesn't exist then you set it to an array, but then attempt to set $model->a->b but a is an array not an object.
So you either need to assign an object, substitute another class for stdclass if needed:
$model->a = $model->a ?? new stdclass;
$model->a->b = $model->a->b ?? new stdclass;
$model->a->b->c = 'some value';

Or assign an array as you are but then access it as an array:
$model->a = $model->a ?? [];
$model->a['b'] = $model->a['b'] ?? [];
$model->a['b']['c'] = 'some value';

However, for an array you don't need to do all of that as array assignments are dynamic.  Just this works fine:
$model->a['b']['c'] = 'some value';

As for the switch from PHP 7.2 to 7.4, this wouldn't have worked in 7.2 either, you must have a difference in error reporting between the two.
You might also look to see if the __set() magic method can help you.


text:
Q: parsing a Complex JSON Structure I am trying to parse this JSON in Java.
{
  "json": {
    "abc": 0,
    "def": "100",
    "ghi": 1,
    "jkl": "0000000000",
    "mno": "3",
    "pqr": "COLS, COMPLETE",
    "stu": 2,
    "vwx": "0000010000",
    "yz": "00",
    "a123": 31,
    "b123": 1,
    "c123": "1270",
    "d123": "2",
    "e123": "00",
    "f123": 1,
    "g123": "0000001000"
  },
  "_indexes": {
    "c123": [
      "1270"
    ],
    "h123": [
      "1270"
    ]
  },
  "_d": false,
  "_dd": "2017-09-12T12:03:53.716Z",
  "_op": "add",
  "_id": 2
}

So far i have done the following using the gson library :-
         JsonParser par = new JsonParser();
         JsonElement jsonelement = par.parse(new FileReader("ddJob.json"));
         JsonArray jsonArr = jsonelement.getAsJsonArray();
             for(Object o : jsonArr)
             {
                 JsonObject obj = (JsonObject)(o);
                 JsonObject mArry = obj.getAsJsonObject();
                 String keyVal = mArry.get("key").toString();

                 if(keyVal.equalsIgnoreCase("\"jsonstore.LinkTree\""))
                 {
                    if(mArry.isJsonArray())
                 {
                     System.out.println("It is a JSONArray");
                 }
                 else if(mArry.isJsonObject())
                 {
                     System.out.println("It is a JSONObject");
                 }
                 else if(mArry.isJsonPrimitive())
                 {
                     System.out.println("It is a JSONPrimitive");
                 }
                 else if(mArry.isJsonNull())
                 {
                     System.out.println("It is a JSONNull");
                 }
                 }
                // Here it prints ,it is a JSONObject

I need help from here, I am not able to parse this JSONObject, I cannot get a JSonArray out of it and I am not able to get anything like a primitive etc. I can see in the debugger it has all the information I need. It is unreadable because of the spaces in between.
Can you please let me know how I can parse the rest of this JSON.
Thank you very much.

A: I used Java API for JSON Processing. Jar can be found here.
This updated version should help with multiple JSON objects separated by commas. This version attempts to find the correct comma then splits the string based on those commas.
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
import static javax.json.stream.JsonParser.Event.KEY_NAME;
import static javax.json.stream.JsonParser.Event.VALUE_FALSE;
import static javax.json.stream.JsonParser.Event.VALUE_NUMBER;
import static javax.json.stream.JsonParser.Event.VALUE_STRING;
import static javax.json.stream.JsonParser.Event.VALUE_TRUE;

/**
 *
 * @author blj0011
 */
public class JSONParserTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String jsonString = "{\n" +
                            "  \"json\": {\n" +
                            "    \"abc\": 0,\n" +
                            "    \"def\": \"100\",\n" +
                            "    \"ghi\": 1,\n" +
                            "    \"jkl\": \"0000000000\",\n" +
                            "    \"mno\": \"3\",\n" +
                            "    \"pqr\": \"COLS, COMPLETE\",\n" +
                            "    \"stu\": 2,\n" +
                            "    \"vwx\": \"0000010000\",\n" +
                            "    \"yz\": \"00\",\n" +
                            "    \"a123\": 31,\n" +
                            "    \"b123\": 1,\n" +
                            "    \"c123\": \"1270\",\n" +
                            "    \"d123\": \"2\",\n" +
                            "    \"e123\": \"00\",\n" +
                            "    \"f123\": 1,\n" +
                            "    \"g123\": \"0000001000\"\n" +
                            "  },\n" +
                            "  \"_indexes\": {\n" +
                            "    \"c123\": [\n" +
                            "      \"1270\"\n" +
                            "    ],\n" +
                            "    \"h123\": [\n" +
                            "      \"1270\"\n" +
                            "    ]\n" +
                            "  },\n" +
                            "  \"_d\": false,\n" +
                            "  \"_dd\": \"2017-09-12T12:03:53.716Z\",\n" +
                            "  \"_op\": \"add\",\n" +
                            "  \"_id\": 2\n" +
                            "},\n" +
                            "{\n" +
                            "  \"json\": {\n" +
                            "    \"abc\": 0,\n" +
                            "    \"def\": \"100\",\n" +
                            "    \"ghi\": 1,\n" +
                            "    \"jkl\": \"0000000000\",\n" +
                            "    \"mno\": \"3\",\n" +
                            "    \"pqr\": \"COLS, COMPLETE\",\n" +
                            "    \"stu\": 2,\n" +
                            "    \"vwx\": \"0000010000\",\n" +
                            "    \"yz\": \"00\",\n" +
                            "    \"a123\": 31,\n" +
                            "    \"b123\": 1,\n" +
                            "    \"c123\": \"1270\",\n" +
                            "    \"d123\": \"2\",\n" +
                            "    \"e123\": \"00\",\n" +
                            "    \"f123\": 1,\n" +
                            "    \"g123\": \"0000001000\"\n" +
                            "  },\n" +
                            "  \"_indexes\": {\n" +
                            "    \"c123\": [\n" +
                            "      \"1270\"\n" +
                            "    ],\n" +
                            "    \"h123\": [\n" +
                            "      \"1270\"\n" +
                            "    ]\n" +
                            "  },\n" +
                            "  \"_d\": false,\n" +
                            "  \"_dd\": \"2017-09-12T12:03:53.716Z\",\n" +
                            "  \"_op\": \"add\",\n" +
                            "  \"_id\": 2\n" +
                            "},\n" +
                            "{\n" +
                            "  \"json\": {\n" +
                            "    \"abc\": 0,\n" +
                            "    \"def\": \"100\",\n" +
                            "    \"ghi\": 1,\n" +
                            "    \"jkl\": \"0000000000\",\n" +
                            "    \"mno\": \"3\",\n" +
                            "    \"pqr\": \"COLS, COMPLETE\",\n" +
                            "    \"stu\": 2,\n" +
                            "    \"vwx\": \"0000010000\",\n" +
                            "    \"yz\": \"00\",\n" +
                            "    \"a123\": 31,\n" +
                            "    \"b123\": 1,\n" +
                            "    \"c123\": \"1270\",\n" +
                            "    \"d123\": \"2\",\n" +
                            "    \"e123\": \"00\",\n" +
                            "    \"f123\": 1,\n" +
                            "    \"g123\": \"0000001000\"\n" +
                            "  },\n" +
                            "  \"_indexes\": {\n" +
                            "    \"c123\": [\n" +
                            "      \"1270\"\n" +
                            "    ],\n" +
                            "    \"h123\": [\n" +
                            "      \"1270\"\n" +
                            "    ]\n" +
                            "  },\n" +
                            "  \"_d\": false,\n" +
                            "  \"_dd\": \"2017-09-12T12:03:53.716Z\",\n" +
                            "  \"_op\": \"add\",\n" +
                            "  \"_id\": 2\n" +
                            "}"; //I am guessing this is how your data looks.

        List<Integer> positions = new ArrayList();
        Pattern p = Pattern.compile("\\},\n\\{");//Find this pattern ***MAKE SURE THIS PATTERN IS CORRECT FOR YOU*** Your patter may be "\\},\\{"
        Matcher m = p.matcher(jsonString);
        while(m.find())
        {
            positions.add(m.start() + 1);//save starting position of the found pattern
        }

        System.out.println("# of positions: " + positions.size());
        List<String> jsonStringObjects = new ArrayList();

        if(positions.size() >= 1)
        {
            jsonStringObjects.add(jsonString.substring(0, positions.get(0)));//get first jsonString
            //System.out.println(jsonString.substring(0, positions.get(0)));
            jsonStringObjects.add(jsonString.substring(positions.get(positions.size() - 1) + 1));//get last jsonString
            //System.out.println(jsonString.substring(positions.get(positions.size() - 1) + 1));
        }
        if(positions.size() >= 2  )
        for(int i = 0; i < positions.size() - 1; i++)//get all jsonStrings between first and last
        {
            jsonStringObjects.add(jsonString.substring(positions.get(i) + 1, positions.get(i + 1)));
            //System.out.println(jsonString.substring(positions.get(i) + 1, positions.get(i + 1)));
        }

        System.out.println("# of jsonStringObjects: " + jsonStringObjects.size());
        int counter = 0;
        for(String item : jsonStringObjects)
        {
            System.out.println("JSON Object #: " + ++counter);
            try (JsonParser parser = Json.createParser(new StringReader(item))) {
                while (parser.hasNext()) {
                    final Event event = parser.next();
                    switch (event) {
                        case KEY_NAME:
                            String key = parser.getString();
                            System.out.println("\t" + key);
                            break;
                        case VALUE_STRING:
                            String value = parser.getString();
                            System.out.println("\t" + value);
                            break;
                        case VALUE_NUMBER:
                            BigDecimal number = parser.getBigDecimal();
                            System.out.println("\t" + number);
                            break;
                        case VALUE_TRUE:
                            System.out.println("\t" + true);
                            break;
                        case VALUE_FALSE:
                            System.out.println("\t" + false);
                            break;
                    }
                }
            }
        }
    }

}

Output:

run:
# of positions: 2
# of jsonStringObjects: 3
JSON Object #: 1
    json
    abc
    0
    def
    100
    ghi
    1
    jkl
    0000000000
    mno
    3
    pqr
    COLS, COMPLETE
    stu
    2
    vwx
    0000010000
    yz
    00
    a123
    31
    b123
    1
    c123
    1270
    d123
    2
    e123
    00
    f123
    1
    g123
    0000001000
    _indexes
    c123
    1270
    h123
    1270
    _d
    false
    _dd
    2017-09-12T12:03:53.716Z
    _op
    add
    _id
    2
JSON Object #: 2
    json
    abc
    0
    def
    100
    ghi
    1
    jkl
    0000000000
    mno
    3
    pqr
    COLS, COMPLETE
    stu
    2
    vwx
    0000010000
    yz
    00
    a123
    31
    b123
    1
    c123
    1270
    d123
    2
    e123
    00
    f123
    1
    g123
    0000001000
    _indexes
    c123
    1270
    h123
    1270
    _d
    false
    _dd
    2017-09-12T12:03:53.716Z
    _op
    add
    _id
    2
JSON Object #: 3
    json
    abc
    0
    def
    100
    ghi
    1
    jkl
    0000000000
    mno
    3
    pqr
    COLS, COMPLETE
    stu
    2
    vwx
    0000010000
    yz
    00
    a123
    31
    b123
    1
    c123
    1270
    d123
    2
    e123
    00
    f123
    1
    g123
    0000001000
    _indexes
    c123
    1270
    h123
    1270
    _d
    false
    _dd
    2017-09-12T12:03:53.716Z
    _op
    add
    _id
    2


text:
Q: Git: how to ignore all target and build subdirectories? I have a lot of projects organized in tree.
There are a lot of directories "target" and "build" in random places of the tree, and I want to vanish them all form Git repository ignoring them.
Please tell me what to add to .gitignore for that?

A: Simply target/ should be enough.
Make sure to put it in a .gitignore at the root folder of your Git repository.
And check it works (even without committing) with:
git check-ignore -v -- path/to/target/aFile

If it does not (meaning you get an empty output):
git rm -r --cached -- path/to/target/aFile

Then try again the git check-ignore command: you should see a .gitignore rule.

A: .gitignore is indeed the way to go here.
The actual content of gitignore file depends on the actual technologies you're working with, build system, ide, etc.
Here is an example of such a .gitignore file (relevant for java developers):
# Maven
target/

# IntelliJ project files
*.iml
*.iws
*.ipr
.idea/
.idea

# eclipse project file
.settings/
.classpath
.project

# Binaries
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.war
*.ear
*.sar
*.class

# Misc
*.swp
release.properties
pom.xml.releaseBackup
pom.xml.tag

Note the "target/" definition - you can add 'build' folder following the same pattern.
One caveat though: add .gitignore to git (read commit it) before the actual "garbage" files are created (for example before you're running the build tool that creates some stuff in the target directory).
A presence of .gitignore file won't really "remove" the already committed files.
I usually tend to commit .gitignore right after the initial commit.
If you've already committed some files, remove them first and then commit the .gitignore file.


text:
Q: How to get reference of GridGroupingControl through GridTableControl?
   I am developing a windows application in which i used GridGroupingControl (Syncfusion Control). In the code i used void TableControl_MouseMove(object sender, MouseEventArgs e) event, in the event i was getting "GridTableControl" reference of GGC using : GridTableControl grdControl = sender as GridTableControl; but i also want the reference of GridGroupingControl to which GridTableControl belong, like :
GridTableControl grdControl = sender as GridTableControl;
GridGroupingControl ggc = (grdControl.Parent) as GridGroupingControl;

But here ggc is null.Thanks in advance.

A: We can access Grid Grouping Control from TableControl by using GridGroupingControl ggc = (grdControl.GroupingControl) as GridGroupingControl instead of GridGroupingControl ggc = (grdControl.Parent) as GridGroupingControl.
Here is the code that you need to handle in MouseMove Event:
GridTableControl grdControl = sender as GridTableControl;
GridGroupingControl ggc = (grdControl.GroupingControl) as GridGroupingControl;

I hope the above code will help you achieve your result.


text:
Q: What are the differece between core/email_template and core/email_template_mailer every one ,can anyone tell me please what are the difference between core/email_template_mailer and core/email_template...I want to know its each function in details.

A: Your question is quite vague. Take a look at:

*

*app/code/core/Mage/Core/Model/Email/Template.php, and

*app/code/core/Mage/Core/Model/Email/Template/Mailer.php
Magento refers to them as

Template model

And

Email Template Mailer Model

Respectively.
The Mailer.php model is responsible for the email functionality, i.e setting templates, setting senders & sending the actual email.
The Template.php model is responsible for configuration of the actual email template.
All relevant functions can be found within the aforementioned model files.

A: One big difference is setReplyTo()
(My Magento version is 1.7.0.1)
I added setReplyTo() functionality to the email_template_mailer via a customization of a core file:
app/code/local/Mage/Core/Model/Email/Template/Mailer.php
Why? Because it was easier to add a couple lines of code than to rewrite the code utilizing email_template_mailer to send Admin copies of order emails. I wanted the emails to come showing the customers' name and having their email as Reply-To.
Note that changing the From Email to their email gets you blacklisted, so I change the From Name and for the From Email use my own auto-confirm@ address.
While reviewing the two files:
app/code/core/Mage/Core/Model/Email/Template.php
and
app/code/core/Mage/Core/Model/Email/Template/Mailer.php
I concluded that email_template_mailer is a simplified wrapper for email_template, probably a result of how difficult it used to be to just send an email.
The core file app/code/core/Mage/Core/Model/Email/Template/Mailer.php uses email_template:
line 64:           $emailTemplate = Mage::getModel('core/email_template');
and then goes on to use sendTransactional() just like sending email had always been.
app/code/core/Mage/Core/Model/Email/Template.php defines the method sendTransactional() as well as instantiates a private Zend_Mail member object:
line 141:           $this->_mail = new Zend_Mail('utf-8');
sendTransactional() is a wrapper for the public method send(), which does the heavy lifting building the email for Zend_Mail. The send() function populates out the various headers and prepares the body's plain text or HTML content with $this->getProcessedTemplate($variables, true);. And then this send() calls Zend_Mail's own send().
The big deal here is that Varien made the email_template to minimize the need for directly editing code by translating the templates and variables in the database into useful emails.


text:
Q: Set Max Age for GAE Datastore Entries I'm writing a program using Java Google App Engine. I'd like to have certain types of entities automatically removed from a datastore once they reach a certain age, to prevent using unnecessary memory. Here's the very unexciting way I'm creating entities:
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity entity = new Entity("thingamabob","special_thingamabob");
    datastore.put(entity);

In this case, I'd want to have special_thingamabob automatically go away from the datastore after, say, 12 hours. I know I could give each entity a timestamp and then use cron to query every hour for timed-out entities, but is there an easier way?

A: Looks like background-threads might work:
    Thread thread = ThreadManager.createBackgroundThread(new Runnable() {
 private volatile boolean isRunning = true;
  public void run() {
    try {
      while (isRunning) {
        Thread.sleep(12*60*60); // sleep for 12 hours
        datastore.delete(key); //then delete key
        isRunning=false;
      }
    } catch (InterruptedException ex) {
      throw new RuntimeException("Interrupted in loop:", ex);
    }
  }
});
thread.start();


text:
Q: Nested IF Error Can someone assist me fixing these two arguments:
=IF(O18="Ksh",P18,"",IF(O18="USD",P18*U18))

Need to next these are two functions, that work when singularly in cell:
=IF(O18="Ksh",P18,"")

=IF(O18="USD",P18*U18,"")

A: Look for the commas in =IF(O18="Ksh",P18,"",IF(O18="USD",P18*U18)):
There are three, so that is four arguments.
syntax is; IF(test_expression, what_to_do_when_True, what_to_do_when_False)
... so THREE arguments.
Now what did you INTEND with your formula?
=IF(O18="Ksh",P18,IF(O18="USD",P18*U18,"")) - maybe?

A: You need to rewrite your formula like this:
=IF(O18="Ksh",P18,IF(O18="USD",P18*U18,""))

Considering this one =IF(O18="Ksh",P18,"") you need to replace "" with "",
otherwise you get #NAME error.
Next one has no issue.

*

*You may adjust cell references in the formula as needed.

A: If you don't want to use nested IF() functions, here is a fun alternative:
=SWITCH(O18,"Ksh",P18,"USD",P18*U18,"")

You'd need Excel 2019 or 365 for the SWITCH() function to be available though.


text:
Q: Evaluating inline C# code from post content I have been around in circles with this one and need some help. I have a method that evaluates code, so if I pass this Eval("DateTime.Now.Year - 1986") it returns 29, its working great and this means I can have inline code in my posts that dynamically evaluate at runtime (this might present some security concerns, but that for some other time), here's the example string I am trying to work with: string inStr = "this year is [EVAL]DateTime.Now.Year[/EVAL] and it has been [EVAL]DateTime.Now.Year - 1986[/EVAL] years since 1986"; I need a regex that will replace all [EVAL] instances and return the full text with the evaluated results. Anyone?

A: You want a Regex, you can have a regex...
string inStr = "this year is [EVAL]DateTime.Now.Year[/EVAL] and it has been [EVAL]DateTime.Now.Year - 1986[/EVAL] years since 1986";

var rx = new Regex(@"(\[EVAL\])(.*?)(\[/EVAL])");

string outStr = rx.Replace(inStr, RegexReplacer);

with
public static string RegexReplacer(Match match)
{
    return Eval(match.Groups[2].Value);
}

or depending on the return type of Eval:
public static string RegexReplacer(Match match)
{
    object obj = Eval(match.Groups[2].Value);
    return obj != null ? obj.ToString() : string.Empty;
}

The capture group #2 is the (.*?). Note the use of the lazy quantifier .*?, because otherwise the capture would be [EVAL]DateTime.Now.Year[/EVAL] and it has been [EVAL]DateTime.Now.Year - 1986[/EVAL]


text:
Q: Beautifulsoup + Python HTML UL targeting, creating a list and appending to variables I'm trying to scrape Autotrader's website to get an excel of the stats and names.
I'm stuck at trying to loop through an html 'ul' element without any classes or IDs and organize that info in python list to then append the individual li elements to different fields in my table.
As you can see I'm able to target the title and price elements, but the 'ul' is really tricky... Well... for someone at my skill level.
The specific code I'm struggling with:
for i in range(1, 2):
    response = get('https://www.autotrader.co.uk/car-search?sort=sponsored&seller-type=private&page=' + str(i))
    html_soup = BeautifulSoup(response.text, 'html.parser')
    ad_containers = html_soup.find_all('h2', class_ = 'listing-title title-wrap')
    price_containers = html_soup.find_all('section', class_ = 'price-column')

    for container in ad_containers:
        name = container.find('a', class_ ="js-click-handler listing-fpa-link").text
        names.append(name)
        # Trying to loop through the key specs list and assigned each 'li' to a different field in the table
        lis = []
        list_container = container.find('ul', class_='listing-key-specs')
        for li in list_container.find('li'):
            lis.append(li)
        year.append(lis[0])
        body_type.append(lis[1])
        milage.append(lis[2])
        engine.append(lis[3])
        hp.append(lis[4])
        transmission.append(lis[5])
        petrol_type.append(lis[6])
        lis = [] # Clearing dictionary to get ready for next set of data

And the error message I get is the following:

Full code here:
from requests import get
from bs4 import BeautifulSoup
import pandas
# from time import sleep, time
# import random

# Create table fields
names = []
prices = []
year = []
body_type = []
milage = []
engine = []
hp = []
transmission = []
petrol_type = []

for i in range(1, 2):
    # Make a get request
    response = get('https://www.autotrader.co.uk/car-search?sort=sponsored&seller-type=private&page=' + str(i))
    # Pause the loop
    # sleep(random.randint(4, 7))
    # Create containers
    html_soup = BeautifulSoup(response.text, 'html.parser')
    ad_containers = html_soup.find_all('h2', class_ = 'listing-title title-wrap')
    price_containers = html_soup.find_all('section', class_ = 'price-column')

    for container in ad_containers:
        name = container.find('a', class_ ="js-click-handler listing-fpa-link").text
        names.append(name)
        # Trying to loop through the key specs list and assigned each 'li' to a different field in the table
        lis = []
        list_container = container.find('ul', class_='listing-key-specs')
        for li in list_container.find('li'):
            lis.append(li)
        year.append(lis[0])
        body_type.append(lis[1])
        milage.append(lis[2])
        engine.append(lis[3])
        hp.append(lis[4])
        transmission.append(lis[5])
        petrol_type.append(lis[6])
        lis = [] # Clearing dictionary to get ready for next set of data
    for pricteainers in price_containers:
        price = pricteainers.find('div', class_ ='vehicle-price').text
        prices.append(price)

test_df = pandas.DataFrame({'Title': names, 'Price': prices, 'Year': year, 'Body Type': body_type, 'Mileage': milage, 'Engine Size': engine, 'HP': hp, 'Transmission': transmission, 'Petrol Type': petrol_type})
print(test_df.info())
# test_df.to_csv('Autotrader_test.csv')

A: The ul is not a child of the h2 . It's a sibling.
So you will need to make a separate selection because it's not part of the ad_containers.

A: I followed the advice from David in the other answer's comment area.
Code:
from requests import get
from bs4 import BeautifulSoup
import pandas as pd

pd.set_option('display.width', 1000)
pd.set_option('display.height', 1000)
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)

names = []
prices = []
year = []
body_type = []
milage = []
engine = []
hp = []
transmission = []
petrol_type = []

for i in range(1, 2):
    response = get('https://www.autotrader.co.uk/car-search?sort=sponsored&seller-type=private&page=' + str(i))
    html_soup = BeautifulSoup(response.text, 'html.parser')

    outer = html_soup.find_all('article', class_='search-listing')
    for inner in outer:
        lis = []
        names.append(inner.find_all('a', class_ ="js-click-handler listing-fpa-link")[1].text)
        prices.append(inner.find('div', class_='vehicle-price').text)
        for li in inner.find_all('ul', class_='listing-key-specs'):
            for i in li.find_all('li')[-7:]:
                lis.append(i.text)
        year.append(lis[0])
        body_type.append(lis[1])
        milage.append(lis[2])
        engine.append(lis[3])
        hp.append(lis[4])
        transmission.append(lis[5])
        petrol_type.append(lis[6])

test_df = pd.DataFrame.from_dict({'Title': names, 'Price': prices, 'Year': year, 'Body Type': body_type, 'Mileage': milage, 'Engine Size': engine, 'HP': hp, 'Transmission': transmission, 'Petrol Type': petrol_type}, orient='index')
print(test_df.transpose())

Output:
                                Title Price           Year  Body Type        Mileage Engine Size      HP Transmission Petrol Type
0    Citroen C3 1.4 HDi Exclusive 5dr  £500  2002 (52 reg)  Hatchback  123,065 miles        1.4L   70bhp       Manual      Diesel
1                Volvo V40 1.6 XS 5dr  £585   1999 (V reg)     Estate  125,000 miles        1.6L  109bhp       Manual      Petrol
2  Toyota Yaris 1.3 VVT-i 16v GLS 3dr  £700   2000 (W reg)  Hatchback   94,000 miles        1.3L   85bhp    Automatic      Petrol
3               MG Zt-T 2.5 190 + 5dr  £750  2002 (52 reg)     Estate   95,000 miles        2.5L  188bhp       Manual      Petrol
4       Volkswagen Golf 1.9 SDI E 5dr  £795  2001 (51 reg)  Hatchback  153,000 miles        1.9L   68bhp       Manual      Diesel
5   Volkswagen Polo 1.9 SDI Twist 5dr  £820  2005 (05 reg)  Hatchback  106,116 miles        1.9L   64bhp       Manual      Diesel
6     Volkswagen Polo 1.4 S 3dr (a/c)  £850  2002 (02 reg)  Hatchback  125,640 miles        1.4L   75bhp       Manual      Petrol
7              KIA Picanto 1.1 LX 5dr  £990  2005 (05 reg)  Hatchback  109,000 miles        1.1L   64bhp       Manual      Petrol
8    Vauxhall Corsa 1.2 i 16v SXi 3dr  £995  2004 (54 reg)  Hatchback   81,114 miles        1.2L   74bhp       Manual      Petrol
9           Volkswagen Beetle 1.6 3dr  £995  2003 (53 reg)  Hatchback  128,000 miles        1.6L  102bhp       Manual      Petrol


text:
Q: multiple processes stuck on same cpu after multiple 'fork's (Linux/C) On a multi-core machine, why doesn't the CPU automatically move a process to a new core if there are multiple processes all on the same core at full capacity?
Here is a sample program which reproduces the problem I'm seeing:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

void RunClient(int i) {
  printf("Starting client %d\n", i);
  while (true) {
  }
}

int main(int argc, char** argv) {
  for (int i = 0; i < 4; ++i) {
    pid_t p_id = fork();
    sleep(3);
    if (p_id == -1) {
      perror("fork");
    } else if (p_id == 0) {
      RunClient(i);
      exit(0);
    }
  }

  return 0;
}

This works as expected (when I check top, I see all 4 processes are running at 100%).
However, if I remove the "sleep(3)" line, then sometimes multiple processes are set to the same CPU and thus not running at full capacity (for example, one process might be at 100% while the other 3 are each at 33%). What's going on and how do I fix it?
I know I can manually set the CPU affinity, but that seems like a fragile solution?

A: This isn't an issue with your code, it's an issue with your OS scheduler. It works as expected for me (ubuntu 11.10) both with and without the sleep(3)
But +1 for posting an SSCCE


text:
Q: svg pseudo background-image file not showing on live site but works on localhost why? I have simple svg arrow but it doesn't show when I use as pseudo background-image online but it works fine on my localhost: any idea?
span a:after {
  content: "";
  background-image: url(arrow_right.svg);
  width: 24px;
  height: 18px;
  display: inline-block;
  margin: 0px 0 0 10px;
  position: relative;
  top: 3px;
}

svg:
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 24 18" enable-background="new 0 0 24 18" xml:space="preserve">
<path fill="#F9C32C" d="M19.8,10.1l-6.6,6.4l1.5,1.5L24,9l-9.3-9l-1.5,1.5l6.6,6.4H0v2.1H19.8z"/>
</svg>

A: Add  content-type=image/svg+xml  to your .htaccess file at the root instead of content-type=text/xml


text:
Q: python string to number list python string contains floating point numbers
S = "1,2.5,e,3"
I am trying to convert it to number list by ignoring non-number values.
numbers = ' '.join(c for c in S)

numbers_list = []

for x in numbers:
    if x.isdigit():
        numbers_list.append(x)
print(numbers_list)

Instead of
[1,2.5,3]

it is giving me
['1', '2', '5', '3']

A: S = "1,2.5,e,3"

numbers = []
for x in S.split(','):
    try:
        numbers.append(float(x))
    except ValueError:
        pass

print(numbers)

Output:
[1.0, 2.5, 3.0]


text:
Q: Errors getting Abstract class, interface, and extending class to implement generics without wildcard Its very clear from searching around on SO that this is a problem others have faced. However, I just cannot seem to get the solutions others have offered to compile using generics and not wildcards because of the extra complexity of the interface here.
The code below compiles, but I don't like that I'm using a wildcard and not a generic.
ListSorter.Java
import java.util.List;
public interface ListSorter <T> {
    public List<T> sort(List<T> list);
}

AbstractListSorterTest.java
package com.learning.test.algorithms;

import com.learning.algorithms.sorting.ListSorter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import junit.framework.TestCase;

public abstract class AbstractListSorterTest extends TestCase {
    private List<String> unsortedStringList;
    private List<String> sortedStringList;

    // Eclipse shows "ListSorter is a raw type. References to generic type ListSorter<T> should be parameterized"
    protected abstract ListSorter createListSorter();

    public void testSortSimpleStrings() {
        ListSorter sorter = createListSorter();
        List<?> result = sorter.sort(unsortedStringList);

        assertEquals(unsortedStringList.size(), result.size());

        Iterator<?> actual = result.iterator();
        Iterator<?> expected = sortedStringList.iterator();

        while (actual.hasNext() && expected.hasNext()) {
          assertEquals(expected.next(), actual.next());
    }
 }

If I try the following:
List<T>  result = sorter.sort(unsortedStringList);

I get a compiler error "T cannot be resolved to a type" (which I get for a lot of different type of solutions).
UPDATE
Stuart's answer was spot on and I now have one warning left.
In BubblesortListSorterTest.java, I get the following warning:
The return type ListSorter<T> for createListSorter() from the type BubblesortListSorterTest<T> needs unchecked conversion to conform to ListSorter<Object> from the type AbstractListSorterTest

BubblesortListSorterTest.java
public class BubblesortListSorterTest<T extends Comparable<? super T>> extends AbstractListSorterTest {

  @Override
  protected ListSorter<T> createListSorter() {
    return new BubblesortListSorter<T>();
  }
}

Update 2
After making some additional changes, I finally got everything to work.
BubblesortListSorterTest.java
public class BubblesortListSorterTest extends AbstractListSorterTest {

  @Override
  protected <T extends Comparable<? super T>> ListSorter<T> createListSorter() {
    return new BubblesortListSorter<T>();
  }
}

AbstractListSorterTest.java
protected abstract <T extends Comparable<? super T>> ListSorter<T> createListSorter();

  public void testSortSimpleStrings() {
    ListSorter<String> sorter = createListSorter();
    List<String> result = sorter.sort(unsortedStringList);

    assertEquals(unsortedStringList.size(), result.size());

    Iterator<String> actual = result.iterator();
    Iterator<String> expected = sortedStringList.iterator();

    while (actual.hasNext() && expected.hasNext()) {
      assertEquals(expected.next(), actual.next());
    }
  }

ListSorter.java
public interface ListSorter <T> {
    public List<T> sort(List<T> list);
}

BubblesortListSorter.java
public class BubblesortListSorter <T extends Comparable<? super T>> implements ListSorter<T> {

  @Override
  public List<T> sort(List<T> list) {
    for (int outer = 1; outer < list.size(); outer++) {
      for (int left = 0; left < (list.size() - outer); left++) {
        int right = left + 1;
        if (list.get(left).compareTo(list.get(right)) > 0) {
          swap(list, left, right);
        }
      }
    }
    return list;
  }

  private void swap(List<T> list, int leftPos, int rightPos) {
    T temp = list.get(leftPos);
    list.set(leftPos, list.get(rightPos));
    list.set(rightPos, temp);
  }
}

A: The AbstractListSorterTest wants to test a ListSorter implementation using a list of strings. So the test needs to tell whoever creates ListSorter that T should be String. If one were instantiating ListSorter directly (say, as an anonymous inner class) one would write something like
ListSorter<String> sorter = new ListSorter<String>() { ... };

Instead, you want the sorter instance to be created by an abstract method createListSorter(). Presumably something within this method is going to construct a ListSorter implementation. So you need to pass a type argument through createListSorter() so that it can in turn pass that argument to a ListSorter constructor. The way to do this is to make createListSorter() a generic method:
abstract <T> ListSorter<T> createListSorter();

Then change the point of call in the test to this:
ListSorter<String> sorter = createListSorter();

(The compiler infers that T is String in this case so that you don't have to pass an explicit type argument.)
At this point you can change the subsequent declarations from Iterator<?> to Iterator<String>.
The next issue you will run into is that the ListSorter implementation will not be able to sort objects of arbitrary type T since there is no way to compare them. Either you will have to pass in a comparator object to the ListSorter abstract factory and constructor, or you will have to add type bounds to ensure that T is a subtype of Comparable. Look at the Collections.sort() overloads in the JDK documentation for ideas of the generic type signatures that need to be added.


text:
Q: Spring Security returns 403 Forbidden to expired jwt token. How can I change it to 401 Unauthorized response with custom body? I have created application for generating JWT tokens for users that either logging in or registering.
I have another demo endpoint for getting some data from API.
But because the project is Spring Security it checks if token that has been passed in Bearer Header is valid or not. And It detects the token is expired giving this ExpiredJwtException. I want to catch that exception and return custom Response to Client.
Exception when jwt token is expired:

io.jsonwebtoken.ExpiredJwtException: JWT expired at
2023-02-16T10:54:29Z. Current time: 2023-02-16T12:44:41Z, a difference
of 6612302 milliseconds.  Allowed clock skew: 0 milliseconds.     at
io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:427)
~[jjwt-impl-0.11.5.jar:0.11.5]    at
io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:529)
~[jjwt-impl-0.11.5.jar:0.11.5]    at
io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:589)
~[jjwt-impl-0.11.5.jar:0.11.5]    at
io.jsonwebtoken.impl.ImmutableJwtParser.parseClaimsJws(ImmutableJwtParser.java:173)
~[jjwt-impl-0.11.5.jar:0.11.5]

But It returns 403Forbidden with empty body.
How can I change this response?
This is my SecurityConfiguration class:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration{

    private final JwtAuthenticationFilter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf()
                .disable()
                .authorizeHttpRequests()
                .requestMatchers("/api/v1/auth/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

This is my ErrorHandler:
@RestControllerAdvice
@Log4j2
public class ErrorHandler extends ResponseEntityExceptionHandler {

    private static final String LOG_ERROR = "Error. {} \n{}";
    //There are other methods here that handle other exceptions

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ExpiredJwtException.class)
    public ResponseEntity<ErrorResponse> handleJwtExpiredTokenException(ExpiredJwtException ex) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(new ErrorResponse(ErrorCode.TOKEN_EXPIRED, ex.getMessage()));
    }

}

I explained issue to ChatGpt. It recommended some code changes like adding new AuthenticationEntryPoint and others. But this didn't solve my problem


text:
Q: How can I reuse the escaped value of a query string in PHP? I'd like to reuse a multiple-term search query with + for escaping spaces.
$_SERVER['QUERY_STRING'] results in
q=my+search+term

while $_GET['q'] results in
my search term

How can I get
my+search+term

does it have to be regex?

A: urlencode($_GET['q']);

A: No, you can use str_replace:
$str = str_replace(' ', '+', $str);

but if there are more special characters, urlencode is the better choice:
$str = urlencode($str);

A: $q = str_replace(' ', '+', $_GET['q'])

or
$q = urlencode($_GET['q']);

A: $clean = urldecode($_SERVER['QUERY_STRING']);
http://www.php.net/manual/fr/function.urldecode.php


text:
Q: ElasticSearch Cardinality issue Cardinality Aggregation calculates an approximate count of distinct values. But why even for an index stored in a single shard, it is showing incorrect value?

    GET /jobs/_settings

    {
      "jobs": {
        "settings": {
          "index": {
            "number_of_shards": "1",
    ...

    position_id is long

    GET /jobs/_search
    {
      "size": 0,
      "aggs": {
        "count_position_id": {
          "value_count": {
            "field": "position_id"
          }
        },
        "unique_position_id": {
          "cardinality": {
            "field": "position_id",
            "precision_threshold": 40000
          }
        }
      }
    }

    {
      "took": 44,
      "timed_out": false,
      "_shards": {
        "total": 1,
        "successful": 1,
        "failed": 0
      },
      "hits": {
        "total": 52836,
        "max_score": 0,
        "hits": []
      },
      "aggregations": {
        "unique_position_id": {
          "value": 52930
        },
        "count_position_id": {
          "value": 52836
        }
      }
    }

A: Its more to do with algorithm used to calculate cardinality than single shard in picture.
ES cardinality agg works using HLL ( hyperloglog) which is approximate counting algorithm ( It relies on observation on  binary representation of hash to approximate unique values count )
You can control precision by increasing precision_threshold .So by definition this is "approximate count"  - not really incorrect.


text:
Q: How to have more then one java file in cordova plugin I have plugin.xml file that look like this:
<?xml version="1.0" encoding="UTF-8"?>
<plugin id="pl.jcubic.leash.service" version="1.0.0"
        xmlns="http://apache.org/cordova/ns/plugins/1.0">
  <name>Exec</name>
  <description>Apache Cordova Leash shell service plugin</description>
  <license>Apache 2.0</license>
  <keywords>cordova,exec,runtime,process,shell,command</keywords>
  <js-module name="service" src="www/service.js">
    <clobbers target="service"/>
  </js-module>
  <platform name="android">
    <config-file parent="/*" target="res/xml/config.xml">
      <feature name="Service">
        <param name="android-package" value="pl.jcubic.leash.Service" />
        <param name="onload" value="true" />
      </feature>
    </config-file>
    <source-file src="src/pl/jcubic/leash/Service.java"
                 target-dir="src/pl/jcubic/leash/Service" />
  </platform>
</plugin>

my plugin is in Service.java file but now I want to create super class and put some logic there so my Service.java file look like this:
package pl.jcubic.leash;

public class Service extends ReflectService {

    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        // your init code here
    }

    public String echo(String input) {
        if (input.equals("ping")) {
            return "pong";
        } else {
            return null;
        }
    }

}

and ReflectService.java look like this:
package pl.jcubic.leash;

public class ReflectService extends CordovaPlugin {
    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
    }
   ...
}

but when I've add the plugin and run cordova run android I've got this error:
/home/kuba/projects/jcubic/leash/leash/platforms/android/src/pl/jcubic/leash/Service/Service.java:22: error: cannot find symbol
public class Service extends ReflectService {
                             ^
  symbol: class ReflectService
/home/kuba/projects/jcubic/leash/leash/platforms/android/src/pl/jcubic/leash/Service/Service.java:25: error: cannot find symbol
        super.initialize(cordova, webView);
        ^
  symbol:   variable super
  location: class Service
2 errors

How can I import class from the same package in android/cordova plugin? When I've installed the plugin the ReflectService.java file is there. Do I need to put more then one source-file in xml file? How can I do this?

A: All I need to do is to put another source-file into xml file:
<source-file src="src/pl/jcubic/leash/Service.java"
             target-dir="src/pl/jcubic/leash/Service" />
<source-file src="src/pl/jcubic/leash/ReflectService.java"
             target-dir="src/pl/jcubic/leash/Service" />


text:
Q: Are WM_ERASEBKGND messages posted to the message queue? WM_PAINT messages are not posted to the message queue, but rather when the message queue is empty, the WM_PAINT message is sent to the window procedure (if some area of the window is invalid).
However, are WM_ERASEBKGND messages sent in some similar way, or are they simply posted to the message queue (the documentation don't say anything about this).

A: It is both, not untypical for Windows messages.  It will be sent when the program executes a command like UpdateWindow() or processes a message like WM_SYSCOMMAND that moves or resizes the window.  It will be posted when the program has called InvalidateRect().
Same is true for WM_PAINT, normally a "posted" message but only returned by GetMessage() when the message queue is empty.  It however will be sent when you call UpdateWindow(), ensuring the window is painted when it returns.
Not taking a dependency on those implementation details is pretty important.


text:
Q: cs1513 c# expected unity Hi everyone i'm new to Unity scripting and i cant deal with the problem please someone help me
here is the code:
using UnityEngine;
using System.Collections;

public class testScript  : MonoBehaviour
{
    int i = 1;
    // Use this for initialization
    void Start()
    {

        for (i = 1; i > 6; i++)
        {

            Debug.Log("value of i = " + i);

        }

        Debug.Log("i'm out of the loop");

    } //the problem is cs1513 c# expected unity here(21.line)

    // Update is called once per frame
    void Update()
    {

    }

program i'm using Microsoft Visual Studio
Thanks in advance!!!

A: You only missing } at the end of the script. The last } should close the class {. This was likely deleted by you by mistake. Sometimes, Unity does not recognize script change. If this problem is still there after making this modification, simply close and re-open Unity and Visual Studio/MonoDevelop.
using UnityEngine;
using System.Collections;

public class testScript  : MonoBehaviour
{
    int i = 1;
    // Use this for initialization
    void Start()
    {

        for (i = 1; i > 6; i++)
        {

            Debug.Log("value of i = " + i);

        }

        Debug.Log("i'm out of the loop");

    } //the problem is cs1513 c# expected unity here(21.line)

    // Update is called once per frame
    void Update()
    {

    }
}//<====This you missed.


text:
Q: Rails 3- Devise - Sign in error after login with facebook I setup devise & omniauth to authen,
After login with facebook, i create a user and generate a password for user
user = User.new :fullname => auth_hash['extra']['raw_info']['name'],
:email =>auth_hash['extra']['raw_info']['email'],
:encrypted_password => Devise.friendly_token[0,20]

But when i try to login with my facebook user (http://localhost:3000/users/sign_in) , i have a error :
BCrypt::Errors::InvalidHash in Devise::SessionsController#create
invalid hash

Request
Parameters:
{"utf8"=>"✓",
 "authenticity_token"=>"/xA0goLirKlI2YWSLSMQk+3a8xDrVmrhqIjhILh0OME=",
 "user"=>{"email"=>"xxx@gmail.com",
 "password"=>"[FILTERED]",
 "remember_me"=>"1"},
 "commit"=>"Sign in"}

A: Devise by default uses bcrypt's encrypted password algorithm, and so my guess is that it's having problems with you trying to input the encrypted version of the password manually. Have you tried simply setting a :password value as opposed to :encrypted_password? As in:
user = User.new :fullname => auth_hash['extra']['raw_info']['name'],
:email =>auth_hash['extra']['raw_info']['email'],
:password => Devise.friendly_token[0,20]


text:
Q: Calculating area of a shape with circular boundaries with elementary methods Question. $\square ABCD$ is a square with $AB = 10$. Circle $O$ inscribes the $\square ABCD$. The center of the arc is $A$. What is the area of the colored area?

Explanation: This problem can be solved by integral. But, this problem is from an elementary math book, which means that integral is not a good solution for this.
Our teacher solved this problem with integral, but she was not able to solve it with elementary math. She asked my school students about this problem, but none of us were able to solve it. How can we solve the problem using only elementary math?
Korean elementary math does not contain:

*

*irrationals and imaginary numbers

*functions

*Of course, angle functions (such as $sin$, $cos$, $tan$, etc)

*inscribed angle

*non-linear equations

*similarity and congruence

If you are unsure that you can use certain formulas or something else, comment me and I'll answer you.
Edit 1. Actually, we do not study $\pi$ in elementary school. We just assimilate it to $3.14$. But it's not so important, so let's use $\pi$.

A: Hint
The two yellow areas are equal.
You can easily calculate $$2 \mbox{yellow}+\mbox{blue}+\mbox{purple}=\mbox{Area} ABCD-\frac{1}{4} \mbox{Area} C(A, AB)$$
Next
$$4\mbox{purple}=\mbox{Area} ABCD- \mbox{Area} C(0, OA)$$
Finally
$$\mbox{Blue}=\mbox{Area} (sector \, OEF) -\mbox{Area} (sector \, AEF) +\mbox{Area}(AEOF)$$

A:
Evaluate the areas of the circular sectors ABP and OPE, as well as the quadrilateral APOF and then subtract them from the half square to get the shaded area. (A unit square assumed below.)
With A being the origin, the two circles are
$$r=1; \space \space r(\sin\theta + \cos\theta)=r^2+\frac{1}{4}.$$
Eliminate $r$ to obtain,
$$\sin\beta = \frac{5+\sqrt{7}}{8},\>\>\>\>\>
\sin\alpha = \frac{0.5-\cos\beta}{0.5}=\frac{\sqrt{7}-1}{4}$$
Then, the area of the quadrilateral AFOP which is made of two triangles AFP and FPO, is
$$A_q = \frac{1}{4}\sin\beta +  \frac{1}{4}\left(\frac{1}{2}-\cos\beta \right)=\frac{2+\sqrt{7}}{16}
$$
And the area of the two sectors is
$$A_c=\frac{1}{2}\left( \frac{\pi}{2}-\beta\right) + \frac{\alpha}{8}
=\frac{\pi}{8}-\frac{1}{8}\sin^{-1} \left(\frac{23\sqrt{7}+67}{128}\right). $$
Therefore, the shaded area is
$$A_s=\frac{1}{2}-A_c-A_q=\frac{6-\sqrt{7}-2\pi}{16}+\frac{1}{8}\sin^{-1} \left(\frac{23\sqrt{7}+67}{128}\right). $$


text:
Q: Remove last entry of vector if zero How can I make sure that the last entry of the vector is non-zero?
# Current output
polycoefs("-x^{3}+3x^5-x-3x^3- 3x^5 - 1")
x^0 x^1 x^2 x^3 x^4 x^5
 -1  -1   0  -4   0   0

# Intended output
polycoefs("-x^{3}+3x^5-x-3x^3- 3x^5 - 1")
x^0 x^1 x^2 x^3
 -1  -1   0  -4

A: If:
result = polycoefs("-x^{3}+3x^5-x-3x^3- 3x^5 - 1")
x^0 x^1 x^2 x^3 x^4 x^5
 -1  -1   0  -4   0   0

If you want to make the last entry non-zero:
while(tail(result,1) == 0){
  result = result[-length(result)]
}

That:
> result
x^0 x^1 x^2 x^3
 -1  -1   0  -4

You can add it to your function just before returning result.
If you want to remove all 0s you can do (Idk why keeping x2):
> result[-which(result == 0, arr.ind=TRUE)]
x^0 x^1 x^3
 -1  -1  -4


text:
Q: Run a script inside a div once mouse is clicked before heading to the next page I've been at this for a while. I've managed to get my popup code inserted into the ajax div once the mouse clicks on the video thumbnail image but it doesn't run before going to the next page where the video is. Any ideas?

A: try this example maybe it will help you, change your the url by yours and classes

alert("dddddd"+$(".imgg").attr('id'))
$('.imgg').click(function () {

        $.ajax({
           url:"https://www.radiantmediaplayer.com/test-your-streaming-url.html",                          //     url: "eaeffalkzi.php",
            type: "GET",

            success: function (data) {

              //  var datat = JSON.parse(data);
                alert(data);
  $('#output').html(data);

            }
        });
    });

<button  id='ffff'class="imgg">
</button>


text:
Q: Como validar la hora que seleccionó el usuario sea de formato 24 horas Php,Js,JQuery Buenos días tengo este campo de tipo time en html lo que debo de hacer es validar que la hora que seleccionó el usuario sea en formato 24 horas, debido a que algunos computadores de los usuarios estan en ingles, no he podido encontrar como validar esa hora alguien me puede hacer el favor de ayudarme?
<input type="time" name="HoraEntradaEstablecida" id="HoraEntradaEstablecida" >


text:
Q: Return statement while using worker thread Do I always have to return something using Worker Thread in Swing? What if I don't have any return value? I just want to use the worker thread to run an infinite for loop... so what to return? and even if I write a dummy return statement after the infinite for loop, say for e.g return 0; then also it will probably say "code not reachable".

A: I suspect you haven't tried it. The code you've suggested in the comment should work fine:
public Object construct() {
  for (;;) {
    Node.execution();
    Clock.incrementTimeTick();
    System.out.println(Clock.getTimeInTick());
    repaint();
  }
  // End of loop is unreachable, so no need for a return statement.
}

A tight loop like this seems like a bad idea to me, and the repaint() code will need to be made appropriately thread-safe, but it should compile...
Personally I prefer to use while (true) for "forever" loops, but for (;;) should work too.

A: Implement the worker as SwingWorker<Void, SomeObject> and just return null. Trick the compiler about the infinite loop. Make it depending on some method that in the runtime always return true.

A: A method like the follow will compile without any compilation errors:
public Object foo() {
    for (;;) {
        // do something ... or nothing
    }
}

The reason is that any statement following the for loop is unreachable, according to the rules set out in the JLS 14.21.  Specifically

*

*Any for loop with no condition expression (or a condition expression that is a compile-time constant expression with value true) cannot "complete normally".

*Any statement in a block that is preceded by a statement which cannot complete normally is unreachable.


text:
Q: Sparse graphs that are hard to color I am interested in knowing if there are any types of graphs that are very sparse, perhaps consisting of just connections between paths and cycles, and for which $k$-coloring is $\mathsf{NP}$-hard for some $k \in \mathbb{N}$.
I know a single cycle and path are very easy to color. Are there types of graphs that, when combined in a clever way, become hard to color?

A: Barbanchon proved that 3-colorability of planar graphs is NP-complete and the number of 3-colorings of a planar graph is parsimoniously #P-complete after dividing by 6.  This is a really nice hardness result that immediately implies a sparseness result, since the average valence of any planar graph is less than 6.   Although I do not really know, I suspect that his construction can yield some uniform upper bound on the valence of all vertices.
If you just want NP-hardness and bounded valence, it's easier than planarity.   The standard method to show that 3-colorability is NP-hard is to first show that 3-coloring extension is NP-hard by replacing 3-SAT clauses or even logic gates with partially colored subgraph gadgets.   In a typical scheme, if the colors are red, green, and blue, red and blue represent 0 and 1 in a Boolean circuit, while green is the "control" color.   As a final step, all of the precolored vertices are identified together into a complete graph on 3 vertices (a triangle) which is called the palette.   The three colors of the palette are arbitrary and are logically called "red", "green", and "blue"; and then coloring the rest of the graph can be equivalent to any coloring extension problem.  It is not hard to generalize this to $k$-coloring with larger $k$:  You have a larger palette, and you can force all of the uncolored vertices of the graph to be (notional) red, green, and blue and not really use the other colors.
Circuit satisfiability is easily NP-hard for circuits with bounded valence.  The valence is automatically bounded except for fanout, and you can make the fanout at most 2 locally with a cheap step such as inserting NOT gates between partial fanouts.   So, the only remaining issue is that the valence is very high at the palette itself.  It is not hard to replicate the palette with a bounded-valence gadget and then spread out the use of the palette across many copies.
Of course, as John Machacek points out, if you have a sufficiently severe bound on valence, then a coloring must exist or can be found in polynomial time, e.g., by the greedy algorithm in the baby Brooks theorem.  (The baby Brooks theorem say that the chromatic number is at most the max valence plus 1; the more serious theorem reduces the upper bound by 1 except in the case of a complete graph or an odd cycle.)

A: If we consider very sparse graphs to be subcubic graphs (i.e. graphs with maximum degree at most 3) as suggested in the comments, the answer is that vertex coloring is never hard. Coloring of subcubic graphs can be done in polynomial time.
Let $G$ be a  connected subcubic graph. By Brooks' Theorem the graph $G$ is $3$-colorable unless $G = K_4$. Moreover, it is easy (for any graph) to decide if it is $1$-colorable or $2$-colorable. This shows the decision problem is easy for subcubic graphs. Actually producing a coloring can also be done efficiciently.  For example, one can the algorithm in $\Delta$-list vertex coloring in linear time by Skulrattanakulchai.


text:
Q: JS File Loading Selectively I am working with contextMenu.js, and it was mostly working fine. Technically, it's still working fine when the page has a low load of things to do, but when there is also a form loaded on the page there runs a risk of this error:
TypeError: $(...).contextMenu is not a function

It's not that it simply hasn't loaded yet. I can wait a long time and try to add the context menu and I still get the error. It seemingly happens at random, although certain pages are more prone than others I can load the page 10 times and get the error nine of the times. Other pages I'll get the error one out of ten times. Essentially, on occasion it doesn't see the contextMenu function and other times it does.
I've already played around with the load order, and jquery is the first thing to load and I can still use jquery throughout the rest of the document, so I don't think it's a problem with jquery. I'm at a loss, any ideas?
Here's my code:
function createSavedReportsMenu(name, location, report, fileNumber){
// creates the popup menu for the saved reports area

var menu = [{  //begin first item on the pop up menu
    name: 'Run Report', // the name that is displayed for the first button
    img: '/Reports/images/run.png', // display an image
    title: 'run button', // mouse over text
    fun: function () {
       //do something
    }
}, {
    name: 'Load Parameters',
    img: '/Reports/images/load.png',
    title: 'load button',
    fun: function () {
        //do something
    }
}, {
    name: 'Rename Report',
    img: '/Reports/images/rename.png',
    title: 'rename button',
    fun: function () {
        //do something
    }
}, {
    name: 'Delete',
    img: '/Reports/images/delete.png',
    title: 'delete button',
    fun: function () {
          //do something
    }
}];
var reportDiv = "#file" + fileNumber;
try{
$(reportDiv).contextMenu(menu);
}catch(err){
    alert(err);
}

}


text:
Q: How do I add a cover page in Freemarker? I'm working with Freemarker (mainly to generate quotes from our web-based accounting system). I've figured out headers/footers which work great but what I'd like to do is add a COVER PAGE so that the first page is a cover page, and then the generated quote is below that.
Now I could just throw in some HTML to make it look nice with a bunch of spaces to bring everything down, but I'd like to insert the TITLE from my accounting system's quote on the cover page. My fear is if someone puts in a title that is say 3-4 lines, it'll throw off the look later.
So is there a way I can specify in my code that "this is my cover page"


text:
Q: git how to confirm that l am behind the git repository l can use git status to confirm what file l modified locally, but l don't know how to confirm that l am behind the git repository.
l always find out it when l push my code to git, or git pull before git push anytime. but l think it's not a smart way. l tried to google, but found nothing(maybe keywords' problem)
git add .
git commit -m "xxx"
git push
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to
'git@code.xxx.com/xxxx'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

A: The usual way to answer this question locally is to do a git fetch.  This will update the local tracking branch origin/master, which is what Git uses locally to figure out whether your local master branch is ahead or behind of the true remote master branch.  So all you need to do here is the following:
git fetch origin
git status

You might see output looking something like the following:
This branch is 2 commits ahead and 2 commits behind master

If this were your status, it would imply that you had made two commits since the point when you last synched.  And it would also mean that other people had laid down two commits to the remote master branch since the last sync.

A: When someone else has pushed some new features or code you have to pull them first to get the new changes and merge them with your local state. If you have some conflicts you have to merge them and then you can push.
So i don't understand your problem that is the normal way.


text:
Q: Given that $3\mathsf P(A\cap B)=2 \mathsf P(A'\cap B) = \mathsf P(A'\cap B')$ and $\mathsf P(A\cap B)=3/5$, what is $\mathsf P(A\mid B')$? $A$ and $B$ are two events such that, $\mathsf P(A\cap B)=3/5$.
Given that $3\mathsf P(A\cap B)=2 \mathsf P(A'\cap B) = \mathsf P(A'\cap B') = x$. Find $\mathsf P(A\mid B')$.
Attempt:
$$P(B')=P(A \cap B')+P(A' \cap B')$$
Considering the conditions given
$$3P(A \cap B)=P(A' \cap B')$$
Therefore
$$P(A' \cap B')=3P(A \cap B)$$
But $P(A \cap B)=\frac 35$.
thus $P(A'\cap B')=3\times\frac35=\frac95$
This is where I am confused after getting a probability which is greater than $1$.

A: Use the following:
$$\begin{align}\text{By definition of conditional probability:}
\\
\mathsf P(A\mid B') &= \dfrac {\mathsf P(A\cap B')}{\mathsf P(B')}
\\
\text{By the Law of Total Probabitity:}
\\ \mathsf P(B') & = \mathsf P(A\cap B')+\mathsf P(A'\cap B')
\\ \mathsf P(B) & = \mathsf P(A\cap B)+\mathsf P(A'\cap B)
\\
\text{By definition of complementary probability:}
\\ \mathsf P(B') &= 1-\mathsf P(B)
\end{align}$$


text:
Q: (intergation) area of region bounded by a curve and a line with unknown a Let $S1$ be the area of the region bounded by the curve $y = x^2$ and the lines $y = ax, (0 < a < 1)$, and let $S2$ be the area of the region bounded by the curve $y = x^2$, the lines $y = ax, (0 < a < 1)$ and the line $x = 1$, where $a$ is the same constant.
(a) Find the value of $a$ that minimizes the value of $S1 + S2$. What is the minimum value?
(b) Find the volume of the solid generated by revolving the region, that takes the minimum value of $S1 + S2$, about the x-axis.
I find $S1 = \displaystyle \frac{a^3}{6}$ and $S2 = \displaystyle \frac{a^3}{3} - \frac{a}{2} + \frac{1}{3}$, but how can I calculate the value of $a$?

A: You have calculated value of $\small S_1$ and $\small S_2$ correctly. Now to find value of $a$ that minimizes $ \small S = S_1+S_2$, take the derivative of $S$ with respect to $a$ and equate to zero.
$\small S = S_1 + S_2 = \displaystyle \frac{a^3}{3} - \frac{a}{2} + \frac{1}{3}$
$\small S' = \displaystyle a^2 - \frac{1}{2} = 0 \implies a = \frac{1}{\sqrt2}$
That leads to minimum area of $\small S_1 + S_2 = \displaystyle \frac{\sqrt2 - 1}{3 \sqrt2}$
Now you need to find volume of solid generated by revolution of the region about x-axis $\big($for $a = \displaystyle \small \frac{1}{\sqrt2}\big)$. For $\small S_1$, both shell and washer methods are fine. For $\small S_2$, it is easier to apply washer method as the shell method will require you to split the integral into two.


text:
Q: Using gdata with channel or user I am trying to use the YouTube API v2.0 to retrieve videos from a user account.
i was able to receive videos from this account
http://gdata.youtube.com/feeds/users/REMAXIntl/uploads?alt=json-in-script&callback=showMyVideos2&
but when i try to use this account:
http://www.youtube.com/channel/UC8dWY6fFXoqcMWPIqdN8JyA
I don't receive any videos. I think this may have to do with the url being different MEANING one points to users and one point to channels. I would really appreciate a nudge in the right different to resolve this issue. Thanks in advance :)

A: There are no videos in the channel with id "UC8dWY6fFXoqcMWPIqdN8JyA". There's a playlist, but it doesn't contain videos from that channel.
In general, you can just substitute in channel ids wherever you used to use a legacy username when constructing a GData API v2 URL. This is explained in more detail in this guide: https://developers.google.com/youtube/v3/guides/working_with_channel_ids


text:
Q: How to adjust date range aggregation values on date field? Iam trying to group docs using a date field in each docs. I need to groub them by docs from last 30days, from 30-60 days, from 60-90. by applying the following range aggs. I got a totaly wrong date ranges.
{
  "aggs": {
    "dateRanges": {
      "date_range": {
        "field": "date",
        "keyed": true,
        "format": "yyyy-mm-dd",
        "ranges": [
            {"from": "now/d",
              "to": "now/d-1M",
              "key": "Last 30 Days"
            },
            {"from": "now/d-1M",
              "to": "now/d-2M",
              "key": "Last 60 Days"
            },
            {"from": "now/d-2M",
              "to": "now/d-3M",
              "key": "Last 90 Days"
            }
          ]

      }
    }
  }
}

Current results:
  "aggregations" : {
    "dateRanges" : {
      "buckets" : {
        "Last 90 Days" : {
          "from" : 1.585008E12,
          "from_as_string" : "2020-00-24",
          "to" : 1.5825024E12,
          "to_as_string" : "2020-00-24",
          "doc_count" : 0
        },
        "Last 60 Days" : {
          "from" : 1.5876864E12,
          "from_as_string" : "2020-00-24",
          "to" : 1.585008E12,
          "to_as_string" : "2020-00-24",
          "doc_count" : 0
        },
        "Last 30 Days" : {
          "from" : 1.5902784E12,
          "from_as_string" : "2020-00-24",
          "to" : 1.5876864E12,
          "to_as_string" : "2020-00-24",
          "doc_count" : 0
        }
      }
    }
  }
}

why does each bucket has the same 'from' and 'to' values?

A: All seems correct except that your date format is wrong, you need to make the following change
    "format": "yyyy-MM-dd",
                    ^^
                    ||
          month instead of minutes


text:
Q: Hard symbolic link directory I am taking over control of a server and I have found a directory in two different locations:
/var/www
/home/user.name (i.e., ~/)

that have the exact same inode number:
ls -i
11895253 directory.name

I had thought that hard links on directories were entirely impossible. What is this then? How does a folder exist in two places at once with the exact same contents?

A: It's a "bind mount". From the mount man page:

The bind mounts.
  Since Linux 2.4.0 it is possible to remount part of the file hierarchy somewhere else. The call is

 mount --bind olddir newdir

See also http://backdrift.org/how-to-use-bind-mounts-in-linux and http://backdrift.org/how-to-use-bind-mounts-in-linux.


text:
Q: Stack ggplot plots with same axes dimensions I have the following hypothetical example:
library(ggplot2)
library(gridExtra)

# df1
descr <- c("aaa","bbb","ccc")
v1 <- c(10,20,30)
df1 <- data.frame(descr,v1)

# df2
descr <- c("aaa","bbb","ccc")
v11 <- c(11111,22222,33333)
df2 <- data.frame(descr,v11)

# plot 1
p01 <- ggplot() +
  geom_point(data = df1, aes(x=descr, y=v1,color=v1), size=5))

# plot 2
p02 <- ggplot() +
  geom_point(data = df2, aes(x=descr, y=v11, color=v11), size=5)

# put them together and save
p_both <- arrangeGrob(p01,p02,nrow=2)
ggsave(file="testSave.png",p_both, width = 10, height = 15, units = "cm")

As you can see, the axes don't line up. I am aware that in this particular example I could turn the dfs into long format and use faceting, but that is not the point.
Is it possible to manually manipulate the axes to make them match up, so that the inner plots are the exact same dimensions?
Thanks!

A: How about trying the patchwork package?
library(tidyverse)
# install.packages("devtools")
devtools::install_github("thomasp85/patchwork")
library(patchwork)

p01 + p02 + plot_layout(ncol = 1)


text:
Q: Text that changes with the date I have been searching for a while and need help figuring out how to make text change depending on the date. I am traveling and people want to know where I am when, so I was going to post a "where am i now" section on my website.
For example, today I need it to say Dominican Republic, tomorrow Haiti, etc. for the next few weeks.
This is what I have so far but I have no idea if I'm doing it right. Not experienced at all with this!

Where am I now?

Dominican Republic

Haiti

Jamaica

Thank you for your help!

A: getMonth() is 0 based, yo you need to add +1 to get current month;

var date=new Date();
var year=date.getFullYear();
var month=date.getMonth() + 1;
var day=date.getDate(); // fixed
(function SetDivContent() {

    if (year == 2017 && month == 6) {
        if (day == 8) {
            $("#first").css("display","block");
        }
        else if (day==9) {
            $("#second").css("display","block");
        }
        else if (day==10) {
            $("#third").css("display","block");
        }
    }
})();
#first,#second,#third {
    display:none;
}

Where am I now?

Dominican Republic

Haiti

Jamaica


text:
Q: How do I prevent ^C from showing when displayed when pressing CTRL+C I am trying to prevent ^C from showing when a user presses CTRL+C while my script is running.
Why do I want to prevent that?
Because things like this will happen and it does not look nice:
$ python3 myscript.py
^CYour pressed CTRL+C

I know there is a similar question here, but it does not work in Python

A: I found an easy method!
# Returning the cursor to home and dont create a new line
print("\r", end="")

# Now we are able to print on the line where ^C would be displayed
print("Your pressed CTRL+C")

A:
Because things like this will happen...

Just my two cents: the fact that ^C displays in the terminal is a good thing. It's confirmation that SIGINT was sent to the process, as expected. Don't try to remove it; instead, as others have suggested, start a new line if you really want to. Or just exit without printing anything additional at all, like lots of other command line applications.