text:
Q: How to set a secondary y-axis in Python I'm currently trying to change the secondary y-axis values in a matplot graph to ymin = -1 and ymax = 2.  I can't find anything on how to change the values though.  I am using the secondary_y = True argument in .plot(), so I am not sure if changing the secondary y-axis values is possible for this. I've included my current code for creating the plot.
df.plot()
df.plot(secondary_y = "Market")

A: Setting ylim on plot does not appear to work in the case of secondary_y, but I was able to workaround with this:
import pandas as pd

df = pd.DataFrame({'one': range(10), 'two': range(10, 20)})

ax = df['one'].plot()
ax2 = df['two'].plot(secondary_y=True)
ax2.set_ylim(-20, 50)
fig = ax.get_figure()
fig.savefig('test.png')

A: From your example code, it seems you're using Pandas built in ploting capabilities. One option to add a second layer is by using matplotlib directly like in the example "two_scales.py".
It uses
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax1.plot(df["..."])
# ...
ax2 = ax1.twinx()
ax2.plot(df["Market"])
ax2.set_ylim([0, 5])

where you can change the y-limits.

A: This is a solution for showing as much y-axes as data columns the dataframe has
colors = ['tab:blue',
            'tab:orange',
            'tab:green',
            'tab:red',
            'tab:purple',
            'tab:brown',
            'tab:pink',
            'tab:gray',
            'tab:olive',
            'tab:cyan']

#X axe and first Y axe
fig, ax1 = plt.subplots()
x_label = str( dataFrame.columns[0] )
index = dataFrame[x_label]

ax1.set_xlabel(x_label)
ax1.set_xticklabels(dataFrame[x_label], rotation=45, ha="right")

firstYLabel = str( dataFrame.columns[1] )
ax1.set_ylabel(firstYLabel, color = colors[0])
ax1.plot(index, dataFrame[firstYLabel], color = colors[0])
ax1.tick_params(axis='y', labelcolor = colors[0])

#Creates subplots with independet y-Axes
axS =[]
def newTwix(label, ax1, index, dataFrame):
    print(label)
    actualPos = len(axS)
    axS.append(ax1.twinx())
    axS[actualPos].set_ylabel(label, color = colors[actualPos%10 + 1])
    axS[actualPos].plot(index, dataFrame[label], color=colors[actualPos%10 + 1])
    axS[actualPos].tick_params(axis='y', labelcolor=colors[actualPos%10 + 1])

    identation = 0.075  #would improve with a dynamic solution
    p = 1 + identation
    for i in range(2,len(dataFrame.columns)):
        newTwix(str(dataFrame.columns[i]), ax1, index, dataFrame)
        if (len(axS) == 1):
            axS[len(axS)-1].spines.right.set_position(("axes", p))
        else:
            p = int((p + identation)*1000)/1000
            axS[len(axS)-1].spines.right.set_position(("axes", p))

fig.tight_layout()  # otherwise the right y-label is slightly clipped
    plt.subplots_adjust(left=0.04, right=0.674, bottom=0.1)
    mng = plt.get_current_fig_manager()
    mng.full_screen_toggle()

    plt.show()

multiple y-axes with independent scales


text:
Q: Computer architecture - paging assume that
- accessing and searching the TLB takes 5ns
- transferring the data from the tlb into a register takes 10 ns
- updating a record in the TLB takes 15 ns
- accessing and searching the pt takes 50ns
- transfering the data from the PT into a register takes 70ns
- the TLB hit ratio is 0,6.
How many nanoseconds are needed on average to perform all the TLB and PT operations needed to compute the physical address for a given virtual address(assuming that all referenced pages are in main memory).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scipy: Convert RGB TIFF to grayscale TIFF and output it on Matplotlib I want to manipulate RGB bands in a TIFF file and output the grayscale map on matplotlib. So far I have this code, but I couldn't get it on grayscale:
import scipy as N
import gdal
import sys
import matplotlib.pyplot as pyplot

tif = gdal.Open('filename.tif')

band1 = tif.GetRasterBand(1)
band2 = tif.GetRasterBand(2)
band3 = tif.GetRasterBand(3)

red = band1.ReadAsArray()
green = band2.ReadAsArray()
blue = band3.ReadAsArray()

gray = (0.299*red + 0.587*green + 0.114*blue)

pyplot.figure()
pyplot.imshow(gray)
pylab.show()

And these are the arrays:
[[255 255 255 ..., 237 237 251]
 [255 255 255 ..., 237 237 251]
 [255 255 255 ..., 237 237 251]
 ...,
 [237 237 237 ..., 237 237 251]
 [237 237 237 ..., 237 237 251]
 [242 242 242 ..., 242 242 252]]

[[255 255 255 ..., 239 239 251]
 [255 255 255 ..., 239 239 251]
 [255 255 255 ..., 239 239 251]
 ...,
 [239 239 239 ..., 239 239 251]
 [239 239 239 ..., 239 239 251]
 [243 243 243 ..., 243 243 252]]

[[255 255 255 ..., 234 234 250]
 [255 255 255 ..., 234 234 250]
 [255 255 255 ..., 234 234 250]
 ...,
 [234 234 234 ..., 234 234 250]
 [234 234 234 ..., 234 234 250]
 [239 239 239 ..., 239 239 251]]

Any idea how can I fix this?

A: I don't have gdal installed, but a similar approach using PIL looks like this:
import numpy as np
import Image
import matplotlib.pyplot as pyplot

img = Image.open("/Users/travis/Desktop/new_zealand.tif")

img.getdata()
r, g, b = img.split()

ra = np.array(r)
ga = np.array(g)
ba = np.array(b)

gray = (0.299*ra + 0.587*ga + 0.114*ba)

pyplot.figure()
pyplot.imshow(img)
pyplot.figure()
pyplot.imshow(gray)
pyplot.figure()
pyplot.imshow(gray, cmap="gray")

It may be a simple matter of setting the color map to something besides the default ("jet") to get what you want, but I'm not sure what you're seeing.
Here are the images that are generated (don't ask me why the original is upside-down -- not sure what causes that):


text:
Q: How do I dual boot? I have windows 10 installed on my pc. It was originally windows 8. I was wondering how to dual boot with Ubuntu. I want Ubuntu to be default but I still want to keep windows so I can play video games without paying for a VM. Is it as easy as hitting the Ubuntu download button and selecting an option for dual boot? Also, why do I need to download Ubuntu to a USB drive? I just want it installed on my computer and if I need to change back to windows for gaming then have that option at startup.

A: Question: "Is it as easy as hitting the Ubuntu download button and selecting an option for dual boot?"
Answer: No

Question: "why do I need to download Ubuntu to a USB drive?"
Answer: You can't install Ubuntu from inside Windows. (Well, techincally there's Wubi, but do not use it) You need to burn the ISO to a USB drive or DVD because you need to be able to boot the computer from the ISO. As the BIOS isn't smart enough to be able to read the ISO directly from the disk, you have to boot it from some other medium.

Read this, or else you'll be doomed to failure, frustration, and possible data loss.


text:
Q: Knockout binding to checkboxes I have a list of objects that need to be (un)checked by user:
var myList = [
    { id: 1, value: "aaa", checked: true}
    { id: 2, value: "bbb", checked: false}
    { id: 3, value: "ccc", checked: true}
]

Depending on user choice some business logic must be performed over the rest elements. It must be executed after any (un)check action so I need to know what exact element was affected.
I am using knockout.js and would like to display and bind values using this approach.
Checkbox "checked" binding can be done by 2 ways: by passing the boolean that will be automatically set according to user choice, or by passing an array whose content will expose what values were checked. I was unable to get the affected listed object and therefore run business logic in both cases.

*

*When I pass a boolean to checkbox and it returns flat boolean so I couldn't know what listed object it belongs to

*When I pass an observable array then I only can subscribe to its changes but in the handler I only have the whole array and still don't know what element was affected.

Can you help me?

A: Sorry all, just found that i can provide subscriptions with the context. The full syntax for subscribe is something like
observableItem.subscribe(function (newValue) {...}, context, stringVal)

where stringVal can be "beforeChange" that will subscribe you to the event before change. I didnt know that as they don't document it at the official site. Btw anybody knows where the latest docs are?


text:
Q: where should the mybatis-config.xml, the main configuer file of myBatis, be placed in? I am developing an application based on Spring and myBatis 3.3.1 in myEclipse 10 IDE.
My question is: where should the mybatis-config.xml, the main configuer file of myBatis, be placed in? According to official documents, it should be placed in classpath, but in myEclipse 10 where is the classpath?

A: It depends on which type of build tool you are using. If you are using Maven/Gradle then put it in src/main/resources folder.


text:
Q: GPUImageMovie Not Support Alpha Channel? I create Video Effect by GPUImage like this
self.overlayerView = [[GPUImageView alloc] init];
self.overlayerView.frame = self.view.frame;

dispatch_queue_t queue = dispatch_queue_create("queue", NULL);
dispatch_async(queue, ^{

    NSURL *sourceURL = [[NSBundle mainBundle] URLForResource:@"212121" withExtension:@"mp4"];
    GPUImageMovie *sourceMovie = [[GPUImageMovie alloc] initWithURL:sourceURL];
    sourceMovie.playAtActualSpeed = YES;
    sourceMovie.shouldRepeat = YES;

    sourceMovie.shouldIgnoreUpdatesToThisTarget = YES;

    NSURL *maskURL = [[NSBundle mainBundle] URLForResource:@"rose" withExtension:@"mp4"];
    GPUImageMovie *maskMovie = [[GPUImageMovie alloc] initWithURL:maskURL];
    maskMovie.playAtActualSpeed = YES;
    maskMovie.shouldRepeat = YES;

    NSURL *alphaURL = [[NSBundle mainBundle] URLForResource:@"rose_alpha" withExtension:@"mp4"];
    GPUImageMovie *alphaMovie = [[GPUImageMovie alloc] initWithURL:alphaURL];
    alphaMovie.playAtActualSpeed = YES;
    alphaMovie.shouldRepeat = YES;

    NSURL *topURL = [[NSBundle mainBundle] URLForResource:@"screen" withExtension:@"mp4"];
    GPUImageMovie *topMovie = [[GPUImageMovie alloc] initWithURL:topURL];
    topMovie.playAtActualSpeed = YES;
    topMovie.shouldRepeat = YES;

    filter0 = [[GPUImageThreeInputFilter alloc] initWithFragmentShaderFromString:@"precision highp float;uniform sampler2D inputImageTexture;uniform sampler2D inputImageTexture2;uniform sampler2D inputImageTexture3;varying vec2 textureCoordinate;void main(){vec4 video=texture2D(inputImageTexture,textureCoordinate);vec4 mv=texture2D(inputImageTexture2, textureCoordinate);vec4 alpha = texture2D(inputImageTexture3, textureCoordinate);gl_FragColor = video * (1.0 - alpha.r) + mv;}"];

    filter1 = [[GPUImageTwoInputFilter  alloc] initWithFragmentShaderFromString:@"\nprecision highp float;\nuniform sampler2D inputImageTexture; //video\nuniform sampler2D inputImageTexture2; //screen\nvarying vec2 textureCoordinate;\nvoid main()\n{\nvec4 video = texture2D(inputImageTexture, textureCoordinate);\nvec4 screen = texture2D(inputImageTexture2, textureCoordinate);\nmediump vec4 whiteColor = vec4(1.0);\ngl_FragColor = whiteColor - ((whiteColor - screen) * (whiteColor - video));\n}"];

    [sourceMovie addTarget:filter0];
    [maskMovie addTarget:filter0];
    [alphaMovie addTarget:filter0];
    [filter0 addTarget:filter1];
    [topMovie addTarget:filter1];

    [sourceMovie startProcessing];
    [alphaMovie startProcessing];
    [maskMovie startProcessing];
    [topMovie startProcessing];

    [filter0 forceProcessingAtSize:CGSizeMake(480,480)];
    [filter1 forceProcessingAtSize:CGSizeMake(480,480)];

    dispatch_async(dispatch_get_main_queue(), ^{
        [filter1 addTarget:self.overlayerView];
    });
});

