text:
Q: Footprints for Sentinel-1 GRD imagery as GeoJSON or shapefiles I made this script to create a visualization of the images available for an area of interest:

var north_demosite = ee.Geometry.Rectangle([13.18,58.53,16.99,61.33])
Map.addLayer(north_demosite, {color: 'FF0000'}, 'North Demosite');

// Filter the collection for the VV product from the descending track
var collectionVV = ee.ImageCollection('COPERNICUS/S1_GRD')
    .filter(ee.Filter.eq('instrumentMode', 'IW'))
    .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV'))
    .filter(ee.Filter.eq('orbitProperties_pass', 'DESCENDING'))
    .filterBounds(north_demosite)
    .select(['VV'])
    .filterDate('2017-03-15', '2017-09-15');

    //.filterDate('2018-03-15','2018-09-15');
print("printing VV collection")
print(collectionVV.size())
print(collectionVV);

// Filter the collection for the VH product from the descending track
var collectionVH = ee.ImageCollection('COPERNICUS/S1_GRD')
    .filter(ee.Filter.eq('instrumentMode', 'IW'))
    .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH'))
    .filter(ee.Filter.eq('orbitProperties_pass', 'DESCENDING'))
    .filterBounds(north_demosite)
    .select(['VH'])
    .filterDate('2017-03-15', '2017-09-15');

    //.filterDate('2018-03-15','2014-09-15');

print("printing VH collection")
print(collectionVH.size())
print(collectionVH);

function addImage(image) { // display each image in collection

  var id = image.id
  var image = ee.Image(image.id);
  var array = id.split("/");
  var date = array[2];
  var date = date.slice(0, 8);
  print(image)

  Map.addLayer(image)
}

collectionVH.evaluate(function(collectionVH) {  // use map on client-side
  collectionVH.features.map(addImage, {min: -25, max: 5})

})

collectionVV.evaluate(function(collectionVV) {  // use map on client-side
  collectionVV.features.map(addImage, {min: -25, max: 5})

})

It works fine! But I would need the information of this query in a GeoJSON or shapefile format. Is this possible? I haven't seen anything in the documentation of Google Earth Engine

A: Map over the ImageCollection, get the S1 images 'system:footprint' property (coordinate list) and use it as the geometry to define a Feature for each given image. The resulting FeatureCollection can be exported as GeoJSON.
var fcVV = ee.FeatureCollection(collectionVV.map(function(img){
  var geom = ee.Geometry(img.get('system:footprint'));
  return ee.Feature(img).copyProperties(img, img.propertyNames());
}));
fcVV = ee.FeatureCollection(fcVV);
Map.centerObject(collectionVV.first());
Map.addLayer(collectionVV.first(), {}, 'image');
Map.addLayer(ee.Feature(fcVV.first()),{color:'blue'}, 'footprint');

Export.table.toDrive({
  collection: fcVV,
  description: 'VV_footprints',
  fileFormat: 'GeoJSON'
});

See lines 23-37: https://code.earthengine.google.com/38a9b7cf168422b1f5c509a2af98ec00


text:
Q: Passing data to destination view controller with performSegue So I know that if there is a segue which is setup and activated through the storyboard, one can use the prepareForSegue method to pass data to the destination view controller.
I'm wondering if there is a way to do this if one uses the performSegueWithIdentifier method? It seems the prepareForSegue method is only called if the segue is activated with the storyboard, not with performSegue.
One particular problem is that I can't access the UIStoryboardSegue (it is not an argument in performSegue as it is in prepareForSegue), and therefore can't access the destination VC either.

A: Answer is here in StackOverflow.
How to pass prepareForSegue: an object
// When any of buttons are pressed, push the next view
- (IBAction)buttonPressed:(id)sender
{
    [self performSegueWithIdentifier:@"MySegue" sender:sender];
}

// This will get called too before the view appears
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"MySegue"]) {

        // Get destination view
        SecondView *vc = [segue destinationViewController];

        // Get button tag number (or do whatever you need to do here, based on your object
        NSInteger tagIndex = [(UIButton *)sender tag];

        // Pass the information to your destination view
        [vc setSelectedButton:tagIndex];
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filter cse results using labels I want to get the json response for the domains I already have labeled.
var URL = "https://www.googleapis.com/customsearch/v1?key=**&cx=**&q=allinurl:"+queryUrl+"&fields=items(title,link,snippet)&more:"+label;
When I use that query, my results are the same as if I don't use more:label
The domains in one label aren't in the rest, and the labels have the FILTER mode.

A: It was my own mistake, the more key has to go within the query (q=) with a +, like this:
&start="+startResult+"&q=allinurl:"+queryUrl+"+more:"+label


text:
Q: Center horizontal navbar in list on flexible width page I've seen similar questions to this already, and I've been trying to fit the code to my own situation, but I'm just not finding a solution to this problem.
I need a centered horizontal navbar with has an image with text below it. I have everything in place, I just cannot get the list as a whole to center within the page.
Here is my css:
#mainnav {
width: 100%;
text-align: center; }
#mainnav ul {
list-style-type: none;
text-align: center;}
#mainnav li {
display: inline;
float: left;
text-align: center;
margin-left: 3%;
margin-right: 3%;
margin-top: 10px; }
#mainnav a {
display: block;
margin-right: 0% auto;
padding-left: 0% auto; }

This is my html:

About Us

Programs and Initiatives

Resources

Feedback

FAQs

News & Events

So I have an icon, then directly below it is the text. Those are centered relative to each other, but then the whole thing needs to be centered on the page.
I am close, but it's spread out too much because of that "margin-left: 5%; margin-right: 5%" specification under the li. If I change that, it slides to the left. How do I get it centered and have it not be so wide, with so much space between each list item?
Also, yes, I do need to have flexible width as it's a requirement by my work that I am building this page for. Thanks!

A: You need to change your css as follows: You cannot horizontally align floated elements
#mainnav {
width: 100%;
text-align: center; }
#mainnav ul {
list-style-type: none;
text-align: center;}
#mainnav li {
display: inline-block;
text-align: center;
margin-left: 3%;
margin-right: 3%;
margin-top: 10px; }
#mainnav a {
display: block;
margin-right: 0% auto;
padding-left: 0% auto; }

See http://jsfiddle.net/FM2df/1/ for results


text:
Q: GeoServer doesn't recognize imagery in GeoPackage I'm currently trying to upload a GeoPackage containing raster images to a GeoServer (v2.13) instance with the GeoPackage extension. The file contains ~425 layers but after I add the file to the server's data directory and attempt to add it to the data stores (GeoPackage Mosaic), I get a vague error message:
Could not list layers for this store, an error occurred retrieving them: null
I'm wondering if this is an existing error somewhere but I can't seem to find anything current in the GitHub repo issues or elsewhere on the net. The images are perfectly in QGIS 3 and in Python.
See the screenshot below (ignore the locale setting weirdness):


text:
Q: Android change the title color in XML I have this part of the code in drawer.xml.
<item android:id="@+id/navigation_item1"
            android:checkable="true"
            android:title="Map"
            android:textColor="#FFFFFF"
            android:icon="@mipmap/ic_launcher"/>

I want to change the color of "Map" to white. I tried android::textColor, it doesn't work.  Can I get some help?
Thanks!

A: <android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/header"
    app:itemTextColor="#ffffff"
    app:menu="@menu/drawer" />


text:
Q: Deleting duplicate polygon using QGIS I am using QGIS "Delete Duplicate Geometries" tool, I am trying to delete one of the below two polygons , but failed.
The below two polygons are identical with vertices , but the start of the vertices is different.
How to identify those and delete it using QGIS?
MultiPolygon (((1087121.56094263 4537352.23808735, 1087121.5609641 4537352.23808582, 1087124.60834866 4537351.52946457, 1087127.2876076 4537349.9138321, 1087129.33647638 4537347.54933776, 1087130.55439745 4537344.66743475, 1087130.82215222 4537341.55022379, 1087130.11353097 4537338.50283923, 1087128.4978985 4537335.82358029, 1087126.13340417 4537333.77471151, 1087123.25150115 4537332.55679044, 1087120.13430105 4537332.28903661, 1087117.08692558 4537332.99764883, 1087114.40766316 4537334.61327553, 1087112.35878929 4537336.97776546, 1087111.14086201 4537339.85966585, 1087110.87310054 4537342.97687623, 1087111.58171523 4537346.02426232, 1087113.19734193 4537348.70352473, 1087115.56183186 4537350.7523986, 1087118.44373225 4537351.97032588, 1087121.56094263 4537352.23808735)))
MultiPolygon (((1087120.13430105 4537332.28903661, 1087117.08692558 4537332.99764883, 1087114.40766316 4537334.61327553, 1087112.35878929 4537336.97776546, 1087111.14086201 4537339.85966585, 1087110.87310054 4537342.97687623, 1087111.58171523 4537346.02426232, 1087113.19734193 4537348.70352473, 1087115.56183186 4537350.7523986, 1087118.44373225 4537351.97032588, 1087121.56094263 4537352.23808735, 1087121.5609641 4537352.23808582, 1087124.60834866 4537351.52946457, 1087127.2876076 4537349.9138321, 1087129.33647638 4537347.54933776, 1087130.55439745 4537344.66743475, 1087130.82215222 4537341.55022379, 1087130.11353097 4537338.50283923, 1087128.4978985 4537335.82358029, 1087126.13340417 4537333.77471151, 1087123.25150115 4537332.55679044, 1087120.13430105 4537332.28903661)))

A: Both Check Geometries plugin and Topology Checker plugin can find duplicate polygons.

*

*Find the Geometry Checker (it is a core plugin, you have to enable only) plugin in the Vector menu. On the Setup tab of the dialog of the plugin select the layers to check. Find Check for duplicates in the topology section. In the output vector layers section you have to select Modify input layer or Create new layer. Then select Run button.

I've create a single part polygon and a multi part polygon layer. In both case the vertices are identical but the orders are different. The duplicate multi part polygons trigger two errors one for the duplicate enclave and another for the whole multi part polygon.
You can select correction method to eliminate error.

*The Topology checker is also a core plugin. Find the Topology checker in the vector menu. It opens a new panel, in the toolbar of the panel select Configure button (the third one) to define rules.

Close the configure dialog and use the first tool to check the whole layers.

This case the duplicate multi part polygons cause only single error. Double click on the error row to zoom on feature. No auto correction is available here.


text:
Q: Change MySQL encoding (regarding hex codes?), such as  to ü I am not sure how my error is termed, but I think my data show hex codes rather than the actual foreign characters.
To be more precise, I have a MySQL database with data like:

*

*G<e9>rard instead of Gérard, or

*M<fc>nster instead of Münster.

Apparently my columns have an utf8_unicode_ci-encoding (according to phpMyAdmin).
Now I wish to convert strings like <e9> into é, either directly in the MySQL-database, or in PHP when the output is being shown.
Apparently others were able to use this response to convert their MySQL-table successfully;
UPDATE db_name SET
    column1=convert(cast(convert(column1 using latin1) as binary) using utf8),
    column2=convert(cast(convert(column2 using  latin1) as binary) using utf8)

However, this doesn't change anything in my case.
So how can I achieve the conversion?
Thank you!

A: Here's how I would fix this if the special characters are actually sequences of four characters.
First, make sure the table is all converted to utf8mb4:
ALTER TABLE mytable CONVERT TO CHARACTER SET utf8mb4;

Use the REPLACE() function to fix each character one by one.
UPDATE mytable SET
  column1 = REPLACE(column1, '<e9>', 'é'),
  column2 = REPLACE(column2, '<e9>', 'é');

Be careful if you're editing this SQL query by copy & paste. Make sure you fix column2 in both the left side and right side of the =. Otherwise if you forget one, you could copy the content of column1 into column2, and lose the old content of column2.
Once you're done with é, then do a similar statement for ü:
UPDATE mytable SET
  column1 = REPLACE(column1, '<fc>', 'ü'),
  column2 = REPLACE(column2, '<fc>', 'ü');

Gradually you will clean up all these hex sequences. You can search the table to see if you have any remaining:
SELECT DISTINCT REGEXP_SUBSTR(column1, '<[[:xdigit:]]{2}>') FROM mytable
WHERE REGEXP_LIKE(column1, '<[[:xdigit:]]{2}>');

(MySQL 8.0 is required for REGEXP_SUBSTR())


text:
Q: Can't connect to GoDaddy mysqli database via PHP script Been trying for ages but just can't get my php script to connect to a mysqli database on my GoDaddy server. I've checked the username, password, database name countless times. Here's the script. Grateful for any advice.
$con = mysqli_connect("localhost","username","password","Villa1234");
$sql = "SELECT * FROM Prospects WHERE email = '$loginEmail'";
if ($result = mysqli_query($con,$sql)) {
    $rows = mysqli_num_rows($result);
    if ($rows == 1) {
        $firstRow = mysqli_fetch_assoc($result);
        $status = $firstRow['status'];
        $access = $firstRow['access'];
        $pid = $firstRow['prospect_ID'];
        if ($status == "Pending") {
            $loginResult = "pending";
        } else if ($access == "locked") {
            $loginResult = "locked";
        } else {
            $storedPassword = $firstRow['password'];
            if ($storedPassword === $password) {
                $loginResult = "success";
                $firstName = $firstRow['firstname'];
                $_SESSION['loginEmail'] = $loginEmail;
            } else {
                $loginResult = "incorrect password";
            };
        };
    } else if ($rows == 0) {
        $loginResult = "email not registered";
    };
};
mysqli_free_result($result);
mysqli_close($con);

A: You could try this: (Even if it doesn't work, it will atleast display the error you are facing)
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);
$con = new mysqli("localhost","username","password","Villa1234");

$sql = "SELECT * FROM Prospects WHERE email = ?";
$stmt = $con->prepare($sql);
$stmt->bid_param("s", $loginEmail);
$stmt->execute();
$result = $stmt->bind_result();
if($result->num_rows==1){
    while($firstRow=$result->fetch_assoc()){
        $status = $firstRow['status'];
        $access = $firstRow['access'];
        $pid = $firstRow['prospect_ID'];
        if ($status == "Pending") {
        $loginResult = "pending";
        }
        else if ($access == "locked") {
        $loginResult = "locked";
        }
        else {
        $storedPassword = $firstRow['password'];
        if ($storedPassword === $password) {
            $loginResult = "success";
            $firstName = $firstRow['firstname'];
            $_SESSION['loginEmail'] = $loginEmail;
        } else {
            $loginResult = "incorrect password";
        }
        }
    }
}
else if ($rows == 0) {
    $loginResult = "email not registered";
}
?>


text:
Q: Cartesian Product and division in relational algebra I'm pretty sure this question has been asked before, I tried looking for something like it, however, I couldn't find anything.
Given two relations $R(A,B),S(B,C)$, assuming S is not empty, prove the following equality:
$$(R \times \pi_A(S)) \div \pi_A(S) \equiv R$$
Intuitively:
It's pretty clear that we are concatenating each entry in $R$ with every entry in $\pi_A(S)$, thus when dividing we get the relation $R$.
Is my claim correct?, if so how can I prove this formally?


text:
Q: .htaccess - hidding .php and forcing trailing slash not working I'm trying to hide .php extension from my website while forcing trailing slash, I've been searching for the last few days with no success.
The site is running in a XAMPP server currently.
Here's the .htaccess file:
Options -Indexes -Multiviews +FollowSymlinks

RewriteEngine On
RewriteBase /

#removing .php extension
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/(.+)/$
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^(.*)/$ $1.php [L]

#forcing trailing slash
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .*[^/]$ $0/ [L,R=301]

ErrorDocument 404 http://localhost/404/

These links work:
localhost/about-us redirects to localhost/about-us/ which is correct but when I try to access localhost/about-us.php, it redirects to localhost/about-us/ instead of localhost/about-us/. (sorry can't post links)
How can this be fixed?

A: You just seem to have accidentally used an absolute path. Just remove the slash at the beginning of /$1/ like your other rules to make it work properly.
#removing .php extension
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ $1/ [L,R=301]


text:
Q: ¿Porque tengo este error al ocultar este MenuItem? estoy haciendo una aplicación en android donde tengo 2 Activities una es el menu principal y la otra es una pantalla de logueo, Para acceder a la actividad de logueo tengo un menu lateral cun un MenuItem que pone Log In, despues de loguearme y recibir el resultado de la Activity quiero que este se oculte y se muertre otro MenuItem para desloguearse, pero me sale un error de NullPointedException al intentar usar los metodos .setVisible() por lo que entiendo que el .findViewById() que uso para asociarlos los elementos creados en XML no esta funcionando, pero no se porque ni como puedo solucionarlo, adjunto el fragmento de codigo
Codigo del onActivityResult() donde intento ocultar un MenuItem y mostrar el otro
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == USERNAME_REQUEST && resultCode == RESULT_OK) {
        MenuItem logInItem = (MenuItem)findViewById(R.id.nav_manage);
        MenuItem logOutItem = (MenuItem) findViewById(R.id.nav_closeSession);
        logInItem.setVisible(false);  //Error aqui
        logOutItem.setVisible(true);
        user = data.getStringExtra("user");
        Log.d("Volviendo al Main ",user);
        presentarUrls(savedState,drawer);
        subtitle = (TextView) findViewById(R.id.subtitle);
        subtitle.setText(user);
    }
}

Archivo XML donde defino los items del menu
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Settings">
    <menu>
        <item
            android:id="@+id/nav_manage"
            android:icon="@drawable/ic_menu_manage"
            android:title="Login" />
        <item
            android:id="@+id/nav_closeSession"
            android:icon="@drawable/common_full_open_on_phone"
            android:title="Log Out"
            android:visible="false"></item>
    </menu>
</item>

<item android:title="Notifications">
    <menu>
        <item
            android:id="@+id/nav_share"
            android:icon="@drawable/ic_menu_share"
            android:title="Notifications" />
    </menu>
</item>

Y el codigo de Error que me saca Android Studio
Process: es.app.appff, PID: 17667
                                                                        java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { cmp=es.app.appfff/.Login (has extras) }} to activity {es.app.appfff/es.app.appfff.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setVisible(boolean)' on a null object reference
                                                                            at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
                                                                            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
                                                                            at android.app.ActivityThread.-wrap16(ActivityThread.java)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:148)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                         Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setVisible(boolean)' on a null object reference

A: Los objetos del menú no debes buscarlos con findViewById. Lo que puedes hacer es volver a crear el menú llamando a invalidateOptionsMenu(), que hará que se ejecute otra vez el método onCreateOptionsMenu y ahí sí vas a tener todos los objetos del menú para hacer con ellos lo que quieras.

A: Mira una cosa que yo hago es después de popular o inflar mi menú obtengo los items de dicho menú y los guardo como atributo en mi actividad para luego utilizarlos cuando necesite y me ha funcionado de maravilla puedes hacer algo como esto en tu caso.
MenuItem logInItem;
MenuItem logOutItem;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_prueba, menu);

    logInItem = (MenuItem) menu.findItem(R.id.nav_manage);
    logOutItem = (MenuItem) menu.findItem(R.id.nav_closeSession);

    return true;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    invalidateOptionsMenu(); // Para asegurarse que lo vuelva a crear

    /** Utilizas los items como te quieras **/
    logInItem.setVisible(false);
    logOutItem.setVisible(true);
}

A: Vale, he encontrado la solución a mi problema, con un menu lateral me referia a un NavigationView, simplemente tenia que usar el metodo NavigationView.getMenu() para sacar el Menu donde estarian los items y buscarlos
Primero, Instancio el NavigationView y lo asocio con su recurso XML
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

Despues ya puedo sacar el menu de items del NavigationView
Menu nav_menu = navigationView.getMenu();

A continuacion de ese menu de items puedo sacar los items segun sus IDs en los recursos XML
MenuItem logInItem = nav_menu.findItem(R.id.nav_manage);
MenuItem logOutItem = nav_menu.findItem(R.id.nav_closeSession);


text:
Q: Performance testing - analysing Graph results in Jmeter Am new to Jmeter and iran the test successfully. Now I'd like to understand what the results mean and what is classed as good/bad measurements, and what can be suggested to improve the results. Below is a table of the results collated in the Summary report of Jmeter.
Can anyone help me understand these results?

A: To improve results you'll want to look at the tests you run to generate these metrics and ask "does this test accurately measure your sites performance".

*

*Are you globally (or regionally) balancing your tests? if you are on the same network as your server you will not be measuring how it responds to people across the country.

*Are the tests spaced out over time, with startup delays, and such

*Is 1800 really enough users to test the site

*Are all the pages tested

*Are you "Retrieving All Embedded Resources" in your http requests

*If you rely on Javascript, and the use of Javascript to pull data into your pages (like with AJAX) you should test with script recording because just a HTTP request will not test data that is AJAX'ed in later.

