text:
Q: Use single quote or double quote for string?
Possible Duplicate:
Difference between single quotes and double quotes in Javascript

I read some codes, it looks like a lot of people like to use single quote for string. I am coming from c#/Java world, usually we use double quote for string.
Any benefit for using single quote, I know single/double are equivalent in JS. But is there any pro and con to use single/double quote?

A: It's a matter of preference.  There is no difference in JavaScript.
Personally, I prefer to use single quotes.  It makes it easier for using double quotes in HTML that you don't have to escape.  That may or may not matter to you.  What does matter is that you are consistent.

A: If you want to write a string containing single quotes it can be convenient to delimit the string with double-quotes and vice versa.
var a = 'abc "def" ghi';
var b = "foo 'bar' baz";

Other than that, it doesn't matter which you use. Be consistent where possible.

A: For the most part, I think the reason is "you don't have to press Shift to get single quotes".
Sometimes choosing the right quotes makes escaping easier, but it's pretty much always personal preference.

A: The best reason to use one over the other is the intention to use the other as literal content. This removes the need to escape the character being used as the delimiter.
For example, ' this """ has double quotes' and " this has single '''' quotes"

A: There is absolutely no difference. Just don't mix and match.


text:
Q: Failed to load viewstate error in asp.net I have a gridview on my aspx page, wherein i have item and edit templates, on of the column contains the buttons for the edit and delete, once user click on the edit button the row should be enable for the editing and buttons would be changing to the update and cancel, it works on all the other forms i have created on the site, but on this specific page, whenever user clicks on the edit button, nothing happens, again if he tries, he is presented with this error message:

Failed to load viewstate.  The control tree into which viewstate is
  being loaded must match the control tree that was used to save
  viewstate during the previous request.  For example, when adding
  controls dynamically, the controls added during a post-back must match
  the type and position of the controls added during the initial
  request.

I didn't understood where i am going wrong.
Does anyone have any idea what would be going wrong with this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django Field is showing up in one view but not the other I'm just starting out with Django and I have a problem where, when I added a field to my model (JobPost which inherits from models.Model) and it migrated successfully I can see and interact with the new field when I create a job post, but not when I view the JobPost (which is displayed using crispy forms using the {{ form|crispy }} tag.
I have added the field name to my fields = [''] in my views.py
models.py
class JobPost(models.Model):
#constants
CLEARANCE_LEVELS=[(...),]

author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
clearance_required = models.CharField(max_length=50, choices=CLEARANCE_LEVELS, default='None')
date_posted = models.DateTimeField(default=timezone.now)

views.py
class JobDetailView(DetailView):
    model = JobPost

class JobCreateView(LoginRequiredMixin, CreateView):
    model = JobPost
    fields = ['title', 'content', 'clearance_required']
    # form_valid checks if the user is logged in
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

jobpost_form.html
{% load crispy_forms_tags %}
{% block content %}

    <form method="POST">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Create Job Post</legend>
            {{ form|crispy }}
        </fieldset>

            <button class="btn btn-outline-info" type="submit">Submit</button>

    </form>

{% endblock content %}

jobpost_detail.html
{% block content %}

            {{ object.author }}
            {{ object.date_posted|date:"F d, Y" }}
            {% if object.author != user %}
                See all jobs the user applied to
            {% endif %}

                {% if object.author == user %}
                See all jobs the user applied to
                Update Job Posting
                Delete
                {% endif %}

{{ object.title }}

{{ object.content }}

{% endblock content %}

So when I view it in my browser, I see the "clearance_required" field when I create a job post. But when I just view the job post, it only shows the title and description, not the new clearance_required field. I don't know how I can get it to display.
Here's a picture of the issue:
Notice how the clearance field is missing in the second picture

A: Do you actually output in object.clearance_required in jobpost_detail.html, because I cannot see it?
And by the way, if you output it, you should use object.get_clearance_required_display, because it is a field with choices.


text:
Q: POST endpoint is receiving null values I am making a POST request. The method parameters are null. I have verified the call and it seems fine to me. Any suggestions appreciated.
var WebServiceURL = 'https://localhost:44341/api/controllername/ForwardInfo'
$.ajax({
  type: webServiceRequestMethod,
  url: WebServiceURL,
  data: JSON.stringify(objSendData),
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data) {}
  failure: function() {}
})

[ApiController]
[Route("api/Ask4Purple/FowardInfo")]
public IActionResult FowardInfo(string zipcode, int searchRadius, string ProductCodes)
//public IActionResult FowardInfo([FromBody] ListOfStores value)
{
  string Zipcode = zipcode;
  int SearchRadius = searchRadius;
  string ProductCode = ProductCodes;
  // ...
}

A: You need to set the POST method receive a viewModel which contains all those properties:
public class MyViewModel
{
    public string zipcode { get; set; }
    public int searchRadius { get; set; }
    public string ProductCodes { get; set; }
}

Besides, maybe you have a typo in your OP that your use FowardInfo on route attribute while js url uses ForwardInfo.
Below is a working demo:
1.Ajax
var WebServiceURL = 'https://localhost:44341/api/Ask4Purple/ForwardInfo';
var objSendData = {
    zipcode: "123",
    searchRadius: 5,
    ProductCodes: "001"
};
$.ajax({
    type: "POST",
    url: WebServiceURL,
    data: JSON.stringify(objSendData),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) { }

})

2. Controller
[Route("api/[controller]")]
[ApiController]
public class Ask4PurpleController : ControllerBase
{
    [HttpPost("ForwardInfo")]

    public IActionResult ForwardInfo([FromBody] MyViewModel value)
    {
        string Zipcode = value.zipcode;
        int SearchRadius = value.searchRadius;
        string ProductCode = value.ProductCodes;
        // ...
        return new JsonResult(value);
    }
}

3.Result:


text:
Q: Get rows from stored procedure to Model This code is Working
  public virtual List<mbSummary_Result> mbSummary(Nullable<System.DateTime> fromDate,
        Nullable<System.DateTime> toDate)
    {
        var fromDateParameter = fromDate.HasValue
            ? new ObjectParameter("FromDate", fromDate)
            : new ObjectParameter("FromDate", typeof(System.DateTime));
        var toDateParameter = toDate.HasValue
            ? new ObjectParameter("ToDate", toDate)
            : new ObjectParameter("ToDate", typeof(System.DateTime));

        var result = ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<mbSummary_Result>("mbSummary",
            fromDateParameter, toDateParameter).ToList();

        return result;
    }

but when it produce so many rows it returns with this error:

An unhandled exception of type
  'System.Data.Entity.Core.EntityCommandExecutionException' occurred in
  EntityFramework.SqlServer.dll
Additional information: An error occurred while executing the command
  definition. See the inner exception for details.


text:
Q: Unable to connect java client application to dockerize ignite server in windows 10 I have been able to successfully run apache ignite with custom config using the command
docker run -it --net=host -v "pathToLocalDirectory"/config:/opt/ignite/apache-ignite/config -e "CONFIG_URI=file:///opt/ignite/apache-ignite/config/default-config.xml"  apacheignite/ignite.

But when I run my java project in IntelliJ I get the message
"IP finder returned empty addresses list. Please check IP finder configuration and make sure multicast works on your network...".
Note: the java client project works if I run the ignite server using windows batch file.
Also, I have published 47500 port as well. the result is the same.

