text:
Q: Rewriting a Java HttpURLConnection method using C# HttpClient I've got a working Java method that uses java.net.HttpURLConnection that I should re-implement in C# using the .NET HttpClient.
Java method:
public static String getMyThingAPIToken() throws IOException{
    URL apiURL = new URL("https://myThingAPI/token");
    HttpURLConnection apiConnection = (HttpURLConnection) apiURL.openConnection();
    apiConnection.setRequestMethod("POST");
    apiConnection.setDoOutput(true);
    String apiBodyString = "myThingAPI login id and secret key";
    byte[] apiBody = apiBodyString.getBytes(StandardCharsets.UTF_8);

    OutputStream apiBodyStream = apiConnection.getOutputStream();
    apiBodyStream.write(apiBody);

    StringBuffer apiResponseBuffer;
    try (BufferedReader in = new BufferedReader(new InputStreamReader(apiConnection.getInputStream()))){
        String inputline;
        apiResponseBuffer = new StringBuffer();
        while((inputline = in.readLine()) != null) {
            apiResponseBuffer.append(inputline);
        }
    }
}

So far, my C# looks like below, and you'll notice that this early form of my implementation does not interpret the response.  Nor does it have a string return type required for the token string.
This is because when I test it, the response has:
StatusCode: 400
ReasonPhrase: 'Bad Request'
So something in my apiBody byte array or use of PostAsync must be different to what the Java method does, but I cannot work out what it could be.
public async static Task<HttpResponseMessage> getMyThingAPIToken(HttpClient client)
{
    var apiURI = new Uri("https://myThingAPI/token");
    string apiBodystring = "myThingAPI login id and secret key";
    byte[] apiBody = System.Text.Encoding.UTF8.GetBytes(apiBodystring);
    var response = await client.PostAsync(apiURI, new ByteArrayContent(apiBody));
    return response;
}

A: The Java code doesn't specify a type which means that by default the request uses application/x-www-form-urlencoded. This is used for FORM POST requests.
The default content type for ByteArrayContent on the other hand is application/octet-stream while for StringContent it's text/plain.
FORM content is used through the FormUrlEncoodedContent class which can accept any Dictionary<string,string> as payload.
The input in the question is not in a x-www-form-urlencoded form so either it's not the real content or the API is misusing content types.
Assuming the API accepts proper x-www-form-urlencoded content, the following should work:
var data=new Dictionary<string,string>{
    ["login"]=....,
    ["secret"]=.....,
    ["someOtherField"]=....
};
var content= new FormUrlEncodedContent(data);
var response=await client.PostAsync(apiURI,content);

To send any text using application/x-www-form-urlencoded, we need to specify the content type in StringContent's constructor:
var contentType="application/x-www-form-urlencoded";
var content= new StringContent(apiBodyString, Encoding.UTF8,contentType);
var response=await client.PostAsync(apiURI,content);

A: Can you try using following code:
                    client.BaseAddress = new Uri("https://myThingAPI/");
                    var message = new HttpRequestMessage(HttpMethod.Post, "/token");

                    // Add your login id and secret key here with the format you want to send
                    message.Content = new StringContent(string.Format("userName={0}&password={1}", UserName, Password));
                    var result = await client.SendAsync(message);
                    return result;


text:
Q: Fast hiding of intersecting rectangles I'm working on an efficient algorithm to "hide" all the pairs of intersecting rectangles laid out in 2D in a set of N rectangles (axis aligned).
All the rectangles have the same width and height.
Suppose my starting set of rectangles laid out in 2D is
R={r_1,r_2,...,r_n}
where r_i are all the rectangles, r_i has the boolean attribute visible.
I want to find the subset S of R such that for every r_i, r_j belonging to S r_i,_r_j don't intersect.
A first trivial solution is the brute force-maximal independent set approach.
First I iterate over N(N-1)/2 rectangles (a given rectangle doesn't intersect with itself)  and check if they intersects or not. Contemporaneously I also put all the rectangles in the set R as the nodes of a graph G=(V,E). Edges in that graphs are represented by the pairs of intersecting triangles.
The set of non intersecting rectangles is then one maximal independent set of the graph.
I think this is not the fastest approach, although correct. I've read in some discussion for example how sorting in advance the list of rectangles by their x coordinate would speed up the computation of intersecting rectangle pairs to O(nlog(n) ) (rather than brute force O(n^2).
Now I'm asking, do someone know a better algorithms for such problem (both for the computation of intersecting pairs in a set of rectangles and for the filtering of those rectangles?)
Reformulating the problem as SAT problem can also be interesting, although this idea just came up to my mind. The problem would be here to find that permutation of visible attributes such that no visible rectangle intersects another one.

A: Yes you should sort the rectangles by x.
Since your rectangles are on the same x axis and are the same height, after you sort them, you should be able to find the intersection in linear time. The algorithm you're looking for is called scan line.
You move a scan line over all your rectangles (jump from their x coords in the set you just sorted) and see which ones intersect at current x location. Load all the x coord overlapping rectangles into a datastructure and check if they intersect (based on y coord).

A: There may not be only one subset S. For example, consider the following layout of rectangles:
     +-----+
     |     |
     |  A  |
+----|    +-----+
|    +----|     |
|  D  |   |  B  |
|     |--- +    |
+-----+    |----+
     |  C  |
     |     |
     +-----+

Both {A,C} and {B,D} are valid answers. So, the problem is somewhat ill-defined. Are you looking for the maximal cardinality subset?

A: Testing all pairwise combinations is a good idea, but being O(n^2) it helps to find ways to speed it up.
Partition the space into a coarse grid, like a checkerboard, with each cell having a list of rectangles it owns.   This means the center point of a rectangle is in the cell.  This assigning of rectangles to cells is O(n).
The cells must be comfortably larger than the size of a rectangle, perhaps twice that, and the whole space needs to be divided into "several" rows and columns - say a dozen, hundreds, however many makes sense for the number of rectangles and the size of the area they inhabit.  At least five rows and five columns, though, or else you won't gain much efficiency.
Then test all pairwise combinations within each cell.  This will eliminate a bunch of overlapping pairs.   For each cell, you must also test all pairwise combinations involving the eight neighboring cells - the ones sharing a side or corner - since a rectangle can overlap up to four cells.   Be careful not to double count pairs, of course.
Execution time is saved because you'll never test any pairs where one rectangle is way over here and the other is over in yon faraway area.
This technique is general and could apply to any shapes, and resembles techniques used by physicists in simulating huge systems of particles such as stars in galaxies.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to backup an Azure SQL database which contains encrypted stored procedures I have an Azure Powershell script that I have used to create a .bacpac file from an Azure SQL database.  It works fine on a basic test database (AdventureWorks), but now that I am trying to use it on a database which contains encrypted stored procedures I am getting the following error:
Error SQL71564: Error validating element [dbo].[encryptedSPROCName]: The element [dbo].[encryptedSPROCName] cannot be
deployed as the script body is encrypted.

The stored procedures were created externally, so I do not have access to try to decrypt them.
The code block that I am using is:
$exportRequest = New-AzureRmSqlDatabaseExport -ResourceGroupName $ResourceGroupName -ServerName $ServerName `
-DatabaseName $CopyDatabaseName -StorageKeytype $StorageKeytype -StorageKey $StorageKey -StorageUri $BacpacUri `
-AdministratorLogin $Administratorlogin -AdministratorLoginPassword $AdministratorLoginPassword

Is there a way using Powershell to omit the encrypted stored procedures when executing the backup?

A: Excluding Specific Object while export/import is not supported!!
However you can exclude certain object types using sqlpackage.exe ExcludeObjectType=StoredProcedures.
More options and info here - Export Parameters and Properties
Hope this helps!


text:
Q: Could not load file or assembly System.Net.Http Version=4.0.0.0
Could not load file or assembly 'System.Net.Http, Version=4.0.0.0,
  Culture=neutral, PublicKeyToken=bfgf5f6f11d50abb'. The system cannot
  find the file specified

Does anyone have any experience with this kind of issue? It is a .net core 1.1 application, I have seen several solutions for similar problems, but they did not seem to work.
at System.Net.HttpWebRequest..ctor(Uri uri)
 at System.Net.WebRequest.HttpRequestCreator.Create(Uri Uri)
 at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
 at System.Net.WebRequest.Create(String requestUriString)
 at _6h.lt.Models.reg_class.<complete_payment>d__7.MoveNext()

A: removing this helped to solve the problem:
left click project file, then click edit some.csproj and then simply delete this and save the file.
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.3" />


text:
Q: Offline messages are not consumed in Moquette with Paho Client I have an issue with respect to consuming offline MQTT messages in Moquette server through eclipse Paho client.
Following are the steps which I have followed.

*

*Created and spinned up the Moquette MQTT broker.

*Created a simple MQTT consumer application using eclipse Paho client.

*Set consumer to consume data on topic : "devices/reported/#" with QOS : 1 and CleanSession : False

*Created a simple MQTT data publisher to publish data to MQTT broker using Eclipse Paho.

*Used MQTT data publisher to publish messages to : "devices/reported/client_1" topic with QOS : 1

Above steps were successful without any issue.
Then I stopped my consumer application and sent MQTT data to broker with the same topic. using my publisher application - Server was able to receive these messages but in this moment there was no any consumer to consume this message since I have stopped my consumer.
Then I started my consumer application again. It was connected to the broker successfully but, it did not receive any message which I sent to broker while the consumer shutdown.
Do I need to do any specific configuration to my Moquette server to persist data (with clean session : false) ?
Or am I missing something ?
Please find my sample code below,
Moquette Server initialization
package com.gbids.mqtt.moquette.main;

import com.gbids.mqtt.moquette.server.PublishInterceptor;
import io.moquette.interception.InterceptHandler;
import io.moquette.server.Server;
import io.moquette.server.config.IConfig;
import io.moquette.server.config.MemoryConfig;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class ServerLauncher {

    public static void main(String[] args) throws IOException {
        Properties props = new Properties();
        final IConfig configs = new MemoryConfig(props);

        final Server mqttBroker = new Server();
        final List<? extends InterceptHandler> userHandlers = Arrays.asList(new PublishInterceptor());
        mqttBroker.startServer(configs, userHandlers);

        System.out.println("moquette mqtt broker started, press ctrl-c to shutdown..");
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.out.println("stopping moquette mqtt broker..");
                mqttBroker.stopServer();
                System.out.println("moquette mqtt broker stopped");
            }
        });
    }
}

