text:
Q: Angular material dialog pre-populated input field does not validate I have a mat-dialog that opens from an edit button in a (mat-)table.
When the dialog opens it gets passed data to populate some input fields.
One of those inputs has validation with the rule that it cannot be empty.
My problem is that the input element that receives an auto-populated value is not recognized by Angular as having a value at all (it has a 'value' in the web-inspector and on the screen).
This means that until the user edits the field either by deleting and reentering a character or typing something new, the 'save' button remains greyed-out. Not al fields need to be edited, if they receive a value it is a valid one.
So how can I get the validation to recognize that the input field is not empty but also that it does have a value? (The reason I can't just remove the validation, it has to have a value, ie != '').
So unless the user input is empty to start with or the user deletes the input, the validation should pass. Or to say it another way, if the input receives a value when the dialog opens, and the user leaves it well alone, the validation should pass.
A side effect of the auto-populated values not being recognized is that if a number is unchanged then it gets posted as null to the backend. So when the data is refreshed in the view, a number that was 30 and not edited by the user is now 0. This, because the form is displaying the auto-populated data, but somehow angular isn't "seeing" it.
simple input:

    <mat-form-field>
      <input matInput #input
             class="form-control"
             placeholder="Name"
             [(ngModel)]="data.name"
             name="name"
             selected="data.name"
             required
             [value]="this.getFunc?.name"
      >
      <mat-error *ngIf="data.name == ''">{{getErrorMessage()}}</mat-error>
    </mat-form-field>

Not sure what to show from the component.ts files here(?!)
Using dialogRef.componentInstance = foo.bar; in the parent component, the dialog gets it's correct values in the input fields and IF the user deletes and then retypes a value, the correct value is sent back via the API.
The issue is that angular can't 'see' the input.
Tried a lot of different stuff, including every other answer on SO/here.
Sorry long text and little code, but there isn't anything to show how angular doesn't recognize that the input field holds a value.

A: I searched long and hard for an answer to this problem, and I think I have the "correct" way to it (one of them at least). So I'll post it here:
First, I changed my form to use 'formGroup' in the form element like so:
<form class="mat-dialog-content" (ngSubmit)="submit()" #formControl="ngForm" [formGroup]="patchForm">

        <mat-form-field>
          <input matInput #input
                 class="form-control"
                 placeholder="name"
                 name="name"
                 formControlName="name"
                 id="name"
                 selected="data.name"
                 required
          >
          <mat-error *ngIf="data.name== ''">{{getErrorMessage()}}</mat-error>
        </mat-form-field>

      [... repeat div class="form" blocks for other inputs/dropdowns etc ...]

Notice that I had to remove [(ngModel)]="someVal" from all the form field elements. Angular throws a wobbly if you try to use them with formGroup.
Now add the element attribute formControlName="name" you see in the code above.
I then had to add to app.module.ts ReactiveFormsModule:
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

and also add this to the imports array of that same file:
 imports: [
    BrowserModule,
    ...
    FormsModule,
    ReactiveFormsModule
  ],

In the component.ts file I set up the [formGroup]="patchForm" according to the documentation here https://angular.io/api/forms/FormGroup#setvalue
I have 3 fields in my dialog:
  patchForm = new FormGroup({
    age: new FormControl(),
    name: new FormControl(),
    numberLegs: new FormControl()
  });

So, the formControl expects an object correspondng to the form. In my onInit function i have a call to the API to get the data I want to populate the form with, and so inside that subscriber I am using patchValue() method from Angular to set the values:
this.projectService.getProjectFunction(this.projId, this.rowId).subscribe(x=> {
  this.fetchedProjFunc = x;
  // patchFrom expects an object matching to the formgroup, field by field.
  this.patchForm.patchValue({
    age: this.fetchedProjFunc['age'],
    name: this.fetchedProjFunc['name'],
    numberLegs: this.fetchedProjFunc['numberLegs']
   });
});

That seemed to work. Then I had to set the valules of the object I was returning to the API/database in my return object to point to the correct values, so when the user clicks the button "save" it calls a 'confirmPut' function that contains the object data to be sent, like so:
 public confirmPut(): void {
    this.projectFunction = {
        ...
        name: this.patchForm.value['name'],
        ...

which in turn calls the function that does the PUT to the API.
I think that was it, the form validates against empty strings and missing values as expected.
If I have missed anything and anyone ever reads this, let me know... :)


text:
Q: Java client socket reading get timeout Acctually developed web application that consumes remote API via socket. This API returns a string response my problem is that on same response getting success message and timeout message error when reading data.
The server is configured to 10000 seconds and throw timeout message. I have no idea about code from server I develop just client for consume it.
Below is my code to reading data from socket response.
this service method:
public String activateSale(final OSBDTO osbDto) throws Exception {

    Socket conn = socketConfig(HOST, PORT);
    BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());
    this.repository.sendDataSocket(MessageUtil.mountAuthenticationMsg(osbDto), conn, bos);

    BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
    String receivedData = this.repository.readMessage(conn, bis, bos);
    closeConnection(conn);

    if (OsbUtils.getStatusCodeMsg(receivedData).equals(MessageStatusEnum.SUCCESS.getStatusCode())) {

        conn = socketConfig(HOST, PORT);

        bos = new BufferedOutputStream(conn.getOutputStream());
        this.repository.sendDataSocket(MessageUtil.mountConfigurationSeriesMsg(osbDto), conn, bos);

        bis = new BufferedInputStream(conn.getInputStream());
        receivedData = this.repository.readMessage(conn, bis, bos);
        closeConnection(conn);

    } else {

        throw new Exception(MessageStatusEnum.getStatusDesc(OsbUtils.getStatusCodeMsg(receivedData)));
    }

    return receivedData;
}

This send and read methods:
@Override
public void sendDataSocket(final String msg, final Socket conn, final BufferedOutputStream bos) throws Exception {

    try {

        bos.write(msg.getBytes());
        bos.flush();

    } catch (Exception e) {
        LOGGER.error("Error to send message." + e.getMessage());
        throw e;
    }

}

@Override
public String readMessage(final Socket conn, final BufferedInputStream bis, final BufferedOutputStream bos) throws IOException {

    byte[] bufferSize = new byte[1024 * 1024];
    int data ;
    StringBuilder builder = new StringBuilder();
    while ((data = bis.read(bufferSize)) != -1) {
        builder.append(new String(bufferSize, 0, data));
    }
    bis.close();
    bos.close();
    return builder.toString();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: style.css is not loaded in other template files than index.php (eg. front-page.php) I am a Wordpress newbie who just started to go through this tutorial: https://developer.wordpress.org/themes/basics/including-css-javascript/#stylesheets
So i created a new theme and activated it.
Theme structure is a basic one:
elitetheme
 -> front-page.php
 -> index.php
 -> style.css

Whatever i write in style.css is shown in my front page if i don't have the front-page.php in my project (so if it picks just index.php)
If i do have front-page.php no style is shown.
I tried to write
<?php
wp_enqueue_style('style', get_stylesheet_uri() );
?>

in front-page.php
I also tried to create functions.php and wrote
<?php
function elitetheme_enqueue_style() {
    wp_enqueue_style( 'style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'elitetheme_enqueue_style' );
?>

Still no style on my front page and it don't understand what i'm doing wrong since i just followed the documentation.
Would appreciate some help.


text:
Q: java:variable initialisation i'm trying to create a class that contains functions that login and logout from the server, the ip address of the server is defined in a static way in the beginning of the function, like this:
private static String loginURL = "http://192.168.1.5/android_login_api/"

I would like to know the best to initialize the loginURL dependending of a condition.
For example:
if(this.isConnectedToServer("192.168.1.5", 500)) {
    private static String loginURL = "http://192.168.1.5/android_login_api/";
}

if(this.isConnectedToServer("192.168.1.9", 500)) {
    private static String loginURL = "http://192.168.1.9/android_login_api/";
}

I thought of passing the loginURL as a parameter to every function of this class then when i call them i use this condition to define the ip address but i think it's too silly.
here is my class:
public class UserFunctions {

private JSONParser jsonParser;

private static String loginURL = "http://192.168.1.5/android_login_api/";
private static String mplayerURL = "http://192.168.1.5/android_mplayer_api/";
private static String registerURL = "http://192.168.1.5/android_login_api/";

private static String login_tag = "login";
private static String register_tag = "register";
private static String delete_tag = "delete";
private static String update_tag = "update";
private static String music_tag = "music";
private static String getusers_tag = "getusers";

// constructor
public UserFunctions(){
    jsonParser = new JSONParser();
}

/**
 * function make Login Request
 * @param email
 * @param password
 * */
public JSONObject loginUser(String email, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    Log.i("JSON", json.toString());
    return json;
}
public JSONObject deleteUser(String email){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", delete_tag));
    params.add(new BasicNameValuePair("email", email));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    Log.i("JSON", json.toString());
    return json;
}

public JSONObject updateUser(String email, String field, String value){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", update_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("field", field));
    params.add(new BasicNameValuePair("value", value));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    Log.i("JSON", json.toString());
    return json;
}

public boolean isConnectedToServer(String url, int timeout) {
    try{
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();
        connection.setConnectTimeout(timeout);
        connection.connect();
        return true;
    } catch (Exception e) {
        // Handle your exceptions
        return false;
    }
}

/**
 * function make Login Request
 * @param name
 * @param email
 * @param password
 * */
public JSONObject registerUser(String name, String email, String mode, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("name", name));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("mode", mode));
    params.add(new BasicNameValuePair("password", password));

    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
    // return json
    return json;
}

    public JSONObject PlayMusic(String name){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", "play"));
    params.add(new BasicNameValuePair("name", name));
    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(mplayerURL, params);
    // return json
    return json;
}

public JSONObject ChangeVol(String volume){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", "volume"));
    params.add(new BasicNameValuePair("volume", volume));
    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(mplayerURL, params);
    // return json
    return json;
}

public JSONObject StopMusic(){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", "stop"));
    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(mplayerURL, params);
    // return json
    return json;
}

public JSONObject ParcourirMusic(){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", "parcourir"));
    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(mplayerURL, params);
    // return json
    return json;
}

/**
 * Function get Login status
 * */
public boolean isUserLoggedIn(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    int count = db.getRowCount();
    if(count > 0){
        // user logged in
        return true;
    }
    return false;
}

/**
 * Function to logout user
 * Reset Database
 * */
public boolean logoutUser(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    db.resetTables();
    return true;
}

public void ReadMail(){

try{
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "rami.mtiri@gmail.com", "pass");
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);

SearchTerm term = new SearchTerm() {
  @Override
  public boolean match(Message mess) {
    try {
      return mess.getContent().toString().toLowerCase().indexOf("boston") != -1;
    } catch (IOException ex) {
     // Logger.getLogger(JavaMailTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MessagingException ex) {
     // Logger.getLogger(JavaMailTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
  }
};

Message[] searchResults = inbox.search(term);
for(Message m:searchResults){
    Log.e("mail",m.getFrom()[0].toString() );
  System.out.println("MATCHED: " + m.getFrom()[0]);

}
} catch (Exception e) {

}

}

}

please can anyone give me a full solution using my code UP, i'm new in java dont care if the the function or the variavble is static or not , all i want is to initalize the ip address by condition. i call the functions of this class in evry other class so it will be rude to do tests in evry class. im keeping that as a last resort

A: This
if(this.isConnectedToServer("192.168.1.5", 500))
{
    private static String loginURL = "http://192.168.1.5/android_login_api/";
}
if(this.isConnectedToServer("192.168.1.9", 500))
{
    private static String loginURL = "http://192.168.1.9/android_login_api/";
}

Is not valid java code, assuming that the above statements lie within the declaration of a class (the usage of the private static modifiers require this to be the case).
Fields cannot be conditionally declared. If fact, most statements (if, while, for, so on) are illegal outside of functions. The only thing you can do statically within the class body is to declare the field and give it an initialization value.
private static String loginURL; //no initialization yet as you don't have an instance to call isConnectedToServer() on

Now, it is very difficult to solve your problem because as Adrian pointed out, you are trying to use a non-static method (isConnectedToServer()) to determine static behavior (the value of loginURL). This doesn't make sense. You must either you make loginURL non-static or make isConnectedToServer() static.
You probably want the first the first option.
Due to the nature of your initialization conditions it would easier to initialize loginURL in a a constructor, which would be almost exactly the same as initializing it statically. Here would be a skeleton example of such a setup:
class Example
{
     private String loginURL; //non-static, no initialization

     public Example()//construcutor
     {
           //run conditions normally
           if(this.isConnectedToServer("192.168.1.5", 500))
           {
                loginURL = "http://192.168.1.5/android_login_api/";
           }
           //you might want to use else if here
           if(this.isConnectedToServer("192.168.1.9", 500))
           {
                loginURL = "http://192.168.1.9/android_login_api/";
           }
           //if neither if starement executes, loginURL is null.
     }
}

If you do want the functionality to be static for whatever reason, move the initialization code to a static block:
class StaticExample
{
     private static String loginURL;

     //isConnectedToServer must be declared static in order for this to work!
     //I believe your current function can be made static without changing its code
     public static boolean isConnectedToServer()
     {
        ...
     }

     static
     {
           if(isConnectedToServer("192.168.1.5", 500))
           {
                loginURL = "http://192.168.1.5/android_login_api/";
           }
           //you might want to use else if here
           if(isConnectedToServer("192.168.1.9", 500))
           {
                loginURL = "http://192.168.1.9/android_login_api/";
           }
           //if neither if starement executes, loginURL is null.
     }

A: all i had to do is to initialize the var in the constructor this way:
private JSONParser jsonParser;

private static String loginURL = "/android_login_api/";
private static String mplayerURL = "/android_mplayer_api/";
private static String registerURL = "/android_login_api/";
public String ip;
private static String login_tag = "login";
private static String register_tag = "register";
private static String delete_tag = "delete";
private static String update_tag = "update";
private static String music_tag = "music";
private static String getusers_tag = "getusers";

// constructor
public UserFunctions(){
    jsonParser = new JSONParser();
    if(isConnectedToServer("192.168.1.5", 500)==false)
    {
        if(isConnectedToServer("www.google.com", 500)==true)
        {
            ReadEmails re = new ReadEmails();
            ip=re.processMail();
        }else{
            ip="192.168.1.5";
        }
    }else{
        ip="192.168.1.5";
    }
}


text:
Q: How to slice ArrayIterator into two? I've got this code
$second_half = $items; //ArrayIterator Object;
$first_half = array_slice($second_half ,0,ceil(count($second_half)/2));

This gives the warning Warning: array_slice() expects parameter 1 to be array, object given
Is there a way to slice an ArrayIterator object in two?
Basically I want one half of the unknown amount of items stored in $first_half and the remaining items $second_half; the result would be two ArrayIterator objects with two different sets of items.

A: It would appear you can use the getArrayCopy method of the ArrayIterator. This will return an array that you can then manipulate.
As for assigning one half of the results to a new ArrayIterator, and the other half to another ArrayIterator, you wouldn't need to reduce it to an array. You could simply use the count and append methods of the Iterator itself:
$group = new ArrayIterator;
$partA = new ArrayIterator;
$partB = new ArrayIterator;

$group->append( "Foo" );
$group->append( "Bar" );
$group->append( "Fiz" );
$group->append( "Buz" );
$group->append( "Tim" );

foreach ( $group as $key => $value ) {
  ( $key < ( $group->count() / 2 ) )
    ? $partA->append( $value )
    : $partB->append( $value );
}

This results in two new ArrayIterator's being constructed:
ArrayIterator Object ( $partA )
(
    [0] => Foo
    [1] => Bar
    [2] => Fiz
)
ArrayIterator Object ( $partB )
(
    [0] => Buz
    [1] => Tim
)

Modify the ternary condition as needed.

A: $first_half = new LimitIterator($items, 0, ceil(count($items) / 2));
$second_half = new LimitIterator($items, iterator_count($first_half));

This will get you 2 iterator which will allow you to only iterate over a half of the original $items.


text:
Q: Weird behaviour when trying to estimate an unknown variable I'm trying to estimate an unknown variable (p) with a very high precision. What I have is a large number of ordered values (I call them t-values). Each value has a sequence number (n). Each of those t-values is basically the result of multiplying n with p and then adding a random offset ("noise"). My idea is to simply order the t-values according to their sequence number and then take the mean of all the offsets. It works very well. Here are 10 examples of estimates (true p is 1.0 and the number of t-values is 100000):
1.0000737485173519
0.9999987583319258
1.0000688058361697
1.0002021529901506
0.9999391175701831
1.000012370796987
0.9999891218161053
1.0001566049086157
0.9999818309412788
0.9999594118399372

Close enough for what I want.
But in practice, a certain amount of t-values will also be lost. If I introduce a random loss of t-values the precision goes down dramatically, even if the number of lost t-values is as low as 0.001% - 0.01% and, this is the weird part, even if I compensate by generating more t-values so the number of t-values used in calculating the mean is the same!
Here are 10 examples when about 1% of the values were dropped:
1.0024257205135292
1.0019969333070318
1.0019520792036436
1.001061555944925
0.997728342781954
1.000205614588305
0.9964173869854615
1.0028314864552466
1.0014389330965119
0.9954499027939065

Why is this?
I have made a simulation in Python to demonstrate. To see the difference, first run it as is. Then change drop_probability to 0.01 and run again.
Python:
#!/usr/bin/python3
import random

random.seed(42)

runs = 10
effective_number_of_values = 100000

real_period=1
static_offset=0.5
lambd=0.2

drop_probability=0.00000001
#drop_probability=0.0001
#drop_probability=0.001
#drop_probability=0.01
#drop_probability=0.1
#drop_probability=0.5

for run in range(0, runs):
    values = []
    dropped_ts = 0

    last_was_dropped = False
    num_values = 0
    n = 1
    t = 0
    while num_values < effective_number_of_values + 1:

        actual_t = t
        noise = static_offset + random.expovariate(lambd)
        effective_t = actual_t + noise

        if drop_probability is not None and \
            random.random() <= drop_probability:

            values.append((n, effective_t, True))
            dropped_ts += 1
            last_was_dropped = True
        else:
            values.append((n, effective_t, False))
            if not last_was_dropped:
                num_values += 1
            last_was_dropped = False

        t += real_period
        n += 1

    values.sort()

    last_n = 0
    last_t = 0
    last_was_dropped = False
    avg_sum = 0
    avg_n = 0
    for v in values:
            n, t, dropped = v

            if n > 1:
                    if not dropped and not last_was_dropped:
                        avg_sum += t - last_t
                        avg_n += 1

            last_t = t
            last_n = n
            last_was_dropped = dropped

    print(avg_sum / avg_n, "(values used: %d, dropped along the way: %.2f%% (%d))" % (avg_n, (dropped_ts/len(values))*100, dropped_ts))
                         <br>

A: Your problem is due to the nature of your sampling. As you increase the percentage chance of dropping values, the overall percentage of dropped values will increase exponentially and will drastically reduce your accuracy and precision.
Needless to say, such a significant change in the sampling population causes your measurements to become exponentially more imprecise as the percentage of lost samples increases. As you increase the population, this problem becomes less apparent. If you expect more values to be dropped, take a much larger sample. If your means of sampling is so inaccurate that it loses more than ~10% of samples, then you must either rectify this problem which causes reduced accuracy by dropping less samples, taking significantly more, or reconsidering whether you need less than 1% variance in your estimations.
Much of this is rooted in statistical theory. A cursory study of probabilities and random sampling will yield many helpful equations and rules of thumb to help ensure accurate estimates of unknown parameters.
The primary equation you'll need to use for this purpose is the one calculating the Margin of Error for a Normal Distribution to represent your sampling method: ME = z * sqrt( (p_hat * q_hat) / n).
You will also need the Margin of Error for a Poisson distribution to represent the error introduced by the noise: the formula, given large values of n*lambd is ME = z * sqrt( lambd / n ). You'll need to include this value in your total error after sampling, and with 95% confidence, 10,000 samples, and lambd of 0.2, you find that it goes as high as 0.45%, explaining a large proportion of the unexpected error.
However, this method of determining margin for error of the Poisson distribution is only a crude approximation that treats it as if it were a normal distribution. In your situation, with such a small lambd, you may wish to consider one of the 19 approximations contained within this paper.
In Summary
It does appear that you are correct about losing accuracy (assuming a normal distribution), however it may be due to the use of random.expovariate(lambd):

"Exponential distribution... Returned values range from 0 to positive infinity if lambd is positive."

Using a mean function will not yield a valid result because such a low value of u=0.2 for a Poisson distribution (basically what expovariate is) will be non-symmetrical, as is attested by W.R.Leo of CalTech:

Note that the distribution is not symmetric. The peak or maximum of the distribution does not, therefore, correspond to the mean. However, as µ becomes large, the distribution becomes more and more symmetric and approaches a Gaussian form.

A: Not sure I fully understand your question, but I'm trying to be helpful.
I do believe the result your seeing is to be expected. Suppose the drop rate increase such that in average every second measurement is dropped. The average difference between two consecutive remaining measurements will be twice the value it had been before. So the drop rate does affect the result. Similarly, If you drop just 10%, then the difference should increase by ~10%.
Here is the way I rewrote your code. In this version I always drop a fixed amount of measurements using the random.sample function.
import random

#random.seed(42)

effective_number_of_values = 100000

real_period = 1
static_offset = 0.5
lambd = 0.2

drop_probabilities = [0.00001, 0.001, 0.01, 0.1, 0.2, 0.3, 0.5, 0.9, 0.99]

values = []
t = 0
for drop_probability in drop_probabilities:
    desiredlen = round(effective_number_of_values * (1 + drop_probability))

    for t in range(desiredlen):
        noise = static_offset + random.expovariate(lambd)
        effective_t = t + noise
        values.append((t, effective_t))

    values_after_drop = random.sample(values, effective_number_of_values)
    values_after_drop.sort()

    diff_t = [values_after_drop[i][1] - values_after_drop[i-1][1]
              for i in range(1, len(values_after_drop))]

    avg = sum(diff_t)/len(diff_t)

    print("avg = {}. {} dropped out of {} at {} probability".
          format(avg, len(values) - effective_number_of_values,
                 len(values), drop_probability))

A: For completeness here is the actual problem I'm trying to solve:
Two computers are connected to the internet.
Computer A is sending a special kind of packets to computer B with a fixed interval (the packets are based on UDP). Computer B needs to estimate what this interval is with very high accuracy.
The packets have sequence numbers. Each packet will obviously be more or less delayed and some will be lost. Some will arrive in the wrong order.
So what computer B knows is this: the list of arrived packets with their sequence numbers and the time they arrived. From that I hoped it would be possible to estimate the interval with at least four decimals accuracy, with not more than around 10000 samples (since I want to account for small fluctuations in the clock of the computers during the day and a typical interval will be 1 second I dont want to use more than that). I hoped this would be possible even with a high rate of lost packets (for example 50%).


text:
Q: How can I save files from ftp? I have a methode that copy folder structure from ftp to local folder and then copy all files that consists in them:
public void CreateDirectories()
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Url);
    request.Credentials = new NetworkCredential(Login, Pass);
    request.Method = WebRequestMethods.Ftp.ListDirectory;

    string soursePath = @"L:\Test";

    StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());

    string directoryName = streamReader.ReadLine();

    while (directoryName != null)
    {
        //Create directories structure
        if (directoryName.StartsWith("I") && !directoryName.Contains("p"))
        {
            string newPath = System.IO.Path.Combine(soursePath, directoryName);
            if (!System.IO.Directory.Exists(newPath))
            {
                System.IO.Directory.CreateDirectory(newPath);

                //get file list and invoke DownLoad(string directoryName, string fileName)
                FtpWebRequest fileRequest = (FtpWebRequest)WebRequest.Create(Url + directoryName + "/");
                fileRequest.Credentials = new NetworkCredential(Login, Pass);
                fileRequest.Method = WebRequestMethods.Ftp.ListDirectory;

                StreamReader fileStreamReader = new StreamReader(fileRequest.GetResponse().GetResponseStream());
                string fileName = fileStreamReader.ReadLine();
                while (fileName != null)
                {
                    DownLoad(directoryName, fileName);
                    fileName = streamReader.ReadLine();
                }

            }
        }

        directoryName = streamReader.ReadLine();
    }

    request = null;
    streamReader = null;
}