Are your results good or bad First you'll want to have a good foundation on how response time impacts how long users stay on your site. Here is a starter
https://blog.kissmetrics.com/loading-time/?wide=1
e.g. If your pages load in 3 seconds 10% of users leave because thats too long for them, well, you have to decide if that is good, or bad for your company.
Understanding the graph Here is some info from the jmeter site on this particular graph:
http://jmeter.apache.org/usermanual/component_reference.html#Graph_Results
at a glance Generally, it looks like your response time is fine, it almost seems so low that it hits you may not be covering everything necessary to test (see "to improve results") I do see your deviation is increasing as load increases, so there may be some small issue related to that.

A: *

*JMeter comes with various samplers that can be used for analysis. You can have some additional and useful samplers from JMeter Plugins site.

*In order to begin with analysis you need to have a look at 90th Percentile Response Time for each request.

*Check if response time meets SLA. Also check for throughput you are getting.

*Have different sets of test so that you can find relation with growing number of users, response time and throughput.

*Aggregate Report Sampler can be used for this. If you find some requests are not meeting SLAs then run test with those requests, add some profilers, take thread dumps to analyze the bottleneck.


text:
Q: Securing IP check php I have
$result = mysqli_query($mysqli,"SELECT * FROM ".MYSQLBTCTABLE." WHERE ip = '" . $_SERVER['REMOTE_ADDR'] . "' AND date = '".date("Y-m-d")."' AND time = '".date("D")."'") or die(mysqli_error());

How can I secure the  $_SERVER['REMOTE_ADDR']  so it checks not only the user ip/proxy but also the socks ip so they can't abuse my code by changing IP?
also I found this code:
                function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

Will it work so if I put WHERE ip = '".($ip)."'?

A: You can not do that in common case

*

*You can't be sure if user is using proxy: it can be anonymous proxy

*You can't be sure if he is using computer device

*You can't be sure that he is human: it may be request via cURL or similar stuff

So that's the reality of the Internet. You can not rely on any information that came from client side. If you're suspecting that user changed his IP address - then hide critical part behind authentication. Thus, you'll be able to identify user by his login in your web-application.