A: try running it using docker -run -it --net=host (don't mount the volumes).
If that doesn't work, it means that either something is incorrect w/your docker setup OR you are configuring discovery differently for clients and servers.
check the IP addresses listed in your client discovery section.
ssh into the container and check what is actually mounted?
run docker exec -it container-name /bin/bash
check: /opt/ignite/apache-ignite/config/default-config.xml is there and contains the correct discovery info.
Check that the ignite log (located in /opt/ignite/apache-ignite/work/log/) specifies that the correct config is being used.
It will have a line like so: [INFO][main][IgniteKernal] Config URL: file:/opt/ignite/apache-ignite/config/default-config.xml
If you don't see the mounted config file try mounting more simply.
docker run -d -v /local/dir/config.xml:/config-file.xml -e CONFIG_URI=/config-file.xml   apacheignite/ignite
more info:
https://apacheignite.readme.io/docs/docker-deployment
https://apacheignite.readme.io/docs/tcpip-discovery


text:
Q: Why does string_stream.str() = a_string; compile? I can create an std::istringstream like so
std::istringstream string_stream(inp_string);

I can then change the contents of the stream:
string_stream.str(std::move(inp_string_2));

However, I might accidentally try something like this:
string_stream.str() = inp_string_2;

This compiles, but will not change the contents of string_stream. If you check the return value of std::istringstream::str() here, you will see that the return value is of non-reference type.
I believe that std::istringstream::str() is an r-value, and writing it on the left side of the equals sign should give an error, but the following code compiles in MSVC:
#include <iostream>
#include <string>
#include <sstream>

int main() {
    // Create string stream
    std::string inp_string = "this is a test string";
    std::istringstream string_stream(inp_string);

    // Try to replace the string stream
    std::string inp_string_2 = "a new test string";

    // incorrect:
    string_stream.str() = inp_string_2;            // Expected Error
    string_stream.str() = std::move(inp_string_2); // Expected Error

    // correct:
    // string_stream.str(std::move(inp_string_2));

    // Check contents of string stream
    std::cout << string_stream.str();
}

The output is
this is a test string

A Related Example
Below is similar example that will fail to compile:
#include <iostream>
#include <vector>

class MyClass {
private:
    std::vector<int> my_vec;

public:
    MyClass(std::vector<int>& vec) : my_vec(std::move(vec)){}

    int operator() (int i) {
        return my_vec[i];
    }
};

int main() {
    std::vector<int> inp = { 1, 2, 3, 4,  5 };
    MyClass my_class(inp);
    my_class(3) = 2;               // ERROR
    std::cout << my_class[3];

}

This gives the error
error C2106: '=': left operand must be l-value

as expected.


text:
Q: Electrons emitting photons. Real life example? In highschool we are taught about Bohr's atom model and how electrons emit light/ photons when transitioning from a higher energy orbit to a lower energy orbit.
First question
Where does this phenomenon actually occur in real life? Is it referring to when the sun/ stars emit light? Is it referring to when objects are heated?
Second question
Is this the only way light is emitted?
If so, how does the above phenomenon apply to a light bulb emitting light? My understanding for a light bulb emitting light is that a current (moving electrons) travels through the wires to the filament and the filament heats up to the point where it begins to emit photons. If this is the case, where is the explanation of electrons transitioning back to a lower energy state to emit photons as we are taught in highschool?
Your help would be much appreciated.

A: I recommend taking a look at this article.
https://en.wikipedia.org/wiki/Cold_cathode

And then this article
https://en.wikipedia.org/wiki/Black-body_radiation

A: The commonest example of electrons jumping energy levels and emitting light is the fluorescent lamp, first popularised as neon lights. The light from a given band is of a single frequency or color. Different atoms have different energy levels and emit different colored light. For example neon primarily emits red, sodium yellow, mercury red, blue and ultraviolet. Another increasingly common example is the light emitting diode or LED, such as the screen you are probably reading this on.
The broadband thermal "black body" radiation emitted by an incandescent filament reflects the surplus energy of an atom as a whole.
Stars emit both kinds of light. The main color is determined by its temperature as a black body, but superimposed on that are narrowband emission lines from its hot surface and absorption lines from its cooler atmosphere.
Light can be emitted by other mechanisms, for example any charged particle will emit light when accelerated, but they are relatively rare.

A: Photons are emitted when a charged object transitions from a higher energy state to lower. This is the fundamental principle. And all sources of light can be explained using this. It is also to be noted that what we see as light is only a small range of frequencies, plus only when many many photons are involved.
Now in the case of an incandescent bulb, electrical energy is converted into heat which is finally radiated as light. So how can we explain this in terms of our fundamental principle? Well, to begin with the wire is made up of many many atoms. And heat is basically the energy with which the atoms are vibrating about their mean positions. And the frequency of vibration is different in different atoms. Some with high some with low. And this energy sometimes causes an electron to excite to a higher energy state and transition back, releasing a photon as a result. Remember that if the photon doesn't have the right energy (of visible range) we won't be able to see it.
But as the temperature/heat increases, the number of atoms vibrating with higher frequencies also increases (look up canonical ensemble. This causes more and more electrons to excite-deexcite and release photons. And at some point, the temperature is just right to get a significant number of photons in the visible region.

As a side note, if the temperature is high enough, we will have similar number of photons at each frequency of the visible range in which case the emitter will look white.

A:
In highschool we are taught about Bohr's atom model and how electrons emit light/ photons when transitioning from a higher energy orbit to a lower energy orbit.
First question
Where does this phenomenon actually occur in real life? Is it referring to when the sun/ stars emit light? Is it referring to when objects are heated?

Visible light is a small part of the frequencies of the electromagnetic spectrum
The Bohr model was introduced in order to describe the visible spectrum absorption and emmision lines within the classical electromagnetic theory.
In classical electromagnetism, an accelerating charge would emit electromagnetic radiation, depending on the energy of the particle. The existence of atoms , i.e. with negaive electrons orbiting, like planets, around a positive nucleus could not be modeled in classical theory,because the negative electron would accelerate towards the positive nucleus and give a continuous spectrum of electromagnetic radiation. Also there could be no ions, as the electron would be absorbed. The experimental data gave absorption and emission spectra, and stable atoms.
The Bohr model solved the conundrum by postulating quantized angular momenta for the trajectories of the atoms. The theory of quantum mechanics developed a rigorous method of modeling the microworld of atoms and molecules.
Depending on the atoms of the material different color lines can be seen, and are used  as explained in the other answers.

Second question

Is this the only way light is emitted?
No, as mentioned in the first paragraph, accelering charges also emit light, for example a spark gives off light, because of the acceleration of numerous free electrons , free in various ways ( rubbing, cathode ray tubes...)
Also, again because of accelerating charges in solids and liquids and gasses,due to the temperature, electromagnetic radiation of many frequencies come out , called black body radiation, as mentioned in an other answer. This covers a lot of frequencies, depending on the temperature of the material. The radiation of the sun is predominantly black body,though one can see the spectral component also.
Black body radiation is how light is mainly emitted by incandescent lamps, and how iron show red when its temperature is high ...


text:
Q: Creating a new role How do I create a new role in my database with my first name which is Denise, and add read only access on the HR user's EMPLOYEES table to this role.

A: Using Adventureworks database as a reference, following shows sudo code
USE [AdventureWorks]
GO
CREATE ROLE [Denise]
GO
USE [AdventureWorks]
GO
GRANT SELECT ON [HumanResources].[Employee] TO [Denise]
GO

A: From the documentation on MSDN for Create Role and Grant select
create role denise identified by appropriateVariable;

grant select on HR.employees to denise;


text:
Q: set .htpasswd with bash expect I'm trying to automate setting a user's password in .htpasswd for Apache, but this script doesn't seem to actually set the password. What am I missing? Thanks!
#!/bin/bash

PASSWORD=`tr -dc a-z0-9_ < /dev/urandom | head -c 10`

cat << EOF | /usr/bin/expect
spawn /usr/bin/htpasswd -c /var/.htpasswd testuser
expect "assword:"
send "$PASSWORD\r"
expect "assword:"
send "$PASSWORD\r"
EOF

echo -e "\nPassword set to: $PASSWORD\n"

A: You can specify a password on the command line using the -b flag.
#!/bin/bash

PASSWORD=`tr -dc a-z0-9_ < /dev/urandom | head -c 10`
htpasswd -cb /var/.htpasswd testuser $PASSWORD
echo Password set to: $PASSWORD

# output:
# Adding password for user testuser
# Password set to: gzu00n4lp8

For clarification, here's a version using expect:
#!/bin/bash

PASSWORD=`tr -dc a-z0-9_ < /dev/urandom | head -c 10`

expect << EOF
spawn htpasswd -c /var/.htpasswd testuser
expect {
    "New password:" { send "$PASSWORD\r"; exp_continue }
    "Re-type new password:" { send "$PASSWORD\r"; exp_continue }
}
EOF

echo Password set to: $PASSWORD


text:
Q: Parse variable from URL to display different content on HTML page (JS) I have an email newsletter being sent out each week with a different subject and there's one webpage where you can click to from the email.
On week 1 the email is about 'phones' and if someone clicked the link it could contain a slightly different variable (for example week 1 being ?content=phone on the end of the URL).
When the webpage loads, only the content on phones is displayed.
There is going to be 8 emails so there will be 8 sets of content and different variables in the URLs on each week.
I just need a javascript to do this?

A: You can do something very simple and old-school with just HTML like:

This is my phone section

This is my car section

This is my house section

Then all of your urls look like:
emaillink1.html#car
Where the section you want at the top follows the hash mark.

A: If this has to be done on a static page on client side, you could use window.location.hash to show/hide different parts of the page.
https://developer.mozilla.org/en/window.location


text:
Q: How to use requests library without system-configured proxies If I supply None or an empty dict to the proxies parameter, requests will automatically fall back to the proxies configured for the operating system as obtained through urllib.request.getproxies() (Python 3) / urllib.getproxies().
import requests
r = requests.get('http://google.com', proxies = {}) # or = None...
print(r.text)

Specifying proxies = { 'http': False } will even cause requests to hang completely for whatever weird reason.
So how do I direct requests to perform HTTP requests directly, without any proxy ?

A: Turns out you have to use an empty string for the protocol you want to use a direct connection:
r = requests.get('http://google.com', proxies = { 'http': '', ... })

Weird, but that's life.


text:
Q: Add range of mulitlevel index in Python I would like to add a column containing the range of the first level of a multi-level index in Python.
For example:
| Index1| Index2| count_of_Index1_Instances |
---------------------------------------------
|   1   |  20   |           1              |
|       |  40   |           2              |
|       |  10   |           3              |
|   2   |  20   |           1              |

I know thedf.groupby(level=['Index1']).size() command, but this is not what I am looking for. The result in the last column should be a range from 1 to the size of Index-Group1.
Some piece of code would be great!
Thank you!

A: IIUC, use groupby.cumcount and add 1:
df['count_of_Index1_Instances'] = df.groupby(level=['Index1']).cumcount().add(1)


text:
Q: Windows 7 deployments via WDS result in oversized hiberfil.sys and pagefile.sys files. How do I stop that? The longer version: I have a stock Windows 7 image sitting in VMware Workstation that I use to create new VMs, to save time. I just snapshot and clone the stock image, and voila! a new Windows 7 VM. Now, I'm trying to use that same image with Windows Deployment Services (WDS) on Server 2012 to install Windows 7 to a Dell Optiplex 9010. Everything works fine, including the answer file for WinPE but NOT for post-install (still working on that), but once the installation is complete C:\ is WAY too big.
Upon further examination, I noticed that hiberfil.sys and pagefile.sys are 33GB and 25GB, respectively. This is MUCH larger than normal, and these outsized files do not appear when I use WDS to install the image in VMware. hiberfil.sys comes from Windows hibernate, and pagefile.sys is used by the RAM. Obviously I can't just go deleting them willy nilly.
Based on the files not appearing in the VM, it seems like they're being generated after deployment (as opposed to being captured as part of the image and then deployed out). The only difference between the installations is that the deployment to the physical machine also includes a driver set, which the VM deployment does not.
Short of disabling hibernation (which will shut down hiberfil.sys but not pagefile.sys), how can I prevent this giant files from appearing? Extra points if you can tell me why they're appearing.
EDIT: Turns out pagefile.sys is expanding because we're deploying the image to a machine with 16x RAM (32GB total). hiberfil.sys is so large because pagefile.sys is so large. We still don't know hiberfil.sys is showing up on machines with hibernation disabled (including the VMs), but at least we can disable it via the command line.

A: I would use powershell to disable the page file, or lower the page file size after deploying the image. After a reboot it should shrink or disappear.
This is quite easy for me since we use sccm osd, however it can still be done using wds alone. I haven't tested the code here yet, but there are different solutions across the net for it to be possible.


text:
Q: Exception thrown at 0x00000000 in Project0_opengl.exe: 0xC0000005: Access violation executing location 0x00000000 I'm writing right code but the compiler throws an error. The error says that the mistake is on glGenBuffers but I've copied it from the official website. Where is my mistake?
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <stdio.h>

int main(void)
{
    GLFWwindow* window;
    glewExperimental = GL_TRUE;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    float pos[6] = {
        -0.5f, -0.5f,
         0.0f,  0.5f,
         0.5f, -0.5f
    };

    GLuint buf;
    glGenBuffers(1, &buf);
    glBindBuffer(GL_ARRAY_BUFFER, buf);
    glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), pos, GL_STATIC_DRAW);

    if (glewInit() != GLEW_OK)
        printf("Error\n");

    printf("%s", glGetString(GL_VERSION));

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GL_TRIANGLES, 0, 3);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

A: glewInit() has to be called after the OpenGL context is made current, after glfwMakeContextCurrent.
But it has to be called before any OpenGL instruction. See also Initializing GLEW:
// [...]

/* Make the window's context current */
glfwMakeContextCurrent(window);

glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
    printf("Error\n");

float pos[6] = {
    -0.5f, -0.5f,
     0.0f,  0.5f,
     0.5f, -0.5f
};