and the methode that copy current file:
public void DownLoad(string directoryName, string fileName)
{
    string localPath = @"L:\Test\" + directoryName;

    FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create("ftp://ftp.equip.me/prod/" + directoryName + "/" + fileName);
    requestFileDownload.Credentials = new NetworkCredential(Login, Pass);
    requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;

    FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();

    Stream responseStream = responseFileDownload.GetResponseStream();
    FileStream writeStream = new FileStream(localPath + "\\" + fileName, FileMode.Create);

    int Length = 2048;
    Byte[] buffer = new Byte[Length];
    int bytesRead = responseStream.Read(buffer, 0, Length);

    while (bytesRead > 0)
    {
        writeStream.Write(buffer, 0, bytesRead);
        bytesRead = responseStream.Read(buffer, 0, Length);
    }

    responseStream.Close();
    writeStream.Close();

    requestFileDownload = null;
    responseFileDownload = null;
}

But in line   Stream responseStream = responseFileDownload.GetResponseStream(); it stop for nearly 40 seconds and then throw an exeption of timeout, and no one file has not been saved (file is small  - 50 kb)

A: The first thing that you should try is to turn passive mode off since this is automatically blocked by most firewalls, but is the default mode of operation for ftpWebRequest.
Just below this line:
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;

and this one:
requestFileDownload.UsePassive = false;


