text:
Q: Why does adding local variables causes delay in method? I have recently started reading about benchmarks and writing them for Android (in Java). I am aware of such problems as warmups, garbage collector and compiler optimizations but don't know if the problem I face could be caused by any of those.
In my benchmark app I create an array of 10,000 float variables and initialize it with random values.
When running benchmark code:
private void runMinorBenchmarkFloat (float[] array) {
        float sum = 0;
        long startTime;
        long endTime;

        /* Fast warm-up */
        startTime = System.nanoTime();
        for(int i=0; i<SMALL_LOOP_ITERATION_COUNT; i++)
            for(int j=0; j<TAB_SIZE; j++)
                sum += array[j];
        endTime = System.nanoTime() - startTime;
        postMessage("Warm-up for FLOAT finished in: " + endTime/1000000 + "ms.\n");

        /* Main benchmark loop */
        startTime = System.nanoTime();
        for(int i=0; i<BIG_LOOP_ITERATION_COUNT; i++)
        {
            sum = 0;
            for(int j=0; j<TAB_SIZE; j++)
                sum += array[j];
        }
        endTime = System.nanoTime() - startTime;
        postMessage("Benchmark for FLOAT finished in: " + endTime/1000000 + "ms.\n");
        postMessage("Final value: " + sum + "\n\n");
    }

on my phone I get around 2 seconds for warmup and 20 seconds for "real" loop.
Now, when I add two more float variables (sum2 and sum3 - never used inside the method):
private void runMinorBenchmarkFloat (float[] array) {
        float sum = 0, sum2 = 0, sum3 = 0; // <------- the only code change here!!!
        long startTime;
        long endTime;

        /* Fast warm-up */
        startTime = System.nanoTime();
        for(int i=0; i<SMALL_LOOP_ITERATION_COUNT; i++)
            for(int j=0; j<TAB_SIZE; j++)
                sum += array[j];
        endTime = System.nanoTime() - startTime;
        postMessage("Warm-up for FLOAT finished in: " + endTime/1000000 + "ms.\n");

        /* Main benchmark loop */
        startTime = System.nanoTime();
        for(int i=0; i<BIG_LOOP_ITERATION_COUNT; i++)
        {
            sum = 0;
            for(int j=0; j<TAB_SIZE; j++)
                sum += array[j];
        }
        endTime = System.nanoTime() - startTime;
        postMessage("Benchmark for FLOAT finished in: " + endTime/1000000 + "ms.\n");
        postMessage("Final value: " + sum + "\n\n");
    }

execution time jumps from 2 seconds for warmup to 5 seconds and from 20 seconds for real loop to 50 seconds.
The constants:
SMALL_LOOP_ITERATION_COUNT = 100,000
BIG_LOOP_ITERATION_COUNT = 1,000,000

Do you think that such difference could be caused by alignment problems (just loose idea)?
Thanks in advance for any answers.
EDIT:
It seems like this error does not appear on every device. I can reproduce it on Samsung Galaxy S5.
The main goal of the program was to make little benchmark. I did four almost-the-same functions (runMinorBenchmark____ where _ was either: int, short, float, double) which differed only in variable 'sum' type. In the main benchmark function I invoked those functions. Because the mentioned error occured I decided to merge those function into one big one.
Now... When running test I have such times:
 1. 37640ms. (for int)
 2. 46728ms. (for short)
 3. 60589ms. (for float)
 4. 34467ms. (for double)
I know that short is meant to be slower because of type casting. I also thought that float should be slower in case of casting it to double (maybe FPU does type casting to double every time(?)). But when I change variable type for sumFloat from float to double the time for float is identical to double time.
I also did this "benchmark" on one other device which seemed to not suffer from this strange behaviour and the times for every test were almost the same: ~45000ms. (really no visible differences).
Dalvik VM error (?)

A: I refuse to believe that is the cause of your trouble. Surely the compiler just chucks those unused variables away? Are you sure the input array doesn't change, or your constants, or TAB_SIZE?
If you're still sure, prove it by running something like this and pasting the output here:
public void proveIt() {
    float[] inputArray = new float[10000];
    for (int i = 0; i < 10000; i++) {
        inputArray[i] = 1;
    }

    postMessage("Without declaration:");
    runMinorBenchmarkFloatA(inputArray);

    postMessage("With declaration:");
    runMinorBenchmarkFloatB(inputArray);

    postMessage("And again just to make sure...");

    postMessage("Without declaration:");
    runMinorBenchmarkFloatA(inputArray);

    postMessage("With declaration:");
    runMinorBenchmarkFloatB(inputArray);
}

long TAB_SIZE = 10000;
long SMALL_LOOP_ITERATION_COUNT = 100000;
long BIG_LOOP_ITERATION_COUNT = 1000000;

private void runMinorBenchmarkFloatA(float[] array) {
    float sum = 0;
    long startTime;
    long endTime;

    /* Fast warm-up */
    startTime = System.nanoTime();
    for (int i = 0; i < SMALL_LOOP_ITERATION_COUNT; i++)
        for (int j = 0; j < TAB_SIZE; j++)
            sum += array[j];
    endTime = System.nanoTime() - startTime;
    postMessage("Warm-up for FLOAT finished in: " + endTime
            / 1000000 + "ms.\n");

    /* Main benchmark loop */
    startTime = System.nanoTime();
    for (int i = 0; i < BIG_LOOP_ITERATION_COUNT; i++) {
        sum = 0;
        for (int j = 0; j < TAB_SIZE; j++)
            sum += array[j];
    }
    endTime = System.nanoTime() - startTime;
    postMessage("Benchmark for FLOAT finished in: " + endTime
            / 1000000 + "ms.\n");
    postMessage("Final value: " + sum + "\n\n");
}

private void runMinorBenchmarkFloatB(float[] array) {
    float sum = 0, sum2 = 0, sum3 = 0;
    long startTime;
    long endTime;

    /* Fast warm-up */
    startTime = System.nanoTime();
    for (int i = 0; i < SMALL_LOOP_ITERATION_COUNT; i++)
        for (int j = 0; j < TAB_SIZE; j++)
            sum += array[j];
    endTime = System.nanoTime() - startTime;
    postMessage("Warm-up for FLOAT finished in: " + endTime
            / 1000000 + "ms.\n");

    /* Main benchmark loop */
    startTime = System.nanoTime();
    for (int i = 0; i < BIG_LOOP_ITERATION_COUNT; i++) {
        sum = 0;
        for (int j = 0; j < TAB_SIZE; j++)
            sum += array[j];
    }
    endTime = System.nanoTime() - startTime;
    postMessage("Benchmark for FLOAT finished in: " + endTime
            / 1000000 + "ms.\n");
    postMessage("Final value: " + sum + "\n\n");
}

A:
Now, when I add two more float variables (sum2 and sum3 - never used inside the method):

float sum = 0, sum2 = 0, sum3 = 0; // <------- the only code change here!!!

But sum2 and sum3 are used inside the method. They are initialized to zero. This costs time.
If they weren't initialized, the generated byte code would be identical with and without them, apart from the size of the stack frame allocated, which doesn't affect timing.


text:
Q: UserControl in vb6.0 getting border in Windows 7 In my VB6 application, a UserControl is used. Recently we moved to Windows 7 from Windows XP. In Windows 7 the UserControl is getting borders on the top and the left.
Please tell me how to remove those borders.
Ii have attached the image below.
On top of the UserControl there is a ListBox. On the UserControl, the top and left borders are visible.

A: Without code it is hard to tell, but perhaps you are using Width and Height instead of ScaleWidth and ScaleHeight in your painting?  The latter will give you the size of the client area you are working with.
Again, just a guess until we see some code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ElasticSearch nested document search with AND operator Here it is stated in nested documents, without using nested query it is not possible to retrieve document which satisfies multiple conditions at the same time through nested document's fields. Here also another explanation with example at beginning. Why does not it retrieve the only doc which satisfies all conditions?

A: if you need multiple conditions with nested queries, why not to use bool query or bool filtered query?


text:
Q: PyArg_ParseTuple SegFaults in CApi I am writing a code, trying to get used to the C API of NumPy arrays.
#include <Python.h>
#include "numpy/arrayobject.h"
#include <stdio.h>
#include <stdbool.h>

static char doc[] =
"Document";

static PyArrayObject *
    trace(PyObject *self, PyObject *args){

    PyArrayObject *matin;

    if (!PyArg_ParseTuple(args, "O!",&PyArray_Type, &matin))
         return NULL;

    printf("a");
    return matin;
}

static PyMethodDef TraceMethods[] = {
    {"trace", trace, METH_VARARGS, doc},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
inittrace(void)
{
    (void) Py_InitModule("trace", TraceMethods);
    import_array();
}

This is a stripped-down version. I just want to be able to get an object of type PyArrayObject and return it back. Unfortunately this gives a SegFault also.
Linux, 64-bit, Python 2.7.1

A: From the docs:

O (object) [PyObject *]
Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object's reference count is not increased. The pointer stored is not NULL.
O! (object) [typeobject, PyObject *]
Store a Python object in a C object pointer. This is similar to O, but...

You're returning a stolen reference. Increment it first.


text:
Q: UnsatisfiedLinkError nativeLibraryDirectories=[/vendor/lib64, /system/lib64 The situation is as follows:
I have a 64 bit apk which should a 32bit shared object(.so file) from /system/lib. But the apk crashes when running and reports:
UnsatisfiedLinkError nativeLibraryDirectories=[/vendor/lib64, /system/lib64

I think it tries to search my .so file which is located in /system/lib from /system/lib64, then error happens.
How could I make it search from /system/lib instead of /system/lib64?

A: This is happening because you are bundling at least one 64-bit native library.  Android detects this and decides to seek out the rest of the .so files in 64-bit only locations.  It doesn't find them because you are only building for 32-bit architectures.
To verify that this is your problem, open up the built apk and look in the "lib" dir.  Each subdirectory therein represents a native binary architecture.  If you are not building all of the native .so files for that architecture, the directory shouldn't be there.  Find out why it is and stop it.
One example of this is Crashlytics which can quietly bundle itself.  The resulting crash only appears on 64-bit devices because 32-bit devices never search 64-bit architecture directories.
You have to prune the architectures you are not fully supporting from all your third party middleware.

A: If you have only x86 and armeabi-v7a libraries, your app should automatically be installed in "32-bit mode".
Try to use this in your gradle file:
android {
    ....
    defaultConfig {
        ....
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
    }
}


text:
Q: Detele files depending of date in Powershell I need to remove all files that are from 2014 with the extension of .png, excluding the folders with Powershell.
This is as far as I got:
Remove-Item X:\path\* -include .png -recurse

How do I get the date of the files so I can delete only the .png files that are from 2014?

A: Get-ChildItem -Recurse -Filter *.png |
Where-Object {$_.LastWriteTime -match '2014'} |
% {"Deleting $($_.FullName)"; Remove-Item $_.FullName}

Add the -Force after the Remove-Item if you don't want it to ask you before deletion of each file


text:
Q: Activity not found exception Android Here is the error in logcat:
FATAL EXCEPTION: Thread-8
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.slehmann.volumetimechanger.MAINACTIVITY }

Here is my manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.slehmann.volumetimechanger"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:screenOrientation="portrait"
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="com.slehmann.volumetimechanger.APP" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <receiver  android:process=":remote" android:name="AlarmReceiver"/>
          <activity
            android:screenOrientation="portrait"
            android:label="@string/app_name"
            android:name=".splash" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Here is my intent:
} finally {
    Intent openMenus = new Intent("com.slehmann.volumetimechanger.MAINACTIVITY");
    startActivity(openMenus);
}

A: You should use
} finally { Intent openMenus = new Intent("com.slehmann.volumetimechanger.APP"); startActivity(openMenus); }