GLuint buf;
glGenBuffers(1, &buf);
glBindBuffer(GL_ARRAY_BUFFER, buf);
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), pos, GL_STATIC_DRAW);

// [...]

Note, the instructions like glGenBuffers are function pointers. These pointers are initialized to NULL. glewInit() assigns the address of the function to those pointers.
When you try to call the function, before the initialization, this causes:

Access violation executing location 0x00000000


text:
Q: Create a dataframe from a list with multiple columns I want to create a dataframe from a list, the thing is that my column name is also in the list.
List:
['Input_file_column_name,Is_key,Config_file_column_name,Value\nEmployee ID,Y,identifierValue,identityTypeCode:001\nCumb ID,N,identifierValue,identityTypeCode:002\nFirst Name,N,first_Name \nLast Name,N,last_Name   \nEmail,N,email_Address   \nEntityID,N,entity_Id,entity_Id:01\nSourceCode,N,sourceCode,sourceCode:AHRWB\n']

Resulting dataframe:
Input_file_column_name Is_key Config_file_column_name                 Value
0            Employee ID      Y         identifierValue  identityTypeCode:001
1                Cumb ID      N         identifierValue  identityTypeCode:002
5               EntityID      N               entity_Id          entity_Id:01
6             SourceCode      N              sourceCode      sourceCode:AHRWB

How do I convert it? Do I convert the list to a dictionary and then do it or is there a way that it can be done directly?
Code:
import pandas as pd
with open('onboard_config.txt') as myFile:
  text = myFile.read()
result = text.split("regex")
print result

df=pd.DataFrame[[sub.split(",") for sub in result]]

A: Seems like you need splitlines then convert to Series.str.split
df=pd.Series(l[0].splitlines()).str.split(',',expand=True).T.set_index(0).T.dropna()
df
Out[1183]:
0 Input_file_column_name          ...                          Value
1            Employee ID          ...           identityTypeCode:001
2                Cumb ID          ...           identityTypeCode:002
6               EntityID          ...                   entity_Id:01
7             SourceCode          ...               sourceCode:AHRWB
[4 rows x 4 columns]

A:     split=list[0].split('\n')
    df= []
    for i in split:
        df.append(i.split(','))

    columns= df[0]
    df=df[1:]
    pd.DataFrame(df, columns=columns)

This will give you your desired df.


text:
Q: Angular TypeError: Cannot read property 'length' of null in interceptor when i deployed my project i am getting error of this. Cannot read property 'length' of null .Actually i am not getting where is the problem in my code. i share my interceptor.service code.please look it this code and share to suggestion me.where is the problem and i am sharing error screenshot also.thank you
interceptor.service.ts
 import { Injectable, Inject } from '@angular/core';