text:
Q: Three.js animating with speed and friction Im trying to make a 3D spinning wheel animation in three.js, where i press a key to accelerate the wheel and when i release the key it decelerates by friction until it stops.
I've experimented with different examples on this site but i just cant get it to run properly. I understand the physics but im having a hard time implementing it in the render loop.
Also in the future i would like to implement a deceleration curve.
Does anyone have a clue on how to make something like this?
Thanks in advance
Edit:
Finally got something working kinda like i want it! This is my code:`

var container, outputLeap;
var camera, scene, renderer;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

var sceneRoot = new THREE.Group();
var wheelSpin = new THREE.Group();
var wheelMesh;

var clock = new THREE.Clock();

var speed = 0.1;
var decelRate = 100;

function onWindowResize() {
  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);
}

function onWindowResize() {
  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);
}

function init() {
  outputLeap = document.getElementById('output-leap');
  container = document.getElementById('container');

  camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 0.1, 80);

  scene = new THREE.Scene();

  var geometryWheel = new THREE.CylinderGeometry(3, 3, 0.05, 32);
  var materialWheel = new THREE.MeshBasicMaterial({
    color: 0xffff00,
    wireframe: true
  });
  var wheelMesh = new THREE.Mesh(geometryWheel, materialWheel);
  scene.add(sceneRoot);

  sceneRoot.add(wheelSpin);
  wheelSpin.add(wheelMesh);

  renderer = new THREE.WebGLRenderer();
  renderer.setClearColor(0x000000);
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  container.appendChild(renderer.domElement);

  window.addEventListener('resize', onWindowResize, false);
}

function render() {

  var time = clock.getElapsedTime();
  var delta = clock.getDelta();

  camera.position.y = 15;

  if (speed > 0)
    speed = Math.max(0, speed - decelRate * delta);
  else
    speed = Math.min(0, speed + decelRate * delta);

  camera.lookAt(scene.position);
  wheelSpin.rotation.y -= speed;

  outputLeap.innerHTML = 'Rotation: ' + speed;

  renderer.render(scene, camera);
}

function animate() {
  requestAnimationFrame(animate);
  render();
}

init();
animate();
<!DOCTYPE html>

  <title></title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

It seems like delta was the key to making the animation work. But now i wonder why? I also wonder how you translate the speed and deceleration variables into more "realistic" values?

A: There are many ways to simulate friction and related accelerations.
Here is one via simple integration.
Friction (drag) is a force related to a exponent of velocity, that force acts against the mass of the moving (spinning) object.
We can ignore the fact that we have a spinning object as the location of the friction is at the center. Also one expects that the axis is rotating on a bearing or lubricated shaft, which for the most part can be described as drag.
If we remove all the coefficients, areas, viscosity, rolling friction, and blah blah from the drag function (they are all linear in relation) and look at the core function. drag = 1/2 * v*v where v is velocity. Multiply that by some adjustable coefficient and we get the force.
The velocity is the movement of the part of the wheel touching the axle and we get from the radius of the axle and rate of spin.
Thus we can set up the sim.
wheel = {
   mass : 100,  // mass
   axleRadius : 40,  // the lower the radius the less the drag
   deltaRot : 0.3,  // rate of turn per unit time.
   dragCoff : 0.1, //coefficients of drag
}

Get the velocity against the axle
var velocity = wheel.deltaRot * axleRadius;

Get the drag from that velocity
var drag = 0.5 * velocity * velocity * wheel.dragCoff;

Apply that drag (as a force) on the wheel's mass f = ma
var accel = drag / wheel.mass;

Convert the acceleration back to velocity on the surface touching the axle
wheel.deltaRot -= accel / wheel.axleRadius;

And you have a good approximation of a wheel turning on a axle.
The axle radius has a big impact on the drag. The greater the radius the greater the drag.  The dragCoff is all the factors we did not include, like surface area touching the axle, bearing rolling resistance, lubrication viscosity. They are all linear relations (as I assume you will not be changing the axle radius during the simulation) compared to the velocity squared so can be bundled as one number to suit your needs (less than one of course)
And the Mass, the greater the mass the longer the wheel will spin.
As a simple demo the function has been simplified a little

var wheel = {
   mass : 100,
   radius : 100,  // has no effect on the sim
   axleRadius : 30,
   deltaRot : 1.3,
   dragCoff : 0.2, //coefficients of drag
   rotation : 0,
}
function updateWheel(w){
    w.deltaRot -= ((0.5 * Math.pow(w.deltaRot * w.axleRadius,2) * w.dragCoff) / w.mass) / w.axleRadius;
    w.rotation += w.deltaRot;
}
function drawCircle(radius,x=0,y=0){
    ctx.beginPath();
    ctx.arc(0,0,radius,0,Math.PI * 2);
    ctx.fill();
}
function display() {
    ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
    ctx.globalAlpha = 1; // reset alpha
    ctx.clearRect(0, 0, w, h);
    updateWheel(wheel);
    ctx.setTransform(1,0,0,1,cw,ch); // draw at center of canvas
    ctx.rotate(wheel.rotation);
    ctx.fillStyle = "black";
    drawCircle(wheel.radius);
    ctx.fillStyle = "red";
    drawCircle(wheel.radius-10);
    ctx.fillStyle = "black";
    ctx.fillRect(0,-10,wheel.radius-5,20);
    ctx.fillStyle = "white";
    drawCircle(wheel.axleRadius+2);
    ctx.fillStyle = "black";
    drawCircle(wheel.axleRadius);
}

var w, h, cw, ch, canvas, ctx, globalTime = 0, firstRun = true;
;(function(){
    var  createCanvas, resizeCanvas;
    createCanvas = function () {
        var c, cs;
        cs = (c = document.createElement("canvas")).style;
        cs.position = "absolute";
        cs.top = cs.left = "0px";
        cs.zIndex = 1000;
        document.body.appendChild(c);
        return c;
    }
    resizeCanvas = function () {
        if (canvas === undefined) {
            canvas = createCanvas();
        }
        canvas.width = innerWidth;
        canvas.height = innerHeight;
        ctx = canvas.getContext("2d");
        cw = (w = canvas.width) / 2;
        ch = (h = canvas.height) / 2;
        wheel.deltaRot = 1.3;
    }
    function update() { // Main update loop
        display(); // call demo code
        requestAnimationFrame(update);
    }
    setTimeout(function(){
        resizeCanvas();
        window.addEventListener("resize", resizeCanvas);
        requestAnimationFrame(update);
    },0);
})();


text:
Q: How to add icons to post listing (edit.php) in admin Is there a filter or something to add these kind of icons based categories and what not to all posts?

I can't seem to find one. I tried the_title but ofc that gets sanitized and just displays the html..
Thanks!

A: We can style the table with CSS and dashicons.
Example:
For our video category, we can use for example:
.edit-php .wp-list-table tr.category-video td.post-title strong:before {
    content: "\f126";
    color: #ccc;
    display: inline-block;
    width: 20px;
    height: 20px;
    margin: 0 4px;
    font-size: 20px;
    line-height: 20px;
    font-family: "dashicons";
    font-weight: normal;
    vertical-align: top;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

where we target the tr.category-video class.
Just check out how it's used in the backend, to get an idea of the CSS attributes.
We can get the list of dashicons here.
Update:
Here's it the part of the WP_Posts_List_Table  class that displays the post format icon:
$pad = str_repeat( '— ', $level );
echo "";
if ( $format = get_post_format( $post->ID ) ) {
    $label = get_post_format_string( $format );

    echo '
             $format, 'post_type' => $post->post_type ), 'edit.php' ) ) . '"
             class="post-state-format post-format-icon post-format-' . $format
             . '" title="' . $label . '">' . $label . ": ";
}


text:
Q: Return an object with properties from function parameter list I'm trying to create a function that constructs and returns an object with properties that match the array of strings passed in the params.
type Foods = 'apple' | 'banana' | 'pear';

function foodObjects<K extends Foods>(foods: Foods[]): Record<K, number> {
    const ret = {};
    foods.forEach((food, i) => {
        ret[food] = i;
    })
    return ret;
}

foodObjects(['apple', banana']); // should return { apple: 0, banana: 1 }

In this simple example, you pass it an array of fruits and it returns an object with the fruit names as keys. However, I get a warning when defining the ret variable (const ret = {};):

Type '{}' is not assignable to type 'Record<K, number>'

I can resolve that error with the as keyword, but this doesn't feel correct:
const ret = {} as Record<K, number>;

A: If you want an array to turn into an object, your best bet is to reduce it:
type Foods = "apple" | "banana" | "pear";

function foodObjects<K extends Foods>(foods: Foods[]): Record<K, number> {
  return foods.reduce((acc, food, i) => ({ ...acc, [food]: i }), <Record<K, number>>{});
}

console.log(foodObjects(["apple", "banana"])); // should return { apple: 0, banana: 1 }

Since it was pointed out that casting is not super ideal, here is a version that does not need casting:
type Foods = "apple" | "banana" | "pear";

type FoodObjects = {
  [K in Foods]: number;
};

function foodObjects(foods: Foods[]): FoodObjects {
  const entries = foods.map((food, i) => [food, i]);
  return Object.fromEntries(entries);
}


text:
Q: ReactJS hooks: update state inside condition everyone!
Can some one tell me if updating state inside if / else statement is acceptable by React rules.
In particular updating state based on the result of a promise inside of the condition.
For example:
import {useState} from "react";
import {somePromiseOne, somePromiseTwo} from "./example";

function example(){

  const [state, setState] = useState();

  if(true){
    somePromiseTwo().then((result) => setState(result));
  }else{
    somePromiseOne().then((result) => setState(result));
  }

}

A: The Rules of hooks states that you must only call a hook at the top level, meaning you can't call it inside a conditional branch. However, it is perfectly fine to call the setState function it inside a branch because it is not a hook itself, just a function to trigger a state update.
So it is fine to do A but not B
// A: Valid
function example(){
  const [state, setState] = useState();
  useEffect(() => {
    if(true){
      somePromiseTwo().then((result) => setState(result));
    }else{
      somePromiseOne().then((result) => setState(result));
    }
  }, […]);
}

// B: not valid

function example(){
  if(true){
    const [state, setState] = useState();
  }else{
   // …
  }
}

However, note that I put your async logic inside a useEffect hook. Why? Because your function can be called an arbitrary number of times by React, and you don't want the async logic to trigger every time it is called. The idiomatic way to control when and how often it is called in a custom hook/component in React is by using useEffect. You can read more about it here

A: It is acceptable to use state inside condition. If you want to know what are rules of React hooks you can read about it here:
https://reactjs.org/docs/hooks-rules.html

A: Yes why not :
const promiseFunc = isCondidtionValid ? somePromiseTwo : somePromiseOne;
promiseFunc().then(result => setState(result));

A: Yes, it is acceptable. For example:
Promise.resolve().then(() => {
  setState("newState");
});

would work just fine.


text:
Q: fetching substring with a condition from another df I have 2 data sets, 1 with only address like this
import pandas as pd
import numpy as np

df = pd.DataFrame({"Address": ["36 omar st, pal, galambo","33 pom kopd malan", "15 kop st,dogg, ghog", "23 malo st, pal, kola"]})

                    Address
0  36 omar st, pal, galambo
1         33 pom kopd malan
2      15 kop st,dogg, ghog
3     23 malo st, pal, kola

and the other is a dataset with every state and the cities inside of it
df2 = pd.DataFrame({"State": ["galambo", "ghog", "ghog", "kola", "malan", "malan"], "City": ["pal", "dogg", "kopd", "kop", "pal", "kold"]})

     State  City
0  galambo   pal
1     ghog  dogg
2     ghog  kopd
3     kola   kop
4    malan   pal
5    malan  kold

I'm trying to fetch state name and city name out of each address, so I tried this
df["State"] = df['Address'].apply(lambda x: next((a for a in df2["State"].to_list() if a in x), np.nan))
df["City"] = df['Address'].apply(lambda x: next((a for a in df2["City"].to_list() if a in x), np.nan))

                    Address    State  City
0  36 omar st, pal, galambo  galambo   pal
1         33 pom kopd malan    malan  kopd
2      15 kop st,dogg, ghog     ghog  dogg
3     23 malo st, pal, kola     kola   pal

but as you see, the rows 1,3 are incorrect because according to df2 the State malan has no City called kopd, and State kola has no City called pal
so how can I make the output shows only the cities that are in the States as suggested in df2?
Update:
Expected output
                    Address    State  City
0  36 omar st, pal, galambo  galambo   pal
1         33 pom kopd malan    malan  NaN
2      15 kop st,dogg, ghog     ghog  dogg
3     23 malo st, pal, kola     kola   NaN

A: You can extract the last matching state/city name, then perform a merge to replace the invalid cities by NaN:
# craft regexes
regex_state = f"({'|'.join(df2['State'].unique())})"
regex_city = f"({'|'.join(df2['City'].unique())})"

# extract state/city (last match)
df['State'] = df['Address'].str.findall(regex_state).str[-1]
df['City'] = df['Address'].str.findall(regex_city).str[-1]

# fix city
df['City'] = df.merge(df2.assign(c=df2['City']), on=['City', 'State'], how='left')['c']

Output:
                    Address    State  City
0  36 omar st, pal, galambo  galambo   pal
1         33 pom kopd malan    malan   NaN
2      15 kop st,dogg, ghog     ghog  dogg
3     23 malo st, pal, kola     kola   NaN


text:
Q: Converse of Kolmogorov's Zero-One Law The Kolmogorov zero-one law says that for a sequence of independent events, any event belonging to the tail $\sigma$-field has probability either $0$ or $1$. However the converse is not true, because you can find dependent sequence of events, for which the tail events have probability zero or one. Two such interesting examples i found are:

*

*Consider a probability space $(\Omega,\mathcal{A},P)$Let $E_1,E_2,\cdots$ be a sequence of events defined as
$$E_1=E_2=A,~~E_3=E_4=\cdots=\phi$$
where $\phi$ denotes the empty set, and $A\in\mathcal{A}$.

*Consider a prob space $(\Omega,\mathcal{A},P)$, and take any independent sequence of events, $\{B_n\}$. Then construct an interleaving sequence of events, $\{E_n\}$ as
$$E_1=B_1,E_2=B_2,E_3=B_1\cup B_2,E_4=B_3,E_5=B_2\cup B_3,E_6=B_4,E_7=B_3\cup B_4,\cdots$$ Then $\{E_n\}$ is a sequence of dependent events and the tail $\sigma$-field generated by $\{E_n\}$ is same as that generated by $\{B_n\}$ and hence every tail event has probability either $0$ or $1$.

Seeing these examples I guess that if every event in the tail $\sigma$-field of a sequence of events has probability either $0$ or $1$, then there must exist a sequence of independent events from the same probability space which has the same tail $\sigma$-field.
Is this true, or there is some very obvious counterexample?


text:
Q: Dynamically grab form ID, turn off all buttons in parent form I've succeeded in dynamically getting the form ID, but can't seem to turn off the buttons once one of them is clicked. I am trying to use the .prop to turn off the buttons.
As people make choices by clicking on buttons, I want to disable the previous choices.
Code:

function get_parentID(clicked_id) {
  var parent_div = ('#' + clicked_id);
};

function set_path(clicked_id) {
  var divX = ('#' + clicked_id);
  $(divX + '_z').show('slowly');
  //$(divX).prop('disabled', true);
  disable_btn();
}

function disable_btn() {
  $(parent_div + " :input").prop('readonly', true);
};
.parent {
  border: 2px solid blue;
  margin: 10px;
  padding: 10px;
}
.child {
  border: 2px solid red;
  margin: 10px;
  padding: 10px;
  display: none;
  background-color: yellow;
}

Intro Level

  <form id="level_1_form">
    <input type="button" id="level_1a" value="Choice A" onclick="get_parentID(this.parentNode.id);set_path(this.id);">
    <input type="button" id="level_1b" value="Choice B" onclick="set_path(this.id);get_parentID(this.parentNode.id);">
  </form>

This is Level 1 A

    <form id="level_2a_form">
      <input type="button" id="level_2a" value="Choice A-This go nowhere" onclick="get_parentID(this.parentNode.id);set_path(this.id);">
      <input type="button" id="level_1b" value="Choice B-This go nowhere" onclick="set_path(this.id);get_parentID(this.parentNode.id);">
    </form>

This is Level 1 B

    <form id="level_2b_form">
      <input type="button" id="level_2a" value="Choice A-This go nowhere" onclick="get_parentID(this.parentNode.id);set_path(this.id);">
      <input type="button" id="level_2b" value="Choice B-This go nowhere" onclick="set_path(this.id);get_parentID(this.parentNode.id);">
    </form>

A: You don't need to get the parent ID, just use jQuery DOM traversal:
$(":button").click(function() {
    $(this).closest("form").find(":input").not(this).prop('readonly', true);
});

A: I'm not really sure if THIS is what you want, you tell me!

function toggleContent(button) {
    button += '_z';
    $('.parent > div').each(function() {
        if ($(this).attr('id') == button) {
            $(this).show('slowly');
        }
    });
}

$(document).on('click', '.parent > form > input', function (e) {
    e = $(this).attr('id');
    $(this).prop('disabled', true);
    toggleContent(e);
});

$('.parent > div').hide();

Intro Level

    <form id="level_1_form">
        <input type="button" id="level_1a" value="Choice A" />
        <input type="button" id="level_1b" value="Choice B" />
    </form>

This is Level 1 A
        <form id="level_2a_form">
            <input type="button" id="level_1a_1a" value="Choice A-This go nowhere" />
            <input type="button" id="level_1a_1b" value="Choice B-This go nowhere" />
        </form>

This is Level 1 B

        <form id="level_2b_form">
            <input type="button" id="level_1b_1a" value="Choice A-This go nowhere" />
            <input type="button" id="level_1b_1b" value="Choice B-This go nowhere" />
        </form>

A: You can use the DOM API to select the form elements and iterate through them, attaching a click handler along the way. Then in the click handler you can find all buttons within the form and disable the any that were not clicked. This requires no external libraries.
You need to remove all of the onclick="" attributes from your HTML code as this binds the event handler to the form directly.
(Demo)
/*    Select the forms and iterate through each form, attaching an event
 *    handler to the click event as you go. You can change the selector
 *    to be more specific if you have other forms on the page that you
 *    don't want to be affected
 */
var forms = document.querySelectorAll('form'), form, i;
for(i = 0; (form = forms[i]); i++) {
    form.onclick = handleClick;
}

/*    This is the function that handles the click event. First we check
 *    to make sure the clicked element is a button, then get the parent
 *    element and select all buttons contained within. From there we
 *    iterate through the buttons and check to make sure the button is
 *    not the clicked element, then disable it if not.
 */
function handleClick(e) {
    if(e.target.type === "button") {
        var parent = e.target.parentNode;
        var buttons = parent.querySelectorAll('input'), button, j;

        for(j = 0; (button = buttons[j]); j++) {
            if(e.target.isSameNode(button)) continue;
            button.disabled = true;
        }
    }
}


text:
Q: a tag seen twice on iPad I have created a tag which on click opens a simple popup asking for an email id to retrieve the password. Now, when I click on forget password it shows me the forget link two times. Below is my code.
Forgot Password?

Given is code for JQuery
$(document).ready(function () {
            $("#username").focus();
            $('a[href="#forgot_password"]').click(function () {
                if ($("#username").val().length > 0) {
                    try {
                        var retVal = "";
                        $("#errMsg").text('');
                        $("#errMsg").removeClass("error");
                        var urlCreate = "login.aspx?method=ForgotPasswordSecurityQuestion&userName=" + String($("#username").val());
                        $.ajax({
                            type: "POST",
                            url: urlCreate,
                            contentType: "text/plain",
                            dataType: "",
                            success: function (response) {
                                //alert(response);
                                if (String(response).length >= 0) {

                                    if (response.indexOf('not found') > 0) {
                                        ShowError(response);
                                    }
                                    else {

                                        var returnVal = response.split("|");
                                        var re = new RegExp('_', 'g');
                                        $('#securityQuestion').text((returnVal[1]).replace(re," ") + "?");

                                        securityAnswer = returnVal[2];
                                        userID = returnVal[0];
                                        ShowSplashScreen("splashScreenForgotPassword");
                                    }
                                }
                                else {

                                    ShowError("error occurred while processing your request");
                                }
                            },
                            error: function (response) {
                                ShowError(response);

                            }
                        });
                    }
                    catch (err) {
                        alert("Catch" + err);
                    }

                }
                else {
                    ShowError("Please enter user name");
                }
            });
        });

A: I think your href and id both are conflicting and generating issue.
Please try with the below code.
HTML:
Forgot Password?

jQuery:
$(document).ready(function () {
        $("#username").focus();
        $('#forgotPassword').click(function () {
            // your code here
        });
});


text:
Q: Install COD file on BlackBerry OS 10
I have developed BlackBerry Apps using Java SDK till BBOS 10 got released. But the recent BBOS 10 released doesn't provide Java SDK platform for developing the applications.
So is there any way that I can run my previously developed applications(using Java SDK 5.0,6.0,7.0,7.1) on the BBOS 10 simulator/device.
Is BlackBerry on the process of releasing the Java SDK in the near future.??
Thanks.

A: If you wrote WebWorks application then you could recompile it to BB 10. Otherwise there is no chance to run your app on the BB 10. Unfortunately!


text:
Q: Parser for json Object in java I am trying to create a common parser in java.I am passing json object from different class based on my need.But parsing doesnot works for me.Can anybody help me to make a JSONObject parser in java.Any help will be highly appreciable....
This is my code for common parser
public JSONObject jsonParser(JSONObject objJson){
        //JSONObject myjson = new JSONObject(objJson);
        JSONArray the_json_array = objJson.getJSONArray("profiles");
        JSONObject SnapshotRequest= objJson.g;
        Iterator x = SnapshotRequest.keys();
        JSONArray jsonArray = new JSONArray();

        while (x.hasNext()){
            String key = (String) x.next();
            jsonArray.put(songs.get(key));
        }

}

In this code I am getting an error that need to cast.
JSONArray the_json_array = objJson.getJSONArray("profiles");
But casting won't work.


text:
Q: How to Use SharedPreferences in Retrofit2 onResponse method? I am trying to get a user's login credentials while he signing in. I am sending to my database User_Email and User_Password then returning a Json like below. Actually the problem is simple but i dont know the solution, i am kinda new. I am %100 sure the error in my onResponse method. Because I am seeing this successfull response Toast, so i am getting successfull response but the problem here i dont know how to get this Json response into sharedpreferences. Thanks.
{
    "User": [
        {
            "SSN": "123456789",
            "FirstName": "Furkan",
            "User_Role": "1"
        }
    ]
}

And my model class for this response is :
public class UserList {

    @SerializedName("User")
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

public class User {
    @SerializedName("SSN")
    public String sSN;
    @SerializedName("FirstName")
    public String firstName;
    @SerializedName("User_Role")
    public intuserRole;

    public String getsSN() {
        return sSN;
    }

    public void setsSN(String sSN) {
        this.sSN = sSN;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public int getUserRoleTypeId() {
        return userRoleTypeId;
    }

    public void setUserRoleTypeId(int userRoleTypeId) {
        this.userRoleTypeId = userRoleTypeId;
    }
}

I am trying to add these userRoleTypeId, firstName and sSN to SharedPreferences in my call.enqueue onResponse. But i could not figure it out.
Here is my LoginActivity.class for the login:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    Button bSignUp, bLogin;
    EditText etPassword, etEmail;
    private int userRoleTypeId;
    private SharedPreferences sharedPreferences;
    private ProgressDialog progressDialog;
    Intent intent;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        bSignUp = (Button) findViewById(R.id.bSignUp);
        bLogin = (Button) findViewById(R.id.bLogin);
        bSignUp.setOnClickListener((View.OnClickListener) this);
        bLogin.setOnClickListener((View.OnClickListener) this);
        etPassword = (EditText) findViewById(R.id.etPassword);
        etEmail = (EditText) findViewById(R.id.etEmail);
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Logging in");
        progressDialog.setMessage("Please wait ....");

        sharedPreferences = getApplicationContext().getSharedPreferences("LoginActivity",MODE_PRIVATE);

 bLogin.setOnClickListener(this);
    }

 @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bSignUp:
                Intent SignUpIntent = new Intent(this, SignUpActivity.class);
                startActivity(SignUpIntent);
                break;
            case R.id.bLogin:
                String email = etEmail.getText().toString();
                String password = etPassword.getText().toString();
                if (!email.isEmpty() && !password.isEmpty()) {
                    progressDialog.show();
                    loginProcess(email, password);
                    this.userRoleTypeId = sharedPreferences.getInt(Constants.USERROLE, 0);
                    if (userRoleTypeId == 1) {
                        intent = new Intent(this, OrganizerHomeActivity.class);
                        startActivity(intent);
                    } else if(userRoleTypeId == 2 || userRoleTypeId == 3) {
                        intent = new Intent(this, UserHomeActivity.class);
                        startActivity(intent);
                    }
                    else{
                        Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
                }

                break;
            default:
                break;
        }
    }

 private void loginProcess(String email, String password) {
        LoginAPI loginAPI = RetrofitService.getClient().create(LoginAPI.class);
        retrofit2.Call<UserList> call = loginAPI.loginUser(email,password);
        call.enqueue(new Callback<UserList>(){
            @Override
            public void onResponse(Call<UserList> call, Response<UserList> response) {
                //I am sure the fault in here. In below i tried to take Json response and fetch it into the Shared Preferences.
                UserList userLists = response.body().getUser();
                if(response.isSuccessful()){
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean(Constants.IS_LOGGED_IN, true);
                   // editor.putString(Constants.NAME, userLists.getFirstName);
                    //editor.putString(Constants.SSN, userLists.getsSN);
                   // editor.putInt(Constants.USERROLE, userLists.getuserRoleTypeId);
                    editor.apply();

    // I am seeing this successfull response toast, so i am getting successfull response but the problem here i dont know how to get this Json response into sharedpref.
Toast.makeText(LoginActivity.this, "successfull response", Toast.LENGTH_SHORT).show();
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<UserList> call, Throwable t) {
                Toast.makeText(LoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
        });

    }
}

A: Try this
    if(response.isSuccessful()){
                List<User> userLists = response.body().getUser();
    SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
    SharedPreferences.Editor prefEditor = settings.edit();
    editor.putBoolean(Constants.IS_LOGGED_IN, true);
    prefeditor.putString("UserName", userLists.getUser().getFirstName());
    prefEditor.putString(Constants.SSN, userLists.getUser().getsSN());
    prefEditor.putInt(Constants.USERROLE, userLists.getUser().getUserRoleTypeId());
    prefEditor.commit();
            }


text:
Q: DELETE request pending for a long time then fails I am playing with nodejs/expressjs/angularjs with MondgoDB on Ubuntu 12.04. I was going through this example. When I tested this locally, deleting a wine worked just fine. But after deploying to Ubuntu 12.04 box, DELETE request failed. I am using nginx as proxy and running nodejs on port 3000.
I tried to stop nginx and running it directly on nodejs on different port. It didn't help; proves me that this problem has nothing to do with nginx.
But using curl I was able to delete an item. e.g. curl -i -X DELETE http://localhost:3000/wines/5069b47aa892630aae000007.
So am I missing something in middle-tier(expressjs)? Here is my sandbox.


text:
Q: Pulling first level relationship via Standard Controller If you try to test the following visualforce page:
<apex:page standardController="Account" >
     <apex:repeat var="contact" value="{!record.Contacts}">
        <apex:outputText value="{!contact.Name}">example</apex:outputText>
    </apex:repeat>
</apex:page>

You get an error that says:
SObject row was retrieved via SOQL without querying the requested field: Account.Contacts
Why is this not possible and what is the correct approach? Shall we use custom controllers or controller extensions?

A: You can do this, you just need to refer to the Account differently. It works like this:
<apex:page standardController="Account" >
    <apex:repeat var="contact" value="{!Account.Contacts}">
        <apex:outputText value="{!contact.Name}">example</apex:outputText>
    </apex:repeat>
</apex:page>

See https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_std_access_data.htm

For example, a page that uses the Account standard controller can use
  {!account.name} to return the value of the name field on the account
  that is currently in context.


text:
Q: sty file not found on WSL I want to install fltpage package (https://ctan.org/pkg/fltpage) for my thesis.
I'm using Windows 10 LTSC and NVIM v0.3.4 inside Windows subsystem for linux and TeX 3.14159265 (TeX Live 2019) with kpathsea version 6.3.1.
I have tried to put the .sty file everywhere /home/myhome/txmf/ftlpage/fltpage.sty, in /home/myhome/txmf/tex/latex/ftlpage/fltpage.sty , in /usr/local/texlive/2019/texmf-dist/tex/latex/fltpage/fltpage.sty
After each try I typed sudo $(which mktexlsr)
but I still have the same message File 'fltpage.sty' not found
I will appreciate any help thank you very much in advance !
And for info the output of kpsewhich --var-value TEXMF is
{{}/home/vincent/.texlive2019/texmf-config,/home/vincent/.texlive2019/texmf-var,/home/vincent/texmf,!!/usr/local/texlive/texmf-local,!!/usr/local/texlive/2019/texmf-config,!!/usr/local/texlive/2019/texmf-var,!!/usr/local/texlive/2019/texmf-dist}

EDIT : Solution is to place the file like
/usr/local/texlive/texmf-local/tex/latex/fltpage/fltpage.sty AND to remove ls-R file in the texmf tree. Thank you @Ulrike Fischer !

A: The solution is to place the file like /usr/local/texlive/texmf-local/tex/latex/fltpage/fltpage.sty
AND to remove ls-R file in the texmf tree.
Thank you @Ulrike Fischer !


text:
Q: Fluent Nhibernate 1.0 - Specify foreign key constraint name between class and joined subclass I think this should be simple, but I can't figure out how to do it.  Suppose I have the following maps:
public class AnimalMap : ClassMap<Animal> { Id( x => x.Id); }

public class CatMap: SubclassMap<Cat> {
    Extends<AnimalMap>();
    Map(x => x.IsDomestic);
}

Which creates tables as I expect:
Animal
------
Id

Cat
----
AnimalId : FK to Animal (named FK3500ABA0D)
IsDomestic

As noted, the FK gets generated by the db and ends up as FK3500ABA0D.  All I want to do is set the name of that constraint, but I can't find how to do it via Fluent NHibernate (or actually even plain NHibernate, for that matter).
So, what am I missing?

A: Fluent NH does allow this:
public class ReferenceConvention : IReferenceConvention{
     public void Apply(IManyToOneInstance instance) {
          instance.ForeignKey(string.Format("FK_{0}_{1}",
               instance.EntityType.Name,
               instance.Name));
     }
}

You'd also need to implement IHasManyConvention and IHasManyToManyConvention in the same way as above.

A: I don't know if FluentNH supports it, but the XML is simple:
<joined-subclass name="Cat">
  <key column="AnimalId" foreign-key="NameOfTheFK"/>
</joined-subclass>

A: I had the same problem, the following works well for me:
public class JoinedSubclassForeignKeyConvention : IJoinedSubclassConvention
{
    public void Apply(IJoinedSubclassInstance instance)
    {
        if (instance.Type.BaseType != null)
            instance.Key.ForeignKey(string.Format("FK_{0}_{1}", instance.EntityType.Name, instance.Type.BaseType.Name));
    }
}

Your foreign key constraint would then be named as FK_Cat_Animal


text:
Q: How to change language automatically using user browser language Yii2? A user can change the language manually from the website. But for better user experience, I would like to change it automatically based on the users' browser language. I have a global Controller and can use init() and then redirect.
Please give me tips to do it right.

A: You should remember the chosen language for a user, if they had selected one previously, I store this in the database, in a user_preference table.
Then you need to intercept the request, it can be done in the application configuration file, using the on beforeRequest property.
If you don't have stored a preference for the current user, or the user is a guest, use the browser language to set the application language.

Configuration file

use app\models\User;

...

'on beforeRequest' => function ($event) {

    $user_lang = '';

    if (!Yii::$app->user->isGuest) {

        // Check if you have stored a language preference for the user
        $user_lang = User::findIdentity(Yii::$app->user->id)->getUserPreference('lang');

    }

    if (!empty($user_lang)) {

        // If you have a stored preference for the user, use it
        Yii::$app->language = $user_lang;

    } else {

        // If you don't have a preference, use the browser language
        // Get the browser language from the headers
        $browser_lang = Yii::$app->request->headers->get('accept-language');

        // Alternatively get the headers from the event
        // $event->sender->request->headers->get('accept-language')

        // Calculate the language you want to provide based on the browser language
        $language_code = LanguageHelper::calculatei18nCode($browser_lang);

        Yii::$app->language = $language_code;

    }
},
...

If you wanted to keep your configuration file clean, you could use filters instead to intercept the request.
Your LanguageHelper::calculatei18nCode($browser_lang) method would try to find a match for the browser language in the available languages, if it didn't find one it could return the closest match, or the default application language.

LanguageHelper

public static function calculatei18nCode ($browser_lang) {

    // For example, if you are offering one translation file for french
    if (stripos($browser_lang, 'fr')) {
        return 'fr';
    }

    ...

    return 'en';
}


text:
Q: How to make the bottom button follow the keyboard display in SwiftUI With the help of the following, I was able to follow the button on the keyboard display.
However, animation cannot be applied well.
How to show complete List when keyboard is showing up in SwiftUI
import SwiftUI
import Combine
import UIKit

class KeyboardResponder: ObservableObject {
    let willset = PassthroughSubject<CGFloat, Never>()
    private var _center: NotificationCenter
    @Published var currentHeight: CGFloat = 0
    var keyboardDuration: TimeInterval = 0

    init(center: NotificationCenter = .default) {
        _center = center
        _center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        _center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    deinit {
        _center.removeObserver(self)
    }

    @objc func keyBoardWillShow(notification: Notification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            currentHeight = keyboardSize.height

            guard let duration:TimeInterval = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return }
            keyboardDuration = duration
        }
    }

    @objc func keyBoardWillHide(notification: Notification) {
        currentHeight = 0
    }
}

import SwiftUI

struct Content: View {
    @ObservedObject var keyboard = KeyboardResponder()

    var body: some View {
        VStack {
            Text("text")

            Spacer()

            NavigationLink(destination: SubContentView()) {
                Text("Done")
            }
        }
        .padding(.bottom, keyboard.currentHeight)
        animation(Animation.easeInOut(duration: keyboard.keyboardDuration))
    }
}

enter image description here

A: Your main problem, is that you are using an implicit animation. Not only it may be animating things you may not want to animate, but also, you should never apply .animation() on containers. Of the few warnings in SwiftUI's documentation, this is one of them:

Use this modifier on leaf views rather than container views. The
  animation applies to all child views within this view; calling
  animation(_:) on a container view can lead to unbounded scope.

Source: https://developer.apple.com/documentation/swiftui/view/3278508-animation
The modified code removes the implicit .animation() call and replaces it with two implicit withAnimation closures.
I also replaced keyboardFrameEndUserInfoKey with keyboardFrameEndUserInfoKey, second calls were giving useless geometry.
class KeyboardResponder: ObservableObject {
    let willset = PassthroughSubject<CGFloat, Never>()
    private var _center: NotificationCenter
    @Published var currentHeight: CGFloat = 0
    var keyboardDuration: TimeInterval = 0

    init(center: NotificationCenter = .default) {
        _center = center
        _center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        _center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    deinit {
        _center.removeObserver(self)
    }

    @objc func keyBoardWillShow(notification: Notification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

            guard let duration:TimeInterval = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return }
            keyboardDuration = duration

            withAnimation(.easeInOut(duration: duration)) {
                self.currentHeight = keyboardSize.height
            }

        }
    }

    @objc func keyBoardWillHide(notification: Notification) {
        guard let duration:TimeInterval = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return }

        withAnimation(.easeInOut(duration: duration)) {
            currentHeight = 0
        }
    }
}

struct ContentView: View {
    @ObservedObject var keyboard = KeyboardResponder()

    var body: some View {

        return VStack {
            Text("text \(keyboard.currentHeight)")

            TextField("Enter text", text: .constant(""))
            Spacer()

            NavigationLink(destination: Text("SubContentView()")) {
                Text("Done")
            }
        }
        .padding(.bottom, keyboard.currentHeight)
//        .animation(Animation.easeInOut(duration: keyboard.keyboardDuration))
    }
}


text:
Q: React js Second call to API request I'm a newbie in React Js and I'm having an issue with a button behaviour.
This is my class, which basically shows a label and an "empty" button.

 class NotificationsMenuTitle extends React.Component {
    constructor(props){
    super(props);
    this.emptyNotifications = this.emptyNotifications.bind(this);
  }

  emptyNotifications(e){
    e.preventDefault();
    this.props.emptyNotifications();
  }

  render(){
    const { formatMessage } = this.props.intl;
    return (

{formatMessage(labels.notifications)}

        <SmallButton
          className="notifications-menu__list__title__emptyButton"
          actionType="confirm"
          onClick={this.emptyNotifications}>
          {formatMessage(labels.empty)}
        </SmallButton>

    );
  }
}

const SmartEmptyNotifications = connect(props => ({
  emptyNotifications: notificationRequests.emptyNotifications
}))(injectIntl(NotificationsMenuTitle));

export default SmartEmptyNotifications;

My request looks like this :

const notificationRequests = {
  emptyNotifications: () => ({
    emptyNotifications: {
      url: `${ENDPOINT_URL}/notification/all`,
      method: "DELETE",
      body: JSON.stringify()
}})};

When clicking on the "empty" button, I do my API request which does what it's suppose to do with no problem.
The second time, I click on the button, I systematically get an error in the browser console => TypeError: this.props.emptyNotifications is not a function and my API request is not sent.
Do I need to "reset" the emptyNotifications somehow, so that I can call it more than once ? I feel that the "fulfilled: true" is the issue, but I do not know
This is what my this.props.emptyNotifications looks like on the second call :
emptyNotifications: {…}
   fulfilled: true
   meta: Object { request: Request, response: Response, component: undefined }
   pending: false
   reason: null
   refreshing: false
   rejected: false
   settled: true
   value: 1
   __proto__: Object { then: then(), catch: _catch(), … }

Thanks for any help you may to bring me :)

A: Look's like  you somehow reassign notificationRequests.emptyNotifications  to promise  which was returned after first request.

A: As Alexandr suggested, I was overwriting my own function. To fix this issue, I used a fetch instead of a promise (I hadn't really understood the difference between the two).
My emptyNotifications function now looks like :
emptyNotifications(e){
   e.preventDefault();
   const headers = makeHeadersForRequest();
   fetch(`${ENDPOINT_URL}/notifications/all`, {
     method: 'delete',
     headers: headers,
   }).then(response =>
     response.json().then(json => {
     return json;
   })
);}

And this works for me


text:
Q: Close to 50% threads are in BLOCKED state while sending some concurrent requests Basic configuration for tomcat is as follows:
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="500" minSpareThreads="30" maxIdleTime="60000" prestartminSpareThreads = "true" />

 <Connector port="80" protocol="org.apache.coyote.http11.Http11Nio2Protocol"
    maxThreads="200" minSpareThreads="10" acceptCount="100"
    maxConnections="10000" acceptorThreadCount="4" URIEncoding="UTF-8" redirectPort="8443"/>

While doing load testing with JMeter, simulating some concurrent users, like 2000, from thread dump log, close to 50% threads are in BLOCKED state, which are waiting to lock the same resource <0x00000007401424d0>, as follows:
"http-nio2-80-exec-3" #19 daemon prio=5 os_prio=0 tid=0x00007f7090635000 nid=0x6bab waiting for monitor entry [0x00007f70705be000]
   java.lang.Thread.State: BLOCKED (on object monitor)
at org.apache.log4j.Category.callAppenders(Category.java:204)
- waiting to lock <0x00000007401424d0> (a org.apache.log4j.spi.RootLogger)
at org.apache.log4j.Category.forcedLog(Category.java:391)
at org.apache.log4j.Category.info(Category.java:666)

Then find out the following thread which locks the resource <0x00000007401424d0>, as follows, could anyone help look at what's going on here?
"http-nio2-80-exec-1" #17 daemon prio=5 os_prio=0 tid=0x00007f7090631000 nid=0x6ba9 runnable [0x00007f70706c0000]
   java.lang.Thread.State: RUNNABLE
at java.io.FileOutputStream.writeBytes(Native Method)
at    java.io.FileOutputStream.write(FileOutputStream.java:326)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291
  at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:295)
at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
- locked <0x00000007420ef208> (a java.io.OutputStreamWriter)
at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
at org.apache.log4j.helpers.QuietWriter.flush(QuietWriter.java:59)
at org.apache.log4j.WriterAppender.subAppend(WriterAppender.java:324)
at org.apache.log4j.DailyRollingFileAppender.subAppend(DailyRollingFileAppender.java:369)
at org.apache.log4j.WriterAppender.append(WriterAppender.java:162)
at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:251)
- locked <0x0000000741000de8> (a org.apache.log4j.DailyRollingFileAppender)
at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:66)
at org.apache.log4j.Category.callAppenders(Category.java:206)
- locked <0x00000007401424d0> (a org.apache.log4j.spi.RootLogger)
at org.apache.log4j.Category.forcedLog(Category.java:391)
at org.apache.log4j.Category.debug(Category.java:260)


text:
Q: Match port number I am trying to match port numbers in  tags from an html page:

                8080

            80

            3124

            1142

Script:
import urllib2
import re

h = urllib2.urlopen('http://www.proxy360.cn/Region/Brazil')

html = h.read()

parser_port = '\s*([0-9]){2,}\s*'

p = re.compile(parser_port)

list_port = p.findall(html)

print list_port

But I'm getting this output:
['8', '8', '0', '0', '0', '8', '8', '0', '0', '8', '8', '8', '8', '8', '8', '8', '8', '0']

And I need it to match 8080 for example.

A: If you're looking to pull the ports off the page.
parser_port = '\s*([0-9]{2,})+\s*'

You want one or more characters (the + sign) with a length of at least two (the {2,}. But still unclear as to what the use case is.

A: You are repeating the group ([0-9]){2,}. which is overwritten with the last value.
Instead, repeat the subpattern inside the group:
]*>\s*([0-9]{2,})\s*</\s*span>

Code
parser_port = ']*>\s*([0-9]{2,})\s*</\s*span>'
p = re.compile(parser_port)

list_port = p.findall(html)


text:
Q: Adding event listeners through for loop I'm having some issues with some JavaScript code.
What I am trying to do is add event listeners to elements in an array.
The problem is that after the code is ran only the last element in the array gets the eventlistener working, the rest of the elements are returning errors.
I'm assuming this is because of the logic I'm using with the for loop and the eventlisteners.
What would be an effective way to achieve the desired result?
function addSlider(config) {
var controls = `

 next

 previous