MQTT Consumer
package com.gbids.mqtt.moquette.main;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class ConsumerLauncher implements MqttCallback {

    private static final String topicPrefix = "devices/reported";
    private static final String broker = "tcp://0.0.0.0:1883";
    private static final String clientIdPrefix = "consumer";

    public static void main(String[] args) throws MqttException {
        final String clientId = "consumer_1";
        MqttClient sampleClient = new MqttClient(broker, clientId, new MemoryPersistence());
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(false);
        sampleClient.connect(connOpts);
        sampleClient.subscribe(topicPrefix + "/#", 1);
        sampleClient.setCallback(new ConsumerLauncher());
    }

    public void connectionLost(Throwable throwable) {
        System.out.println("Consumer connection lost : " + throwable.getMessage());
    }

    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        System.out.println("Message arrived from topic : " + s + " | Message : " + new String(mqttMessage.getPayload()) + " | Message ID : " +mqttMessage.getId());
    }

    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        System.out.println("Delivery completed from : " + clientIdPrefix + "_1");
    }
}

MQTT Publisher
package com.gbids.mqtt.moquette.main;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class ClientLauncher {

    private static final String content = "{\"randomData\": 25}";
    private static final String willContent = "Client disconnected unexpectedly";
    private static final String broker = "tcp://0.0.0.0:1883";
    private static final String clientIdPrefix = "client";

    public static void main(String[] args) throws Exception{
        sendDataWithQOSOne();
        System.exit(0);
    }

    private static void sendDataWithQOSOne(){
        try {
            final String clientId = "client_1";
            MqttClient sampleClient = new MqttClient(broker, clientId, new MemoryPersistence());
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(false); // for publisher - this is not needed I think
            sampleClient.connect(connOpts);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(1);
            final String topic = "devices/reported/" + clientId;
            sampleClient.publish(topic, message);
            System.out.println("Message published from : " + clientId + " with payload of : " + content);
            sampleClient.disconnect();
        } catch (MqttException me) {
            me.printStackTrace();
        }
    }
}

A: In your case you need to set the retained flag to true when creating the MqttMessage in your ClientLauncher (publisher). The default value is false as in the documentation.
...
message.setRetained(true)
...

Setting this flag enables messages to be retained on the broker and be sent to newly connected clients. Please be aware, that the broker only keeps the last message for a topic. There is no way to keep more than one message for a specific topic.


text:
Q: DRF - Dynamically adding fields - (first time works, then throwing error) I want to modify a serializer such that it contains FIELD_display field for every field which has any choices, the value is get_FIELD_display.
I'm trying to dynamically add those fields inside __init__ method and it works but then, after refresh it raises error:
Field name `ownership_display` is not valid for model `RealEstate`.

serializer
class ApiRealestateSerializer(serializers.ModelSerializer):

    class Meta:
        model = RealEstate
        fields = [x.name for x in RealEstate._meta.fields]

    def __init__(self, instance=None, data=None, **kwargs):
        super().__init__(instance, data, **kwargs)
        self.set_display_fields()

    def set_display_fields(self):
        """adds FIELD_display field for every CharField (eg. name = "peter", name_display = "Peter" )"""
        for field in RealEstate._meta.fields:
            if field.choices:
                fieldname = f"{field.name}_display"
                self.fields[fieldname] = serializers.CharField(source=f'get_{field.name}_display')
                self.Meta.fields.append(fieldname)

Do you know how to make it work?

A: The first thing I notice is that you're calling super().__init__ before you set your display fields, so it's possible that the parent class method is throwing that error because when it is checking for the fields they don't exist yet, however you didn't post the full traceback and you didn't post enough for me to replicate.
It would be good to tell us exactly what you really want, because the pattern you're engaged in for that serializer looks... not good.


text:
Q: If $P(X \geq k) = p^k$, for $k=0, 1, 2,...$ then $P(X=k)=p^k(1-p)$ If $P(X \geq  k) = p^k$, for $k=0, 1, 2,...$ then $P(X=k)=p^k(1-p)$
The converse is immediate but I don't know how to approach the direct implication.

A: HINT:
$$P(X=k) = P(X \geq k) - P(X \geq k+1)$$

A: $P(X=k) = P(X \ge k) - P(X \ge k+1) = p^k - p^{k+1} = p^k (1-p)$


text:
Q: c++ Set as an class member variable with a class function object I need to have set as a class member variable, but also need it's comparision function object use the attributes of the class.
class Example
{
   int _member1;
   set<string, MyCmp> _myNameSet;

   class MyCmp
   {
      Example& myEx;

      MyCmp( const Example& ex) {
         myEx = ex;
      }

      bool operator() (const string& lhs, const string& rhs)
      {
         /// Use "_member1" here ...

         myEx._member1;

         /// Do something ....
      }
   }
};

So here my question is, how do i pass the Example object as an argument to the MyCmp constructor? Since the "_myNameSet" is an member variable.
If it was not an member variable, there is a way i know:
void Example::functionBlah()
{
   MyCmp obj(&(*this));
   set<String, MyCmp> myLocalSet(obj);
}

A: You may use initializer list in constructor:
class Example
{
public:
    Example() : _member1(0), _myNameSet(this) {}

    Example(const Example&) = delete;
    Example& operator = (const Example&) = delete;

    // Other stuff
private:
   int _member1;
   set<string, MyCmp> _myNameSet;
};


text:
Q: Testing iOS subscriptions upgrade/downgrade on sandbox At the moment, we have one auto-renewable subscription on our live app, and we want to add two more, where the only difference is the price and the subscription time. To accomplish that, we created a "subscription group" and everything is set up on the apple side:

and the app is currently reading all the packs from the store and allow the user to buy them.
Our issue is that we can't fully test the upgrade/downgrade feature when trying to buy another subscription level on sandbox (iOS 14.5). If we buy the lowest pack first, and then try to buy a superior pack, a popup should appear saying that we want to modify our current subscription plan to another one and that it will start on XX/XX/2021 as seen here (image from a tutorial):

This is not the behaviour we are seeing on our app (on sandbox). When we try to buy a superior plan the app shows the normal purchase popup:

and it proceeds to buy the pack normally without showing the popup warning that we are changing our current plan.
This causes some concerns, as it implies that the user is buying two subscriptions. They are on the same subscription group, so it should be impossible, but still brings concerns... Did anyone experienced the same issue? Is this the normal behaviour in sandbox?


text:
Q: call bash script in script not found, directory is in $PATH I have added a directory to my PATH variable to access all my bash scripts. I add the PATH globally on the system under /etc/profile.d/custom.sh as follow:
export PATH=$PATH:/usr/local/bin/helper

This works, but when I call them in another script they are not found. Only if I use the full path to there location or I add a source /etc/profile.d/custom.sh at the top of an script they run.
All Scripts have a #!/usr/bin/env bash at the top.
Is there another way, or have I missed something?

A: What might happen is that the default scripts are overwritten by your local custom scripts (you may have modified it locally or just simply forgot to execute default scripts).
Try to add a call to the custom.sh script in your user scripts (at the bottom of ~/.bashrc file):
# Running custom.sh
source /etc/profile.d/custom.sh


text:
Q: SQL Query Last Three Full Months (Excluding Current Month) I have a database with millions of rows and many years of data.  I'm currently using PowerBI to query the data (ODBC connection), but I don't want to pull everything.  (Recent convert from Crystal.)  Instead, I'm trying to write a clause into my WHERE statement to only query the last three full months of data (excluding the current month.)  So, today being Jan 25,2023 I want to capture Oct 1 2022 - Dec 31 2022.  I would then schedule this so it always pulls the last three months.
My dataset does contain a field that stores the date so I'm trying to write something like the below that I'm able to use to pull previous days.
"Table"."OrderDate" >= DATEADD(d,DATEDIFF(d,0,CURRENT_TIMESTAMP)-1,0) AND
"Table"."OrderDate" < DATEADD(d,DATEDIFF(d,0,CURRENT_TIMESTAMP),0))

Everything so far that I've tried (and found online) gives odd results.  Pulls Nov - Jan and the like.
Thank you for any help you can provide.

A: You can use the following query to pull the last three full months of data. This query uses the DATEADD and DATEDIFF functions to calculate the date range for the last three full months.
WHERE "Table"."OrderDate" >= DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP) - 3, 0) AND "Table"."OrderDate" < DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)


text:
Q: SSD partitioning If I partition a SSD, will it really partition the drive physically or will the SSD Controller (for example Samsung Phoenix) fool the OS that it is partitioned but it actually manages the drive by itself?

A: Partitioning is only ever presented as a logical assignment of space... It's not really a physical operation on modern spinning disks either.
Take sector reassignments as an example - you have no control over where data is physically stored.
With solid-state storage like SSDs and SD cards, this concept is taken to the next level, with logical blocks assigned to physical storage in a way that is completely out of the control of the user and even Operating System - the main reason for this being wear levelling. In addition to this, a growing number of SSDs will encrypt their entire contents, so the data isn't accessible to you at a physical level anyway.