Code can run and i got the video effect like this

The video has a black background that is because the alphaMovie not play the same time with the maskMovie?
This is what i want to create

The effect video no black background
Question:
1: How can i remove the black background ?
2: Why i the effect video have black background ?

A: The GPUImage framework does not contain support for an alpha channel feature like that. There is a green screen feature, so if you pre-produce your video against a green screen then it is possible to split the video from the green screen background. But, what you describe here is an alpha channel video and a second video and that it not going to work properly because you are pulling from two different video sources at the same time and they will not stay in sync. Note that even with the green screen feature, there are issues with the exact edges, as described in this blog post (includes source code). The basic problem is that edges that are near green but not exactly green can be treated in odd ways by the filter ramp. Another approach you might want to think about is to just precompose the N frames down to 1 video before attempting to playback the video with the iOS video logic.


text:
Q: When exactly getApplicationContext will be assigned? In my application, A is an activity which will be launched first. The code is as follows:
    public class A extends Activity {

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Here I'm checking if the user has already got registered, using shared preference. If yes, I want to fetch the version of this application and start Activity B. Other wise perform some other operation.

  if(Registered) {

    //Here, I'm trying to fetch the version of my own application.

    PackageManager manager = getApplicationContext()
                            .getPackageManager();
                    PackageInfo info;
                    try {
                        info = manager.getPackageInfo(getApplicationContext()
                                .getPackageName(), 0);
                        String version = info.versionName;

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

So, as soon as my application gets installed, this code will be executed. Here I'm getting NameNotFoundException. It is caught but still causing me some problem.
getApplicationContext cannot be null in the above code. If it was, then "manager" would be null causing null pointer exception. What might have really happened to cause NameNotfoundException?? Please help.

A: Use
 PackageManager manager = A.this.getPackageManager();

A: Here the Context that should be used is this ,i.e the Activity Context.
Note that:
Application Cotext : Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.


text:
Q: compare rows based on the value of some columns and update the table I have a table that contains 5 columns,for example:
 f_id          s_id         t_id        string        date
  1             2            3          aaa_C       15/03/2008 10:30:00
  1             2            4          vvv_C       15/03/2008 10:30:00
  1             2            4          sss_C       15/03/2008 20:00:00
  1             2            3          xxx_B       15/03/2008 10:30:00
  1             2            5          yay_B       15/03/2008 10:30:00

I'm trying to compare rows to check if:
row1.f_id = row2.f_id = row3.f_id....and row1.s_id = row2.s_id = row3.s_id...
and row1.date = row2.date = row3.date..and row1.string like '%_samesuffix' and row2.string like '%_samesuffix'...

Then the output should be like this:
f_id          s_id         t_id        string        date
  1             2            3           C          15/03/2008 10:30:00
  1             2            4          sss_C       15/03/2008 20:00:00
  1             2            5           B          15/03/2008 10:30:00

I will be grateful for any hints.


text:
Q: Online collection of small public video files encoded with different codecs for testing purposes I'm trying to spot a bug in a video player and I suspect that it's related to a particular codec.
Is there a site that contains a collection of small public-domain video snippets (1-2 MB) encoded with misc video codecs for testing purposes?

A: Archive.org has hundreds of thousands of videos which are in the public domain, which are in a TON of different formats.


text:
Q: Azure AD B2C - Change Domain When you create a B2C tenant and prompted to provide a temporary .onmicrosoft.com domain, the tooltip says that this can be changed later on to a domain our organization currently uses.

How do we go about accomplishing this and changing the domain?
Thanks!

A: Please refer to Add your custom domain to Azure AD.
After the custom domain is added, you may add a local account with it.

A: As per the FAQ:
"Can I use my own URLs on my sign-up and sign-in pages that are served by Azure AD B2C? For instance, can I change the URL from contoso.b2clogin.com to login.contoso.com?
Not currently. This feature is on our roadmap. Verifying your domain in the Domains tab in the Azure portal does not accomplish this goal. However, with b2clogin.com, we offer a neutral top-level domain, and thus the external appearance can be implemented without the mention of Microsoft".


text:
Q: Adding extra information to a subtotal row by linking to another spreadsheet in excel My task is to add another column to a backlog and link data from another worksheet to the backlog. The data should be linked to the corresponding subtotal row in the backlog by inputting the data to a new column in the backlog.  The problem is that I can't figure out how to link the cells without going one-by-one.  Each time I've tried I've come into issues that have to do with data hiding. Since I have to do this with large amounts of information, I don't have the time to do this work one-by-one.  Is there any time-efficient solution for this?

A: In 'new column' first subtotal row, lookup the value of what you want from the row immediately above. Filter on subtotals and copy down the new formula.


text:
Q: Java empty array Currently I'm trying to receive information from a mysql database with the Volley libary (with http request). But when I want to display the information in my android app I receive lots of errors.

10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime: FATAL EXCEPTION: main
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime: Process: com.example.jamie.fysio, PID: 11718
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime: java.lang.NullPointerException: Attempt to read from null array
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at com.example.jamie.fysio.Home.showJSON(Home.java:79)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at com.example.jamie.fysio.Home.access$000(Home.java:28)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at com.example.jamie.fysio.Home$1.onResponse(Home.java:55)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at com.example.jamie.fysio.Home$1.onResponse(Home.java:52)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:739)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:145)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:6872)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
  10-07 20:51:27.205 11718-11718/com.example.jamie.fysio E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

This is my method for parsing the JSON:
public class parseJSON {
    public static String[] adres;

    public static final String JSON_ARRAY = "result";
    public static final String ADRES = "adres";

    private JSONArray users = null;

    private String json;

    public parseJSON(String json){
        this.json = json;
    }