`;
var S_wrapper = config.wrapper;
var controls_html = document.createElement("div");
controls_html.setAttribute("id", "ctrl");
controls_html.innerHTML = controls;

var arrayData = config.wrapper.split(",");

for (i = 0; i < arrayData.length; i++) {
    (function(index) {
        document.querySelector(arrayData[i]).appendChild(controls_html);
        var parent = document.querySelector(arrayData[index]);
        console.log(i, index, arrayData[index], parent);

        document.querySelector(arrayData[index]).addEventListener("mouseover", function(){
            this.querySelector("#ctrl").style.display = "block";
        })

        document.querySelector(arrayData[index]).addEventListener("mouseout", function(){
            this.querySelector("#ctrl").style.display = "none";
        })
    })(i);
}

}

A: There are a couple of problems:

*

*You're moving the same div to a new parent on each loop iteration. Your controls_html isn't HTML, it's a reference to an HTMLDivElement object. This line:
document.querySelector(arrayData[i]).appendChild(controls_html);

moves it from whatever parent it has (initially none, but after the first loop it's the element from the previous loop) to the new parent.
If you want a new div in each parent, you need to create a new div each time.

*You're using the same ID, ctrl, on more than one element. That's invalid, IDs must be unique. Later, when you use #ctrl, you'll get whatever element the browser chooses to give you (it's unspecified behavior, although in my experience it's always the first one).
So we need to handle both of those issues. Taking a minimal-changes-to-your-approach solution, we move div creation into the loop and add the index to the ID:
function addSlider(config) {
    var controls = `

 next

 previous
