text:
Q: cannot get the value of isset($_POST['value']) I have 2 php pages. 1st php page is the following:
<?php
  //code...
  if(isset($_POST['value'])== true && empty($_POST['value']) == false){
    echo"See more results for ";
} ?>

the second page is the "search_form_all_2.php".
<?php

$value = mysql_real_escape_string($_POST['value']);

$name_and_surname = explode(" ", "$value ");

$name = $name_and_surname[0];

$surname = $name_and_surname[1];

$query = mysql_query(" SELECT `name`, `surname`, `email`, `user_id` FROM users
   WHERE (surname LIKE '$name%' AND name LIKE '$surname%') OR (surname LIKE
   '$surname%' AND name LIKE '$name%')  ");

while($run = mysql_fetch_array($query)){
    $surname = $run['surname'];
    $name = $run['name'];
    echo"$surname $name  ";
}
?>

I want to make the $value in "search_form_all_2.php" to get the value of the first page that I have in if(isset($_POST['value'])== true && empty($_POST['value']) == false) of 1st page. How can I do this because when running "search_form_all_2.php" I get an erros message:Notice: Undefined index: value

A: In your 1st page, you can pass an argument in the url... example:
echo "See more results for ";

Then, in your 2nd page, you can call the argument... example:
$value = mysql_real_escape_string($_GET['value']);

PS: You shouldn't be using mysql_* functions. Instead learn mysqli at the very least or PDO.

A: You need to use GET in this case. POST values are only send when a form is submited.
if(isset($_POST['value'])== true && empty($_POST['value']) == false){
    echo "See more results for ";

then on second page you retrieve the GET value
$value = mysql_real_escape_string($_GET['value']);

Be careful, GET values are visible to the user. They are part of a URL. Don't send confidential information.
Another way is to save the value in a COOKIE or in SESSION variable.
setcookie("TestCookie", $_POST['value']);
$value  = $_COOKIE["TestCookie"];

BTW empty() always returns boolean value and it already checks if the variable is set, so you only need:
if(!empty($_POST['value'])

A: On search_form_all_2.php you can't access the data value because when you click a link, it is a GET request, not a POST request. I suggest you look up the differences.
However, if you use this to spit out the link:
echo"See more results for ";

You can then retrieve it with $_GET or $_REQUEST (if you want to be able to use GET or POST) on page 2:
$value = mysql_real_escape_string($_REQUEST['value']);


text:
Q: Python convert iteration output data into a table and save My function generates a list at the end of each iteration. A sample output is given below:
['Apple', 'storage1', 0.670786981803283]
['Apple', 'storage2', 0.21871126661028575]
['Apple', 'storage3', 0.002223827213278317]
['Banana', 'storage1', 0.5838190735354087]
['Banana', 'storage2', 0.012979782583266855]
['Banana', 'storage3', 8.760737814985956e-05]
['Orange', 'storage1', 0.8568037051728143]
['Orange', 'storage2', 0.08342768851519906]
['Orange', 'storage3', 0.000543732080791498]

I would like to convert this into a Table consisting of Fruit name on header and storage on left side index and save this table.
My expected output
           'Apple'      'Banana'       'Orange'
Storage1

Storage2

Storage 3

My code:

redpajama_set_name: RedPajamaStackExchange


text:
Q: getting org.springframework.web.bind.MissingServletRequestParameterException I am using spring annotations I have written one method
public ModelAndView showTestPage(@RequestParam("firstInstanceId") String id1,
  @RequestParam("secondInstanceId") String id2, HttpSession  session) {

  ModelAndView mv = new ModelAndView("showCompareItemList");
  mv.addObject("pageTitle", "showCompareItemList");
  mv.addObject("firstInstanceId", id1);
  mv.addObject("secondInstanceId", id2);

  return mv;
 }

when there both values of id1 and id2 are present it works fine but when there is only one value i get exception org.springframework.web.bind.MissingServletRequestParameterException: Required java.lang.String parameter 'secondInstanceId' is not present
I tried resolve this problem by checking null but still i am getting this exception can anybody tell me what should I do to avoid this excpetion?

A: If request parameter may be missed, mark it with required = false:
public ModelAndView showTestPage(@RequestParam("firstInstanceId") String id1,
    @RequestParam(value = "secondInstanceId", required = false) String id2,
    HttpSession session) {
    ...
}


text:
Q: How can I get the permissions of a file in octal format? ... and how can I set them?
Does this work for directories in the same way?
What happens with sticky bit and that more "exotic" stuff?

A: As suggested by @Gustave, the stat program (which is part of GNU coreutils and essentially a "Linux" program for that reason, though you may have a port or package in BSD systems) can do this.  The command
stat -c "%a %n"file
produces a formatted listing with just the octal mode (including the setuid, setgid and sticky bits encoded) and the filename.  According to the documentation

*

*%a is the "Access rights in octal"

*%n is the "File name"

For instance, given this script:
#!/bin/sh
for name in $*
do
    ls -ld "$name"
    stat -c '%a %n' "$name"
done

you might see output like this from myscript /usr/bin /usr/bin/X /usr/bin/bsd-write:
drwxr-xr-x 5 root root 118784 Jul 11 19:55 /usr/bin
755 /usr/bin
-rwsr-sr-x 1 root root 9232 Dec 16  2011 /usr/bin/X
6755 /usr/bin/X
-rwxr-sr-x 1 root tty 11000 Jun 17  2010 /usr/bin/bsd-write
2755 /usr/bin/bsd-write

You would see 3 or 4 octal digits returned for the access rights, depending on whether the setuid, etc., are set.  The leading (fourth) digit combines

*

*4 (setuid)

*2 (setgid)

*1 (sticky)

The access rights returned exclude the extra bits returned by the system call stat which tell whether the name is a directory (S_IFDIR) or file (S_IFREG).  All of those bits, by the way, fit into a 16-bit value because of the long-ago Unix implementations in the 1970s and early 1980s—and have standard values.  Because the access rights exclude the file type, you can use that value as-is in the chmod command (and also the chmod function), because it is octal, and the chmod command expects that.  Even the setuid, etc., work with octal although things like
chmod u+s /usr/bin/whatever

are more readable.
For further reading

*

*What is the first chmod octal digit in a four-digit value for?

*How does the sticky bit work?

A: stat -c "%a %n" <file>

seems to work - but I do not know more.

A: Getting: as Gustave answered.
Setting:
chmod 0755 myfile

Same for directories. For sticky bit, the first digit should be 1. About the sticky bit: https://askubuntu.com/a/432703


text:
Q: Change viewController BG color based off another view controller So I need some help for a project. I have a simple tab bar SVC where the first view is a timer and the second is a settings page. On the settings page I've setup a struct with an array of colors, then when a user clicks a button a random color in the array is called and applied to the back ground. This part works just as I Intended. What I'd like to do is then apply that color to the background of the second view.
Here is the settings code
import UIKit
import GameKit

public var randomColor = UIColor()

class SettingsViewController: UIViewController {

@IBOutlet weak var pushMe: UIButton!
let colorProvider = BackgroundColorProvider()

@IBAction func pushMeChange(_ sender: Any) {
randomColor = colorProvider.randomColorBG()
print (randomColor.superclass as Any)
view.backgroundColor = randomColor
}

struct BackgroundColorProvider {
let colors = [
    UIColor(red: 90/255.0, green: 187/255.0, blue: 181/255.0, alpha: 1.0), // teal color
    UIColor(red: 222/255.0, green: 171/255.0, blue: 66/255.0, alpha: 1.0), // yellow color
    UIColor(red: 223/255.0, green: 86/255.0, blue: 94/255.0, alpha: 1.0), // red color
    UIColor(red: 239/255.0, green: 130/255.0, blue: 100/255.0, alpha: 1.0), // orange color
    UIColor(red: 77/255.0, green: 75/255.0, blue: 82/255.0, alpha: 1.0), // dark color
    UIColor(red: 105/255.0, green: 94/255.0, blue: 133/255.0, alpha: 1.0), // purple color
    UIColor(red: 85/255.0, green: 176/255.0, blue: 112/255.0, alpha: 1.0), // green color
]

func randomColorBG() -> UIColor {
let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: colors.count)
return colors[randomNumber]
    }
}

}
Then I have this in the main viewController I pulled from here:
Changing background color of all views in project from one view controller?
The function does error below doesn't error out however I'm a noob at best, I'm not sure how the bell should work and i doubt its even being called. Any help is appreciated.
// bringing in background color from SettingsViewController

 func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "Load View") {
        // pass data to next view
        let viewController:SettingsViewController = segue!.destination as!  SettingsViewController
        viewController.view.backgroundColor = self.view.backgroundColor
    }
}

A: Swift has this neat feature called a singleton that can be used to manage "settings" across a list of view controllers. In the viewDidLoad() method of the timer view you can set the view's background color to singleton.backgroundColor. In the settings view, when the user selects a new color, it should set singleton.backgroundColor = newColorThatUserChose. This way, when the user switches back to the Timer View, the color will automatically switch.
As shown in the link above, a singleton can be created like this:
class Settings {
    static let sharedInstance = Settings()
    var backgroundColor = UIColor.White // set to white by default.
}

Then in the viewDidLoad method for the Timer View:
self.view.backgroundColor = Settings.sharedInstance.backgroundColor

Finally in the SettingsViewController when the user chooses a new color:
var color = [UIColor.White, UIColor.Black, UIColor.Blue, UIColor.Green........]
Settings.sharedInstance.backgroundColor = color[x] // where x is the index that was chosen.

This will allow the views to change automatically based on the apps settings. To ensure that this works in all of the views that you would like to change the color for,
self.view.backgroundColor = Settings.sharedInstance.backgroundColor

should be placed in every UIViewController.
To further abstract this, you can create a custom class called GeneralUIViewController which is a class of type UIViewController and has the above code in its viewDidLoad method. After doing this every UIViewController should have its class set to GeneralUIViewController. This will make it so you only need to set the background color in one file and every view controller in your project will automatically inherit setting its background color to what the User has chosen in the settings page of this application.
These preferences should probably be saved when the application is reopened so CoreData can be used for this. I'd check out this link for more information.