or
 } finally { Intent openMenus = new Intent(CLASSNAME.this, TARGETCLASSNAME.class); startActivity(openMenus); }

or change the manifest.xml
<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:screenOrientation="portrait"
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="com.slehmann.volumetimechanger.MAINACTIVITY" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <receiver  android:process=":remote" android:name="AlarmReceiver"></receiver>
      <activity
        android:screenOrientation="portrait"
        android:label="@string/app_name"
        android:name=".splash" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />

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

A: you have a silly mistake, your activity name is MainActivity and in your intent call you have declared it as MAINACTIVITY for that reason that happening. It would be like --
finally {
                Intent openMenus = new Intent("com.slehmann.volumetimechanger.MainActivity");
                startActivity(openMenus);
            }

A: your activity name is MainActivity into manifest and When call intent then use MAINACTIVITY for that reason that happening. Remember about the uppercase and lowercase.
and another thing:
Only One activity should be registered with the Category of Launcher.
<activity android:name=".FirstClassName"
      android:label="@string/app_name">
 <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
</activity>

Other Activities Should be Declare like this with no Extra Permissions.
<activity android:name=".SecondClassName"/>

So declare into manifest:
<activity
    android:screenOrientation="portrait"
    android:name=".MainActivity"
    android:label="@string/title_activity_main" >

</activity>

Remove the
<intent-filter>
     //
      </intent-filter>

From the  manifest for the MainActivity declare.


text:
Q: TFramedTransport Error on PHPCassa + Cassandra  We're deleting a massive number of records in Cassandra. We get the following error. We also get this error when we insert a massive number of records:
Error performing remove on 10.130.279.40:9160: exception 'TTransportException' with message 'TSocket: timed out reading 4 bytes from 10.130.279.40:9160' in /home/zonefiles/php/thrift/transport/TSocket.php:268
    Stack trace:
    0 /home/zonefiles/php/thrift/transport/TTransport.php(87): TSocket->read(4)
    1 /home/zonefiles/php/thrift/transport/TFramedTransport.php(135): TTransport->readAll(4)
    2 /home/zonefiles/php/thrift/transport/TFramedTransport.php(102): TFramedTransport->readFrame()
    3 [internal function]: TFramedTransport->read(8192)
    4 /home/zonefiles/php/thrift/packages/cassandra/Cassandra.php(691): thrift_protocol_read_binary(Object(TBinaryProtocolAccelerated), 'cassandra_Cassa...', false)
    5 /home/zonefiles/php/thrift/packages/cassandra/Cassandra.php(664): CassandraClient->recv_remove()
    6 [internal function]: CassandraClient->remove('CUSTOMERSERVICE...', Object(cassandra_ColumnPath), 1301555573936295, 1)
    7 /home/zonefiles/php/connection.php(230): call_user_func_array(Array, Array)
    8 /home/zonefiles/php/columnfamily.php(582): ConnectionPool->call('remove', 'CUSTOMERSERVICE...', Object(cassandra_ColumnPath), 1301555573936295, 1)
    9 /home/zonefiles/php/delete.php(34): ColumnFamily->remove('CUSTOMERSERVICE...')
    10 {main}
    Error connecting to 10.130.279.40:9160: exception 'TTransportException' with message 'TSocket: timed out reading 4 bytes from 10.130.279.40:9160' in /home/zonefiles/php/thrift/transport/TSocket.php:268
    Stack trace:
    0 /home/zonefiles/php/thrift/transport/TTransport.php(87): TSocket->read(4)
    1 /home/zonefiles/php/thrift/transport/TFramedTransport.php(135): TTransport->readAll(4)
    2 /home/zonefiles/php/thrift/transport/TFramedTransport.php(102): TFramedTransport->readFrame()
    3 [internal function]: TFramedTransport->read(8192)
    4 /home/zonefiles/php/thrift/packages/cassandra/Cassandra.php(1015): thrift_protocol_read_binary(Object(TBinaryProtocolAccelerated), 'cassandra_Cassa...', false)
    5 /home/zonefiles/php/thrift/packages/cassandra/Cassandra.php(992): CassandraClient->recv_describe_version()
    6 /home/zonefiles/php/connection.php(63): CassandraClient->describe_version()
    7 /home/zonefiles/php/connection.php(163): ConnectionWrapper->__construct('CDTMain1', '10.130.279.40:9...', NULL, true, 5000, 5000)
    8 /home/zonefiles/php/connection.php(254): ConnectionPool->make_conn()
    9 /home/zonefiles/php/connection.php(241): ConnectionPool->handle_conn_failure(Object(ConnectionWrapper), 'remove', Object(TTransportException), 1)
    10 /home/zonefiles/php/columnfamily.php(582): ConnectionPool->call('remove', 'CUSTOMERSERVICE...', Object(cassandra_ColumnPath), 1301555573936295, 1)
    11 /home/zonefiles/php/delete.php(34): ColumnFamily->remove('CUSTOMERSERVICE...')
    12 {main}

Here is the PHP we use to generate the error:
<?php
set_time_limit(2000);
require 'connection.php';
require 'columnfamily.php';
$servers[0]['host'] = 'private ip';
$servers[0]['port'] = '9160';
$conn = new Connection('Server11', $servers);
$urlFamily = new ColumnFamily($conn, 'Domain'); // ColumnFamily

$start = microtime(true);

$limit = 100000000;

$rows = $urlFamily->get_range($key_start='', $key_finish='zzzzzzzzzzzzzzz',100000000);

$num = 0;
$delCount = 0;

foreach($rows as $key => $columns) {
   // Do stuff with $key or $columns
       if (strpos($key, ' .net') !== false) {
               //echo 'deleting ' . $key . "\n";
               $urlFamily->remove($key);
               $delCount++;
       }
       if ($num++ > 100000000) break;
       //$num++;
       if ($num % 100000 == 0) echo $num . "\n";
}

$end = microtime(true);

echo $num . " total\n";
echo $delCount . ' deleted in ' . ($end - $start) . " seconds\n";
echo $delCount / ($end - $start) . " deleted per second\n";

?>

We are running PHP 5.3.5 on Fedora 14 Laughlin and Thrift 0.5.0.
One theory is that this is caused by a Cassandra not being able to process the commands fast enough. Do you agree/disagree? Have you seen this before?
If you recommend deleting a different way (e.g. Truncate), how do we still prevent this issue from happening when we do other things with Cassandra?

A: Are those just log messages, or is an exception actually being raised? phpcassa calls error_log() every time that an exception like this is caught before retrying with a different connection.  Basically, this means that you should keep an eye on the stack traces that get logged, but you don't need to worry too much about them.
Those are client-side socket timeouts, which means that the call has taken longer than the default timeout of 5 seconds. Why exactly these are happening in the first place depends a lot on how Cassandra is behaving.  Monitoring Cassandra is probably the best place to start.

A: According to my programmer, we actually fixed this by jacking up the timeouts to a very high value. We were trying to import a 5GB file, so I guess the db needed more than 5 seconds per read.
Here are the specific timeouts that were set:
$send_timeout=60000
$recv_timeout=60000


text:
Q: Is there a PowerShell variable that can be checked to see if you the script is running in the Azure cloud shell? Something similar to $IsLinux or $IsWindows.

A: From your description, I am not sure how did you run your script. If you use Start-Job to run the PowerShell script as a background job, you could use Get-Job to see the State.
Start-Job -FilePath ./GetDate.ps1
Get-Job

A: This is an old, but I had the same question and found this environment variable that works for my purposes. I'm not sure if there's another "official" way though.
PS> $env:AZUREPS_HOST_ENVIRONMENT
cloud-shell/1.0

A: I would suggest running a command in a try/catch that is specific to cloud shell, if that is what you are looking for?
    try {
        $sessioninfo = Get-CloudDrive
        if ($sessioninfo) {
            Write-Host "Running in Cloud Shell mode..." -ForegroundColor Green
            $path = ($home + "/clouddrive/" + "report" + "-$(get-date -Format yyyyddMM_hhmmtt).csv")
        }
    }
    catch {
        Write-Host "Running in local PowerShell session mode..." -ForegroundColor Yellow
        $path = "C:\localpath\report"+"-$(get-date -Format yyyyddMM_hhmmtt).csv"
    }


text:
Q: How to specify a range for begin() and end() iterators to find first value of sub vector in a vector of vectors? Hi I'm new to working with vectors and other parts of STL and I would like some help please, I have a vector of string vectors, containing a topic at the index of each sub-vector
e.g arr[1][0] = "topic1", with arr[1][1..n] containing messages related to "topic1",
To find the value of the topicID, the index of the subvector containing the topic, I'm using find() with begin() and end() iterators and effectively checking all value until a match is made, this is very inefficient as I know the topic will always be at arr[i][0], with complexity getting worse with n messages in the topic.
My current approach is shown below,
How can I refactor this to check only the element at arr[i][0] for the length of arr?
int getTopicID(vector< vector<string> >& arr, string topic)
{
    int topicID = 0;
    for (size_t m = 1; m < arr.size(); ++m)
    {
        auto i = find(arr[m].begin(), arr[m].end(), topic);
        if (arr[m].end() != i) { topicID = m; break; }
        else { topicID = 0;}
    }
    return topicID;
}

Thanks for the help :)

A:
How can I refactor this to check only the element at arr[i][0] for the length of arr?

Simply don't loop over all of the elements (std::find being the unnecessary inner loop). Replace body of the outer loop with:
if (arr[m][0] == topic) {
    return m;
}

and after the loop:
return 0;

P.S. You can replace the outer loop with std::find_if.