import {HttpInterceptor,HttpHandler,HttpRequest,HttpEvent,HttpClient,HttpHeaders,HttpResponse,HttpErrorResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import { LocalStorageService } from 'angular-2-local-storage';
import { LogserService } from '../logser.service';

import { Router  } from '@angular/router';
import 'rxjs/add/operator/do';
import 'rxjs/add/observable/forkJoin';
import { BatchService } from '../pages/config/batchnew/batch.service';

@Injectable()
export class MainInterceptorService implements HttpInterceptor {
    public error:boolean = true;
    constructor(public localStorage:LocalStorageService,
        public router:Router,public http:HttpClient,
        public loginService:LogserService,
      public BatchServ:BatchService
    ){

    }
//@Inject(Window) private window: any

  intercept(req:HttpRequest<any>,next:HttpHandler):Observable<HttpEvent<any>> {
    // console.log("interceptor",req)
    this.error=true;
    let url:any = req.url
    url = url.split('/')
    url =url[url.length-1]
    // console.log('url',url)
    // console.log(localStorage.get("token"))
    if (url =="authenticateuser"){
        const request = req.clone({
            headers:new HttpHeaders({
                // 'VitalAuthorization':  window.localStorage.getItem('token')
            })
        })
        // console.log("interceptorHeaderLogin",request)
        return  next.handle(request).do((event: HttpEvent<any>) => {
              if (event instanceof HttpResponse) {
                        // do stuff with response if you want
                        console.log("getting 39")
              }
            }, (err: any) => {
              if (err instanceof HttpErrorResponse) {
                if (err.status === 401) {
                  // redirect to the login route
                            // or show a modal
                            console.log("getting 46")

                  alert('UnAutorized access');
                  // console.log(err)
                }
              }
            });
    }else{
            console.log("Line 51")
        const request = req.clone({
            headers:new HttpHeaders({
                        'Authorization':  window.localStorage.getItem('token')

            })
            })

        // console.log("interceptorHeader",request)
        return  next.handle(request).do((event: any) => {
            console.log("getting in interseptor")
}, (err: any) => {
                console.log('error401')
                // console.log('interceptorStatus',err.statusCode)
              if (err instanceof HttpErrorResponse) {
                if (err.status == 501) {
                  // redirect to the login route
                  // or show a modal
                            console.log('error72')
                  if( this.error===true){
                        this.error=false;
                        // this.router.navigate(['/login/'+this.localStorage.get('url')])
                        alert('Session expired ...');
                        let data = JSON.parse(this.localStorage.get('userData'))
                        this.BatchServ.createLogin(data).subscribe((data:any) => {
                            if (data.validAuthentication && data.validAuthentication != "" && data.validAuthentication != "null" && data.validAuthentication !="false"){
                                             window.localStorage.setItem('token',data.validAuthentication);
                                             console.log("line83")
                                console.log(window.localStorage.getItem('token'));
                                window.location.reload();
                                         }
                                         else{

                                         }
                                     });

                  }
                  console.log(err)
                }
              }
            });

    }

    }

   }

and below my screen shot


text:
Q: Specifying gpar settings for grid arrows in R I'm developing a plot of proportionally sized arrows, and have a workflow for size, direction and arrow-head size, but there are a couple of issues with the arrowheads: 1. they have rounded line-join and 2. they don't close (see bottom right corner) even when type='closed'.
require(ggplot2)
require(grid)
d = data.frame(x = 1:10, y = 0, size = 1:10)

ggplot(d, aes(x, y, size = size)) +
  geom_segment(aes(xend = x, yend = y + size),
               arrow = arrow(length = unit(d$size, "mm"), type='closed')) +
  scale_size(range = c(2, 4))

Arrows are based on grid graphics, but I cannot figure out how to specify the setting.  get.gpar() yields:
$lineend
[1] "round"

$linejoin
[1] "round"

but gpar(linejoin = 'mitre', lineend = 'butt') does not change this.  Is there any way to change these settings?  Thanks in advance.

Edit
Plot image including grid.segments arrow added:

A: Found a solution (credit to @baptiste for the pointer).  If you use the geom_segment source code in github and make the following alterations you will end up with lovely pointy arrowheads:
1 require(proto)
2 add ggplot::: in first line of GeomSegment (currently line 51) as follows:
GeomSegment <- proto(ggplot:::Geom, {
3 add argument linejoin = 'mitre' to gpar in segmentsGrob (line 23):
lwd=size * .pt, lty=linetype, lineend = lineend, linejoin = 'mitre'),
Run both functions and you'll end up with:


text:
Q: Calculating the difference between multiple rows and one row containing the highest score in R This is my first post, so forgive me if I have missed anything obvious from my description:
I have a dataframe with 50 rows of different meditation types. The columns NDM, CDM and ADM are categories of meditation. The numbers represent how many times people endorsed each meditation type as belonging to that category, with an Unsure option as well. The Max column is the highest score in that row.
I want to minus each score for each meditation category (Columns: NDM,CDM,ADM,Unsure) from the max score (Across cols for each row) to show the difference between the two, and then create a new column containing the difference for each meditation category.
Finally I want to calculate the mean score from these difference scores and add a column with that in.

Meditation_Type
NDM
CDM
ADM
Unsure
Max

Meditation_1
12
63
8
9
63

Meditation_2
5
75
9
3
75

Meditation_3
20
45
26
1
45

Meditation_4
6
72
12
2
72

I used the code below to calculate the max score across each row:
 Cat_Med[, "max"] <- apply(Cat_Med[, 1:4], 1, max)

I am stuck as how to move forwards from here.
Thanks for reading :-)

A: Desired output is missing, but perhaps this is what you are looking for?
library(data.table)
DT <- fread("Meditation_Type    NDM     CDM     ADM     Unsure
Meditation_1    12  63  8   9
Meditation_2    5   75  9   3
Meditation_3    20  45  26  1
Meditation_4    6   72  12  2")

# make sure your data is in a data.tavle format.
# if it is nog, use setDT() to make it so

# melt to long format
DT.melt <- melt(DT, id.vars = "Meditation_Type")
# subytract each value from the maximum mediatation_type value
DT.melt[, value2 := max(value) - value, by = .(Meditation_Type)]
# cast to wide again
dcast(DT.melt, Meditation_Type ~ variable, value.var = c("value", "value2"))
#    Meditation_Type value_NDM value_CDM value_ADM value_Unsure value2_NDM value2_CDM value2_ADM value2_Unsure
# 1:    Meditation_1        12        63         8            9         51          0         55            54
# 2:    Meditation_2         5        75         9            3         70          0         66            72
# 3:    Meditation_3        20        45        26            1         25          0         19            44
# 4:    Meditation_4         6        72        12            2         66          0         60            70


text:
Q: scratchpad.io functions don't work I am trying to use functions on the website scratchpad.io, but they don't appear to work. I have tried using onclick events for buttons and just having it call the function from inside of the same script tag after it is defined. Does anyone know why this is, and how to fix it?
<script>
function Message(){
alert("scratchpad.io does not work with functions... You won't see this!");
console.log("scratchpad.io does not work with functions... You won't see this!");
}
Message();
</script>
<br>
<button onclick="Message();">Trigger Function</button>

A: scratchpad.io is for HTML & CSS, it does not support javascript. For that you can use one of the many other similar services that exist out there, like:
JSFiddle
JS Bin
CodePen


text:
Q: How to use "pretty" ironically Here is a quote from Peter Benchley's Jaws: "That's a pretty shitty trick."
I would like to know how common this expression is in English, and under what circumstances/instances is used. (That is, what exactly it means and what ironic degree do we have here).
I know that "pretty" can be used ironically, but to me as a non native, it sounds pretty odd.
So, would you please explain it in detail so that I can get a better understanding?

A: In this quote pretty is an informal intensifier meaning "very".  It strengthens the following adjective, shitty, which is an informal and rude word with a negative meaning, here expressing that Harry's trick was reprehensible.
I don't think any irony is involved here.


text:
Q: How do i find collection through a record related to the first collection I need to find a group of collection WHERE the search is based on a record on a related model.
To let you understand I need to get users with the company name that is LIKE my search input.
Here's what i've tried:
$users = App\User::with(['company' => function ($query) {
    $query->where('company_name', 'like', '%'.$searchInput.'%');
}])->paginate(10);

To be honest I spent hours on this but with no luck. I'm using jenseggers/mongodb on laravel 5.8.

A: You should add ::whereHas() to your query which will limit query results where company is like the search query.
Also you will need to change the ::with() closure to ::with('companies').
$users = App\User::whereHas('company', function ($query) use ($searchInput) {
    $query->where('company_name', 'like', '%'.$searchInput.'%');
})
->with('company')
->paginate(10);

Note the use ($searchInput).
Also check if the user relation is companies instead of company.


text:
Q: Autofill a select after submission via jQuery I've got a form where users can choose a car brand. After that I send an SQL-query with Ajax to fill the next select with all the models of the selected brand.
When the form is submited I check it via PHP and if there is any error I return to the previous form with an error-message and fields filled.
The problem is that the 'model' field has the "trigger" set on brand change.
How can I fix this: call the jquery again (to show the models in the select) and display the previous model as selected?
Ajax.php
if ($_POST['brand_car']) {
    $sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
    $req = $dbh->prepare($sql);
    $req->bindValue(':idBrand', $_POST['brand_car']);
    $req->execute();
    $model = array();
    foreach  ($req as $row){
            $model[] = array(
                            'id' => $row['id_model_car'],
                            'modele' => $row['name_model_car']
                        );
    }
    echo json_encode($model);
}

jQuery
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
if(id!=0)
    $.ajax({
        url: '/js/ajax.php',
        dataType: 'json',
        type: "POST",
        data: {brand_car: id},
        success: function(data){
            $('#model_car').html('<option id="0" value="">choose the model</option>');
            if (data.length > 0) {
                data.forEach(function (elem) {
                $('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
            });
         }}
    });

});
XHTML + PHP
<select id="brand_car" name="brand_car">
    <?php
    $sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
    $req = $dbh->query($sql);

    foreach  ($req as $row) {
        $val=$row['id_brand_car'];
        echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
            if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
        echo ' >'.$row['nom_brand_car'].'</option>';
    }
    ?>
</select>
<select id="model_car" name="model_car">
    <option></option>
</select>

A: There are various ways you can fix it.
jQuery Approach
I think the simplest way is to refractor your change() and seperate the ajax call from the change event, like so:
$('#brand_car').change(function () {
   var id = $(this).children(":selected").attr("id");
   getModels(id, 0);
}
function getModels(id, select) {
    if(id!=0)
        $.ajax({
           url: '/js/ajax.php',
           dataType: 'json',
           type: "POST",
           data: {brand_car: id},
           success: function(data){
               $('#model_car').html('<option id="0" value="0">choose the model</option>');
           if (data.length > 0) {
                 data.forEach(function (elem) {
                     $('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
                 });
                 $('#model_car').val(select);
           }}
    });
}

This allows you to make an AJAX call by calling getModels(). So all you have to do is call it:
<select id="brand_car" name="brand_car">
<?php
    $sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
    $req = $dbh->query($sql);

    foreach  ($req as $row) {
        $val=$row['id_brand_car'];
        echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
            if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
                 echo ' >'.$row['nom_brand_car'].'</option>';
    }

?>
</select>
<select id="model_car" name="model_car">
    <option></option>
</select>

Tag this at the end:
<?php
    echo '<script>getModels('.$_SESSION["brand_car"].', '.$_SESSION['model_car'].');</script>';
?>

This way the code is also more testable. This isn't a perfect solution and you should definitely consider using $(function(){}); to make sure the document is ready. AJAX request also needs time to complete, so that models won't be there instantaneously when the page loads.
PHP Approach
Alternatively, you could consider reusing your AJAX code. Wrap it into a function:
function getModels($dbh, $brand_car) {
   // I know nothing about your design, but globals are no good
   $sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
   $req = $dbh->prepare($sql);
   $req->bindValue(':idBrand', $brand_car);
   $req->execute();
   $model = array();
   foreach  ($req as $row){
        $model[] = array(
                        'id' => $row['id_model_car'],
                        'modele' => $row['name_model_car']
                    );
   }
   return $model;
}

AJAX.php
if ($_POST['brand_car']) {
    echo json_encode(getModels($dbh, $_POST['brand_car']));
}

In your XHTML + PHP
<select id="model_car" name="model_car">
   <?php
       foreach(getModels($dbh, $_SESSION["brand_car"]) as $model) {
              echo '<option name="'.$model["id"].'" id="'.modelp["id"].'">'.$model["modele"].'</option>';
       }
   ?>
</select>

PS. It looks like your $_SESSION['brand_car'] is never updated.


text:
Q: Should I exclude factors loaded by only one variable when computing factor score I'm writing a thesis on "Factor affecting students academic performance at second cycle institutions."
I used factor analysis to extract 20 factors from 63 variables that presumably influence academic performance in second cycle institutions.
Out of the 20 factors extracted three of these factors had only one variable each. My question: would it be appropriate if I compute factor scores for the remaining 17 factors and ignore the three because they were only loaded by one variable?


text:
Q: What is the best way to loop bluebird promises Now I've working on NodeJS and Sequelize to query and process an database data.
I've call findAll from Table1 and I want to query each rows to apply some data to Table2 then I want to add all data to array before send output, I did like this
var last_promise;
var output_results = {};
Table1Model.findAll()
.then(function(results1)
{
    for (var i = 0; i < results1.length; ++i)
    {
        var result1 = results1[i];
        output_results[result1.id] = result1;
        var add_promise = Table2Model
            .create({
                id_from_table1: result1.id,
                data_from_table1: result1.data
            });
            .then(function(result2) {
                output_results[result2.id_from_table1].data2 = result2;
            });
            if (last_promise)
            {
                last_promise.then(function()
                {
                    return add_promise;
                });
            } else {
                last_promise = add_promise;
            }
        }
    }
}
last_promise.then(function() {
    return output_results;
}

I want to know that there any better way to execute promises sequentially in a loop like this ?

A: It looks like you can do that with .all() method:
Table1Model
  .findAll()
  .then(function(results1) {
    return Promise.all(results1.map(function(result) {
      return Table2Model
        .create({
            id_from_table1: result1.id,
            data_from_table1: result1.data
        })
        .then(function(result2) {
            ...
        });
    }));
  })
  .then(function(output_results) {
  });


text:
Q: Posting url through Facebook Graph API does not embed the url, just puts it as a url I am trying to post a URL to wall. Usually, when you post by hand it will load and include a snippet with the title, image, and byline. This does not happen with my API call. Using Python 3.10, with the facebook-sdk.
def post(self, article):
    print(f"\n\n[FacebookPoster] Posting on Facebook:\n\n\"{article.post}\"\n\n")
    self.graph.put_object(parent_object="me", connection_name="feed", message=article.post)

Thanks ahead of time!

A: Try to use the link parameter to pass your URL.
If I modify your code, it should give something like:
def post(self, article):
  print(f"\n\n[FacebookPoster] Posting on Facebook:\n\n{article.post}\n\n")
  self.graph.put_object(parent_object="me", connection_name="feed", message=article.post, link=article.link)


text:
Q: Parsing XML from webpage If I copy and paste the xml from this site into a xml file I can parse it with java
http://api.indeed.com/ads/apisearch?publisher=8397709210207872&q=java&l=austin%2C+tx&sort&radius&st&jt&start&limit&fromage&filter&latlong=1&chnl&userip=1.2.3.4&v=2
However, I want to parse it directly from a webpage if possible!
Here's my current code:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;

  public class XMLParser {

public void readXML(String parse) {
    File xml = new File(parse);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xml);
 //         System.out.println("Root element :"
 //                 + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("result");

        System.out.println("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

 //             System.out.println("\nCurrent Element :" +
     nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                System.out.println("job title : "
                        +
 eElement.getElementsByTagName("jobtitle").item(0)
                        .getTextContent());;
                System.out.println("Company: "
                        +
  eElement.getElementsByTagName("company")

 .item(0).getTextContent());
                System.out.println("City : "
                        +
  eElement.getElementsByTagName("city").item(0)
                                .getTextContent());
                System.out.println("State : "
                        +
eElement.getElementsByTagName("state").item(0)
                                .getTextContent());
                System.out.println("Country : "
                        +
eElement.getElementsByTagName("country").item(0)
                                .getTextContent());
                System.out.println("Date posted : "
                        +
     eElement.getElementsByTagName("date").item(0)
                                .getTextContent());
                System.out.println("Job summary : "
                        +
    eElement.getElementsByTagName("snippet").item(0)
                                .getTextContent());
                System.out.println("Latitude : "
                        +
 eElement.getElementsByTagName("latitude").item(0).getTextContent());
                System.out.println("longitude : "
                        +
eElement.getElementsByTagName("longitude").item(0).getTextContent());

            }
        }

    } catch (ParserConfigurationException | SAXException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    new XMLParser().readXML("test.xml");
}
 }

any help would be appreciated.

A: Give it the URI instead of the XML. It will download it for you.
Document doc = dBuilder.parse(uriString)

A: Please find the code snippet like this
String url = "http://api.indeed.com/ads/apisearch?publisher=8397709210207872&q=java&l=austin%2C+tx&sort&radius&st&jt&start&limit&fromage&filter&latlong=1&chnl&userip=1.2.3.4&v=2";

try
{
  DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
  DocumentBuilder b = f.newDocumentBuilder();
  Document doc = b.parse(url);
}

A: That's how I parsed data directly from url http://www.nbp.pl/kursy/xml/+something
static class Kurs {
    public float kurs_sprzedazy;
    public float kurs_kupna;
}

private static DocumentBuilder dBuilder;

private static Kurs getData(String filename, String currency) throws Exception {
    Document doc = dBuilder.parse("http://www.nbp.pl/kursy/xml/"+filename+".xml");

    doc.getDocumentElement().normalize();
    NodeList nList = doc.getElementsByTagName("pozycja");

    for(int i = 0; i < nList.getLength(); i++) {
        Element nNode = (Element)nList.item(i);
        if(nNode.getElementsByTagName("kod_waluty").item(0).getTextContent().equals(currency)) {
            Kurs kurs = new Kurs();
            String data = nNode.getElementsByTagName("kurs_sprzedazy").item(0).getTextContent();
            data = data.replace(',', '.');
            kurs.kurs_sprzedazy = Float.parseFloat(data);
            data = nNode.getElementsByTagName("kurs_kupna").item(0).getTextContent();
            data = data.replace(',', '.');
            kurs.kurs_kupna = Float.parseFloat(data);
            return kurs;
        }
    }
    return null;
}


text:
Q: Reverse engineer pl/sql to flowchart or any other diagram Does anyone know of an open source/free tool for converting pl/sql code to a flowchart or data flow or activity diagram?
Thanks

A: *

*Visustin v6 Flow chart generator

*Code Visual to Flowchart 3.5

They are not really freeware but you can do pretty much everything using their free version.

A: No I don't.  Data flow and activity diagrams are at a much higher level of abstraction than PL/SQL code, so it wouldn't make sense to try to generate those from PL/SQL.  Flowcharts are for code, but I thought they went out of vogue about 25 years ago?  They are so pointless.
What you can get are IDEs like SQL Developer (free), Toad etc. that can show the structure of your code, allow you to collapse logical blocks of code, colour code the different elements of the code, indent code etc.

A: It might be of help to build a kind of three with a query through dba_dependencies:
select lpad(name, length(name)+3*level, ' ')
,      type
,      prior name
--,      prior type
from   dba_dependencies
start
with   name='&enter_your_package'
and    type='PACKAGE'
connect
by     nocycle
       name = prior referenced_name
and    type = prior referenced_type
;


text:
Q: On conditions to prove that a Lie group is compact. Can anyone help me with this problem:
If G is a Lie group and H a compact subgoup of G, such that G/H is also compact, how to prove that G is compact?
I have tried to push forward an open covering of G to G/H be the quotient map, apply compactness and then pull it back, but there are subtle accommodations that should be made and I can not figure out how. Thanks in advance.

A: Root idea:  take an open cover
$$
G = \bigcup_{\alpha} U_\alpha.
$$
Since $H$ is compact, so is every coset $gH$.  So, $G$ can be partitioned into compact components, so to speak. And, note that the quotient space $G/H$ is also compact, by assumption.
So, each coset $gH$ is also covered by the same covering, but by compactness you only need a finite number of them.  Denote this cover by
$$
\mathcal{U}_g = \bigcup_{i=1}^{n_g} U_{\alpha_i}^g
$$
where I hope it is somehow clear that every $U_{\alpha_i}^g$ is one of the original $U_\alpha$'s.  (There may very well be better notation and indexing, but I'm in a hurry.)
As $gH \subseteq \mathcal{U}_g$ and $q$ is a closed map there is an open set $W_g$ in $G/H$ such that $q^{-1}(W_g) \subseteq \mathcal{U}_g$.  Now $\bigcup_{g \in G} W_g$ covers $G/H$ and by compactness this can be done finitely:
$$
G/H = \bigcup_{i=1}^r W_{g_i}.
$$
Now, if you take the preimage under $q$ of both sides you get
$$
G = \bigcup_{i=1}^r q^{-1}(W_{g_i}).
$$
But now we have
$$
G = \bigcup_{i=1}^r q^{-1}(W_{g_i}) \subseteq \bigcup_{i=1}^r \mathcal{U}_{g_i} = \bigcup_{i=1}^r \bigcup_{k=1}^{n_{g_i}} U_{\alpha_k}^{g_i}.
$$
This last union is a finite one derived from the original cover, so $G$ is compact.


text:
Q: Execute npm start or npm run with Input variable I have been reading and trying everything I can but I can't find a way to mock the input data of my javascript project, it is supposed to be a window in a web page that inherits the data from cached variables that it reads when starting.
I can modify the code by hand and put the data inside it, but then there can be errors of forgetting to delete the data when doing the commit.
Any ideas to send the data from a global variable to the project while it starts?
PS: I can mock the service calls through the package.json and generate the desired result in the window, but I prefer to pass the input data and verify that the services work correctly without the need to mock them


text:
Q: When copy the url from one browser to another browser my session data are not coming in asp.net MVC3 When i copy the URL from one browser to paste it in another browser my session data not retrieved it shows "Object reference not set to an instance of an object".

A: (Please note - this answer assumes you are not already using cookieless sessions)
The way sessions work in ASP.NET is that when you first access a site, a cookie-file is placed in your browsers cookie-store. The cookie contains a session ID, so the next time you access that site from that browser the ID is passed to the web-application and it knows which session-state to load.
However, each browser implements it's own cookie-store, so switching browsers means the site cannot determine your session ID.
One way to get around this is to use cookieless sessions. However, these have a number of issues relating to usability and security, so think long and hard before deciding they are for you.
Another option is to tie together your authorization and session systems. However, this is not generally recommended either.

A: You will not be able to access session values across multiple browsers.
Also, you should check if the value exists in Session to avoid Server Error.
if(Session["Key"] != null)
{
//Write your code here
}
else
{
 //Alternative code (redirection code)
}


text:
Q: value getting null while calling function from another form in windows form i am working on windows form application.i have two froms
in MDIparant form i opening my two form together like this:
Public Class MDIParent1
    Dim frmVE As VisitorInfo
  Dim frmVX As VisitorExitsign

Private Sub InvokeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InvokeToolStripMenuItem.Click

frmVX = New VisitorExitsign
        frmVX.Location = New Point(781, 0)
        frmVX.MdiParent = Me
        frmVX.Show()

        frmVE = New VisitorInfo()
        frmVE.Location = New Point(0, 0)
        frmVE.MdiParent = Me
        frmVE.Show()

now both forms are opend .i have one save button in Visitoinfo form .
also i have textbox in visitorexitsign form.name is txtvisitoridExit
while cliking save button i want to check wethar this textbox(txtvisitoridExit) contains any value,then i have to cal function in the VisitorExitsign form..so i wrote code like this:
Dim forms As FormCollection = Application.OpenForms
        For Each form As Form In forms
            If form.Name = "VisitorExitsign" Then
                Dim vs As String = CType(form, VisitorExitsign).txtvisitoridExit.Text
                VisitorExitsign.savebutton()
            End If
        Next

here am getting valu if vs .but
while going VisitorExitsign page am getting this textbox value (txtvisitoridExit.Text) null.how come that value become null
how i can resolve this issue?

A: Reason: You are calling a local variable in another scope(VisitorExitSign), this will result a null value.
Solution: Define a Public Static value for what you want to call in another form.
Example:-
In the first form
Public Static Dim textbox1 As String = txtvisitoridExit.Text
In the second from
Dim vs As String = CType(form, VisitorExitsign).txtvisitoridExit.Text
Conclusion: You will get the real value.


text:
Q: HttpHandler Redirect I want to write an HttpHandler to redirect traffic to various webpages on the server.
The user will type in http://www.thisissupposedtoberedirected.com/site12 and should be redirected to the appropiate site, in this example site version 1.2
I know how to program in ASP.NET and C# but I don't seem to grab the finer detail about website management.
How can I manage to get this done? What should I do in the web.config? I've read this msdn page but it isn't much help.

A: HttpHandlers are actually fairly simple components.
First, you need to create a class that inherits either IHttpHandler or IHttpAsyncHandler (for your use, I'd suggest IHttpHandler since there's really no heavy lifting being done).
You then compile the DLL and drop it in the bin folder of your web application.
Now the tricky part. Deploying HttpHandlers in the web.config file is tricky since it's different between IIS6, IIS7 Integrated Mode, and IIS7 Classic Mode. The best place to look is this MSDN page:
How to: Register HTTP Handlers
IIS6
<configuration>
  <system.web>
    <httpHandlers>
      <add verb="*" path="SampleHandler.new"
        type="SampleHandler, SampleHandlerAssembly" />
    </httpHandlers>
  <system.web>
</configuration>

IIS7 Classic Mode
<configuration>
  <system.web>
    <httpHandlers>
      <add verb="*" path="SampleHandler.new"
        type="SampleHandler, SampleHandlerAssembly" />
    </httpHandlers>
  <system.web>
  <system.webServer>
    <add name=SampleHandler" verb="*" path="SampleHandler.new"
      Modules="IsapiModule"
      scriptProcessor="FrameworkPath\aspnet_isapi.dll"
      resourceType="File" />
  </system.webServer>
</configuration>

IIS7 Integrated Mode
<configuration>
  <system.webServer>
    <handlers>
      <add name="SampleHandler" verb="*"
        path="SampleHandler.new"
        type="SampleHandler, SampleHandlerAssembly"
        resourceType="Unspecified" />
    </handlers>
  <system.webServer>
</configuration>

As you can see, each IIS configuration requires entries in slightly different sections of the web.config file. My suggestion would be to add entries in each location so that IIS configuration changes don't break your HttpHandler.

A: 1) You need to create a new class that implements IHttpHandler or IHttpAsyncHandler (the latter being when you are very comfortable with managing your own threads). Create your logic there.
2) Then, modify the web.config so that you register your handler:
<system.web>
    <httpHandlers>
      <add verb="*" path="*.htm" type="System.Web.StaticFileHandler"/>
      <add verb="*" path="*.html" type="System.Web.StaticFileHandler"/>
      <add verb="*" path="*.ico" type="System.Web.StaticFileHandler"/>
    </httpHandlers>