text:
Q: How to get a textarea's value and put it into another textarea using Javascript? I am trying to develop a url decoder using Javascript but my code won't work, can anyone tell me how to do it,thx
<textarea id="input"></textarea>

<button id="yes" align="center" onclick="getInput(document.getElementById('input')">Click to transfer</button>

The decoded URL:

<textarea id="decode"></textarea>

A: Assuming logic is correctly done in your original code.
Since it is a text area,you must use value
Try :
document.getElementById("decode").value = uri_decode;

More Properties at HERE

A: even though im still quite new to this, i think i found a few mistakes, im not sure if it will fix you're problem, but you should give it a try.
1.

i hope this works, if it doesn't then tell me.

A: In your else if, you didn't specify an if-statement.
Guess you meant else

A: My suggestion would be to use the jQuery Api.
Once you click a button you can pick it up using
$('#transfer').click(function() { }

Then simply collect the text from the first text box using
var url = $('#urlToDecode').val();

then write the 'url' variable into the second text box using
$("#decodedURL").val = url;

Hope that helps! :) Note: you will need to link to the jQuery API which is hosted by Google.


text:
Q: can graylog2 output to flat file and elasticsearch at the same time? I'm very new to graylog2. I finally have it up and running, storing logs to elasticsearch. My question is: can graylog2 also dump to flat file? if so can it dump log files to both flat file and elastic search simultaneously?  I can't seem to find the answer googling. If any log guru knows the answer, would u kindly point me to a right direction?
thank you!

A: you can send syslog messages to standard rsyslog port udp/514 and then from rsyslog to graylog2.
Rsyslog.conf

if $fromhost-ip == '10.10.205.1' then /var/log/hosts/host1.log
if $fromhost-ip == '10.10.205.1' then @0.0.0.0:515


text:
Q: How to set Akka actors run only for specific time period? I have a big task,which i break down into smaller task and analyse them. I have a basic model.
Master,worker and listener .
Master creates the tasks,give them to worker actors. Once an worker actor completes,it asks for another task from the master. Once all task is completed ,they inform the listener. They usually take around less than 2 minutes to complete 1000 tasks.
Now,Some time the time taken for some tasks might be more than others. I want to set timer for each task,and if a task takes more time,then worker task should be aborted by the master and the task has to be resubmitted later as new one. How to implement this? I can calculate the time taken by a worker task,but how Master actor keeps tab on time taken by all worker actors in real time?

A: One way of handling this would be for each worker, on receipt of a task to start on, sets a timeout before changing state to process the task, eg:
  context.setReceiveTimeout(5 minutes)  // for the '5 minutes' notation - import scala.concurrent.duration._

If the timeout is received, the worker can abort the task (or whatever other action you deem appropriate - eg. kill itself, or pass a notification message back to the master). Don't forget to cancel the timeout (set duration = Duration.Undefined) if the task is completed or the like.


text:
Q: Want 10 rows in every page while binding to a repeater I have a repeater which is bound to a data source having 500 rows.I don't want it for paging.
Simple when the rows are coming to repeater they grow down.So ,suppose i have  10 pages, each page having 50 rows in the browser print preview, when i am printing the document with ctrl+p command.
so,is there any way , so that my page will contain only 10 rows and with header and footer in every page.
Thanks
Manas

A: You can add inside the repeater an if, then, Write call, using also a public integer value from code behind, as:
public int ImetritisReapeter = 1;

and on the page:
<asp:Repeater ID="rMyID" runat="server">
  <ItemTemplate>
    <% if (ImetritisReapeter++ % 10 == 0) {
        Response.Write("<br>Extra header ever 10 lines");
    } %>
  </ItemTemplate>
</asp:Repeater>


text:
Q: Can EF Core map a GET (calculated) property? I have a model class that has an array of objects which I want to store in the database. In order to fit this data into a single row and column; I have a get property which concatenates the array and returns a single string. I want to store this concatenated string in the database.
[NotMapped]
public object[] Values { get; set; }

public string Value
{
    get
    {
        return string.Join("|", this.Values);
    }
}

I have confirmed that the Value property contains the string that I expect. However, this does not save to the database; it just saves it as NULL. I do not have any special mapping code in place; it is relying on the defaults of having the column name match the property name.
The closest thing I have found it this tutorial which describes using the HasField() method to map the column to a private field instead of a property; but in my case it's not just that I have a private set; it's that I don't have any set property at all.

A: Why don't you just do somethig like this?
private object[] values;