If I partition a SSD, will it really partition the drive physically

No, but it never was a physical operation anyway.

... or will the SSD Controller (for example Samsung Phoenix) fool the OS that it is partitioned but it actually manages the drive by itself?

Partition tables are typically something that the storage device knows nothing about - it presents itself to the operating system as "a massive array of blocks" (hence the term "block device").
It is entirely the Operating System's job to correctly interpret the partition table, and present the logical partitions for use (e.g: as the space to store a filesystem). This presentation is not much more than simply "from x to y is referred to as partition 1" - it's a transparent window that bounds your access to the underlying storage device, and restricts access to between these points.

In the (very rough) example above, we have:

*

*The partition table at the front, in purple. As mentioned above, it informs the OS where the partitions logically are in the storage device.

*Partition #1 starts at location 8, and runs through to location 456 (i.e: it's 449 units in size).

*Unused space

*Partition #2 starts at location 504, and runs through to location 904 (i.e: it's 401 units in size).

*Unused space

In this example, the OS will present the two as things that can be used... you'll probably have filesystems on both, and the contents of the filesystem will be presented at a mountpoint (like C:\ on Windows, or perhaps /home on *nix).
The "foolery" that you're referring to is actually lower than this... The SSD keeps a map of where each logical block is physically located. But this is completely invisible to everything outside of the SSD. If you looked at the raw / physical flash, then it would be:

*

*A jumble of non-sensical mess that you'd need to reconstruct (using the SSD's propietary map)

*More and more likely it would appear as random noise, with no data or patterns present, because it's encrypted.

To clarify a potential source of confusion, some things (like eMMC storage) do support physical partitioning, but this is not what you're referring to.
For eMMC, it's a one-time operation that can be used to physically keep one region of flash separate from another - the wear levelling algorithms will never cross that boundary. It can also be used to treat a section as SLC rather than MLC, supposedly for greater longevity and reliability, and is intended specifically for embedded systems.

A: On an SSD there is no fixed assignment which chip contains which sector. Therefore the "partitioning" is not existing on hardware level (because the SSD controller dynamically assigns the flash chip sections to sectors to perform wear leveling and increase the life of the SSD).
If you name this "fooling" than yes. But you will only recognize this if you solder out the flash chips and access them directly. Or if you manage to access the SSD bypassing the SSD controller (normally this is not possible).
However in the data level the partitioning is existent  and visible to the OS and that is everything what matters.

A: Almost certainly the partitioning will be done by the OS. Only the newest SSD's for large enterprises have the capability to do the partitioning in the SSD. An example would be the Samsung PM1725a. You might find such an SSD in a cloud server, which is used by multiple customers at the same time. They even have features to be accessed by multiple Operating Systems at the same time. More consumer-oriented SSD's like the Samsung 980 are designed for a single user and do not offer this sort of features.


text:
Q: Incompatible Shape between input image and expected model input image I am trying to train a FCN model for segmentation. I have an array of train images of size (256,256,3) and another array of ground truth(masks) of size (256,256,3). My model summary is as below :
Model Structure
I am not sure how to train the model so i am using model.fit() to train it.
Model Compile and fit
But i am getting incompatible input image size error
Error
Can anyone, please help me to rectify the code and train the model. Thank you


text:
Q: Unable to populate Bokeh HoverTool Values from Passed in Pandaframe I am using Bokeh on Jupyter Notebooks to help with data visualization. I wanted to be able to plot the data from a panda DataFrame, and then when I hover over the Bokeh plot, all the feature values should be visible in the hover Box. However, with the code below, only the index correctly displays, and all the other fields appear as ???, and I'm not sure why.
Here is my working example
//Importing all the neccessary things
import numpy as np
import pandas as pd
from bokeh.layouts import row, widgetbox, column
from bokeh.models import CustomJS, Slider, Select, HoverTool
from bokeh.plotting import figure, output_file, show, ColumnDataSource
from bokeh.io import push_notebook, output_notebook, curdoc
from bokeh.client import push_session
#from bokeh.scatter_with_hover import scatter_with_hover
output_notebook()

np.random.seed(0)
samples = np.random.randint(low = 0, high = 1000, size =  1000)
samples = samples.reshape(200,5)
cols = ["A", "B", "C", "D", "E"]
df = pd.DataFrame(samples, columns=cols)

# Here is a dict of some keys that I want to be able to pick from for plotting
labels = list(df.columns.values)
axis_map = {key:key for key in labels}

code2 = ''' var data = source.data;

           //axis values with select widgets
           var value1 = val1.value;
           var value2 = val2.value;

           var original_data = original_source.data
           // get data corresponding to selection

           x = original_data[value1];
           y = original_data[value2];
           data['x'] = x;
           data['y'] = y;

           source.trigger('change');

           // set axis labels
           x_axis.axis_label = value1;
           y_axis.axis_label = value2;

           '''
datas = "datas"
source = ColumnDataSource(data=dict( x=df['A'], y=df['B'],
                                    label = labels, datas = df))

original_source = ColumnDataSource(data=df.to_dict(orient='list'))

a=  source.data[datas].columns.values
#print a.columns.values
print a

TOOLS = [ HoverTool(tooltips= [(c, '@' + c) for c in  source.data[datas].columns.values] +
                               [('index', '$index')] )]
# hover.tooltips.append(('index', '$index'))
#plot the figures
plot = figure(plot_width=800, plot_height=800,   tools= TOOLS)
plot.scatter(x= "x",y="y", source=source, line_width=2, line_alpha=0.6,
             size = 3)

callback = CustomJS(args=dict(source=source, original_source = original_source,
                              x_axis=plot.xaxis[0],y_axis=plot.yaxis[0]), code=code2)

#Create two select widgets to pick the features of interest
x_axis = Select(title="X Axis", options=sorted(axis_map.keys()), value="A", callback = callback)
callback.args["val1"] = x_axis
callbackDRange.args["val1"]= x_axis

y_axis = Select(title="Y Axis", options=sorted(axis_map.keys()), value="B", callback = callback)
callback.args["val2"] = y_axis
callbackDRange.args["val2"]= y_axis

plot.xaxis[0].axis_label = 'A'
plot.yaxis[0].axis_label = 'B'

#Display the graph in a jupyter notebook
layout = column(plot, x_axis, y_axis )
show(layout, notebook_handle=True)

I'm even passing in the full dataframe into the source ColumnDataSource so I can access it later, but it won't work. Any guidance would be greatly appreciated!

A: Running your code in recent version of Bokeh results in the warning:

Which suggests the root of the problem. If we actually look at the data source you create for the glyph:
source = ColumnDataSource(data=dict(x=df['A'],
                                    y=df['B'],
                                    label=labels,
                                    datas = df))

It's apparent what two things are going wrong:

*

*You are violating the fundamental assumption that all CDS columns must always be the same length at all times. The CDS is like a "Cheap DataFrame", i.e. it doesn't have ragged columns. All the columns must have the same length just like a DataFrame.

*You are configuring a HoverTool to report values from columns named "A", "B", etc. but your data source has no such columns at all! The CDS you create above for your glyph has columns named:

*

*"x", "y"

*"labels" which is the wrong length

*"datas" which has a bad value, columns should normally be 1-d arrays

The last column "datas" is irrelevant, BTW. I think you must think the hover tool will somehow look in that column for information to display but that is not how hover tool works. Bottom line:
If you configured a tooltip for a field @A then your CDS must have a column named "A"
And that's exactly what's not the case here.
It's hard to say exactly how you should change your code without more context about what exactly you want to do. I guess I'd suggest taking a closer look at the documention for hover tools in the User's Guide


text:
Q: Can GitHub Pages be used as an image CDN I am aware that GitHub isn't meant to be used a CDN.
However, is there a downside to storing images in a GitHub repository, creating GitHub Pages and using it as an image CDN?


text:
Q: how to change theme of grid using jqwidgets I am using jqgrid to display data. I am very new to this
I have tried How to change the theme of the jqGrid? but its not working for me.
Can anyone tell me how to change theme of grid?

A: jqGrid uses jQuery UI CSS for the grid by default. Thus you have to include some jQuery UI CSS. I'd recommend you to choose one from well-known CSS and use it directly from Internet. There are some common CDNs, which provides servers in different locations of the world and which have long time interval for caching. As the result the CSS will be loaded quickly and the next loading will be made mostly from the local cache. As the results, the loading could be typically more quickly as loading form your private web site.
On jQuery UI blog you can find URLs to jQuery CDN, MaxCDN, Google Ajax Libraries API (CDN), Microsoft Ajax CDN and other.
The list of standard themes is relatively long: black-tie, blitzer, cupertino, dark-hive, dot-luv, eggplant, excite-bike, flick, hot-sneaks, humanity, le-frog, mint-choc, overcast, pepper-grinder, redmond, smoothness, south-street, start, sunny, swanky-purse, trontastic, ui-darkness, ui-lightness, and vader. You can choose someone and use it. For example
<link rel="stylesheet"
       href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css">