</system.web>

This is a sample setup in my web.config - yours may vary slightly.
Now, your HttpHandler should be registered and based on the details provided in your registration in the web.config, when you request certain URLs, you will be mapped to the Handler you created instead of the normal ASP.NET Page Handler.
Additionally, for your specific issue, I wouldn't recommend writing a HttpHandler - I would just do a DNS redirect, or do some lookup in your OnInit code to check the Host Url, and if it is one specified in your DB, you do the redirect yourself based on the configuration data.


text:
Q: Inpute missing value based on identifier I like to fill in missing values for some variable based on its value paired with a matching index. Example (First col is the index; second col is the values).
mat <- cbind(c(1,1,2,2,3,3,4,4,4), c(4.3, NA, 2.4, NA, 3.8, NA, 1.2, NA, NA))
newmat <- cbind(c(1,1,2,2,3,3,4,4,4), c(4.3, 4.3, 2.4, 2.4, 3.8, 3.8, 1.2, 1.2, 1.2))

A: We can use fill
library(dplyr)
library(tidyr)
mat %>%
  as_tibble %>%
  group_by(V1) %>%
  fill(V2, .direction = 'updown')


text:
Q: Using Entity frame work Code First with built in asp.net membership authentication I found this post on using the simple membership provider that ships with MVC 4.
Using MVC 4 SimpleMembership with an existing database-first EF model
I already have a data layer set up using IOc etc using the ef code first approach. Every thing is pretty clean at the moment and I want to keep it that way. The above post is great and explains a lot but there is one question that is not answered...
HOW DOES THIS FIT IN WITH CODE FIRST MIGRATIONS (Sorry for the caps)
The point I am making is currently my entities are mapped to the database, when I make changes to the entities the  database updates, I can add seed data etc.
Now how do the membership tables that are created fit in to all of this.
Do they get created each time I run the application?
What order are the tables created in? i.e. My custom tables then the membership ones. When does the seed code run?
Any ideas?
One last thing the post says that you need to provide a connection 'string'... and you cant use your ef entities to get the connection string..
I do not want to have a direct reference from the MVC site directly to the database even if that is just a connection string... surely this should come via a service?