[NotMapped]
public object[] Values {
    get => values;
    set {
        if (value != values);
        values = value;
        Value = string.Join("|", value);
    }
}

public string Value { get; set; }

A: You can trick EF by doing something like this:
[NotMapped]
public object[] Values { get; set; }

public string Value
{
    get
    {
        return string.Join("|", this.Values);
    }
    set {}
}

Setter won't do anything, so you achieve what you want.

A: Another approach not to mix business and persistence structures.
Other parts of application should care/know how data is stored.
public class BusinessObject
{
    public object[] Values { get; set; }
}

public class ValuesEntity
{
    public static ValuesEntity From(BusinessObject object)
    {
        return new ValuesEntity { Values = string.Join("|", object.Values) };
    }

    public string Values { set; set; }

    public BusinessObject ToBusinessObject()
    {
        return new BusinessObject { Values = Values.Split("|") };
    }
}

With this approach you will explicitly "tell" other developers or reader of the code your intentions.
Working with different classes for each responsibility(business logic or persistence) will be simpler because both responsibilities are isolated from each other.

A: This seems to be a good use case for a value convertor.
You keep the array property mapped and supply a value convertor for it when you configure the EF model. The value convertor will dump all values in a single string when saving to the DB, and will split a string into array of values when reading from the DB. You can program any logic in it.


text:
Q: Implement security in an intranet application I have worked on a desktop application which I have created using the combination of WPF, WCF, EF 4 and SQL Seerver 2008 R2.
Now I have to prepare my software for security audit and I need to know what best I can do for ensuring security parameters in my application. Currently I'm using WCF Service authentication with Active Directory.
To my knowledge following things I can do to make my application more secure:

*

*Code Obfuscation -- to secure code base

*Can use TDE -- to secure the database and encrypt confidential tables.

*Can use SSL -- to secure communication channel (Any good article on this can helps a lot coz I didn't found any thing good which can explain like how to do this for intranet desktop application)

What else I can do to secure the application. I'm still not clear on how to secure the communication channel between client <--> Server and Server <--> database.
Any help will be greatly appreciated. Thanks..

A: Don't waste your time with obfuscation. Good security is transparent. Obfuscation is only useful for protecting intellectual property, and even then that's debatable.
Anyways, it sounds like you want to focus on a few things:

*

*Obtain an SSL server certificate for your application server and also for your SQL Server. If you don't want to spend the money on one, you can create your own PKI or self-signed certificate authority. I wouldn't recommend self-signed for production, and rolling your own PKI shouldn't be taken lightly, either.

*Use protocol encryption to secure the connection between your application and the SQL Server instance.

*Use binding that requires transport security to make your WCF communication use SSL. http://msdn.microsoft.com/en-us/library/ms734679.aspx
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/b361ee9e-2f37-4ecf-ba8b-96c6d6e6118a

*Audit your authentication routines. Are you hashing and salting passwords? Do you audit security events (login, logout, failed attempts)? Do you lock accounts after a certain number of failed attempts? So on and so forth. It would be helpful to work with whomever is auditing you to get a feel for what they will be looking for.


text:
Q: How to read the json config file inside angular module? I am writing the javascript, AngularJS app using typescript. Also I am using grunt for building. In fact I have started off with ng boilerplate.
Now suppose I have a config.json file something like below-
{
    "app": "abc",
    "login": "xyz"
}

I want some variables in my app to be configurable. So at some place I could use something like -
var loginUrl : string = "def?pqr="+config.app;

Now how can I read this config in my javascript files? I am looking for best practice answer. I am fine with substitution at grunt build step also.
Note: The config file is present on client itself, i.e no need to load it from server separately.

A: In my case, I use grunt to inject a config file (shared with the server) in an angular constant module :
Using grunt-preprocess :
I having a config.tpl.js with :
angular.module('app.config', [])

.constant('appConfig', {

    // clientside specific constants
    var1                        : 'value1',
    var2                        : [1,2,3],
    sharedVars                  : /* @echo SHARED_VARS */
});

Then, in my gruntFile :
preprocess: {
    options: {
        context: {
            SHARED_VARS: grunt.file.read('config.json'),
        }
    },
    config: {
        src: 'src/config.tpl.js',
        dest: 'src/config.js' // true file generated and loaded in index.html
    }
},

That way you can inject a full config file in an angular constant module, or pick only the vars you want.

A: For client side code you should just use $http.get to get the json file from the server. Assuming the json file is http accessible at /manage/config.json you would do:
$http.get('/manage/config.json').then((res)=>{
     var config = res.data;
});

$http automatically does json parsing for you.

A: here is what i did
   var initInjector = angular.injector(['ng']);
   var $http = initInjector.get('$http');
   var configModule = angular.module('portalConfig', []);
   $http.get('../config/Settings.json').then(
            function (response) {

                configModule.value('config', response.data);
            }
        );

and then suppose your app module is foo then
angular.module('foo',['portalConfig'])


text:
Q: Getting Parcelable encountered IOException writing serializable object I am getting Parcelable encountered IOException writing serializable object exception when try to pass custom object. Below is my code snippet:
val intent = Intent(this@MyDowoodleActivity, CreateDowoodleActivity::class.java)
intent.putExtra("DATA", Activity())
startActivity(intent)

Model class:
 data class Activity(
    @SerializedName("isDeleted")
    val isDeleted: Int = 0,
    @SerializedName("startDate")
    **val startDate: Any = Any()** // I think this exception is because of Any type

 ):Serializable

But I want to have Any() as the type. How to do this?
The log shows this:
    java.lang.RuntimeException: Parcelable encountered IOException writing
   serializable object (name = com.smartlayer.dowoodle.Activity)
    at android.os.Parcel.writeSerializable(Parcel.java:1536)
    at android.os.Parcel.writeValue(Parcel.java:1484)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:733)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1408)
    at android.os.Bundle.writeToParcel(Bundle.java:1133)
    at android.os.Parcel.writeBundle(Parcel.java:773)
    at android.content.Intent.writeToParcel(Intent.java:9253)
    at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3545)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1526)
    at android.app.Activity.startActivityForResult(Activity.java:4404)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
    at android.app.Activity.startActivityForResult(Activity.java:4363)
    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
    at android.app.Activity.startActivity(Activity.java:4687)
    at android.app.Activity.startActivity(Activity.java:4655)
    at com.smartlayer.dowoodle.create_dowoodle.MyDowoodleActivity$onDowoodleEdit$1.onResponse(MyDowoodleActivity.kt:66)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
 Caused by: java.io.NotSerializableException: java.lang.Object
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1224)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1584)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1549)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1472)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1218)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)

Any answer will be appreciated.
Thanks

A: Yes you're correct.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html
The Any() object is not marked as Serializable, if you convert startdate to Date or DateTime or even long and add a method for converting long to startdate you should be fine.


text:
Q: Blazor WA hosted - 401 Unauthorized on Azure AppService I have a simple Blazor app from template. You can inspect it here: https://blazorfun2.azurewebsites.net/ . FetchData page is only for authorized users, but when I authorize I get 401 Unauthorized error. Under the Response header it shows this error:

WWW-Authenticate: Bearer error="invalid_token", error_description="The issuer 'https://blazorfun2.azurewebsites.net' is invalid"

You can test that with testmail@testmail.something and Error#2 password.
I don't have this error on local host.
I am using Azure app service, dotnet 5.0 on Linux.
It is solvable by changing IssuerUri (source), but I guess it's not the best option..
//Main method in Program.cs in Client:
 var builder = WebAssemblyHostBuilder.CreateDefault(args);
 builder.RootComponents.Add<App>("#app");

 builder.Services.AddHttpClient("BlazorPlaygroundFun.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
     .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

 // Supply HttpClient instances that include access tokens when making requests to the server project
 builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("BlazorPlaygroundFun.ServerAPI"));

 builder.Services.AddApiAuthorization();

 await builder.Build().RunAsync();

//startup.cs in server project:
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));

services.AddDatabaseDeveloperPageExceptionFilter();

services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

services.AddIdentityServer()
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

services.AddAuthentication()
    .AddIdentityServerJwt();

services.AddControllersWithViews();
services.AddRazorPages();

What is wrong here? Thank you!

A: When you log in successfully, call
var token = await TokenProvider.GetTokenAsync();

method to get jwt token.
Then in Fetch Data, bring the jwt token in header, which will solve your problem.
For more details, please check the related post.
Thanks for enet's answer.
Blazor WebAssembly 401 Unauthorized even when I am authorized


text:
Q: Drawing polylines over Image in UIImage View I want to draw polylines over and image loaded in an UIImageView.
Can someone give me some tips on where to start?
Thank you

A: To draw polygon you should use the drawRect method located in UIView subclass.
So 2 solutions :
1°) You subclass UIImageView and in drawRect you draw your image and draw your polylines then
2°) You have an UIImageView and on the top an UIView subclass where you draw your polylines
Drawing the polylines won't be a problem (you should find an answer on stack).
(like here : polyines on iphone)


text:
Q: How to calculate perplexity for LDA with Gibbs sampling I perform an LDA topic model in R on a collection of 200+ documents (65k words total). The documents have been preprocessed and are stored in the document-term matrix dtm. Theoretically, I should expect to find 5 distinct topics in the corpus, but I would like to calculate the perplexity score and see how the model fit changes with the number of topics. Below is the code I use. The problem is it gives me an error when i try to calculate the perplexity score and I am not sure how to fix it (I am new to R). The error is in the last line of code. I would appreciate any help.
burnin <- 4000  #burn-in parameter
iter <- 2000    # #of iteration after burn-in
thin <- 500     #take every 500th iteration for further use to avoid correlations between samples
seed <-list(2003,10,100,10005,765)
nstart <- 5     #use 5 different starting points
best <- TRUE    #return results of the run with the highest posterior probability

#Number of topics (run the algorithm for different values of k and make a choice based by inspecting the results)
k <- 5

#Run LDA using Gibbs sampling
ldaOut <-LDA(dtm,k, method="Gibbs",
             control=list(nstart=nstart, seed = seed, best=best,
                          burnin = burnin, iter = iter, thin=thin))

 perplexity(ldaOut, newdata = dtm)