text:
Q: How to bundle one jar into another in android project I'm writing a android library (no resources), and planning to distribute it as jar. My library.jar depends on third party libraries say: thirdParty_1.jar and thirdParty_2.jar. I'm building library.jar in eclipse. thirdParty_1.jar and thirdParty_2.jar are included in build path and order of export is checked for both.
When I drop library.jar in a sample app, it gives the run time exception that the classes in third-party library is not found.
Do you know whats the correct way to wrap third-party libraries into your own jar and distribute it as a standalone jar?
[Update]
I'm able to create one jar using Eclipse FatJar plugin. Is it the only way to ship dependencies along with your jar?

A: I've managed to do this using ant's zip task at -post-build.
Edit build.xml at the bottom to look like so:
<!-- version-tag: custom -->
<import file="${sdk.dir}/tools/ant/build.xml" />
<target name="-post-build">
    <zip destfile="bin/my-library.jar">
        <zipgroupfileset dir="bin/" includes="classes.jar"/>
        <zipgroupfileset dir="libs/" includes="*.jar"/>
    </zip>
</target>

I'm not sure how Eclipse handles the build process, since I exclusive use the command-line SDK tools for development, but it probably calls on ant debug or ant release or something, all of which depend on the -post-build target.


text:
Q: Slight problem with pixels and browser with my jQuery effect In order to highlight a certain p element, I've written some JS to make it appear above a darkened background.
In order to do this, I used jQuery to create an overlay, and then clone the information p element and absolutely positioned it over the overlay.
Because it dropped a few CSS properties (not being inherited because of the new position in the page), I used jQuery to add them.
It works almost perfectly. In my Firefox 3.5.6 on Mac OS X, when it fades away, there is a slight disrepencacy of a matter of pixels. I know it's nitpicking, but I'd love to have it disappear and the end user not know the difference.
The test is available here: https://www.ikatanspa.com/book-online/?test
Here is the jQuery function too
var highlightFormSuccess = function() {

    var fadeTo = 0.6;

    var $info = $('p.information');

    if ($info.length) {

        // make overlay

        var $overlay = $('
')
            .css({
                display: 'none',
                width: '100%',
                height: $(document).height(),
                position: 'absolute',
                top: 0,
                left: 0,
                zIndex: 32767,
                opacity: 0
            })
            .attr({
                id: 'overlay'
            })
            .appendTo('body');

        // pull out success block and position above overlay

        var left = $info.position().left,
            top = $info.position().top,
            fontSize = $info.css('font-size'),
            width = $info.width(),
            color = $info.css('color'),
            lineHeight = $info.css('line-height');

        var $newInfo = $info.clone()
                            .css({
                                position: 'absolute',
                                top: top,
                                left: left,
                                'font-size': fontSize,
                                'line-height': lineHeight,
                                width: width,
                                color: color,
                                zIndex: 32767
                            })
                            .appendTo('body');

        $overlay
        .show()
        .fadeTo(1000, fadeTo);
        // wait then fade back out
        setTimeout(function() {

            $($overlay, $newInfo).fadeOut(1000, function() {
                $newInfo.fadeOut(250, function() { $(this).remove(); } );
            });

        }, 2500);

    };

};

A: Perhaps you can make things a bit easier. I just replicated the desired effect by setting my paragraph rules to:
p.highlight {
  position:relative;
  background-color:#ffffff;
  z-index:10;
}

And my overlay to:
div.overlay {
  position:fixed;
  background-color:#000000;
  z-index:5; // lower than my paragraph, higher than all else
  top:0; left:0; width:100%; height:100%;
}

--

I'm a paragraph.

I too am a paragraph.


text:
Q: Get Image URL of photo with UIImagePickerControllerDelegate I am using UIImagePickerController to select images. I was hoping to get the local path too.
I am doing this for images in an album using
info[UIImagePickerController.InfoKey.imageURL] as? URL
In the case of an image using the camera this is nil however.
Is it possible to capture this path using UIImagePickerControllerDelegate?

A: Yes, but with another key:
info[UIImagePickerController.InfoKey.originalImage] as? UIImage

or
info[UIImagePickerController.InfoKey.editedImage] as? UIImage

Please note that the object there will be UIImage type, not URL
Camera photos are not saved by default and don't have local path. So you need to save it by yourself. E.g.:
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
    try? image.pngData()?.write( .... )
}


text:
Q: Importing D3 in a JavaScript module via script tag When importing D3 in a JavaScript module via a script tag I get an Uncaught TypeError: Cannot read property 'd3' of undefined error.
Having read that all main browsers now support JavaScript modules, I am trying to import my D3 code via a <script type="module" src="network.js"></script> tag as described here:
https://developers.google.com/web/fundamentals/primers/modules
However, when I import D3 I receive the error:
d3.js:5 Uncaught TypeError: Cannot read property 'd3' of undefined
    at d3.js:5
    at d3.js:6

If I have an index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
</head>
<body>
<script type="module" src="network.js"></script>
</body>
</html>

With D3 v5.7.0 in the same directory and network.js simply containing:
import * as d3 from "./d3.js";

or just
import "./d3.js";

the above error is received.
I would expect the same behaviour found with CommonJS or AMD:
https://github.com/d3/d3-interpolate/issues/45#issuecomment-329590699


text:
Q: How to encrypt transmissions between Elasticsearch cluster nodes with TLS without using Shield Elastic provides the ability to encrypted traffic between cluster nodes with Shield: https://www.elastic.co/guide/en/shield/current/ssl-tls.html
However, Shield is quite expensive for our organization and we're looking for a way to achieve TLS encryption between nodes without using Shield.
Is there a way? If possible, I'd be looking for a way to do this in both version 2.4 and 5.0.


text:
Q: XAML Rectangle event Tapped doesn't fire in Windows 8 I have a simple Rectangle in XAML
<Rectangle x:Name="rect" IsTapEnabled="True" Height="100" Width="100" Fill="#FF72BB5C" Stroke="#FFFB0000" Tapped="rect_Tapped"/>

It draws fine but when I try and click on it nothing happens.
I have tried making the stroke bigger and clicking that and nothing.
I have tried lots of the other events associated with the Rectangle and nothing fires.
Would there be a problem calling the Tapped event when I'm using a mouse and not a touch screen?

A: Just faced the same issue. Solved with IsHitTestVisible property for Rectangle and every view above it. True for rect and False for others. Though True is default, could be omitted.

A: I just found strange and funny solution for this.
If your layout looks like this:
<Grid>
    <Canvas>
        <Rectangle x:Name="rect" IsTapEnabled="True" Canvas.Top="100" Canvas.Left="100" Height="100" Width="100" Fill="#FF72BB5C" Stroke="#FFFB0000" Tapped="rect_Tapped"/>
    </Canvas>
    <TextBlock Name="Test" Text="Hi" />
</Grid>

Then change it to this:
<Grid>
    <Canvas>
        <Rectangle x:Name="rect" IsTapEnabled="True" Canvas.Top="100" Canvas.Left="100" Height="100" Width="100" Fill="#FF72BB5C" Stroke="#FFFB0000" Tapped="rect_Tapped"/>
    </Canvas>
    <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Name="Test" Text="Hi" />
</Grid>

I just added VerticalAlignment="Center" HorizontalAlignment="Center" to TextBlock and now it works. Don't know why, but works. I'm going to go deeper into this issue.


text:
Q: App Engine - Mobile Safari - AJAX - Page load time takes around 30 seconds I have come across a strange bug that I just can't figure out.
The page does not execute the ajax json call for 30 seconds.
Here is how I recreate the bug:

*

*Phone: iPhone 6 with iOS 9.0.1

*Safari: Cleared history and website
data in safari settings

*Wifi: Turn off cellular data and leave wi-fi
only

*Page: Go to page http://www.bazmo.com/best/staplers
It does work properly when using cellular data and even on wifi using Web Inspector.
Here are the Google App Engine logs:

$.ajax({
        dataType: "json",
        url: '/json/' + currentUrlPath,
        success: function (dataSource) {
            // Populate item list
            data = dataSource;
            alert("works");
            // Apply CategoryViewModel binding
            $(function () {
                ko.applyBindings(new CategoryViewModel(),
                        document.getElementById("outer_content"));
            });
        }

Thanks in advance!
Kris


text:
Q: Memory Leak with Single Method This whole memory leak thing seems very complicated to me.  A lot of great info here, but I cannot quite understand it.  Even after reading Creating a memory leak with Java, I am still lost!  Can someone point out to me where the memory leak is in this code, please?  (It happens when this method is run repeatedly.) Thank you very much!
08-11 23:02:07.487: I/ViewRootImpl(969): Reporting drop result: true
08-11 23:02:07.987: D/dalvikvm(969): GC_FOR_ALLOC freed 1769K, 18% free 10101K/12180K, paused 13ms, total 13ms
08-11 23:02:08.057: D/dalvikvm(969): GC_CONCURRENT freed 4K, 11% free 10915K/12180K, paused 3ms+5ms, total 30ms
08-11 23:02:08.057: D/dalvikvm(969): WAIT_FOR_CONCURRENT_GC blocked 1ms
08-11 23:02:14.757: I/dalvikvm(969): threadid=3: reacting to signal 3
08-11 23:02:14.767: I/dalvikvm(969): Wrote stack traces to '/data/anr/traces.txt'

public void deal(View v) {

    // call and play
    if (dealt) {

        if (anteBet == playBet) {
            // hand plays
            dealt = false;
            deal.setImageResource(R.drawable.deal);
            fold.setImageResource(R.drawable.clear);
            dealersCards.clear();
            dealersCards.add(d1);
            dealersCards.add(d2);
            dealersCards.add(d3);
            displayCards(dealersCards);

            if (getHand(pc1, pc2, pc3) > getHand(dc1, dc2, dc3)
                    && getHand(dc1, dc2, dc3) >= 1120000) {
                award = true;
                ante(anteBet);
                award = true;
                play(playBet);
            } else if (getHand(dc1, dc2, dc3) < 1120000) {
                award = true;
                ante(anteBet);
            }

            else {
                if (!(getHand(pc1, pc2, pc3) == getHand(dc1, dc2, dc3))) {

                    award = true;
                    ante(-anteBet);
                    award = true;
                    play(-playBet);
                }
            }
            antePlusPayout();
            pairPlusPayout();

        } else {
            play(anteBet - playBet);
        }

        // deal cards
    } else if (anteBet > 0) {
        deal.setImageResource(R.drawable.call);
        fold.setImageResource(R.drawable.fold);
        displayCards(display);
        d1.setImageResource(R.drawable.facedown);
        d2.setImageResource(R.drawable.facedown);
        d3.setImageResource(R.drawable.facedown);
        dealt = true;
        deal.setImageResource(R.drawable.call);
    }
}

public void displayCards(List<ImageView> disp) {
    int cardNumber = 0;
    for (ImageView c : disp) {

        cardNumber++;

        Card tempCard;

        do {
            tempCard = deck.get(rand(52));
        } while (cardsInPlay.contains(tempCard));

        cardsInPlay.add(tempCard);
        rank = tempCard.getRank();
        suit = tempCard.getSuit();

        if (cardNumber == 1) {
            dc1 = tempCard;
        } else if (cardNumber == 2) {
            dc2 = tempCard;
        } else if (cardNumber == 3) {
            dc3 = tempCard;
        } else if (cardNumber == 4) {
            pc1 = tempCard;
        } else if (cardNumber == 5) {
            pc2 = tempCard;
        } else {
            pc3 = tempCard;
        }

        if (rank == 2 && suit == 'c') {
            c.setImageResource(R.drawable.clubs2);
        } else if (rank == 3 && suit == 'c') {
            c.setImageResource(R.drawable.clubs3);
        } else if (rank == 4 && suit == 'c') {
            c.setImageResource(R.drawable.clubs4);
        } else if (rank == 5 && suit == 'c') {
            c.setImageResource(R.drawable.clubs5);
        } else if (rank == 6 && suit == 'c') {
            c.setImageResource(R.drawable.clubs6);
        } else if (rank == 7 && suit == 'c') {
            c.setImageResource(R.drawable.clubs7);
        } else if (rank == 8 && suit == 'c') {
            c.setImageResource(R.drawable.clubs8);
        } else if (rank == 9 && suit == 'c') {
            c.setImageResource(R.drawable.clubs9);
        } else if (rank == 10 && suit == 'c') {
            c.setImageResource(R.drawable.clubs10);
        } else if (rank == 11 && suit == 'c') {
            c.setImageResource(R.drawable.clubsj);
        } else if (rank == 12 && suit == 'c') {
            c.setImageResource(R.drawable.clubsq);
        } else if (rank == 13 && suit == 'c') {
            c.setImageResource(R.drawable.clubsk);
        } else if (rank == 14 && suit == 'c') {
            c.setImageResource(R.drawable.clubsa);
        }

        else if (rank == 2 && suit == 'd') {
            c.setImageResource(R.drawable.diamonds2);
        } else if (rank == 3 && suit == 'd') {
            c.setImageResource(R.drawable.diamonds3);
        } else if (rank == 4 && suit == 'd') {
            c.setImageResource(R.drawable.diamonds4);
        } else if (rank == 5 && suit == 'd') {
            c.setImageResource(R.drawable.diamonds5);
        } else if (rank == 6 && suit == 'd') {
            c.setImageResource(R.drawable.diamonds6);
        } else if (rank == 7 && suit == 'd') {
            c.setImageResource(R.drawable.diamonds7);
        } else if (rank == 8 && suit == 'd') {
            c.setImageResource(R.drawable.diamonds8);
        } else if (rank == 9 && suit == 'd') {
            c.setImageResource(R.drawable.diamonds9);
        } else if (rank == 10 && suit == 'd') {
            c.setImageResource(R.drawable.diamonds10);
        } else if (rank == 11 && suit == 'd') {
            c.setImageResource(R.drawable.diamondsj);
        } else if (rank == 12 && suit == 'd') {
            c.setImageResource(R.drawable.diamondsq);
        } else if (rank == 13 && suit == 'd') {
            c.setImageResource(R.drawable.diamondsk);
        } else if (rank == 14 && suit == 'd') {
            c.setImageResource(R.drawable.diamondsa);
        }

        else if (rank == 2 && suit == 'h') {
            c.setImageResource(R.drawable.hearts2);
        } else if (rank == 3 && suit == 'h') {
            c.setImageResource(R.drawable.hearts3);
        } else if (rank == 4 && suit == 'h') {
            c.setImageResource(R.drawable.hearts4);
        } else if (rank == 5 && suit == 'h') {
            c.setImageResource(R.drawable.hearts5);
        } else if (rank == 6 && suit == 'h') {
            c.setImageResource(R.drawable.hearts6);
        } else if (rank == 7 && suit == 'h') {
            c.setImageResource(R.drawable.hearts7);
        } else if (rank == 8 && suit == 'h') {
            c.setImageResource(R.drawable.hearts8);
        } else if (rank == 9 && suit == 'h') {
            c.setImageResource(R.drawable.hearts9);
        } else if (rank == 10 && suit == 'h') {
            c.setImageResource(R.drawable.hearts10);
        } else if (rank == 11 && suit == 'h') {
            c.setImageResource(R.drawable.heartsj);
        } else if (rank == 12 && suit == 'h') {
            c.setImageResource(R.drawable.heartsq);
        } else if (rank == 13 && suit == 'h') {
            c.setImageResource(R.drawable.heartsk);
        } else if (rank == 14 && suit == 'h') {
            c.setImageResource(R.drawable.heartsa);
        }

        else if (rank == 2 && suit == 's') {
            c.setImageResource(R.drawable.spades2);
        } else if (rank == 3 && suit == 's') {
            c.setImageResource(R.drawable.spades3);
        } else if (rank == 4 && suit == 's') {
            c.setImageResource(R.drawable.spades4);
        } else if (rank == 5 && suit == 's') {
            c.setImageResource(R.drawable.spades5);
        } else if (rank == 6 && suit == 's') {
            c.setImageResource(R.drawable.spades6);
        } else if (rank == 7 && suit == 's') {
            c.setImageResource(R.drawable.spades7);
        } else if (rank == 8 && suit == 's') {
            c.setImageResource(R.drawable.spades8);
        } else if (rank == 9 && suit == 's') {
            c.setImageResource(R.drawable.spades9);
        } else if (rank == 10 && suit == 's') {
            c.setImageResource(R.drawable.spades10);
        } else if (rank == 11 && suit == 's') {
            c.setImageResource(R.drawable.spadesj);
        } else if (rank == 12 && suit == 's') {
            c.setImageResource(R.drawable.spadesq);
        } else if (rank == 13 && suit == 's') {
            c.setImageResource(R.drawable.spadesk);
        } else if (rank == 14 && suit == 's') {
            c.setImageResource(R.drawable.spadesa);
        }

    }
}

A: In java, the usual cause of excessive memory usage, is objects being allocated and not destroyed, in some sort of loop, such as a game loop. Are you adding to a dynamic array/list of sorts in a loop? Also, if a method takes a while, this effect can happen with local variables before they are destroyed.

A: You need to do this with your ImageView if you change their images often

Drawable obj = imgView.getDrawable();

if( obj instanceof BitmapDrawable)
{
    Bitmap bmp = obj.getBitmap();
    bmp.Recycle();
}

Before this statement call a cleanupcode function
Bitmap CleanupCode(ImageView imgView) {

Drawable obj = imgView.getDrawable();

if( obj instanceof BitmapDrawable) {

 Bitmap bmp = obj.getBitmap(); bmp.Recycle(); return bmp;
 }
 return null;
}
////

Bitmap bmp = CleanupCode(c);

c.setImageResource(R.drawable.clubs3);
if(null != bmp) {
bmp.Recycle();
bmp = null;
}


text:
Q: Merging regex rules into one? How could I merge these into one line? I'm sure it's possible.
RewriteRule ^forums$                   pages/forum.php [L]
RewriteRule ^forums/([A-z]+)$          pages/forum.php?category=$1 [L]
RewriteRule ^forums/([A-z]+)/([A-z]+)$ pages/forum.php?category=$1&sort=$2 [L]

A: RewriteRule ^forums(/([A-z]+)(/([A-z]+))?)?$ pages/forum.php?category=$2&sort=$4 [L]

Note that you're still supplying category and sort to the PHP script, but they'll be empty.
I think you may have a problem with [A-z] including unexpected characters.  (Review your ASCII charset for details).  Replace it with [A-Za-z] or [[:alpha:]] if that's what you really want.


text:
Q: SlimFramework v3 - Same route with AND whithout final '/' I created a small application with SlimFramework v3 and I am able to build a simple route like this:
// GET localhost/admin
$app->get('/admin', function(){
    # code here
});

My problem is that this work only for localhost/admin and not for localhost/admin/ (with final backslash). Is there any option to use ONE route for both?

A: There are 2 possibilities

*

*Specify an optional /
$app->get('/admin[/]', function(){
    # code here
});

*Add middleware that redirects routes with an ending / to the url without that.
use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

$app->add(function (Request $request, Response $response, callable $next) {
    $uri = $request->getUri();
    $path = $uri->getPath();
    if ($path != '/' && substr($path, -1) == '/') {
        // permanently redirect paths with a trailing slash
        // to their non-trailing counterpart
        $uri = $uri->withPath(substr($path, 0, -1));

        if($request->getMethod() == 'GET') {
            return $response->withRedirect((string)$uri, 301);
        }
        else {
            return $next($request->withUri($uri), $response);
        }
    }

    return $next($request, $response);
});

(Source: http://www.slimframework.com/docs/cookbook/route-patterns.html)


text:
Q: Fastest way to order a huge vector? I am looking for the fastest way to order a multidimensional vector of 220000 * 7 * 6.
I am ordering by the [x][5][y] and I have to make all the value of the middle (7) vector follow up.
for(int i =0;i<211876;i++){
    for(int k =0;k<211876;k++){
        if(vec[k][5][myposition] < vec[k+1][5][myposition]){
            for(int n =0;n<7;n++){
            swap2int(vec[k][n][myposition],vec[k+1][n][myposition]);}
        }
    }
}

void swap2int(int &one, int& two){
    int temp=0;
    temp = one;
    one = two;
    two = temp;

    return;
}

this is somewhat very slow and I am looking for ways to improve the speed of this.

A: Always use std::sort unless you have a very good reason not to. std::sort allows you to supply your own sorting criterion if necessary, so there are hardly any reasons not to use it. You may need to provide a stride iterator in your case, but those are straightforward.

A: You can always put them inside a min heap (creating a min (or max) heap from a vector takes O(n) on average), then, you can simply extract numbers from your min heap in perfect order, with O(log n) cost for each top()+pop() operation. That way, you'll get a nice O(N log N) cost, you'll play with heaps, which are always interesting, and might have more fun (and add some bug that will make you post here again) than if you just used std::sort :P
Or you can use std::sort as said before, and forget everything else ;)
Btw: In your swap2int() function, there is no need to waste time assigning 0 to temp if you won't use it. Just change it to:
int temp;
temp=one;
or straight to:
int temp=one;


text:
Q: How many would you like to request it for? Trying not to sound too ignorant while instructing a piece of software in order to allow people to make request of services/items and while trying to say "For how many people would you like to make this request" or "How many of this do you want?", the sound of the sentence in the title appeared kind enough to me.
I followed the empiric principle of postponing the 'for' at the end of the sentence while coping the affermative version of it
I'd like to request it for 3 people -> How many would you like to request it for?
Does that look correct?

A: There is a rule of thumb to never end a sentence with a preposition. This "rule" is often broken; there are many clear and grammatical constructions that end a sentence in a preposition. Both of the following are grammatical and natural sounding (at least to my ears).

How many people would you like to request it for?
For how many people would you like to request it?

However, do note that I added the word people to both sentences. Although many can be used as a noun, the phrase how many always acts an adjective. In some cases, especially in dialogue, the noun can be implied by context:

I want some fish.
How many [fish]?

This pattern can also extends to prepositional phrases:

I would like to request it for some people.
For how many [people]?

But outside of this context, you should include the noun in the question.


text:
Q: Scraping and writing the table into dataframe shows me TypeError I am trying to scraping the table and write in a dataframe they show me a typeerror. How to resolve these errors?
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium import webdriver
import pandas as pd
temp=[]
driver= webdriver.Chrome('C:\Program Files (x86)\chromedriver.exe')
driver.get("https://www.fami-qs.org/certified-companies-6-0.html")
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='Inline Frame Example']")))
headers=WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//table[@id='sites']//thead"))).text
rows=WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//table[@id='sites']//tbody"))).text
temp.append(rows)
df = pd.DataFrame(temp,columns=headers)
print(df)

In headers I pass the data FAMI-QS Number  ... Expiry date while in rows I will pass the FAM-0694  ...  2022-09-04

A: You can get all table data from api calls html response using only pandas as follows:
Code:
import requests
import pandas as pd

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'}

url = "https://famiqs.viasyst.net/certified-sites"

req = requests.get(url,headers=headers)

table = pd.read_html(req.text)

df = table[0]#.to_csv('info.csv',index = False)

print(df)

Output:
    FAMI-QS Number  ... Expiry date
0          FAM-0694  ...  2022-09-04
1          FAM-1491  ...  2022-10-17
2     FAM-ISFSF-003  ...  2022-10-27
3          FAM-1533  ...  2022-10-31
4          FAM-1090  ...  2022-11-13
...             ...  ...         ...
1472    FAM-1761-01  ...  2024-10-27
1473       FAM-1796  ...  2024-09-29
1474    FAM-1427-01  ...  2023-12-01
1475       FAM-1861  ...  2024-11-22
1476    FAM-0005-07  ...  2024-11-25

[1477 rows x 7 columns]

A: To scrape the FAMI QS Number and Site Name column you need to create a list of the desired texts using List Comprehension inducing WebDriverWait for the visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

*

*Code Block:
driver = webdriver.Chrome(service=s, options=options)
driver.get("https://www.fami-qs.org/certified-companies-6-0.html")
FAMI_QS_Numbers = []
Site_Names = []
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='Inline Frame Example']")))
FAMI_QS_Numbers.extend([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//table[@id='sites']//tbody//tr/descendant::td[1]")))])
Site_Names.extend([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//table[@id='sites']//tbody//tr//td/p")))])
df = pd.DataFrame(data=list(zip(FAMI_QS_Numbers, Site_Names)), columns=['FAMI QS Number', 'Site Name'])
print(df)
driver.quit()

*Console Output:
  FAMI QS Number                             Site Name
0       FAM-1293                    AmTech Ingredients
1       FAM-0841                    3F FEED & FOOD S L
2       FAM-1361                5N Plus Additives GmbH
3    FAM-1301-01                   A & V Corp. Limited
4       FAM-1146  A. + E. Fischer-Chemie GmbH & Co. KG
5       FAM-1589          A.M FOOD CHEMICAL CO LIMITED
6    FAM-0613-01                          A.W.P. S.r.l
7       FAM-0867             AB AGRI POLSKA Sp. z o.o.
8    FAM-1510-02                              AB Vista
9    FAM-1510-01                            AB Vista *

A: To scrape all the data from all the columns you need to induce WebDriverWait for the visibility_of_element_located() of the <table> element, extract the outerHTML, read the outerHTML using read_html() and you can use the following Locator Strategies:

*

*Code Block:
driver.get("https://www.fami-qs.org/certified-companies-6-0.html")
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='Inline Frame Example']")))
data = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "table#sites"))).get_attribute("outerHTML")
df  = pd.read_html(data)
print(df)
driver.quit()