text:
Q: Issue with typing a large text in the Espresso test script If I try to type a large content of the text in the message body while automating it's not working. It throws the below error:

java.lang.RuntimeException: Failed to get key events for string Daniel
  is a British bloke who works with Skyscanner and LonelyPlanet on the
  regular. He's an amazing writer with tons of useful tips, and is an
  even better photographer. I had the privilege of traveling with Daniel
  and working with him in India. There was never a dull moment! His
  photography has also been published in Beautiful Destination, Travel &
  Leisure, National Geographic, Travel Channel and Matador Network.
  (i.e. current IME does not understand how to translate the string into
  key events). As a workaround, you can use replaceText action to set
  the text directly in the EditText field.

I tried replacing the command from "typeText()" to "replaceText()" which eventually didn't work for me.


text:
Q: joblib to do parallel computing of a for loop, get error:'A task has filed to un-serialize' I am using joblib to parallel a for loop for my own function.
from joblib import Parallel, delayed
from my_function import my_case_study

result = Parallel(n_jobs=4)(delayed(my_case_study)(i) for i in range(100))

So my_case_study is the only function in my_function.py file, and it takes i as the hyperparameter. my_case_study calls a bunch of different model fitting algorithm contains in the other python files, which are imported at the top of my_function.  my_function.py basicly looks like
from anotherfile import fun1
from anotherfile import fun2
def my_case_study(i):
     mse1 = fun1(i)
     mse2 = fun2(i)
     return (mse1,mse2)

But then I get the error message: A task gas failed to un-serialize. Please ensure that the arguments of the function are all picklable.
How to solve this? Thanks!!

A: I found the solution in the following link helpful in my case:

https://github.com/joblib/joblib/issues/810

Don't know if there is any other better solution. Since the comments at the end mentioned that there might be some issues with that (didn't fully understand).


text:
Q: How to iterate for each column name and append it to a table or data frame in python I want to make a customize correlation table, after a long script this is my final data look like:
ID        a      ...  z
1         76.0   ...  1.033004
2         257.0  ...  0.629641
3         99.0   ...  0.672139
4         52.0   ...  1.007708
5         129.0  ...  1.080922

And this is the script I made to my customize correlation table for a vs all variable
pg.pairwise_corr(df_pvt, columns=[['a'], list(df_pvt.columns)], method='pearson')[['X','Y','r']].append
pg.pairwise_corr(df_pvt, columns=[['b'], list(df_pvt.columns)], method='pearson')[['X','Y','r']].append ......... #until variable z

How can I loop or select specific column number without typing variable name 'a' until 'z'  ?
I am new in python. Thank you in advance

A: import pandas as pd

data = pd.DataFrame({"ID": [1,2,3,4,5], "a": [76.0, 257.0, 99.0,52.0,129.0], "z": [1.033004, 0.629641, 0.672139,1.007708, 1.080922]}, columns=["ID", "a", "z"])

true_columns = []

for index, row in data.iterrows():
    true_col_list = [col for col in data.columns[1] if row[col]]
    true_columns.append(",".join(true_col_list))

data["Columns"] = true_columns

print(data)

A: As I'm not allowed to comment yet, I think this is what you're looking for. Correct me if I'm wrong.
for letter in 'abcdefghijklmnopqrstuvwxyz':
    pg.pairwise_corr(df_pvt, columns=[letter], list(df_pvt.columns)], method='pearson')[['X','Y','r']].append ....

edit: And I think, if you want to be cool and pythonic (I've seen this in many answers) you could not write out the alphabet yourself but import it with
import string
alphabet = string.ascii_lowercase # this equals 'abcdefghijklmnopqrstuvwxyz'

# then iterate over the alphabet
for letter in alphabet:
    # do your stuff here something something[letter] something :P


text:
Q: Python Pandas find element in a list I created two list from pandas dataframe as follows:-
List1: was created from multiple csv files within a folder as seen below...

import glob as gb
csv_files = gb.glob("csv\\*.csv")

# csv_files = csv_files[0:]

# Create list of the CSV in dataframes
dfList = []
for file in csv_files:
    df_csv = pd.read_csv(file, header=None)
    dfList.append(df_csv)

# print (dfList)

# Convert each dataframe within the list into individual list
new_dfList = []
for ind_df in dfList:
    # Convert the dataframe to a list
    new_convert = ind_df.values.tolist()
    new_dfList.append(new_convert)

List2: was created from a text file that contain keywords as seen below.

# Open keywords TEXT file
keywords = pd.read_csv("words.txt", header=None)

# Convert the dataframe to a list
keywords = keywords.values.tolist()

# Move out from inner list
# keywords = list(chain(*keywords))

# print (keywords)
keywords[0]

These keywords from list2 are to be compared with each list in list1. How do I do it?
How do I make the first keyword (in list2) goto first list (in list1), second keyword (in list2) goto second list (in list1), third keyword (in list2) goto third list (in list1)....and so on to search and return a match result?

A: Why don't you just do it in pandas?
keywords = pd.read_csv("words.txt", header=None)

dfList = []
for file in csv_files:
    df_csv = pd.read_csv(file, header=None)
    dfList.append(df_csv)

df = pd.concat(dfList, keys=keywords)
# Or, make a panel
wp = pd.Panel(dict(zip(keywords, dfList)))
# Or, just leave it as a dictionary
df_dict = dict(zip(keywords, dfList))

And if you really want a dictionary of lists:
df_dict_list = dict(zip(keywords, [df.tolist() for df in dfList]))


text:
Q: Implicit conversion and functional operators I'm studying functional operators and can't understand why code snippets like this compile:
class Pocket
{
    int value;
public:
    Pocket(int value) :value(value) {}
    int getValue() const
    {
        return value;
    }
    operator int() const
    {
        return value;
    }
    bool operator<(const Pocket & _Right) const
    {
        return value < _Right.value;
    }
};

int main() {
    Pocket mynumbers1[] = { 3, 9, 2, -4, 4 };
    Pocket mynumbers2[] = { 3, 9, 5, 0, 4 };
    vector<Pocket> v1(mynumbers1, mynumbers1 + 5);
    vector<Pocket> v2(mynumbers2, mynumbers2 + 5);
    vector<Pocket> v3(5, 0);
    transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), minus<Pocket>());
    return 0;
}

My reasoning is that when you call the minus<Pocket> operator inside transform, the whole thing would reduce to a subtraction between two Pockets. As you can see, the class doesn't defines a proper operator-, only an operator<, which should be useless in this case, and a conversion to int, which shouldn't even be considered since both arguments are of the same type.
So what am I missing?

A: The user-defined conversion function which makes the following initializations possible in your code:
Pocket mynumbers1[] = { 3, 9, 2, -4, 4 };
Pocket mynumbers2[] = { 3, 9, 5, 0, 4 };

will also be used by the compiler in the transform call when applying the minus to the given range :
transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), minus<Pocket>());

If you were to remove the operator int() const conversion function neither the initializations nor the transform would work.
However, if you were to make the conversion function explicit, it would work for initializations but not for the transform. See demo here.
The relevant section in the standard for this:

15.3.2 Conversion functions [class.conv.fct]
  ...
  2.  A conversion function may be explicit, in which case it is only considered as a user-defined conversion for direct-initialization. Otherwise, user-defined conversions are not restricted to use in assignments and initializations.


text:
Q: Computer crashes when shutting down Sometimes, when I shut down my computer, it does not shut down, but it restarts. When I log in, I get the message that Windows recovered from an unexpected shutdown:
Problem signature:
  Problem Event Name:   BlueScreen
  OS Version:   6.1.7601.2.1.0.256.48
  Locale ID:    1033

Additional information about the problem:
  BCCode:   9f
  BCP1: 0000000000000003
  BCP2: FFFFFA8007057BB0
  BCP3: FFFFF80000B9C3D8
  BCP4: FFFFFA80074137C0
  OS Version:   6_1_7601
  Service Pack: 1_0
  Product:  256_1

Files that help describe the problem:
  C:\Windows\Minidump\070314-27565-01.dmp
  C:\Users\Thomas\AppData\Local\Temp\WER-202754-0.sysdata.xml

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
  C:\windows\system32\en-US\erofflps.txt

You can find the dump file in the code block at the bottom. I've also tried the "Check for solution" button, but that dialog box just disappears after some time and does not show a solution.
What is causing this issue? And how can I fix this?
    Microsoft (R) Windows Debugger Version 6.12.0002.633 AMD64
    Copyright (c) Microsoft Corporation. All rights reserved.

    Loading Dump File [C:\Windows\Minidump\070314-27565-01.dmp]
    Mini Kernel Dump File: Only registers and stack trace are available

    DbsSplayTreeRangeMap::Add: ignoring zero-sized range at ?00000000`00000000?
    DbsSplayTreeRangeMap::Add: ignoring zero-sized range at ?00000000`00000000?
    DbsSplayTreeRangeMap::Add: ignoring zero-sized range at ?00000000`00000000?
    DbsSplayTreeRangeMap::Add: ignoring zero-sized range at ?00000000`00000000?
    DbsSplayTreeRangeMap::Add: ignoring zero-sized range at ?00000000`00000000?
    DbsSplayTreeRangeMap::Add: ignoring zero-sized range at ?00000000`00000000?
    DbsSplayTreeRangeMap::Add: ignoring zero-sized range at ?00000000`00000000?
    DbsSplayTreeRangeMap::Add: ignoring zero-sized range at ?fffff8a0`002b76c2?
    DbsSplayTreeRangeMap::Add: ignoring zero-sized range at ?fffff8a0`08437c32?
    DbsSplayTreeRangeMap::Add: ignoring zero-sized range at ?fffff800`00b9c3c0?
    Symbol search path is: symsrv*symsrv.dll*c:\localsymbols*http://msdl.microsoft.com/download/symbols
    Executable search path is:
    Windows 7 Kernel Version 7601 (Service Pack 1) MP (4 procs) Free x64
    Product: WinNt, suite: TerminalServer SingleUserTS
    Built by: 7601.18409.amd64fre.win7sp1_gdr.140303-2144
    Machine Name:
    Kernel base = 0xfffff800`03058000 PsLoadedModuleList = 0xfffff800`0329b890
    Debug session time: Thu Jul  3 20:22:22.486 2014 (UTC + 2:00)
    System Uptime: 0 days 12:05:52.703
    Loading Kernel Symbols
    ...............................................................
    ................................................................
    ..............................................................
    Loading User Symbols
    Loading unloaded module list
    ........
    *******************************************************************************
    *                                                                             *
    *                        Bugcheck Analysis                                    *
    *                                                                             *
    *******************************************************************************

    Use !analyze -v to get detailed debugging information.

    BugCheck 9F, {3, fffffa8007057bb0, fffff80000b9c3d8, fffffa80074137c0}

    Unable to load image \SystemRoot\system32\DRIVERS\VBoxNetAdp.sys, Win32 error 0n2
    *** WARNING: Unable to verify timestamp for VBoxNetAdp.sys
    *** ERROR: Module load completed but symbols could not be loaded for VBoxNetAdp.sys
    Probably caused by : ntkrnlmp

    Followup: MachineOwner
    ---------