In the same way free jqGrid (it's the fork of jqGrid, which I develop) is accessible from two other CDNs too (cdnjs and jsDelivr CDN). See the wiki article for details.
As the result, the typical code, which uses free jqGrid can looks like described here:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Your page title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.12.1/css/ui.jqgrid.min.css">

See JSFiddle demo too.
In other words, you don't need to generate customized jQuery UI theme, but you should just use one from existing.

A: For the jQWidgets Grid, you should do two things: include the CSS theme file and then set the widget's theme property to the theme's name. Example: Styling and Appearance


text:
Q: Projective line as a quotient by a torus Let $k$ be a field, and let $T$ an $n$-dimensional split torus over $k$. Let $X$ be a $k$-scheme with algebraic $T$-action. Solve for X:
$$X / T \cong \mathbf{P}^1_k$$
(The quotient should be a categorical quotient in the category of $k$-schemes. A categorical quotient is a morphism $\pi : X \to X/T$ which is universal among morphisms which are constant on $T$-orbits.)
For example, $X = \mathbf{P}^1_k \times T$ with $T$ acting by right multiplication on the right factor is a trivial solution. More generally, I expect to find such $X$ among $(n+1)$-dimensional toric varieties.
Would someone explain how nasty this question actually is and what restrictions could be made:

*

*on the field $k$ or

*on the scheme $X$ or

*on the quotient morphism $\pi : X \to X/T$ or

*on the action morphism $\gamma : X \times T \to X$ or

*on the category in which the quotient is taken or

*on the "goodness" of the categorical quotient

in order to have a simple classification of the solutions? In other words, the solution to this problem will be itself a problem, a possibly modified version of the above admitting a simple solution. This might be a complex question (or not!), in which case a partial answer would still be interesting.

A: I recommend you read about "universal torsors" in the sense of Colliot-Th'el`ene and Sansuc.  These are torsors for (not necessarily split) algebraic tori which are universal among all such torsors.  A universal torsor does not always exist, but it does exist when there is a $k$-rational point (or even just a degree $1$, zero cycle).  In the case of $\mathbb{P}^n_k$, a universal torsor is the following $\mathbb{G}_m$-torsor $U$,
$$\mathbb{A}^{n+1}\setminus \{0\} \rightarrow \mathbb{P}^n.$$
For every algebraic torus $T$, for every $T$-torsor, $X\to \mathbb{P}^n$, there exists a unique group-scheme homomorphism $\rho:\mathbb{G}_m\to T$ such that $X$ is isomorphic, as a $T$-torsor over $\mathbb{P}^n$, to $(T\times U)/\Delta(\mathbb{G}_m)$, where $\Delta$ denotes the diagonal action of $\mathbb{G}_m$, via $\rho$ and the standard action on $U$.  Thus, the torsors $X$ for your torus $T$ (up to isomorphism of $T$-torsor) are in one-to-one correspondence with the group-scheme homomorphisms $\rho:\mathbb{G}_m\to T$, i.e., the group of cocharacters of $T$.

A: $\mathbb P^1$ viewed as a toric variety has $3$ orbits. If we take a quotient of a $n+1$-dimensional toric variety by an $n$-dimensional subtorus of its torus, the number of orbits does not change, so we are looking at toric varieties with $3$ orbits. The fan of such a toric variety consists of the central point with two rays coming out. The subgroup you quotient by corresponds to a hyperplane in $\mathbb Z^{n+1}$. To map to the correct points of $\mathbb P^1$ in the quotient, the rays must lie on opposite sides of the hyperplane.
Thus, classifying the toric ways of viewing $\mathbb P^1$ as a quotient is equivalent to classifying pairs of slopes up to automorphism. If we hold the torus fixed then we hold the hyperplane fixed, so the only automorphisms left are shears that add a fixed integral slope to the slope of both rays, meaning that these are classified by $\mathbb Q^{2n}/\mathbb Z^n$.
If we require $T$ to act without stabilizer, then we are just classifying principal $T$-bundles, which are just classified $H^1(\mathbb P^1,\mathbb G_m^n)=H^1(\mathbb P^1, \mathbb G_m)^n=\mathbb Z^n$. We can construct these by taking line bundles, removing the zero section, and then taking the fiber product. Torically these correspond to pairs of rays with integral slopes.
For toric varieties with rational slopes, $T$ acts with stabilizer above $0$ and $\infty$.


text:
Q: JavaScript - Test if page was searched by user on browser I want to make it so my webgame cannot be searched using javascript. Example:

*

*Enter url in browser search box

*If so, redirect to page

*Without doing it on onload.
HTML -  JavaScript


text:
Q: How to select and replace matching syntax in VS Code I am trying to find a quick and easy way to select and replace matching syntax in VS Code. Specifically, I am writing JS / React but theoretically, this could work for several languages.
I have looked for keyboard shortcuts and various extensions to solve this problem and I assume others would benefit from this as well. I am fairly certain this is a solved problem in vim, so I figured there might be a solution for VS Code as well.
Basically, I am looking for a quick way to go from this:
const Component = () => (

some stuff here

)

To this:
const Component = () => {

some stuff here

}

By simply highlighting and replacing the matching syntax when I do a "special select" of one of the pieces of syntax.
This may seem small, but I do this quite often when I switch from implicit returns to explicit returns within a component. For example, if I am trying to debug and want to add some logic to a component that it did not previously need.
Thank you for your time!


text:
Q: After converting bits to Double, how to store actual float/double value without using BigDecimal? According to several floating point calculators and as well as my code below, the following 32 bits 00111111010000000100000110001001 has an actual Floating Point value of (0.750999987125396728515625). Since it is the actual Float value, I should think storing it in a Double or Float would retain the precision and exact value so long as (1) no arithmetic is performed (2) the actual value is used and (3) the value is not down-casted. So why is the actual value different from the casted (example 1) and literal (example 2) value of (0.7509999871253967)?
I used this calculator as an example:
https://www.h-schmidt.net/FloatConverter/IEEE754.html

import java.math.BigInteger;
import java.math.BigDecimal;

public class MyClass {
    public static void main(String args[]) {
      int myInteger = new BigInteger("00111111010000000100000110001001", 2).intValue();
      Double myDouble = (double) Float.intBitsToFloat(myInteger);
      String myBidDecimal = new BigDecimal(myDouble).toPlainString();

      System.out.println("      bits converted to integer: 00111111010000000100000110001001 = " + myInteger);
      System.out.println("    integer converted to double: " + myDouble);
      System.out.println(" double converted to BigDecimal: " + myBidDecimal);

      Double myDouble2 = 0.750999987125396728515625;
      String myBidDecimal2 = new BigDecimal(myDouble2).toPlainString();

      System.out.println("");
      System.out.println("       Ignore the binary string: ");
      System.out.println("            double from literal: " + myDouble2);
      System.out.println(" double converted to BigDecimal: " + myBidDecimal2);
    }
}

Here is the output:
      bits converted to integer: 00111111010000000100000110001001 = 1061175689
    integer converted to double: 0.7509999871253967
 double converted to BigDecimal: 0.750999987125396728515625

       Ignore the binary string:
            double from literal: 0.7509999871253967
 double converted to BigDecimal: 0.750999987125396728515625

A: There is no actual loss of precision; the issue is your incorrect expectations about how doubles are converted to String (e.g. when printed).
From the documentation of Double.toString:

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.

So when a double gets printed, it is printed only with enough digits to uniquely identify that double value, not with the number of digits needed to describe the precise value as a real number.
If you want to get the precise value of a double with all possible digits, new BigDecimal(theDouble).toPlainString() is how you do it -- and, as you demonstrate, it gets the correct result.


text:
Q: iPhone photo uploads overwrite each other in gallery I have an image gallery where users will be uploading images from their phones into a database which then gets called onto my gallery page. Each entry has an ID, an image, and a description in the DB.
This is the code that exports the gallery:
    //include database connection
    include 'mysqlconnect.php';

    $sql="select * from images order by image desc";
    $query=mysql_query($sql);
    while($row=mysql_fetch_array($query))
    {
        $image=$row ['image'];
        $description=$row ['description'];

        //call all images from DB
        echo '';
    }

The problem is when a user uploads photos with an iPhone. Because iPhones always save their images as "image.jpg", every time one is uploaded it overwrites the previous iPhone images in the gallery. I think this is because the gallery is only calling for file names.
Is there a way to call for the images based on their row ID? Something like $image=$row['id','image']; ?

A: Firstly, if the same image name gets uploaded and you haven't made provisions to rename it or used a distinctive folder to use them as being unique, then that is a problem right there.
If you want to view a photo based on an ID, then use it in your query.
I.e.:
$sql="select * from images WHERE id='some_id' order by image desc";

"Is there a way to call for the images based on their row ID? Something like $image=$row['id','image']; ?"

No, that is invalid syntax:
$image=$row['id','image'];

You would need to use two seperate $row(s).
I.e.:
$id = $row['id'];
$image=$row['image'];

Sidenote: You may not even need to use the WHERE clause, and just use the $row['id'].
However, if you're set on displaying images based only on a particular user, then yes; use a WHERE clause and even using sessions based on their session username.

*

*http://php.net/manual/en/reserved.variables.session.php
Rename uploaded files:
Consult the following on how to use a unique name on uploads:

*

*How to rename uploaded file before saving it into a directory?
You're also using a deprecated MySQL library. Best you move over to either mysqli_ or PDO, as it will be removed from future PHP releases.
References:

*

*http://php.net/manual/en/book.mysqli.php

*http://php.net/manual/en/book.pdo.php


text:
Q: Linq-To-Entities 'Contains' clause 1-many relationship Consider a (simplified) table structure like this:
[USERS]

*

*EMPID

*NAME

[APPOINTMENTS]

*

*(FK_APPT_USER) EMPID

*APPTTYPEID

*COMPLETE

Each user can have 0..* appointments, each of which can be one of many APPTYPEID's, and can either be complete or not complete.
I want to filter the result set of a IQueryable[USER] query such that it only includes USERS who have an appt of some typeID (say 1) and where the COMPLETE field is in a list of values. I'm doing this as part of a gridview filter that allows users to select either to show only completed or not completed users for particular appointment types.
List<string> vals = new List<string> {"Y","N"}
//maybe the user has only selected Y so the above list only contains 1 element
var qry = ctx.USER.Where(x=> vals.Contains( ? ));
//bind etc

This is really easy to do if the values I'm comparing against the list are in a 1-1 relationship with the USER object, for example:
var qry = ctx.USER.Where(x=> vals.Contains(x.NAME));

But I don't understand how to do it with a 1-many relationship like with my appointments table, it's getting me all brain-tied trying to conceptualize the entity sql for it. Can anybody explain how to do this?

A: qry = ctx.USER.Where(u => u.APPOINTMENTS
                           .Where(a => a.APPTYPEID == 1)
                           .Any(a => vals.Contains(a.COMPLETE)));

UPDATE (added returning those users, which do not have appointments at all)
qry = ctx.USER.Where(u =>
        !u.APPOINTMENTS.Any() ||
         u.APPOINTMENTS.Any(a => a.APPTYPEID == 1 && vals.Contains(a.COMPLETE)));


text:
Q: If $(x,y)\mapsto f(x,y)=(x-y,x-y).$ Prove that $f \circ f=0$ I have proved that the following map is linear but cannot prove that $f \circ f=0$.
Here is the question:

Let $$f:\Bbb{R^2}\to \Bbb{R^2}$$
$$(x,y)\mapsto f(x,y)=(x-y,x-y).$$
Prove that $f \circ f=0$

I don't know if anyone can help me with its proof. Thanks in advance!

A: $$\langle x,y\rangle\stackrel{f}{\mapsto}\langle x-y,x-y\rangle\stackrel{f}{\mapsto}\langle (x-y)-(x-y),(x-y)-(x-y)\rangle=\langle 0,0\rangle$$

A: Let $a=x-y$. Then
$(f \circ f)(x,y)=f(a,a)=(a-a,a-a)=(0,0)$.

A: As $f$ is a linear map, you can also look at the matrix representing $f$:
$$ A_f= \begin{pmatrix} 1 & -1 \\ 1 & -1 \end{pmatrix} $$
Computing $A^2$ yields $\begin{pmatrix} 0 & 0 \\ 0 & 0 \end{pmatrix}$. Now use the fact that this matrix represents $f \circ f$.


text:
Q: First Occurrence of a Type of Card in a Randomly Shuffled Deck Suppose that I have a deck of $T$ cards, with some set of size $X$ of them having some property.  If it helps you to think of a specific property, in a poker deck they could be all the hearts, in a MTG deck they could be mana cards, etc.
If I shuffle the deck, and pull cards one at a time into my "hand," what is the expected number of cards I need to draw to get one card of type $X$?  What sort of distribution do the first occurrences fall into.
Here is where I have gotten so far.  I may be on the completely wrong path, and I would appreciate being told so, even if you don't have the solution.
I tried to compute some sort of weighted average, multiplying each draw number by the chance that an $X$ card is drawn first on that turn.
The first draw has an $X\over T$ chance of being an $X$ card.  The first term in my sum is $$1 * \frac{X}{T}$$
The second draw has an $\frac{X}{T-1}$ chance of being an $X$ card, and there is a $1-{X\over T}$ chance that the first draw was not an $X$ card.  Now my sum reads: $$1 * \frac{X}{T} + 2 * (\frac{X}{T-1}) * ({1-{X\over T}}) $$
The chance that the the third draw is an $X$ card is $\frac{X}{T-2}$, the chance that the second draw was not the first occurrence is $(1- (\frac{X}{T-1}) * ({1-{X\over T}}))$.  This must be multiplied by the chance that draw #$1$ was not the first, which is $(1-\frac{X}{T})$.  All in all, the sequence with the third term reads:$$1 * \frac{X}{T} + 2 * (\frac{X}{T-1}) * ({1-{X\over T}} + 3 * (\frac{X}{T-2})(1- (\frac{X}{T-1})({1-{X\over T}}))(1-\frac{X}{T})$$  This is starting to look rather unwieldy.  I have no clue how to continue beyond this method, which I am pretty sure is wrong.  Any help would be much appreciated.  Is there a general formula for the expected number of cards one must draw before the $n$th
 card of type $X$ is drawn?
^************************************************************************
EDIT:
The answer which Lulu gave does appear indeed to be correct.  I simulated via computer 100000 shuffles of a random deck and checked the first occurrence of a heart.  The average was $3.79157$.  $53 \over 14$ is $3.78571428571$.  Those numbers are close enough for me to be satisfied.

A: Think of it this way:  Add an extra card $C$ to the deck and (for now) include it in the subset $X$.  Now arrange all the $T+1$ cards randomly in a circle.  By uniformity, we expect there to be $\frac {\#T+1}{\#X+1}$ cards in between each of the cards in the extended $X$ (counting the first element of $X$ that you reach).  Now remove $C$ from the circle and thereby define the start of the shuffled deck.  We then see that we expect $\frac {\#T+1}{\#X+1}$ until we reach the first element of $X$.
Sanity check:  $\#T=2,\#X=1$.  Then the two possible shuffles are $XY, YX$ so the answer is $\frac 32$ which matches the result given by the formula.  Similarly, for $\#T=n, \#X=1$, there are $n$ equally probable places for the unique $X$ to occur so the answer is $\frac {n(n+1)}2\Big / n=\frac {n+1}2$ which again matches the formula.
As another example, if $\#T=3,\#X=2$ then the possible shuffles are $XXY,XYX,YXX$ so the answer is $\frac 43$, again confirming the formula.


text:
Q: .NET - Check if an image can be deleted or is writable after using it to perform .net image scaling I've got an app where the user uploads an image and the app resizes the image three different ways based on different variables.  They all use the same image.  I can't check to see if it's done using the image so I wondered if there was a way to check to see if the file is writable.  A small loop that exits once it becomes writable (or "deleteable").  Working out of VB.NET.  Thanks!

A: Are you using the free image resizing.net library? It properly closes file handles and avoids the 28 GDI bugs that most other solutions (and all the sample code you find on the internet) have. It also supports dynamic image resizing with correctly threaded disk caching, which would probably let you skip your issue altogether.
It's been supported and maintained since 2007, and uses all the best techniques for performance and reliability. It has a 1-line API, and is very easy to use.


text:
Q: Adding numbers from a string without using split Java I want to add the numbers from a user input, String. I know I can do it by using split function like this:
import java.util.Scanner;
public class MyClass{
    public static void main(String[] args){
        String[] Numbers = in.nextLine().split(" ");
        int sum = 0;
        for (String s : Numbers) {
            sum += Integer.parseInt(s);
        }
    }
}

Lets assume that the user input is: "1 2 3 4 5" the sum will be sum=15.
Ok, now I want to do it but without using arrays and the split().
A friend told me about using Scanner.hasNext() Method, but I cannot make it work

A: Try this:
import java.util.Scanner;
public class MyClass{
    public static void main(String[] args){
        int sum = 0;
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()){
            sum += in.nextInt();
        }
    }
}


text:
Q: Xamarin, Open RDP connection into ContentView I'm checking to undertand if there are a way to open RDP session
   into my xamarin application.
   Using the "intent" the rdp connection work and open the session into a new task, but my goal is to open the RDP into a particular content view.
But I cannot retrive that information.
Thank you
Alberto


text:
Q: Well-known text (wkt) validator Is there anything like http://jsonlint.com or http://geojsonlint.com for WKT? How can I validate a complex WKT string, say e.g. a Multipolygon?

A: One possible WKT validator can be PostGIS or a whatever spatial DBMS you like. For instance:
SELECT ST_GeomFromText('POINT(-71.064544 42.28787)');

is executed successfully, because POINT(-71.064544 42.28787) is a valid WKT representation. Instead:
SELECT ST_GeomFromText('POINT(-71.064544, 42.28787)');

returns:

ERROR:  parse error - invalid geometry HINT:  "POINT(-71.064544, "
  <-- parse error at position 18 within geometry
  *** Error ***
ERROR: parse error - invalid geometry SQL state: XX000 Hint:
  "POINT(-71.064544, " <-- parse error at position 18 within geometry

because POINT(-71.064544, 42.28787) is not a valid WKT. Hope this helps.


text:
Q: Where is the update-manager? I can't seem to upgrade to the latest version ubuntu. It asked me once, but I was doing something else at the time. Now that I ant to do it I can't find it. I can find software updater, but that just seems to update programs that are on the computer.

A: The update manager has the upgrade button you are looking for.
start the update manager with typing update-manager in a terminal. The upgrade button will be shown there.
Or you can search for it in dash by typing update manager.

A: Click on the Gear on the top-right corner> System Settings...>Software&Updates
there go to the Updates Tab and then check that "Notify me of a new Ubuntu version is set to: For any version.
then execute the Software updater and it should tell you (if not hit refresh)
Hope it helps

A: Click Alt + F2 and type update-manager at the prompt or do the same in Terminal.
If this does not show the update open a Terminal window and type in
sudo apt-get update
sudo apt-get upgrade

The sudo apt-get upgrade command updates any installed software requiring an update before you proceed
sudo do-release-upgrade

This searches for and upgrades your system
How to safely upgrade from an older Ubuntu version to a newer one? Is the best and safest way.
Edited with corrections suggested below


text:
Q: Roslyn compiler causes recycling of application pool during compilation I have a fairly large ASP.NET website with Roslyn compiler installed. I have also app pool recycling enabled for 'private memory usage' (IIS 10, limit set to 4GB). I was wondering why my website recycles with event log message ID 5117

A worker process serving application pool 'pool_name' has requested a recycle because it reached its private bytes memory limit.

even though the committed memory of application pool itself is well under 1GB. By test&trial I came to conclusion it's caused by the Roslyn compiler, which is most probably ran under the pool and its memory is also counted towards the recycle limit.
So the question is - is this behavior normal and how can it be set up in a way the compilation does not cause the recycling? (other than precompilation)


text:
Q: Run job to check if mail is sent or not I am sending mail through sidekiq.
Now I have to run a job which will check if the mail is sent or not, because I have to call a method on successful mail send . Is there any method to do this in rails?

A: You can save this adding a new attribute in a table if the email was sent successfully
if UserMailer.delay.application_rejected(user)
  user.update_column(:email_status_rejected, true) # the email was sent to the job
end

A: Sidekiq does not allow to check status of a particular job. That is what Batches are for.
Refer to this documentation of Batches.
They provide detailed information in case of failures and also have neat callback methods which you can use.
Edit: If you just want to monitor your jobs, sidekiq provides a nice web interface for that: https://github.com/mperham/sidekiq/wiki/Monitoring#web-ui


text:
Q: The generous lazy caterer It is well-known that $n$ chords divide any convex shape into at most $\frac{n^2+n+2}2=T_n+1$ regions – the lazy caterer's sequence. For example, the pancake below is cut into seven pieces by three cuts:

If these are meant for seven people, however, someone has to take the very small central triangle, which is sad. Now suppose the lazy caterer is feeling generous and wants to maximise the smallest amount of food each person can get, which leads to my question.

If a unit circle is divided into $T_n+1$ non-empty regions by $n$ chords, what is the largest possible area of the region with smallest area?

My best results for one to six cuts are shown below, with the shaded regions in each circle having the same smallest area $A$.

As discussed in a related question, the ideal of every region having area $\frac\pi{T_n+1}$ can be attained for one and two cuts. For further cut numbers, this is not possible and I found the values of interest by a melange of symmetry assumptions, mpmath and SciPy.
$$\begin{array}{c|cc}
n&A&\frac{A(T_n+1)}\pi\\
1&\frac\pi2=1.57079632\dots&1\\
2&\frac\pi4=0.78539816\dots&1\\
3&0.20025783\dots&0.4462\\
4&0.05900936\dots&0.2066\\
5&0.05394118\dots&0.2747\\
6&0.02456012\dots&0.1720
\end{array}$$
The last column in the above table gives $A$ as a proportion of the ideal region-wide smallest area.
I have numerically verified the optimality of the three-cut arrangement by optimising over possible arrangements (see lazy2.py in the Gist link above). The four- to six-cut arrangements have not been so verified; I am pretty sure the five-cut arrangement is also optimal and not sure about the six-cut arrangement. I am almost certain that the four-cut arrangement can be improved – looking at how the five-cut arrangement achieves a higher proportion of the ideal area against the trend of decreasing efficiency – but haven't had the time to do so. What are the optimal arrangements for four to six cuts, and for seven or more cuts?

A: Just few (new)(?) values/shapes; free for further improvement.
Symmetric shapes only were considered.
Cutting lines are written in normal form:
$$x\cos \varphi + y\sin \varphi - r = 0.$$
\begin{array}{|c|c|c|c|c|}
\hline
n & A & \frac{A(T_n+1)}{\pi} & lines \\
\hline
4 & 0.06807114... & 0.2383 &
{  \varphi = \pm 0.4514698, r = 0.0688937;
\\ \varphi = \pm 1.0207965, r = 0.3450090} \\
\hline
7 & 0.01685409... & 0.1555 &
{  \varphi = \pm 1.2920277, r = 0.2081783;
\\ \varphi = \pm 2.3794749, r = 0.1845881;
\\ \varphi = \pm 2.5799602, r = 0.0680407;
\\ \varphi = \pi, r = 0.4250664
} \\
\hline
8 & 0.01144959... & 0.1348 &
{  \varphi = \pm 0.7247806, r = 0.1946717;
\\ \varphi = \pm 0.9329640, r = 0.0573711;
\\ \varphi = \pm 1.1974689, r = 0.2406817;
\\ \varphi = \pm 2.9276052, r = 0.2045243
} \\
\hline
9 & 0.01068619... & 0.1564 &
{  \varphi = \pm 0.8084867, r = 0.2272170;
\\ \varphi = \pm 1.2859084, r = 0.2272170;
\\ \varphi = \pm 2.9028818, r = 0.2272170;
\\ \varphi = \pm \pi/3, r = 0.0627546;
\\ \varphi = \pi, r = 0.0627546
} \\
\hline
\end{array}
Images:
 $\qquad$

 $\qquad$


text:
Q: Manipulation of Large Numbers I encountered a puzzling problem (though I don't remember where) to find the prime factorization of the number
$$7^{100}-1$$
I think there may be some kind of trick or technique that one could use to solve this problem that I am unaware of. I already know the fact that any number of the form $c^n-1$ is divisible by $c-1$, so I know that $7^{100}-1$ is divisible by $6$, but now what do I do?

A: You can find a number of small factors fairly easily.  As you say, $6$ is a factor.  You can also factor it as the difference of squares.  One of those factors will again factor as the difference of squares.  This brings you to $7^{25}+1$ which has a factor $7+1$.  The difference of fifth powers factors as well.  I doubt you will get the complete factorization, which Alpha says is $2^5\times 3\times 5^4\times 11\times 101\times 191\times 281\times 2551\times 2801\times 4021\times 13001\times 25301\times 31280679788951\times 79787519018560501\times 38327966300231909291101$

A: As suggested in the comments, start from the factorization of $x^{100}-1$ in terms of cyclotomic polynomials:
$$
x^{100}-1=
(x - 1) (x + 1) (x^2 + 1) (x^4 - x^3 + x^2 - x + 1) (x^4 + x^3 + x^2 + x + 1) (x^8 - x^6 + x^4 - x^2 + 1) (x^{20} - x^{15} + x^{10} - x^5 + 1) (x^{20} + x^{15} + x^{10} + x^5 + 1) (x^{40} - x^{30} + x^{20} - x^{10} + 1)
$$
which comes from
$$
x^n-1=\prod_{d \mid n} \Phi_d(x)
$$
This gives
$$
7^{100}-1
=
6 \cdot
8\cdot
50\cdot
2101\cdot
2801\cdot
5649505\cdot
79787519018560501\cdot
79797014141614001\cdot
6366805738369687774841443066497505
$$
It is possible to further factorize this, but it is not easy because $79787519018560501$ is prime and $6366805738369687774841443066497505$ has a prime factor $38327966300231909291101$, though its other factors are quite small.
factor from BSD gives
6: 2 3
8: 2 2 2
50: 2 5 5
2101: 11 191
2801: 2801
5649505: 5 281 4021
79787519018560501: 79787519018560501
79797014141614001: 2551 31280679788951
6366805738369687774841443066497505: 5 101 13001 25301 38327966300231909291101

A: Take advantage of the difference of two squares:
$$\begin{align}7^{100}-1&=(7^{50}+1)(7^{50}-1)\\&=(7^{50}+1)(7^{25}+1)(7^{25}-1)\end{align}$$
Then recall $a^5-b^5=(a-b)(a^4+a^3b+a^2b^2+ab^3+b^4)$ to get
$$\begin{align}7^{25}-1&=(7^5-1)(7^{20}+7^{15}+7^{10}+7^5+1)\\&=(7-1)(7^4+7^3+7^2+7+1)(7^{20}+7^{15}+7^{10}+7^5+1)\end{align}$$
Likewise, $a^5+b^5=(a+b)(a^4-a^3b+a^2b^2-ab^3+b^4)$, so we have
$$\begin{align}7^{25}+1&=(7^5+1)(7^{20}-7^{15}+7^{10}-7^5+1)\\&=(7+1)(7^4-7^3+7^2-7+1)(7^{20}-7^{15}+7^{10}-7^5+1)\\7^{50}+1&=(7^{10}+1)(7^{40}-7^{30}+7^{20}-7^{10}+1)\\&=(7^2+1)(7^8-7^6+7^4-7^2+1)(7^{40}-7^{30}+7^{20}-7^{10}+1)\end{align}$$
We see that
$7-1=6=2\times3$
$7^4+7^3+7^2+7+1=2801=\text{prime}$
$7^{20}+7^{15}+7^{10}+7^5+1=79797014141614001=2551\times31280679788951$
$7+1=8=2^3$
$7^4-7^3+7^2-7+1=2101=11\times191$
$7^{20}-7^{15}+7^{10}-7^5+1=79787519018560501=\text{prime}$
$7^2+1=50=2\times5^2$
$7^8-7^6+7^4-7^2+1=5649505=5\times281\times4021$
$7^{40}-7^{30}+7^{20}-7^{10}+1\\=6366805738369687774841443066497505\\=5\times101\times13001\times25301\times38327966300231909291101$


text:
Q: Select certain values and sort alphabetically in ES6 How can I select on certain values and sort them alphabetically using ES6.
The current codes defines a constant. I wanted to know if I could manipulate this data without having to create a new constant with just the values I need.
export const names = {
John: 'John',
Mike: 'Mike',
David: 'David',
Chris: 'Chris'
};

Return only Chris and David.
Chris
David

A: const names = {
  John: 'John',
  Mike: 'Mike',
  David: 'David',
  Chris: 'Chris',
};

const searchNames = (args, search) => {
  const arr = Object.values(args);
  const result = arr.filter(n => {
    return search.includes(n);
  });
  return result.sort().join('\n');
};

searchNames(names, ['David', 'Chris']);
// returns: Chris
//          David

Not the most elegant, but it works. It would be easier to start with an array instead of an object. It doesn't seem like the object is necessary since the keys and values are identical. Nonetheless, this is a pretty easy task with an array. I converted the obj to an array containing only the values. Then created a new array
filtering out the names we wanted, returned that array sorted alphabetically and in a string format. The ('\n') in the return statement is just delimiting the elements of the array by a new line, since that's the format you showed. But that can be changed to anything, if you don't need the names to be on separate lines.
Just to clarify, as per the documentation, const can be used here:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

A: Yes you can manipulate this data, have a look on how const works in javascrips.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

const names = {
John: 'John',
Mike: 'Mike',
David: 'David',
Chris: 'Chris'
};

console.log(names.John);

names.John = 'noJohn';

console.log(names.John);


text:
Q: An identity involving partitions I have been trying to prove an identity using a combinatorial argument or another technique.  I need to define the following first:
$$R(n,m) = \{ (r_1,r_2,...,r_n): \sum_{i=1}^n r_i = m \text{ and } r_i \text{ is a positive integer }\}.$$
I believe there is a name for this set.  If so let me know.  I think of it as the set of ordered partitions of m of size n.
The identity I want to prove is the following.  For $m \ge 2$:
$$\sum_{n=1}^m \frac{(-1)^n}{n!}\sum_{r \in R(n,m)}\frac{1}{r_1r_2r_3...r_n}=0$$
The reason I know this identity is true is that the left side is the coefficient of $T^m$ in the power series expansion of $\exp (\log(T+1)) = T+1$ where exp and log are defined by $$\exp(T) = \sum_{n=0}^\infty \frac{T^n}{n!}$$ and $$\log(T+1)=-\sum_{n=1}^\infty(-1)^n\frac{T^n}{n}.$$  I am trying to use the identity to show that exp and log as defined by these power series are in fact inverses.  Thanks for any help.

A: Note:  This question was answered also by some one else.
See the bottom for the link.
After much thought, I can answer my own question.   I find it easier to start from the beginning.  The initial problem I had was proving that if $$\exp(T) = \sum_{n=0}^{\infty}\frac{T^n}{n!}$$ and $$\log(1+T)=\sum_{n=1}^{\infty}\frac{(-1)^{k-1}T^k}{k}$$ then $$\exp(\log(1+T)) = 1+T$$
We have $$\exp(\log(1+T))=\frac{1}{0!}+\frac{(\frac{T}{1}-\frac{T^2}{2}+\ldots )}{1!}+\frac{(\frac{T}{1}-\frac{T^2}{2}+\ldots )^2}{2!}+\cdots $$
Collecting the first few terms of $\exp(\log(1+T))=\sum_{n=0}^{\infty}a_nT^n$ we get:
$$a_0 = \frac{1}{0!}=1$$
$$a_1T =\frac{T}{1!} = T$$
$$a_2T^2 = -\frac{T^2}{2\cdot 1!}+\frac{T^2}{1\cdot 1\cdot 2!}$$
$$a_3T^3 = \frac{T^3}{3\cdot 1!}-\frac{T^3}{1\cdot 2\cdot 2!}-\frac{T^3}{2\cdot 1\cdot 2!}+\frac{T^3}{1\cdot 1\cdot 1\cdot 3!}$$
$$a_4T^4=-\frac{T^4}{4\cdot 1!}+\frac{T^4}{1\cdot 3\cdot 2!}+\frac{T^4}{2\cdot 2\cdot 2!}+\frac{T^4}{3\cdot 1 \cdot 2!}-\frac{T^4}{1\cdot 1\cdot 2\cdot 3!}-\frac{T^4}{1\cdot 2\cdot 1\cdot 3!}-\frac{T^4}{2\cdot 1\cdot 1\cdot 3!}+\frac{T^4}{1\cdot 1\cdot 1\cdot 1\cdot 4!}$$
To find a general formula for $a_n$ we let $R(m,n)$ be the set of m-tuples $(r_1,r_2,\ldots,r_m)$ of positive integers for which $\sum r_i=n$.  Then for $n\ge 1$,
$$a_n=-\sum_{m=1}^{n}(-1)^{n-m}\sum_{r\in R(m,n)}\frac{1}{(\Pi {r_i})m!}$$
I want to show that for $n\ge 2$, we have $a_n=0$.  (This is equivalent to what I was asking in my original question above.)  Now we will associate each m-tuple in $R(m,n)$ with a multi-set.  So $(r_1,r_2,\ldots,r_m)$ is associated with the multi-set $\{r_1,\ldots, r_m\}$.  Let the multi-set $K_M=\{k_1,k_2,\ldots, k_l\}$ be the multiplicities of the multi-set $M$.
Let $\mathcal M(m,n)$ be the collection of all multi-sets of $m$ positive integers whose sum is $n$.  Let $M\in \mathcal M(m,n)$ with $K_M = \{k_1,k_2,\ldots,k_l\}$. There are $$\frac{m!}{k_1!k_2!\ldots k_l!}$$ m-tuples in $R(m,n)$ associated with this multi-set.
Note: You may have seen this formula in a discrete math class.  Does anyone remember how to find the number of ways to arrange the letters of in the word MISSISSIPPI?  It's the same idea here.  The letters form a multi-set.  An arrangement is an m-tuple.
Knowing this, it is now possible to write $a_n$ as the sum over multi-sets instead as:
$$a_n=-\sum_{m=1}^{n}(-1)^{n-m}\sum_{M\in \mathcal M(m,n)}\frac{m!}{(\Pi_{k\in K_M}(k!)}\frac{1}{(\Pi r_i)m!}$$
Which can be rewritten as
$$a_n=\frac{-1}{n!}\sum_{m=1}^{n}(-1)^{n-m}\sum_{M\in \mathcal M(m,n)}\frac{n!}{(\Pi_{k\in K_M}k!)(\Pi r_i)}$$
Separating the negative and positive terms of this sum we get:
$$a_n=\frac{-1}{n!}(\sum_{M\in \mathcal M_e}\frac{n!}{(\Pi_{k\in K_M}k!)(\Pi r_i)}-\sum_{M\in \mathcal M_o}\frac{n!}{(\Pi_{k\in K_M}k!)(\Pi r_i)})$$
where $\mathcal M_e$ and $\mathcal M_o$ are the multisets (adding to n) for which n-m is even and n-m is odd respectively.
We can identify each multi-set $M$ of positive integers, which add to n, with a conjugacy class of $S_n$ by setting $M$ as the cycle type of the conjugacy class.  For example, $M=\{2,3,2,1,1,4\}$ can be identified with the class $H_M\subset S_{13}$ of all permutations of the form
$$\phi = (ab)(cde)(fg)(h)(i)(jklm)$$
where the product is made up of disjoint cycles.  Note that any cycle of length r can be written in r different ways and we can interchange the position in the product of two cycles of the same length.  For example,
$$\phi = (ab)(cde)(fg)(h)(i)(jklm)=(fg)(cde)(ab)(i)(h)(lmjk)$$
so the multiset $M=\{2,3,2,1,1,4\}$ is identified with the conjugacy class $H_M$ and $H_M$ has cardinality
$$\frac{13!}{2!1!2!1!\cdot 2\cdot 3\cdot 2\cdot 1\cdot 1\cdot 4}=\frac{n!}{(\Pi_{k\in K_M}k!)(\Pi r_i)}$$
For any given multi-set $M\in \mathcal M(m,n)$, every $\phi\in H_M$ can be written as the product of transpositions (cycle of length 2).  A cycle of length $r_i$ is the product of $r_i-1$ transpositions.  Thus $\phi$ is the product of $\sum_{i=1}^{m}(r_i-1)= n-m$ transpositions.  If $n-m$ is even then $\phi\in A_n$ so $H_M\subset A_n$.  If $n-m$ is odd then $H_M\subset S_n\setminus A_n$.  Both $A_n$ and $S_n\setminus A_n$ are half the cardinality of $S_n$, for $n\ge 2$.  We therefore have:
$$a_n=\frac{-1}{n!}(\sum_{M\in \mathcal M_e}|H_M|-\sum_{M\in \mathcal M_o}|H_M|$$
Thus,
$$a_n=\frac{-1}{n!}(|A_n|-|S_n\setminus A_n|)=0$$
for $n\ge 2$.
I didn't notice this before but this question was answered quite nicely here:
Composition of formal power series of exp and log


text:
Q: how to retrive data from google search result page and save that data,is it possible or not..? how to retrive data from google search result page and save that data #,

i have code to retrive the data from URL , but i cant retrive the data
  from google search result...
plz help me

code to retrive the data from URL
enter code here  URL iurl = new URL("https://www.google.co.in/search?q=Anirudhcreative%2Cprojects&sub=Submit+Query");
URLConnection urlconn = iurl.openConnection();

System.out.println("url connection>>:"+urlconn);
File f = new File("Ani 7 hindi gogole out put.html");  //************************************ file name ***

FileOutputStream fop = new FileOutputStream(f);
    BufferedReader br = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
    String line;
    //PrintWriter pw = respons
int ii=0;
    String st="";
    System.out.println("*************  output of web page  ***********");
    while((line=br.readLine())!= null)
    {
System.out.println(""+line+"");
ii++;

st=">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+ii;
System.out.println(">>>>>>>>>"+ii);
if(f.exists()){
fop.write(line.toString().getBytes());

//fop.write(st.toString().getBytes());

A: Don't do that, use the Google JSON Search API if you want to retrieve data from the google search because it's easier to use this API than screen scraping.
Also look at the Terms and Conditions when using this API, maybe you are going to use this data for not allowed proposes.


text:
Q: Excel IF AND formula between two times I would like to have a formula which will tell me if a time in a cell is between 2 separate vlaues in other cells and to return a value if so.
I have already created the below code but this is not returning any values back at all.
=IF(AND(F4>=$R$1,F4<P1),"Night Shift",IF(AND(F4>=$P$1,F4<$Q$1),"AM Shift",IF(AND(F4>=$Q$1,F4<$R$1),"PM Shift","")))

In this example the cell values are (P1 = 06:00, Q1 = 14:00, R1 = 22:00). The value in the F4 is 00:31:38.
Any help would be appreciated.

A: Your first AND needs to adjust a little.
Excel sees TIME as a fraction of 1 whole day.  So 00:31:38 though you meant it to be the next day from 22:00, Excel does not know that and as such will not see it greater than 22:00
We also do not need to test for the Night Shift.  It is the only option left if the time is not in one of the others:
=IF(F4<>"",IF(AND(F4>=$P$1,F4<$Q$1),"AM Shift",IF(AND(F4>=$Q$1,F4<$R$1),"PM Shift","Night Shift")),"")

You could also create a small table like such:
0            6:00       14:00       22:00
Night Shift AM Shift    PM Shift    Night Shift

Then use a HLOOKUP to return the correct value:
=HLOOKUP(F4,O1:R2,2,TRUE)

A: I took a slightly different path that Scotts.

*

*A Night Shift occurs if the time is greater or equal to 10PM, OR is less than 6AM.
=OR($F$4<$P$1,$F$4>=$R$1)

*An AM Shift occurs when the time is greater or equal to 6AM, AND is less than 2PM.
=AND($F$4>=$P$1,$F$4<$Q$1)

*A PM Shift occurs when the time is greater or equal to 2PM, AND is less than 10PM.
=AND($F$4>=$Q$1,$F$4<$R$1)
Stick the three conditions together and you have:
=IF(OR($F$4<$P$1,$F$4>=$R$1),"Night Shift",IF(AND($F$4>=$P$1,$F$4<$Q$1),"AM Shift",IF(AND($F$4>=$Q$1,$F$4<$R$1),"PM Shift","")))

Edit
During testing I entered 00:00:00 in A1 and =A1+TIMEVALUE("00:01:00") in A2:A1440.
At 06:00:00, 14:00:00 and 22:00:00 the changeover in shift happened a minute later.
If, however, I manually typed in 06:00:00 the changeover happened on the hour.  This seems to be because TIMEVALUE is calculating 6AM as 0.2499999 rather than 0.25.

A: =IF(OR(HOUR(NOW())>22,HOUR(NOW())<7),"NIGHT","")&IF(AND(HOUR(NOW())>6,HOUR(NOW())<15),"MORNING","")&IF(AND(HOUR(NOW())>14,HOUR(NOW())<23),"LATE","")

I know a bit late but simplifies everything without the need of using other cells (note there are different times used).
Night - 23-07
AM - 07-15
PM - 15-23


text:
Q: Tem como usar display block e flex juntos? Recentemente vi um Indiano fazer um menu de navegação usando HTML,CSS,JS mas oque me intrigou foi ele usar display: block e display: flex no mesmo elemento. Talvez ele errou porque até então eu sei que o último a ser declarado é oque recebe a aplicação. Eu até fiz testes mas o último sempre é aplicado!
Então fica a pergunta: é possível usar esses 2 display no mesmo elemento?

A: Antes de saber se é possível ou não devemos saber o que faz cada um, seja Block ou Flex

O que faz o display: block?
Faz com que o elemento HTML seja renderizado como bloco tal com os parágrafos e os cabeçalhos são.

Exemplo de aplicação na página abaixo:

Demonstração de como é exibido o estilo bloco na página.

O que faz o display: flex?
É um recurso do CSS3 que serve para "moldar" e/ou organizar elementos em containers de forma flexível conforme a sua necessidade.

Exemplo de aplicação na página abaixo:

Afinal da para usar ambas propriedades juntas?
Não é possível utiliza-los no mesmo elemento juntamente. Atributos repetidos seguem a regra da especificidade para dizer qual será utilizado. Como o usuário @Rafael Tavares mencionou, podes visualizar claramente pelo DevTools (ou Inspencionador de Elementos do Navegador)


text:
Q: Can't POST using loopj AsyncHttpClient and an authorization header I am using loopj (1.4.7) and AsyncHttpClient to post Json to a Web API server. My (simplified) code is:
private void createCode() {
    // 1. Get the current data and time
    DateFormat df = DateFormat.getDateTimeInstance();
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    String gmtTime = df.format(new Date());

    // 2. Setup few things
    AsyncHttpClient client = new AsyncHttpClient();
    Context context = this.getApplicationContext();
    connCode = "1234";

    JSONObject jsonData = new JSONObject();
    try {
        jsonData.put("ClientCode", connCode);
        jsonData.put("CodeCreated", gmtTime);
    } catch (Exception ex) {
        // Should not really happen
    }

    // 3. Authorization/Authentication
    String userName = "TestUser";
    String userPassword = "TestPassword";
    String userNamePassword = userName + ":" + userPassword;
    byte[] loginString = userNamePassword.getBytes();
    String loginStringEncoded = Base64.encodeToString(loginString, Base64.DEFAULT);

    client.setAuthenticationPreemptive(true);

    // This is the line that cause the problem
    client.addHeader("Authorization", loginStringEncoded);

    // 4. Setup various options
    StringEntity entity = null;
    try {
        entity = new StringEntity(jsonData.toString());
    } catch (UnsupportedEncodingException e) {
        return;
    }
    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

    // 5. Post the code to the database
    client.post(context, CODE_URL, entity, "application/json", new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // TODO - Process results...
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, java.lang.Throwable throwable, org.json.JSONArray errorResponse) {
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, java.lang.Throwable throwable, org.json.JSONObject errorResponse) {
        }
    });
}

The response is "400 - Bad Request" because not everything makes it to the server if I use the "Authorization" header. What shows up on the server is (verified using Fiddler):
{"ClientCode":"1234","CodeCreated":"Jul 17, 2015 1:03:00 AM

If I get rid of the "client.addHeader("Authorization", loginStringEncoded);" line, everything works fine and the server receives everything (but I need the Authorization header to limit access):
{"ClientCode":"1234","CodeCreated":"Jul 17, 2015 1:10:00 AM"}

I can tell that the server is processing the authorization properly but the response fails because of the missing "}". I have verified that the whole string is part of the "entity" variable before the "client.post" command gets executed.
If it makes a difference, I am running Android Studio on a Mac and I have verified using WireShark that the missing "}" is already not there when the Mac connects to the Web API server.
What could be causing it? A similar setup works fine for GET but I cannot make it work for POST. Is there perhaps a better way to do this?
Thanks.

A: This works with me:
 AsyncHttpClient client2 = new SyncHttpClient();
//check if needs this header or I can take off this and leave just the url+token2
                client2.addHeader("x-auth-token", token2);

                client2.post(String.valueOf(url), params, new BaseJsonHttpResponseHandler(String.valueOf(Looper.getMainLooper())) {

                    /**
                     * Base abstract method, handling defined generic type
                     *
                     * @param statusCode      HTTP status line
                     * @param headers         response headers
                     * @param rawJsonResponse string of response, can be null
                     * @param response        response returned by {@link #parseResponse(String, boolean)}
                     */
                    @Override
                    public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, String rawJsonResponse, Object response) {

                        onPostExecute((JSONObject)response);

                    }

                    /**
                     * Base abstract method, handling defined generic type
                     *
                     * @param statusCode    HTTP status line
                     * @param headers       response headers
                     * @param throwable     error thrown while processing request
                     * @param rawJsonData   raw string data returned if any
                     * @param errorResponse response returned by {@link #parseResponse(String, boolean)}
                     */
                    @Override
                    public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {

                    }

                    /**
                     * Should return deserialized instance of generic type, may return object for more vague
                     * handling
                     *
                     * @param rawJsonData response string, may be null
                     * @param isFailure   indicating if this method is called from onFailure or not
                     * @return object of generic type or possibly null if you choose so
                     * @throws Throwable allows you to throw anything from within deserializing JSON response
                     */
                    @Override
                    protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                        return null;
                    }

I hope it will help you.


text:
Q: ExpressJS - duplicate key error collection I have problem with this error when I am creating a new event with category which exists in my database, for example I created an event with category "javascript" and save it to db, and then i tried to create a new event with categories "javascript, html, css" and then i got this error duplicate key error collection
So my schema for event is this:
    const EventSchema = new Schema({
    title: {
        type: String,
        required: true,
        min: 3,
        max: 100
    },
    featuredImage: {
        type: Object,
    },
    from: {
        type: Date,
        required: true
    },
    to: {
        type: Date,
        required: true
    },
    location: {
        name: {
            type: String
        },
        address: {
            type: Object
        }
    },
    description: {
        type: String
    },
    categories: {
        type: Array,
        trim: true
    },
    featured: {
        type: Boolean
    },
    created_by: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    slug: {
        type: String,
        default: null
    },
    registration: {
        type: Boolean
    },
    tickets: [],
    allday: {
        type: Boolean
    },
    speakers: [{
        type: Schema.Types.ObjectId,
        ref: 'User'
    }],
    attendees: [{
        type: Schema.Types.ObjectId,
        ref: 'User'
    }],
    comments: [CommentSchema]
}, {
    timestamps: true,
    usePushEach: true
});

So basically sending array of strings and i got this error.

A: You probably have some index defined on categories with the unique flag.
You can list the existing indexes with db.events.getIndexes().
You could drop and recreate the culprit (be careful):
> db.events.dropIndex({categories:1})
> db.events.ensureIndex({categories:1},{sparse:true})