*Console Output:
[  FAMI-QS Number                             Site Name              City  ... Status Certified from Expiry date
0       FAM-1293                    AmTech Ingredients        albert lea  ...  Valid     2020-10-08  2023-10-07
1       FAM-0841                    3F FEED & FOOD S L       vizcolozano  ...  Valid     2020-04-17  2023-04-16
2       FAM-1361                5N Plus Additives GmbH  eisenhüttenstadt  ...  Valid     2020-10-01  2023-09-30
3    FAM-1301-01                   A & V Corp. Limited            xiamen  ...  Valid     2020-09-09  2023-09-08
4       FAM-1146  A. + E. Fischer-Chemie GmbH & Co. KG         wiesbaden  ...  Valid     2020-06-05  2023-06-04
5       FAM-1589          A.M FOOD CHEMICAL CO LIMITED             jinan  ...  Valid     2020-01-07  2023-01-06
6    FAM-0613-01                          A.W.P. S.r.l        crevalcore  ...  Valid     2020-02-27  2023-02-07
7       FAM-0867             AB AGRI POLSKA Sp. z o.o.           smigiel  ...  Valid     2020-08-03  2023-03-19
8    FAM-1510-02                              AB Vista       marlborough  ...  Valid     2020-04-16  2023-04-15
9    FAM-1510-01                            AB Vista *         rotterdam  ...  Valid     2020-04-16  2023-04-15

[10 rows x 7 columns]]


text:
Q: Who would win a fight between Tom Bombadil and a Nazgul? Both Tom Bombadil and the Nazgul are powerful magical beings within the context of the Lord of the Rings Universe.  What would happen in a face to face fight between the two?  Who would win?

A: As Gandalf put it in The Council of Elrond:

No, I should not put it so. Say rather that the Ring has no power over him. He is his own master. But he cannot alter the Ring itself, nor break its power over others.

A Nazgul, as a servant of the Ring, would therefore have no power over Bombadil, but Bombadil on the other hand would also be ineffective against a Nazgul.  What would happen?  Nothing.
Edit to add:
On double-checking the text, I've come across the following from Fog on the Barrow Downs:

Out east my knowledge fails. Tom is not master of Riders from the Black Land far beyond his country.

This seems conclusive; Tom couldn't defeat a Nazgul, but whether a Nazgul could defeat him depends on interpretation of Gandalf's statement above (with strong circumstantial evidence against).


text:
Q: How to send activation email to user in spring framework? I want to send activation email to user, when they sign up my website, they will receive an email to verify their account activation request. Can you tell me some idea do that?
I'm using Spring Framework to build my website.
Thank a lot :)

A: Spring has no build in "Double Opt In" functionality. You need to implement them by your own.
What you can use is:

*

*Use Spring Mail support for sending the email

*Use Spring JBCD or Spring JPA Support or Spring Data JPA for storing the activation key that is send with the email in some database.

*Use Spring MVC for the frontend which use the user to interact with


text:
Q: Laravel form validation, why I don't have the $errors variable available on my view? Taken from lrvl 5.1 documentation, I read:
using these lines in the controller:
$this->validate($request, [
    'title' => 'required|unique:posts|max:255',
    'author.name' => 'required',
    'author.description' => 'required',
]);

If validation doesn't pass controller stops execution and redirect back to previous location.
This is happening correctly.
Then doc says:
"$errors variable will always be available in all of your views on every request"
And then suggests the following blade code:
@if (count($errors) > 0)

        @foreach ($errors->all() as $error)

{{ $error }}

        @endforeach

@endif

But actually I'll get a ErrorException undefined variable errors....
What am I missing?
Thanks

A: I'll answer myself to this question,
just in case It was not clear the commented solution.
(Thanks to train_fox for the hint).
Just add 'web' middleware usage.
in your routing that is target in form action (get/post)
Example:
Route::group(['middleware' => 'web'],
       function(){
          Route::post('/edit'           , 'My_Controller@edit');
       });

Variable $errors the becomes available on view to be parsed.


text:
Q: NSFetchedResultsController that contains objects from a relation I have a NSManagedObject with related objects. The relation is described by a keyPath.
Now I want to display these related objects in a table view. Of course I could just take the NSSet with these objects as a data source, but I'd prefer to refetch the objects with a NSFetchedResultsController to benefit from its features.
How can I create a predicate that describes these objects?

A: To display the related objects of a given object with a fetched results controller,
you would use the inverse relationship in the predicate. For example:

To display the children related to a given parent, use a fetched results controller
with the following fetch request:
Parent *theParent = ...;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Child"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parent = %@", theParent];
[request setPredicate:predicate];

For nested relationships, just use the inverse relationships in inverted order. Example:

To display the streets of a given country:
Country *theCountry = ...;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Street"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city.country = %@", theCountry];
[request setPredicate:predicate];

A: Thanks Martin, you gave me important information.
To generically get the key path I have found the following implementation:
    // assume to have a valid key path and object
    NSString *keyPath;
    NSManagedObject *myObject;

    NSArray *keys = [keyPath componentsSeparatedByString:@"."];
    NSEntityDescription *entity = myObject.entity;
    NSMutableArray *inverseKeys = [NSMutableArray arrayWithCapacity:keys.count];
    // for the predicate we will need to know if we're dealing with a to-many-relation
    BOOL isToMany = NO;
    for (NSString *key in keys) {
        NSRelationshipDescription *inverseRelation = [[[entity relationshipsByName] valueForKey:key] inverseRelationship];
        // to-many on multiple hops is not supported.
        if (isToMany) {
            NSLog(@"ERROR: Cannot create a valid inverse relation for: %@. Hint: to-many on multiple hops is not supported.", keyPath);
            return nil;
        }
        isToMany = inverseRelation.isToMany;
        NSString *inverseKey = [inverseRelation name];
        [inverseKeys insertObject:inverseKey atIndex:0];
    }
    NSString *inverseKeyPath = [inverseKeys componentsJoinedByString:@"."];
    // now I can construct the predicate
    if (isToMany) {
        predicate = [NSPredicate predicateWithFormat:@"ANY %K = %@", inverseKeyPath, self.dataObject];
    }
    else {
        predicate = [NSPredicate predicateWithFormat:@"%K = %@", inverseKeyPath, self.dataObject];
    }

Update: I changed the predicate format so that it also supports many-to-many relations.
Update 2 This is getting more complex: I need to check my inverse relation if it is to-many and use different predicates. I updated the code example above.

A: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city.country = '%@'", theCountry];

You miss ' ' in predicateWithFormat string. Now it work.