If I run the !analyze -v, I get:
*******************************************************************************
*                                                                             *
*                        Bugcheck Analysis                                    *
*                                                                             *
*******************************************************************************

DRIVER_POWER_STATE_FAILURE (9f)
A driver is causing an inconsistent power state.
Arguments:
Arg1: 0000000000000003, A device object has been blocking an Irp for too long a time
Arg2: fffffa8007057bb0, Physical Device Object of the stack
Arg3: fffff80000b9c3d8, Functional Device Object of the stack
Arg4: fffffa80074137c0, The blocked IRP

Debugging Details:
------------------

DRVPOWERSTATE_SUBCODE:  3

IMAGE_NAME:  ntkrnlmp

DEBUG_FLR_IMAGE_TIMESTAMP:  0

MODULE_NAME: ntkrnlmp

FAULTING_MODULE: fffff88000db9000 VBoxNetAdp

IRP_ADDRESS:  fffffa80074137c0

DEVICE_OBJECT: fffffa800a397050

DRIVER_OBJECT: fffffa800a37e220

CUSTOMER_CRASH_COUNT:  1

DEFAULT_BUCKET_ID:  VISTA_DRIVER_FAULT

BUGCHECK_STR:  0x9F

PROCESS_NAME:  System

CURRENT_IRQL:  2

