text:
Q: Screensaver only on primary screen I'm trying to set a screensaver only on primary screen. Is it possible?
I know, that I can disable screensaver on specified monitors using screensaver settings->display settings, but I'm looking for an option, to set "Enabled only on primary screen".
Maybe it is possible via registry or gpedit?

A: This is usually dependent on the screen-saver itself, if it was programmed
with this possibility. If it was, this is normally set in its Settings page.
You could also look for some configuration settings on your display adapter,
as some adapters do have that option.
There are products that can force this, but they are usually commercial.
One I know of is
Actual Multiple Monitors,
and another might be DisplayFusion,
but I don't believe that this is worth the cost.


text:
Q: Can i Run two ant tasks at the same time? i want to reduce the build time taken for a build by excecuting  as many independent tasks at the same time as possible. is it possible to do it?
I have tried using parallel tasks in the targets but parallel task will only parallelise within a target.i didnt get any significant build time reduction with parallel tasking.so now i am want to run entire targets in parallel.

A: Ant supports parallel tasks. See this documentation: http://ant.apache.org/manual/Tasks/parallel.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android is not showing permissions I've made an app that requests internet permission but it is showing no permissions permissions requested in the app info place.
Here is the manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myartsonline.bharath.lowloss">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Here is my MainActivity.java file
package com.myartsonline.bharath.lowloss;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CalendarView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.myartsonline.bharath.lowloss.RewardsRecyclerView.Data;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private static final int INTERNET_PERMISSION = 0;
    LinearLayout home,calendar,rewards,help;
    CalendarView calendarView;
    RecyclerView rewardsRecView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        home=(LinearLayout)findViewById(R.id.homeLayout);
        calendar=(LinearLayout)findViewById(R.id.calendarLayout);
        rewards=(LinearLayout)findViewById(R.id.rewardsLayout);
        help=(LinearLayout)findViewById(R.id.helpLayout);
        calendarView=(CalendarView)findViewById(R.id.calendarView);
        rewardsRecView=(RecyclerView)findViewById(R.id.rewardsRecView);
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET)!= PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.INTERNET}, INTERNET_PERMISSION);
        }
        Data d=new Data(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "fab", Toast.LENGTH_SHORT).show();
            }
        });
        calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView calendarView, int i, int i1, int i2) {
                Toast.makeText(MainActivity.this, i2+"", Toast.LENGTH_SHORT).show();
            }
        });
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.nav_home) {
            calendar.setVisibility(View.GONE);
            rewards.setVisibility(View.GONE);
            help.setVisibility(View.GONE);
            home.setVisibility(View.VISIBLE);
        } else if (id == R.id.nav_calendar) {
            calendar.setVisibility(View.VISIBLE);
            rewards.setVisibility(View.GONE);
            help.setVisibility(View.GONE);
            home.setVisibility(View.GONE);
        } else if (id == R.id.nav_rewards) {
            calendar.setVisibility(View.GONE);
            rewards.setVisibility(View.VISIBLE);
            help.setVisibility(View.GONE);
            home.setVisibility(View.GONE);
        } else if (id == R.id.nav_about) {
            calendar.setVisibility(View.GONE);
            rewards.setVisibility(View.GONE);
            help.setVisibility(View.VISIBLE);
            home.setVisibility(View.GONE);
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

A: There is no need to check internet permission.
And ActivityCompat.requestPermissions needs a callback named ActivityCompat.OnRequestPermissionsResultCallback

A: if you want your app to check internet connection, you can use this code
 public final boolean isInternetOn() {

    // get Connectivity Manager object to check connection
    ConnectivityManager connec =
            (ConnectivityManager) getActivity().getSystemService(getActivity().CONNECTIVITY_SERVICE);

    // Check for network connections
    if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
            connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {

        // if connected with internet
        Toast.makeText(getActivity(), " Connected ", Toast.LENGTH_LONG).show();

        return true;

    } else if (
            connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                    connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {
        Toast.makeText(getActivity(), " Not Connected ", Toast.LENGTH_LONG).show();
        return false;
    }
    return false;
}

and then wherever you want to check your internet connection call above method,
boolean isInternet = isInternetOn();
if (isInternet) {  //write your code here    }


text:
Q: Converting unsigned char array to hex I want to convert unsigned char to hex (using unsigned int). This is my code so far. I have a program1 that produces an unsigned char array and the other program2 only takes in only hex (using unsigned int), so what i want to achieve is getting an input of unsigned char array and converting that array into hex.

(E.g., program1 outputs "1234567812345678", program2 should output "31323334353637383132333435363738")

Sorry if this question seems dumb. Looked around for answers here but it didn't seem to be what I wanted.
uint64_t phex (unsigned char[16], long);

int main (void) {

int i;
unsigned char key[16] = "1234567812345678";

uint64_t* keyHex = phex(key,16); //store into an array here

for(i = 0; i < 16; i++)
printf("%.2x ", keyHex[i]);

free(keyHex);

return 0;

}

uint64_t phex(unsigned char* string, long len)
{

int i;
//allocate memory for your array
uint64_t* hex = (uint64_t*)malloc(sizeof(uint64_t) * len);

for(i = 0; i < len; ++i) {
    //do char to int conversion on every element of char array
    hex[i] = string[i] - '0';
}

//return integer array
return hex;

}

A: If all you need to do is print the values, then you do not need to do any conversion. Just use printf %.2xon the original array.
int main (void) {
    int i;
    unsigned char key[16] = "1234567812345678";
    for(i = 0; i < 16; i++)
        printf("%.2x", key[i]);
    return 0;
}

Even if you want to use the array in some other function, the actual bytes stored in key are the ascii characters, i.e. 0x31 0x32 etc. You can generally directly use the array key
Edit: To store the output in a character array, you can use the sprintf function.
char hex[33];
for(i = 0; i < 16; i++)
    sprintf(hex+2*i, "%.2x", key[i]);

Also note that the original array key should be 17 bytes to account for the \0 at the end.

A: Here is my take on it - the phex() function converts any data
in memory into a newly allocated string containing the hex representation.
The main() function shows an example usage. The output is "31323334353637383930" for the example data.
#include <stdlib.h> /* malloc() */
#include <stdio.h>  /* sprintf() */
#include <string.h> /* strlen(), in the example main() */

/*
 * Return a hex string representing the data pointed to by `p`,
 * converting `n` bytes.
 *
 * The string should be deallocated using `free()` by the caller.
 */
char *phex(const void *p, size_t n)
{
    const unsigned char *cp = p;              /* Access as bytes. */
    char *s = malloc(2*n + 1);       /* 2*n hex digits, plus NUL. */
    size_t k;

    /*
     * Just in case - if allocation failed.
     */
    if (s == NULL)
        return s;

    for (k = 0; k < n; ++k) {
        /*
         * Convert one byte of data into two hex-digit characters.
         */
        sprintf(s + 2*k, "%02X", cp[k]);
    }

    /*
     * Terminate the string with a NUL character.
     */
    s[2*n] = '\0';

    return s;
}

/*
 * Sample use of `phex()`.
 */
int main(void)
{
    const char *data = "1234567890";               /* Sample data */
    char *h = phex(data, strlen(data));  /* Convert to hex string */

    if (h != NULL)
        puts(h);                                  /* Print result */

    free(h);                             /* Deallocate hex string */
    return 0;
}

A: I see the function signature as
 uint64_t phex (unsigned char[16], long);

so I think, you do not need array of uint64_t to transform one string, representing one number (perhaps I am wrong and you want to transform each single character from its char-representation to int and show as hexadecimal number).
First, let's consider the following code to transformation in decimal (actually, number in your example - 1234567812345678 - looks like decimal number):
uint64_t phex(unsigned char* string, long len)
{

    int i;
    //you do not need to allocate memory for array
    uint64_t hex = 0; // just one variable

    for (i = 0; i < len; ++i) {
        hex *= 10; // shift
        hex += string[i] - '0'; // add to the smallest rank
    }

    //return integer Value
    return hex;

}

Then for hexadecimal the program will be:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
uint64_t phex(unsigned char[16], long);

int main(void) {

    int i;
    unsigned char key[16] = "A123B00CF1";

    uint64_t keyHex = phex(key, strlen(key));

    printf("%lld(dec) = %llx(hex)", keyHex, keyHex);

    return 0;
}

uint64_t phex(unsigned char* string, long len)
{
    int i;
    uint64_t hex = 0;
    for (i = 0; i < len; ++i) {
        hex *= 0x10; // shift for one hexadecimal digit
        // -'0' for digits 0..9 and -('A'-10) for digits `A`..`F`
        hex += toupper(string[i]) - ((string[i] >= 'A') ? ('A' - 10) : '0');
        // TODO: Consider making check for characters that are not hexadecimal
        // e.g. use isxdigit(string[i]) in some if statement
    }
    return hex;
}

Note: There is a mistake in your example code - uint64_t* keyHex take the value from function that returns uint64_t (not pointer ``uint64_t*`), but if you accept my idea, you do not need pointer at all.

A: If the task is to transform chars ('1', '2', etc.) to their hexadecimal representation (31 for '1', 32 for '2', etc.) it is hard to understand why you need uint64_t.
But for your task code can be as follows (without uint64_t):
#include <stdio.h>
#include <string.h>

unsigned int * phex(unsigned char[16], long);

int main(void) {
    int i;
    unsigned char key[16] = "1234567812345678";
    unsigned* keyHex = phex(key, strlen(key)); // strlen(key) to determine number of characters
    for (i = 0; i < 16; i++)
        printf("%.2x", keyHex[i]); // you do need space as I see from your example
    free(keyHex);
    return 0;

}

unsigned int * phex(unsigned char* string, long len)
{
    int i;
    //allocate memory for array
    unsigned int * hex = (unsigned int *)malloc(sizeof(unsigned int) * len);
    for (i = 0; i < len; ++i) {
        //no special conversion needed
        hex[i] = string[i];
    }
    //return array with hexadecimal representation for each character in string
    return hex;
}


text:
Q: App behaves different when run from XCode compared to .ipa I have a very puzzling problem.
My app uses several custom buttons that use gesture recognizers to determine a tap or a long press.
When I run the app from XCode on my device everything works as it should. However, when I package the app in an .ipa file and install that on the same device the buttons no longer work! None of the gestures are recognized nor do they change state when pressed. Everything else seems to work fine...
The devices I tested are an iPhone 5 (running iOS 6.1.4) and iPhone 4 & 4S (both running iOS 6.1.3). And I'm using XCode 4.6.2 on Max OSX 1.8.3.
Any ideas what might be causing this very strange behavior?
PS: The "Xcode generated" code keeps on working after I've disconnected it from XCode.

A: It could be Optimization Level! You probably build AdHoc builds with Fastest, Smallest [-Os]. See Optimization Level in your build settings. Build your debug with Fastest, Smallest [-Os], then you can see your misbehaviour in action, so you can fix it, and still submit apps with the preferred way of optimization (with Release configuration).
Fastest, Smallest [-Os] somehow releases weak references more strictly, as far as I experienced.

A: Typically the code you archive into an IPA file would use a different configuration than from when you run it from XCode. I can't guess what's wrong specifically without looking at your project file or having some more information, but the first thing I would try would be to do an Edit Scheme on the scheme you're using and compare the build configuration used for the Run action and the Archive action.

A: Same kind of surprising situation happened to me. I had all project related strings in GameStrings.h file defined against different macros. Those strings were detected while going to use them from the .ipa file in my iPad 2 but they were not shown on the screen. It's all about the target scheme configurations. As @ScorpioCurse has told that building and archiving a project may use different build configurations ,these type of problems may arise.

Just check whether these two(Build and Archive) schemes use the same configuration or not. Make sure that both of these schemes use the same build configuration.


text:
Q: Would allowing user input to python's __import__ be a security risk? Say I create a simple web server using Flask, and allowing people to query certain things that I modulated in different python files, using the __import__ statement, would doing this with user supplied information be considered a security risk?
Example:
from flask import Flask

app = Flask(__name__)

@app.route("/<author>/<book>/<chapter>")
def index(author, book, chapter):
    return getattr(__import__(author), book)(chapter)
    # OR
    return getattr(__import__("books." + author), book)(chapter)

I've seen a case like this recently when reviewing code, however it didn't feel right to me.

A: It is entirely insecure, and your system is wide open to attack. Your first return line doesn't limit what kind of names can be imported, which means the user can execute any arbitrary callable in any importable Python module.
That includes:
/pickle/loads/<url-encoded pickle data>

A pickle is a stack language that lets you execute arbitrary Python code, and the attacker can take full control of your server.
Even a prefixed __import__ would be insecure if an attacker can also place a file on your file system in the PYTHONPATH; all they need is a books directory earlier in the path. They can then use this route to have the file executed in your Flask process, again letting them take full control.
I would not use __import__ at all here. Just import those modules at the start and use a dictionary mapping author to the already imported module. You can use __import__ still to discover those modules on start-up, but you now remove the option to load arbitrary code from the filesystem.
Allowing untrusted data to direct calling arbitrary objects in modules should also be avoided (including getattr()). Again, an attacker that has limited access to the system could exploit this path to widen the crack considerably. Always limit the input to a whitelist of possible options (like the modules you loaded at the start, and per module, what objects can actually be called within).

A: More than being a security risk, it is a bad idea e.g. I could easily crash your web app by visiting the url:
/sys/exit/anything

translating to:
...
getattr(__import__('sys'), 'exit')('anything')

Don't give the possibility to import/execute just about anything to your users. Restrict the possibilities by using say a dictionary of permissible imports, as @MartijnPieters as clearly pointed out.


text:
Q: Elicpse CDT thinks it's broken I'm using Eclipse for some embedded development and recently is started to give me these errors every time I save a file or do a build. It's annoying but for the most part it doesn't seem to be causing any problems (It even still highlights warnings/errors int the source. What's going on here?
Plug-in org.eclipse.cdt.cross.arm.gnu was unable to load class
org.eclipse.cdt.managedbuilder.internal.scannerconfig.DefaultGnuWinScannerInfoCollector.

Plug-in org.eclipse.cdt.cross.arm.gnu was unable to load class
org.eclipse.cdt.managedbuilder.internal.scannerconfig.ManagedGCCScannerInfoConsoleParser

A: It looks like the eclipse wiki FAQ says

The most likely reason is that an exception was thrown in the static initializer for a class declared by the offending plug-in. Check the .log file to see whether that indeed happened.
  The Eclipse Platform loader will not load a plug-in when exceptions are thrown during the initialization of the Java classes that make up the plug-in.
Another common reason for this error is the lack of an appropriate constructor for the class being loaded. Most classes declared in extension points must have a public zero-argument constructor. Check the extension point documentation to see what constructor is required for the classes that you declare in an extension.

If the problem only occurs when deploying a packaged plug-in (i.e., when it is not started in a runtime workbench via PDE) it is usually a good idea to check the Bundle-ClassPath attribute in the MANIFEST.MF file.
  The JAR file that contains the plug-in classes must be listed in the Bundle-ClassPath. Even if the plug-in's proper classes are all listed, class loading may still fail because a .class file may contain references to other classes that cannot be resolved at runtime. In this case, the missing classes need to be identified (usually by looking at the import statements of the problematic class) and the necessary entries need to be added to the Bundle-ClassPath. If additional JAR files are required, those JARs also need to be listed in the build.properties file so that they are included when the plug-in is packaged.

(See this thread as an illustration of that last point)

So, for instance, in this thread, for another issue back in eclipse3.0 time:

The plugin.xml file specifies "org.eclipse.core.runtime.compatablity" as a required plugin. However, I am using Eclipse Version 3.0.1 and should be using  "org.eclipse.core.runtime_3.0.1".
Solution:
Replace the line in the Plugin.xml

<import plugin="org.eclipse.core.runtime.compatability"/>

with

<import plugin="org.eclipse.core.runtime"/>

A: VonC is right -- with a fair bit of detail on what might go wrong with class loading...
In this case, your arm.cross toolchain is referencing internal classes in CDT's managedbuild which aren't accessible.  This is an incompatibility between your arm toolchain and CDT. You should file a bug with them on this error, first trying a newer version.


text:
Q: Jquery - simple multiplication assignment mistake https://jsfiddle.net/ohrgw29y/#&togetherjs=4USeqx1oCx
I'm trying to make a column "price together" each cell in which would display two other cells of a row multiplied. I got it to "add assign" but cannot "multiply assign.

$(document).ready(function() {
  $('tr').each(function() {
    var price_row_total=0
    $(this).find('.subjects').each(function() {
      var price_attributes=$(this).text();
      if(price_attributes.lenght!==0) {
        price_row_total+=parseFloat(price_attributes);
      }
    });
    $(this).find('#price_row_total').html(price_row_total);
  });
});

      Supply
      Used by
      Periodicity
      Amount
      Units
      Price per unit
      Price together

      water

        plant1

 monthly

        10

 liters

        2.99

      hay

        animal1

 one time

        15

 stacks

        1.50

P.S. I'm not even a beginner in JS , I have no idea what I'm doing, sorry. I'm sure it's simplest thing ever but I'm too short on time to learn JS synthax right now. Trying to finish this volunteered project for an animal sanctuary. Hope this explains why someone posts such simple things.

A: By no means is this answer elegant or even best practice, but it addresses you're current issue.

$(document).ready(function() {
  $('tr').each(function() {
      // this was modified to get price and unit based off class name (changed from subjects)
      const unit = Number($(this).find('.units').text());
      const price = Number($(this).find('.price').text());
      // the toFixed(2) rounds to 2 decimal places as these are floating point numbers you will end up with something like 29.90000002
      const price_row_total = (unit * price).toFixed(2);
      $(this).find('.total').html(price_row_total);
  });
});

      Supply
      Used by
      Periodicity
      Amount
      Units
      Price per unit
      Price together

      water

        plant1

 monthly

        10

 liters

        2.99

      hay

        animal1

 one time

        15

 stacks

        1.50


text:
Q: Iptables - Redirect outbound traffic on a port to inbound traffic on 127.0.0.1 Is there a way to redirect traffic set to go out of the server to another IP, back to the server on localhost (preferably as if it was coming from the original destination)?
I'd basically like to be able to set up my own software that listens on say, port 80, and receives traffic that was sent to say, 1.2.3.4.
So as an example with some code. Here would be the server:
my $server = IO::Socket::INET->new(

    LocalAddr => '127.0.0.1',
    LocalPort => '80',
    Listen => 128,

);

And that would receive traffic from the following client:
my $client = IO::Socket::INET->new(

    PeerAddr => 'google.com',
    PeerPort => '80',

)

So rather than having the client be connecting to google.com, it would be connecting to the server I have listening on localhost for that same server.
My intention is to use this to catch malware connecting to remote hosts.
I don't specifically need the traffic to be redirected to 127.0.0.1, but it needs to be redirected to an IP the same machine can listen to.
Edit:
I've tried the following, and it doesn't work--
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 127.0.0.1:80
iptables -t nat -A POSTROUTING -j MASQUERADE

A: You want to use the iptables REDIRECT target.
iptables -t nat -A OUTPUT -p tcp -d 1.2.3.4 --dport 80 -j REDIRECT

The iptables manpage specifies a single option to REDIRECT that allows you to change the port.
That option is --to-ports.

A: As far as i understand, you could use the TPROXY iptables feature and IP_TRANSPARENT sockets to achieve a fully transparent redirect (without involving NAT).
In that way your application will create a special socket which will accept traffic even if the destination IP was another box, and then use the iptables rules to redirect the traffic with destination port 80 on port 80 of the first local interface, without altering it at all.
iptables -t mangle -A PREROUTING -i eth0 -p tcp -m tcp -d 1.2.3.4 --dport 80 -j TPROXY --on-port 80

This is used in Squid Proxy in order to operate in fully transparent mode without doing any NATting, thus not altering a single byte of the packet.
Remember that you have to use a special socket for that, otherwise it won't work!
Just in case, extract from Kernel docs on how to open a tproxy socket:
fd = socket(AF_INET, SOCK_STREAM, 0);
/* - 8< -*/
int value = 1;
setsockopt(fd, SOL_IP, IP_TRANSPARENT, &value, sizeof(value));
/* - 8< -*/
name.sin_family = AF_INET;
name.sin_port = htons(0xCAFE);
name.sin_addr.s_addr = htonl(0xDEADBEEF);
bind(fd, &name, sizeof(name));


text:
Q: JPA Hibernate определить составной первичный ключ и внешний ключ, имеющие общее поле Есть JPA-сущность, для которой определеня связь один-ко-многим:
@Entity
@Table(name = "organization")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"}, ignoreUnknown = true)
public class Organization extends BlockchainEntity {
    @Id
    @Column(name = "msp")
    @JsonProperty("msp")
    private String msp;

    @Column(name = "signers")
    @JsonProperty("signers")
    @OneToMany(mappedBy = "organization", cascade = CascadeType.ALL)
    private List<Certificate> signers;
}

И JPA-класс сертификатов:
@Entity
@IdClass(Certificate.CertificatePK.class)
@Table(name = "certificate", indexes = {})
public class Certificate {

    @Id
    @Column(name = "msp")
    @JsonProperty("MSP")
    private String msp;

    @Id
    @Column(name = "fingerprint")
    @JsonProperty("fingerprint")
    private String fingerprint;

    @ManyToOne
    @JoinColumn(name = "msp", referencedColumnName = "msp", nullable = false)
    private Organization organization;
}

Таблица без лишних полей определяется так:
create table if not exists certificate
(
  fingerprint            varchar(255) not null,
  msp                    varchar      not null,
  active           boolean,

  foreign key (msp) references organization(msp),
  constraint certificate_pkey primary key (fingerprint, msp)
);

То есть в таблице есть первичный составной ключ (fingerprint, msp) и одновременно поле msp должно быть внешним ключом к таблице организаций.
Как это технически реализовать? При запуске приложения я получаю исключение:

Caused by: org.hibernate.MappingException: Repeated column in mapping
  for entity: core.entities.certificate.Certificate column: msp (should
  be mapped with insert="false" update="false")

Таблица certificate заполняется независимо от таблицы organization.

A: Ну надо добавить insertable=false, updatable=false в @JoinColumn


text:
Q: Integrable submartingale Suppose $X_n$ is a uniformly integrable submartingale and $T$ a stopping time. I wanna show that $X_T$ is integrable. To this end, I write $X_T=\lim_{n\to \infty}\sum_{k=1}^n X_k \mathbb{1}_{\{T=k\}}$. Now I would like to apply the dominated convergence theorem, but I  can't find a clearly integrable function that would upper bound each of the partial sums. Perhaps $\sup_n X_n^+$: but is the uniform integrability of $(X_n)$ enough to guarantee that $\sup_n X_n^+$ is integrable?

A: Note that by uniform integrability, there exists a random variable $X_\infty$ such that $X_n\to X_\infty$ almost surely and in $L^1$. Moreover, for each non-negative integers $\ell$ and $k$, the submartingale property gives
$$
\mathbb E\left[\lvert X_T\rvert\mathbf{1}_{\{T=k\}}\right]=\mathbb E\left[\lvert X_k\rvert\mathbf{1}_{\{T=k\}}\right]\leqslant \mathbb E\left[\lvert X_{k+\ell}\rvert\mathbf{1}_{\{T=k\}}\right]
$$
and the convergence of $X_{k+\ell}$ to $X_\infty$ in $L^1$ shows that
$$
\mathbb E\left[\lvert X_T\rvert\mathbf{1}_{\{T=k\}}\right]\leqslant \mathbb E\left[\lvert X_\infty\rvert\mathbf{1}_{\{T=k\}}\right].$$
Summing all the inequalities over $k$ and using integrability of $X_\infty$ finishes the proof.


text:
Q: How to forward all kind of request from ROOT to other web app context with Tomcat I need to forward all kind of request from the ROOT, i.e http://localhost:8080/ to http://localhost:8080/myRoot
Is it possible, do I need to create a redirect servlet? However, I think tomcat can be configured to behave that way?

A: An easy way would be to create a filter something like this
@WebFilter("/*")
public class RedirectFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String uri = request.getRequestURI();
        String query = request.getQueryString();

        if (query != null) {
            uri = uri + "?" + query;
        }

        response.setStatus(301);
        response.setHeader("Location", "/myRoot" + uri);
        // Can also use response.sendRedirect(), but this does 302 by default.
    }

    // ...
}

and put it in Tomcat/webapps/ROOT/WEB-INF/classes/com/example/RedirectFilter.class.
If you're still using Tomcat 6.0 or older, then remove @WebFilter annotation and create the web.xml accordingly.

A: What I did is to use UrlRewriteFilter
Deployed the filter into the ROOT and modified the urlrewrite.xml like this:
<rule>
    <from>^/$</from>
    <to type="redirect">%{context-path}/myRoot</to>
</rule>

And now it works.


text:
Q: Rendering Sliced images using Javascript I have been given the task of rendering sliced images using javascript.
My teacher has supplied me with a folder of sliced images. I have been asked to place each image into a table  individually. There are 4 rows and 5 columns per row (20 sliced images). I now need to use javascript to render the images, creating an whole image with no blank spaces or gaps in between the slices.
My teacher has given me a clue in that I need to use a nested for loop to render the slices together and that the rendering should be achieved by a single statement.
I understand nested for loops, but I cannot seem to wrap my head this task. Can someone please show me how to render sliced images within a table, using a single nested for loop statement, leaving no gaps or blank spaces?
//JavaScript

var numRows = 4;
var numCols = 5;

var redBowl = document.getElementsByClassName('orderImage');
  var orderImage = '';

for (var i = 0; i < numRows; i++) {
    orderImage += '
';
        for(var j = 0; j < numCols; j++) {
            orderImage += '' + i + j + '	';
    }
orderImage += '
';
}

redBowl.innerHTML = orderImage;

//HTML

A: I made a simple nested loop example. Is this help enough or what have you tried and where are you stuck?

var ele = document.getElementById('table');
var table = '';

for(var i = 0 ; i < 4 ; i++) {
 table += '
';
  for(var j = 0 ; j < 5 ; j++) {
   table += '' + i + j + '	';
  }
  table += '
';
}
ele.innerHTML = table;
td {
  border: 1px solid lightgray;
}


text:
Q: How does laravel track a one-to-one relationship if i have not used the unique() method in my migration This is a Laravel and SQL-related question. Basically if I want to create a one-to-one relationship in SQL i do it as follows:
CREATE TABLE dbo.Person
(
Pk_Person_Id INT IDENTITY PRIMARY KEY,
Name VARCHAR(255),
EmailId VARCHAR(255),
);

CREATE TABLE dbo.PassportDetails
(
Pk_Passport_Id INT PRIMARY KEY,
Passport_Number VARCHAR(255),
Fk_Person_Id INT UNIQUE FOREIGN KEY REFERENCES dbo.Person(Pk_Person_Id)
);

INSERT INTO dbo.Person VALUES ('Niraj','v.a@emails.com');
INSERT INTO dbo.Person VALUES ('Vishwanath','v.v@emails.com');
INSERT INTO dbo.Person VALUES ('Chetan','c.v@emails.com');
GO

INSERT INTO dbo.PassportDetails VALUES (101, 'C3031R33', 1);
INSERT INTO dbo.PassportDetails VALUES (102, 'VRDK5695', 2);
INSERT INTO dbo.PassportDetails VALUES (103, 'A4DEK33D', 3);
GO

SELECT * FROM dbo.Person
SELECT * FROM dbo.PassportDetails;

Notice how the passpoerdetials column Fk_Person_Id is UNIQUE.
Now in Laravel if I want to have a one-to-one realtionship, the documentation here, says the following:

A one-to-one relationship is a very basic relation. For example, a
  User model might be associated with one Phone. To define this
  relationship, we place a phone method on the User model. The  phone
  method should call the hasOne method and return its result:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

I was just wondering how Laravel tracks this hasOne relationship if in my migration I have not used unique() ? This is a bit confusing for me, I just wanted to learn more about the indepth working of Laravel and hence I am asking this question. I would really appreciate if somebody could solve this mystery for me.
P.S. this not a HOW TO question, its more of a WHY question.

A: In short: it doesn't.
The hasOne relation indicates how your data is structured (ie, $this->hasOne('App\Phone'); indicated that your App\Phone table has a foreign key referring to the User). However, Laravel does nothing to ensure that this foreign key is unique.
If you look at the code for the hasOne relation, we see:
/**
 * Get the results of the relationship.
 *
 * @return mixed
 */
public function getResults()
{
    return $this->query->first() ?: $this->getDefaultFor($this->parent);
}

In other words, Laravel leaves the responsibility of ensuring uniqueness to you, and gives its result assuming this responsibility has been fulfilled (And thus the first result will be correct).


text:
Q: Variables in DB data to avoid redundancy? "Avoid redundancy" is important to me.
I want to store the input data for configuration management in a relational database.
My input data:

*

*project_name

*linux_user

*db_user

*db_name

In 95% of all cases all attributes are equal:

*

*project_name: foo

*linux_user: foo

*db_user: foo

*db_name: foo

If I would store this data in YAML, then I could use variables to avoid repetition.
AFAIK this does not work in relational databases.
I could store this in DB, but AFAIK I need to evaluate it myself:

*

*project_name: foo

*linux_user: {project_name}

*db_user: {project_name}

*db_name: {project_name}

How can I avoid redundancy if I store this in a relational database? Unfortunately these values are not always equal, only in most cases.
I use PostgreSQL

A: There is no built-in way of doing this in SQL. If the default is always the project_name, I would probably allow nulls in the other columns, and create a view that uses coalesce() to return a default value:
create view real_data
as
select project_name,
       coalesce(linux_user, project_name) as linux_user,
       coalesce(db_user, project_name) as db_user,
       coalesce(db_name, project_name) as db_db_name
from base_data;

Another option would be a complicated case statement for each column:
create view real_data
as
select project_name,
       case linux_user
           when '{project_name}' then project_name
           when '{db_name}' then db_name
           when '{db_user}' then db_user
           else linux_user
       end as linux_user,
       ... repeat the above for the other columns ..
from base_data;

You could hide the case statement in a function or use a set returning function and dynamic SQL, so you don't need to hardcode each column name and possible variable.
If you only need to make sure you have a default value when creating the rows, then just replacing that in a trigger during insert might also be an option. That way there is no need for the view.


text:
Q: Get Getter Function in Javascript In JavaScript there is the possibility to create getters and setters the following way:
function MyClass(){
 var MyField;
 this.__defineGetter__("MyField",function(){
  return MyField;
 });
 this.__defineSetter__("MyField",function(value){
  MyField = value;
 });
}

But is there a way to get the Getter or Setter FUNCTION? I think of something like this:
var obj = new MyClass();
obj.__getSetter__("MyField")("MyValue");

I need such a functionality when extending base classes. For example:
Class "A" has field "a", Class "B" extends from "A" and also wants to have a field "a".
To pass values from the "a"-field of a "B"-object to the "a"-field of a "A"-object I need to get the setter/getter function before overriding them.

A: The old way
__defineGetter and __defineSetter__ have been deprecated in the time since this question was initially posted.
Accessing those accessor and mutator functions was handled with __lookupGetter__ and __lookupSetter__ respectively.
Example

function MyClass() {
 var MyField
 this.__defineGetter__("MyField",function(){
  return MyField
 })
 this.__defineSetter__("MyField",function(value){
  MyField = value
 })
}

var obj = new MyClass()
obj.__lookupSetter__("MyField")("MyValue")
console.log(obj.MyField)

The new way
The current standard way to create a dynamic accessor or mutator is to use Object.defineProperty or Object.defineProperties.
Accessing accessor and mutator functions can be done using Object.getOwnPropertyDescriptor and Object.getOwnPropertyDescriptors.
Example

function MyClass() {
 let MyField
 Object.defineProperty(this, 'MyField', {
   get: () => MyField,
   set: value => {
     MyField = value
   }
 })
}

var obj = new MyClass()
Object.getOwnPropertyDescriptor(obj, 'MyField').set('MyValue')
console.log(obj.MyField)

ES6 Classes
Note that Object.getOwnPropertyDescriptor works even when using get and set keywords, however there are a couple gotchas if you're using the class keyword.
Accessors and mutators defined on a class are not "own properties" of the instances of that class. Instead they belong to the prototype for that class (class is just syntactic sugar for declaring a prototype).
Because the functions added to the class are added to the prototype you will need to be careful about context when calling the getter or setter.

class MyClass {
  get MyField() {
    return this._myField
  }
  set MyField(value) {
    this._myField = value
  }
}

const obj = new MyClass()
Object.getOwnPropertyDescriptor(MyClass.prototype, 'MyField').set.call(obj, 'MyValue')
console.log(obj.MyField)

A: Actually, __lookupGetter__ and __lookupSetter__ methods are deprecated. Instead of these you must use:
/* __lookupGetter__ */
Object.getOwnPropertyDescriptor(obj, 'MyField').get;

/* __lookupSetter__ */
Object.getOwnPropertyDescriptor(obj, 'MyField').set;

A: Take a look at lookupGetter.

A: In Google Chrome lookupGetter/lookupSetter is broken: http://code.google.com/p/chromium/issues/detail?id=13175


text:
Q: How to let JSF skip getter method call after clicking of button on that page? Actualy I want after clicking logout session get invalidate. But it is going firstly on getter setter and there I created a session. After that is goes to session invalidate method. And it will throw exception.
How would I skip getter setter on click of button and directly call the action method?

A: Just don't do business job in getters/setters. The getters/setters should solely do the things as their name suggests: returning a property or setting a property. Nothing more. It should not load/preinitialize properties. The loading/preinitializing should be done by a (post)constructor or action(listener) method.
See also:

*

*Why JSF calls getters multiple times


text:
Q: React Storing data for complicated processing I am somewhat new to ReactJS.
I want to store data for complicated computations in ReactJS. Since the setState is asynchronous, I cannot be bothered to store all the required data inside state as it would be next to impossible to do what I want.
I was thinking of doing the following: store the needed variables inside an object inside the state itself. E.g the state defined in the constructor is the following object
constructor(props){
    this.state = { complicated_storage: { x : 123, y : 324 } }
}

This way I can manipulate this.state.compicated_storage.x or this.state.compicated_storage.y, and do stuff like this.state.compicated_storage.x = 4 without worrying about asynchronous behavior.
Is this a bad way of doing stuff in ReactJS. I noticed that with this you can bypass the entire setState mechanism, and just store all my variables inside the object within the state.
Thank You

A:
Is this a bad way of doing stuff in ReactJS. I noticed that with this you can bypass the entire setState mechanism, and just store all my variables inside the object within the state.

The entire purpose of state is re-rendering components whenever it changes. If you modify it directly, such as state.someVariable = 2, React will not know about your change, and it will not rerender your components after the change (however, the change will be reflected if something else later causes a rerender).
If you need a change to some data trigger a rerender and update the view, use state together with setState.
If not, you can simply use a class field, rather than store it inside state.
Besides, I'm not sure in what way asynchrony you think will impede your goals, so perhaps you should be clearer there. State being asynchronous just means that changes to state are made "a little later" after the function is called (it's a whole other topic), so React can batch updates for performance reasons.
Last but not least, you should look into hooks (useState), instead of using class components.


text:
Q: Behavior of setting the model and ng-class I'm reading the AngularJS book from O'REALLY. And in page 28, it says that we can set up the model from the template:

Since expressions execute in the context of the controller's scope associated with their element, setting properties in expressions is the same as setting a property of the controller's scope.

And shown as an example:
<button ng-click='count=3'>...
has the same effect as:
<button ng-click='setCount()'>...
where function
CountController($scope) { $scope.setCount = function() {$scope.count=3; }}

So I tried the following:
<!DOCTYPE html>

        {{restaurant.name}}
        {{restaurant.cuisine}}

The line ng-click = 'selectedRow = $index' is where I'm setting up the module from the view.
But the behavior is that the row clicked gets green and stays green after selecting other row.
On the other hand, if I replace this line with ng-click = 'selectRestaurant($index)', the behavior is, as expected, that the clicked row gets green and fades when other row is clicked.
I don't have a clue on what is happening. Any explanation is welcomed. I would say both ways of changing selectedRow should work fine. But obviously I'm missing something.
Thank you for your help.

A: It's because ng-repeat creates its own child scope, so within the repeat if you have:
ng-click = 'selectedRow = $index'

It set the selectedRow of the child scope - and leaves the parent alone. Now, if you call the function:
ng-click = 'selectRestaurant($index)'
$scope.selectRestaurant = function(row){
     $scope.selectedRow = row;
};

This refers to the selectedRow in the parent scope - thus not allowing more than 1 row to be selected.


text:
Q: Problems increasing an integer in android studio I am making an android studio app and am trying to get my screen to loop through the digits 0-9 until the user clicks and stops the loop on a particular number. The code I have written so far is:
public void loop () {
        for (int a = 0; a<10; a = ++a % 10) {
            textView2.setText("" + a);
        }

Relevant xml section
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="@+id/textView2"
.../>

This code doesn't output anything onscreen. I have tried a few different variations of the code and if it does display a number, it only displays the last digit, '9'. This makes me think that it has worked but it goes through the numbers too quickly for me to see and stops on the last one instead of looping indefinitely. Is anyone able to point out where I may be going wrong? I'm still learning so apologies for the relatively simple query.
Also when I do get it to work, and I want to make it clickable, do I put the onclicklistener in the for-loop?
Many thanks.

A: You were right, when it displays 9, it just looped through the numbers very quickly, you couldn't even see them changing.
You are not doing anything wrong, you just have to take pauses between changing the numbers. The very easy and ugly fix would be adding: wait(1000) after the setText(...) method.
However, this is not recommended, because Android draws and receives events on the main thread. When you block the thread for 1000 milliseconds with the wait, you make the thread unable to accept any events for that one second, which makes your app freeze.
To fix the freezing, you need to update your TextView, and then post a message on the main thread, that it should update again over 1 second. Because of the separation, it won't really look like a loop.
For posting messages on the main thread, I will use a Handler (android.os.Handler), which executes messages on the thread it was created, unless you use a different Looper.
Here's a rough example:
private int a = 0;
private Handler handler = new Handler();
private TextView textView2;

public void loop() {
     handler.post(new Runnable() {
         @Override
         public void run() {
             updateText();
             a = a++ % 10;
             if (a < 10) {
                 handler.postDelayed(this, 1000);
             }
         }
     });
}

public void updateText() {
    textView2.setText("" + a);
}

Just call loop() when the button was clicked, the rest will be handled automatically.


text:
Q: Can cassandra-stress tool be run against existing table data? I have an existing Cassandra test install that I have been testing on.  The table I want to run the cassandra-stress tool against currently has real (not live) data, around 100k rows.  So I was wondering if the tool can be used against that data, or can it only be data that the tool has inserted into an empty table in order to determine write speeds etc?

A: cassandra-stress can certainly use existing tables. You have to create a stress profile, take a look at the yaml files.
You'd have to declare the ks and table definition and define the column-spec which is essentially a profile of what data cells in a row are expected to hold.
Finally you provide a workload and you're good to go:
cassandra-stress user profile=table1.yaml ops (specname.insert=10,specname.read=1000)

Although not directly related, this resource will be useful.


text:
Q: excel vba finding with like or regex I'm writing a VBA program.
I have a problem with finding this string [BLOCKED] in one column
For j = 0 To 4
    For i = 2 To lastrow
        If Cells(i, 12).Value = groupnames(j) And Cells(i, 8).Value Like "*" & "[BLOCKED]" & "*" Then
            groupsum(j) = groupsum(j) + 1
        End If
    Next i
Next j

The problem is I have 96 cells for this string but the program found 500 how can I do this to going work?
Thanks for help

A: The syntax of your Like  operation is incorrect.  Use:
... Like "*[[]BLOCKED]*"

[...] is a Character class.  So, the way you have it written in your question, it will find any single character in the set of BLOCKED.  That is not what you want, apparently.
To match the [ character, you enclose it within a character class, as I have shown.  To match the ] character, it must be outside of a character class.

A: here is my code
Sub blocked()

Dim SfileUsers As String
Dim path As String
Dim pathread As String
Dim sFileread As String
Dim lastrow As Long
Dim keres() As Variant
Dim groupadd() As String
Dim groupnames(4) As String
Dim groupsum(4) As Long

path = "C:\Users\uids9282\Desktop\"
SfileUsers = "Users.xlsx"
Workbooks.Open path & SfileUsers
Dim hossz As Long
hossz = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
ReDim keres(hossz)
ReDim groupadd(hossz)
For i = 2 To hossz
keres(i) = Sheets(1).Cells(i, 2).Value
groupadd(i) = Sheets(1).Cells(i, 4).Value
Next i

'fájlmegnyitás
pathread = "C:\Users\uids9282\Desktop\20170703\"
sFileread = "open.xml"
        If Dir(pathread & sFileread) = sFileread Then
            Workbooks.Open pathread & sFileread
            lastrow = Workbooks(sFileread).Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row

            Else
            MsgBox ("Nincs ilyen nevű excel táblázat. Kérem próbálkozzon újra")
        End If

'groupok hozzáadása a fájlhoz
Dim user As String
For j = 2 To hossz
    For i = 2 To lastrow
    user = Trim(Cells(i, 5).Value)
        If user = keres(j) Then
            Cells(i, 12).Value = groupadd(j)
        End If
    Next i
Next j

'group szummázása és átírása
ThisWorkbook.Activate
For i = 2 To 6
groupnames(i - 2) = Cells(i, 1).Value
Next i
Workbooks(sFileread).Activate
For j = 0 To 4
    For i = 2 To lastrow
        If Cells(i, 12).Value = groupnames(j) And Cells(i, 8).Value Like "*[[]BLOCKED[]]*" Then 'itt van benne a hiba!!         groupsum(j) = groupsum(j) + 1
        End If
    Next i
Next j
ThisWorkbook.Activate
For j = 2 To 6
    Cells(j, 4).Value = groupsum(j - 2)
Next j

Workbooks(SfileUsers).Close SaveChanges:=False
Workbooks(sFileread).Close SaveChanges:=True

End Sub

this is my excel file where i want to searching


text:
Q: ctypes - view c_char_p field of returned struct I've defined a simple C struct called TestStruct and a function init_struct to create an instance and return a pointer to it
#include <stdlib.h>
#include <stdio.h>

typedef struct {
    int x;
    int y;
    char* msg;
} TestStruct;

TestStruct* init_struct(int x, int y, char* msg) {
    TestStruct* p;
    TestStruct initial = {x, y, msg};
    p = malloc(sizeof(TestStruct));
    *p = initial;
    return p;
}

I compile the C code into a .so file using gcc. Then, in Python, I want to create a binding using ctypes that can access all the members of the C struct
import ctypes
import os

class PyStruct(ctypes.Structure):
    _fields_ = [('x', ctypes.c_int),
                ('y', ctypes.c_int),
                ('msg', ctypes.c_char_p)]

lib = ctypes.cdll.LoadLibrary(os.path.abspath('/path/to/libstruct.so'))
_init_struct = lib.init_struct
_init_struct.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_char_p]
_init_struct.restype = ctypes.POINTER(PyStruct)

myStruct = _init_struct(1, 4, ctypes.c_char_p(b'hello world'))
print(myStruct.contents.x, myStruct.contents.y, myStruct.contents.msg)

The integer members of the struct (x and y) print out fine, but I can't figure out how to print the string that msg points to. Instead of the expected hello world, I end up seeing a bytes string b'\x01. My hunch from other reading is that I'm truncating the true, longer string and only showing the first byte.

A: You are passing ctypes.c_char_p(b'hello world') to init_struct and copying the pointer to the c_char_p block in the assignments to initial and p. However, that pointer to the c_char_p block is only valid for the duration of the call to init_struct, i.e., once init_struct returns, that c_char_p pointer will no longer be valid and accessing it will be undefined behavior. In other words, the copy of that pointer you took in myStruct.msg is dangling and should never be accessed outside init_struct.
Remember that ctypes does NOT violate Python's Garbage Collection (GC) rules. In this line myStruct = _init_struct(1, 4, ctypes.c_char_p(b'hello world')) ctypes will allocate some c_char_p object, copy in the string bhello world, null terminate it, and pass the raw pointer to that memory to the C side. Then the C side runs and your code takes a copy of that pointer. When the C side returns, ctypes releases its reference to the c_char_p object. Python's GC then finds that the c_char_p is no longer referenced and so it gets garbage collected. Hence, you end up with a dangling pointer in myStruct.msg.
The proper solution is to clone msg contents inside init_struct and provide a fini_struct function to free that clone memory when you are done with it, something like:
#include <stdlib.h>
#include <stdio.h>

typedef struct {
    int x;
    int y;
    char* msg;
} TestStruct;

TestStruct* init_struct(int x, int y, char* msg) {
    TestStruct* p = malloc(sizeof(TestStruct));
    p->x = x;
    p->y = y;
    p->msg = strdup(msg);
    return p;
}

void fini_struct(TestStruct* p) {
    free(p->msg);
    free(p);
}

Then the python side:
import ctypes
import os

class PyStruct(ctypes.Structure):
    _fields_ = [('x', ctypes.c_int),
                ('y', ctypes.c_int),
                ('msg', ctypes.c_char_p)]

lib = ctypes.cdll.LoadLibrary(os.path.abspath('/path/to/libstruct.so'))
_init_struct = lib.init_struct
_init_struct.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_char_p]
_init_struct.restype = ctypes.POINTER(PyStruct)

_fini_struct = lib.fini_struct
_fini_struct.argtypes = [ctypes.POINTER(PyStruct)]

myStruct = _init_struct(1, 4, ctypes.c_char_p(b'hello world'))
print(myStruct.contents.x, myStruct.contents.y, myStruct.contents.msg)

# when you are done with myStruct
_fini_struct(myStruct)


text:
Q: Add exception in rewriterule nginx Basically I have this rewriterule:
location / {
    rewrite ^/([A-Za-z]+)/?$ /index.php?goto=$1 break;
    rewrite ^/page/([A-Za-z]+)/?$ /index.php?goto=$1&page=$2 break;
}

And works like a charm. The problem is that I have a folder named images (in the same directory of the location, in the root) that I want to avoid to be included in the rewriterule.
When I visit domain.com/images, it gives me the 404 not found error (because is interpreted in the rewriterule) but if I add index.php at the end (the index of the images folder) it works.
Any idea to resolve this issue?
It's not a problem of configuration of nginx, because without rewriterule domain.com/images works without problems.

A: Try adding a negative lookahead to exclude /images in the regex:
location / {
    rewrite ^/(?!images)([A-Za-z]+)/?$ /index.php?goto=$1 break;
    rewrite ^/page/([A-Za-z]+)/?$ /index.php?goto=$1&page=$2 break;
}


text:
Q: Python module urllib3: increase the `maxsize` (max pool size) of HTTPSConnectPool to a host, it make the https request slower I have a code to test the HTTPS requests speed. I use urllib3 module and eventlet.
The code is simple just like below, the pool max size is maxsize=1000.
# -*- coding: utf-8 -*-
import eventlet
eventlet.monkey_patch()
import urllib3
import json

vss=[
    "Project_0ef86f5b-59ab-4036-b460-035fba7cbae2",
] * 20

urls = [
    "https://123.123.123.244:443/mgmt/tm/ltm/virtual/" + \
        "~" + "Project_8a2d7296ae9b4bd4a412eb3cb9aa680e" + "~" + vs
    for vs in vss
]

if __name__ == "__main__":
    http = urllib3.PoolManager(num_pools=2, maxsize=1000)
    headers = urllib3.make_headers(basic_auth='admin:test')
    headers['Content-Type'] = "application/json"

    body = {"connectionLimit": 123}
    encoded_data = json.dumps(body)

    pool = eventlet.greenpool.GreenPool()
    for url in urls:
        pool.spawn(http.request, 'GET', url, headers=headers)
    pool.waitall()

I do some hard code to print some time elapses:
[root@ci-4183549-rdo-pzhang test_icontrol]# python icontrol_get_test.py
Build NEW connection time elapse is 0.001942
Build NEW connection time elapse is 0.012094
Build NEW connection time elapse is 0.013818
Build NEW connection time elapse is 0.013012
Build NEW connection time elapse is 0.007247
Build NEW connection time elapse is 0.010341
Build NEW connection time elapse is 0.013482
Build NEW connection time elapse is 0.020885
Build NEW connection time elapse is 0.013927
Build NEW connection time elapse is 0.009739
Build NEW connection time elapse is 0.016819
Build NEW connection time elapse is 0.015231
Build NEW connection time elapse is 0.022680
Build NEW connection time elapse is 0.013895
Build NEW connection time elapse is 0.015198
Build NEW connection time elapse is 0.035994
Build NEW connection time elapse is 0.024190
Build NEW connection time elapse is 0.017719
Build NEW connection time elapse is 0.013729
Build NEW connection time elapse is 0.013873
EVENTLET GREEN SSL time elapse is 0.051242
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.051957
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.054515
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000169
EVENTLET GREEN SSL time elapse is 0.049463
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.049840
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.060299
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000094
EVENTLET GREEN SSL time elapse is 0.047258
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.047623
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.057479
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000150
EVENTLET GREEN SSL time elapse is 0.057035
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.057440
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.069707
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000529
EVENTLET GREEN SSL time elapse is 0.053266
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.053610
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.067651
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000216
EVENTLET GREEN SSL time elapse is 0.058025
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.058406
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.072347
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000122
EVENTLET GREEN SSL time elapse is 0.073248
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.073845
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.095143
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000396
EVENTLET GREEN SSL time elapse is 0.084811
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.085183
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.098409
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000165
EVENTLET GREEN SSL time elapse is 0.084291
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.084646
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.098489
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000523
EVENTLET GREEN SSL time elapse is 0.086874
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.087236
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.094723
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000176
ACTUAL REQUEST time elapse is 0.150891
ACTUAL REQUEST time elapse is 0.166222
ACTUAL REQUEST time elapse is 0.172489
ACTUAL REQUEST time elapse is 0.208163
ACTUAL REQUEST time elapse is 0.223595
ACTUAL REQUEST time elapse is 0.228818
ACTUAL REQUEST time elapse is 0.241930
ACTUAL REQUEST time elapse is 0.234952
ACTUAL REQUEST time elapse is 0.245768
ACTUAL REQUEST time elapse is 0.253769

EVENTLET GREEN SSL time elapse is 6.222013
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 6.222441
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 6.239439
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000201
EVENTLET GREEN SSL time elapse is 6.234959
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 6.235361
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 6.258194
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000168
EVENTLET GREEN SSL time elapse is 6.241790
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 6.242165
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 6.257899
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000671
EVENTLET GREEN SSL time elapse is 6.280445
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 6.280884
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 6.295080
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000187
EVENTLET GREEN SSL time elapse is 6.299682
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 6.300054
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 6.315421
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000275
EVENTLET GREEN SSL time elapse is 6.308870
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 6.309240
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 6.345404
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000193
EVENTLET GREEN SSL time elapse is 6.345892
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 6.346267
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 6.360176
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000186
EVENTLET GREEN SSL time elapse is 6.363362
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 6.363804
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 6.388216
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000305
EVENTLET GREEN SSL time elapse is 6.368939
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 6.369322
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 6.387182
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000407
EVENTLET GREEN SSL time elapse is 6.373431
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 6.373835
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 6.387855
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000180
ACTUAL REQUEST time elapse is 0.172811
ACTUAL REQUEST time elapse is 0.195098
ACTUAL REQUEST time elapse is 0.187940
ACTUAL REQUEST time elapse is 0.136162
ACTUAL REQUEST time elapse is 0.213076
ACTUAL REQUEST time elapse is 0.145465
ACTUAL REQUEST time elapse is 0.194409
ACTUAL REQUEST time elapse is 0.150222
ACTUAL REQUEST time elapse is 0.152019
ACTUAL REQUEST time elapse is 0.182908

From the above log, There are 20 requests sent, I find it very slow to do the first HTTPS connection SSL validation (as log SLOW validate). And it seems every 10 requests is about 5-6 seconds slower than previous requests.
after the SSL validation handshake, I also log the new connection time Build NEW and actual request time ACTUAL REQUEST, they seem faster than the SSL handshake.
The weird things happened, when I change the pool max size to 1 as maxsize=1. the code is just as below:
ACTUAL REQUEST time elapse is 0.166906
# -*- coding: utf-8 -*-
import eventlet
eventlet.monkey_patch()
import urllib3
import json

vss=[
    "Project_0ef86f5b-59ab-4036-b460-035fba7cbae2",
] * 20

urls = [
    "https://123.123.123.244:443/mgmt/tm/ltm/virtual/" + \
        "~" + "Project_8a2d7296ae9b4bd4a412eb3cb9aa680e" + "~" + vs
    for vs in vss
]

if __name__ == "__main__":
    http = urllib3.PoolManager(num_pools=2, maxsize=1)
    headers = urllib3.make_headers(basic_auth='admin:test')
    headers['Content-Type'] = "application/json"

    body = {"connectionLimit": 123}
    encoded_data = json.dumps(body)

    pool = eventlet.greenpool.GreenPool()
    for url in urls:
        pool.spawn(http.request, 'GET', url, headers=headers)
    pool.waitall()

The only change is maxsize=1. Then I run the code again. I found it faster than before.
And the log is:
[root@ci-4183549-rdo-pzhang test_icontrol]# python icontrol_get_test.py
Build NEW connection time elapse is 0.015360
Build NEW connection time elapse is 0.017999
Build NEW connection time elapse is 0.025342
Build NEW connection time elapse is 0.021459
Build NEW connection time elapse is 0.023889
Build NEW connection time elapse is 0.026711
Build NEW connection time elapse is 0.031111
Build NEW connection time elapse is 0.027637
Build NEW connection time elapse is 0.023971
Build NEW connection time elapse is 0.025077
Build NEW connection time elapse is 0.030668
Build NEW connection time elapse is 0.029985
Build NEW connection time elapse is 0.034746
Build NEW connection time elapse is 0.028624
Build NEW connection time elapse is 0.029502
Build NEW connection time elapse is 0.037975
Build NEW connection time elapse is 0.036091
Build NEW connection time elapse is 0.031267
Build NEW connection time elapse is 0.022034
Build NEW connection time elapse is 0.021854
EVENTLET GREEN SSL time elapse is 0.050881
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.051288
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.075853
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000185
EVENTLET GREEN SSL time elapse is 0.058581
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.066372
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.084548
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000120
EVENTLET GREEN SSL time elapse is 0.062094
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.062490
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.089335
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000427
EVENTLET GREEN SSL time elapse is 0.060111
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.060585
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.085756
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000099
EVENTLET GREEN SSL time elapse is 0.066614
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.067027
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.088786
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000196
EVENTLET GREEN SSL time elapse is 0.065821
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.066171
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.097392
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000093
EVENTLET GREEN SSL time elapse is 0.082791
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.083365
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.098947
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000248
EVENTLET GREEN SSL time elapse is 0.074760
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.075168
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.099560
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000750
EVENTLET GREEN SSL time elapse is 0.078279
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.078932
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.105360
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000234
EVENTLET GREEN SSL time elapse is 0.076575
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.077019
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.105298
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000373
ACTUAL REQUEST time elapse is 0.151813
ACTUAL REQUEST time elapse is 0.179453
ACTUAL REQUEST time elapse is 0.184682
ACTUAL REQUEST time elapse is 0.207302
EVENTLET GREEN SSL time elapse is 0.270626
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.271068
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.301941
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000250
EVENTLET GREEN SSL time elapse is 0.276534
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.276893
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.307036
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000199
EVENTLET GREEN SSL time elapse is 0.277267
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.277619
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.312475
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000135
ACTUAL REQUEST time elapse is 0.229100
ACTUAL REQUEST time elapse is 0.219073
ACTUAL REQUEST time elapse is 0.241250
ACTUAL REQUEST time elapse is 0.243543
EVENTLET GREEN SSL time elapse is 0.325758
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.326065
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.354829
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000165
EVENTLET GREEN SSL time elapse is 0.329577
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.329849
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.366091
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000175
EVENTLET GREEN SSL time elapse is 0.331157
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.331404
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.361000
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000110
ACTUAL REQUEST time elapse is 0.266746
EVENTLET GREEN SSL time elapse is 0.341352
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.341600
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.379702
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000261
ACTUAL REQUEST time elapse is 0.278251
EVENTLET GREEN SSL time elapse is 0.362323
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.362653
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.394090
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000209
EVENTLET GREEN SSL time elapse is 0.372634
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.372951
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.395210
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000165
ACTUAL REQUEST time elapse is 0.158835
ACTUAL REQUEST time elapse is 0.154795
ACTUAL REQUEST time elapse is 0.180860
EVENTLET GREEN SSL time elapse is 0.457490
URLLIB3 CONNECTION SLOW TIME after build new connection time elapse is 0.457814
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:855: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/security.html
  InsecureRequestWarning)
SLOW validate connection time elapse is 0.479805
CONNECTIONPOOL after ssl validation Request with ARGS connection time elapse is 0.000156
ACTUAL REQUEST time elapse is 0.165210
ACTUAL REQUEST time elapse is 0.170411
ACTUAL REQUEST time elapse is 0.183082
ACTUAL REQUEST time elapse is 0.182051
ACTUAL REQUEST time elapse is 0.173406
ACTUAL REQUEST time elapse is 0.195164
ACTUAL REQUEST time elapse is 0.144579

As you can see, the SSL validation time SLOW validate for each request is decreased dramatically.
I dig the code to eventlet ssl, and I find it also slow (as log EVENTLET GREEN SSL indicates) when maxsize is 1000, and it becomes faster when the maxsize is 1.
I do not get why it behaves like this. I am sure it may be related to the urllib3 module since its parameter does change the performance.
Anyone could give me some hints, Thanks a lot.


text:
Q: Refresh WPF DataGrid without losing cell focus I have a WPF DataGrid with some data bound to LINQ to SQL entity classes. One column is a clock showing a given flight's airborn time, which is calculated using logic in Flight's partial class. I have a timer calling datagrid.Items.Refresh every 2 seconds to update the clock.
The refresh works fine, but now I'm adding keyboard shortcuts. Navigating through cells with the keyboard arrows works fine with the timer off, but with the Refresh timer enabled, the focused cell (actually the entire datagrid) loses focus.
I need to either somehow maintain focus (preferred) or disable the timer whenever the DataGrid is focused. I can't even seem to get the latter to work. I've tried:
if (!dataGrid.IsFocused)
    dataGrid.Items.Refresh();

and
if (!dataGrid.IsKeyboardFocused)
        dataGrid.Items.Refresh();

for the timer, but these properties return false even when the datagrid is focused.
Any ideas?

A: The best way is not to use dataGrid.Items.Refresh() as update mechanism. It sounds like the underlying objects are already updated separately. If they implement INotifyPropertyChanged, you should try  to set the binding mode for the colum as TwoWay Binding:
<DataGridTextColumn Binding="{Binding xyz, Mode=TwoWay}"/>

A: i think you may get the present focus and after grid is refreshed give the selected cell back its focus something like
int index = 11;
myDataGrid.SelectedItem = myDataGrid.Items[index];
myDataGrid.ScrollIntoView(myDataGrid.Items[index]);
DataGridRow dgrow = (DataGridRow)myDataGrid.ItemContainerGenerator.ContainerFromItem(myDataGrid.Items[index]);
dgrow.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

also check this out it may help you

A: Your cells lose focus because you change the underlying collection (ItemsSource). There is no beautiful way, as far as I recall, to get the cell. For the row :
If you work with MVVM, you can memorize your SelectedItem or SelectedIndex and restore it after the reload is done by binding. That will get you in the right row, for a start.  Both have different drawbacks:

*

*SelectedItem requires a bit more work. Make sure you override Equals and GetHashCode in the underlying objects if you use it. If your item was number 5 in the collection and during the reload another row appears before it, you will still end up in the right line

*SelectedIndex is the quickest solution, but is only a numeric position. If you select entry number 5 and the reload merges in rows before it, you will end up with the wrong selected row.

As I said, I haven't tried with the cells, but you can read this for a start. Maybe you can apply it to your issue.


text:
Q: How to combine two queries into one output I have two queries that help with roster cleanup in my system. The first query shows all headcount that is hourly or salaried and is in a wrong cost center. The second query shows all headcount that is linked with a closed station. Both hc I want to cleanup and show in a query.
SELECT emplid,
employee_login,
employee_full_name,
reports_to_level_7_employee_name,
job_level_name,
employee_business_title ,
reports_to_level_8_employee_name,
costcenter_id,
location_building_code,
company_country_code,
employee_type_short_name,
CASE
When department_id = '1092' and employee_type_short_name = 'S' then '1172'
When department_id = '1172' and employee_type_short_name = 'H' then '1092'
else employee_type_short_name
end as "incorrect_mapp"
FROM pm_employee_headcount_conf pehc
left join wbr_global.raw_station_extended_attribute rsea on pehc.location_building_code =      rsea.location_code
 WHERE current_transaction_flag = 'Y'
 and incorrect_mapp <> 'S'
 and incorrect_mapp <> 'H'
 and department_id in('1092','1172')
and company_country_code in('USA','CAN')
and job_level_name <>  99
 and job_level_name <> 0
 and job_level_name <> 1
 and job_level_name <> 2

SELECT emplid,
employee_login,
employee_full_name,
reports_to_level_7_employee_name,
  job_level_name,
employee_business_title ,
reports_to_level_8_employee_name,
costcenter_id,
  location_building_code,
company_country_code,
employee_type_short_name,
rsea.status
FROM pm_employee_headcount_conf pehc
left join wbr_global.raw_station_extended_attribute rsea on pehc.location_building_code = rsea.ds
WHERE current_transaction_flag = 'Y'
and department_id in('1092','1172')
and company_country_code in('USA','CAN')
and job_level_name <> 99
and job_level_name <> 0
and job_level_name <> 1
and job_level_name <> 2
and status <> 'Active'
and status <> 'Launch'

A: Use UNION ALL between the two queries; that will make it one query and append the results from the second to those from the first (the number and type of respective columns must be identical; naturally!)

A: Use UNION operator to combine the result-set of two or more SELECT statements.
The columns must also have similar data types, in every SELECT statement must also be in the same order.
SELECT emplid,
employee_login,
employee_full_name,
reports_to_level_7_employee_name,
job_level_name,
employee_business_title ,
reports_to_level_8_employee_name,
costcenter_id,
location_building_code,
company_country_code,
employee_type_short_name,
CASE
When department_id = '1092' and employee_type_short_name = 'S' then '1172'
When department_id = '1172' and employee_type_short_name = 'H' then '1092'
else employee_type_short_name
end as "incorrect_mapp"
FROM pm_employee_headcount_conf pehc
left join wbr_global.raw_station_extended_attribute rsea on pehc.location_building_code =      rsea.location_code
 WHERE current_transaction_flag = 'Y'
 and incorrect_mapp <> 'S'
 and incorrect_mapp <> 'H'
 and department_id in('1092','1172')
and company_country_code in('USA','CAN')
and job_level_name <>  99
 and job_level_name <> 0
 and job_level_name <> 1
 and job_level_name <> 2

UNION ALL

SELECT emplid,
employee_login,
employee_full_name,
reports_to_level_7_employee_name,
  job_level_name,
employee_business_title ,
reports_to_level_8_employee_name,
costcenter_id,
  location_building_code,
company_country_code,
employee_type_short_name,
rsea.status
FROM pm_employee_headcount_conf pehc
left join wbr_global.raw_station_extended_attribute rsea on pehc.location_building_code = rsea.ds
WHERE current_transaction_flag = 'Y'
and department_id in('1092','1172')
and company_country_code in('USA','CAN')
and job_level_name <> 99
and job_level_name <> 0
and job_level_name <> 1
and job_level_name <> 2
and status <> 'Active'
and status <> 'Launch'


text:
Q: Distribution of objects into boxes I had been facing problems with questions on distribution of objects into boxes lately. I thought that it would be a nice idea to frame a general question that covers all cases. It would also help other users on this site as well including me. I would greatly appreciate any help i get.
Question: In how many ways can $a$ objects be distributed into $b$ boxes taking into account all the possibilities (distinct and non-distinct) for both the objects and the boxes. ($a$ may be greater than $b$ or may be less than $b$)
There are 8 cases possible.
When a < b
CASE 1: All the objects are distinct and all the boxes are distinct
CASE 2: All the objects are distinct and all the boxes are non-distinct
CASE 3: All the objects are non-distinct and all the boxes are distinct
CASE 4: All the objects are non-distinct and the boxes are non-distinct
When a > b
CASE 1: All the objects are distinct and all the boxes are distinct
CASE 2: All the objects are distinct and all the boxes are non-distinct
CASE 3: All the objects are non-distinct and all the boxes are distinct
CASE 4: All the objects are non-distinct and the boxes are non-distinct
What would be the best way to proceed in each case? What does it mean when we say that all the boxes are distinct?


text:
Q: Undefined Property and PHP Fatal Error: Allowed memory exhausted when querying mssql from php through unixODBC/FreeTDS After upgrading php from version 5.2.10 to 5.3.3 I am getting a very strange set of errors when using odbc queries that works fine in 5.2.10.
I get a lot of Undefined Property: stdClass::$username finally ending in a Memory Exhaust Allowed error when I run queries like the following:
    $conn = odbc_connect("dsn", "user", "pw") or die(odbc_error_msg());

    $query = "select usr_n as username from usr";
    $rs = odbc_exec($conn,$query);

    while ($rows = odbc_fetch_object($rs)) {
        echo "$rows->username";
        }
    odbc_free_result($rs);
    odbc_close($conn);

the strange part is that if I run this code without the 'username' alias and use the table name as shown in the query underneath, it works fine:
    $conn = odbc_connect("dsn", "user", "pw") or die(odbc_error_msg());

    $query = "select usr_n from usr";
    $rs = odbc_exec($conn,$query);

    while ($rows = odbc_fetch_object($rs)) {
        echo "$rows->usr_n";
        }
    odbc_free_result($rs);
    odbc_close($conn);

also if I use alias with a count(*) statement it works fine, but as soon as I replace a tablename with an alias it all goes wrong.
I tried the query in iSQL with the alias, and it works like it is supposed to, so the unixODBC and FreeTDS is working.
I have searched through all the material I could find both here and google, but havent got any answer to why this is happening.
Appreciate it if anyone here has an idea to what is going on here, as it seems to me to have something to do with aliases and I use aliases a lot.
BTW: Upgrading php is sadly not an option for me.

A: In my case the problem was accented characters (spanish). I solved this adding Collate SQL_Latin1_General_CP1253_CI_AI to every field with this chars on every SELECT.


text:
Q: Run time error when running very simple program (C++) I wrote a program as part of a learning exercise that takes doubles as inputs, and outputs the total sum of all the doubles, as well as the smallest, largest, and the mean. When trying to run the program, I get this run time error:
 Unhandled exception at 0x74b01d4d in Hello World.exe: Microsoft C++ exception: Range_error at memory location 0x00dcf760.

When I use the Visual Studio 2010 debug option, I get vector subscript is out of range.
The code is:
#include "C:\Users\Kevin\Documents\Visual Studio 2010\Projects\std_lib_facilities.h"

int main() {
    vector<double> v;
    double number = 0;
    cout << "Enter the distance between two cities along the route.\n";
    while (cin >> number) {
        double sum = 0;
        v.push_back(number);
        sort(v.begin(),v.end());
        for (size_t i = 0; i < v.size(); ++i)
            sum += v[i];
        cout << "The total distance from each city is " << sum
                     << ". The smallest distance is " << v[0]
                     << " and the greatest distance is " << v[v.size()]
                     <<". The mean distance is " << sum/v.size() <<".\n";
        cout << "Enter the distance between two cities along the route.\n";}
}

I had to change the type of the variable defined in the for loop because I was getting a signed/unsigned mismatch error. The code gives no errors when compiled and I am having difficulty seeing the problem.

A: " and the greatest distance is " << v[v.size()]

is an undefined behavior because the last index in vector is v.size() - 1 if v.size() > 0 (if v.size() = 0 there is no items and nothing to subscript)
You should thus write:
if( !v.empty())
    std::cout << " and the greatest distance is " << v[ v.size() - 1];

or better;
if ( !v.empty()) {
    std::cout << " and the greatest distance is " << v.back();

std::vector::back


text:
Q: AVCaptureDeviceType crashing on iPad Obejective-C I am having the same code as on Apple Documentation:
https://developer.apple.com/library/archive/samplecode/AVCam/Listings/Objective_C_AVCam_AVCamCameraViewController_m.html#//apple_ref/doc/uid/DTS40010112-Objective_C_AVCam_AVCamCameraViewController_m-DontLinkElementID_7
NSArray<AVCaptureDeviceType> *deviceTypes = @[AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeBuiltInDualCamera];

Code breaks on this line.
Stack trace screenshot is attached. Stack Trace Screeshot

A: Take reference from the link below.This solved my problem for camera crashing on iPads with lower iOS versions.
https://github.com/imjerrybao/AVCam

Also make sure where your app is crashing.
  If it is Crashing because of core data(NSPersistentContainer) on lower versions of iOS, try using: INSPersistentContainer instead.

https://github.com/inspace-io/INSPersistentContainer


text:
Q: linux-modules-extra-4.15.0-59-generic needs to be reinstalled but can't find an archive for it I am running ubuntu 18.04.3 LTS. For last few days I am getting this error "linux-modules-extra-4.15.0-59-generic needs to be reinstalled but can't find an archive for it" whenever I check for software updates from "Settings->Details->Check for updates"
I have tried the following from the terminal but am getting the same message
sudo apt-get update
sudo apt-get upgrade

This throws an error "The package linux-modules-extra-4.15.0-59-generic needs to be reinstalled but I can't find an archive for it".
I tried
sudo apt-get install --reinstall linux-modules-extra-4.15.0-59-generic

Still the same error
I also tried
sudo apt-get install -f linux-modules-extra-4.15.0-59-generic

Still the same error
Thus no software updates are getting installed