text:
Q: Javascript Vue Event Emit Not Value Good Evening,
does anyone know why the input toggle switch value is being flipped to the reverse value when emitted to the parent component?  I'm new to Vue, I have been working with it on and off for a few days now.  It works in concept, I can see the value of the attribute in both areas using vue dev tools.  However, the child value is reversed when emitted to the parent and assigned.  I could immediately fix by !'ing the incoming value, but I would like to find out if anyone knows why this is occurring.
Parent Update Bind
updateMiddle(article){
  this.article.meta_title = article.meta_title;
  this.article.meta_desc = article.meta_desc;
  this.article.published = article.published;
  this.article.is_review = article.is_review;
}

Child Emit
methods: {
  update() {
    this.$emit('changeMiddle',this.article)
  }

Input
<input id="tc-review" type="checkbox" hidden="hidden" name="is_review"
       v-model="article.is_review" v-on:input="update">

A: The problem is that the input event fires before the v-model binding has changed the data.
Simple solution is to use the change event instead. For example
<input v-model="article.is_review" @change="update">

Simplified demo ~ http://jsfiddle.net/u20h5tzv/
Hint: Try changing it back to @input and see the difference in timing.


text:
Q: Can I upload the files from console application to google drive in specific folder I have a requirement. Insert the file from console application to google drive through code.
I read some articles, but I didn't understand. please help me...

A: Google dev website has what you are looking for. Also, please at least try some code before asking questions here so we can help fixing it.
class Program
{
    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/drive-dotnet-quickstart.json
    static string[] Scopes = {  DriveService.Scope.DriveReadonly };
    static string ApplicationName = "Drive API .NET Quickstart";

    static void Main(string[] args)
    {
        UserCredential credential;

        using (var stream =
            new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

        // Create Drive API service.
        var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

        // Define parameters of request.
        FilesResource.ListRequest listRequest = service.Files.List();
        listRequest.PageSize = 10;
        listRequest.Fields = "nextPageToken, files(id, name)";

        // List files.
        IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
            .Files;
        Console.WriteLine("Files:");
        if (files != null && files.Count > 0)
        {
            foreach (var file in files)
            {
                Console.WriteLine("{0} ({1})", file.Name, file.Id);
            }
        }
        else
        {
            Console.WriteLine("No files found.");
        }
        Console.Read();

    }
}

For further, check the following link.
https://developers.google.com/drive/v3/web/quickstart/dotnet


text:
Q: How to make a repsonsive design so H2 get its maximum font size in a 1-line DIV? How do I make a headline, H2, to fit into the current width of a DIV.
I want the H2 to get the maximum font size, displaying its full context (without using overflow to cut or hide its content), while not breaking into a second line within the DIV.

A: There's a few ways - some more complex than others. There's a few JavaScript plugins that can handle this which might serve you best.
A simple but effective CSS-only way would be to use the viewport width (vw) as the value for font-size. Here's an example using white-space: nowrap in conjunction: https://jsfiddle.net/6tueLheq/
HTML:
<h2>
  Hello there i don't break to the next line no matter what the width!
</h2>

CSS:
h2 {
  white-space: nowrap;
  font-size: 3vw;
}

NOTE - this way is not perfect by any means - I'd suggest using something like FitText: http://fittextjs.com/, which is quite powerful.
More info on viewport units: https://web-design-weekly.com/2014/11/18/viewport-units-vw-vh-vmin-vmax/

A: Js Way :
You can use Javascript based plugins like FitTextJs http://fittextjs.com/. This plugin allows you to have headings that can resize based on the current device width.
CSS Way:
You can provide the font size using vw units.  This will scale the font size based on current viewport size.
E.g., 1vw will direct the browser to use the font size as 1% of current viewport width.
But please check if your targeted browsers support this unit before Implementation.
Custom implementation :
I have used following way to design fluid websites,  that should align and appear identical in all possible screen resolutions.
If the font size at 320 px is 12px, then the mobile font multiplication factor will be
320px has font size as 12px
Then what should be the font size at 480px
The calculation will be
X = ( 12 * 480)  / 320;

Once the font size is dynamically calculated,  you can set the font size to body tag and set font sizes for dependent elements in %.
e.g.,
h2 { font-size:110%;}

This method  is fun to implement.
But there will be a slight delay before the new calculated font size to be applied on window resize or orientation changes


text:
Q: Grant CREATE SCHEMA (only) to users Imagine I have one shared database set up for my class that each student has the potential to access (access to the database is open and only requires kerberos auth).  The public space is where I place all my default course material (tables, views, etc), most of which can be accessed by anyone interested.
What I would like is for:

*

*each student (any authenticated user) to be able to create their own schema and use that as the scope where they can create tables and views

*students to not be able to create tables/views/objects in public

*to apply these settings to all all users; or more specifically, not have to target specific user accounts when assigning permissions

Thought process:
REVOKE ALL ON DATABASE class FROM PUBLIC
GRANT CREATE ON DATABASE class TO PUBLIC  -- can it be CREATE SCHEMA ?
-- being able to create on database makes it seem like they can create in public
-- can permissions be revoked from public?

As user:
psql -h <host> class

-- desire: permitted
CREATE SCHEMA <current_user>;
GRANT USAGE ON <current_user> TO teacher;
CREATE TABLE <current_user>.<table name> ...;
SELECT * FROM public.<table name>;
SELECT * FROM <current_user>.<table name>;

-- desire: not permitted
CREATE TABLE public.<table name> ...;

I'm not sure those are the proper permissions.  I was also curious if I could create a roll and use the role to administer permissions.  The tricky bit is I would like any authenticated user to be part of that role, which I don't think you can add public to a role, so I don't know how that would work.
I haven't thought this through thoroughly, but appreciate any feedback, concerns, and answers offered.  Of course, I'm available to answer questions for clarification -- being concise while still offering comprehensive details is a challenge.

A: Postgres is quite good at doing such things, this is one reason I like it.
You can create an arbitrarily complex role hierarchy, but for our purposes a simple one will be enough:
CREATE ROLE student;

REVOKE CREATE ON SCHEMA public FROM public;  -- the second public is a pseudorole
                                             -- every role (user, group) is a member of
REVOKE CREATE ON DATABASE class FROM public; -- disallows schema creation, see below

GRANT USAGE ON SCHEMA public TO student;

At this point, student is a role that cannot log in.  We will use it as the privilege collector for the actual students, which you will have to create like this:
CREATE USER jsmith IN ROLE student;  -- will be able to log in,
                                     -- and a member of the student role

You can put the latter two statements into a stored function/procedure (which will include some dynamic SQL), or a script in your second favourite language.
This way your students will be able to create a schema for themselves (the name can be anything), and as they own that schema, they can also create objects in it.  If you want to restrict them to a schema named after them, do the following after the CREATE USER:
CREATE SCHEMA jsmith AUTHORIZATION jsmith;

To allow access for the teacher to all student schemas and objects, the easiest solution is:
GRANT student TO teacher;

What remains now is to allow students to access the existing and future tables in the public schema:
GRANT SELECT ON ALL TABLES IN SCHEMA public TO student;
ALTER DEFAULT PRIVILEGES IN SCHEMA public FOR ROLE teacher
      GRANT SELECT ON TABLES TO student;

The last command assumes the tables will be created by the user/role teacher.

A: You might want to go about this a different way. Create a script that the teacher can run (assuming the teacher is setup as a dba on the database) that sets all of that up. The script would do everything you need to get your students up and running.
Create Script: Input Username

*

*Create the user on the database

*Create the schema

*Create needed objects based on template schema

*Load needed data from the template schema

*Grant/Revoke privileges as needed

Teardown Script: Input Username

*

*Removes Schema

*Removes user

You could make it a little more advanced and allow for an email to be passed in and it can email the students information they need to login to the database. This is assuming your database has access to send email and a reliable email system to use.


text:
Q: Expiration of NHibernate query cache Is it possible to configure expiration of NHibernate's query cache?
For second level cache I can do it from nhibernate.cfg.xml, but I can't find a way for SQL query cache.
EDIT:
ICriteria query = CreateCriteria()
                  .Add(Expression.Eq("Email", identifiant))
                  .SetCacheable(true)
                  .SetCacheRegion("X");

 <syscache>
    <cache region="X" expiration="10" priority="1" />
  </syscache>

A: Yes, we can set cache expiration via region. Adjust the query like this:
criteria.SetCacheable(true)
    .SetCacheMode(CacheMode.Normal)
    .SetCacheRegion("LongTerm");

And put similar configuration into web.config file
<configSections>
    <section name="syscache" type="NHibernate.Caches.SysCache.SysCacheSectionHandler, NHibernate.Caches.SysCache" requirePermission="false" />
</configSections>
<syscache>
    <cache region="LongTerm" expiration="180" priority="5" />
    <cache region="ShortTerm" expiration="60" priority="3" />
</syscache>

EDIT: I am just adding this link Class-cache not used when getting entity by criteria
To be sure what I mean by SQL Query cache. In the linked answer I am explaining that topic
Just for a clarity. The configuration of the NHibernate "session-factory" must contain:
<property name="cache.use_query_cache">true</property>

This switch will make query cache working. More details: http://nhibernate.info/doc/nh/en/index.html#performance-querycache


text:
Q: PowerBI Embedded "Provision Token" generation error I am trying to follow this PowerBI embedded example and am getting an error:
'PowerBIToken' does not contain a definition for 'CreateProvisionToken'

This MSDN article describes the CreateProvisionToken() method.

*

*I installed latest Microsoft.PowerBI.Core and Microsoft.PowerBI.Api using NuGet package manager

*included Microsoft.PowerBI.Security and Microsoft.PowerBI.Api.V1 in my project.
I also tried changing CreateProvisionToken() part to the following:
var credentials = new TokenCredentials(accessKey, "AppKey");

var client = new PowerBIClient(credentials);

var devToken = PowerBIToken. CreateDevToken(reportID, workspaceID);
using (client)
{
    var embedToken = PowerBIToken.CreateReportEmbedToken(
        collectionName,
        workspaceID,
        reportID);
    var embedTokenString = embedToken.Generate(accessKey);
}

Which generates a token which "looks about right", but using this token in the example html in the end of the article results in an error This content is not available when rendering the report.
What am I missing?

A: The latest version of Power BI embedded simplifies the authentication mechanism by only support one embedded token, no other tokens anymore from Power BI blog:
https://powerbi.microsoft.com/en-us/blog/what-s-new-and-what-s-next-for-power-bi-embedded-july-2016/

We have simplified the way developers authenticate their calls to Power BI. From today on, app tokens will only be used to authenticate embedding requests and other client side requests that may be added in the future. All calls to our REST APIs will be authenticated using our API keys directly. This eliminates the need to generate app tokens each time you want to call the REST API.

You need follow up the example from Microsoft:
https://github.com/Azure-Samples/power-bi-embedded-integrate-report-into-web-app/blob/master/EmbedSample/Controllers/DashboardController.cs


text:
Q: How to configure the configuration file for MONGOS? I am not able to cofigure the configuration file for mongos. How do i set the configurations?

A: Step 1) Create a separate database for the config server.
mkdir /data/configdb

Step 2) Start the mongodb instance in configuration mode. Suppose if we have a server named Server D which would be our configuration server, we would need to run the below command to configure the server as a configuration server.
mongod –configdb ServerD: 27019