STACK_TEXT:
fffff800`00b9c388 fffff800`0313d8d2 : 00000000`0000009f 00000000`00000003 fffffa80`07057bb0 fffff800`00b9c3d8 : nt!KeBugCheckEx
fffff800`00b9c390 fffff800`030d885c : fffff800`00b9c4c0 fffff800`00b9c4c0 00000000`00000000 00000000`00000003 : nt! ?? ::FNODOBFM::`string'+0x33af0
fffff800`00b9c430 fffff800`030d86f6 : fffffa80`0a93c758 fffffa80`0a93c758 00000000`00000000 00000000`00000000 : nt!KiProcessTimerDpcTable+0x6c
fffff800`00b9c4a0 fffff800`030d85de : 00000065`676f3757 fffff800`00b9cb18 00000000`002a998e fffff800`0324c448 : nt!KiProcessExpiredTimerList+0xc6
fffff800`00b9caf0 fffff800`030d83c7 : 00000018`b371f8c5 00000018`002a998e 00000018`b371f83d 00000000`0000008e : nt!KiTimerExpiration+0x1be
fffff800`00b9cb90 fffff800`030c58ca : fffff800`03248e80 fffff800`03256cc0 00000000`00000001 fffff880`00000000 : nt!KiRetireDpcList+0x277
fffff800`00b9cc40 00000000`00000000 : fffff800`00b9d000 fffff800`00b97000 fffff800`00b9cc00 00000000`00000000 : nt!KiIdleLoop+0x5a

STACK_COMMAND:  kb

FOLLOWUP_NAME:  MachineOwner

FAILURE_BUCKET_ID:  X64_0x9F_3_IMAGE_ntkrnlmp

BUCKET_ID:  X64_0x9F_3_IMAGE_ntkrnlmp

Followup: MachineOwner
---------

A: For some reason, the problem disappeared without I have really done something.
The problem that I had here has been reported as a VirtualBox bug: https://www.virtualbox.org/ticket/11730
It is currently not yet fixed. I've posted my dump output there, it could be helpful.


text:
Q: Установка cookie и скрытие блока Нужно поставить cookie и скрыть блок:
HTML:
контент

JS:
function hidetask(id) {
    var ws = new Date();
    ws.setDate(30 + ws.getDate());
    document.cookie = "hide_" + id + "=ok; path=/; expires=" + ws.toGMTString();
    var tohide = document.getElementById(id);
    tohide.style.display = "none";
    alert('ok');
};

Всё работает, но не скрывается. с jQuery:
function hidetask(id) {
    var ws = new Date();
    ws.setDate(30 + ws.getDate());
    document.cookie = "hide_" + id + "=ok; path=/; expires=" + ws.toGMTString();
    $("#" + id).hide();
    alert('ok');
};

То же самое. В чем ошибка?


text:
Q: Material Table refreshes instead of appending onRowAdd I have used the material-table from Material UI for React. When the data is passed statically, it displays row by row but when I bring data from a web service, already added row updates instead of appending a new row. Please help.
const [state, setState] = useState({
columns: [
  { title: 'S.No', field: 'Id', type: 'numeric', editable: 'never' },
  { title: 'Roll Number', field: 'Studentid' },
  { title: 'Name', field: 'Name', editable: 'never' },
  { title: 'Year', field: 'Year', editable: 'never' },
  { title: 'Department', field: 'DeptName', editable: 'never'},
],
data: eventRegistrationStudentsList,
});

  <MaterialTable
    style={{ maxWidth: "95%" }}
    title="Student Details"
    id="studentDetailsTable"
    columns={state.columns}
    data={eventRegistrationStudentsList}
    editable={{
      onRowAdd: newData =>
        new Promise(resolve => {
              const data = [...state.data];
              data.push(newData);
              setState({ ...state, data });
              handleStudentIdChange(newData.Studentid);
              resolve();
        }),
      onRowDelete: oldData =>
        new Promise(resolve => {
          setTimeout(() => {
            resolve();
            const data = [...state.data];
            data.splice(data.indexOf(oldData), 1);
            setState({ ...state, data });
          }, 600);
        }),
    }}
    options={{
      search: false,
      actionsColumnIndex: -1
    }}
  />

eventRegistrationStudentsList holds:
[ DeptName: "AERONAUTICAL ENGINEERING",
Id: 1,
Name: "Jon",
Studentid: "190AE101",
Year: "III" ]

A: The problem lies here
data={eventRegistrationStudentsList}

You are updating the list in the state, but not using the list from the state
data={state.data}

here.


text:
Q: Read bluetooth device rssi without connected them starscan() issue I read this Issue.
I want to make one sample app to read the all BLE device rssi near of my application range without connecting them.
I create STICKY service & access near device scan result.
BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(SmartIDService.this.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();

//Start Scan.
mBluetoothAdapter.startLeScan(mLeScanCallback);

//Listen scan Resul.
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback()
    {

        @Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord)
        {
            AppLogger.showDebugLog(TAG + "rssi: " +rssi);

        }
    };

I got the result as I want,but if BLE device out of range for some time I can't get the result again.
I think that startLeScan() is remove from memory, so I create One alarm service to wakt up mBluetoothAdapter.startLeScan(mLeScanCallback);
some time interval & issue is resolved.
But I can't find the actual time interval that I will wake up alaram service.
any solution !!!
idea time interval for every device?
Any other process?
please guide me


text:
Q: Print image in actual size I want to print an image in it's actual size.
It is from a print screen from the internet.
Is there a way to print actual size?

A: Unless the image is a scan[1], there is no "actual" size, there is at best an intended print size. Your image has a size in pixels, and its print size depends on the ratio of pixels per unit of length, usually expressed as pixels per inch or PPI[2]. This ratio is called the print definition, and it kept as image metadata. In Gimp you can set it in Image>Print size, but keep in mind that a low print definition corresponds to low image quality, if there is text you should use at least 150PPI.
If by "actual size" you mean the size on your screen, then it's not the actual size but Gimp using the print definition of your screen (usually around 100-120PPI, unless you have a high def display) because Gimp displays the image "dot-for-dot" (one pixel of the image is mapped to exactly on pixel of the display). To make the image on your screen the same physical size as in print:

*

*make sure Gimp has a good estimate of your screen definition: Edit>Preferences>Display>Monitor resolution

*tell Gimp to not use "dot-for-dot": uncheck View>Dot for dot
Some more warnings:

*

*the default print definition is usually 72PPI (perhaps because it was the display definition of most CRT displays).

*The printer usually requires a print definition higher than your display, so unless you check the above the printed image will likely look smaller that the one on the screen.

[1] if the image is a scan, the scanner software has set the proper print definition in the image metadata.
[2] dots per inch, or DPI, is also used but this is misleading since inkjet printers use several dots of color to make a single color pixel.

A: Starting with banana.png
Using lp, assuming imageMagick installed
list your printer options with
terminal-where-image-is$ lpstat -p -d
set printer with
terminal-where-image-is$ lpoptions -d printer_name
set PPI (pixels per inch) equal to the actual image property PPI
terminal-where-image-is$ ppi=$(identify -format "%x" banana.png)
now to print as actual size (from PPI setting)
terminal-where-image-is$ lp -o ppi=$ppi banana.png


text:
Q: Create a site using Netlify CLI I want to create a site during my Azure CI using the Netlify CLI. I have it installed locally for now for testing.
When I run netlify sites:create I get a prompt asking me for a name, then I have to select the right team. I found there's a name parameter to initiate a site with a certain name:
netlify sites:create --name anewdeployment but the CLI still requests my Team name.
Also when I first used it I had to give access to the CLI in a browser prompt and I can't do that when I implement this on the Azure devops release pipeline.
So is the only way to achieve this through the Azure api?

A: I think you need the netlify init --manual option from the CLI, see here (I recommend the --manual flag). This way you can use Netlify for Continuous Deployment.

A:
Create a site using Netlify CLI

I think what you know so far is almost correct.
We could not use Netlify task to create a site on the Azure devops release pipeline. That because that extension currently supports two tasks:

*

*Install netlify-cli

*Deploy static website to Netlify
So, we could not use this extension to create a site.
You could check this document Deploying a site to Netlify with Azure DevOps for some more details.
To create a site, we could use the Netlify API to implement it:
Refer to this blog How to deploy a simple site using Postman and the Netlify API.
We could use create a site with Netlify API on the Azure devops release pipeline.


text:
Q: Google Maps street view slow performance on IE8 We are embedding a Google Maps street view in our OpenLayers / ExtJS application. For all the browsers, it seems quite fast, except for IE8, specially in slower workstations, where it gets slow and the panning is not smooth at all.
So, using IE8, we go to maps.google.com , ask for a street view, it works fine. Same machine, IE8, go to our ExtJS application and ask for a street view, it is not that smooth, much slower. Same machine, Firefox (or even IE9), it is smooth enough.
Some thoughts :

*

*Having a look with Firebug and Fiddler it seems that the images are properly cached. So it doesn't seem that we are asking for too many requests. I mean, panning is still slow even if we don't perform any image request at all.

*maps.google.com does not need to authenticate as our app does, but for the previous reason, I would not think that is the problem.

*It is slow no matter we remove additional markers or the map including the pegman besides.

*This happens even if the window size is not too big. That is, smaller than the window we use for testing with maps.google.com

*I can see a CPU usage when panning of roughly 30% using street view in our application and 15% with maps.google.com

The code we use is not very different from the example :
https://developers.google.com/maps/documentation/javascript/examples/streetview-simple
Any idea will be appreciated. Thanks.
Update. To simplify the problem, I tried getting rid of ExtJS. So I just open another window with the simple HTML below. Even that way, its performance is worse than just going to maps.google.com .
<meta charset='utf-8'><title>Street View controls</title>
</div


text:
Q: Find a geometric description of $y=y_0$ under the mapping $w=1/z$ I am given $y_0\neq 0$ and $$\left\{u+iv=\frac{1}{x+iy_0}:x\epsilon R\right\}$$
I'm asked to find a geometric description of this. I notice that $w=\frac{1}{z}$ so $z=\frac{1}{w}$ and if $z=x+iy$ and $w=u+iv$ then $u=\frac{x}{x^2+y^2}$, $v=\frac{-y}{x^2+y^2}$ and on the reverse we have $x=\frac{u}{u^2+v^2}$ and $y=\frac{-v}{u^2+v^2}$
From here I'm pretty much stuck. I know $y=y_0$ so $\frac{-v}{u^2+v^2}=y_0$ but I have no idea if this helps me

A: Given $y_0 \in \Bbb{R}$, let $z=x+iy_0$, then we have
$$v=\frac{-y_0}{|z|^2}$$
We also have $|w|\,|z|=1$. Thus $\frac{1}{|z|^2}=u^2+v^2$. Using this in the second equation given above, we get (which is also what you have stated as one of your derivations)
$$v=-y_0(u^2+v^2) \implies y_0u^2+y_0v^2+v=0$$
Since $y_0 \neq 0$, then we can write this as
$$u^2+\left(v+\frac{1}{2y_0}\right)^2=\frac{1}{4y_0^2}.$$
This is a circle with center at $\left(0,\frac{-1}{2y_0}\right)$ and radius $\frac{1}{2y_0}$.


text:
Q: How to force a user to choose a  option with bootstrap I've been trying to work the answer out to this for hours and it's driving me insane!
I'm using Twitter Bootstrap and bootstrap-min.js.
Here is my code:
<select id="assettype" name="assettype" class="input-medium required">
   <option>-- Please select --</option>
   <option value="1">Printer</option>
   <option value="2">Scanner</option>
</select>

If a user leaves the form as the '-- Please select --' option then I want an error to prevent the user from submitting the form i.e. forcing them to make a selection.
Any help would be massively appreciated! Thanks in advance.

A: Use event.preventDefault()
$('#formId').submit(function (e) {
    if ($('#assettype').val() == '') {
    e.preventDefault(); //stop form submission
}
});

or

Using jQuery Validator
$.validator.addMethod('notNone', function (value, element) {
    return (value != '');
}, 'Please select an option');
$("form").validate({
    rules: {
        assettype: {
            required: true,
            notNone: true
        }
    }
});

A: This seems you need a simple validation before submitting like
$('#formId').submit(function () {
 if ($('#assettype').val() != '')) {  //Check the value of select
    return true; //allow to submit the form
 }
 else {
    alert("Please select an option");
    return false;  //Prevent form being submitted
 }
});

A: <form id="my_form" method="POST" action="" >
<select id="assettype" name="assettype" class="input-medium required">
  <option value="0" >-- Please select --</option>
  <option value="1">Printer</option>
  <option value="2">Scanner</option>
</select>
</form>
<script type="text/javascript">
  $("#my_form").submit(
    var check_value = $("#assettype").val();
    if (check_value == 0)
    {
      e.preventDefault();
      // prevent the user he has to choose something
      // by an alert for example, or background change of the element
      $("#assettype").css("background-color", "red");
      return false;
    }
    else
    {
      // and restore it if it's ok
      $("#assettype").css("background-color", "inherit");
    }
    return true;
  });
</script>


text:
Q: Item is created twice in dB Explanation
It is a form with many V-Radio-Button that are loaded from the database (optionsDB)
options in db:  [{ID: 21, Name: "Cellphones"}, {ID: 32, Name: "Computer",}]].

Then the loading component some options from the database that the user may have previously configured, or may not load anything (OrginalOptions)
 orginalOptions: [{ID: 1, Inventory_Id: 21, Quantity: 32, Status: 1}, {ID: 2, Inventory_ID: 21, Quantity: 32, Status: 1}]

What I do is walk the arrangements to see if the user made a change in any option, checking first if he has inventory_id to send the data to another function that edits the item. So far the program works well.
From here ELSE:
   } else {
            if ((allOptions[indexOpcionesTablas].state ....

Then this is the ELSE, which is for the new items that are configured on the Web and therefore do not have a service assigned from the dB and are not in OrginalOptions [], only exist in AllOps [].
AllOps [] Automatically configures and the status or quantity fields are created depending on what the user modifies (here all well)
 allOptions item changed:  [{ID: 37, Name: "itemx", Quantity: 50}]

What I try to do in This step is to check the changes is the variables "Quantity" and "State" for this way send the data to the DB and create them. (This would put the item in orginalopions [])
The problem in all this is that the item is created twice in the database
 alloption[] a future..
 [{ID: 3, Inventory_Id: 37, status: 1, Quantity: 50}]
 [{ID: 4, Inventory_Id: 37, status: 1, Quantity: 50}]

I think the problem is for the for-in loops.
The program does not have how to check if item was already added ..
Thanks.
    async saveInventarioItemsUser () {
          let self = this
          let itemsToDb = []
          let allOptions = self.items_config_inventario
          let orginalOptions = self.items_config_inventario_original
          for (let indexOpcionesUsuarioOriginal in orginalOptions) {
            for (let indexOpcionesTablas in allOptions) {
              if (allOptions[indexOpcionesTablas].inventario) {
                if (orginalOptions[indexOpcionesUsuarioOriginal].inventario === allOptions[indexOpcionesTablas].inventario) {
                  if (allOptions[indexOpcionesTablas].cantidad !== orginalOptions[indexOpcionesUsuarioOriginal].cantidad || allOptions[indexOpcionesTablas].state !== orginalOptions[indexOpcionesUsuarioOriginal].state) {
                    let inventario = {
                      orden_trabajo: self.$route.params.editar,
                      inventario: allOptions[indexOpcionesTablas].inventario,
                      cantidad: allOptions[indexOpcionesTablas].cantidad,
                      state: allOptions[indexOpcionesTablas].state
                    }
                    self.saveIndividualItemInventario(allOptions[indexOpcionesTablas].id, inventario)
                  }
                } else {
                  console.log('No coincide con .inventario_id', allOptions[indexOpcionesTablas])
                }
              } else {
                if ((allOptions[indexOpcionesTablas].state !== 0 && allOptions[indexOpcionesTablas].state > 0) || allOptions[indexOpcionesTablas].cantidad >= 1) {
                  console.log('ITEM SIN INVENTARIO, CREAR')
                  console.log('ITEM SIN INVENTARIO, CREAR', allOptions[indexOpcionesTablas])
                  if (itemsToDb.length > 0) {
                    itemsToDb.map(item => {
                      if (item.id === allOptions[indexOpcionesTablas].id) {
                        console.log('ITEM EN ARRAY', allOptions[indexOpcionesTablas])
                        let data = {
                          orden_trabajo: self.$route.params.editar,
                          inventario: allOptions[indexOpcionesTablas].id,
                          cantidad: allOptions[indexOpcionesTablas].cantidad || 1,
                          state: allOptions[indexOpcionesTablas].state || 1
                        }
                        self.pushDBNewOpt(data)
                      } else {
                        console.log('PUSH ITEM')
                        itemsToDb.push(allOptions[indexOpcionesTablas])
                        console.log('PUSH ITEM', itemsToDb)
                      }
                    })
                  } else {
                    console.log('PUSH ITEM ELSE')
                    itemsToDb.push(allOptions[indexOpcionesTablas])
                  }
                }
              }
            }
          }
          itemsToDb = []
        }

pushDBNewOpt
async pushDBNewOpt (data) {
  let self = this
  await self._create(`endpoint/item/`, data, (response) => {
    console.log('RESP saveInventarioItemsUser', response)
    self.loadInventarioItemsUser()
  })
},


text:
Q: Why do voltage vary in series and not in parallel My question is kind of old and asked but I still didn't get the answers, if I don't consider the ohm's law or hydraulic analogy and answer this question solely by logic. Why should voltage differ in series and not in parallel with same resistors? The energy for charges to move through the resistors in both the orientation must have been same. Then why should there be a difference in voltage of both the cases?

A: In comments, you clarified your question as,

If I have a set of resistors and I arrange all of them in parallel then, why should the voltage be same for each of them?

If you have resistors connected in parallel, you can say they are all connected between some point "a" and another point "b".
And the potential difference between two points is defined (when it can be defined) as
$$V_b-V_a = V_{ba}=-\int_a^b \vec{E}\cdot d\vec\ell$$
Because of the assumptions we made in assuming we're working with a lumped circuit (no changing magnetic field through our circuit and all dimensions in the circuit much shorter than the wavelengths associated with the highest frequency signals in our circuit), we've assured that the voltage is a defined quantity, and that this integral will have the same value regardless of which path we follow between a and b in calculating the integral.
And therefore the voltage across all the resistors in the parallel combination must be the same.

A: When resistors are in parallel, each is subject to the voltage from the source.  When in series the voltage steps down from one to the next, so the each feels only a fraction of the voltage from the source.


text:
Q: how to connect EC2 and mysql RDS Gurus,
I am very new to AWS and all its services, I would like to know the best way to connect EC2 and RDS so they can talk to each other, while EC2 is on Public subnet and RDS is on a private subnet.
Thanks, gurus

A: Everything in a VPC can "talk to" everything else in the VPC, regardless of public versus private subnets. You just need to edit the security group assigned to the RDS instance to allow connections from the security group assigned to the EC2 instance.