`;
    var S_wrapper = config.wrapper;

    var arrayData = config.wrapper.split(",");

    for (i = 0; i < arrayData.length; i++) {
        (function(index) {
            var div = document.createElement("div");
            div.setAttribute("id", "ctrl" + index);
            div.innerHTML = controls;
            var parent = document.querySelector(arrayData[index]);
            parent.appendChild(div);

            parent.addEventListener("mouseover", function() {
                this.querySelector("#ctrl" + index).style.display = "block";
            })

            parent.addEventListener("mouseout", function() {
                this.querySelector("#ctrl" + index).style.display = "none";
            })
        })(i);
    }
}

But I'd step back and look at the broader picture. For instance, both mouseover and mouseout bubble, so you could hook those on a parent element and handle this with a single handler. There's also probably no reason for that ID at all; we could identify the child div with a class or similar and seach only within parent for it. You could replace the loop and the function within it with Array#forEach. That sort of thing.

Side note: I notice you're using a template literal (the thing you're assigning to controls), which is a feature introduced in ES2015 (aka "ES6"), but not using any of the other ES2015 features. So just flagging that up in case you didn't realize...

A: PS: I'm going to answer the problems in your current code and not talk about design/refactoring (others already commented on this)
Your main problems are using id's instead of classes. remember that only one id can exist within a document, otherwise there is no way to refer to them.
Additionally, you are also reusing the controls_html element, you should create a new one for each element you are adding to. (again, in this situation)
I have created a fiddle with a working copy of your code

function addSlider(config) {
    var controls = `

 next

 previous