Step 3) Start the mongos instance by specifying the configuration server
mongos –configdb ServerD: 27019

Step 4) From the mongo shell connect to the mongo's instance
mongo –host ServerD –port 27017

Step 5) If you have Server A and Server B which needs to be added to the cluster, issue the below commands
sh.addShard("ServerA:27017")
sh.addShard("ServerB:27017")

Step 6) Enable sharding for the database. So if we need to shard the Employeedb database, issue the below command
sh.enableSharding(Employeedb)

Step 7) Enable sharding for the collection. So if we need to shard the Employee collection, issue the below command
Sh.shardCollection("db.Employee" , { "Employeeid" : 1 , "EmployeeName" : 1})


text:
Q: Unable to set reference variable in recursive call I am using a recursive method to find a node in a binary tree using a key. When I find the node, I set it to my reference variable foundNode and return. The problem is that when I read the object its value is still null. Can anybody help?
findGivenNode(root, key, foundNode, parentStack);

private boolean findGivenNode(Node node, int key, Node foundNode, Stack<Node> parentStack) {
    if (node == null) {
        return false;
    }

    parentStack.add(node);
    if (node.getData() == key) {
        foundNode = node;
        return true;
    }
    boolean leftReturn = findGivenNode(node.getLeftChild(), key, foundNode, parentStack);
    boolean RightReturn = findGivenNode(node.getRightChild(), key, foundNode, parentStack);
    if (leftReturn || RightReturn) {
        return true;
    }  else {
        parentStack.pop();
        return false;
    }
}

A: Java doesn't pass arguments by reference, they are passed by value. Read more here
Let's clarify by an example. Make the key you are looking for be integer with value 21.
The situation at the beginning of the function is the following:

So now, when you say:
foundNode = node; // this doesn't reflect outside of the method

You are changing the value of foundNode locally inside the findGivenNode() method, it doesn't apply to outside this method. Basically, the local variable called foundNode references the node you want to change and then you make this local variable foundNode reference the new node by the statement above.
This change is reflected only inside the function. As soon as your function is finished, local variables don't exist anymore so neither does this local version of foundNode. Visual result:

The simple solution is to use a Wrapper function
To keep track of the reference, you can make a simple wrapper class that will store the reference you want:
private class NodeWrapper {
    Node foundNode;
    NodeWrapper() {
        foundNode = null;
    }
}

Then you can create a new NodeWrapper and pass that into your function instead of foundNode
NodeWrapper wrapper = new NodeWrapper();
findGivenNode(root, wrapper, key, parentStack);

Then inside your function instead of:
foundNode = node;

You say:
wrapper.foundNode = node;

This way you can maintain the reference throughout the recursion inside the NodeWrapper. Meaning:
NodeWrapper wrapper = new NodeWrapper();
findGivenNode(root, wrapper, key, parentStack);
// at this point, wrapper.foundNode will hold the reference to the node you need
// or null if the node wasn't found

On another note, above the method you have this function prototype:
findGivenNode(root, key, foundNode, parentStack);

Seems like someone is still used to C/C++ :)
This is unnecessary in Java, you can read this question thread for reasoning behind that or just Google it.


text:
Q: require_once(...) can't find file but it's definitely there I am trying to include a file in a PHP script using a relative path. However, the function returns an error stating that the file doesn't exist.
It does exist - I have attached a file structure screenshot too - and other pages can include it without issue.
Code
require_once("../config.php");

Output

Warning: require_once(../config.php): failed to open stream: No such file or directory in /www/sites/c84/7de/example.com/web/inc/sections.php on line 25
Fatal error: require_once(): Failed opening required '../config.php' (include_path='.:/usr/share/php:/usr/share/pear') in /www/sites/c84/7de/example.com/web/inc/sections.php on line 25
File Structure Screenshot

A: /www/sites/c84/7de/example.com/web/inc../config.php

requires a / after inc and before ..
/www/sites/c84/7de/example.com/web/inc/../config.php

so something like
require_once(__DIR__ . '/../config.php');


text:
Q: Connecting to Movesense I have powered on the Movesense and built the iOS app and installed on my device. I refresh the device list, see a Movesense and tap to connect. From the Device tab in the app, I tap "Connect device", but the wheel spins but never seems to connect. Any ideas?
Other info that may indicate where the issue is: when tapping on the Logging tab and selecting Start data logging, I get the error "The operation couldn't be completed. ([wb] Failed to get resource error 404.) I see the same error when attempting to "Set device time" on the Time and HR tab.
movesense

A: There is an iOS BLE bug that manifested itself when we updated the device bluetooth stack to BLE 4.2 (Nordic Semiconductor SoftDevice 3.0.0). That combination caused the BLE connection getting stuck in service discovery phase.
The fix requires that you flash the latest Movesense device application to the sensor, not just the latest mobile app (actually just the sensor software update is needed because the fix/workaround is there).
So, please flash your sensor with the latest software and you should be able to connect just fine also with iPhone. If you are still having problems, please make an issue in the bitbucket movesense-mobile-lib project.
Full disclosure: I work for Movesense team


text:
Q: Get the digit of last page in Cakephp How do I get just the last page number, not the link that comes with $this->Paginator->last(), but the actual digit itself?

A: This link will help you to achieve the same.
<?php echo $this->Paginator->counter('{:pages}');
     //counter() method with all options
     //echo $this->Paginator->counter('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}');?>

You can call the counter() method into your view to get the last page number.

A: Another solution:
echo $this->Paginator->param('pageCount');


text:
Q: Required MultipartFile parameter 'file' is not present when uploading file I am trying to upload file but i am getting Required MultipartFile parameter 'file' is not present 400 Bad Request org.springframework.web.bind.MissingServletRequestParameterException.
My code here:
<form id="uploadrecords" method="post" enctype="multipart/form-data">

 File to upload:

 <input type="file" class="filestyle" data-buttonName="btn-primary" name="file" id="upload" accept="*"/>

 <button type="submit"  class="btn btn-success" style="padding: 6px 12px;"   id="upload" > Upload</button>
 <button type="button"  class="btn btn-danger"  style="padding: 6px 12px;" id="cancel"  > Cancel</button>

</form>

Jquery code here:
$("form#uploadrecords").submit(function(){
    var formData = new FormData($(this)[0]);
    $.ajax({
    url : '/uploadfile',
    type: 'POST',
    data: formData,
    async: false,
    beforeSend: beforeSendHandler,
    success: function (data) {
    var msg=data.msg;
    var obj=data.obj;
    if(obj != 0){
    $("#countfail").html(obj);
    $("#download-modal").modal('show');
    }else{
    bootbox.alert(msg);
    }
    },
    cache: false,
    contentType: false,
    processData: false
    });
});