Error in method(x, k, control, model, mycall, ...) : Need 1 seeds

A: It needs one more parameter "estimate_theta",
use below code:
perplexity(ldaOut, newdata = dtm,estimate_theta=FALSE)


text:
Q: Flask/AngluarJS Deploying to Heroku I've got a newbee question. I want to deploy my Flask app (simple REST) to heroku. I want to serve the backend with Flask but I would also like to serve a front-end via AngularJS. Do I need to create two separate heroku apps ? one for front-end second for backend? OR Maybe I can pull it of inside one heroku app/process ? I am looking forward to all responses, cheers !

A: You don't need to create two separate Heroku apps. Create a single Heroku app, where your Flask backend serves the front-end experience to the user.
For example:
Say your Flask app serves some index.html to the user:
@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

Make sure you add AngularJs to the index.html file you are serving the user. Add the following line to your index.html. Remember to update this based on whatever version of AngularJS you are using. In this example, I am using version 1.4.9.
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

I suggest that you read up on the client-server model as that will help you understand the role of the client and server, and how they interact.


text:
Q: Rendering a cube I used an object exporter to get a model of cube from Blender. For some reason I can't get the cube rendered - it's probably my lack of view and projection matrices understanding. Could you point out my mistake ?
Rendering a simple triangle with the same renderer, however, 0.0f, 0.49f, 0.0f, -0.49f, 0.0f, 0.0f, 0.49f, 0.0f, 0.0f completes fine.
public class CubeRenderer implements Renderer {

public float xAngle = 0;
public float yAngle = 0;

    public CubeRenderer() {
        cubeBuffer = ByteBuffer.allocateDirect(CubeModel.VERTICES.length * 8)
                .order(ByteOrder.nativeOrder()).asDoubleBuffer();
        cubeBuffer.put(CubeModel.VERTICES).position(0);
    }

@Override
public void onDrawFrame(GL10 arg0) {
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
    GLES20.glUseProgram(iProgramHandle);
    cubeBuffer.position(0);
    GLES20.glVertexAttribPointer(iPositionHandle, 3, GLES20.GL_FLOAT, false, 0,
            cubeBuffer);
    GLES20.glEnableVertexAttribArray(iPositionHandle);
    Matrix.setIdentityM(m_fIdentity, 0);
    Matrix.rotateM(m_fIdentity, 0, -xAngle, 0, 1, 0);
    Matrix.rotateM(m_fIdentity, 0, -yAngle, 1, 0, 0);

    Matrix.multiplyMM(m_MVPMatrix, 0, m_fViewMatrix, 0, m_fIdentity, 0);

    Matrix.multiplyMM(m_MVPMatrix, 0, m_fProjMatrix, 0, m_MVPMatrix, 0);

    GLES20.glUniformMatrix4fv(iMVPMatrixHandle, 1, false, m_MVPMatrix, 0);

    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, CubeModel.VERTICES_COUNT);
}

@Override
public void onSurfaceChanged(GL10 arg0, int width, int height) {
    GLES20.glViewport(0, 0, width, height);
    float ratio = (float) width / height;
    Matrix.frustumM(m_fProjMatrix, 0, -ratio, ratio, -1.0f, 1.0f, 1.0f, 10.0f);
}

@Override
public void onSurfaceCreated(GL10 arg0, EGLConfig arg1) {
    GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1);
    GLES20.glEnable(GLES20.GL_DEPTH_TEST);
    GLES20.glFrontFace(GLES20.GL_CCW);

    Matrix.setLookAtM(m_fViewMatrix, 0, 0.0f, 3.0f, 5.5f, 0.0f, 0.0f, -10.0f, 0.0f, 1.0f, 0.0f);

    iProgramHandle = Utils.LoadProgram(CubeModel.VERTEX_SHADER_CODE, CubeModel.FRAGMENT_SHADER_CODE);
    iColorHandle = GLES20.glGetAttribLocation(iProgramHandle, "a_color");
    iPositionHandle = GLES20.glGetAttribLocation(iProgramHandle, "a_position");
    iMVPMatrixHandle = GLES20.glGetUniformLocation(iProgramHandle, "u_MVPMatrix");
}

}

public class CubeModel {

    public final static String VERTEX_SHADER_CODE = "attribute vec4 a_position;\n"
            + "attribute vec4 a_color;" + "uniform mat4 u_MVPMatrix;\n"
            + "varying vec4 v_color;"
            + "void main()" + "{"
            + "v_color = a_color;"
            + "gl_Position = u_MVPMatrix * a_position;" +
            "}";

    public final static String FRAGMENT_SHADER_CODE = "precision mediump float;"
            + "varying vec4 v_color;" + "void main()" + "{"
            + "gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );" + "}";

    public final static int VERTICES_COUNT = 36;

    public final static double[] VERTICES = new double[]{
      // f 1 2 3 4
      0.499999812500094, -0.499999750000125, -0.499999875000062,
      0.499999812500094, -0.499999750000125, 0.499999625000187,
      -0.499999687500156, -0.499999750000125, 0.499999625000187,
      // f 1 2 3 4
      0.499999812500094, -0.499999750000125, -0.499999875000062,
      -0.499999687500156, -0.499999750000125, -0.499999875000062,
      -0.499999687500156, -0.499999750000125, 0.499999625000187,
      // f 5 8 7 6
      0.499999812500094, 0.499999750000125, -0.499999375000312,
      -0.499999687500156, 0.499999750000125, -0.499999875000062,
      -0.499999687500156, 0.499999750000125, 0.499999625000187,
      // f 5 8 7 6
      0.499999812500094, 0.499999750000125, -0.499999375000312,
      0.499999312500344, 0.499999750000125, 0.500000124999937,
      -0.499999687500156, 0.499999750000125, 0.499999625000187,
      // f 1 5 6 2
      0.499999812500094, -0.499999750000125, -0.499999875000062,
      0.499999812500094, 0.499999750000125, -0.499999375000312,
      0.499999312500344, 0.499999750000125, 0.500000124999937,
      // f 1 5 6 2
      0.499999812500094, -0.499999750000125, -0.499999875000062,
      0.499999812500094, -0.499999750000125, 0.499999625000187,
      0.499999312500344, 0.499999750000125, 0.500000124999937,
      // f 2 6 7 3
      0.499999812500094, -0.499999750000125, 0.499999625000187,
      0.499999312500344, 0.499999750000125, 0.500000124999937,
      -0.499999687500156, 0.499999750000125, 0.499999625000187,
      // f 2 6 7 3
      0.499999812500094, -0.499999750000125, 0.499999625000187,
      -0.499999687500156, -0.499999750000125, 0.499999625000187,
      -0.499999687500156, 0.499999750000125, 0.499999625000187,
      // f 3 7 8 4
      -0.499999687500156, -0.499999750000125, 0.499999625000187,
      -0.499999687500156, 0.499999750000125, 0.499999625000187,
      -0.499999687500156, 0.499999750000125, -0.499999875000062,
      // f 3 7 8 4
      -0.499999687500156, -0.499999750000125, 0.499999625000187,
      -0.499999687500156, -0.499999750000125, -0.499999875000062,
      -0.499999687500156, 0.499999750000125, -0.499999875000062,
      // f 5 1 4 8
      0.499999812500094, 0.499999750000125, -0.499999375000312,
      0.499999812500094, -0.499999750000125, -0.499999875000062,
      -0.499999687500156, -0.499999750000125, -0.499999875000062,
      // f 5 1 4 8
      0.499999812500094, 0.499999750000125, -0.499999375000312,
      -0.499999687500156, 0.499999750000125, -0.499999875000062,
      -0.499999687500156, -0.499999750000125, -0.499999875000062,
    };
}

A: You've got a double buffer and you're telling OpenGL that it's a buffer of GL_FLOAT, perhaps that's a problem?
You might want to use float buffer instead.


text:
Q: Bug with highcharts pie-basic percent I'm using the code of demo pie-basic (Fiddle) with the following values :
series: [{
    type: 'pie',
    name: 'Browser share',
    data: [
        ['Firefox',   34],
        ['IE',       33],
        ['Safari',    26],
        ['Opera',     7],
    ]
}]

and the problem is that it appears as 7.000000000000001% instead of 7%.
How can I get a rounded value to appear?

A: Well, I can't tell you how to prevent the floating point error from occurring in the first place, but I can tell you how to hide it from the user.
You can simply use Math.round() in your formatter function, as follows:
formatter: function() {
    return '<b>'+ this.point.name +'</b>: '+ Math.round(this.percentage) +' %';
}

You already have a formatter function; I've just added Math.round() to it.
I've updated your fiddle to demonstrate: http://jsfiddle.net/A2cVe/1/
[EDIT] You mention that the tooltip was also showing the error. There is also a separate formatter function for that. I've updated the fiddle again with both formatter functions now edited to show the expected value: http://jsfiddle.net/A2cVe/2/

A: This issue is related with known bug https://github.com/highslide-software/highcharts.com/issues/897


text:
Q: Checkbox issue in custom listview I want to select all CheckBox from Custom ListView on single Button click .
But when I have more than 9 items in ListView I am getting NullPointerException in below second line of code.
View vi= diffeneceLv.getChildAt(i);
CheckBox cb = (CheckBox) vi.findViewById(R.id.conschkbx);

A: You are getting it wrong, ListView re-uses your rows, which means number of created rows/layouts in memory are not equal to your items in array.
Typically ListView re-sets the new data to previous row upon scroll.
I would suggest you to study this blog post, here the author is maintaing the Checked state and then setting it accordingly in getView() of adapter.
The author have created an array of bolean like this:
private boolean[] thumbnailsselection;

and storing the state of check or uncheck, and later accessing it from getView(), what you will do is, you will store true for all index and refresh your adapter. It'll select all your rows.
Here is another post.

A: You should NOT hold references of individual views for this purpose, as they are recycled.
For your convenience, ListView holds a BooleanSparseArray to store what items are checked.  This array contains a map of item id (index/position of items in adapter) to a boolean value.
Since ListView does all that for you, its good to avoid re-inventing the wheel and use ListView's capability to hold checked state of its items. All you have to do is to set a choice mode for ListView: setChoiceMode(int choiceMode)