`;

    var S_wrapper = config.wrapper;
    var arrayData = config.wrapper.split(",");

    for (i = 0; i < arrayData.length; i++) {
        (function(index) {
            var controls_html = document.createElement("div");
            controls_html.setAttribute("class", "ctrl");
            controls_html.style.display = 'none';
            controls_html.innerHTML = controls;

            document.querySelector(arrayData[index]).appendChild(controls_html);
            var parent = document.querySelector(arrayData[index]);

            document.querySelector(arrayData[index]).addEventListener("mouseover", function() {
                this.querySelector(".ctrl").style.display = "block";
            })

            document.querySelector(arrayData[index]).addEventListener("mouseout", function() {
                this.querySelector(".ctrl").style.display = "none";
            })
        })(i);
    }
}

addSlider({
    wrapper: '#a,#b,#c'
})

    1

    2

    3


text:
Q: Clarification about equality regarding integrals I'm reading Brezis ch. 8 and got stuck in a passage of lemma 8.2 pag. 205.
Let $I=(a,b)$, let $g \in L_{loc}^1(I)$, for a fixed $y_0 \in I$, set $$ v(x) = \int_{y_0}^x g(t)dt \ \ \ \ \ \ \ \ \ x \in I$$
Then $v \in C(I)$ and $$ \int_I v \varphi' = - \int_I g \varphi \ \ \ \forall \varphi \in C_c^1(I) $$

PROOF
  \begin{align}
\int_I v \varphi' &= \int_I \left[ \int_{y_0}^x g(t) dt \right] \varphi'(x)dx \ \ \ \ (1) \\ &= -\int_{a}^{y_0}dx \int_x^{y_0} g(t)\varphi'(x)dt + \int_{y_0}^b dx \int_{y_0}^x g(t)\varphi'(x)dt \ \ \ \ \ \ (2)
\end{align}
  By Fubini's Theorem, \begin{align} \int_I v \varphi' &= - \int_a^{y_0} g(t) dt \int_a^t \varphi'(x) dx + \int_{y_0}^b g(t) dt \int_t^b \varphi'(x)dx  \ \ \ \ (3) \\ &= - \int_I g(t)\varphi(t)dt \ \ \ \ \ \ \ (4)
\end{align}

I've already worked out all the details except the proof of the equivalence of line (2) and line (3). In other words, I can't understand how from line (2) we can go to line (3) using Fubini.
Every hints are welcomed, thanks in advance!

A: To change the order of integration in such a setting, I usually find it most convenient to describe the domains of integration by a chain of inequalities. In
$$\int_a^{y_0} \int_x^{y_0} g(t)\varphi'(x)\,dt\,dx$$
the variable $x$ of the outer integral varies from $a$ to $y_0$, and the variable $t$ of the inner integral varies from $x$ to $y_0$. So the domain of integration is
$$\{ (x,t) : a \leqslant x \leqslant t \leqslant y_0\}.$$
Now, if we change the order of integration, the inequalities say that $x$ varies from $a$ to $t$, and $t$ varies from $a$ to $y_0$. So
$$\int_a^{y_0} \int_x^{y_0} g(t)\varphi'(x)\,dt\,dx = \int_a^{y_0} g(t)\int_a^t \varphi'(x)\,dx\,dt.$$
For the second integral, it is analogous, the inequalities there are
$$y_0 \leqslant t \leqslant x \leqslant b.$$


text:
Q: java.lang.StackOverflowError at at java.util.regex.Pattern in liferay I am  using liferay 6.1 CE GA2  on 64 bit centos 6 and tomcat 7
When i edit some fields of user and click on save button the page goes to loading state and stay in same state several minute.
if i wait till one minute and  after that  go back to back step by clicking on  "user and organization"  link in control panel and again back to user information then can see that changes is saved .
when i check log file (tomcat/logs/catalina.out) i see the same error :
Exception in thread "http-bio-80-exec-83" java.lang.StackOverflowError
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4078)
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3345)
    at java.util.regex.Pattern$Branch.match(Pattern.java:4114)
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168)
    at java.util.regex.Pattern$Loop.match(Pattern.java:4295)
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4227)
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4078)
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3345)
    at java.util.regex.Pattern$Branch.match(Pattern.java:4114)
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168)
    at java.util.regex.Pattern$Loop.match(Pattern.java:4295)
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4227)
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4078)
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3345)
    at java.util.regex.Pattern$Branch.match(Pattern.java:4114)
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168)
    at java.util.regex.Pattern$Loop.match(Pattern.java:4295)
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4227)
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4078)
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3345)
    at java.util.regex.Pattern$Branch.match(Pattern.java:4114)
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168)
    at java.util.regex.Pattern$Loop.match(Pattern.java:4295)
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4227)
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4078)
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3345)
    at java.util.regex.Pattern$Branch.match(Pattern.java:4114)
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168)
    at java.util.regex.Pattern$Loop.match(Pattern.java:4295)
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4227)
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4078)
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3345)
    at java.util.regex.Pattern$Branch.match(Pattern.java:4114)
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168)
    at java.util.regex.Pattern$Loop.match(Pattern.java:4295)
    at java.util.regex.Pattern$GroupTail.match(Pattern.java:4227)
    at java.util.regex.Pattern$BranchConn.match(Pattern.java:4078)
    at java.util.regex.Pattern$CharProperty.match(Pattern.java:3345)
    at java.util.regex.Pattern$Branch.match(Pattern.java:4114)
    at java.util.regex.Pattern$GroupHead.match(Pattern.java:4168)

this problem had occurred  in dynamic data list , when in control panel i wanted to see records
this problem solved by installing oracle jdk 6 , what david suggest me.
But the same problem is occurring on very operation (often on  saving user changes in control panel )
I have serious  challenge with this problem for six month :(
Any help please

A: JAVA_OPTS="$JAVA_OPTS -Xss16m"
or
JAVA_OPTS="$JAVA_OPTS -Xss1024m"
add this property to setenv in tomcat> bin folder


text:
Q: Instant messages in MVC application I need your help to solve next issue: I am developing MVC application and want to send instant messages between users. This message will ne standard - it's like notification. I am thinking about two optins:

*

*use XMPP protocot, but I don't need the huge amount of options it could provide, I need just basic functionality I've discribed;

*have some static array in MVC application with users invitations were send to and ajax function which will call controller action, check if user is in static list. If yes - make message visible on the page. And plus do page autoupdate. But I am not sure about this becouse array will be called very often.
What do you think, guys? Do you have any ideas? I will be very thankfull for any help!

A: You may take a look at SignalR.

A: Also checkout Jabbr which is built on SignalR:
https://github.com/davidfowl/JabbR
This is a chat application written by the author of SignalR David Fowler.

A: You can set jquery timer to update messages with ajax. And when user writes message , it can be saved in Cache or in database if you want to save it permanently.


text:
Q: Testes unitários abstratos Estou com um problema ao usar classes abstratas para manter o código comum dos meus testes, inicialização encerramento etc...
Utilizo uma classe concreta apenas para  inicializar as variáveis.
O código herdado da classe abstrata não é executado ao rodar os teste, acredito ser alguma configuração faltando, segue um código exemplo:
        namespace meusTestes
        {
            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using NUnit.Framework;

            public abstract class AbTest
            {
                public abstract string getString();

                [Test]
                public void SharedTest()
                {
                    Assert.NotNull(getString()); //Don't execute
                }
            }

            [TestFixture]
            public class RealTest : AbTest
            {
                public override string getString()
                {
                    return " "; //Don't execute
                }

                [Test]
                public void InternalTest()
                {
                    Assert.IsTrue(true); // Execute
                }
            }
        }

O teste InternalTest é executado corretamente, mas o testes herdado(SharedTest) da classe abstrata não, minha duvida é o porque o herdado não executa dodo que a documentação preve herança de testes.

A: Seguindo a sugestão do Cigano segue o código:
namespace meusTestes
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using NUnit.Framework;

    public abstract class AbTest
    {
        public abstract string getString();

        public virtual void SharedTest()
        {
            Assert.NotNull(getString());
        }
    }

    [TestFixture]
    public class RealTest : AbTest
    {
        public override string getString()
        {
            return " ";
        }

        [Test]
        public void InternalTest()
        {
            Assert.IsTrue(true);
        }

        [Test]
        public override void SharedTest() { base.SharedTest(); }
    }
}

A: A classe AbTest não precisa ser abstrata, pois você não precisa se preocupar em  instanciar essas classes, uma vez que o NUnit fará isso para você.
Eu sempre uso classes de teste "base" para encapsular implementações que serão reutilizadas nas filhas e funciona tranquilamente para as chamadas de base.Metodo() e propriedades protected.
Solução
Remova os abstract.


text:
Q: Allow only Admin to delete a file? I am writing a C# application and I want to set (at application start) the permissions so that only the Administrator can delete a file which the application uses. All other users should not be able to delete it or modify its permissions.
The file should be protected from standard file system usage (so no one, except Admin, can delete it). Only Admin should be able to set back the file permissions. Also, other users should be able to read/write it.
Is this possible? I have found some code examples here, but none of them work.
The code I'm trying :
FileSecurity fSecurity = File.GetAccessControl("database.sdf");

        AuthorizationRuleCollection rules = fSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
        foreach (AuthorizationRule rule in rules)
        {
            System.Security.Principal.NTAccount account =
                (System.Security.Principal.NTAccount)rule.IdentityReference.Translate(typeof(System.Security.Principal.NTAccount));
            if (account.Value != "BUILTIN\\Administrators")
            {
                fSecurity.AddAccessRule(new FileSystemAccessRule(account.Value, FileSystemRights.Delete, AccessControlType.Deny));
            }
        }

        File.SetAccessControl("database.sdf", fSecurity);

Can I configure the file permissions and owner programmatically from the app when running it as a normal user, not admin?
Thank you!
PS The file is a SQL Server Compact database.

A: Before we get started, let me just say that this:
System.Security.Principal.NTAccount account =
    (System.Security.Principal.NTAccount)rule.IdentityReference.Translate(typeof(System.Security.Principal.NTAccount));
if (account.Value != "BUILTIN\\Administrators")

is entirely unnecessary.
The builtin Administrators group is a well-known security principal, and is guaranteed to always have the same Security Identifier (S-1-5-32-544), easy to compare against.

Your current procedure of explicitly granting Deny Delete for all principals that already happens to have an access rule may also backfire immensely.
Imagine that an access rule with the following characteristics already exist in the ACL:

Identity: Everyone
Access right: Read
Control type: Allow

Congratulations! You've now implicitly denied everyone the right to delete the file, including the Administrators group.
What you want to do is:

*

*Make sure the Administrators group is the Owner of the file

*Remove all existing access rules that grants Allow Delete (explicitly or implicitly)

*Add a single Access Rule granting Allow FullControl to the Administrators group

*Remove all inherited rules and protect the ACL from inheritance

// Way safer than string comparison against "BUILTIN\\Administrators"
IdentityReference BuiltinAdministrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

// Grab ACL from file
FileSecurity FileACL = File.GetAccessControl(TargetFilePath);

// Check if correct owner is set
if (FileACL.GetOwner(typeof(SecurityIdentifier)) != BuiltinAdministrators)
{
    // If not, make it so!
    FileACL.SetOwner(BuiltinAdministrators);
}

foreach (FileSystemAccessRule fsRule in FileACL.GetAccessRules(true, false, typeof(SecurityIdentifier)))
{
    // Check if rule grants delete
    if ((fsRule.FileSystemRights & FileSystemRights.Delete) == FileSystemRights.Delete)
    {
        // If so, nuke it!
        FileACL.RemoveAccessRule(fsRule);
    }
}

// Add a single explicit rule to allow FullControl
FileACL.AddAccessRule(new FileSystemAccessRule(BuiltinAdministrators, FileSystemRights.FullControl, AccessControlType.Allow));

// Enable protection from inheritance, remove existing inherited rules
FileACL.SetAccessRuleProtection(true, false);

// Write ACL back to file
File.SetAccessControl(TargetFilePath, FileACL);

A: Using Mathias' help, I found the answer to my question:
try
{
       // Way safer than string comparison against "BUILTIN\\Administrators"
       IdentityReference BuiltinAdministrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
       IdentityReference AuthenticatedUsers = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

       FileSecurity FileACL = File.GetAccessControl("database.sdf"); // Grab ACL from file

       if (FileACL.GetOwner(typeof(SecurityIdentifier)) != BuiltinAdministrators) // Check if correct owner is set
       {
             FileACL.SetOwner(BuiltinAdministrators); // If not, make it so!
       }

       foreach (FileSystemAccessRule fsRule in FileACL.GetAccessRules(true, true, typeof(SecurityIdentifier)))
       {
             if ((fsRule.FileSystemRights & FileSystemRights.Delete) == FileSystemRights.Delete ||
                    (fsRule.FileSystemRights & FileSystemRights.ChangePermissions) == FileSystemRights.ChangePermissions) // Check if rule grants delete or change permissions
             {
                  FileACL.RemoveAccessRule(fsRule); // If so, nuke it!
             }
       }

       // Add explicit rules
       FileACL.AddAccessRule(new FileSystemAccessRule(BuiltinAdministrators, FileSystemRights.FullControl, AccessControlType.Allow));
       FileACL.AddAccessRule(new FileSystemAccessRule(AuthenticatedUsers, FileSystemRights.Delete, AccessControlType.Deny));
       FileACL.AddAccessRule(new FileSystemAccessRule(AuthenticatedUsers, FileSystemRights.ChangePermissions, AccessControlType.Deny));
       FileACL.AddAccessRule(new FileSystemAccessRule(AuthenticatedUsers, FileSystemRights.Read, AccessControlType.Allow));
       FileACL.AddAccessRule(new FileSystemAccessRule(AuthenticatedUsers, FileSystemRights.Write, AccessControlType.Allow));

       FileACL.SetAccessRuleProtection(true, false); // Enable protection from inheritance, remove existing inherited rules
       File.SetAccessControl("database.sdf", FileACL); // Write ACL back to file
   }
   catch { }

And in order to work, the application has to be run once as admin.
Setting file permissions programmatically is new to me, so if someone thinks the code may not do what it's intended to do, please correct me.
Thank you!


text:
Q: How redirect HTTP call to HTTPS for webservice in codeigniter? Early my site has no SSL certificate so baseurl for webservice was http://test.com/webservice/index.php. Now I am going to move my site to HTTPS.
So when I tested webservice. All webservice showing unknown method. The base_url is hardcoded in android and iOS. So is there any way to redirect the http call to https. Otherwise app will be crashed. Whether Writing redirection in .htaccess file
can solve this issue.

A: .htaccess can be used to force https. The following usually works for CodeIgniter on Apache.
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]