text:
Q: json string is not converting into object Here is the server side code I am trying to send json
$x = array();
$timestamp = strtotime('22-09-2008');
$x["x"] = $timestamp;
$x["y"] = 22;

$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo json_encode($val);

So output for above code looks like
   "[{ \"name\": \"weight\", \"dataPoints\": [{\"x\":1222041600,\"y\":22}] }]"

Below is the client side code I get the data via Jquery getJSON
var jqxhr = $.getJSON( "https://domain/gettracker.php?id="+id, function(data) {

 console.log(data);

})

I suppose getJson converts json to object automatically , but it logs the raw json like below
"[ {  name: "weight", dataPoints: [{"x":1222041600,"y":22}] } ]"

I tried to do json parse , but i get error.
I guess I am not sending the data properly via php.Can some one guide me ?

A: Your JSON string is not valid - the property names should be enclosed in double quotes - ", and you don't need to encode the string again.
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo $val;

Or better yet, use json_encode to create the string for you:
$data = array(
    'name' => 'weight',
    'dataPoints' => $x
);

echo json_encode($data);


text:
Q: How to get name of each and every file in a folder and apply in a batch file? I want to create a Windows batch file that take each and every file with particular extn (say *.doc ) and apply in a command syntax and execute it. How to do this ?
for ex:
a folder contains
a.doc
b.doc
c.doc

format of command
java -Durl=http://localhost:8983/solr/update/extract?literal.id=**** -Dtype=application/word -jar post.jar ****

where
**** -> name of each document

for ex at first iteration it should produce.
java -Durl=http://localhost:8983/solr/update/extract?literal.id=a.doc -Dtype=application/word -jar post.jar a.doc

and have to execute it.
at 2nd iteration.
java -Durl=http://localhost:8983/solr/update/extract?literal.id=b.doc-Dtype=application/word -jar post.jar b.doc

like this.
How can I do this?
Note : the used file name should not repeat again (not used again in cmd production )

A: @echo off
pushd c:\test_dir

for /r %%a in (*) do (

  java -Durl=http://localhost:8983/solr/update/extract?literal.id=%%~nxa -Dtype=application/word -jar post.jar "%%~dpfnxa"
)

This will process the files recursively.You can filter the files "wild-cards" expression ->
for /r %%a in (*doc) or do it only for the current folder for %%a in (*) .


text:
Q: Exceptions as an error handler OR custom error handling class? I regularly debate with one of my work colleagues as to the most suitable way of 'doing' error handling within an object orientated PHP project.
He is of the view that we should continue to use Exceptions (legacy code).
In his methodology you would have a method as follows:

private function doSomething() {
    if (condition) {
        throw new CustomException("error message");
    }
}

You would then call it within a try catch block and add the exception error to an array of errors (which you can then output as you choose).
In the example above the condition is a boolean comparison for which it is perfectly plausible to receive a true or false response.
Posts like this one: Error Handling in a PHP Class seem to agree with this position..
It is my view that because both true or false are perfectly reasonable responses, this is an inappropriate usage of Exceptions. A false is not Exceptional, but rather perfectly normal.
As such I have gone about created a custom error class which you instantiate at the top of your method. Any errors within your method you then add to an errors array property of this instance. You then return this instance back from your method and can call the passesConditions() method of the class which returns a boolean dependent on if there are any errors or not.
This approach is always extensible in that you could log all failures in a consistent manner (I appreciate you can do similar with Exceptions :))
So are either of us more correct than the other, and if so why?
Many Thanks

A: I'm starting to think that exception based development is bad, although I'm not completely sure yet.
But I disagree with your statement that 'false and true are both valid results'. Of course that is true for a normal boolean, but in the context of the code you are testing. For instance, if you want to request a file, the file must exist, so FileExists should return true. It could return false, which is valid in itself, but not in the context of this file loader script.
In an other example, you could do an HTTP request and get its result status code as an integer. While 404, 500 and even -1 are perfectly good integers, they indicate an exceptional status, assuming that you expect the url to return a proper 200 OK (or maybe 304 Not modified).
So the fact that you are logging an error to your class, indicates that even you agree it is an erroneous value. Whether you solve that by raising an exception is a completely different discussion.
Personally, I don't like your solution so much. I think it clutters the code, because you always have to process the resulting object (whereas exceptions can be caught on a higher level). Also, if you want to return an actual value from the function as well, the object will be in the way, unless you extend it with an extra property containing the actual result, but then I think you will get lost in your own code really, really soon.