*

*To get any item's state, call isItemChecked(int position) on ListView. Useful, if you are overriding getView() of adapter.

*To get all what's checked, call getCheckedItemPositions() on ListView.

*To set checked value, call setItemChecked(int position, boolean value) on ListView.


text:
Q: Javascript on lost focus event for tab out I have a javascript function like this:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "watermark", "function WaterMark(txtWaterMark, event, text) {if(event.type == 'keyup') {var charCode; if (event.charCode) { charCode = event.charCode;} else { charCode = event.keyCode; } if(charCode == 9 && txtWaterMark.value.length == 0) txtWaterMark.value = 'Pakistan';}  if (txtWaterMark.value.length > 0 && event.type == 'mouseover') { txtWaterMark.style.color = '#c6c1c1'; } if (txtWaterMark.value.length > 0 && event.type == 'mouseout') { txtWaterMark.style.color = 'gray';} if (txtWaterMark.value.length == 0 && event.type == 'mouseout') {txtWaterMark.value = text; }  if (event.type == 'focus') {txtWaterMark.style.color = 'gray'; if (txtWaterMark.value == text) { txtWaterMark.value = ''; } }}", true);

and I am calling it like this:
  <asp:TextBox ID="txtFirstName" runat="server" Width="110px" Text="First Name."
                ForeColor="Gray" onmouseover="WaterMark(this, event,'First Name.');" onmouseout="WaterMark(this, event,'First Name.');"
                onfocus="WaterMark(this, event,'First Name.');" onkeyup="WaterMark(this, event,'First Name.');" ToolTip="First Name."
                ValidationGroup="CheckoutConfirm"></asp:TextBox>

I am using on keyup event so that if user press tab key to move between textboxes, then a text is added to the text box, but on keyup is fired when i focus is inside the textbox after pressing tab. I want some event like 'on lost focus' I tried on blur but no benefit.

A: There is blur event in java script fires when a user leaves an input field.
http://www.w3schools.com/jsref/event_onblur.asp


text:
Q: Trying to filter and map to output unique values Is the code below possible if it is manipulated correctly, it's currently not working for me, i also maybe be going about it the wrong way? Trying to filter and then map so that I can avoid duplicate 'Subnames'
App.js
render() {
  const results = !this.state.resultFound
    ? null
    : this.state.search.filter((item, index) =>
        this.state.search.indexOf(item) === index).map(item => (
          <Search
            key={item.key}
            subname={item.subname}
            clickedSub={() => this.getUniqueSubs2(item)}
          />
        ))
      )

  return (

      {results}

  )
}

Search.js
const search = (props) => {
  return (
    <button onClick={props.clickedSub}> {props.subname} </button>
  )
}

A: indexOf method will not work properly since you are not operating over primitive values but on objects. The strict comparison === will fail in this case.
You could try e.g. Array#reduce to get rid of the dupes.

const arr = [{ subname: 'foo', name: 'a' }, { subname: 'boo', name: 'b' }, { subname: 'foo', name: 'c' }];
const r = Object.values(
   arr.reduce((s, a) => (a.subname in s ? a : s[a.subname] = a, s), {}),
);

console.log(r);

A: Echo of indexOf not working on objects, but an example with filter, indexOf, and map.

let search = [{
  key: 1,
  subname: 'a'
}, {
  key: 2,
  subname: 'a'
}, {
  key: 3,
  subname: 'b'
}, {
  key: 4,
  subname: 'b'
}]
let seen = [];
let result = search.filter((item, index) => {
    if (seen.indexOf(item.subname) === -1) {
      seen.push(item.subname)
      return false
    }
    return true
  })
  .map(o => ({
    newValue: 'abc',
    ...o
  }))
document.querySelector('#test').innerHTML = JSON.stringify(result)


text:
Q: Is it possible to share a vector using boost windows_shared_memory? Just getting started to use boost library and familiarizing myself with it to find a solution for my problem.
The issue I am trying to solve is the limitation of not being able to use STL containers on windows in shared memory (CreateFileMapping).
I cannot find a single example of sharing a vector using windows_shared_memory from boost. However there are many examples like this using managed_shared_memory.
Please advise if this is possible and provide an example, for sure many other developers are interested and would benefit massively from this.

A: The snippets below are an excerpt of a much bigger project where I have actually solved that problem. Since it's only snippets, I might have a few mismatches. But I'm trying to outline the general process.
The documentation is basically all available in the boost documentation. However it is terse and it has only two small examples for managed shared memory.
With this approach I was even able to share vectors and maps between 64-bit and 32-bit processes. It failed on strings, which I then exchanged for vectors of char.

The namespaces first:
namespace bipc = boost::interprocess;
namespace bc = boost::container;

If the 32-bit - 64-bit compatibility is not the issue you can get a way with a simple "managed" shared memory type:
typedef bipc::managed_windows_shared_memory                    managed_shm_type;

You can even use the basic (more platform independent) type. But that has different implications on the "persistence" of the shared memory.
typedef bipc::managed_shared_memory                            managed_shm_type;

But if you need 32/64-bit compatibility, you need to use a modified memory type. The key element is the definition of offset_ptr which defines the memory alignment:
typedef bipc::basic_managed_windows_shared_memory
     <  char
     ,  bipc::rbtree_best_fit
        <
            bipc::mutex_family,
            bipc::offset_ptr<void, int64_t, uint64_t> // defines the "alignment"
        >
     ,  bipc::iset_index
     >                                                            managed_shm_type;

Once this is done you can go ahead and define the vector (and string) types you need. The basic rule is that for every type you also need an allocator. (Except for POD types) And for the map-type you need both for both, the key and the value:
typedef managed_shm_type::segment_manager                    segment_manager_t;

typedef bc::scoped_allocator_adaptor<bipc::allocator<void, segment_manager_t> > void_allocator;
typedef void_allocator::rebind<char>::other                  char_allocator;
typedef bc::vector<char, char_allocator>                     char_vector;
typedef bc::basic_string
        <
            char,
            std::char_traits<char>,
            char_allocator
        >                                                    char_string;
typedef void_allocator::rebind<char_string>::other           string_allocator;

typedef bipc::offset_ptr<void, int64_t, uint64_t>            data_ptr;
typedef void_allocator::rebind<data_ptr>::other              data_ptr_allocator;
typedef bc::vector<data_ptr, data_ptr_allocator>             data_vector;

typedef void_allocator::rebind<int32_t>::other               int_allocator;
typedef bc::vector<int32_t, int_allocator>                   int_vector;

typedef bc::vector<char_string, string_allocator>            string_vector;

typedef std::pair<const SEGMENTID, uint32_t>                 segid_type;
typedef bipc::allocator<segid_type, segment_manager_t>       segid_type_allocator;
typedef bc::map
        <
            SEGMENTID,
            uint32_t,
            std::less<SEGMENTID>,
            segid_type_allocator
        >                                                    segid_map;

After all these types are declared you can start using them in your code:
// first get the shared memory segment
global_segment = std::make_unique<managed_shm_type>(bipc::create_only,
                                                    shmem_name.c_str(),
                                                    200000    );

// struct that is going to be allocated in shared memory
struct global_sharedMemory_data
{
    explicit global_sharedMemory_data(const char_allocator & void_alloc)
        :   declutter(50, false, void_alloc)
        ,   core_queue_name(void_alloc)
        ,   remote_queue_counter(0)
        ,   segment_id_map(void_alloc)
    {}

    int_vector              declutter;
    char_string             core_queue_name;
    uint32_t                remote_queue_counter;
    segid_map               segment_id_map;
};

global_sharedMemory_data *  globalShMem;

void_allocator alloc_inst (global_segment->get_segment_manager());
globalShMem = global_segment->construct<global_sharedMemory_data>
                            ("Name of Shared Object")(alloc_inst);

// write a string to shared memory
globalShMem->core_queue_name = "Alcatraz";


text:
Q: Match first parenthesis with Python From a string such as
70849   mozilla/5.0(linux;u;android4.2.1;zh-cn)applewebkit/534.30(khtml,likegecko)version/4.0mobilesafari/534.30

I want to get the first parenthesized content linux;u;android4.2.1;zh-cn.
My code looks like this:
s=r'70849   mozilla/5.0(linux;u;android4.2.1;zh-cn)applewebkit/534.30(khtml,likegecko)version/4.0mobilesafari/534.30'
re.search("(\d+)\s.+\((\S+)\)", s).group(2)

but the result is the last brackets' contents khtml,likegecko.
How to solve this?