Java code:
@RequestMapping(value = "/uploadfile", headers = "Content-Type=multipart/form-data", method = RequestMethod.POST)
public @ResponseBody StatusResponse upload( @RequestParam(value = "file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws IOException, NoSuchFieldException, SecurityException, ParseException {
    StatusResponse sr = new StatusResponse();
    System.out.println("filename::::" + file.getOriginalFilename());
    //my logic here
    return sr;
}

It is not hitting controller class. i find error in Firebug console.
I am using spring boot and jboss-eap-6.4.
What is wrong in my code. How to solve this problem?

A: if you are using @EnableAutoConfiguration then you need to do the following as discussed here https://github.com/spring-projects/spring-boot/issues/2958
@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
define the following beans
@Bean(name = "multipartResolver") public CommonsMultipartResolver commonsMultipartResolver(){ CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setMaxUploadSize(50*1024*1024); return resolver ; }
@Bean @Order(0) public MultipartFilter multipartFilter(){ MultipartFilter multipartFilter = new MultipartFilter(); multipartFilter.setMultipartResolverBeanName("multipartResolver"); return multipartFilter; }


text:
Q: Laravel form not sending any data I am trying to submit form to the laravel. However, I am facing strange issue that the form is being submitted without any data. When I tried to print_r on the cotroller it displays:
Array
(
)

My form looks like this:
<form method="POST" action="{{route('amenityFront.index')}}" id="buildingByProperty">
    @csrf
    <select class="form-control" name="property" id="propertySelect">
        @foreach($properties as $pk => $pv)
            <option value="{{$pv->id}}" {{ ($pv->id == $selectedProperty)?'selected':'' }}>{{$pv->property_name}}</option>
        @endforeach
    </select>
    <button type="submit">Submit</button>
</form>

And this is my route. Is it because of that match route? I am using this match route for first time.
Route:
    Route::match(['get', 'post'],'/', ['as' => 'amenityFront.index', 'uses' => 'AmenityController@index']);

Update:
I have updated form to :
<form method="POST" action="{{route('amenityFront.postIndex')}}" id="buildingByProperty">
    @csrf
    <select class="form-control" name="property" id="propertySelect">
        @foreach($properties as $pk => $pv)
            <option value="{{$pv->id}}" {{ ($pv->id == $selectedProperty)?'selected':'' }}>{{$pv->property_name}}</option>
        @endforeach
    </select>
    <button type="submit">Submit</button>
</form>

and updated route to:
Route::get('/', ['as' => 'amenityFront.index', 'uses' => 'AmenityController@index']);
    Route::post('/', ['as' => 'amenityFront.postIndex', 'uses' => 'AmenityController@postIndex']);

However, instead of redirecting to postIndex I am still being posted to @index
My route:list


text:
Q: $f(z)=\frac1{2\pi i}\int_{\Gamma}\frac{f(\zeta)}{z-\zeta}d\zeta$ if $\lim_{z\to\infty}f(z)=0$ and $f$ is analytic in $|z|\ge1$ Let $f$ be analytic in $|z|\ge1$ and  $\lim_{z\to\infty}f(z)=0$. Then is
$f(z)=\frac1{2\pi i}\int_{\Gamma}\frac{f(\zeta)}{z-\zeta}d\zeta$,$\forall |z|\ge2$, where $\Gamma$ is the circle of radius $2$ with centre at the origin.
I think yes, by the Cauchy integral formula. But, how do we ensure that the non analyticity of $f$ in $|z|<1$ dosent affect the formula? Thanks beforehand.

A: Let $|z|\ge 2$. Let $\Gamma'$ be a circle with centre at $z$ and radius $R$ big enough that the circle lies within the region of analiticity of $f$.
Function $f$ is analitical in the region between the circles $\Gamma$ and $\Gamma'$,  and $z$ lies within this region, so, by the Cauchy formula:
$$ \frac{1}{2\pi i}\Big(\oint_{\Gamma'} - \oint_\Gamma\Big)\frac{f(\zeta)}{\zeta-z}d\zeta = f(z) $$
Let's parametrize circle $\Gamma'$ by $\zeta = z+ Re^{i\phi}$. We have
$$ \oint_{\Gamma'} \frac{f(\zeta)}{\zeta-z}d\zeta = \int_0^{2\pi} \frac{f(z+ Re^{i\phi})}{Re^{i\phi}} iRe^{i\phi}d\phi = i \int_0^{2\pi} f(z+ Re^{i\phi}) d\phi$$
since $R$ is arbitrary (as long as it is large enough) we can take the limit $R\rightarrow\infty$. But since $f$ vanishes at infinity, so does this integral. That means that
$$ \frac{1}{2\pi i}\oint_\Gamma\frac{f(\zeta)}{z-\zeta}d\zeta = f(z) $$


text:
Q: CSS How to center a div horizontally I am working on centering a div horizontally. I have the following code to center my div in the body tag both vertically and horizontally, but seems just the vertical piece works. How can I get the horizontal piece to work as well. Thanks in advance.
body
{
    background-color: #081418;
    font-size: .75em;
    font-family: Verdana, Helvetica, Sans-Serif;
    margin: 0;
    padding: 0;
    color: #696969;
    text-align: center;
}

.OuterRim
{
    border:5px solid #99D7C0;
    height: 97%;
    width: 85%;
    /*center aligning*/
    display: block;
    text-align: left;
    margin: 0px auto;

}

A: margin:0px auto;

if the div is positioned absolute or fixed then use
margin:0px auto;
left:0;
right:0;

A: Take a look here  at this tutorial to learn how to do it. You need to have an element with a fixed width. This can be done with css or jquery.

A: http://jsfiddle.net/persianturtle/jm7vF/1/
I believe this may solve your problem if I understand it correctly.
I placed a container div around your div and put percentage margins all around.
.container {
height: 50%;
margin: 25% 25% 25% 25%;
}

Hope this helps!


text:
Q: The name "Settings" does not exist in the namespace "clr-namespace:App.Properties" I got project, named Perfect. VS 2012 Ultimate, all updated.
I got a window with xmlns:Properties="clr-namespace:Perfect.Properties" in the header
I keep getting error:
The name "Settings" does not exist in the namespace "clr-namespace:Perfect.Properties".

Project compiles, builds and runs fine though. What the hell is with my visual studio?
I got another solution, from which I simply copied the code, there is no such error there.
UPD: There are other namespace troubles, like it can't find my custom Combobox item in my own namespace delcared like xmlns:local="clr-namespace:Perfect.Misc" and used <local:VoidComboItem exchange="All available" />. Class exists and works in runtime, but design editor is not working at all, so I have to use XAML and run app to see changes.

A: I assume you are talking about a WPF app...
1- In most cases this happens when you have other compiler errors, is this the only error you have?
2- also try changing the target to Release and rebuild, then switch back.
3- keep VS updated

A: Most likely your solution is on a network share (see https://stackoverflow.com/a/16218145/647151).
Try mapping the network share to a drive and then open your solution from there.


text:
Q: Get properties with reflection Here is a method in my Xaml.cs:
void itemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.UsingLogicalPageNavigation())
            {
                this.navigationHelper.GoBackCommand.RaiseCanExecuteChanged();
            }

            // Here is the object which properties i am trying to get:
            var mySelectedItem = e.AddedItems[0];

            //Here I would like to acess the properties

        }

Im trying to use reflection to get the propertes from mySelected Item.
Been trying things like:
PropertyInfo property = GetType().GetProperty(propertyName) <--Cant resolve GetProperty()

and
object value = propertyInfo.GetValue(mySelectedItem);<--Cant resolve PropertyInfo

Is it not possibe to use refelctionin this scenario?

A: You don't need reflection for what you want.
You can access the properties of your objects when you cast them to the right object.
void itemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (this.UsingLogicalPageNavigation())
        {
            this.navigationHelper.GoBackCommand.RaiseCanExecuteChanged();
        }
        var mySelectedItem = e.AddedItems[0];

        MyObject myObject = (MyObject)mySelectedItem;

        // Now you can access your property as follows: myObject.MyProperty;

    }


text:
Q: Как анимировать элемент after с помощью css? Это простая линия, которая должна отрисоваться слева на право.

.row {
  height: 100px;
  width: 300px;
  background-color: #555556;
}

.row::before {
  background-color: #63ffd1;
  display: block;
  content: '';
  height: 2px;
  width: 90%;
  position: absolute;
  margin-top: 110px
}

A: Как вариант:

.row {
  height: 100px;
  width: 300px;
  background-color: #555556;
}

.row::before {
  background-color: #63ffd1;
  display: block;
  content: '';
  height: 2px;
  width: 90%;
  position: absolute;
  margin-top: 110px

    -webkit-animation: mymove 5s infinite; /* Safari 4.0 - 8.0 */
    animation: mymove 5s infinite;
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes mymove {
    from {width: 0px;}
    to {width: 200px;}
}

@keyframes mymove {
    from {width: 0px;}
    to {width: 200px;}
}


text:
Q: Can't configure Ubuntu 14.04.3 to generate a warning when battery is low Can't configure Ubuntu 14.04.3 to generate a warning when battery is low. By the way, I do have packages libnotify-bin notify-osd installed.

A: Try to reinstall libnotify-bin notify-osd, using:
sudo apt-get --reinstall install libnotify-bin notify-osd.
This worked for me.


text:
Q: check radiobutton 1, when radiobutton 3 is checked i have html page like this

Q1A Making decisions after finding out what others think

                        <input name="q1a" id="0" value="0" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="1" value="1" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="2" value="2" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="3" value="3" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="4" value="4" onclick="MyAlert()" type="radio" required>
                        <input name="q1a" id="5" value="5" onclick="MyAlert()" type="radio" required>

Q1B Making decisions without consulting others

                        <input name="q1b" id="6" value="0" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="7" value="1" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="8" value="2" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="9" value="3" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="10" value="4" onclick="MyAlert()" type="radio" required>
                        <input name="q1b" id="11" value="5" onclick="MyAlert()" type="radio" required>

if Q1A's value 1 is checked by user, at that moment i want to check Q1B's value 4. analogy is, Q1A's value + Q1B's value = 5.
how can i do this ?
my rough idea is:

but this is not working.
     My Code Example

Thank you for help.

A: You have duplicate IDs, that won't work. getElementById() just returns the first element with that ID.
Instead of finding the element by its ID, find it by its value, a [value=] selector.

function MyAlert(button) {
  if (button.name == 'q19a') {
    var otherName = 'q19b';
    var otherVal = 5 - button.value;
    $(":radio[name=" + otherName + "][value=" + otherVal + "]").prop("checked", true);
  }
}

Q19A Using common sense and conviction to make decisions

<input name="q19a" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q19a" value="5" onclick="MyAlert(this)" type="radio" required>

Q19B Using data, analysis, and reason to make decisions

<input name="q19b" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q19b" value="5" onclick="MyAlert(this)" type="radio" required>

Q20A Planning ahead based on projections

<input name="q20a" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q20a" value="5" onclick="MyAlert(this)" type="radio" required>

Q20B Planning as necessities arise, just before carrying out the plans

<input name="q20b" value="0" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="1" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="2" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="3" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="4" onclick="MyAlert(this)" type="radio" required>
<input name="q20b" value="5" onclick="MyAlert(this)" type="radio" required>


text:
Q: nightmarejs scrape multiple Elements with querySelectorAll I'm trying to scrape some informations from an instagram profile page with nightmarejs (a phantomjs derivate using electron as a browser).
The goal is to get the alt tags of all images on the profile (for examples sake I focus only on the images before the "show more" button)

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });

nightmare
  .goto('https://www.instagram.com/ackerfestival/')
  .evaluate(function () {
    let array = [...document.querySelectorAll('._icyx7')];
    return array.length;
  })
  .end()
  .then(function (result) {
    console.log(result);
  })
  .catch(function (error) {
    console.error('Search failed:', error);
  });

This example works, the array has a length of 12. The electron browser opens and closes, so everything is fine. But if I change the return to just the array, the electron browser never closes and I don't get a console.log.
What am I doing wrong? I want to get all informations from the images in an Array or Object.

A: The problem you're hitting is document.querySelectorAll() returns a NodeList of DOMElements.  Those two object types do not serialize well, and the return value from .evaluate() has to serialize across the IPC boundary - I'm betting you're getting an empty array on the other side of your .evaluate() call?
The easiest answer here is to map out what, specifically, you want from the NodeList.  From the hip, something like the following should get the idea across:
.evaluate(function(){
  return Array.from(document.querySelectorAll('._icyx7')).map(element => element.innerText);
})
.then((innerTexts) => {
  // ... do something with the inner texts of each element
})


text:
Q: Insert into SQL table field not ordered I have this SQL table:

Employee ( Id, Name, Address, Tel)

and I want to execute SQL queries without respecting the indicated order, something like this:
Insert Into Employee (Tel, name, Id, Address)
Values (555621, "Jihen", 10236, "21 Cranberry street")

Am I allowed to do this?

A: Yes, it is allowed. The order in your INSERT query compared to the column order in the table is not signficant.
However, you must ensure the order of column names in your query matches the order that the values are supplied in your query.

A: yes - so long as you specify the order explicitly (as you have shown) in both parts of the statement

A: Yes you can... Have you tried it though?


text:
Q: QAudioProbe не работает с source QMediaPlayer в windows     if(probe->setSource(player))
    {
        qDebug() << "source set ok";

    }
    else
    {
         qDebug() << "source not set";
    }

возвращает "source not set" в Windows.
это проблемный кусок кода, весь проект прекрасно работает в  linux!!!

A: Скорее всего проблема аналогична QVideoProbe:

The WMF plugin in Qt does not currently provide a camera backend.
  Instead, limited support for camera features is provided by the
  DirectShow plugin. Basic features such as displaying a viewfinder and
  capturing a still image are supported, however, majority of camera
  controls are not implemented.
Video recording is currently not supported. Additionally, the
  DirectShow plugin does not support any low-level video functionality
  such as monitoring video frames being played or recorded using
  QVideoProbe or related classes.

Вероятно, что давно нет ведущего разработчика (или вообще никто не хочет этим заниматься) плагинов по направлению QtMultimedia. Реализовано множество обёрток-контролов, предоставляющих унифицированные методы по управлению мультимедиа устройствами, а вот платформозависимый код давно уже не претерпевает каких-либо изменений. С линуксом попроще оказалось, так как бекенд на gstreamer основан и соответственно функционал поддержки устройств сам по себе отчасти обновляется. А с виндовсом хуже - недописали полностью под WMF, а затем и вовсе оставили без внимания.