text:
Q: Signed jar throws java.lang.reflect.InvocationTargetException I wrote a JApplet that lives in a signed jar (I purchased a certificate).  I'm working through trying to get it to work on a web server.  When I invoke it using a standard "applet" tag, I get the nag dialog that recognizes that the jar is signed.  It then displays another dialog asking to block the applet content.  It mentions that I have a mixture of my signed jar, and other unsigned jars (namely javax.mail.jar, mysql-connector-java-5.1.25-bin.jar, and some others).  It results in the following console dump:
security: Trust for: http://MyUrl/javax.mail.jar has ended: Wed Dec 31 19:00:00 EST 1969
basic: exception: java.lang.reflect.InvocationTargetException.
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.runOnEDTAndWait(Unknown Source)
    at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.instantiateApplet(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager.initAppletAdapter(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
    at com.sun.deploy.uitoolkit.impl.awt.OldPluginAWTUtil.invokeAndWait(Unknown Source)
    ... 5 more
Caused by: com.sun.deploy.security.BlockedException: User has denied the priviledges to the code
    at sun.plugin2.applet.Plugin2ClassLoader.getPermissions(Unknown Source)
    at sun.plugin2.applet.Applet2ClassLoader.getPermissions(Unknown Source)
    at java.security.SecureClassLoader.getProtectionDomain(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.defineClassHelper(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.access$100(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin2.applet.Plugin2ClassLoader.findClassHelper(Unknown Source)
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter$1.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
basic: Removed progress listener: sun.plugin.util.ProgressMonitorAdapter@2ddb6b
security: Reset deny session certificate store
basic: Dialog type is not candidate for embedding

The console output also warns about a "Missing Permissions manifest attribute" and a "Missing Codebase manifest attribute" even though I specified them in the html code.
I've also tried running it via a jnlp file.  When I try that, it does not seem to recognize the jar is signed as evidenced by the following:

It results in the same console dump.
I'm treading on new ground.  Can someone shed some light on this?  I know it's probably something basic, but, I could use another set of eyes on this.
Thanks in advance for any help, advice, etc.

A: I was able to resolve this problem by signing the jars one at a time.  I ran the app and watched the console messages.  Each time, the console output would complain about a different jar having expired security.  One by one, I signed the jars in question, and, the problem resolved itself.  I'm not sure this is the appropriate way of handling this, but, it fixed the problem.


text:
Q: Split pandas column into new columns in presence of NaN I have a pandas DataFrame containing a string column which needs splitting into two separate columns.  The answer using tolist that I found on SO from this question works like a charm, except when my column contains NaNs.  The excerpt below describes the difficulty:
import pandas as pd
import numpy as np

# Example DataFrame
df = pd.DataFrame([[25.0, '34.2/ 18.1', 'one'],
                   [32.6, '28.6/ 17.9', 'two'],
                   [12.5, '30.1/ 17.6', 'three']], columns=['A', 'B', 'C'])
df2 = df.copy()

# This method works when all data are present
df['D'] = pd.DataFrame(df['B'].str.split('/').tolist())[1]

# However, when there are NaNs:
df2['B'][0] = np.nan

# This line fails
df2['D'] = pd.DataFrame(df2['B'].str.split('/').tolist())[1]

It gives me a KeyError, because the intermediate DataFrame only has one column, indicating that the bother of going to a list and back doesn't accomplish anything anymore:
               0
0            NaN
1  [28.6,  17.9]
2  [30.1,  17.6]

I've tried dropping the NaN first via pd.DataFrame(df2['B'].str.split('/').dropna().tolist()), but then I lose my index ... I need to keep the NaN at index 0.  I've also thought of somehow duplicating the NaN in the creation of the intermediate DataFrame to force the two columns, but am having no luck.
This is what I would need my data to look like for df2:
      A           B      C     D
0  25.0         NaN    one   NaN
1  32.6  28.6/ 17.9    two  17.9
2  12.5  30.1/ 17.6  three  17.6

Is there a way to do this without using a list as an intermediary?  Or somehow deal with the NaN?

A: You can continue to use your method if you use the str accessor again after the split (instead of using tolist() and making another DataFrame):
>>> df2['D'] = df2['B'].str.split('/').str[-1]
>>> df2
      A           B      C      D
0  25.0         NaN    one    NaN
1  32.6  28.6/ 17.9    two   17.9
2  12.5  30.1/ 17.6  three   17.6

This returns NaN if the index doesn't exist, instead of raising the error.

A: The str.extract method allows you to provide a regex pattern. Each group in the pattern is returned as a separate column. NaN is used when no match is found:
df2['D'] = df2['B'].str.extract(r'/(.*)')
print(df2)

yields
      A           B      C      D
0  25.0         NaN    one    NaN
1  32.6  28.6/ 17.9    two   17.9
2  12.5  30.1/ 17.6  three   17.6

Note that if you want the D column to be treated as floats, then you'll also need to call astype:
df2['D'] = df2['D'].astype('float')


text:
Q: Gradle release build still debuggable? According to the Gradle docs, the default value for "debuggable" a "release" buildType is false. However, whether I explicitly set it to false or not, my release build always seems to be debuggable (I can see logcat output). Am I misinterpreting this property? Can someone please explain?
Here's my build.gradle:
buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.4.2'
    }
}

apply plugin: 'android'

dependencies {
    compile project(':facebook-android-sdk-3.0.1:facebook')
    compile project(':google-play-services_lib')
    compile project(':nineoldandroids')
    compile project(':SlidingMenu-master:library')
    compile project(':ViewPagerIndicator')
    compile project(':volley')
    compile project(':windowed-seek-bar')
    compile files('compile-libs/androidannotations-2.7.1.jar', 'libs/Flurry_3.2.1.jar', 'libs/google-play-services.jar', 'libs/gson-2.2.4.jar', 'libs/picasso-1.1.1.jar', 'libs/crittercism_v3_0_11_sdkonly.jar', 'libs/gcm.jar', 'libs/apphance-library.jar')
}

android {
    buildToolsVersion "17.0"
    compileSdkVersion 17

    signingConfigs {
        debug {
            storeFile file('keystores/debug.keystore')
        }

        release {
            storeFile file('keystores/release.keystore')
            storePassword "***"
            keyAlias "***"
            keyPassword "***"
        }
    }

    buildTypes {
        release {
            signingConfig signingConfigs.release

            sourceSets {
                main {
                    manifest.srcFile 'AndroidManifest.xml'
                    java.srcDirs = ['src', 'normal']
                    resources.srcDirs = ['src']
                    aidl.srcDirs = ['src']
                    renderscript.srcDirs = ['src']
                    res.srcDirs = ['res']
                    assets.srcDirs = ['assets']
                }
            }
        }
    }
}

A: Viewing logcat is not tied to whether the app is debuggable or not.
If you see the process in DDMS then your app is debuggable (unless you're looking at an emulator in which case all apps are considered debuggable).

A: If you're using Build -> Generate Signed APK in Android Studio, it's using assembleDebug gradle task instead of assembleRelease. Try executing assembleRelease task manually and debuggable flag should be false

A: To be sure that debug is not allowed, you can declare debuggable=false in your application tag in the AndroidManifest.xml. Don't know if it will help in your case.


text:
Q: Unable to find element either way in Selenium Below is the link to which I am trying to click but it is showing -- no such element present exception error:
Product

First I tried: driver.findElement(By.linkText("Product")).click();
It was working earlier but now not working.
Other than above I tried XPath and CSS selector but none is working.


text:
Q: Как сравнить элементы списка и словаря. Найти сумму списка со значениями из словаря Суть: есть словарь, где каждому элементу (продукту) присваивается цена
Задача: посчитать общую стоимость продуктов, которые внесены в список nourriture
Проблема: если в список внести 2 одинаковых элемента из словаря (например ["pomme", "orange", "orange"], то одинаковые элементы считаются 1 раз, а не 2 (например, для ["pomme", "orange", "orange"] должен общую сумму вернуть 5, а возвращает 3,5).
Как тогда прописать условие?
prix = { "banane": 4,
    "pomme": 2,
    "orange": 1.5,
    "poire": 3
}

def calculer_facture(nourriture):
    total = 0
    for produit in prix:
        if produit in nourriture:
            total = total + prix[produit]
    return total

A: Как то так:
>>> prix = {"banane": 4, "pomme": 2, "orange": 1.5, "poire": 3}
>>> nourriture = ["pomme", "orange", "orange"]
>>> sum(prix[n] for n in nourriture)
5.0

A: prix = {"banane": 4, "pomme": 2, "orange": 1.5, "poire": 3}

def calculer_facture(nourriture):
    total = 0
    for produit in prix:
        if produit in nourriture:
            total += prix[produit] * nourriture.count(produit)
    return total


text:
Q: Why React Native FlatList style not change with state I have some tabs. I want to change the color of the selected tab. I created a state for selected tab index which will hold the tab ID. When Tab is pressed the selected state change to the pressed tab ID. I am comparing the selected state to tab ID. If  both are equal then the selected tab will have some different style.
But when state changes and condition is true, the selected tab is not changing its state. Why change in state do not trigger the comparison in the style to update the style?

<FlatList
  horizontal
  data={this.state.drinkgroup}
  showsHorizontalScrollIndicator={false}
  renderItem={({item, index}) =>
  {
    return  <Tab
      item={item}
      selected={this.state.selected}
      changeSelected={
        () => {
          this.setState({selected: item.id}, function(){                       console.log(this.state.selected, item.id)
          console.log(this.state.selected==item.id)
          })
        }}
      }
  }
/>

export const Tab = ({item, selected, changeSelected}) => {
    return (
        <TouchableOpacity
            style={[styles.tabStyle, (selected==item.id)? styles.tabSelectedStyle: null]}
            onPress={changeSelected}
            underlayColor='#fff'
        >
            <Text style={{color: '#f2f2f2', textAlign: 'center', fontSize: 15}}>{item.name}</Text>
        </TouchableOpacity>
    );
}

const styles = StyleSheet.create({
    tabStyle: {
        backgroundColor: '#800080',
        height: 32,
        paddingRight: 15,
        paddingLeft: 15
    },
    tabSelectedStyle: {
        borderBottomColor: 'white',
        borderBottomWidth: 3
    }
})

A: By passing extraData={this.state} to FlatList we make sure FlatList itself will re-render when the state.selected changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is also a PureComponent and the prop comparison will not show any changes.
<FlatList
   data={this.props.data}
   extraData={this.state}
   keyExtractor={this._keyExtractor}
   renderItem={this._renderItem}
  />

This is a PureComponent which means that it will not re-render if props remain shallow- equal.
Make sure that everything your renderItem function depends on is passed as a prop (e.g. extraData) that is not === after updates, otherwise your UI may not update on changes.
This includes the data prop and parent component state.
More Details :- FlatList

A: You need to provide extraData prop to the Flatlist, if you want it to re render its items. You can do it like extraData={this.state}.
By passing extraData={this.state} to FlatList we make sure FlatList itself will re-render when the state.selected changes. Without setting this extraData prop, FlatList would not know it needs to re-render any items because it is also a PureComponent and the prop comparison will not show any changes.
For further details you can visit official documentation here


text:
Q: how to format data to make it time series data in R I want to do time series analysis on the following data
but I can't convert it into time series data,
Data can be downloaded from the given link https://datamarket.com/data/set/22ox/monthly-milk-production-pounds-per-cow-jan-62-dec-75#!ds=22ox&display=line
I have tried str_split_fixed function to separate it into two columns but putting back together as a time series after splitting is a problem

This is what I have tried:
#Convert it into Time series
#Train Data
ds.ts<-ts(ds$V2,start = c(1962,1),end = c(1974,12),frequency = 12)
ds.ts
plot(ds.ts)
plot(decompose(ds.ts))
#Test Data
ts.1975<-ts(ds$V2,start=c(1975,1),end=c(1975,12),frequency = 12)

A: I exported as .tsv (tab separated), but .csv should work as well. Then read to data.table and use substr to extract the first 4 digits as year (and convert to integer) and the last 2 digits as month:
library(data.table)
dt <- fread("~/Downloads/monthly-milk-production-pounds-p.tsv")
dt[, ":="(
  year = as.integer(substr(Month, start = 1, stop = 4)),
  month = as.integer(substr(Month, start = 6, stop = 7)))]

>dt
       Month Monthly milk production: pounds per cow. Jan 62 ? Dec 75 year month
  1: 1962-01                                                      589 1962     1
  2: 1962-02                                                      561 1962     2
  3: 1962-03                                                      640 1962     3
  4: 1962-04                                                      656 1962     4
  5: 1962-05                                                      727 1962     5

Updated based on comment by AkselA:
To obtain a time-series use as.Date as suggested by AkselA:
library(data.table)
dt <- fread("~/Downloads/monthly-milk-production-pounds-p.tsv")
dt[, date_time := as.Date(paste0(Month, "-01"), format="%Y-%m-%d")]

>dt
       Month Monthly milk production: pounds per cow. Jan 62 ? Dec 75  date_time
  1: 1962-01                                                      589 1962-01-01
  2: 1962-02                                                      561 1962-02-01
  3: 1962-03                                                      640 1962-03-01
  4: 1962-04                                                      656 1962-04-01
  5: 1962-05                                                      727 1962-05-01


text:
Q: lockfileex doesn't stop create_always from erasing the file in one process, i called createfile with GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_ALWAYS, and FILE_ATTRIBUTE_NORMAL as the params.
then i called LockFileEx on the whole file. i acquired an exclusive lock, and locked from range 0 to UINT_MAX.
after that, in another process, i called ::CreateFileW(path.c_str(), perms, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
and it erased the contents of the file. shouldn't it not be able to do that while my other prcoess has the file locked (exclusively)?
i want other processes to be able to get handles to the file (which is why i used the file_share flags), but i assumed they couldnt change the file at all while another process locked it, and so i was doing something like
createfile
lockfileex
and having it block on lockfileex until the other file releases the lock. is it just me or is msft's behavior here wrong?

A: It is debatable whether Windows should honor file locks when you attempt to open a file with CREATE_ALWAYS, but it appears from your notes that it does not. The best way to prevent other processes from writing to a file that you have open is not to specify FILE_SHARE_WRITE in your exclusive process.
However, this won't give you the waiting behavior that you would get from the file lock implementation without polling. There is no way to open a file with exclusive access and have any other files that are attempting to open it wait until the process with exclusive access relinquishes that access.
If you have access to the source of all of the processes involved, then you could just have the processes that are attempting to truncate the file first call LockFileEx on a region, and then call SetFileSize after acquiring the lock.
As a side note, only locking the region from 0 bytes to UINT_MAX won't provide mutual exclusion if, say, a process opens the file and attempts to write to the location at UINT_MAX + 1 (just past the 4GB point).


text:
Q: How to include instances of a given class in its constructor in python? How do we include instances of a given class in its constructor?
class Node:
  # Results in "Unresolved reference 'Node'"
  def __init__(self, val: int, left: Node, right: Node):
           self.val = val
           self.left = left
           self.right = right

Note: I have seen several questions similar to this but they are not asking exactly the same thing and/or are garbled.
Update  Not surprisingly there does exist an answer somewhere in SOF to the question. But given the question I posed it's basically impossible to find that Q&A from This question already has answers here .  The answer given in a comment below is
from __future_ import annotations

as the first line in the script/module


text:
Q: Getting wrong time for timestamp field with hibernate select Getting wrong time for timestamp field with Hibernate select.

We are using Hibernate framework and Postgres database.
We have a table which stores 'created_time' in column of data type TIMESTAMP WITH TIME ZONE.
+------------------------------------------+
+ created_time +
+------------------------------------------+
+ 2014-09-22 04:30:00.756 +
+ -----------------------------------------+

Assume we have a data '2014-09-22 04:30:00.756' in 'created_time'.
I used the following hibernate query
query= "SELECT column1,column2,createdTime FROM TableName";
…
…
List<Object[]> dataList=selectQuery.list();
for(Object data[] : dataList)
{
System.out.println("Date and time -> "+data[2].toString()); //Time coming wrong here
}

When I go throught the dataList I find that the date is coming correctly, but the time is something else like '11:45:00.345'.
The same query if I used in pgAdminIII means it is coming correctly.
But with hibernate it is coming wrongly.
I have even tried SQL query. Still I face the wrong time problem.
I am not getting a solution when i searched the net.

A: probably you are getting the local time zone instead of the server timezone.
So to get the timestamp of server as it is , change your query to something like below:
query= "SELECT column1,column2,createdTime at time zone current_setting('TIMEZONE') FROM TableName";

A: It is a common problem when we want to read/write dates from DB and store them in UTC time zone. For example in case of reading from DB a date with time 9:54 using Hibernate, thanks to JDBC, we get a 9:54 time, but interpreted as a local date; for me it would be 9:54 UTC+2. This means that on Java side we just got 7:54 UTC time. There is a better explanation of this issue in this article.
Anyway, you can easily fix it by using a small DbAssist open source library. It maps the standard Date fields to a custom UtcDateType, which forces Hibernate to treat dates as UTC. You can find more details about the supported Hibernate versions and installation guide on project's github wiki.
If you are using JPA annotations to map entities, just add the following dependency:
<dependency>
    <groupId>com.montrosesoftware</groupId>
    <artifactId>DbAssist-5.2.2</artifactId>
    <version>1.0-RELEASE</version>
</dependency>

Applying the fix is really simple; for example, if you are using persistence.xml file with your Hibernate, just add a single line inside persistence-unit tag:
<class>com.montrosesoftware.dbassist.types</class>

For other Hibernate configurations, e.g with Spring Boot, refer to the github project page. Anyway, the fix works instantly after this step and now all the dates read from (and saved to) the DB through Hibernate are treated as UTC.


text:
Q: Limit notation: what does it mean when no bound is specified? In my statistics text it is discussing the limit of a probability of a sequence of events, $ A_1, A_2, ...$, and has this notation:
$$
\lim_i \mathbb{P}(A_i)
$$
Can I just consider this shorthand for this?:
$$
\lim_{i \to \infty} \mathbb{P}(A_i)
$$
Or is that somehow inappropriate since i is incrementing discretely?


text:
Q: Purchased at rates from/at rates ranging from Question: Does it sound natural with or without "ranging from"? Or should it be omitted?
I've seen examples of sentences with the noun "price" and both variants - with/without "ranging from" - are possible, as far as I've seen.
Context: I want to explain to users that a certain number of projects have been ordered from freelancers within the range of, let's say, $15 - $20 per hour. The sentence will be similar to the following: 30% of {tasks/projects} were ordered at rates from/ranging from $10 to $20 per hour.
I'm not sure whether I can find a grammatical rule to apply here, so asking native speakers to confirm which variant (with/without "ranging from" will sound natural to you).

A: There are no "rules" governing this. However, as "$10 to $20" is a range, "ranging" seems otiose, although not wrong.


text:
Q: FOR XML EXPLICIT formatting output I have a table with the following structure:
------------------------------------
invoice_id | device_id | terminal_id
------------------------------------
1          | SY000001  | GP000001
1          | SY000001  | GP000001
1          | SY999000  | GP999000
2          | SY111001  | GP111001

I want to get the data from the table in the following format:
SY000001 [GP000001] |
SY999000 [GP999000] |

Currently I was able to get the result in the following format (without the delimiter " | "):
SY000001 [GP000001]
SY999000 [GP999000]

My query is:
SELECT DISTINCT
    1 as tag,
    null as parent,
    'view_device.aspx?id=' + device_id [a!1!href],
    device_id + ' [' + terminal_id + ']' [a!1!]
FROM DEALERS_SIMPAYMENTS
WHERE
    invoice_id = 1
FOR XML EXPLICIT

Is this possible, and if it is, how?
SQL server 2008.

A: Can't you just use this query to achieve your required result??
SELECT
    DISTINCT
    '' + t.device_id + ' [' +
    t.terminal_id + '] |&nbsp'
FROM DEALERS_SIMPAYMENTS t
WHERE t.invoice_id = 1

Returns two strings:
SY00001 [GP00001] |&nbsp
SY999000 [GP999000] |&nbsp

A: It seems you want a HTML fragment rather than XML. In this special case I'd go for string concatenation. Something like:
SELECT '' +
       device_id + ' [' + terminal_id + '] | '
FROM DEALERS_SIMPAYMENTS
WHERE invoice_id=1

should do the trick. This just works for your simple example of course and does no XML/HTML-escaping for funny characters in your data and such nice things. It also returns the entries in seperate rows. I don't know if that is a problem or not.


text:
Q: Transform SQL LIMIT query to Dynamodb How can I transform this sql query Select name , college_id,phone_number from users where college_id =2 limit 100 in dyanmodb.
I tried below code
  $iterator = $dynamo->query(array(
                    'TableName'     => 'users',
                    'IndexName' => 'college_id-phone_number-index',
                    'ScanIndexForward' => false,
                    'KeyConditions' => array(
                        'college_id' => array(
                            'AttributeValueList' => array(
                                array('S' => (string)$collegeId )
                            ),
                            'ComparisonOperator' => 'EQ'
                        ),
                        'phone_number' => array(
                            'AttributeValueList' => array(
                                array('S' => (string)$phoneNumber)
                            ),
                            'ComparisonOperator' => 'EQ'
                        )

                    ),

                    **'Limit' => 100,**
                )

            );

I found that Limit = 100 restrict the total number of items to process than total number of matching items to return .
Please help me.

A: There is no equivalent to the SQL LIMIT command in Amazon DynamoDB. You should keep iterating through the paged result sets until you have reached the desired number of records.
Update:
Oops! There is a limit parameter. From QUERY documentation:

Limit: The maximum number of items to return (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while querying the table, it stops the query and returns the matching values up to that point, and a LastEvaluatedKey to apply in a subsequent operation to continue the query. Also, if the result set size exceeds 1MB before DynamoDB hits this limit, it stops the query and returns the matching values, and a LastEvaluatedKey to apply in a subsequent operation to continue the query.

So, keep paging through 1MB result sets until the limit is met.


text:
Q: Solving a system of equations with less equations than variables For my discrete math/linear algebra class, one of our homework problems reads as follows:
Use backsubstitution to solve the following system of equations and obtain the general
solution.
3x + 4y + 7z - 3t = 3
0x + 5y + 3z = 40

Now, I've always been taught that you need as many equations as variables to solve a system of equations. Is there a way to do this where you don't need as many equations as variables? Or would I be correct in making x and t both equal 1 so that they cancel out and then solve the system that way?

A: Are you familiar with Gaussian elimination for non-square linear systems? You want to construct the augmented matrix
$$ \begin{bmatrix} 3 & 4 & 7 & -3 & | & 3 \\ 0 & 5 & 3 & 0 & | & 40 \end{bmatrix}$$
and perform back-substitution to obtain a reduced row-echelon form. You do not want to arbitrarily set $x = t = 1$, because then you are not obtaining every solution.

A: You have $5y+3z=40.$ Express that as $3z=40-5y \implies z=\frac{40}{3}-\frac{5}{3}y$, and then plug that value of $z$ into your first equation. That's what back substitution essentially is.
Your solution won't be a finite set of points; to have that, you need an independent equation for each variable you have (i.e., no equation is a linear combination of other equations in that matrix). You'll get to that soon enough in your course.
Rather, your equation will be an infinite set of points. We describe them by the final reduced row-echelon form matrix that Christopher Wong alluded to.


text:
Q: use aggregators functions in laravel i have a sql query i want to run in laravel, this would be the final query that works in msql server
select MAX([formulas].[id]),
MAX([formulas].[numero]),
MAX([formulas].[nombre]),
MAX([formulas].[idSeccionFormula]),
MAX([nombreProducto]),
MAX([formulas_equivalencias].[equivalencia]),
MAX([productos].[coste]),
[formulas_detalle].[id]
from [formulas] inner join [formulas_detalle] on
[formulas].[id] =[formulas_detalle].[idFormula] inner join
[formulas_equivalencias] on [formulas].[id] = [formulas_equivalencias].[idFormula]
inner join
[productos] on [formulas_detalle].[idProducto] =[productos].[id]
where [idSeccionFormula] = 1
group by [formulas_detalle].[id]

I have this in Laravel:
$formulas = new Formula();
$formulas = $formulas
->select('MAX([formulas.id])','MAX(formulas.numero)','MAX(formulas.nombre)','MAX(formulas.idSeccionFormula)', 'MAX(productos.nombreProducto)', 'MAX(formulas_equivalencias.equivalencia)', 'MAX(productos.coste)',
                            'formulas_detalle.id')
                    ->join('formulas_detalle', 'formulas.id', '= ', 'formulas_detalle.idFormula')
                    ->join('formulas_equivalencias', 'formulas.id', '= ', 'formulas_equivalencias.idFormula')
                    ->join('productos', 'formulas_detalle.idProducto', '= ', 'productos.id');

But i am getting a Laravel error:

The multi-part identifier "MAX([formulas.id])" could not be bound.

I have read how to use aggregators in laravel but i cannot used them in this case, i tried to use DB::raw(), but no luck.
I hope someone can know the answer to it, thanks in advance.

A: $forumulas = $formulas->join('formulas_detalle', 'formulas.id', '= ', 'formulas_detalle.idFormula')
                      ->join('formulas_equivalencias', 'formulas.id', '= ', 'formulas_equivalencias.idFormula')
                      ->join('productos', 'formulas_detalle.idProducto', '= ', 'productos.id')
                      ->select([
                                 DB::raw('Max(formulas.id) as id'),
                                 DB::raw('Max(formulas.numero) as numero'),
                                 DB::raw('Max(formulas.nombre) as nombre'),
                                 DB::raw('Max(formulas.idSeccionFormula) as idSeccionFormula'),
                                 DB::raw('Max(productos.nombreProducto) as nombreProducto'),
                                 DB::raw('Max(formulas_equivalencias.equivalencia) as equivalencia'),
                                 DB::raw('Max(productos.coste) as coste')
                               ])
                      ->get()


text:
Q: Combination of Data from Two Normal Samples not Normal? I have two sets of data that hypothesis tests have shown to be normal and from the same distribution.  I'm using MATLAB and for the way they give p-values, higher p-values suggest a better goodness-of-fit, as I understand it.  I want to combine the two data sets to get the parameters for the combined data set.  However, when I run a hypothesis test on the combined data set, hypothesis tests either reject the null assumption of Normality or come very close as seen by the test statistics.  I've been looking for an explanation but have no idea where to start. Could anyone shed some light into this?

A: If you're talking about a test of the null hypothesis that your sample data come from an exactly normal distribution, you'll probably want to see this question: Is normality testing 'essentially useless'?
Most (if not all) real data is not normally distributed exactly. You can estimate the skewness and kurtosis to quantify how different your data's distribution is from a normal distribution. Even small amounts of skew or excess kurtosis become easier to estimate precisely as data aggregates. By combining your two samples, you're improving the precision of your estimates. It seems you have enough data to estimate your distribution's differences from a normal distribution so precisely that, with your normality tests' $p$ values,  you can say there's "very close" to or less than $\alpha$ (typically 5%) chance that, from a truly normal distribution, you would randomly sample a dataset that is as large and at least as different from a normal distribution as yours is. Since that's the null hypothesis in a nutshell, and it seems very unlikely to be true, you're probably right to reject it, but this is somewhat of a foregone conclusion.
Whether your data are too different from a normal distribution for your intended purposes is another question. The hypothesis tests you're using probably can't answer it for you by themselves: their outcomes will depend on your sample size, but won't take into account the sensitivity of whatever other analyses you have planned, among other reasons. You would probably get a better idea of how important this issue is by studying the sensitivity of your planned analyses to violations of the normality assumption; some really aren't very sensitive to the usual kinds of minor violations that are present in approximately normal data. You might get better sense of how non-normal your data are from a Q-Q plot, as @Glen_b suggested; knowing just how much non-normality is too much can still be difficult to tell from these plots though.
If you have time, or if your data are particularly problematic, you might want to look into robust alternatives to any other analyses you plan to run. This might even be one of the shorter routes to avoiding validity problems while ignoring the idiosyncrasies of your distribution, but bear in mind that those idiosyncrasies are sometimes interesting in their own right! Finally, if you're particularly serious about minding the sensitivity of any subsequent analyses to data that aren't from exactly normal distributions, you might want to consider doing some simulation testing of those analyses too.
(Full disclosure: for this answer, I borrowed and modified some text from a previous answer of mine.)
Edit: The null hypothesis of the two-sample Kolmogorov-Smirnov test states that the two samples are drawn from populations with the exact same distribution (or are both drawn from the same population, which is roughly equivalent). This would mean equal distributional parameters too...but to test normality (as you say you have), one of the distributions (your "reference distribution") would have to be a normal distribution. You'd need to run two such tests to compare each of two distributions to a normal distribution, or to each other and then one of them to a normal distribution. Testing twice inflates your overall false rejection rate, so you would want to adjust for multiple tests before rejecting those nulls (which you haven't anyway, so this is somewhat moot). Wikipedia mentions a multivariate version of this test, but it's relatively new, so I doubt you would've performed this version of the test unknowingly.

A: Your interpretation of the $p$-value suggests a fundamental misunderstanding about the nature of your hypothesis test.  A test cannot ever confirm that the null is true.  At best, it can only state that there is insufficient evidence to suggest that the alternative hypothesis is true.
If you get a "high" $p$-value using a goodness-of-fit test or a test of normality, that doesn't mean the evidence is strong that the data are drawn from the same distribution, because the $p$-value is a conditional probability: it is the probability of observing a result as extreme as that obtained, given $H_0$ is true.  So, at best, all your test has been able to show is that the data you observed does not suggest any reason to believe they are drawn from different distributions--this is not the same as saying they are in fact drawn from the same distribution.
This subtlety becomes all the more apparent when we consider that the nature of the tests you are using here tend to have very low power:  that is, even if the samples are drawn from different distributions, you would need a LOT of observations for the test to affirmatively conclude that they are.

A: Combining two normally distributed dataset into one, can result in a not-normally distributed dataset. This is best illustrated by an example:
(supposing you're working with R)
# creat two normal distributed datasets
x <- data.frame(var=rnorm(5000,2,1)) # 5000 observations, mean = 2, sd = 1
y <- data.frame(var=rnorm(5000,6,1)) # 5000 observations, mean = 6, sd = 1

When you make density plots the look like this for x and y respectively:

Both look rather normally distrubed. Now combine the two datasets.
# combining the datasets
z <- rbind(x,y)

When you make a density plot of z, you can see that it doesn't look like a normal distribution at all:


text:
Q: PIE CSS works in IE9 but not IE8 For this project, I am using Tomcat 7 and have configured it to serve htc with content type of text/x-component
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
    ...
    <mime-mapping>
            <extension>htc</extension>
            <mime-type>text/x-component</mime-type>
    </mime-mapping>
</web-app>

For some reason, it works in IE9 (gradients, drop shadows, rounded corners) but not in IE8, dont see any CSS3 in effect at all. In the developer console under styles/tracxe styles, I see behavior but I don't see anything like -pie-background for example. Is that a problem?
What might be the cause, it seems wierd that it works in IE9 but not IE8. I don't suppose I need different setup or anything like that? CSS of 1 element:
#masthead {
  background: #0E0E0E;
  background: #0e0e0e;
  background: -moz-linear-gradient(center top, #7d7d7d 0%, #0e0e0e 100%);
  background: -webkit-linear-gradient(top, #7d7d7d 0%, #0e0e0e 100%);
  background: -o-linear-gradient(top, #7d7d7d 0%, #0e0e0e 100%);
  background: -ms-linear-gradient(top, #7d7d7d 0%, #0e0e0e 100%);
  background: linear-gradient(top, #7d7d7d 0%, #0e0e0e 100%);
  -pie-background: linear-gradient(top, #7d7d7d 0%, #0e0e0e 100%);
  behavior: url(/owmw/web/css/PIE.htc);
  height: 35px;
  border: 1px solid #000000;
  color: #FFFFFF;
  position: relative;
  text-align: center;
  margin: 0px auto;
}

I am using IE10 in IE8 compatibility mode, does it matter?

A: I too faced the same issue and following was the reason for my problem:

*

*I used a wrong positioning for my DIV element.

*I was targeting the wrong path in behavior.

From your code, the problem seems to be in targeting the wrong path.
behavior: url(/owmw/web/css/PIE.htc);
FIX:
 Instead try to refer the PIE.htc file in css folder and make it look like behavior: url(PIE.htc);
or
use behavior: url(owmw/web/css/PIE.htc);
Check out behavior property.
I might be wrong, but this solved my issue.
Even I tried using behavior: url(../owmw/web/css/PIE.htc); but not worked.
From your comments, it seems you're using X-UA-Compatible as a fix and it works only through IE10 compatibility mode.
!--  Force IE to use the latest version of its rendering engine -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">

By telling IE to use the latest version of its rendering engine in your page.
Incase if your user opens in IE8 browser?  This will certainly fails.
You can check this in MSDN Library.
Hope you understand.


text:
Q: Facebook Like button for one facebook page of an app from it's own ios app I am looking for Like Button to be shown in my ios native app, users of that app have already connected to app via facebook account.
there are several questions related to Facebook Like Button on stackoverflow but those are not specific to authorized single facebook page of the app.
According to official doc of facebook, facebook pages can not be liked via built-in action o open graph api.
But want only one official facebook page of that app to be liked by user when he hits like button.  i don't want user to navigate away from the app or login again in web view to like facebook page.
is it possible to like app's facebook page without promoting user to log in again in webveiw?
Edit
Findings
1. https://stackoverflow.com/a/5837036/1632984
2. Comment by wallacer
"the general consensus does seem to be that you can't like a page on behalf of the user, however I just had an ios game like a page on my behalf. Extreme Road Trip successfully manages to get you to like their own page. I wish I'd paid more attention when I did it now..." – wallacer

A: This still can't be done directly using the graph api ( to the best of my knowledge ).  What you can do is open a webview to the page you want the user to like.  If you're rewarding their liking your app or something, when they close the webview (you'll have to provide a close button), you can use the graph api to check whether they like your app page.  As far as I can tell this is the best current solution - and seems to be the approach taken by mobile games.
That said, I haven't used Facebook SDK 3 yet, so there may be something in there that could help you.

A: It appears that Liking a page on behalf of a user is still impossible.  I've glanced over the iOS SDK Reference, and it doesn't seem like there is a built in mechanism to like anything.
However, in reading one of the other posts you linked to, and remembering that Facebook opened up the Like open graph action so app developers could allow their users to like content generated by their application...I found this link about built-in-actions (likes).
According to that link, you can post Like actions to your users by POSTing to https://graph.facebook.com/<user_id>/og.likes with the POST params for object (the open graph object URL you want to like on behalf of the user in this case your page's url. eg. www.facebook.com/yourpage) and access_token (obviously, for your user).
I'm not totally convinced that will work; though it is conceivable.  My second thought would be to create an Open Graph Object for your page, and have all your users like that.  Though, that is a little less ideal, as it removes the possibility of people finding your Page while they're on Facebook and would require you to put a lot more effort into getting likes for the Page via your website, application, etc.
I hope that helps a bit, good luck.


text:
Q: Updating sqlalchemy orm instance in flask session In my flask app, I store an instance of a user object in the session
session["user"] = user #Where user is an object

I found out that when updating the object stored in the session directly and commit, the changes are not reflected in the database.
However, I found that when updating the database object directly, the changes are reflected in the database while the session object is unchanged.
If I try a method like
user.username = username
user.password = password
db.commit() #I called my database session 'db', probably not a good idea but not the point
session["user"] = user

it throws:

sqlalchemy.orm.exc.DetachedInstanceError: Instance  is not bound to a Session; attribute refresh operation cannot proceed

What could be a possible solution to update the database correctly and reflect the changes to the flask session? Thanks in advance.

A: Try setting {'expire_on_commit': False} like,
db = SQLAlchemy(app, session_options={

    'expire_on_commit': False

})


text:
Q: how to disable chrome pdf viewer in selenium and it should auto download in the default downloads when any pdf occurs i m navigating a website where  i have a situation that when I m clicking on a button it should download the pdf....
I am using the latest version of chrome 60, selenium 3.4, chromedriver.
        HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
        chromePrefs.put("plugins.plugins_disabled", new String[] {"Chrome PDF Viewer"});
        chromePrefs.put("profile.default_content_settings.popups", 0);
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", chromePrefs);
        DesiredCapabilities cap = DesiredCapabilities.chrome();
        cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
        cap.setCapability(ChromeOptions.CAPABILITY, options);
        WebDriver driver = new ChromeDriver(cap);

I have also used the above code, but it doesn't work.

A: What worked for me was adding:
chromePrefs.put("plugins.always_open_pdf_externally", true);

I hope this helps

A: /*ChromeOptions options = new ChromeOptions();

/*use to disable the "Chrome is handled by automation script" pop up.*/

options.addArguments("disable-infobars");

/* use to start the Chrome browser as maximized.*/

options.addArguments("--start-maximized");

/* HashMap is use to disable the password saving pop up in Chrome browser.*/

Map<String, Object> prefs = new HashMap<String, Object>();

prefs.put("credentials_enable_service", false);

prefs.put("profile.password_manager_enabled", false);

options.setExperimentalOption("prefs", prefs);

/*Download File store in Download folder*/

prefs.put("profile.default_content_settings.popups", 0);

prefs.put("download.default_directory", downloadFilesPath);

prefs.put("plugins.always_open_pdf_externally", true);

HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();

options.setExperimentalOption("prefs", prefs);

options.addArguments("--test-type");

options.addArguments("--disable-extensions"); //to disable browser extension

DesiredCapabilities cap = DesiredCapabilities.chrome();

cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);

cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

cap.setCapability(ChromeOptions.CAPABILITY, options);

driver = new ChromeDriver(cap);*


text:
Q: Selecting a suitable model for time-series prediction problem I'm relatively new to machine learning and data science so please be understanding :)
I'm building a simple model for time-series prediction using feedworward neural network, my data is continous.
What I did until now is: built and trained few neural networks (differing in number of hidden layers and neurons) and compared their accuracy in predicting the values for my test set.
I'm wondering if there is any better way to determine the size of my neural network, instead of building so many models and simply comparing their MSE over the test set. How is it typically done?

A: A general rule of thumb is that if the complexity of your data is low, then you probably don't need a complex model for those data. Meaning, if your time series is a short series or not very noisy, it may be better to choose a simpler model than neural networks (very simple models often do pretty well in a lot of time series cases). Naive methods, moving averages, and linear models are far more common over neural networks in practice for simple forecasting tasks.
As for choosing the best neural network, what you have been doing is often called hyperparameter tuning or model tuning: finding the combination of parameters that give you the best model (like number of neurons and number of layers). The most straightforward method is to do what you're doing. Train a bunch of models and compare the metric. This is typically done by creating a test set or holdout set from your and testing the models on that. If you have 24 months of data, train your networks on the first 18 months and then test them to see how they perform on the last 6 months of unseen data.
For most deep learning tasks in practice, no more than 2 or 3 layers are really needed (most data in practice, especially time series, will need more complexity than that). But again, it always depends on the data and situation. See what works best.


text:
Q: Selecting rows within last 30 days I've got a select statement to get the orders of a reference, but now I need to restrict the results into a range od the last 30 days but i don't know how to do it.
SELECT
    *
FROM AFKO
WHERE AFKO~PLNBEZ = @reference
AND DATEDIFF( DAY, AFKO~GLTRP, @sy-datum ) >= -30
ORDER BY AFKO~GLTRP DESCENDING
INTO TABLE @it_afko.

I've readed that DATEDIFF can make the operatio but SAP says that the function is unknown.
I'm trying directly using the - operator:
SELECT
    *
FROM AFKO
WHERE AFKO~PLNBEZ = @reference
AND AFKO~GLTRP - @sy-datum >= -30
ORDER BY AFKO~GLTRP DESCENDING
INTO TABLE @it_afko.

but SAP says Only elementary arithmetic types can be used in arithmetic expressions. The type of AFKO~GLTRP is invalid
How can I get the difference?

A: You need to prepare calculated date before using it in opensql for old versions like below example.
DATA: lv_date   TYPE sy-datum,
      reference TYPE afko-plnbez,
      it_afko   TYPE TABLE OF afko.

CALL FUNCTION 'RP_CALC_DATE_IN_INTERVAL'
  EXPORTING
    date            = sy-datum
    days            = 30
    months          = 0
    signum          = '-'
    years           = 0
 IMPORTING
   calc_date       = lv_date.

SELECT *
  FROM afko
  INTO TABLE @it_afko
 WHERE afko~plnbez = @reference
   AND afko~gltrp >= @lv_date
 ORDER BY afko~gltrp DESCENDING.

A: Just declare a field and calculate the date accordingly:
DATA(lv_date_minus_30) = sy-datum - 30.

SELECT ...
       WHERE ... gltrp >= lv_date_minus_30


text:
Q: Update Value in Text File based on Value from another Dictionary in Loop Let say I have text file that store log data
2019-03-01 20:00:18; Value1; Value2
2019-03-01 20:00:23; Value1; Value2
2019-03-01 20:00:28; Value1; Value2

and I have Value in Dictionary
ID = Value1
StartDateTime = 2019-03-01 20:00:18
OffDateTime = 2019-03-01 20:00:27
Value = 9

I want to update Value1 in all record in text file which the duration is between StartDateTime and OffDateTime.
In this case, it will update the 1st and 2nd rows.
Right now I'm using this
if (textFileCurrentLineDateTime >= StartDateTime && textFileNextLineDateTime < OffDateTime)
{
   //this line need to update value
}

which is working fine if the duration of StartDateTime and OffDateTime is not more than 1 record.

A:    internal class Program
{
    private static Line CreateLineFromString(string line)
    {
        string[] array = line.Split(';');

        return new Line
        {
            DateTime = Convert.ToDateTime(array[0],CultureInfo.InvariantCulture),
            Value1 = array[1],
            Value2 = array[2]
        };
    }

    private static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        IEnumerable<Line> lines = ReadLines().ToList();

        var startDate = new DateTime(2019, 1, 1);
        var endDate = new DateTime(2019, 6, 30);

        foreach (Line line in lines.Where(line => line.DateTime >= startDate && line.DateTime <= endDate)) line.Value1 = "New Value";

        SaveLines(lines);
    }

    private static IEnumerable<Line> ReadLines()
    {
        using (var reader = new StreamReader("d:\\TextFile1.txt"))
        {
            string stringLine;
            while ((stringLine = reader.ReadLine()) != null)
                if (stringLine != string.Empty)
                    yield return CreateLineFromString(stringLine);

        }
    }

    private static void SaveLines(IEnumerable<Line> lines)
    {
        using (var writer = new StreamWriter("d:\\TextFile1.txt",false))
        {
            foreach (Line line in lines) writer.WriteLine(line.ToString());
        }
    }
}

public class Line
{
    public DateTime DateTime { get; set; }
    public string Value1 { get; set; }

    public string Value2 { get; set; }

    public override string ToString()
    {
        return $"{DateTime.ToString(CultureInfo.InvariantCulture)};{Value1};{Value2}";
    }
}


text:
Q: What is the best way to map windows drives using Python? What is the best way to map a network share to a windows drive using Python?
This share also requires a username and password.

A: Building off of @Anon's suggestion:
# Drive letter: M
# Shared drive path: \\shared\folder
# Username: user123
# Password: password
import subprocess

# Disconnect anything on M
subprocess.call(r'net use m: /del', shell=True)

# Connect to shared drive, use drive letter M
subprocess.call(r'net use m: \\shared\folder /user:user123 password', shell=True)

I prefer this simple approach, especially if all the information is static.

A: I don't have a server to test with here at home, but maybe you could simply use the standard library's subprocess module to execute the appropriate NET USE command?
Looking at NET HELP USE from a windows command prompt, looks like you should be able to enter both the password and user id in the net use command to map the drive.
A quick test in the interpreter of a bare net use command w/o the mapping stuff:
>>> import subprocess
>>> subprocess.check_call(['net', 'use'])
New connections will be remembered.

There are no entries in the list.

0
>>>

A: Assuming that you import necessary libraries, This was a part of an RPC server where the client requested the server to map a drive locally...
#Small function to check the availability of network resource.
def isAvailable(path):
    winCMD = 'IF EXIST ' + path + ' echo YES'
    cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
    return string.find(str(cmdOutPut), 'YES',)

#Small function to check if the mention location is a directory
def isDirectory(path):
    winCMD = 'dir ' + path + ' | FIND ".."'
    cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
    return string.find(str(cmdOutPut), 'DIR',)

================Check the white spaces from here, these were a part of a function============
def mapNetworkDrive(self, drive, networkPath, user, password):

    #Check for drive availability
    if isAvailable(drive) > -1:
        #Drive letter is already in use
        return -1

    #Check for network resource availability
    if isAvailable(networkPath) == -1:
        print "Path not accessible: ", networkPath
        #Network path is not reachable
        return -1

    #Prepare 'NET USE' commands
    winCMD1 = 'NET USE ' + drive + ' ' + networkPath
    winCMD2 = winCMD1 + ' ' + password + ' /User' + user

    print "winCMD1 = ", winCMD1
    print "winCMD2 = ", winCMD2
    #Execute 'NET USE' command with authentication
    winCMD = winCMD2
    cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
    print "Executed: ", winCMD
    if string.find(str(cmdOutPut), 'successfully',) == -1:
        print winCMD, " FAILED"
        winCMD = winCMD1
        #Execute 'NET USE' command without authentication, incase session already open
        cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
        print "Executed: ", winCMD
        if string.find(str(cmdOutPut), 'successfully',) == -1:
            print winCMD, " FAILED"
            return -1
        #Mapped on second try
        return 1
    #Mapped with first try
    return 1

def unmapNetworkDrive(self, drive):

    #Check if the drive is in use
    if isAvailable(drive) == -1:
        #Drive is not in use
        return -1

    #Prepare 'NET USE' command
    winCMD = 'net use ' + drive + ' /DELETE'
    cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
    if string.find(str(cmdOutPut), 'successfully',) == -1:
        #Could not UN-MAP, this might be a physical drive
        return -1
    #UN-MAP successful
    return 1

A: An alternative to subprocess:
import os

os.system("net use m: \\\\shared\folder")

Or
import os

cmd = "net use m: \\\\shared\folder"
os.system(cmd)

A: Okay, Here's another method...
This one was after going through win32wnet. Let me know what you think...
def mapDrive(drive, networkPath, user, password, force=0):
    print networkPath
    if (os.path.exists(drive)):
        print drive, " Drive in use, trying to unmap..."
        if force:
            try:
                win32wnet.WNetCancelConnection2(drive, 1, 1)
                print drive, "successfully unmapped..."
            except:
                print drive, "Unmap failed, This might not be a network drive..."
                return -1
        else:
            print "Non-forcing call. Will not unmap..."
            return -1
    else:
        print drive, " drive is free..."
    if (os.path.exists(networkPath)):
        print networkPath, " is found..."
        print "Trying to map ", networkPath, " on to ", drive, " ....."
        try:
            win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive, networkPath, None, user, password)
        except:
            print "Unexpected error..."
            return -1
        print "Mapping successful"
        return 1
    else:
        print "Network path unreachable..."
        return -1

And to unmap, just use....
def unmapDrive(drive, force=0):
    #Check if the drive is in use
    if (os.path.exists(drive)):
        print "drive in use, trying to unmap..."
        if force == 0:
            print "Executing un-forced call..."
        try:
            win32wnet.WNetCancelConnection2(drive, 1, force)
            print drive, "successfully unmapped..."
            return 1
        except:
            print "Unmap failed, try again..."
            return -1
    else:
        print drive, " Drive is already free..."
        return -1

A: I had trouble getting this line to work:
win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive, networkPath, None, user, password)
But was successful with this:
win32wnet.WNetAddConnection2(1, 'Z:', r'\UNCpath\share', None, 'login', 'password')

A: If you want to map the current login user, i think subprocess solve your problem. But is you want to control different mappings for different users, from a single master account. You could do this from the register of windows
The idea is to load the profile of a given user.
import win32api
import win32security
import win32profile
import win32netcon
import win32net
import win32netcon
import win32con

il = 'G'
m = '\\\\192.168.1.16\\my_share_folder'
usu = 'my_user'
cla = 'passwd'

#login the user
hUser = win32security.LogonUser(
       usu,
       None,
       cla,
       win32security.LOGON32_LOGON_NETWORK,
       win32security.LOGON32_PROVIDER_DEFAULT
    )

#load the profile
hReg = win32profile.LoadUserProfile (
             hUser,
             {"UserName" : usu}
            )

#alter the regedit entries of usu
win32api.RegCreateKey(hReg, "Network")
hkey = win32api.RegOpenKey(hReg, "Network\\", 0, win32con.KEY_ALL_ACCESS)
win32api.RegCreateKey(hkey, il)
hkey = win32api.RegOpenKey(hReg, "Network\\%s" % il, 0, win32con.KEY_ALL_ACCESS)
win32api.RegSetValueEx(hkey, "ConnectionType", 0, win32con.REG_DWORD, 1)
win32api.RegSetValueEx(hkey, "DeferFlags", 0, win32con.REG_DWORD, 4)
win32api.RegSetValueEx(hkey, "ProviderName", 0, win32con.REG_SZ, "Red de Microsoft Windows")
win32api.RegSetValueEx(hkey, "ProviderType", 0, win32con.REG_DWORD, 131072)
win32api.RegSetValueEx(hkey, "RemotePath", 0, win32con.REG_SZ, m)
win32api.RegSetValueEx(hkey, "UserName", 0, win32con.REG_DWORD, 0)


text:
Q: Imacros Login With Proxy I want to make a imacros script for firefox where I can load a list of emails (email:password) then login them to a website using a proxy list (ip:port). How do I do that?
So basically my process will be like this:
visit a website using proxy > login using email1 on the list > upvote a comment > logout
Next process will be the same but the proxy will change (from the list of proxy) and then pick email2 to login and do the same process.

A: For future reference, create a csv file with ip,port
SET !LOOP 2
SET !DATASOURCE C:\Temp\ips.csv
SET !DATASOURCE_LINE {{!LOOP}}
PROXY ADDRESS={{!COL1}}:{{!COL2}} BYPASS=*google.com*


text:
Q: How is raw SQL run against an Entity Framework Core context? I have used Entity Framework for a long time, but have an edge case where I need to use SQL.  I was wondering if I could use my existing Entity Framework Core context for this or not.  Here is what I have currently, but the queryResults variable contains a "-1" value, instead of a list of Students, after running it:
string tableName = "Students";
var queryResults = db.Database.ExecuteSqlRaw(@"SELECT * FROM {0}", tableName);

Any ideas?

*

*Entity Framework Core 3.1

*.NET Core 3.1

*Linq-to-SQL

A: It is possible; I just had to do this for a pet project.
You need to reference the Microsoft.EntityFrameworkCore.Relational NuGet.
ConsoleApp Example:
Program.cs
using System.Collections.Generic;

namespace EfDirectSql
{
    class Program
    {
        /*
         * written:  VS2019 .Net Core 3.1 Console App
         *
         * used nugets:
         *
         *      Microsoft.EntityFrameworkCore.SqlServer  3.1.0
         *      Microsoft.EntityFrameworkCore.Relational 3.1.0
         *
        */
        static void Main(string[] args)
        {
            // attention: supply your database server name
            ApplicationContext context = new ApplicationContext("?YOURSERVER?", "Master");

            //  note:   leveraging included extension methods for the dbContext class.
            object scalarResult = context.ExecuteScalar("SELECT COUNT(1) FROM Master.dbo.SysObjects");
            object nonQueryResult = context.ExecuteNonQuery("SELECT * FROM Master.dbo.SysObjects");  // likely your -1

            IEnumerable<SysObject> readerResult = context.ExecuteReader<SysObject>("SELECT * FROM Master.dbo.SysObjects");
        }
    }
}

ApplicationContext.cs
using Microsoft.EntityFrameworkCore;

namespace EfDirectSql
{
    public class ApplicationContext
    : DbContext
    {
        public ApplicationContext(string serverName, string catalogName)
        {
            this.ServerName = serverName;
            this.CatalogName = catalogName;
        }

        public readonly string ServerName;

        public readonly string CatalogName;

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer($"Data Source={this.ServerName};Initial Catalog={this.CatalogName};Integrated Security=true;");

            base.OnConfiguring(optionsBuilder);
        }
    }
}

DbContextExtensions.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;

namespace EfDirectSql
{
    public static class DbContextExtensions
    {
        public static object ExecuteScalar
        (
            this DbContext context,
            string sql
        )
        {
            IDbConnection connection = context.Database.GetDbConnection();
            IDbCommand command = connection.CreateCommand();
            object result = null;

            try
            {
                connection.Open();

                command.CommandText = sql;
                command.CommandType = CommandType.Text;

                result = command.ExecuteScalar();
            }
            finally
            {
                connection.Close();
            }

            return result;
        }

        public static int ExecuteNonQuery
        (
            this DbContext context,
            string sql
        )
        {
            IDbConnection connection = context.Database.GetDbConnection();
            IDbCommand command = connection.CreateCommand();

            int result;

            try
            {
                connection.Open();

                command.CommandText = sql;
                command.CommandType = CommandType.Text;

                result = command.ExecuteNonQuery();

                //  likely the -1
            }
            finally
            {
                connection.Close();
            }

            return result;
        }

        public static IEnumerable<TType> ExecuteReader<TType>
        (
            this DbContext context,
            string sql
        )
        where TType : class, new()
        {
            IDbConnection connection = context.Database.GetDbConnection();
            IDbCommand command = connection.CreateCommand();

            IEnumerable<TType> result = new List<TType>();

            try
            {
                connection.Open();

                command.CommandText = sql;
                command.CommandType = CommandType.Text;

                IDataReader reader = command.ExecuteReader(CommandBehavior.Default);

                result = Convert<TType>(reader);
            }
            finally
            {
                connection.Close();
            }

            return result;
        }

        private static IEnumerable<TType> Convert<TType>(IDataReader reader)
        where TType : class, new()
        {
            List<PropertyInfo> properties = typeof(TType)
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(p => p.CanWrite)
                .ToList();

            IList<TType> instances = new List<TType>();

            while (reader.Read())
            {
                TType instance = new TType();

                properties
                    .ForEach
                    (p =>
                        // for the purposes of the example, this works - could be outliers.
                        p.SetValue(instance, reader[p.Name] == DBNull.Value ? null : reader[p.Name])
                    );

                instances.Add(instance);
            }

            return instances;
        }
    }
}

SysObject.cs
namespace EfDirectSql
{
    //  shortened represenation of the MS-SQL sysobject table
    public class SysObject
    {
        public string name { get; set; }

        public int id { get; set; }

        public string xtype { get; set; }

        public int uid { get; set; }

        public int info { get; set; }

        public int status { get; set; }

        //  the rest are not needed for a demo.
    }
}

A: "I was wondering if I could use my existing Entity Framework Core context for this or not":
Yes you can use your existing databaseContext but you have to execute that query on your dbContext Entity see the example below:
var sqlCommand = $"SELECT * FROM Students";
var executeSQL = await _context.Students.FromSqlRaw(sqlCommand).ToListAsync();
return Ok(executeSQL);

Output:

Note: As you can see I am executing sqlCommand on Students dbContext this is valid. But using DbContext you cannot pass the
table name dynamically. You must need to define it explicitly.

Hope above steps guided you accordingly, You can have a look on official document for more details here
Update Using Ado.Net Connection:
     using (var connection = _context.Database.GetDbConnection())
            {
                connection.Open();
                var tableName = "Students";
                List<Student> _listStudent = new List<Student>();
                var command = connection.CreateCommand();
                command.CommandType = CommandType.Text;
                command.CommandText = string.Format("SELECT * FROM [{0}];", tableName);
                SqlDataReader reader = (SqlDataReader)command.ExecuteReader();
                while (reader.Read())
                {
                    var student = new Student(); // You have to bind dynamic property here based on your table entities
                    student.FirstName = reader["FirstName"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
                    student.LastName = reader["LastName"].ToString();
                    _listStudent.Add(student);

                }
                reader.Close();
                command.Dispose();
                connection.Close();

            }


text:
Q: Custom post type permalink returns 404 when set to private I have a custom post type that is configured to use a permalink structure prepended with the post type name. When using get_permalink(), the URL that is returned does not include the post type name. This is virtually identical to the scenario described in this question.
register_post_type('activity', [
  ...
  'public' => true,
  'rewrite' => [
    'slug' => 'activities',
    'with_front' => true,
  ],
]);

The permalink should take the form http://example.com/activities/the-activity-title, whereas get_permalink() returns http://example.com/the-activity-title.
Usually, WordPress does a pretty good job of guessing the correct post that should be displayed, and redirects the former to the latter. However, if the post is set to be private, that first URL results in a 404, even though the second URL is visible to the logged in user.

*

*Is it normal for get_permalink() to omit the post type slug from the URL it returns, resulting in a redirect? If not, what's causing it?

*If it is normal, how can I fix the 404 so it also redirects for logged in users?

The code I'm working with is all defined in a custom plugin. The register_post_type() snippet above is called by an init hook action, while the problem get_permalink() calls are in the plugins_loaded hook action.
The author of the question linked above states that his issues was caused by querying the permalink before the post type had been registered. Are the hooks I'm using in my code sufficient to avoid this cause?

A: My problem was indeed the same as in the question I linked, in that the get_permalink() call was happening before the post type was registered. I confirmed this when trying to write a work-around that used get_post_type_object(), which worked fine in functions.php but returned null when moved into my plugin.
By referring to the action reference page in the WordPress documentation (which, although it doesn't mention it, is sorted by the firing sequence of the actions) I could see that the action I was using to get the permalink, init is fired after the one I was using for registering the post type, plugins_loaded.
By moving the code using get_permalink() to the init action, I was able to fix the problem, and now the correct URLs are being returned, with the post type slug as expected.


text:
Q: Let $X,Y\sim U(0,1)$ and suppose $X$ and $Y$ Are independent. How to find explicitly the distribution of $Z=XY$ Using conditional expectation? I found this problem interesting but I don't see clearly how to solve it. Any hint or ideas on how to get this one started?

A: For example like that:
Take any $t \in (0,1)$. Then: $$\mathbb P(XY \le t) = \mathbb E [ \mathbb P(XY \le t|Y)] = \mathbb E[\mathbb P(Xy \le t)|_{y=Y}] = \mathbb E((\frac{t}{y}1_{\{y \ge t\}}+1_{\{y<t\}})|_{y=Y}) =
$$ $$= \mathbb E[\frac{t}{Y}1_{\{Y \ge t\}} + 1_{\{Y < t\}}] = t \int_{t}^1\frac{dy}{y}+\int_0^tdy=t-t\ln(t) $$
Which gives us $F_Z(t) = \begin{cases} 0 & t \le 0 \\ t-t\ln(t) & t \in(0,1) \\ 1 & t \ge 1\end{cases}$
Where $1_A$ means the indicator function and I used the fact that $\mathbb E[f(X,Y)|Y] = \mathbb E[f(X,y)]|_{y = Y}$ when $X,Y$ are independent and $f$ is such that $\mathbb E[|f(X,Y)|] < \infty$.


text:
Q: FabricJS - how to get current canvas object in loadFromJSON callback? I have several canvases and i need to block all object selection after loading them.
The problem is that loadFromJSON function is async and when it fires callback i variable is already last one so selection is being disabled only for last canvas.
var floorPlanS = ... -- array of json's
var canvas = [];
for(i=0;i<floorPlanS.length;i++) {
    jQuery('.floorPlans').append('
<canvas id="cFloorPlan'+i+'" width="800" height="516"></canvas>
');
    canvas[i] = new fabric.Canvas('cFloorPlan'+i);
    canvas[i].loadFromJSON(floorPlanS[i], function() {
        for(o=0;o<canvas[i]._objects.length;o++) {
            canvas[i]._objects[o].selectable = false;
        }
        canvas[i].renderAll();
    });
}

Is there any way to get canvas object inside loadFromJSON callback?


text:
Q: Check two specific exceptions in a match expression in Scala So I have a Try block in Scala
  def fromString(s: String): Option[Pitch] = scala.util.Try {
    val (pitchClassName, octaveName) = s.partition(c => !c.isDigit)
    val octave = if octaveName.nonEmpty then octaveName.toInt else 5
    Pitch(pitchClassIndex(pitchClassName) + octave  * 12)
  } match {
    case scala.util.Success(value) => Some(value)
    case scala.util.Failure(e) =>
    case scala.util.Failure(e) => throw e
  }

Now, I know there's a lot of code here that needs an explanation. For the purpose of this question though what is needed to know is this:
When creating a Pitch instance with a given note like "D#4" there can be two different exceptions that I want to specifically handle. The first is if the Map pitchClassIndex cannot find the given key pitchClassName, the second is if Pitch argument is outside of a given range.
pitchClassIndex:
val pitchClassIndex: Map[String, Int] = pitchClassNames.zipWithIndex.toMap

pitchClassNames:
val pitchClassNames: Vector[String] = Vector("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B")

So now we enter s: String and check whether it has a digit, if so split it into the tuple val (pitchClassName, octaveName) If s = "D#4" the tuple is now ("D#", "4")
val octave = 4 So now when creating our Pitch instance we'll get the value in pitchClassIndex: Map[String, Int] from the key pitchClassName: String = "D#" (Note here that if pitchClassName does not correspond to a value in pitchClassNames we'll get an exception) we'll then add octave: Int = 4 first multiplied by 12. Pitch(51)
Now the two first lines of Pitch looks like this:
case class Pitch(nbr: Int):
  assert((0 to 127) contains nbr, s"Error: nbr $nbr outside (0 to 127)")

So if arguments passed into Pitch is outside of the range (0 to 127) then throw and AssertionError with error message.
So right now we have two cases where it can throw an exception, the first is the assert in the beginning. The second is if pitchClassIndex(pitchClassName) takes a key that is not included in pitchClassNames: Vector[String] for example "K#". Then it will throw a NoSuchElementException with message: "key not found: K#"
Now as you can see I have an empty Failure case in the match expression where I test the Try statement, in this case I wanna check whether exception e is either the AssertionError or the NoSuchElementException and if it is one of these I wanna print some special text. The last case is for other exceptions. However I'm not quite sure how to test this? Is there something I can write inside the Failure like (e: ???) Any ideas?

A: You could add two case clauses for the two exceptions
case Failure(e: AssertionError) =>
  // do something
case Failure(e: NoSuchElementException) =>
  // do something else
case Failure(e) =>
  // goes here for other exceptions

If you want to combine them into just one case, you can no longer capture details in the variable e, so that may not be an option:
case Failure(_: AssertionError)
      | Failure(_: NoSuchElementException)     =>
   // cannot use `e` anymore

I suppose you could resort to .isInstanceOf
case Failure(e)
  if e.isInstanceOf[AssertionError] ||
     e.isInstanceOf[NoSuchElementException] =>
   // now `e` is Throwable in here


text:
Q: Convert CFStringRef to NSString I'm trying to retrieve some info from the main bundle:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    CFStringRef bundleVer = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey);
    NSString *appVersion = (__bridge NSString *)bundleVer;
}

I can get the CFStringRef (in debug I can see the proper value associate to the variable), but when I try to cast it to NSString my appVersion variable has "null" value (previously it was nil).
What am I doing wrong?
I'm using ARC.
EDIT: It seems that I have problem with my project, every NSString object can't be assigned even with a simple static assignment, the value of the test variable is (null)
NSString *test = @"";

A:   CFStringRef boundleVer = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey);
  NSString *appVersion = (__bridge NSString *)(boundleVer);

Its working fien on my side,, it is returning "2"

A: I would use that code instead of your current one to fetch the same information:

NSString *_shortVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];

or
NSString *_version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];

NOTE: I'm not sure which information you need eventually from the bundle.


text:
Q: Covariance of Two Quadratic Forms We're looking for the $\operatorname{Cov}\left[x^T A x, ~x^T B x\right]$ where $x$ is random variable and mean-centered, but not independent and $A$ and $B$ are symmetric matrices. The fundamental term to compute is $E\left[x^T A x x^T B x\right]$, a quartic form. For the normal case, you can find this in the matrix cookbook. Has anyone figured this out in general?

A: In the special case when $A$ and $B$ commute, they are simultaneously diagonalisable. If the spectrum of $A$ is made of the $\lambda_i$'s and the spectrum of $B$ of the $\xi_i$'s, then
$$\text{Cov}[x^T A x, ~x^T B x]=\sum_i \lambda_i\xi \text{var}(X_i^2)$$
if $X_i$ is the $i$-th coordinate of $X$ in the orthonormal basis.


text:
Q: Can't see close img or other attributes in LIghtbox2 I can't see close img or other attributes in Lightbox2.
It does open a larger image in Firefox but the only controls are the back arrow in browser.
When I make changes to CSS they do not show up.