A: The main issue you have is the greedy dot matching .+ pattern. It grabs the whole string you have, and then backtracks, yielding one character from the right at a time, trying to accommodate for the subsequent patterns. Thus, it matches the last parentheses.
You can use
^(\d+)\s[^(]+\(([^()]+)\)

See the regex demo. Here, the [^(]+ restricts the matching to the characters other than ( (so, it cannot grab the whole line up to the end) and get to the first pair of parentheses.
Pattern expalantion:

*

*^ - string start (NOTE: If the number appears not at the start of the string, remove this ^ anchor)

*(\d+) -  Group 1: 1 or more digits

*\s - a whitespace (if it is not a required character, it can be removed since the subsequent negated character class will match the space)

*[^(]+ - 1+ characters other than (

*\(  - a literal (

*([^()]+) - Group 2 matching 1+ characters other than ( and )

*\)- closing ).

Debuggex Demo
Here is the IDEONE demo:
import re
p = re.compile(r'^(\d+)\s[^(]+\(([^()]+)\)')
test_str = "70849   mozilla/5.0(linux;u;android4.2.1;zh-cn)applewebkit/534.30(khtml,likegecko)version/4.0mobilesafari/534.30"
print(p.findall(test_str))
# or using re.search if the number is not at the beginning of the string
m = re.search(r'(\d+)\s[^(]+\(([^()]+)\)', test_str)
if m:
    print("Number: {0}\nString: {1}".format(m.group(1), m.group(2)))
# [('70849', 'linux;u;android4.2.1;zh-cn')]
# Number: 70849
# String: linux;u;android4.2.1;zh-cn

A: You can use a negated class \(([^)]*)\) to match anything between ( and ):
>>> s=r'70849  mozilla/5.0(linux;u;android4.2.1;zh-cn)applewebkit/534.30(khtml,likegecko)version/4.0mobilesafari/534.30'

>>> m = re.search(r"(\d+)[^(]*\(([^)]*)\)", s)
>>> print m.group(1)
70849
>>> print m.group(2)
linux;u;android4.2.1;zh-cn


text:
Q: Is there a way to construct a constexpr function to get bit representation of a double? Is there a standard way to construct a constexpr function that allows conversion of double to it's 64 bit representation:
constexpr uint64_t double_to_uint64_t(double d) {
   ??????
}

So that
constexpr uint64_t two_bits = double_to_uint64_t(2.0);

would compile?
The reverse method (uint64 to double) is also of interest.

A: Not until C++20. All of the usual tricks are either outright forbidden (reinterpret_cast) or undefined behavior, and UB becomes ill-formed when executed at compile-time.
C++20 provides std::bit_cast, which does binary conversion between two types, so long as they are both trivially copyable and have the same size. And the function is constexpr, so you can use it at compile-time.


text:
Q: What are the advantages of a random effects model versus a pooled OLS regression with cluster–robust standard errors? Both models allow for explanatory variables that are time-invariant.
I had thought that the advantage of a random effects model might be related to the fact that random effects models mitigate serial correlation (does it?) whereas pooled OLS regression with cluster–robust standard errors do not, but I then found a post that noted (emphasis added):

Clustered standard errors are robust to heteroskedasticity and serial correlation in the error term. In that sense, clustered standard errors are "appropriate" when you think this is the case in
  your context, as they still give you valid inference. One likely
  reason in panel data for (positive) serial correlation in the error
  term is the presence of time-invariant unobservables. However, if
  there are such time-invariant unobservables, other estimators might be
  more appropriate than pooled OLS, e.g. fixed effects if you think the
  time-invariant unobservables are correlated with your regressors, or
  random effects if you think there is no such correlation.

A related question is here but the person who asked that question asked about pooled OLS (not pooled OLS regression with cluster–robust standard errors).


text:
Q: How can I set the daterangepicker to today + 1 day? I want to set the startdate of my daterangepicker to today + 1 day and the enddate of my daterangepicker to today + 2 days.
  <script type="text/javascript">
            $(document).ready(function () {
                var date = new Date();
                var currentMonth = date.getMonth();
                var currentDate = date.getDate();
                var currentYear = date.getFullYear();
                $('input[name="daterange"]').daterangepicker({
                    minDate: new Date(currentYear, currentMonth, currentDate)
                    , dateFormat: 'yy-mm-dd'
                    , startDate: +1
                    , endDate: +2
                    , locale: {
                        format: 'DD.MM.YYYY'
                    }
                });
            });
        </script>

my result is 09.08.2017 - 09.08.2017
But I expect 10.08.2017 - 11.08.2017

A: Your issue is in these lines:
, startDate: +1
, endDate: +2

Change to:
 , startDate: moment(date).add(1,'days')
 , endDate: moment(date).add(2,'days')

The snippet:

var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('input[name="daterange"]').daterangepicker({
    minDate: new Date(currentYear, currentMonth, currentDate)
    , dateFormat: 'yy-mm-dd'
    , startDate: moment(date).add(1,'days')
    , endDate: moment(date).add(2,'days')
    , locale: {
        format: 'DD.MM.YYYY'
    }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />

<input type="text" name="daterange" value="01/01/2015 - 01/31/2015" />


text:
Q: Don't really understand how arrays work in Assembly I've just started learning Assembly and I got stuck now...
%include 'io.inc'

global main

section .text
main:
    ; read a
    mov eax, str_a
    call io_writestr
    call io_readint
    mov [nb_array], eax
    call io_writeln

    ; read b
    mov eax, str_b
    call io_writestr
    call io_readint
    mov [nb_array + 2], eax
    call io_writeln

    mov eax, [nb_array]
    call io_writeint
    call io_writeln
    mov eax, [nb_array + 2]
    call io_writeint

section .data
nb_array dw 0, 0
str_a db 'a = ', 0
str_b db 'b = ', 0

So, I have a 2 elem sized array and when I try to print the first element, it doesn't print the right value. Although I try to print the second element, it prints the right value. Could someone help me understand why is this happening?

A: The best answer is probably "because there are no arrays in Assembly". You have computer memory available, which is addressable by bytes. And you have several instructions to manipulate those bytes, either by single byte, or by groups of them forming "word" (two bytes) or "dword" (four bytes), or even more (depends on platform and extended instructions you use).
To use the memory in any "structured" way in Assembly: it's up to you to write piece of code like that, and it takes some practice to be accurate enough and to spot all bugs in debugger (as just running the code with correct output doesn't mean much, if you would do only single value input, your program would output correct number, but the "a = " would be destroyed anyway - you should rather every new piece of code walk instruction by instruction in debugger and verify everything works as expected).
Bugs in similar code were so common, that people rather used much worse machine code produced by C compiler, as the struct and C arrays were much easier to use, not having to guard by_size multiplication of every index, and allocating correct amount of memory for every element.
What you see as result is exactly what you did with the memory and particular bytes (fix depends whether you want it to work for 16b or 32b input numbers, you either have to fix instructions storing/reading the array to work with 16b only, or fix the array allocation and offsets to accompany two 32b values).


text:
Q: PXE Boot an ISO with iSCSI information High Level: I'm using pxelinux.0 and memdisk to boot a Windows PE iso. I then connect to an iSCSI lun and apply a Windows WIM.
More information: Normally netboot/i is used to automatically assign clients their initiator name and target when they boot. The options available are boot from iscsi, next bbs device, boot from CD, and my custom boot to WinPE iso. When I burn the ISO to CD and use the boot from CD option the client is connected to its LUN via the iscsicd.0 file provided with netboot/i. This results in the initiator name, target and a session being set and created in the WinPE environment. Letting the technicians treat the system as though it had a physical disk. Less headache for me.
The Problem: Trying to go true diskless, I need a way to load the iSCSI information via one of the netboot/i provided .0 files, then pass control back to pxelinux.0 which in turn will use memdisk and load the WinPE ISO. Currently the only way to set the initiator name and connect to the target is to set the initiator manually, add the discover portal manually and launch the session manually. This is a bit beyond me.
Why? While I could go through the whole headace of setting up a pxeboot directly to the WinPe.Wim file, it seems as though booting to the ISO is faster. Not to mention easier to add tools and scripts to the disk by simply mounting the ISO and adding/updating files.

A: Use iPXE instead of using pxelinux, then the winpe image can be loaded over HTTP(S) which is faster than TFTP.
Or use iPXE to boot directly from an iSCSI LUN
You might find the iPXE documentation useful
http://ipxe.org/howto/winpe
http://ipxe.org/howto/wds_iscsi


text:
Q: Looking for a GMail-like autosuggest textbox I need an auto-suggest textbox, just like the one for entering the recipient's email address in GMail when we compose an email.

A: JQueryUI does this. You'll want a combination of the Custom data and Multiple values options.

A: See this document:
http://docs.jquery.com/Plugins/autocomplete
This uses ajax query which would be easy to handle.

A: Yeah..U can Use AJAXSCRIPT Manager and AjaxAutoExtender
Put your coding in Autoextender method to retrive datas from SQL-server

A: Check this link.
It will automatically validate the values as gmail does. And you can enter multiple values and you can remove values by clicking on close button of the entry
If you want simple autocomplete then you can go with this link.


text:
Q: UIPickerView cannot fetch Array output in Swift 3.0 I have these PHP file to fetch data from database based on "dept" condition.
getDeptList.php
<?php
    if (isset($_POST['dept'])){
        $dept       = $_POST['dept'];

        $sql   = "SELECT * FROM users WHERE dept ='$dept'";
        $result = mysqli_query($connect, $sql);

        if ($result && mysqli_num_rows($result) > 0){
            while ($row = mysqli_fetch_array($result)) {

                $login_db       = $row['login'];
                $real_namedb    = $row['real_name'];

                $output[]= array('login' => $login_db, 'real_name' => $real_namedb);

            }

            echo json_encode($output);
        mysqli_free_result($result);
        }
        else {
            $output = array('login' => 'wrong credentials from PHP code!');
            echo json_encode($output);
            echo mysqli_error($connect);
        }
    }
?>

In x code, I have value UILabel that has been set to "ITD" and this value need to be post into PHP first to produce Array output in UIPickerView.
Here's my code so far.
UPDATE
getDeptList.swift
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    @IBOutlet var deptLbl: UILabel!
    @IBOutlet var loginLbl: UILabel!
    @IBOutlet var real_nameLbl: UILabel!
    @IBOutlet var dropdownTxt: UITextField!
    @IBOutlet var dropdown: UIPickerView!

    var persons = [Person]()

    struct Person {
        var login: String
        var real_name: String

        init?(dict: [String:Any]) {
            guard let login = dict["login"] as? String, let real_name = dict["real_name"] as? String else {
                return nil
            }
            self.login = login
            self.real_name = real_name
        }
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.persons.count
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return persons[row].real_name
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if row >= self.persons.count {
            return
        }
        self.loginLbl.text = self.persons[row].login
        self.real_nameLbl.text = self.persons[row].real_name
        self.dropdown.isHidden = true
        self.dropdownTxt.resignFirstResponder()
    }
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self.dropdownTxt {
            self.dropdown.isHidden = false
        }
    }

    func getDropdownJSON(){
        deptLbl.text = "ITD"
        var request = URLRequest(url: URL(string: "http://localhost/getDeptList.php")!)
        request.httpMethod = "POST"
        let postString = "dept=\(deptLbl.text!)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            guard let data = data, error == nil else {
                print("error=\(error)")
                return
            }
            if let result = try? JSONSerialization.jsonObject(with: data, options: []) {
                print(result)
            }
        }
        task.resume()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        getDropdownJSON()
    }
}

Console did'nt print result value

The problem is, UIPickerView can't fetch the Array output. I'm not sure why. maybe someone can help to solve this issue.
Thanks.


text:
Q: fetched data getting updated I'm trying to give permission to different users based on their roles. The permissions are fetch, add, delete, edit etc. When i give only certain permission to a user like for example, if I give only add and delete for user1 then while creating the next user and then while giving permission only add and delete are available, the other permissions are not avaliable. How do i resolve this ? I want a new group id for each roles permission. I tried coding it below, but it doesn't seem to work.

service.ts

add_permission(data){
var headers = new HttpHeaders().set('Authorization', 'Token ' +
localStorage.getItem('usertoken'));

var options =  {
  headers: headers
};
return this.httpClient.post('/api/auth/permission_list/',data,
options)
 }

component.ts

id :number;
dropdown_data:any = [];
checkedList = [];
permissionList:any = [];
perms:any = [];
permission_data:any = [];

onChange(email:string, checked: boolean) {
if(checked) {
this.perms.push(this.permission_data.permission_list)
}
}

ngOnInit(): void{

//get permission

  this.Authentication.get_permissions().subscribe(res =>{
    this.permissionList = res;
    console.log(res);

    for(let val of this.permissionList){
      this.dropdown_data = val.permission_list
      this.id = val.group_id
    }
  })

}

//getting values of selected check box

onCheckboxChange(val, event) {
if(event.target.checked) {
this.checkedList.push(val);
console.log(this.checkedList);
} else {
for(var i=0 ; i < this.dropdown_data.length; i++) {
  if(this.checkedList[i] == val){
    this.checkedList.splice(i,1);
  }
}
}
}

// add permission

addPermission(){
let permissions = {};
permissions['group_id'] = this.id
permissions['permission_list']= this.checkedList;
console.log(permissions)

this.Authentication.add_permission(permissions).subscribe(res => {
  console.log('added')
},
err =>{
console.log('error');
})
}

component.html

           Permissions
           Select/Unselect

            {{val}}

                <input type="checkbox"  value="{{val}}" (change)="onCheckboxChange(val,$event)" >

          <button type="button"  class="btn btn-primary pull-right" (click)="addPermission()">Submit</button>


text:
Q: Management packages. What tool should I use? I'm starting new app with meteor and I'm confuse when I have to install packages.
Meteor gives the possibility to install packages just like that:
meteor add <username>:<packagename>
Ok, very easy. The problem is that I would like use bower then, How I have to install the packages? For example angular.
meteor add urigo:angular

is the same as? what is the difference*? How I have to perform?
bower install angular

The logical conclusion could be use one of them, but I have seen in examples that they can be toguether.
*the package is recorded in different places, but the operation is the same?

A: With
meteor add <developer>:<packagename>

you add packages from the Meteor specific package database. Meteor packages are completely integrated into the Meteor eco-system and may contain both server and client side code.
You should use "meteor add" whenever possible.
To find Meteor packages you can use Atmosphere
Bower on the other hand is a framework independent package system for client side (mostly) JavaScript packages. It's not well integrated with Meteor - Although community packages exists to simplify usage of Bower packages with Meteor.
To answer you specific example:
meteor add urigo:angular

This command adds the Angular package of the Angular-Meteor project to your Meteor application. It's not only Angular but does also include some Angular services ($meteor) to provide integration of Meteor with Angular.
It even adds Angular support to the server side to some degree.
bower install angular

only downloads the official minified and non-minified javascript file of the latest Angular version for client side use.
You could use the Bower version with Angular but you wouldn't get the benefits of the integration.

A: While I don't use Bower myself, check out this package: https://atmospherejs.com/mquandalle/bower. I think it may help answer your question.


text:
Q: $B^2A - A$ is invertible $\Rightarrow $ $AB - A$ is invertible I'm trying to solve the problem in the title. So far I have concluded:
1) $det(B^2A - A) \neq 0 \Rightarrow det(A)\neq0$ and $det(B^2 - I)\neq0 $
2)Suppose $det(AB - A) = 0$  $\Rightarrow det(A)=0$ or $det(B - I) = 0 $
By (1): $det(A)\neq0$ and so I'd like to show:  $det(B^2 - I)\neq0 \Rightarrow det(B - I)\neq0$
Suggestions?