    protected void parseJSONMeth(){
        JSONObject jsonObject=null;
        try {
            jsonObject = new JSONObject(json);
            users = jsonObject.getJSONArray(JSON_ARRAY);

            adres = new String[users.length()];

            for(int i=0;i<users.length();i++){
                JSONObject jo = users.getJSONObject(i);
                adres[i] = jo.getString(ADRES);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

And this is my sendrequest :
private void sendRequest(){

    StringRequest stringRequest = new StringRequest(Request.Method.POST,JSON_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    showJSON(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(Home.this, error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> map = new HashMap<String, String>();
        map.put(KEY_USERNAME, gebruikersnaam);
        return map;
    }
};

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private void showJSON(String json) {
    parseJSON pj = new parseJSON(json);
    pj.parseJSONMeth();
    adres.setText(parseJSON.adres[0]);
}

}
I"m not very familiar with the volley libary what am I doing wrong?

A: the response you get from the onResponse(String response) doesn't seem to pass a valid JSONObject which leads to a JSONException being caught before adres is assigned.
Check your JSON_URL.
By the way adres shouldn't be static, and should be accessed through pj.


text:
Q: Sharp bound on off-diagonal entries of matrix with 1's on diagonal to make matrix invertible Suppose $A$ is an $n \times n$ matrix with all 1 on the diagonal. What is the sharp bound $\epsilon(n)$ so that $A$ is invertible if all off-diagonal entries of $A$ have absolute value less than $\epsilon(n)$?  Obviously $\epsilon(n) > 0$ exists, because as all off-diagonal elements go to zero, $A$ approaches the identity matrix which is invertible.

A: Let $S$ be the set of non-negative real numbers $r$ for which if $|a_{i,j}|\lt r$ for all $i\neq j$, then $A$ is invertible. We have that $S\supset \left(0,\frac 1{n-1}\right]$  (because in this case $A$ is diagonal dominant, hence invertible). We can't hope more (take $a_{i,j}:=\frac 1{n-1}$; then $A$ is not invertible).


text:
Q: Query dramatically slower with less rows from WHERE to evaluate What is the query
SELECT SQL_NO_CACHE id, laptime, driver_id, driverName
FROM (
   SELECT race_result_details.id id, driver_id, driver.name as driverName, laptime
   FROM race_result_details
   LEFT JOIN races ON races.id = race_result_details.race_id
   LEFT JOIN `drivers` `driver` ON `race_result_details`.`driver_id` = `driver`.`id` AND driver.name != ""
   WHERE (
    `race_result_details`.driver_id IS NOT NULL
    AND races.track_length_id = 2
    AND `race_result_details`.lap_number > 0
    AND `race_result_details`.laptime > 3449
    AND `race_result_details`.`timestamp` > 1197426432
   )
   ORDER BY `race_result_details`.laptime ASC
   limit 100
) f
GROUP BY driverName
order by laptime ASC
LIMIT 10;

What does it do
It selects the best ranked racers based on their minimal laptime, showing maximum once per driver name.
It does so pretty well until I change the track_length_id to 2. Well, that should return faster, because we have less races with track_length_id = 2 right?
MariaDB > SELECT COUNT(*) FROM races WHERE races.track_length_id = 1;
+----------+
| COUNT(*) |
+----------+
|    33396 |
+----------+
1 row in set (0.038 sec)

MariaDB > SELECT COUNT(*) FROM races WHERE races.track_length_id = 2;
+----------+
| COUNT(*) |
+----------+
|     7919 |
+----------+
1 row in set (0.026 sec)

not really! Explain please.
id 1
+------+-------------+---------------------+--------+-------------------------------------+---------+---------+---------------------------------------------+--------+---------------------------------+
| id   | select_type | table               | type   | possible_keys                       | key     | key_len | ref                                         | rows   | Extra                           |
+------+-------------+---------------------+--------+-------------------------------------+---------+---------+---------------------------------------------+--------+---------------------------------+
|    1 | PRIMARY     | <derived2>          | ALL    | NULL                                | NULL    | NULL    | NULL                                        | 100    | Using temporary; Using filesort |
|    2 | DERIVED     | race_result_details | range  | race_id,timestamp,laptime,driver_id | laptime | 4       | NULL                                        | 598051 | Using where                     |
|    2 | DERIVED     | races               | eq_ref | PRIMARY,track_length_id             | PRIMARY | 4       | speeder_nette.race_result_details.race_id   | 1      | Using where                     |
|    2 | DERIVED     | driver              | eq_ref | PRIMARY                             | PRIMARY | 4       | speeder_nette.race_result_details.driver_id | 1      | Using where                     |
+------+-------------+---------------------+--------+-------------------------------------+---------+---------+---------------------------------------------+--------+---------------------------------+

vs id 2
+------+-------------+---------------------+--------+-------------------------------------+-----------------+---------+---------------------------------------------+------+----------------------------------------------+
| id   | select_type | table               | type   | possible_keys                       | key             | key_len | ref                                         | rows | Extra                                        |
+------+-------------+---------------------+--------+-------------------------------------+-----------------+---------+---------------------------------------------+------+----------------------------------------------+
|    1 | PRIMARY     | <derived2>          | ALL    | NULL                                | NULL            | NULL    | NULL                                        | 100  | Using temporary; Using filesort              |
|    2 | DERIVED     | races               | ref    | PRIMARY,track_length_id             | track_length_id | 4       | const                                       | 7919 | Using index; Using temporary; Using filesort |
|    2 | DERIVED     | race_result_details | ref    | race_id,timestamp,laptime,driver_id | race_id         | 5       | speeder_nette.races.id                      | 23   | Using where                                  |
|    2 | DERIVED     | driver              | eq_ref | PRIMARY                             | PRIMARY         | 4       | speeder_nette.race_result_details.driver_id | 1    | Using where                                  |
+------+-------------+---------------------+--------+-------------------------------------+-----------------+---------+---------------------------------------------+------+----------------------------------------------+

So, I kinda see that the planner picked up a way which seemed like an optimal one and failed. I had some class about database systems in university but it's not enough to understand this correctly.
I've been trying to switch up the indexes in race_result_details table (but that doesn't seem to be a problem in the first place), swap the order of WHERE clauses (does it really matter? I feel like I remember instances where it did help, but that's probably related only to multi column indexes, am I right?).
The difference is huge, 0.011s to 3.5s
Is there a good way to trick the planner to pick the way it did for the first query?
Edit:
Tables (trimmed to minimal example):
CREATE TABLE `drivers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) NOT NULL DEFAULT '',
  `username` varchar(128) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `races` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `track_length_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `track_length_id` (`track_length_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `race_result_details` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `race_id` int(11) DEFAULT NULL,
  `race_group_id` int(11) DEFAULT NULL,
  `driver_id` int(11) DEFAULT NULL,
  `lap_number` int(11) NOT NULL,
  `laptime` int(11) NOT NULL COMMENT 'real lap time',
  `timestamp` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `race_id` (`race_id`),
  KEY `timestamp` (`timestamp`),
  KEY `laptime` (`laptime`),
  KEY `driver_id` (`driver_id`),
  CONSTRAINT `race_result_details_ibfk_1` FOREIGN KEY (`race_id`) REFERENCES `races` (`id`),
  CONSTRAINT `race_result_details_ibfk_3` FOREIGN KEY (`driver_id`) REFERENCES `drivers` (`id`) ON DELETE SET NULL,

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Changing LEFT JOIN to JOIN and deleting driver_id from the where didn't change anything at all.

A: So I did some last second googling after formuling the sentences which I wanted to ask and came up with an answer for one of them:
Is there a good way to trick the planner to pick the way it did for the first query?
Yes, there is! The index key used on the biggest table was "laptime" on the fast query. I am not sure why laptime (maybe it has the lowest number of values in it? Correct me if wrong please.)
It was just enough to add
FORCE INDEX (laptime)

just after FROM clause and it started to work lightning fast again. Yahoo! I keep this question here for future strugglers. I am still looking for somebody to answer more in depth response, which I will hopefuly get.


text:
Q: Tag to ignore HTML formatting code? I thought the  tags were supposed to ignore HTML like with BBcode, but that doesn't seem to be the case. Is there a way to achieve this in HTML so I can show code examples? I found a page about <plaintext> and <xmp>, but they're apparently deprecated, so what should I use? I've seen  tags for comments, but those are completely hidden from view. I just need something to ignore tags.

A: In HTML, the only solution guaranteed to work everywhere is to escape the code manually.

*

*Replace the < character with <

*Replace the > character with >

*Optionally surround your HTML sample with or without tags. (e.x.  or
)


text:
Q: How to use generated token from passport Laravel oAuth Can someone assist me here, i have succeeded in setting up my passport on laravel 5.4 everything seems to work perfected. My question is once token is generated, am i supposed to save it for subsequent usage? i am just confused on the workflow. I am using password grant. I want to know how to pass token to another route that is making another call to another endpoint once token has been generated.

A: You append the token generated for each and every subsequent request that needs to be authenticated.In this case attach to the Authorization header of the request. Something like this:
Bearer eJ0eXAiOi.......


text:
Q: How can I make an svg circle always appear above my graph line path? I have a mousemove function that makes it so that when the user moves their mouse over the graph, a circle with a box on top, displaying information, moves to the closest data point. It all works fine, except that the circle appears underneath the path line which looks really bad. I would like this circle to on top of this line yet reordering and using z-index have not merited success. Any help would be greatly appreciated. Here is my mouseMove and draw function, which I believe should be the only relevant code.
rrd3.mouseMove = function(){
    var xMouse = rrd3.xScale.invert(d3.mouse(this)[0]),
        index = d3.bisector(function(d){return d.timestamp}).left(rrd3.data, xMouse, 1),
        d0 = rrd3.data[index - 1],
        d1 = rrd3.data[index],
        d;

        if(d0 == undefined){
            d0 = d1;
        }
        if(d1 == undefined){
            d1 = d0;
        }

        if((xMouse - d0.timestamp) > (d1.timestamp - xMouse))
            d = d1;
        else
            d = d0;

    d3.select(".focusCircle")
        .attr("cx", rrd3.xScale(d.timestamp))
        .attr("cy", rrd3.yScale(d.count));

    d3.select(".focusLine")
        .attr("x1", rrd3.xScale(d.timestamp))
        .attr("y1", 0)
        .attr("x2", rrd3.xScale(d.timestamp))
        .attr("y2", rrd3.height)
        .attr("stroke-width", 2);

    rrd3.tooltip.style("top", rrd3.yScale(d.count) - 10 + "px");
    rrd3.tooltip.style("left", rrd3.xScale(d.timestamp) + rrd3.leftMargin + "px");
    rrd3.tooltip.html("
" + d.count + "
Listeners");
};

rrd3.draw = function(){
    d3.select(".line").remove();
    d3.select(".areapath").remove();

    rrd3.graph.append("path")
        .datum(rrd3.data)
        .attr("class", "line")
        .attr("d", rrd3.line)
        .attr("fill", "none")
        .attr("stroke", "#5a8fc2")
        .attr("stroke-width", "1.5px");

    rrd3.graph.append("path")
        .datum(rrd3.data)
        .attr("class", "areapath")
        .attr("d", rrd3.area);
};

A: You can use sort() function of d3.js to change svg order.
This is a sample code.
// draw a circle
d3.select("svg").append("circle").datum({type: "circle"}).attr({
    cx: 100,
    cy: 100,
    r: 30,
    fill: "blue"
});
// draw a triangle
d3.select("svg").append("path").datum({type: "triangle"}).attr({
    d: "M100,100 L150,150 V100 z",
    fill: "red"
});

// Here, triangle is shown over circle,
// because it is positioned after circle.
// e.g.
// <svg>
//     <circle ... />
//     <path ... />
// </svg>

// re-order by sort() function
d3.selectAll("circle, path").sort(function(d1, d2) {
    if (d1.type === d2.type)
        return 0;
    return d1.type === "circle" ? 1 : -1;
});

// Here, circle is shown over triangle.
// <svg>
//     <path ... />
//     <circle ... />
// </svg>


text:
Q: How do I make a cefpython Kivy widget I am trying to embed a browser using cefpython3 within my kivy application - I don't need a ton of functionality (I just need the browser to run some javascript for me).
I downloaded the cefpython3 repo and got the hello_world.py to work, and now I am simply trying to get that window that pops up into a kivy widget.
The examples seem pretty dated and people are saying that they only developed in certain environments - what would I have to do/learn to make a widget and drop this browser in there?


text:
Q: MySql, Engine Memory, index needed for this simple table? I'm trying to implement a very fast table meant to store relationships between users.
CREATE TABLE IF NOT EXISTS `friends_ram` (
`a` varchar(16) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`b` varchar(16) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL
) ENGINE=MEMORY DEFAULT CHARSET=latin1;
INSERT INTO friends_ram (a, b)

I made some tests with circa 5M of relations and it's blazing fast and it occupies circa 134MB of ram; my question is, since the queries will be:
SELECT a WHERE b = 'foo';

or
SELECT b WHERE a = 'baar';

I'd like to know if I should use a proper indexing (increasing the size of RAM required).

A: I'm actually ashamed of the results,
Probably the first time I made the tests i misread the output.
Turns out that with 1000 random queries without index on a or b it takes 1000 the times with proper indexing. ahem...
Another very important thing to notice is that I tried with memcached. while it takes a little longer to store data it's faster for retrieval. also it consumes way less memory.
mysql 192MB -> Mysql MEMORY engine did it in; 0.50138092041016 seconds
memcached  76MB -> Memcache engine did it in; 0.34592795372009 seconds
memcached compressed: 45.4 MBytes -> Memcache engine did it in; 0.31583189964294 seconds

so, if you need to store simple things such as these I'd recommend memcached (compressed)


text:
Q: Dealing with an invalid edit Revision in question
This editor took my correct answer, and turned it into an incorrect one. This led to negative comments, and even a downvote before I was able to roll it back and explain what happened.
Besides the rollback, is there anything that can be done to prevent this happening again? I ask this mainly out of curiousity, since this does have potential to sabotage other people's answers.

A: If they continue rolling back your rollback you could flag, but in this particular case it looks like it's just a simple mistake, not malicious or abusive behavior.  Given that, rolling back the edit as you've done should be fine.  If you want you could post a comment on your answer explaining the reason you rolled it back and giving the editor an opportunity to explain their decision or at least understand their mistake.  (Note that you can reply to an editor using the @ functionality.  Even though it won't auto-complete their name it will notify them if you type it out.)


text:
Q: Sharing List with BackgroundWorker across two forms I'm trying to build a little image widget. It's supposed to starts up with a splash screen that loads images from an XML list, puts them in a List inside an object, and then closes that form and returns to the MainWindow. I use a BackgroundWorker on the splash screen so I can exit out if I want.
As far as I can tell the splash screen is working, at least the list's Count shows it has objects in it when the MainWindow checks. The problem I'm having is when I try to access the objects in the List. Then I get the following error: The calling thread cannot access this object because a different thread owns it.
I've tried Delegates, a static object, and even passing a copy of the MainWindow into the Splash form (which is the version I'm pasting). However, I cannot solve this problem. Any help would be welcome.
Splash.xaml.cs
namespace Yvonne1
{
    public partial class Splash : Window
    {
        public BackgroundWorker bw;
        public string url = @"http://domain.com/pics-list.php";
        public MainWindow mw;
        public XmlNodeList xl;
        public Splash()
        {
            InitializeComponent();
            SetupWorker();
            FetchXml();
            progOne.Maximum = xl.Count;
            bw.RunWorkerAsync();
        }

        private void SetupWorker()
        {
            bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
        }

        private void FetchXml()
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(this.url);
                this.xl = doc.SelectNodes("//image");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.DialogResult = false;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            bw.CancelAsync();
            this.DialogResult = false;
        }

        public void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            int xcount = 0;
            foreach(XmlNode xn in xl)
            {
                string full = xn.FirstChild.InnerText;
                string thumb = xn.LastChild.InnerText;
                BitmapImage temp = new BitmapImage(new Uri(thumb));
                mw.p1.New = new Piccy(full, thumb, temp);

                xcount += 1;
                bw.ReportProgress(xcount);

                Thread.Sleep(200);
                if (bw.CancellationPending == true)
                {
                    e.Cancel = true; return;
                }
            }
        }

        public void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progOne.Value = Double.Parse(e.ProgressPercentage.ToString());
            int done = int.Parse(progOne.Value.ToString()) - 1;
            Piccy temp = mw.p1.Get(done);
            txtStatus.Text = "Fetched: " + temp.Thumb;
        }

        public void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (progOne.Value == progOne.Maximum)
            {
                this.DialogResult = true;
            }
        }
    }
}

MainWindow.xaml.cs (The part with the error.)
private void StartUp()
{
    try
    {
        MessageBox.Show(p1.Count.ToString());
        Piccy temp = p1.Get(1);
        imgMain.Source = temp.Img;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message+"\n\n"+ex.Source+"\n\n"+ex.StackTrace, "Error");
    }
}

The line imgMain.Source = temp.Img; is where the thread error shows up.
Thanks in advance.
UPDATE: The BitmapImage temp = new BitmapImage(new Uri(thumb)); line is where the trouble was. Thanks.

A: try this I  hope this will solve your issue
private void StartUp()
{
 try
 {
    MessageBox.Show(p1.Count.ToString());
    Piccy temp = p1.Get(1);
    this.Dispatcher.Invoke((Action)(()=>imgMain.Source = temp.Img);
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message+"\n\n"+ex.Source+"\n\n"+ex.StackTrace, "Error");
  }

}

A: You can add a Singleton class, which will house a public List. The advantage of using singletons is that there is always one instance of the class/object (and the List too) and that every class or thread can get the Instance of that Singleton class. If implemented correctly that means that you can access all the variables and methods in this Singleton from each class and thread in your program.
Read more and see how to implement it at: http://msdn.microsoft.com/en-us/library/ff650316.aspx and http://msdn.microsoft.com/en-us/library/ff650849.aspx


text:
Q: Setting onClickListner for items within popup window in android I have a popup window that contains 2 text views.
If user click on one text view toast must appear.I coded for this function but shows Nullpointer exception in line far.setOnClickListener(new OnClickListener() { Please help me on this.
My code :
btn_a.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View popup_view = lInflater.inflate(R.layout.popup_a, null);
            final PopupWindow popup = new PopupWindow(popup_view,200,75,true);
            popup.setFocusable(true);
            popup.setBackgroundDrawable(new ColorDrawable());
            popup.showAsDropDown(btn_a,  0,0);

            TextView far = (TextView) rootView.findViewById(R.id.fartext);
            far.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(), "Clicked Far", Toast.LENGTH_SHORT).show();

                }
            });
        }
    });

A: Change this line
TextView far = (TextView) popup_view.findViewById(R.id.fartext);

instead of this
TextView far = (TextView) rootView.findViewById(R.id.fartext);

A: You get a NullPointerException because you are trying to set a click listener on a view that is actually part of your popup_view and not rootView. Fix it like this:
TextView far = (TextView) popup_view.findViewById(R.id.fartext);
            far.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(getActivity(), "Clicked Far", Toast.LENGTH_SHORT).show();

                }
            });

A: The problem is your are looking in rootView where fareText is not exists. You should look into the inflated layout. Check below code.
btn_a.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View popup_view = lInflater.inflate(R.layout.popup_a, null);
        final PopupWindow popup = new PopupWindow(popup_view,200,75,true);
        popup.setFocusable(true);
        popup.setBackgroundDrawable(new ColorDrawable());
        popup.showAsDropDown(btn_a,  0,0);

        TextView far = (TextView) popup_view.findViewById(R.id.fartext);
        far.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Clicked Far", Toast.LENGTH_SHORT).show();

            }
        });
    }
});


text:
Q: access master router from a pc via a mid router placed inbetween PC and master router I have 2 routers, Master router which is ADSL broadband modem/router (192.168.0.1). which is connected to a telephone ISP. then a Mid router which has Wan port connected to the master router's lan port(192.168.0.2) and Its LAN port is configured as 192.168.1.1 and it provides dhcp server as 192.168.1.x as ip and 192.168.1.1 as gateway.
I am able to connect to the internet from 192.168.1.10 with router as 192.168.1.1.
My question is i want to access the master router which is (http:// 192.168.0.1) from 192.168.1.10.
I want it to be stacked. dont want to end up with single flat network

A: Don't "stack" up Network Address Translating (NAT) routers like that.
Disable the DHCP server on the "Mid router" (sic) and configure it with a static IP address other than 192.168.1.1 in the 192.168.1.0/24 subnet. Connect it to a LAN port on the "Master router" (sic).
This will eliminate a redundant NAT step and an unnecessary DHCP server. You'll end up with a single "flat" network and you'll be able to access the user interfaces of both routers (the "Master" at 192.168.1.1, and the "Mid" at whatever IP address you assign to it).

Edit:
Change the network addressing on the "Mid router" (sic) LAN network to some subnet other than 192.168.1.0/24. Then you will be able to access the "Master router" user interface.


text:
Q: breaking equation and different alignments I would like to break the following two equations. I would like for them to have the colons aligned together, but besides that they should have their own, unique alignment points. Please see the picture for a reference regarding alignment of the colons.
Here is a MWE illustrating the problem:
\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{alignat*}{2}
a + a + a + a + a + a \quad &: \quad \alpha + \alpha + \alpha + \alpha + \alpha =&& +1 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2\\
        &                && -3 + 4-3 + 4-3 + 4-3 + 4-3 + 4-3 \\
a \quad &: \quad \beta  =&& +4+4+4+4+4+4+4+4+4+4+4+4+4+4+4 \\
        &                && +4+4+4+4+4+4+
\end{alignat*}
\end{document}

A: You could have two separate alignat* environments inside a gather* environment:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{gather*}
\begin{alignat*}{2}
a + a + a + a + a + a \quad &: \quad \alpha + \alpha + \alpha + \alpha + \alpha =&& +1 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2\\
        &                && -3 + 4-3 + 4-3 + 4-3 + 4-3 + 4-3
\end{alignat*}\\
\begin{alignat*}{2}
a \quad &: \quad \beta  =&& +4+4+4+4+4+4+4+4+4+4+4+4+4+4+4 \\
        &                && +4+4+4+4+4+4
\end{alignat*}
\end{gather*}
\end{document}

A: A solution using two aligned environments within an align, to have a partial alignment of the two groups of equations. I think aligning inside the groups a little further looks better:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[upright]{fourier}
\usepackage[showframe, nomarginpar]{geometry}

\usepackage{mathtools}

\begin{document}

\begin{align*}
a + a + a + a + a + a \quad & : \quad \begin{aligned}[t]
\alpha + \alpha + \alpha + \alpha + \alpha = +1 & + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2 + 2\\
         & -3 + 4-3 + 4-3 + 4-3 + 4-3 + 4-3 \\
\end{aligned}\\[1ex]
a \quad & : \quad \begin{aligned}[t]
\beta = +4+4+4 & +4+4+4+4+4+4+4+4+4 \\&+4+4+4 +4+4+4+4+4+4+{}
\end{aligned}
\end{align*}

\end{document}

Depending on the context, the aligned environments could as well be multilined environments


text:
Q: bluetooth profiles in-use on Windows 10 tl;dr how do I list in-use "bluetooth profiles".
In Windows 10, I would like a listing of Bluetooth Profiles currently in-use for Bluetooth connected devices. Is there a Powershell command or application for this?
For example, which profile (and codec) is my bluetooth-connected headset currently using?

A: Here is a partial answer that will list the Service of active bluetooth devices; use cmdlet Get-PnpDevice and filter "Bluetooth" devices.
Get-PnpDevice | Where-Object {$_.Class -eq "Bluetooth"}

Using Format-Table to filter properties, the interesting properties were:
PS> Get-PnpDevice | Where-Object {$_.Class -eq "Bluetooth"} | `
Format-Table -Property Name,Present,Status,Service,Description,Caption -Wrap -AutoSize | out-string -width 9999

Here is a sampling of the output I get
Name                                   Present Status Service                            Description                                Caption
----                                   ------- ------ -------                            -----------                                -------
Personal Area Network NAP Service         True OK                                        Personal Area Network NAP Service          Personal Area Network NAP Service
BT-850ANC Avrcp Transport                 True OK     Microsoft_Bluetooth_AvrcpTransport Microsoft Bluetooth Avrcp Transport Driver BT-850ANC Avrcp Transport
BT-850ANC                                 True OK                                        Bluetooth Device                           BT-850ANC
HEADSET123                                True OK                                        Bluetooth Device                           HEADSET123
HEADSET123 Avrcp Transport                True OK     Microsoft_Bluetooth_AvrcpTransport Microsoft Bluetooth Avrcp Transport Driver HEADSET123 Avrcp Transport
Bluetooth Device (RFCOMM Protocol TDI)    True OK     RFCOMM                             Bluetooth Device (RFCOMM Protocol TDI)     Bluetooth Device (RFCOMM Protocol TDI)
Realtek Bluetooth 5.1 Adapter             True OK     BTHUSB                             Realtek Bluetooth 5.1 Adapter              Realtek Bluetooth 5.1 Adapter
Object Push Service                       True OK                                        Object Push Service                        Object Push Service
...

Both BT-850ANC and HEADSET123 are headsets. But HEADSET123 is off. Whereas BT-850ANC is connected and active.
Unfortunately, this does not cleanly list formal Bluetooth profiles. Also, it's not clear which devices are currently active and connected.
However, it is a starting point.

Thanks to @Vomit IT - Chunky Mess Style suggesting this related (but not the same) question How to list bluetooth devices near me using PowerShell.


text:
Q: Updating Redux state partially using object.assing I got a React/Redux app that receives posts from a server. So far, I got the RECEIVE_POSTS right in my reducer, which looks as follows:
function posts(
    state = {
        items: []
    },
    action
) {
    switch (action.type) {
        case RECEIVE_POSTS:
            return Object.assign({}, state, {
                items: action.posts,
            })
        case ADD_POST:
        default:
            return state
    }
}

Now for the other cases, I am struggling with the Object.assign syntax. How would I update the state in the ADD_POST case , where a newly created post contained in action.post is to be appended to the existing items?

A: Assuming CREATE_POST refers to ADD_POST based on receiving post data, it would look like this :
case CREATE_POST:
  return {...state, items: state.items.concat(action.post)};

No need to use object assign since you can just concat your post with the already existing posts from your state. As a reminder, concat does not mutate state, it returns a new array with the added post.

A: This is done assuming that a single post inside an array is being passed
function posts(
    state = {
        items: []
    },
    action
) {
    switch (action.type) {
        case RECEIVE_POSTS:
            return Object.assign({}, state, {
                items: action.posts,
            })
        case CREATE_POST:
            return Object.assign({}, state, {
                items: [...state.items, ...action.post]
            })
        default:
            return state
    }
}


text:
Q: Castle Project Active Record or Fluent NHibernate We've been looking at using an ORM at work.
Currently we are trying to way up the pro's and con's of fluent nhibernate against castle active record.
We are unsure of the flexibility of each as our database isn't very conventional. It lacks foreign keys and identities on the primary keys (A little confusing but the next value is stored in a seperate table). Also there are a few situations where we have table names suffix'd by the year. We then select from one depending on the year. This could obviously be a little trickier.
I've currently managed to sort the foreign key mapping using castle and also the primary key generation by create a custom class.
Does any one have any opnions on either of these frameworks and or ideas of how to solve these problems with either.
Ps. please don't ask us to refactor the database. Its not an option at the moment.
Thanks.

A: FluentNHibernate and ActiveRecord are quite different.
The first one is just codified, convention driven mapping generator for NHibernate.
The latter is a layer of abstraction on top of NHibernate along with implementation of the Active Record pattern.
Castle Active Record does hide certain aspects of NHibernate from you, taking care of some things by itself. As such it may be less flexible option if you already have a convoluted existing database.
FluentNHibernate just generates your mappings and you use NHibernate directly all the time to interact with your database.
So while I'm not the expert in any of these, I'd say for such convoluted DB you want to stay as close to the metal as possible, so perhaps bare NHibernate (mapped via FluentNHibernate or hbms where required), or even IBatis.NET would be a better option for you.
Where ActiveRecord shines, is when you start your project from scratch, with no legacy DB.

A: Here is a database first approach code generator, which supports Both Castle ActiveRecord and EntityFramework CodeFirst.
Give it a try.
http://salardbcodegenerator.codeplex.com/

A: An updated answer. Just in case someone is still considering Castle Active Record.
Castle ActiveRecord is obsolete. Meaning, that you cannot use it with NHibernate version >= 3.3.


text:
Q: RedisStore - on error callback I'm using connect-redis - https://github.com/visionmedia/connect-redis
in my project.
Is there any on error event? Something, where I can put callback to tell me,
that (for example) my app can't connect to redis server?
I tried to search but I have found nothing useful.
Part of my config code:
app.use(express.methodOverride());
app.use(expressLayouts);
app.use(express.json());
// app.use(express.logger('dev'));

app.use(express.cookieParser());
app.use(express.session({
    secret: 'have a fun',
    maxAge: new Date(Date.now() + 3600000),
    store: new RedisStore( config[app.get('env')].redis ),
    // store: new FileStore({path:'./data/sessions', useAsync:true})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

app.use(app.router);

Every useful tip is welcome...

A: The library you are using is backed by awesome node-redis hence it should have events attached to it like error event.
So, considering following is the code you are using to create an object -
var session = require('express-session'),
    RedisStore = require('connect-redis')(session);
RedisStore.on('error', function(err){
  console.log("Connection error.");
})

Above code is not tested, but it should work.
Just take Redis server down and then start node server, it should print the log.
If this works, then go here and you will find more 5 events and some more stuff.


text:
Q: .Net Component for JavaScript Obfuscation? Are there any .Net components for obfuscating JavaScript? I'm generating JavaScript dynamically & emitting via ClientScript.RegisterClientScriptBlock. I'd like to make it more difficult for others to view and modify that script.
Caveats:

*

*Yes, I know that JavaScript obfuscation will merely inconvenience a serious developer.

*I do intend to add (non-obfuscated) copyright notices.

*My C# program that generates the JavaScript is my real value-add. That source won't be available to viewers. Nevertheless, I'd like to obscure the functions and data that it creates.

Thanks!

A: You can call out to Google's Closure Compiler from .NET, here's an example:

*

*http://madskristensen.net/post/Use-Googles-Closure-Compiler-in-C.aspx
Or there's a .NET port of the YUI Compressor:

*

*http://www.codeplex.com/YUICompressor

A: Try to use the YUI Compressor for .Net. It does not obfuscate, but it do compress at least. You use it as a dll.
http://yuicompressor.codeplex.com/

A: The Ajax Minifier mentioned above by Darin Dimitrov has been updated to include obfuscation as well as minification functionalities. It is also designed to work with your build and release process.

A: Maybe you can try JS cruncher or stunnix

A: You could take a look at Ajax Minifier which was recently released from Microsoft and which they use internally.


text:
Q: Finding Islands With Group and Interval Data I'm using SQL Server 2008R2 in this problem. Here's an example dataset:
WIRE_ID     FROM    TO      CLASS
05485       0.000   1.520   PL
05485       1.520   3.050   PL
05485       3.050   22.250  SL
05485       3.050   22.250  SP
05485       22.250  33.530  SL
05485       22.250  33.530  QT
05485       33.530  43.580  QT
05485       43.580  52.580  PL
05485       52.580  57.910  QT
114161      0.000   3.000   SW
114161      3.000   5.000   SL
114161      5.000   6.000   SL
114161      6.000   9.412   YN
114161      9.412   10.549  YN
114161      10.549  12.375  CM
114161      12.375  14.438  SL
114161      14.438  15.126  SL

So, a non-sequential ID associated ranged values and a group/classification. As you can see you can sometimes have duplicate intervals as different classes may be applied. Ultimately the result I'd like to achieve would look like the following:
WIRE_ID     FROM    TO      CLASS
05485       0.000   3.050   PL
05485       3.050   22.250  SL
05485       3.050   22.250  SP
05485       22.250  33.530  SL
05485       22.250  43.580  QT
05485       43.580  52.580  PL
05485       52.580  57.910  QT
114161      0.000   3.000   SW
114161      3.000   6.000   SL
114161      6.000   10.549  YN
114161      10.549  12.375  CM
114161      12.375  15.126  SL

Seems easy at first and I've constructed a solution that works, but once I apply it to the entire data-set it grinds to a halt. Ideally I need a solution that can handle a million rows of this style of data in a more or less efficient manner... Here's my solution:
Declare @WIRE_CLASS Table(WIRE_ID varchar(25), [FROM] float, [TO] float, CLASS varchar(15));
Insert @WIRE_CLASS(WIRE_ID, [FROM], [TO], CLASS) Values
('05485',0.000,1.520,'PL'),
('05485',1.520,3.050,'PL'),
('05485',3.050,22.250,'SL'),
('05485',3.050,22.250,'SP'),
('05485',22.250,33.530,'SL'),
('05485',22.250,33.530,'QT'),
('05485',33.530,43.580,'QT'),
('05485',43.580,52.580,'PL'),
('05485',52.580,57.910,'QT'),
('114161',0.000,3.000,'SW'),
('114161',3.000,5.000,'SL'),
('114161',5.000,6.000,'SL'),
('114161',6.000,9.412,'YN'),
('114161',9.412,10.549,'YN'),
('114161',10.549,12.375,'CM'),
('114161',12.375,14.438,'SL'),
('114161',14.438,15.126,'SL');

;with WIRE AS (
SELECT
    WIRE_ID,
    FROM,
    TO,
    CLASS
FROM
    WIRE_CLASS
), ISLANDS AS (
SELECT
    ROW_NUMBER() OVER (ORDER BY WI.WIRE_ID, WI.FROM) ID,
    WI.WIRE_ID,
    WI.FROM,
    WI.TO,
    WI.CLASS,
    CASE WHEN WI2.WIRE_ID IS NULL THEN 1 ELSE 0 END BREAKER
FROM
    WIRE WI
    LEFT JOIN WIRE WI2 ON
        WI2.WIRE_ID = WI.WIRE_ID
        AND (WI2.TO = WI.FROM)
        AND WI2.CLASS = WI.CLASS

), DATA AS(
SELECT
    IS1.WIRE_ID, IS1.FROM, IS1.TO, IS1.CLASS,
    (SELECT sum(BREAKER) FROM ISLANDS IS2 WHERE IS1.ID >=  IS2.ID) BREAKER
FROM ISLANDS IS1
)
SELECT
    DA.WIRE_ID,
    MIN(DA.FROM),
    MAX(DA.TO),
    MIN(DA.CLASS)
FROM DATA DA
GROUP BY
    DA.WIRE_ID,
    BREAKER,
    DA.CLASS
ORDER BY
    DA.WIRE_ID,
    MIN(DA.[FROM]),
    MAX(DA.[TO])

Can you suggest a better way to do this??? Thanks a bunch SQL gurus!

A: As others have said, using a temp table instead of a table variable will make a world of difference to the performance. I assume however, you've only used the table variable to pose your example and in reality you have a proper user table that contains all this data.
My query will find the islands, but will provide slightly different output to your results from your sample data.  My query will not split islands as it appears yours has in some instances... I see a discrepancy in your results between the way the SL/SP/QT results are handled for wire 05485. I think
WIRE_ID     FROM    TO      CLASS
05485       3.050   22.250  SL
05485       3.050   22.250  SP
05485       22.250  33.530  SL
05485       22.250  33.530  QT
05485       33.530  43.580  QT
should result in
WIRE_ID     FROM    TO      CLASS
05485       3.050   33.530  SL
05485       3.050   22.250  SP
05485       22.250  43.580  QT
not
WIRE_ID     FROM    TO      CLASS
05485       3.050   22.250  SL
05485       3.050   22.250  SP
05485       22.250  33.530  SL
05485       22.250  43.580  QT
Your results have split the SL island, but not the QT. Even though there is from/to pairs matching between SL & SP (3.05/22.5) and then SL & QT (22.5/33.53).
I've run the query below on a VM on my laptop (read: a server should be quicker) and for 1M records, with ~2000 Wire/Class combinations and ~20% rows needing to have from/to combined. I've randomly generated the data a few times and it typically takes only between 80 and 100 seconds.
I've created the table as:
IF OBJECT_ID('tempdb.dbo.#WIRE_CLASS', 'U') IS NOT NULL
    DROP TABLE #WIRE_CLASS
GO
CREATE TABLE #WIRE_CLASS (
    WIRE_ID varchar(25),
    [FROM] float,
    [TO] float,
    CLASS varchar(15),
    PRIMARY KEY (WIRE_ID, [FROM], CLASS)
)
Here's the query, with explanations in comments
-- The Cross Join ensures we always have a pair of first and last from/to pairs
-- The left join matches all from=to combinations,
-- allowing the where clause to restrict to just the first and last
-- These first/last pairs are then grouped in the CTE
-- The final select is then quite simple
; With GroupedData AS (
    SELECT
        (Row_Number() OVER (ORDER BY W1.WIRE_ID, W1.CLASS, W1.[FROM]) - 1) / 2 Grp,
        W1.WIRE_ID, W1.[FROM], W1.[TO], W1.CLASS
    FROM #WIRE_CLASS W1
    CROSS JOIN (SELECT 0 AS [First] UNION SELECT 1) SetOrder
    LEFT OUTER JOIN #WIRE_CLASS W2
        ON W1.WIRE_ID = W2.WIRE_ID
        AND W1.CLASS = W2.CLASS
        AND ((W1.[TO] = W2.[FROM] AND [First] = 0)
             OR (W2.[TO] = W1.[FROM] AND [First] = 1))
    WHERE W2.WIRE_ID IS NULL
)
SELECT WIRE_ID, MIN([FROM]) AS [FROM], MAX([TO]) AS [TO], CLASS
FROM GroupedData
GROUP BY Grp, WIRE_ID, CLASS
ORDER BY WIRE_ID, [FROM], CLASS

A: Using temporary tables instead of CTE's with large datasets will improve the performance, but without your dataset I'm unable to test the performance of this.
Here's your queries using temp tables:
Declare @WIRE_CLASS Table(WIRE_ID varchar(25),
                          [FROM] float,
                          [TO] float,
                          CLASS varchar(15));

Insert @WIRE_CLASS(WIRE_ID, [FROM], [TO], CLASS)
Values ('05485',0.000,1.520,'PL'),
       ('05485',1.520,3.050,'PL'),
       ('05485',3.050,22.250,'SL'),
       ('05485',3.050,22.250,'SP'),
       ('05485',22.250,33.530,'SL'),
       ('05485',22.250,33.530,'QT'),
       ('05485',33.530,43.580,'QT'),
       ('05485',43.580,52.580,'PL'),
       ('05485',52.580,57.910,'QT'),
       ('114161',0.000,3.000,'SW'),
       ('114161',3.000,5.000,'SL'),
       ('114161',5.000,6.000,'SL'),
       ('114161',6.000,9.412,'YN'),
       ('114161',9.412,10.549,'YN'),
       ('114161',10.549,12.375,'CM'),
       ('114161',12.375,14.438,'SL'),
       ('114161',14.438,15.126,'SL');

SELECT
    WIRE_ID,
    [FROM],
    [TO],
    CLASS
INTO #tmp_WIRE
FROM
    @WIRE_CLASS

SELECT
    ROW_NUMBER() OVER (ORDER BY WI.WIRE_ID, WI.[FROM]) ID,
    WI.WIRE_ID,
    WI.[FROM],
    WI.[TO],
    WI.CLASS,
    CASE WHEN WI2.WIRE_ID IS NULL THEN 1 ELSE 0 END  as BREAKER
INTO #tmp_ISLANDS
FROM
    #tmp_WIRE WI
    LEFT JOIN #tmp_WIRE WI2 ON
        WI2.WIRE_ID = WI.WIRE_ID
        AND (WI2.[TO] = WI.[FROM])
        AND WI2.CLASS = WI.CLASS

SELECT
    IS1.WIRE_ID, IS1.[FROM], IS1.[TO], IS1.CLASS,
    (SELECT sum(BREAKER) FROM #tmp_ISLANDS IS2 WHERE IS1.ID >=  IS2.ID) BREAKER
INTO #tmp_DATA
FROM #tmp_ISLANDS IS1

SELECT
    DA.WIRE_ID,
    MIN(DA.[FROM]),
    MAX(DA.[TO]),
    MIN(DA.CLASS)
FROM #tmp_DATA DA
GROUP BY
    DA.WIRE_ID,
    BREAKER,
    DA.CLASS
ORDER BY
    DA.WIRE_ID,
    MIN(DA.[FROM]),
    MAX(DA.[TO])

Related Reading:
Which are more performant, CTE or temporary tables?
What's the difference between a CTE and a Temp Table?

A: Note: The query is in Oracle. You will have to convert it
The bottleneck in your case is multiple self join of such large temporary tables. A different approach could do this without joining.
First lets try to group overlapping rows. For this I used a sequence and 2 functions. The functionality of the 2 functions is the same as nextval and currval. The query is
  SELECT WIRE_ID,
     FROM_,
     TO_,
     CLASS,
     CASE
        WHEN LAG (TO_, 1, -999999)
                OVER (PARTITION BY WIRE_ID, CLASS ORDER BY FROM_) >= FROM_
        THEN
           CURRENTVALUE ()
        ELSE
           NEXTVALUE ()
     END
        GRP
FROM WIRE_CLASS
ORDER BY WIRE_ID, CLASS, FROM_

The output is
"unable to upload image"
Now just use this output as inline view and aggregate. Query is
  SELECT WIRE_ID,
     MIN (FROM_) AS FROM_,
     MAX (TO_) AS TO_,
     CLASS
FROM (SELECT WIRE_ID,
             FROM_,
             TO_,
             CLASS,
             CASE
                WHEN LAG (TO_, 1, -999999)
                        OVER (PARTITION BY WIRE_ID, CLASS ORDER BY FROM_) >=
                        FROM_
                THEN
                   CURRENTVALUE ()
                ELSE
                   NEXTVALUE ()
             END
                AS GRP
        FROM WIRE_CLASS) BASE_Q
GROUP BY WIRE_ID, CLASS, GRP
ORDER BY WIRE_ID, FROM_;

The final output is
"unable to upload image"
The functions are used because Oracle does not allow sequences to be used in conditional statements. Here are the definition of functions
CREATE OR REPLACE FUNCTION NEXTVALUE
RETURN NUMBER
IS
VAL   NUMBER;
BEGIN
SELECT WIRE.NEXTVAL INTO VAL FROM DUAL;
RETURN VAL;
END;

CREATE OR REPLACE FUNCTION CURRENTVALUE
RETURN NUMBER
IS
VAL   NUMBER;
BEGIN
SELECT WIRE.CURRVAL INTO VAL FROM DUAL;
RETURN VAL;
END;

Hope it helps.

A: You would want the be sure that all keys are indexed. Additionally if you're matching up columns of different types that's going to yield a performance hit.
Additionally, where you have the row_number function that's going to change the whole to at least O(2n) efficiency, that would be in part, why you're seeing such long run times with your alg
And as Tanner had written, a move to temp tables would yield a performance improvement

A: You can use the OVER() clause of the MIN and MAX statements.
Below you will find a working sample (including the generation of a decent test data set).
-- create a temp table to hold a decent amount of testdata
IF OBJECT_ID('tempdb..#testdata') IS NOT NULL
    DROP TABLE #testdata;

CREATE TABLE #testdata
    (
      Id INT PRIMARY KEY ,
      WIRE_ID INT NOT NULL ,
      _FROM FLOAT NOT NULL ,
      _TO FLOAT NOT NULL ,
      CLASS VARCHAR(15) NOT NULL
    );

-- create some testdata
-- : 1KK records, divided over 10K WIRE_ID's (so 100 values per wire-id)
-- : FROM-TO values randomly divided into 4 value ranges [0-25][26-50][51-75][76-100]
-- : CLASS  bucketnumber + randomly classification from 1 to 5 (cls_1_2 => cls_[bucketnum]_[rand between 1 and 5]
DECLARE @nrows INT = 1000000;
DECLARE @nwires INT = 100;
DECLARE @numbuckets INT = 4;
DECLARE @bucketsize INT= 25000;
DECLARE @bucketstartMax INT= 5000;
DECLARE @clsMax INT = 5;

WITH    TestRecs
          AS ( SELECT TOP ( @nrows )
                        ROW_NUMBER() OVER ( ORDER BY ( SELECT 1) ) AS Rnum ,
                        bucketNumber = ABS(CHECKSUM(NEWID()) % @numbuckets) ,
                        fromStart = ABS(CHECKSUM(NEWID()) % @bucketstartMax) ,
                        fromIncrement = ABS(CHECKSUM(NEWID()) % ( @bucketsize- ABS(CHECKSUM(NEWID())% @bucketstartMax) )) ,
                        clsNum = ABS(CHECKSUM(NEWID()) % @clsMax) + 1
               FROM     sys.all_columns c1
                        CROSS JOIN sys.all_columns c2
                        CROSS JOIN sys.all_columns c3
             )
    INSERT  INTO #testdata
            ( Id ,
              WIRE_ID ,
              [_FROM] ,
              [_TO] ,
              CLASS
            )
            SELECT  RNum AS _id ,
                    CAST(RNum / @nwires + 1 AS INT) AS Wire_ID ,
                    _from = ( ( bucketNumber * @bucketsize ) + fromStart ) / CAST(1000 AS FLOAT) ,
                    _to = ( ( bucketNumber * @bucketsize ) + fromStart + fromIncrement ) / CAST(1000 AS FLOAT) ,
                    _cls = 'cls' + CAST(bucketNumber AS VARCHAR(3)) + '_' + CAST(clsNum AS VARCHAR(5))
            FROM    TestRecs;

-- selecting the results can be achieved using OVER() clauses on MIN() and MAX()
-- note this forces you to include _from and _to in GROUP BY
-- , so you need a 2nd select is required to get the distict list
WITH    Bucketized
          AS ( SELECT   WIRE_ID ,
                        CLASS ,
                        MIN(_FROM) OVER ( PARTITION BY WIRE_ID, CLASS ) AS _FROM ,
                        MAX(_TO) OVER ( PARTITION BY WIRE_ID, CLASS ) AS _TO
               FROM     #testdata
               GROUP BY WIRE_ID ,
                        CLASS ,
                        _FROM ,
                        _TO
             )
    SELECT  WIRE_ID ,
            CLASS ,
            _FROM ,
            _TO
    FROM    Bucketized
    GROUP BY WIRE_ID ,
            CLASS ,
            _FROM ,
            _TO;

-- a sample with a million rows takes 6 seconds on my laptop

A: Try this:
select wire_id, class, [from], [to],
ROW_NUMBER() over (order by wire_id, class,[from], [to]) gg,
1 as is_continous
into #temp1
from #WIRE_CLASS
group by wire_id, class, [from], [to]

--Including index to improve performance of selects
create index IX_temp1 on #temp1(gg) include (is_continous)
create index IX_temp2 on #temp1(wire_id, class) include (is_continous)

update this
set is_continous = 0
from #temp1 prev join #temp1 this on prev.gg = this.gg -1
where prev.[to] <> this.[from]

update this
set this.[from] = prev.[from]
--select prev.*, this.*
from #temp1 prev join #temp1 this
on prev.gg <= this.gg and this.gg <> 1 and prev.wire_id = this.WIRE_ID
and prev.CLASS = this.CLASS and this.is_continous = 1

update prev
set prev.[to] = this.[to]
--select prev.*, this.*
from #temp1 prev join #temp1 this
on prev.gg <= this.gg and this.gg <> 1 and prev.wire_id = this.WIRE_ID
and prev.CLASS = this.CLASS and this.is_continous = 1 and this.gg <> 1

select distinct wire_id, [from], [to], class
from #temp1


text:
Q: SMTP Server unable to send mails I have an SMTP Server Setup on Windows server 2003 R2 on my domaiin.
This is when I receive the mail:

*

*When I send a mail using a txt file placed inside the Pickup folder of the mailroot I receive the mail.

*When I write a Pl/SQL Block to send mail.

This is when I don't receive a mail:

*

*When I try to send a mail from an Oracle 11g Package, the log files in the SMTP Server shows the following:

    14:39:59 XXX.XXX.XXX.XXX HELO - 250
    14:39:59 XXX.XXX.XXX.XXX MAIL - 250
    14:39:59 XXX.XXX.XXX.XXX RCPT - 250
    14:39:59 XXX.XXX.XXX.XXX DATA - 250
    14:39:59 XXX.XXX.XXX.XXX QUIT - 240
    14:39:59 YYY.YYY.YYY.YYY - - 0
    14:39:59 YYY.YYY.YYY.YYY - - 0
    14:39:59 YYY.YYY.YYY.YYY EHLO - 0
    14:39:59 YYY.YYY.YYY.YYY - - 0
    14:41:00 YYY.YYY.YYY.YYY - - 0
    14:41:00 YYY.YYY.YYY.YYY EHLO - 0
    14:41:00 YYY.YYY.YYY.YYY - - 0
    14:42:00 YYY.YYY.YYY.YYY - - 0
    14:42:00 YYY.YYY.YYY.YYY EHLO - 0
    14:42:00 YYY.YYY.YYY.YYY - - 0
    14:43:00 YYY.YYY.YYY.YYY - - 0
    14:43:00 YYY.YYY.YYY.YYY EHLO - 0
    14:43:00 YYY.YYY.YYY.YYY - - 0

Can somebody please explain what does this response mean. And why am I not getting these mails.

*Also, when I send a mail from an Oracle Apex application, I don't receive it. The Apex admin mail log logs the mail but I donot receive it in my mail box.
Please Help!!!

Thanks in Advance
Cheers!!!

A: Realized that the Mime Header was malformed hence the SMTP Server that I setup wasn't accepting the mails and all the mails went to the BADMAIL folder.
Anyways....
Thanks for the response.


text:
Q: HTML 5 Dialog element overlapping google captcha I have an issue with captcha and HTML5 dialog element, my dialog box is overlapping captcha images
I have changed z-index of my dilogbox to 0, but still its overlapping. I am using dialog-polyfill. How I can fix this issue?
This issue is happening in Mac Google Chrome Version 52.0.2743.116 (64-bit)
Please see the jsfiddle link here:

    <dialog class="auth">

    </dialog>

https://jsfiddle.net/a8793aop/

A: I found the issue, I was using showModal() instead of show() to display the dialogbox. showModal() will add the dialogbox to "top layer". The z-index property has no effect in the top layer.
HTML5 top layer


text:
Q: I wanted to draw on a Canvas which is on top of another control and also able to access the control, is this possible in HTML? I have an use case to draw lines/shapes using Canvas or SVG APIs, These graphics will be drawn on a layer which is on top of a set of controls. The issue I have now is, Once the Canvas is placed on top of the controls, I am not able to access the controls, like clicking on a checkbox/button etc.  How can I enable this ?
eg

         <input type="submit"/>

    <canvas id="layer2" style="position:absolute;top:0px;left:10px"></canvas>

In the above sample, I am not able to click on the "submit" button because of the layer on top, What I wanted to do is to draw circle around the button, same time I should be able to click on the button as well.
Is this possible in HTML ?

A: Typically you can't click "through" HTML elments, but you still have a lot of options.
One very quick solution is to use pointer-events: none; in your style code for the canvas.
This will work on Firefox/chrome/safari, but not IE.
For IE you'll have to get more clever.
...But why not just put the button on top instead of having the canvas on top? A quick way to do this is to give the canvas z-index: -1; in its style.
So all together now:

         <input type="submit"/>

    <canvas id="layer2" style="position:absolute;top:0px;left:10px; border: 1px solid black; pointer-events: none; z-index: -1;"></canvas>


text:
Q: How to implement fixed bottom in IE6? With css.
Please don't refer me to another link.
EDIT
Make something always at the bottom of viewport no matter how you scroll the bar.

A: If you're having problems specifically with IE6 - consider using a resets script.  It will make your life much, much easier.  There are lots of different flavours of reset script out there, so do a bit of research and to find one that you like.  Personally, I find that yahoo produce one that's fit for purpose.
The thinking behind using a resets script is:

*

*Each browser applies a set of
default styles and properties,
before any user style sheet is even
loaded.

*A lot of the differences between the
way a page renders are due to the
inconsistencies between these
defaults.

*If we could find a way to 'flatten
the ground' before we begin
building, life would be easier

A resets script performs that flattening - and IE6 can be dealt with in a much more logical way.
The obligatory link ;)
http://developer.yahoo.com/yui/reset/
Solution
Bearing in mind the use of this resets script, I offer you the following solution.
As you're probably aware, IE6 doesn't support position:fixed.
To solve the problem you can make use of the following snippet:

Which should be applied to a document containing the following elements within it's :

            I'm at the bottom

            Your content here.....

This should work because:

*

*IE6 treats height in the same way that most browsers treat max-height.  The overflow auto will allow content to flow (with scrollbars) if the content carries on past the height of the browser viewport.

*The '*' hack is used for simplity - it makes sure that IE6 applies 'position:absolute;' rather than 'position:fixed'.  You should use conditional comments to provide specific CSS for IE6.

*Note that this solution will only work when IE6 is set to use 'strict mode'.  This can be set explicitly by choosing an appropriate doctype; for example:
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">


text:
Q: Неизвестные значения в массиве Добрый день)
При отправке команды в массиве char sim[300]; через раз появляются непонятные символы из предыдущих запросов, не смотря на то что каждый раз  при отправке команды весь массив =0 (memset(sim, 0, sizeof(sim));)
Как быть куда смотреть? если посмотреть снифером что передается по USB то там только верные значения, то есть проблема в само программе!
private: System::Void ReadBtn_Click(System::Object^  sender,
System::EventArgs^  e) {

memset(sim, 0, sizeof(sim));
if (printer.TryConnection())
{

    PrinterTypeLB->Text = DeviceNameCB->Text;

    printer.SendComand(Firmware);
    FirmwareLB->Text = gcnew String(sim);

    printer.SendComand(BoardRevision);
    BoardRevisionLB->Text = System::Convert::ToString(sim[0]);

    printer.SendComand(Temperature);
    HeadTempLB->Text = System::Convert::ToString(sim[0]) + " C°";

    printer.SendComand(CountCuted);
    value = string(sim);
    value.replace(value.end() - 4, value.end(), "");
    CutCounterLB->Text = gcnew System::String(value.c_str());

    printer.SendComand(PrintedPaper);
    value = string(sim);
    value.replace(value.end() - 2, value.end(), "");
    PrintedPaperLB->Text = gcnew System::String(value.c_str());

    printer.SendComand(PowerCounter);
    value = string(sim);
    value.replace(value.end() - 2, value.end(), "");
    PowerCounterLB->Text = gcnew System::String(value.c_str());

    printer.SendComand(SerialNumb);
    SerialLB->Text = gcnew String(sim);

    printer.SendComand(RetractCounter);

    value = string(sim);
    value.replace(value.end() - 3, value.end(), "");
    RetractCounterLB->Text = gcnew System::String(value.c_str());

}
else
    FalseConnection();
}

void SendComand(byte byt[]) {
    connectedStatus = CreatePrinter(n);
    if (connectedStatus) {
        try {
            memset(sim, 0, sizeof(sim));
            OVERLAPPED OverlapWrite;
            OverlapWrite.OffsetHigh = 1;
            OverlapWrite.Offset = 1;
            OverlapWrite.hEvent = CreateEvent(NULL, false, false, NULL);

            OVERLAPPED OverlapRead;
            OverlapRead.OffsetHigh = 1;
            OverlapRead.Offset = 1;
            OverlapRead.hEvent = CreateEvent(NULL, false, false, NULL);

            int sizebyt = sizeof(byt)-1;

            //Пишем
            bool sucsses = WriteFile(ConDevice, (LPCVOID)byt, sizebyt, &ReturnedLength, &OverlapWrite);

            ReturnedLength = 0;
            //Читаем

            sucsses = ReadFile(ConDevice, &sim, sizeof(sim), &ReturnedLength, &OverlapRead);

            //CloseHandle(ConDevice);
            throw std::exception();
            Sleep(20);
        }
        catch (const std::exception err)
        {

        }
    }

}


text:
Q: View cached data in ASP.NET MVC Is there any third party tool or something in visual studio that lets you see the cached objects?
For example, an action is caching data (varied by parameters) and I want to see the cached objects and the attributes (like which parameter values were sent to the action when this data was cached).

A: You can find more answers to what you might desire on the Stackoverflow question:
How to display the content of asp.net cache?
Basically you can create a page to view all cached items from your application. After that, it can customize and UI pump it to your needs and objectives.
If you just need to debug, then you can use Ringer's solution displayed on your comments.


text:
Q: Help 3 buttons in AJAX I want to add 3 buttons with different actions. I have made the PHP code that handles those actions but in order to get to those actions I need with ajax and method GET to add 2 parameters: id and act. I made this, in a very primitive way! It does not work because it only gets the first id="act" (which in this case is delete) no matter what I click!:
<form>
     <input type="hidden" id="act" value="delete">
     <input type="hidden"  id="id" value="'.$row['order_id'].'">
     <input type="button" id="delete" value="delete" onclick="ajaxFunction()">
</form>

<form>
    <input type="hidden" id="act" value="edit">
    <input type="hidden" id="id" value="'.$row['order_id'].'">
    <input type="button" id="edit" value="edit" onclick="ajaxFunction()">
</form>

And here is the AJAX function:
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            document.myForm.time.value = ajaxRequest.responseText;
        }
    }
    var id = document.getElementById(\'id\').value;
    var act = document.getElementById(\'act\').value;
    var queryString = "?id=" + id + "&act=" + act;
    ajaxRequest.open("GET", "classes/ajaxed/reservation_functions.php" + queryString, true);
    ajaxRequest.send(null);
}

//-->
</script>

So my question is how to make those 3 buttons with delete, edit, print and each one to send with it GET method the proper ID and ACTION (id & act)?

A: Simplified Markup:
<button onclick="ajaxFunction('delete', '<?php echo $row['order_id']; ?>')">Delete</button>
<button onclick="ajaxFunction('edit', '<?php echo $row['order_id']; ?>')">Edit</button>
<button onclick="ajaxFunction('print', '<?php echo $row['order_id']; ?>')">Print</button>

Change you need to make to your JS function:
function ajaxFunction(action,id){
    ...
    var queryString = "?id=" + id + "&act=" + action;
    ...
}

A: The main reason is there are two forms both of them have two buttons having same id i.e. id and act.
So change the id's and your problem will be solved.


text:
Q: Is NSNotificationCenter is part of UITextView? Sorry for the basic Question, I'm fairly new to programming and trying to understand something in the code apple suggester for a certain solution to something I wanted to preform.
I created a simple notes app, very basic, currently I have:
1. CreateNote view controller
2. NotesList table view controller
So I wanted to add a behaviour when a note is being created and a user types below the keyboard so the text resized so the user can still see what he types and the text is not going behind the keyboard.
So I add some lines of code suggested by apple to accomplish that.
In the viewWillAppear called a method on NSNotificationCenter and I could not understand where is an NSNotificationCenter object is declared...?
So this is my CreateNote view controller(Please help me understand why they could preform this call):
#import "NMCreateNotesViewController.h"

@interface NMCreateNotesViewController () <UITextViewDelegate>

@property (weak, nonatomic) IBOutlet UIBarButtonItem *createButton;

@property (weak, nonatomic) IBOutlet UITextView *textField;

@end

@implementation NMCreateNotesViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // listen for keyboard hide/show notifications so we can properly adjust the table's height
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

#pragma mark - Notifications

- (void)adjustViewForKeyboardReveal:(BOOL)showKeyboard notificationInfo:(NSDictionary *)notificationInfo
{
    // the keyboard is showing so resize the table's height
    CGRect keyboardRect = [[notificationInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration =
    [[notificationInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = self.textField.frame;

    // the keyboard rect's width and height are reversed in landscape
    NSInteger adjustDelta = UIInterfaceOrientationIsPortrait(self.interfaceOrientation) ? CGRectGetHeight(keyboardRect) : CGRectGetWidth(keyboardRect);

    if (showKeyboard)
        frame.size.height -= adjustDelta;
    else
        frame.size.height += adjustDelta;

    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.textField.frame = frame;
    [UIView commitAnimations];
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    [self adjustViewForKeyboardReveal:YES notificationInfo:[aNotification userInfo]];
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    [self adjustViewForKeyboardReveal:NO notificationInfo:[aNotification userInfo]];
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if (sender != self.createButton) return;
    if (self.textField.text.length > 0) {
        self.note = [[NMNote alloc] init];
        self.note.content = self.textField.text;

    }
}

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

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

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

@end

A:
Is NSNotificationCenter is part of UITextView?

No it is not. NSNotificationCenter is - as it's name says - a notification center. Objects can subscribe to notifications and post notifications with NSNotificationCenter to handle and notify of certain events.
They are using NSNotificationCenter to have the viewcontroller subscribe to UIKeyboardWillHideNotification and UIKeyboardWillShowNotification events.
Take a look at this one:
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];

NSNotificationCenter is designed to be used as a singleton ( I believe this is the correct term, correct me if I'm wrong ) so we access the NSNotificationCenter for this app's process by calling the class method defaultCenter. it adds observer 'self' ( which in this case is an instance of the view controller) and basically instructs it to send the message keyboardWillShow to the observer when a Notification under the name of UIKeyboardWillShowNotification is fired.
What object fires the UIKeyboardWillShowNotification? Well it's not a UITextView, this notification name is actually defined in UIWindow.h so it probably came from there, which in turn probably was invoked from UIKeyboard which is not a public API as far as I know.

A: NSNotificationCenter is a class. In Objective-C, classes are declared in header files; this one is in NSNotification.h. (Try pressing Command-Shift-O and typing "NSNotificationCenter" to find this yourself.) When you want to use a class, you #import the header file that the class is declared in; this makes the compiler read that header file first and make all the classes (and other globals) available to your code to use.
This would be a huge pain, though, since a typical Cocoa app uses zillions of classes and other globals from Apple's libraries. So, instead, you just need to #import <Foundation/Foundation.h> which is a header file that just includes a bunch of other header files, including NSNotification.h. (The import statement for Foundation is probably in your own header file, or something else like #import <UIKit/UIKit.h> which also will include foundation and ultimately NSNotification.h.)
One final detail is that there's is probably a "prefix" header in your project which includes UIKit.h in all of your files automatically, so anything declared in there is always available to your code.

A: NSNotificationCenter is a class in Foundation.

A: NSNotificationCenter doesn't need to be declared and stored in a variable, its just a call, to explain it further, think of NSNotificationCenter as a tackboard where things get posted, you add a note to that backboard by creating the NSNotificationCenter, and you assingn observers to look at that board, and do something when a note is added.

A: The NSNotificationCenter object being used in this case is a Singleton. What you need to know is that sending the message defaultCenter to the NSNotificationCenter class object always returns the same NSNotificationCenter object.
Here's what the call to default center might look like
+ (NSNotificationCenter*)defaultCenter
{
    static dispatch_once_t once;
    static NSNotificationCenter* sharedInstance;

        dispatch_once(&once, ^{

            sharedInstance = [[self alloc] init];
             /*
             set up properties, etc
             */
     });

     return sharedInstance;
}


text:
Q: How an Authentication Server works As the title suggests, I am not sure how an Authentication Server works. I have implemented authentication on multiple websites but it hasn't ever sat on a separate server. So, how would this architecture work? Is there material online that can explain this (I couldn't find any)? Advantages/ Disadvantages of this approach when compared to an implementing authentication on the same machine.

A: Having different authentication systems per application would land the user to create multiple profile which could be cumbersome for the user. Also architecturally you are creating tight coupling between application and authentication.
You should consider & design authentication as a simple Service/API call, this would help you in removing the coupling, achieving re-usability and maintainability. Following are few benefits of Authentication as a service or separate system:

*

*Isolating Authentication system would create a path for implementing Single Sign On feature.

*Implement changes and testing would be easier.

*You can have the road-map to apply standardization in elegant manner.

*In future your authentication can also handle authorization responsibilities.

*When you change your Authentication system to a new IDAM solution, the impact on the business applications is reduced or eliminated.
You can find lot of Identity Access Management Solutions in the market which are pretty much industry standard. I would recommend you to research on SSO & IDAM products, which should give you comprehensive idea about the above mentioned points.


text:
Q: Spring webflow second popup problem I have 1st popup, and this 1st popup opens 2nd popup
Code:
<view-state id="paneMaintenance" parent="#pe-cards"  model="model">
    <transition on="task-view" then="developers-task-view" bind="false">
    </transition>
</view-state>

<view-state id="developers-task-view" view="/WEB-INF/jsp/taskView/taskAssignDevelopersPopUp.jsp" model="taskAssignModel" parent="#paneMaintenance" popup="true" >
    <transition on="create" to="create-task-after" bind="false" >
        <evaluate expression="taskAssignHandler.create(taskAssignModel, model.paneModel, true)" />
    </transition>
</view-state>

<view-state id="create-task-after" view="/WEB-INF/jsp/taskView/taskCreateAfter.jsp" model="taskAssignModel" parent="#developers-task-view" popup="true">
      <transition on="confirm" bind="true">
                 <evaluate expression="taskAssignHandler.saveTaskAssign(taskAssignModel, model.paneModel)" />
      </transition>
    <transition on="cancel" bind="false"  to="paneMaintenance"/>
</view-state>

I need to execute some code, then close 2nd popup, and then return to 1st popup.
How can i do it?
If 1st popup opens 2nd popup, and there is transition from 2nd popup to 1st popup, then 2nd popup opens second 1st popup, instead of close himself and return to 1st popup
Please help.

A: You can use tiles and create some tiles definitions, like this:
<definition name="myBasicView" extends="myView">
    <put-attribute name="body" value="/WEB-INF/jsp/taskView/yourPageBody.jsp" />
</definition>

<definition name="myFirstView" extends="myView">
    <put-attribute name="body" value="/WEB-INF/jsp/taskView/yourPageBody.jsp" />
    <put-attribute name="popup" value="/WEB-INF/jsp/taskView/taskAssignDevelopersPopUp.jsp" />
</definition>

<definition name="mySecondView" extends="myView">
    <put-attribute name="body" value="/WEB-INF/jsp/taskView/yourPageBody.jsp" />
    <put-attribute name="popup" value="/WEB-INF/jsp/taskView/taskCreateAfter.jsp" />
</definition>

and then use these definitions:
<view-state id="paneMaintenance" parent="#pe-cards" model="model" view="myBasicView" >
    <transition on="task-view" then="developers-task-view" bind="false">
    </transition>
</view-state>

<view-state id="developers-task-view" view="myFirstView" model="taskAssignModel" parent="#paneMaintenance" popup="true" >
    <transition on="create" to="create-task-after" bind="false" >
        <evaluate expression="taskAssignHandler.create(taskAssignModel, model.paneModel, true)" />
    </transition>
</view-state>

<view-state id="create-task-after" view="mySecondView" model="taskAssignModel" parent="#developers-task-view" popup="true">
    <transition on="confirm" bind="true">
        <evaluate expression="taskAssignHandler.saveTaskAssign(taskAssignModel, model.paneModel)" />
    </transition>
    <transition on="cancel" bind="false" to="paneMaintenance"/>
</view-state>

So 1 popup for each view!


text:
Q: Jackson deserialization with @JsonUnwrapped I have following classes -
public class Request {
   public String name;

   @JsonUnwrapped
   @JsonInclude(JsonInclude.Include.NON_NULL)
   public DateOfBirth dateOfBirth;
}

public class DateOfBirth {
   public int day;
   public int month;
   public int year;
}

{
  "name" : "John Doe"
}

Deserealization of this JSON creates a Request object with name John Doe and dateOfBirth with day, month and year 0.
How can I override this behaviour so that dateOfBirth is null.

Worth noting that on removing @JsonUnwrapped annotation, such JSON is deserealized into null object, so I feel like I am missing some trick here.
Jackson version - 2.13.1


text:
Q: Disable jQuery Mobile transition when going back in iOS7 Safari history As described here in Safari on iOS7 - if you swipe in from the left of the screen it triggers a history back event as if the user clicked the back button.
The default behavior of jQuery Mobile is to reverse the transition that was used to reach a particular page when going back to the previous page. This works great when using the < and > buttons but looks terrible when swiping in from the left.
Is there a way to completely disable transitions in the 'reverse' direction using jQuery mobile?

A: Just capture the pagecontainerbeforetransition event on the page widget.
You can then look at ui.options.reverse and cancel the transition. If you want you can detect iOS7, but I think I'll just give this to all my visitors.
    $(document).on("pagecontainerbeforetransition", function (event, ui)
    {
        if (ui.options.reverse == true)
        {
            ui.options.transition = "none";
        }
    });

Here's a sample of a typical ui.options object.
{"reverse":true,"changeHash":false,"fromHashChange":true,"showLoadMsg":true,
 "allowSamePageTransition":false,"transition":"none"}

For some reason reverse always seems to be true even when navigating forward. May be a but, but I decided to check for it anyway.