A: Hint: $B^2-I=(B+I)(B-I)$. Now take the determinant.

A: $det(AB-A)=det(A)det(B-I)$, $det(A)=0$ implies $det(B^2A-A)=0$, $det(B-I)=0$ implies that $det(B-I)(B+I)=det(B^2-I)=0$.


text:
Q: Matching/classifying unlabeled pairs of observations Various measurements corresponding to the same person are taken at different points of time resulting into DF1 and DF2 as shown below (this is only a sample of the hundreds of observations). Assuming the identity (ID) of the persons is not known (unlabeled classification), I want to match observation which belong to the same person. I thought of matching them using least Euclidean distance but provided very poor match. Any idea on how to do this in R, e.g., probability based matching?
ID <- letters[1:10]
lpl <- c(729,718,715,632,634,779,649,773,659,746)
wb1 <- c(153,173,113,130,158,176,178,165,126,193)
wb2 <- c(42,44,42,43,43,44,43,45,41,42)
wb3 <- c(330,308,356,300,295,349,292,328,274,330)
wb4 <- c(39,104,40,41,41,43,40,42,40,101)

DF1 <- data.frame(ID,lpl,wb1,wb2,wb3,wb4)

ID <- letters[1:10]
lpl <- c(703,681,672,599,574,712,590,707,621,721)
wb1 <- c(161,171,113,129,154,168,181,155,128,193)
wb2 <- c(41,44,41,42,41,42,41,41,41,41)
wb3 <- c(339,309,350,303,290,332,288,312,279,328)
wb4 <- c(39,105,38,38,41,40,39,39,41,99)

DF2 <- data.frame(ID,lpl,wb1,wb2,wb3,wb4)


text:
Q: Suspend from console without leaving authenticated terminal on wake up I want to suspend my computer from terminal (one obtained by CTR+ALT+F1).
If I call:
# echo -n mem > /sys/power/state

after wakeup I'm leaving an authenticated console with (possibly) root credentials open to anyone.
Is there any elegant way to suspend the computer without leaving this console open?
Background: Suspend button is not working on my XFCE desktop and because of many reasons I don`t want to fix it right now. So it is easier to just suspend from terminal.

A: Here is my solution (it is not very clean).
I created a script called /sbin/suspend.sh containing:
#!/bin/bash
echo -n mem > /sys/power/state

and then in my .bashrc file added following alias:
alias dosuspend='sudo suspend.sh && exit'

Now whenever I call dosuspend console is logged out right after wakeup.


text:
Q: Does [My]SQL have a Pre-Processor-like Facility? I'm writing a small deployment SQL script for my first database-driven app.
In the process, I find that I repeat myself a lot, for instance:
GRANT USAGE ON *.* TO 'foo'@'localhost';
DROP USER 'foo'@'localhost';
CREATE USER 'foo'@'localhost' IDENTIFIED BY 'password';

It would be fantastic if I could use a variable or a macro to replace commonly occurring data. Is it possible to implement something like the the following snippet?
#define USER 'foo'        #or "Type USER = 'foo'"
#define HOST 'localhost'  #or "Type HOST = 'localhost'"

GRANT USAGE ON *.* TO USER@HOST
DROP USER USER@HOST
CREATE USER USER@HOST IDENTIFIED BY 'password'

A: Most SQL databases have some kind of bind variables that you can use for that.
For instance, in PostgreSQL you use the \set command in plsql:
\set user = foo
drop user :user;
create user :user identified by 'password';

However, I am not sure if MySQL have something like that. It do have variables, and since the host and user is a string, you might be able to do something like this:
select @user = 'foo';
select @host = 'localhost;

drop user @user@@host;
create user @user@@host identified by 'password';

If variables doesn't work with the drop and create user statements, you can always modify the mysql.user table directly, just don't forget to execute flush privileges after.
insert into user values(host,@user,PASSWORD('some_pass'),
       'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
flush privileges;

A: You can certainly do something like:
SET @user='foo';


text:
Q: Data structure for clipping detection I'm using SDL (pygame) for a cnc simulator. Initally, screen refreshing is done using the painter's algorithm (just draw everything back-to-front) but it quicly becames slow with big surfaces.
To speed-up redrawing I'm only refreshing the parts of the screen that change at any given moment so if a numeric value changes its value, only its surface and the correspondant sub-surface for every colliding surface gets redrawn.
At the moment, im doing a clipping test over everything on on screen to detect the colliding surfaces, while significantly faster I think there should be a data structure and/or algorithm to avoid testing all the surfaces on screen.

A: You should consider using a quadtree to store the bounds of each of your surfaces. This will optimize your operation when finding the colliding surfaces.
You might find the question / answer useful.


text:
Q: Use ULS Tracing Service to write to other files This starts sounding more and more silly the longer I think about it, but is there a way I can utilize the ULS Tracing service programmatically but have it write to another file, not the default XXXXXXX-DATE.log file?
I work with a farm that provides hosting for tenants, and with their custom code many of them like to write trace events to ULS but when digging for platform level errors it becomes a pain to start adding filters to ULS Viewer. I'd also like to separate concerns here so that if any particular tenant needs a log dump it would be easier on my end.
I've been digging into the SPDiagnosticsServiceBase class and even so far down into beginning to look into the ULS class itself to see if there was anything I could pick up but so far I'm not seeing much in terms of where I can inject a path and custom naming convention.
Perhaps the issue here is, the tenants shouldn't be writing to the ULS logs. However, I would like to explore the idea of writing out their diagnostic checks in the same format that ULS Viewer can read.
Any ideas or points in the right direction would be greatly appreciated.

A: What about writing a script that copies the ULS as it's written, and separates out the built-in and custom lines? This way, you don't have to hack any core code (yikes!), and you can provide the users with either or both logs.

A: IMO you shouldn't mess with Diagnostics Service. It is writing to centralized log for a reason.
Instead I would try to convince tenants to write Product information in their logging records. This way you can filter records by respected product and even send filtered reports using ULS Viewer.
Personally, I like to map a feature to product field in ULS.