Q: Error in google map loading I got this crash when Try to start any map activity ..
this is my gradle dependencies:
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.android.support:design:23.4.0'
compile 'com.facebook.android:facebook-android-sdk:4.5.0'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile 'cn.pedant.sweetalert:library:1.3'
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.android.support:support-v4:23.4.0'
compile 'com.android.support:multidex:1.0.0'
compile 'com.google.android.gms:play-services-location:8.4.0'
compile 'com.android.support:cardview-v7:23.4.0'
compile 'com.melnykov:floatingactionbutton:1.3.0'
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
compile 'com.google.code.gson:gson:2.7'

compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.google.android.gms:play-services-gcm:8.4.0'
compile 'com.onesignal:OneSignal:3.4.1'

compile 'com.wang.avi:library:1.0.3'
compile 'com.nineoldandroids:library:2.4.0'

}

this is logcat
11-05 10:00:19.603 10285-10285/com.wneet.white E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.wneet.white, PID: 10285
                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wneet.white/com.wneet.white.LoadingFirst}: java.lang.NullPointerException
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2578)
                                                                     at android.app.ActivityThread.access$900(ActivityThread.java:170)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:146)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5727)
                                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
                                                                     at dalvik.system.NativeStart.main(Native Method)
                                                                  Caused by: java.lang.NullPointerException
                                                                     at com.wneet.white.LoadingFirst.onCreate(LoadingFirst.java:88)
                                                                     at android.app.Activity.performCreate(Activity.java:5581)
                                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2483)
                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2578)
                                                                     at android.app.ActivityThread.access$900(ActivityThread.java:170)
                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:146)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:5727)
                                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
                                                                     at dalvik.system.NativeStart.main(Native Method)

thanx in advance.

A: Please check and make sure that you were able to set up your project with a compatible Google Play services SDK as discussed in Setting Up Google Play Services. If you haven't installed the Google Play services SDK yet, go get it now by following the guide to Adding SDK Packages.
Solutions given in this blog post and GitHub post might also give you possible workaround and might help.


Q: Is there an async-safe way to get the current thread ID in Linux? Is there any way to get the current thread ID from a signal handler in Linux? The getpid() method does what I want, but it is not clear if it is async-safe. man 7 signal provides a list of POSIX methods which are async safe, but this tells us nothing about non-POSIX methods such as getpid(). Presumably some of the many non-POSIX methods Linux has added are async safe, but I can't find the list.
There is also this answer which claims that all direct (not multiplexed) syscalls are async safe, but provides no evidence.
The goal is to build some kind of async-safe thread local storage, since __thread is not safe in the general case.
It doesn't have to be the "Linux thread ID" - any consistent thread ID would be fine. For example pthread_self would be great, but there is nothing claiming that is async safe. If we examine the implementation of that method in glibc Linux, it defers to the THREAD_SELF macro, which looks like:
# define THREAD_SELF \
({ struct pthread *__self;                                                  \
  asm ("movl %%gs:%c1,%0" : "=r" (__self)                                  \
          : "i" (offsetof (struct pthread, header.self)));                    \
  __self;})

It seems to be that this should be async-safe, if the thread in question was created under a regime that populates the gs resgister (perhaps all threads in Linux are, I'm not sure). Still looking at that header makes me pretty scared...

A: As mentioned in Async-signal-safe access to __thread variables from dlopen()ed libraries? you provided (emphasis is mine):

The __thread variables generally fit the bill (at least on Linux/x86),
  when the variable is in the main executable, or in a directly-linked DSO.
But when the DSO is dlopen()ed (and does not use initial-exec TLS model),
  the first access to TLS variable from a given thread triggers a call to
  malloc...

In other words, it only requires one access to that thread specific variable to bring it to life and make it available in signal handlers. E.g.:

*

*Block the signals you are interested in in the parent thread before creating a child thread.

*Unblock those interesting signals in the parent thread after the call to pthread_create.

*In the child thread initialize your __thread variable and unblock those interesting signals.

I normally store the write end of a unix pipe in that tread-specific variable and the signal handler writes the signal number into that pipe. The read end of the pipe is registered with select/epoll in that same thread, so that I can handle signals outside of the signal context. E.g.:
__thread int signal_pipe; // initialized at thread start

extern "C" void signal_handler(int signo, siginfo_t*, void*)
{
    unsigned char signo_byte = static_cast<unsigned>(signo); // truncate
    ::write(signal_pipe, &signo_byte, 1); // standard unix self pipe trick
}


Q: How Get xml content from xml Ip api and display it on webpage? I am using XML api of http://ip-api.com/docs/api:xml on my webpage to get information about a visiter visiting my website.
following is the successful xml document returned from their api :
<country>United Kingdom</country>
<countryCode>UK</countryCode>
<region>Bristol</region>
<ip>xx.xx.xx.x</ip>
<ISP>VodafoneM</ISP>

I want to show content of this xml document on my webpage using javascript, I know it can easily be done using a server side language like PHP, My php version is old and it's returning error for parsing an xml document. So I am looking for a client side solution.
Here is what I have tried so far :
<script>
xmlDoc=loadXMLDoc("http://ip-api.com/xml/xx.xx.xx.x");
x=xmlDoc.getElementsByTagName("country")[0]y=x.childNodes[0];
document.write(y.nodeValue);
</script>

It doesn't work, I am getiing a blank page.
How can I display the content of xml file on my webpage?
Please help me, I have been trying to solve this since morn

A: I have adapted your code as follows:
    //txt = loadXMLDoc("http://ip-api.com/xml/xx.xx.xx.x");
    var txt = '<country>United Kingdom</country><countryCode>UK</countryCode><region>Bristol</region><ip>xx.xx.xx.x</ip><ISP>VodafoneM</ISP>';
    txt = '<query>' + txt + '</query>';

    // Info: http://www.w3schools.com/xml/xml_parser.asp
    if (window.DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(txt, "text/xml");
    }
    else // Internet Explorer
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.loadXML(txt);
    }

    var x = xmlDoc.getElementsByTagName("country")[0];
    var y = x.childNodes[0];
    //document.write(y.nodeValue);
    document.getElementById("content").innerHTML = y.nodeValue;

Please check the result in jsfiddle.


Q: Trigger to enforce M-M relationship Suppose I have following schema :
DEPARTMENT (DepartmentName, BudgetCode, OfficeNumber, Phone)
EMPLOYEE (EmployeeNumber, FirstName, LastName, Department, Phone, Email)

The problem am facing is how to design a system of triggers to enforce the M-M relationship.Assuming that departments with only one employee can be deleted. Also I need to assign the last employee in a department to Human Resources.
I have no idea to enforce M-M relationship through trigger. Please help

A: Many-to-many conditions should not be enforced using a trigger. Many-to-many conditions are enforced by creating a junction table containing the keys in question, which are then foreign-keyed back to the respective parent tables.
If your intention is to allow many employees to be in a department, and to allow an employee to be a member of many departments, the junction table in question would look something like:
CREATE TABLE EMPLOYEES_DEPARTMENTS
  (DEPARTMENTNAME  VARCHAR2(99)
     CONSTRAINT EMPLOYEES_DEPARTMENTS_FK1
       REFERENCES DEPARTMENT.DEPARTMENTNAME,
   EMPLOYEENUMBER  NUMBER
     CONSTRAINT EMPLOYEES_DEPARTMENTS_FK2
       REFERENCES EMPLOYEE.EMPLOYEENUMBER);

This presumes that DEPARTMENT.DEPARTMENTNAME and EMPLOYEE.EMPLOYEENUMBER are either primary or unique keys on their respective tables. Get rid of the column EMPLOYEE.DEPARTMENT as it's no longer needed. Now by creating rows in the EMPLOYEES_DEPARTMENTS table you can relate multiple employees with a department, and you can relate a single employee with multiple departments.
The business logic requiring that only departments with one or fewer employees can be deleted should not be enforced in a trigger. Business logic should be performed by application code, NEVER by triggers. Putting business logic in triggers is a gatèw̢ay to unending debugging sessions. M̫̣̗̝̫͙a̳͕̮d̖̤̳̙̤n̳̻̖e͍̺̲̼̱̠͉ss̭̩̟ lies this way. Do not give in. Do not surrender. ̬̦B҉usi͢n̴es̡s logic ̶in triggers opens deep wounds in the fabric of the world, through which unholy beings of indeterminate form will cross the barrier between the spheres, carryi͞n̨g o̡f͠f t͢h̶e ̕screaming͡ souĺs o͜f͜ ̢th͜e̴ ̕dev́e̡lope͜r͝s to an et͞er͜n̸it̶y ́of͢ pain̶ ąn̨d͢ ̨to͟r̨ment͟. Do not, as I have said, put b́u͜siness͞ ̸log̛i͘ç ̵in͢ ͞trigge͠rs͞.̡ Be firm. Resist.You must resist. T̷he ̢Tem͟p͞t̶ati͝o̶n҉s͘ ̢m͘a̶y ́śing hymns̷ ́o͢f̴ ̸un͘hol̵y r̶ev͢ęla͠t̡ion̴ ͢buţ ́yo͠u̵ mus͝t ͝n͜͟o҉t̶͡ ̷l̸̛͟͢ì̧̢̨̕s̵̨̨͢t̵̀͞e̶͠n̶̴̵̢̕. Only by standing firmly in the door between the worlds and blocking out the hideous radiance cast off by bú̧s̷i̶̢n̵̕e̵ş͝s ́l̴ó̢g̛͟i̕c i͞n̕ t̵͜r͢͝i̸̢̛ģ͟ge̸̶͟r̶s͢͜, which perverts the very form of the world ąnd̴̀͝ ç͞a̧͞l̶l͟͜s̕͘͢ Z̶̴̤̬͈̤̬̲̳͇ͯ̊ͮ͐̒̆͂͠Â̮̘̗̻̞̬̱̆́̊̓͛́̚ͅL̛̦͕̤͎̮̦̄̌G̷͖̙̬͛̇ͬ̍͒̐̅O̡̳͖͎̯̯͍ͫ̽ͬ͒͂̀ i͜҉nt͝ǫ̴ ̸b̷͞è͢ì̕n̴g,̛̀͘ ̴c҉á̴͡ń ̀͠youŕ̨ ̧̨a̸p̡͡pl̷͠ic͞a̢t̡i͡҉ǫn̴ ̸s̶͜u̶͢ŗv̛í̴v́ȩ.͘͘ Resist. R͢͝e͢͟s̸͜ì̢̢s͠ţ̀. T̶̀h̨̀e̶r̀e͢͞ ̶i̶̡͢s̴ ͞͞n̵͝o̡ ́ẁ҉̴a̡y̕҉ ̶b́u̵̶̕t͜ ̨s͘͢t͘͠į͟l͘l̷̴ ̴͜͜ỳò͜u҉̨ ̨mus̸͞t̸̛͜ ̧rȩ̴s̢͢i͘͡st̸.̛̀͜ Your very śo͡u̧̧͘ļ͟͡ is compromised by p͝u͘͝t̢͜t͠i̸ņ̸̶g͟͡ ̵̶̛b̴҉u̶̡̨͜͞s̷̵̕͜͢i͝҉̕͢ǹe̡͞ś̸ş̕͜͡҉ ̴̨ĺ̵̡͟͜o̶̕g͠i͢͠c̕͝ ̕͞i̧͟͡n̡͘͟ ̶̕͞t̡͟҉̕r̸̢̧͡͞i̴̵̡͜g̵̴͟͝ģ̴̴̵ę̷̷͢r̢̢ś̸̨̨͜. T̀͜͢o̷͜ny̕ ͟͡T̨h̶̷̕e ̢͟P̛o̴̶n͡y shall rise from his dark stable and d͞ę̡v̶̢ó͟u̸̸r̴ ̷t͞h̀e̛ ̨͜s̷o̧͝u҉l̀ ͟͡o͢f̵͢ ̛t͢h̶̛e̢̢ ̡̀vi͜͞r̢̀g̶i̢n͞, and yet y͢ơú͝ m̷̧us͡t̡͠ ̛s̷̨t̸̨i̴̸l̶̡l ͝ǹot̵ ͞p̧u̵t̨ ͜b̀̕u̕s̨í̵ņ̀͠ȩs̵͟s ́͞l̛҉o̸g̨i̴͟c ͘͘i͘nt̛o͡ ͘͘͞t̶͞r̀̀i̕ǵ̛g̵̨͞e̸͠҉r̵͟ś! It is too much to bear, we cannot stand! Not even the children of light may put business logic into their triggers, for b̴̸̡̨u̧͜͝ş̶i̷̸̢̛҉ń̸́͟e̡s̷̵̡s̕͟ ̴҉͞l̷̡ǫ̷̶͡g҉̨̛į̸͘͠c̕͢ ̸̶̧͢͢i̸̡̛͘n͢͡ ̀͢͝t̷̷̛́ŗì̴̴̢g̶̷ǵ͠ȩ̀́r̸̵̢̕͜s̵͞ is the very es̵s̕͡ę̢n͞c̨e̢͟ ̴o̶̢͜f ͟d́ar͟͞͠k̡͞n̢̡es̵̛͡s̀̀͡ and dev͘ou͝͡r̨̡̀s͢͝ ҉͝t҉h̴e̡͘ l̫̬i̤͚ͅg̞̲͕̠͇̤̦̹h̩̙̘̭̰͎͉̮̳t͙̤̘̙! Yea, yea, the blank-faced ones rì͢s̨͘e from the f͟͢o̵͜͝n̶t̨ ̵of̸̡͠ ͝fl͟͞a̵̷҉me̶̵͢ and ca͝s͜t́ down the p̹̤̳̰r̮̦̥̥̞̫͑͂ͤ͑ͮ͒̑ï̄̌ͬͨe̦̗͔ͥͣ̆̾̂s̬̭̮̮̜ͭt̻̲̍sͫͣ̿ ̐͗̈ͤ͂ͦ̅f̭͚̪̻̣̩ͮ̒ṟͨ͌ͮ̅̓ỏ̝͓̝̣̟̼m̳͇̱̝͔͒ ͒ͫͧ͂̓̈̈́t̲̔̅̎͐h̺͈͍ͣͧ̿ē̪̼̪̻͉̪̙̐̽̎̉i̠͎̗͕̗̣̬̐̎͛r͓̫͌ͅ ̼a͑̈ͯͦ̍l̪͉͖̥͚̤͌ͨ͊ͦͤ̔t̫͎̹ͯa̼̻͍̳̟̤̬̓ͪ̀r̭͖̓ͬ̉̉ͤ͊ṡ̐ͪ̊̋̄̅! A̵̵̛v͝é͜ŕt̶ ̶y̸͝͠o̶u̧͘r̡ ̧e͞y҉e̕͝s,̀ ͡t̛h̛o̢͞ug̸̢h̵͟ ̡y̷o͢҉͢u̧͡ ̕͡c҉̵̶an͠n҉o̧͢t!̸̨͘ ͡H̵e̸͢͡ ̧̕c̶ơm̷̢̢e̶͞ś͢!̨́ ̷H̕ȩ ̵c̨̡͟o̴҉m̷͢es͠!̷͘͞ P̱̼̯̟͈h̝̳̞̖͚'͉̙͉̰̲̺n̪̦͕̗͜g͔̹̟̰̰̻̩l̬͈̹̥͕͖ͅụ̻̺̤̤̬̳i̸̯̬̝̻̣͚̫ ̰̹̞̞m͟g̷̝͓͉̤l̩͇̙͕w̪̦̰͔'̮̟̱̀n̢̜a̦f̘̫̤̘̬͓̞h̠͍͖̯ͅ ̩̠͓̯̘̫C̟̘̗̘͘ṭ͍͕ͅh̤ͅu̼̦̘̥ͅl҉̦hu̠̤̤̘͚ ̘̕R̶̟'̠͔̞̻͇l̩̺̗̻͖͓̕ͅy̛̖ȩ͉̭̖ẖ̡̥̼͈̖ w̟̫̮͇͔͞ͅg͈̘̱̻a̰͟h̘͙͖͢'̮̲̯͞n̤̜͍̯̳a͓͓̲̲g̱̻͈ĺ͍ ̷̣̞̲͖͍̲̺f̲ͅh͇͕̪̘͟t͔͈̙a͓͢g҉̳̜̲͚n͓͚͎̱̠̜!
Don't ask me how I know.
Best of luck.


Q: Ajax add to cart button in product detail page magento 2 I have check online demo of Magento 2 http://magento2-demo.nexcess.net/fusion-backpack.htmlwhen we click on add to cart it add product via AJAX but i have Set up demo on localhost it don't to add Product to cart via AJAX.
Can anyone tell where is settings to enable ajax on add to cart ?

A: You have to just override addtocart.phtml file
app/design/frontend/Packagename/themename/Magento_Catalog/templates/product/view/addtocart.phtml

Replace "bindSubmit": false to "bindSubmit": true

to

Remove cache and check its in detail page.

A:
Add method to your class

public function __construct(
    ......................................................
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Catalog\Block\Product\ListProduct $listProductBlock,
    ......................................................
) {
    ......................................................
    $this->productFactory = $productFactory;
    $this->listProductBlock = $listProductBlock;
    ......................................................
}

public function getProductData($id)
{
    $collection = $this->productFactory->create()->load($id);
    return $collection;
}

public function getAddToCartPostParams($product)
{
    return $this->listProductBlock->getAddToCartPostParams($product);
}

Add into your phtml file

<?php
$_product = $block->getProductData(11);
?>
<?php $postParams = $block->getAddToCartPostParams($_product); ?>
<form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post">
    <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
    <input type="hidden" name="<?php /* @escapeNotVerified */ echo "uenc"; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data']['uenc']; ?>">
    <?php echo $block->getBlockHtml('formkey')?>
    <button type="submit"
            title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
            class="action tocart primary">
        <?php /* @escapeNotVerified */ echo __('Add to Cart') ?>
    </button>
</form>


Q: Remove server from react-boilerplate How should one do to remove server folder from react-boilerplate? Question is also asked here by another person https://github.com/react-boilerplate/react-boilerplate/issues/2110.

A: Removing just server folder will not work because the webpack dev configuration is utilising it for hot reload as well as your npm start command starts express server from this folder.
If you want to remove server folder completely and still want the application to be working as it was like hot reloading etc, follow the below steps. We will require webpack dev server in that case:

*

*Remove ./server folder manually.

*Install webpack-dev-server and react-hot-loader as dev dependencies.

*In  your ./internals/webpack/webpack.dev.babel.js, do the following modifications:

*

*Change entry to this:
entry: [
      require.resolve('react-app-polyfill/ie11'),
      'react-hot-loader/patch',
      `webpack-dev-server/client?http://localhost:3000/`,
      'webpack/hot/only-dev-server',
      path.join(process.cwd(), 'app/app.js'), // Start with js/app.js
],

*Add publicPath in output:
output: {
    filename: '[name].js',
    chunkFilename: '[name].chunk.js',
    publicPath: `http://localhost:3000/`,
},

*Add webpack dev server config property in the same file:
devServer: {
   port: 3000,
   publicPath: `http://localhost:3000/`,
   compress: true,
   noInfo: false,
   stats: 'errors-only',
   inline: true,
   lazy: false,
   hot: true,
   open: true,
   overlay: true,
   headers: { 'Access-Control-Allow-Origin': '*' },
   contentBase: path.join(__dirname, '..', '..', 'app', 'build'),
   watchOptions: {
       aggregateTimeout: 300,
       ignored: /node_modules/,
       poll: 100,
   },
   historyApiFallback: {
       verbose: true,
       disableDotRule: false,
   },
},

*In ./internals/webpack/webpack.base.babel.js, add the line:
devServer: options.devServer,

And finally, modify your start script in package.json as below:
"start": "cross-env NODE_ENV=development node --trace-warnings ./node_modules/webpack-dev-server/bin/webpack-dev-server --color --config internals/webpack/webpack.dev.babel.js",

And you are good to go!!

A: Just remove with rm -rf ./server if you feel harassed :)


Q: Case Statement Block Level Declaration Space in C# Is there a reason I am missing that a block within a case statement isn't considered a block level declaration space?
I keep getting an error (variable has already been declared) when I try
case x:
  var someVariable = 42;
break;
case y:
   var someVariable = 40;
break;

but I can do
case x:
   try{var someVariable = 42;}catch{}
break;
case y:
    try{var someVariable = 40;}catch{}
break;

If C# allowed fall through statements, that would make sense, but it doesn't, and I can't think of a scenario where you can declare a variable in a case statement and use it outside of that block.

A: You could also do:
case x:
  {var someVariable = 42;}
break;
case y:
   {var someVariable = 40;}
break;

Essentially the braces create the lexical scope, so without the braces, someVariable is loaded into the symbol table twice. I believe this choice is likely made simply to avoid confusion, and possibly to avoid adding complexity to the building of the symbol table.

A: UPDATE: This question was used as the inspiration for this blog post; see it for further details.
http://ericlippert.com/2009/08/13/four-switch-oddities/
Thanks for the interesting question.

There are a number of confusions and mis-statements in the various other answers, none of which actually explain why this is illegal. I shall attempt to be definitive.
First off, to be strictly correct, "scope" is the wrong word to use to describe the problem. Coincidentally, I wrote a blog post last week about this exact mis-use of "scope"; that will be published after my series on iterator blocks, which will run throughout July.
The correct term to use is "declaration space".  A declaration space is a region of code in which no two different things may be declared to have the same name.  The scenario described here is symptomatic of the fact that a switch section does not define a declaration space, though a switch block does.  Since the OP's two declarations are in the same declaration space and have the same name, they are illegal.
(Yes, the switch block also defines a scope but that fact is not relevant to the question because the question is about the legality of a declaration, not the semantics of an identifier lookup.)
A reasonable question is "why is this not legal?"  A reasonable answer is "well, why should it be"?  You can have it one of two ways.  Either this is legal:
switch(y)
{
case 1:  int x = 123; ... break;
case 2:  int x = 456; ... break;
}

or this is legal:
switch(y)
{
case 1:  int x = 123; ... break;
case 2:  x = 456; ... break;
}

but you can't have it both ways. The designers of C# chose the second way as seeming to be the more natural way to do it.
This decision was made on July 7th, 1999, just shy of ten years ago. The comments in the notes from that day are extremely brief, simply stating "A switch-case does not create its own declaration space" and then giving some sample code that shows what works and what does not.
To find out more about what was in the designers minds on this particular day, I'd have to bug a lot of people about what they were thinking ten years ago -- and bug them about what is ultimately a trivial issue; I'm not going to do that.
In short, there is no particularly compelling reason to choose one way or the other; both have merits. The language design team chose one way because they had to pick one; the one they picked seems reasonable to me.

A: Because cases aren't blocks, there are no curly braces denoting the scope. Cases are, for lack of a better word, like labels.
You're better off declaring the variable outside the switch() statement and using it thereafter. Of course, in that scenario, you won't be able to use the var keyword, because the compiler won't know what type to initialize.

A: Ah - you don't have fall through, but you can use goto to jump to another labelled case block.  Therefore the blocks have to be within the same scope.

A: As of C# 8.0 you can now do this with switch expressions

you use the switch expression to evaluate a single expression from a list of candidate expressions based on a pattern match with an input expression

var someVariable = caseSwitch switch {
    case x => 42,
    case y => 40,
    _ => throw new Exception("This is how to declare default")
};

A: You could just declare the variable outside the scope of the switch statement.
var someVariable;

switch();
case x:
someVariable = 42;
break;
case y:
someVariable = 40;
break;


Q: String [] to char Array using java I have a weird situation, am working on a Data base project that only gives me a string [] s = ["A","B","C","D"] and I wanted to change from string array to Char Array since it's a char but i dunno what function to use to convert the entire array to char with one line of code.
char ch = [ 'A', 'B', 'C'] --> this is what am looking to get
My plan B  is to loop the entire string and convert to char one by one. but am avoiding that one.
any help I will highly appreciate

A: this might help you.
Would be better if we could use Stream<char>, but, this does not work, so, we need to use the wrapper class.
Since you want the first index, you can use 0.
String.charAt(index) returns a char primitive, so, it will use less memory than a String.substring(...) that returns a new String.
    final String[] array = {"A", "B", "C", "D"};
    final Character [] char_array = Arrays.stream(array)
            .map(s -> s.charAt(0))
            .toArray(Character[]::new);

    for(char a: char_array) {
        System.out.println(a);
    }

A: You can use streams, this will return a char [] array.
 Arrays.stream(S).map(s -> s.substring(0,1)).collect(Collectors.joining()).toCharArray();

Full code
String [] S = { "A", "B", "C"} ;

      char [] ch =Arrays.stream(S).map(s -> s.substring(0,1))
.collect(Collectors.joining()).toCharArray();

       for(int i=0;i<ch.length;i++){
           System.out.println(ch[i]);
       }

For better use, I suggest making a method that implements this stream and returns a char []
public char [] convertToChar(String [] yourArray){

       return Arrays.stream(youArray).map(s -> s.substring(0,1)).collect(Collectors.joining()).toCharArray();
    }


Q: AWS NEXRAD and pyart grid_from_radars Can someone take a look at this code and help me debug?
import numpy as np
import pyart

 radar_data=[]
 RADAR_FILE = r'C:\Sourcecode\NEXRAD\KTLX20150506_235157_V06.gz'

 radar = pyart.io.read_nexrad_archive(RADAR_FILE)

 radar.fields['reflectivity']['data'][:, -10:] = np.ma.masked

gatefilter = pyart.filters.GateFilter(radar)
gatefilter.exclude_transition()
gatefilter.exclude_masked('reflectivity')

 grid = pyart.map.grid_from_radars(
(radar,), gatefilters=(gatefilter, ),
grid_shape=(1, 9720, 1832),
grid_limits=((2000, 2000), (-123000.0, 123000.0), (-123000.0, 123000.0)),
fields=['reflectivity'])

It fails to make the grid with the error:  "numpy.core._exceptions.MemoryError: Unable to allocate array with shape (9720, 1832) and data type float64"
I think my grid_shape is off somehow...  THanks

A: Solved.  Installed 32-bit Python by mistake, should be 64-bit for this.


Q: reading config file in python with ConfigParser I have used configparser to read configurations in my python written program . I am reading file from s3 for now , but my requirement is to configurations defined in the program itself rather than from any other external source .
code written is below:
config = configparser.ConfigParser()
config.readfp(open(s3:path\config))

config file format :
config.ini
[section1]
var1=Y
var2=Y
var3=['col1','col2']

I am reading above file that is located in s3 , but instead of reading from s3 I want to read from program in itself . what needs to be done in order to achieve this ?
above code is written in pyspark program , I am passing config file with spark submit command but to read config file i need to provide path and this is not desirable .
spark submit in aws emr :
'Args': ['spark-submit','--deploy-mode', 'cluster','--master', 'yarn','--executor-memory', conf['emr_step_executor_memory'],'--executor-cores',  conf['emr_step_executor_cores'],'--conf','spark.yarn.submit.waitAppCompletion=true','--conf','spark.rpc.message.maxSize=1024',f'{s3_path}/file1.py',  '--py-files',f'{s3_path}/file2.py',f'{s3_path}/file3.py',f'{s3_path}/file4.py','--files', f'{s3_path}/config ]

because of config.readfp(open(s3:path\config)) line i need to provide s3 path , that is not desirable options are either pass config file from spark submit and make available to every other python files those are reading configs or read configuration inside of program itself .

A: you can do something like this:
parser = configparser.ConfigParser()
parser.read_dict({'section1': {'key1': 'value1',
                                'key2': 'value2',
                                'key3': 'value3'},
                   'section2': {'keyA': 'valueA',
                                'keyB': 'valueB',
                                'keyC': 'valueC'},
                   'section3': {'foo': 'x',
                                'bar': 'y',
                                'baz': 'z'}})

Check this for detailed info as well as some other alternative way to achieve this.
Sample retrieval
parser["section1"]["key1"]
'value1'


Q: Reporting shadow prices from SimplexSolver I'm using the SimplexSolver class directly to solve a linear program, with AddRow, AddVariable and SetCoefficient. This works quite well.
We need to come up with shadow prices now, and I don't see any way to access either the shadow prices or the simplex matrix.
If I set SimpleSolverParams.GetSensitivityReport to true, casting the return of SimplexSolver.GetReport to ILinearSolverSensitivityReport may be the key here. Checking it out.

A: It looks like ILinearSolverSensitivityReport.GetDualValue returns the shadow price.
Hopefully this saves someone else a merry chase through dotPeek. :-)


Q: Display NSDates in terms of week Scenario:
I have an expense tracking iOS Application and I am storing expenses from a expense detail view controller into a table view (with fetched results controller) that shows the list of expenses along with the category and amount and date. I do have a date attribute in my entity "Money" which is a parent entity for either an expense or an income.
Question:
What I want is to basically categorize my expenses for a given week, a month, or year and display it as the section header title for example : (Oct 1- Oct 7, 2012) and it shows expenses amount and related stuff according to that particular week. Two buttons are provided in that view, if I would press the right button, it will increment the week by a week (Oct 1- Oct 7, 2012 now shows Oct8 - Oct 15, 2012) and similarly the left button would decrement the week by a week.
How would I accomplish that? I am trying the following code - doesn't work.
- (void)weekCalculation
{
   NSDate *today = [NSDate date];  // present date (current date)

   NSCalendar* calendar = [NSCalendar currentCalendar];
   NSDateComponents* comps = [calendar components:NSYearForWeekOfYearCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:today];

   [comps setWeekday:1]; // 1: Sunday
   firstDateOfTheWeek = [[calendar dateFromComponents:comps] retain];
   [comps setWeekday:7]; // 7: Saturday
   lastDateOfTheWeek = [[calendar dateFromComponents:comps] retain];

   NSLog(@" first date of week =%@", firstDateOfTheWeek);
   NSLog(@" last date of week =%@", lastDateOfTheWeek);

   firstDateOfWeek = [dateFormatter stringFromDate:firstDateOfTheWeek];
   lastDateOfWeek = [dateFormatter stringFromDate:lastDateOfTheWeek];

}

Code for incrementing date -
- (IBAction)showNextDates:(id)sender
{
   int addDaysCount = 7;

   NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
   [dateComponents setDay:addDaysCount];

   NSDate *newDate1 = [[NSCalendar currentCalendar]
                    dateByAddingComponents:dateComponents
                    toDate:firstDateOfTheWeek options:0];

   NSDate *newDate2 = [[NSCalendar currentCalendar]
                    dateByAddingComponents:dateComponents
                    toDate:lastDateOfTheWeek options:0];

   NSLog(@" new dates =%@ %@", newDate1, newDate2);

}

Suppose the week shows like this (Nov4, 2012 - Nov10, 2012) and I press the increment button, I see in the console, date changes to Nov11,2012 and Nov.17, 2012 which is right but if I press the increment button again, it shows the same date again (Nov 11, 2012 and Nov.17, 2012).
Please help me out here.

A: Declare currentDate as an @property in your class. And try this.
@property(nonatomic, retain) NSDate *currentDate;

Initially set
self.currentDate = [NSDate date];

before calling this method.
- (void)weekCalculation
{
   NSCalendar* calendar = [NSCalendar currentCalendar];
   NSDateComponents* comps = [calendar components:NSYearForWeekOfYearCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:self.currentDate];

   [comps setWeekday:1]; // 1: Sunday
   firstDateOfTheWeek = [[calendar dateFromComponents:comps] retain];
   [comps setWeekday:7]; // 7: Saturday
   lastDateOfTheWeek = [[calendar dateFromComponents:comps] retain];

   NSLog(@" first date of week =%@", firstDateOfTheWeek);
   NSLog(@" last date of week =%@", lastDateOfTheWeek);

   firstDateOfWeek = [dateFormatter stringFromDate:firstDateOfTheWeek];
   lastDateOfWeek = [dateFormatter stringFromDate:lastDateOfTheWeek];

}

Once the view is loaded self.currentDate value should be updated from showNextDates. Make sure it is not getting reset anywhere else.
- (IBAction)showNextDates:(id)sender
{
   int addDaysCount = 7;

   NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
   [dateComponents setDay:addDaysCount];

   NSDate *newDate1 = [[NSCalendar currentCalendar]
                    dateByAddingComponents:dateComponents
                    toDate:firstDateOfTheWeek options:0];

   NSDate *newDate2 = [[NSCalendar currentCalendar]
                    dateByAddingComponents:dateComponents
                    toDate:lastDateOfTheWeek options:0];

   NSLog(@" new dates =%@ %@", newDate1, newDate2);

   self.currentDate = newDate1;

}

A: I had needed similar thing in one of my old projects and achieved it via the code below. It sets this weeks date to an NSDate variable and adds/removes 7 days from day component in each button click. Here is the code:
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDate *date = [NSDate date];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSWeekdayCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)  fromDate:date ];
//
[components setDay:([components day] - ([components weekday] )+2)];
self.currentDate = [calendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"dd.MM.yyyy HH:mm:ss";
self.datelabel.text = [formatter stringFromDate:self.currentDate];

The code above calculates this week start and sets it to currentDate variable. I Have two UIButtons with UIActions named prevClick and nextClick which calls the method that sets the next or previous weekstart:
- (IBAction)prevClick:(id)sender {
[self addRemoveWeek:NO];

}
-(void)addRemoveWeek:(BOOL)add{
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit|NSWeekdayCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)  fromDate:self.currentDate ];
components.day = add?components.day+7:components.day-7;
self.currentDate = [calendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"dd.MM.yyyy HH:mm:ss";
self.datelabel.text = [formatter stringFromDate:self.currentDate];

}
- (IBAction)nextClk:(id)sender {
[self addRemoveWeek: YES];

}


Q: Getting a linechart entry label MPAndroidChart I have a line chart with entries that the user can click on via line chart.setOnChartValueSelectedListener. Is there a way that I can programmatically get the label of whichever entry is clicked? Or is there some other way of achieving this in my code?
private void chartAreaClickResponse(LineChart lineChart) {
    lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
        @Override
        public void onValueSelected(Entry e, Highlight h) {
          //get the label of the entry here

        }

        @Override
        public void onNothingSelected() {

        }
    });
}

A: I figured it out, in case anyone needs to know this in the future.Simply add the following line under "onValueSelected":
    @Override
    public void onValueSelected(Entry e, Highlight h) {
      String label = dataSets.get(h.getDataSetIndex()).getLabel(); //add this
    }

In this case, dataSets is the "ILineDataSet" used to populate the line chart


Q: equivalent of __FUNCTION__ of C lanauage in Java For debug purpose, I want to print out current executing function name in Java. If it were C, I would just do printf("%s \n" ,__FUNCITON__).

A: new Exception().getStackTrace()[0].getMethodName();

A: I'd use one of the logging frameworks (logback with slf4j is probably the best one at the moment, but log4j should suffice), then you can specify a layout that will print the method name logback layout documentation here


Q: Google Script - get data from Gmail into Sheet I have been looking around here on SO and on Google, but I cannot find anything that is working.
So when I am running my code below, I am getting the result on the image.
I want to extract data from the newest/most recent thread in mails that have a specific label.
However, in my Gmail, I only have the 3 mails under "Action"-label that I have highlighted in bold.
The other mails have been deleted, hence, they are in trash, but do still have the "Action" label.
I want to only show the mails that I have "Action"-label on - meaning that I only want the newest thread time/date, subject line as well as the ID, so I can create a link to that mail.

function myFunction() {

  var ss = SpreadsheetApp.getActiveSheet();

  var query = "label:action -label:trash -label:action-done -from:me";

  var threads = GmailApp.search(query);

    for (var i = 0; i < threads.length; i++)
    {
      var messages = threads[i].getMessages();

      for (var j = 0; j < messages.length; j++)
      {
        var mId = messages[j].getId()
        var from = messages[j].getFrom();
        var cc = messages[j].getCc();
        var time = messages[j].getDate()
        var sub = messages[j].getSubject();

        ss.appendRow([from, cc, time, sub, 'https://mail.google.com/mail/u/0/#inbox/'+mId])
      }
    }
  }
}

A: So I managed to solve it, by finding the max index in the array.
I have commented the code, so it can help others. Thanks, all.
function myFunction() {
  // Use sheet
  var ss = SpreadsheetApp.getActiveSheet();
  // Gmail query
  var query = "label:support -label:trash -label:support-done -from:me";
  // Search in Gmail, bind to array
  var threads = GmailApp.search(query);
  // Loop through query results
  for (var i = 0; i < threads.length; i++)
  {
    // Get messages in thread, add to array
    var messages = threads[i].getMessages();

    // Used to find max index in array
    var max = messages[0];
    var maxIndex = 0;

    // Loop through array to find maxIndexD = most recent mail
    for (var j = 0; j < messages.length; j++) {
      if (messages[j] > max) {
        maxIndex = j;
        max = messages[j];
      }
    }
    // Find data
    var mId = messages[maxIndex].getId() // ID used to create mail link
    var from = messages[maxIndex].getFrom();
    var cc = messages[maxIndex].getCc();
    var time = threads[i].getLastMessageDate()
    var sub = messages[maxIndex].getSubject();
    // Write data to sheet
    ss.appendRow([from, cc, time, sub, 'https://mail.google.com/mail/u/0/#inbox/'+mId])
  }
}

A: What do you mean by recent?
How about adding newer_than:3d to the search?
You can test the search in your own Gmail account and when it's doing what you want then just paste it into the query.


Q: Proving the binomial coefficient identity $\binom{~s + t~ }{s} = \prod_{i=1}^s \prod_{j=1}^t \frac{i + j}{i + j - 1}$ I tried expanding the factorial, but I do not know how to finish the proof.
\begin{eqnarray*}
\binom{~s + t~ }{s} & = &  \frac{(s+t)!}{s! ~ t!}\\
& = & \frac{(s+t)(s+t-1) \cdots (t+2)(t+1)}{s!} \\
& = & \prod_{i=1}^s \frac{t + i}{i} \\
\end{eqnarray*}
How do I get
$$ \prod_{i=1}^s \frac{t + i}{i} = \prod_{i=1}^s \prod_{j=1}^t \frac{i + j}{i + j - 1}$$?

A: Hint: Telescopic product. Write a few terms out for $j=1,2,3..$:
$$\frac{i+1}i\cdot\frac{i+2}{i+1}\cdots\frac{i+t}{i+t-1} = \frac{i+t}i$$

A: $$\binom{~s + t~ - 1}{s - 1} + \binom{~s + t~ - 1}{s}$$
$$\prod_{i=1}^{s-1} \prod_{j=1}^{t} \frac{i + j}{i + j - 1} + \prod_{i=1}^s \prod_{j=1}^{t-1} \frac{i + j}{i + j - 1}$$
$$\left(\prod_{j=1}^{t} \frac{s + j - 1}{s + j} + \prod_{i=1}^s \frac{i + t - 1}{i + t}\right) \prod_{j=1}^{t} \prod_{i=1}^s \frac{i + j}{i + j - 1}$$
$$\left(\prod_{j=1}^{t} \frac{s + j - 1}{s + j} + \prod_{i=1}^s \frac{i + t - 1}{i + t}\right) \binom{s+t}{s}$$
$$\left(\frac{s}{s + t} + \frac{t}{s + t}\right) \binom{s+t}{s}$$
$$\binom{s+t}{s}$$


Q: How to create gifs with images in Python Are there any APIs or libraries I can use to create a .gif out of .jpgs and .pngs? I'm looking for one that will work with Python 3.

A: Try googling, there are a lot of answers for this question. Here are the top three when I looked
Programmatically generate video or animated GIF in Python?
Generating an animated GIF in Python
https://sukhbinder.wordpress.com/2014/03/19/gif-animation-in-python-in-3-steps/

A: Here is something that I wrote a while ago.  I couldn't find anything better when I wrote this in the last six months.  Hopefully this can get you started.  It uses ImageMagick found here!
import os, sys
import glob
dataDir = 'directory of image files' #must contain only image files
#change directory gif directory
os.chdir(dataDir)

#Create txt file for gif command
fileList = glob.glob('*') #star grabs everything, can change to *.png for only png files
fileList.sort()
#writes txt file
file = open('blob_fileList.txt', 'w')
for item in fileList:
    file.write("%s\n" % item)

file.close()

#verifies correct convert command is being used, then converts gif and png to new gif
os.system('SETLOCAL EnableDelayedExpansion')
os.system('SET IMCONV="C:\Program Files\ImageMagick-6.9.1-Q16\Convert"')
# The following line is where you can set delay of images (100)
os.system('%IMCONV% -delay 100 @fileList.txt theblob.gif')

New convert call
For whatever reason (I didn't look at differences), I no longer needed the set local and set command lines in the code.  I needed it before because the convert command was not being used even with path set.  When you use the new 7.. release of image magick.  See new line of code to replace last three lines.  Be sure to check box that ask to download legacy commands e.g convert when installing.  Everything was converted to a single magick command, but I didnt want to relearn the new conventions.
os.system('convert -delay 50 @fileList.txt animated.gif')


Q: Can the new Skylanders SWAP Force figures be used on the Spyro's Adventure portal? We have the older portal from Spyro's Adventure.  Can the new Skylanders: SWAP Force
figures be used on this portal?

A: Unfortunately, it looks like the answer is no.  From Activision Support:

However, you cannot use the Portal of Power from previous games with Skylanders SWAP Force.


Q: Is it possible to connect Dialogflow (Api.ai) with Slack so that humans can monitor and possibly even intervene or add to the conversation via Slack? I know Dialogflow (Api.ai) can be a bot in Slack.  But what about monitoring the conversation and possibly manually intervene in the conversation?  If possible, what would be the general direction to implement this?

A: So Slack has Open APIs for interacting with the Slack App. Here
Since you want to monitor the conversations so Events APIs and Conversations APIs would help you to notify as well as capture the conversations.

conversations.history will help you to fetch the messages within public or private channels.
Since you want to intervene in the conversation then I suggest using chatbot, which will provide a suitable way to intervene and respond to some particular events. Bot Users

A: Dialogflow has an sample on how to do this: https://github.com/dialogflow/agent-human-handoff-nodejs
You'll have to build you own front end for the human to override the response and call the Dialogflow query API to integrate:
Slack <--> Front end w/human override <--> Dialogflow's query API <--> Dialogflow Agent

A: Yes, it's possible. Just login to DialogFlow with your Google credentials, then on the left sidebar you can see the Integrations Tab. Click on it. You will find a bunch of different integrations for line, telegram, Twilio, kik, Viber, Skype and a lot more.
Click on Slack. It will ask you for some details for connecting with endpoints such as client ID, token, client secret. You can get it from the Slack API. You can also check the Slack API integration link here. After everything is properly set up, click the "Test in Slack" button in the DialogFlow Slack integration.


Q: Get recent nth set of data from tables with Group in SQL I have got a table like this

Here as you can see there are different groups of data for different dates.
(When we ignore the time part in the datetime there, we have groups of dates)
So what I need is to take most recent from every group and from that result I need to get the recent nth set.
For example if I pass 2, it should return
LogId     etime
--------------------
19         2021-07-16
--------------------------

Same way if we pass the parameter 3 it should return
LogId     etime
--------------------
18         2021-07-15
--------------------------

I did some query which I really believe its not the best way and it looks little twisty..
create table MYTABLE(logid int,etime datetime)
insert into MYTABLE (logid,etime) values
(15,'2021-07-12 01:32:00 PM'),
(16,'2021-07-15 01:32:00 PM'),
(17,'2021-07-15 04:32:00 PM'),
(18,'2021-07-15 07:32:00 PM'),
(19,'2021-07-16 11:32:00 AM'),
(20,'2021-07-16 08:10:00 AM'),
(21,'2021-07-17 11:20:00 PM')

select logid,etime from (
select *,ROW_NUMBER() over (order by etime desc) serial from (
select logid,dense_rank() over(partition by cast(etime as date) order by etime desc) drnk,Cast(etime as date) etime from @table
)tbl where drnk=1 )tbl2 where serial=3

Could you please share some optimal way
Here is the fiddle
SQLFiddle

A: Seems like OFFSET and FETCH would be more succinct here:
DECLARE @N int = 2,
        @Date date = '20210716';

SELECT LogID, etime
FROM dbo.MYTABLE
WHERE etime >= @Date
  AND eTime < DATEADD(DAY, 1, @Date)
ORDER BY etime ASC
OFFSET @N-1 ROWS FETCH NEXT 1 ROWS ONLY;

A: Imo the way you're doing it now is a really good way and you could stick with it.  Again imo: the nested SELECT are not as nice as common table expressions.  I would rewrite and parameterize the code something like this
declare @param              int=3;

with
dr_cte(logid, etime_dt, drnk) as (
    select logid, Cast(etime as date),
           dense_rank() over(partition by cast(etime as date) order by etime desc)
    from #MYTABLE),
serial_cte(logid, etime_dt, drnk, serial) as (
    select *, row_number() over (order by etime_dt desc)
    from dr_cte
    where drnk=1)
select *
from serial_cte
where serial=@param;

[EDIT] It could be made a tiny bit more concise (or maybe it's the same?) by using TOP 1 WITH TIES in the dr_cte.  Then the WHERE condition in the second CTE could be removed.  Afaik this code is equivalent
declare @param              int=2;

with
dr_cte(logid, etime_dt) as (
    select top 1 with ties logid, Cast(etime as date)
    from #MYTABLE
    order by row_number() over(partition by cast(etime as date) order by etime desc)),
serial_cte(logid, etime_dt, serial) as (
    select *, row_number() over (order by etime_dt desc)
    from dr_cte)
select *
from serial_cte
where serial=@param;

[Edit 2] It could also be done by OFFSET paging.
declare @param              int=3;

with
dr_cte(logid, etime_dt) as (
    select top 1 with ties logid, Cast(etime as date)
    from #MYTABLE
    order by row_number() over(partition by cast(etime as date) order by etime desc))
select *
from dr_cte
order by etime_dt desc
offset @param-1 rows fetch next 1 rows only;


Q: Huawei Mobile Services SDK violation Device and Network Abuse policy
Your app contains content that doesn’t comply with the Device and
Network Abuse policy. We found your app is using a non-compliant
version of Huawei Mobile Services SDK which contains code to download
or install applications from unknown sources outside of Google Play.

I am using Huawei Mobile Services SDK for Auto Eraser.

List of used dependency

implementation 'com.huawei.hms:ml-computer-vision-segmentation:3.0.0.301'
implementation 'com.huawei.hms:ml-computer-vision-image-segmentation-body-model:2.0.2.300'

buildscript {
    repositories {
        mavenCentral()
        jcenter()
        google()
        maven {url 'http://developer.huawei.com/repo/'}
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.2'

        //Auto eraser
        classpath 'com.huawei.agconnect:agcp:1.3.1.300'
    }
}

Added below meta data in manifest.xml

<meta-data
    android:name="com.huawei.hms.ml.DEPENDENCY"
    android:value="imgseg" />

A: If you have dependencies that can be replaced with Google compatible equivalent dependencies then this could be a possible solution to manage both in one code base.
Using app flavours I was able to separate my GMS and HMS dependencies. In your app level build.gradle file you can create product flavour like so
android {
    flavorDimensions "platforms"
    ...
    productFlavors {
        gms {
            dimension "platforms"
        }
        hms {
            dimension "platforms"
        }
    }
    ...
}

More on product flavors here.
And then you can specify if a dependency should be part of the flavour by prefixing it to the keyword implementation under dependencies.
dependencies {
    ...
    gmsImplementation 'com.google.android.gms:play-services-maps:18.0.2'
    hmsImplementation 'com.huawei.hms:maps:5.0.0.300'
    ...
}

I then went a bit further by wrapping the usage of each dependency in a class that is available in both flavours but the implementation differs based on the dependency's requirements.
com.example.maps.MapImpl under src>hms>java
and
com.example.maps.MapImpl under src>gms>java

So I am free to use the wrapper class anywhere without worrying about the dependency mismatch.
The HMS dependency is no longer part of the GMS build variant so I would be able to upload that to the Google playstore.

A: I solved it by doing similar to what @Daniel has suggested to avoid such worries in the future:

*

*Create different product flavors in your app level Gradle file:

android {
    ...

    flavorDimensions 'buildFlavor'

    productFlavors {
        dev {
            dimension 'buildFlavor'
        }

        production {
            dimension 'buildFlavor'
        }

        huawei {
            dimension 'buildFlavor'
        }
    }
}

*Restrict the Huawei related dependencies so they're only available for Huawei product flavor:

    huaweiImplementation "com.huawei.hms:iap:3.0.3.300"
    huaweiImplementation "com.huawei.hms:game:3.0.3.300"
    huaweiImplementation "com.huawei.hms:hwid:5.0.1.301"
    huaweiImplementation "com.huawei.hms:push:5.0.0.300"
    huaweiImplementation "com.huawei.hms:hianalytics:5.0.3.300"
    huaweiImplementation "com.huawei.hms:location:5.0.0.301"

*Since dev and production flavors are not going to have Huawei dependencies now, you may get build errors for the Huawei related classes that you use in your app.

For that I create dummy classes with the same packages tree as Huawei, for instance:
app > src > dev > java > com > huawei > hms > analytics > HiAnalytics.kt
class HiAnalytics {

    companion object {

        @JvmStatic
        fun getInstance(context: Context): HiAnalyticsInstance {
            return HiAnalyticsInstance()
        }
    }
}

*This solves the Cannot resolve symbol error when trying to import Huawei classes in your main, dev, or production flavors and you can import those classes anywhere:

import com.huawei.hms.analytics.HiAnalytics

Now if you change the build variant to dev, you should have access to the dummy classes in your app. If you change it to huawei, you should be able to access the classes from Huawei dependencies.

A: Update:
Note:
If you have confirmed that the latest SDK version is used, before submitting a release to Google, please check the apks in all Testing track on Google Play Console(including Open testing, Closed testing, Internal testing). Ensure that the APKs on all tracks(including paused track) have updated to the latest HMS Core SDK.

HMS Core SDKs have undergone some version updates recently. To further improve user experience, update the HMS Core SDK integrated into your app to the latest version.

HMS Core SDK
Version
Link

Keyring
com.huawei.hms:keyring-credential:6.4.0.302
Link

Location Kit
com.huawei.hms:location:6.4.0.300
Link

Nearby Service
com.huawei.hms:nearby:6.4.0.300
Link

Contact Shield
com.huawei.hms:contactshield:6.4.0.300
Link

Video Kit
com.huawei.hms:videokit-player:1.0.12.300
Link

Wireless kit
com.huawei.hms:wireless:6.4.0.202
Link

FIDO
com.huawei.hms:fido-fido2:6.3.0.304com.huawei.hms:fido-bioauthn:6.3.0.304com.huawei.hms:fido-bioauthn-androidx:6.3.0.304
Link

Panorama Kit
com.huawei.hms:panorama:5.0.2.308
Link

Push Kit
com.huawei.hms:push:6.5.0.300
Link

Account Kit
com.huawei.hms:hwid:6.4.0.301
Link

Identity Kit
com.huawei.hms:identity:6.4.0.301
Link

Safety Detect
com.huawei.hms:safetydetect:6.4.0.301
Link

Health Kit
com.huawei.hms:health:6.5.0.300
Link

In-App Purchases
com.huawei.hms:iap:6.4.0.301
Link

ML Kit
com.huawei.hms:ml-computer-vision-ocr:3.6.0.300com.huawei.hms:ml-computer-vision-cloud:3.5.0.301com.huawei.hms:ml-computer-card-icr-cn:3.5.0.300com.huawei.hms:ml-computer-card-icr-vn:3.5.0.300com.huawei.hms:ml-computer-card-bcr:3.5.0.300com.huawei.hms:ml-computer-vision-formrecognition:3.5.0.302com.huawei.hms:ml-computer-translate:3.6.0.312com.huawei.hms:ml-computer-language-detection:3.6.0.312com.huawei.hms:ml-computer-voice-asr:3.5.0.301com.huawei.hms:ml-computer-voice-tts:3.6.0.300com.huawei.hms:ml-computer-voice-aft:3.5.0.300com.huawei.hms:ml-computer-voice-realtimetranscription:3.5.0.303com.huawei.hms:ml-speech-semantics-sounddect-sdk:3.5.0.302com.huawei.hms:ml-computer-vision-classification:3.5.0.302com.huawei.hms:ml-computer-vision-object:3.5.0.307com.huawei.hms:ml-computer-vision-segmentation:3.5.0.303com.huawei.hms:ml-computer-vision-imagesuperresolution:3.5.0.301com.huawei.hms:ml-computer-vision-documentskew:3.5.0.301com.huawei.hms:ml-computer-vision-textimagesuperresolution:3.5.0.300com.huawei.hms:ml-computer-vision-scenedetection:3.6.0.300com.huawei.hms:ml-computer-vision-face:3.5.0.302com.huawei.hms:ml-computer-vision-skeleton:3.5.0.300com.huawei.hms:ml-computer-vision-livenessdetection:3.6.0.300com.huawei.hms:ml-computer-vision-interactive-livenessdetection:3.6.0.301com.huawei.hms:ml-computer-vision-handkeypoint:3.5.0.301com.huawei.hms:ml-computer-vision-faceverify:3.6.0.301com.huawei.hms:ml-nlp-textembedding:3.5.0.300com.huawei.hms:ml-computer-ner:3.5.0.301com.huawei.hms:ml-computer-model-executor:3.5.0.301
Link

Analytics Kit
com.huawei.hms:hianalytics:6.5.0.300
Link

Dynamic Tag Manager
com.huawei.hms:dtm-api:6.5.0.300
Link

Site Kit
com.huawei.hms:site:6.4.0.304
Link

HEM Kit
com.huawei.hms:hemsdk:1.0.4.303
Link

Map Kit
com.huawei.hms:maps:6.5.0.301
Link

Wallet Kit
com.huawei.hms:wallet:4.0.5.300
Link

Awareness Kit
com.huawei.hms:awareness:3.1.0.302
Link

Crash
com.huawei.agconnect:agconnect-crash:1.7.0.300
Link

APM
com.huawei.agconnect:agconnect-apms:1.5.2.310
Link

Ads Kit
com.huawei.hms:ads-prime:3.4.55.300
Link

Paid Apps
com.huawei.hms:drm:2.5.8.301
Link

Base
com.huawei.hms:base:6.4.0.303

Required versions for cross-platform app development:

Platform
Plugin Name
Version
Link

React Native
react-native-hms-analytics
6.3.2-301
Link

react-native-hms-iap
6.4.0-301
Link

react-native-hms-location
6.4.0-300
Link

react-native-hms-map
6.3.1-304
Link

react-native-hms-push
6.3.0-304
Link

react-native-hms-site
6.4.0-300
Link

react-native-hms-nearby
6.2.0-301
Link

react-native-hms-account
6.4.0-301
Link

react-native-hms-ads
13.4.54-300
Link

react-native-hms-adsprime
13.4.54-300
Link

react-native-hms-availability
6.4.0-303
Link

Cordova(Ionic-CordovaIonic-Capacitor)
cordova-plugin-hms-analyticsionic-native-hms-analytics
6.3.2-301
Link

cordova-plugin-hms-locationionic-native-hms-location
6.4.0-300
Link

cordova-plugin-hms-nearbyionic-native-hms-nearby
6.2.0-301
Link

cordova-plugin-hms-accountionic-native-hms-account
6.4.0-301
Link

cordova-plugin-hms-pushionic-native-hms-push
6.3.0-304
Link

cordova-plugin-hms-siteionic-native-hms-site
6.4.0-300
Link

cordova-plugin-hms-iapionic-native-hms-iap
6.4.0-301
Link

cordova-plugin-hms-availabilityionic-native-hms-availability
6.4.0-303
Link

cordova-plugin-hms-adsionic-native-hms-ads
13.4.54-300
Link

cordova-plugin-hms-adsprimeionic-native-hms-adsprime
13.4.54-300
Link

cordova-plugin-hms-mapionic-native-hms-map
6.0.1-305
Link

cordova-plugin-hms-mlionic-native-hms-ml
2.0.5-303
Link

Flutter
huawei_safetydetect
6.4.0+301
Link

huawei_iap
6.2.0+301
Link

huawei_health
6.3.0+302
Link

huawei_fido
6.3.0+304
Link

huawei_push
6.3.0+304
Link

huawei_account
6.4.0+301
Link

huawei_ads
13.4.55+300
Link

huawei_analytics
6.5.0+300
Link

huawei_map
6.5.0+301
Link

huawei_hmsavailability
6.4.0+303
Link

huawei_location
6.0.0+303
Link

huawei_adsprime
13.4.55+300
Link

huawei_ml
3.2.0+301
Link

huawei_site
6.0.1+304
Link

Xamarin
Huawei.Hms.Hianalytics
6.4.1.302
Link

Huawei.Hms.Location
6.4.0.300
Link

Huawei.Hms.Nearby
6.2.0.301
Link

Huawei.Hms.Push
6.3.0.304
Link

Huawei.Hms.Site
6.4.0.300
Link

Huawei.Hms.Fido
6.3.0.304
Link

Huawei.Hms.Iap
6.4.0.301
Link

Huawei.Hms.Hwid
6.4.0.301
Link

Huawei.Hms.Ads-prime
3.4.54.302
Link

Huawei.Hms.Ads
3.4.54.302
Link

Huawei.Hms.Maps
6.5.0.301
Link

If you have any further questions or encounter any issues integrating any of these kits, please feel free to contact us.

Region
Email

Europe
developereu@huawei.com

Asia Pacific
developerapac@huawei.com

Latin America
developerla@huawei.com

Middle East & Africa
developermea@huawei.com

Russia
developer_ru@huawei.com

A: UPDATE 06/04/2022
Huawei released a new version of their SDK : 3.4.0.300
3.4.0.300 (2022-03-04)
New Features

*

*Real-time translation: Added Afrikaans to the list of languages
supported. (Note that this language is available only in Asia,
Africa, and Latin America.)

Modified Features

*

*Deleted the capability of prompting users to install HMS Core (APK).

*Modified the SDK privacy and security statement. Updated the SDK

*versions of all subservices.

For me, since I've migrated to Google ML Kit, I will wait till August, then I will switch back to Huawei ML Kit to make sure Google will not remove or suspend my apps.

Old answer :
I used to love the HMS ML kit, but because of this issue, I'm aware that Google will one day completely suspend my apps because I'm using HMS services, and even if Huawei fixes the issue, we'll have to wait 120 days to find out if we're safe.
In my case, I'm using the HMS Segmentation ML Kit. I've just switched to Google Selfie Segmentation ML. I will wait till 120 days have passed and see if the issue is still persisting for other developers. If not, I will switch back to the HMS Kit.

A: The solution to the problem is to update the dependencies like in this link.
With this update, the ability to prompt users to install HMS Core (APK) has been removed.
https://developer.huawei.com/consumer/en/doc/development/hmscore-common-Guides/hmssdk-kit-0000001050042513#section20948233203517

A: I just use hms push when upload to huawei.
i fixed by commenting hms services in  build.gradle and app/build.gradle when to upload to playstore.
Then, I uncomment if upload to huawei.
//apply plugin: "com.huawei.agconnect"

apply plugin: 'com.google.gms.google-services'

//implementation 'com.huawei.hms:push:5.3.0.304'.


Q: Show another button when using "commitEditingStyle" in a UITableView datasource I want to show an "Edit" button below the default "Delete" button that shows up with a swipe gesture on a cell when you implement "commitEditingStyle" on the table's datasource.
Is this possible by only implementing "commitEditingStyle" or will i have to implement my own way of showing the buttons on the cells? And if it is, how would i handle the commit?

A: Yes you have to implement your own way of showing buttons on UITableViewCells by customizing the UITableViewCells.
As far as your requirement is concerned, I dont think its a good idea to show the "edit" button below the "delete" button, as accommodating both buttons vertically one-by-one may disappoint the user to make desired touch actions.
I mean to say, user may want to touch edit, but due to successive placing of custom edit/delete buttons, delete button may get clicked which is dangerous & not acceptable too. Of course,it will cause user to take proper care every-time making any of the edits.


Q: ASP.NET how to make slider for table? I have an ASP.NET table that gets lots of rows put into it. I want to have a slider to view more rows instead of making my page extremely long. This seemed like a basic task, but I cannot find any way to do this...
I would love to hear any ideas!
To be clear, my question is: how do I add a slider to my asp.net table?

A: Not sure if this will exactly fit the bill, but check out the ASP.NET Scrollable Table Server Control
Or were you asking for a slider pager control that will load more results for the user?

A: For future reference,
    .FixedHeightContainer
    {
      float:left;
      height: 350px;
      width:100%;
      padding:3px;
    }
    .Content
    {
      height:224px;
      overflow:auto;
    }

along with:

Results

        <asp:Table ID="Table1" runat="server" GridLines="Both" Height="350px" Width="80%">
            <asp:TableHeaderRow>
                <asp:TableHeaderCell>

                </asp:TableHeaderCell>
            </asp:TableHeaderRow>
        </asp:Table>

Is what I used to create a table with a slider
Thanks for all the comments :)
Nikita Silverstruk, your comment helped so much :) thanks


Q: Difference between wic and hddimg format in yocto I have generated a core-image-minimal image for my Intel board in Yocto.
Looking into tmp/deploy/images folder they are many images.
I flashed *.wic image using dd command on USB and it created two partitions ( Boot and Platform ) and allowed only to perform a live booting without allowing it to install on the hard disk of the board.
I then flashed *.hddimg on the USB using dd command. It only created a "boot" partition which has rootfs.img, syslinux and EFI folder.
Booting using USB provided me an "Install" option, which installed on the board and when I rebooted after installing, it displays "No bootable media found"
Using bootable image there are two partitions in the hard disk. Why it is not booting..
Steps followed:

*

*Created an minimal yocto image using "bitbake core-image-minimal" command

*Flashed the USB using the dd command.

sudo dd if=tmp/deploy/images/intel-corei7-64/core-image-minimal-intel-corei7-64.hddimg of=/dev/sdb

*Clicked on install and typed “sda”

*The installation was successful and when I tried to restart by removing the USB Drive, it says “No boot options found. Please install bootable media and restart."

What is the mistake I am doing here.
Which image to choose and when..

A: There was not much info about online, so I asked this question in the intel community and here is the response of that:
Generally a .wic image is intended to be installed directly to its final destination, whereas an hddimg is for evaluation and installation elsewhere.
By default meta-intel .wic images only have an EFI bootloader, and will not boot via legacy BIOS.
An hddimg will have both an EFI bootloader and the syslinux binaries that let it boot from legacy BIOS.
On startup with your installer USB image do you get a light gray screen with four options? If so it is booting via legacy BIOS.


Q: How can I add cookies to Seaside responses without redirecting? I'm making a small web application in Seaside. I have a login component, and after the user logs in I want to send along a cookie when the next component renders itself. Is there a way to get at the object handling the response so I can add something to the headers it will output?
I'm trying to avoid using WASession>>redirectWithCookies since it seems pretty kludgey to redirect only because I want to set a cookie.
Is there another way that already exist to add a cookie that will go out on the next response?

A: There is currently no built-in way to add cookies during the action/callback phase of request processing. This is most likely a defect and is noted in this issue: http://code.google.com/p/seaside/issues/detail?id=48
This is currently slated to be fixed for Seaside 2.9 but I don't know if it will even be backported to 2.8 or not.
Keep in mind that there is already (by default) a redirection between the action and rendering phases to prevent a Refresh from re-triggering the callbacks, so in the grand scheme of things, one more redirect in this case isn't so bad.
If you still want to dig further, have a look at WARenderContinuation>>handleRequest:. That's where callback processing is triggered and the redirect or rendering phase begun.
Edited to add:
The issue has now been fixed and (in the latest development code) you can now properly add cookies to the current response at any time. Simply access the response object in the current request context and add the cookie. For example, you might do something like:
self requestContext response addCookie: aCookie

This is unlikely to be backported to Seaside 2.8 as it required a fairly major shift in the way responses are handled.

A: I've just looked into this in depth, and the answer seems to be no.  Specifically, there's no way to get at the response from the WARenderCanvas or anything it can access (it holds onto the WARenderingContext, which holds onto the WAHtmlStreamDocument, which holds onto the response's stream but not the response itself).  I think it would be reasonable to give the context access to the current response, precisely to be able to set headers on it, but you asked if there was already a way, so: no.
That said, Seaside does a lot of extra redirecting, and it doesn't seem to have much impact on the user experience, so maybe the thing to do is to stop worrying about it seeming kludgey and go with the flow of the API that's already there :)


Q: SymbolSource Nightmare So after hours of jumping through hoops, I have gotten SymbolSource running except I am unable to push any packages.  The error I am getting now is:
Response status code does not indicate success:
418 (Reading package metadata failed: The schema version of 'MyNugetPackage'
is incompatible with version 2.1.31002.9028 of NuGet. Please upgrade NuGet
to the latest version from See http://www.symbolsource.org/Public/Home/Help
for possible reasons. Fiddler may help diagnosing this error if your client
discards attached detailed information.).

First problem is that you can no longer download the command line version of v2.1.3 of Nuget.  I tried the the oldest version available: v2.8.6 but I get the same error.  Second problem is it looks like SymbolSource.Server.Basic hasn't been touched in 3 years.  Is this project dead?  Am I wasting my time?  I can't find any other alternative for debugging nuget packages without publishing to a third party service (which my company won't allow)?

A: The Symbol Server project master branch hasn't been touched for 4 years as of writing, and there is a queue of pull requests and issues left open for even longer.
There is an 'upgrade' branch which hasn't been touched since 2014, but that has updated NuGet version.
There is a slightly more recent fork at https://github.com/TrabacchinLuigi/SymbolSource.Community/tree/upgrade
which uses more recent versions of NuGet. Also have a look at the GitHub 'network' for other potential maintained forks: https://github.com/SymbolSource/SymbolSource.Community/network
And alternative hosting solutions include:

*

*https://inedo.com/proget

*https://github.com/GitTools/GitLink
Edit -- I got my own version running:
https://github.com/i-e-b/SymbolSourceSane


Q: Print 2 arrays into a CSV file with javascript I was following the mentioned question and this one:
JavaScript array to CSV
Trying to print 2 arrays in columns A and B which i can turn into a string separated by comas"," which ever is more easy to do but i just can´t get it to work with the examples available.
My arrays look like this:
var Test = ["John", "Ivar", "Peter", "Tony"];
var Addres = ["Canada", "Sweden", "England", "Chile"];

And in string format its the same only separated by comas
I thought it was going to be an easy task but it's more complicated than I expected
Hope anyone here can help me with this,
Thanks

A: You can accomplish it with one-liner reduce:
var Test = ["John", "Ivar", "Peter", "Tony"];
var Addres = ["Canada", "Sweden", "England", "Chile"];

var result = Test.reduce((str, name, i) => `${str}${name},${Address[i]}\n`, 'Test,Address\n');

console.log(result);


Q: Why is this C program returning correct value in VC++2008? We know that automatic variables are destroyed upon the return of the function.
Then, why is this C program returning correct value?
#include <stdio.h>
#include <process.h>

int * ReturningPointer()
{
    int myInteger = 99;

    int * ptrToMyInteger = &myInteger;

    return ptrToMyInteger;
}

main()
{
    int * pointerToInteger = ReturningPointer();

    printf("*pointerToInteger = %d\n", *pointerToInteger);

    system("PAUSE");
}

Output
*pointerToInteger = 99

Edit
Then why is this giving garbage values?
#include <stdio.h>
#include <process.h>

char * ReturningPointer()
{
    char array[13] = "Hello World!";

    return array;
}

main()
{
    printf("%s\n", ReturningPointer());

    system("PAUSE");
}

Output
x≈§

A: There is no answer to that question: your code exhibits undefined behavior. It could print "the right value" as you are seeing, it could print anything else, it could segfault, it could order pizza online with your credit card.
Dereferencing that pointer in main is illegal, it doesn't point to valid memory at that point. Don't do it.
There's a big difference between you two examples: in the first case, *pointer is evaluated before calling printf. So, given that there are no function calls between the line where you get the pointer value, and the printf, chances are high that the stack location pointer points to will not have been overwritten. So the value that was stored there prior to calling printf is likely to be output (that value will be passed on to printf's stack, not the pointer).
In the second case, you're passing a pointer to the stack to printf. The call to printf overwrites (a part of) that same stack region the pointer is pointing to, and printf ends up trying to print its own stack (more or less) which doesn't have a high chance of containing something readable.
Note that you can't rely on getting gibberish either. Your implementation is free to use a different stack for the printf call if it feels like it, as long as it follows the requirements laid out by the standard.

A: This is undefined behavior, and it could have launched a missile instead. But it just happened to give you the correct answer.
Think about it, it kind of make sense -- what else did you expect? Should it have given you zero? If so, then the compiler must insert special instructions at the scope end to erase the variable's content -- waste of resources. The most natural thing for the compiler to do is to leave the contents unchanged -- so you just got the correct output from undefined behavior by chance.
You could say this behavior is implementation defined. For example. Another compiler (or the same compiler in "Release" mode) may decide to allocate myInteger purely in register (not sure if it actually can do this when you take an address of it, but for the sake of argument...), in that case no memory would be allocated for 99 and you would get garbage output.
As a more illustrative (but totally untested) example -- if you insert some malloc and exercise some memory usage before printf you may find the garbage value you were looking for :P
Answer to "Edited" part
The "real" answer that you want needs to be answered in disassembly. A good place to start is gcc -S and gcc -O3 -S. I will leave the in-depth analysis for wizards that will come around. But I did a cursory peek using GCC and it turns out that printf("%s\n") gets translated to puts, so the calling convention is different. Since local variables are allocated on the stack, calling a function could "destroy" previously allocated local variables.

A: *

*Destroying is the wrong word imho. Locals reside on the stack, if the function returns the stack space may be reused again. Until then it is not overwritten and still accessible by pointers which you might not really want (because this might never point to something valid)

*Pointers are used to address space in memory, for local pointers the same as I described in 1 is valid. However the pointer seems to be passed to the main program.

*If it really is the address storing the former integer it will result in "99" up until that point in the execution of your program when the program overwrite this memory location. It may also be another 99 by coincidence. Any way: do not do this.
These kind of errors will lead to trouble some day, may be on other machines, other OS, other compiler or compiler options - imagine you upgrade your compiler which may change the behaviour the memory usage or even a build with optimization flags, e.g. release builds vs default debug builds, you name it.

A: In most C/C++ programs their local variables live on the stack, and destroyed means overwritten with something else. In this case that particular location had not been overwritten yet when it was passed as a parameter to printf().
Of course, having such code is asking for trouble because per the C and C++ standards it exhibits undefined behavior.

A: That is undefined behavior. That means that anything can happen, even what you would expect.
The tricky part of UB is when it gives you the result you expect, and so you think that you are doing it right. Then, any change in an unrelated part of the program changes that...
Answering your question more specifically, you are returning a pointer to an automatic variable, that no longer exists when the function returns, but since you call no other functions in the middle, it happens to keep the old value.
If you call, for example printf twice, the second time it will most likely print a different value.

A: The key idea is that a variable represents a name and type for value stored somewhere in memory. When it is "destroyed", it means that a) that value can no longer be accessed using that name, and b) the memory location is free to be overwritten.
The behavior is undefined because the implementation of the compiler is free to choose what time after "destruction" the location is actually overwritten.


Q: Code to define biological and technical replicate samples (brain twister) In my expression dataset I have various kinds or replicates, biological and technical. A biological replicate I consider if the same person was sampled at different dates. A technical replicate I consider if a sample was taken from the same person at the same date and measured either at the same or different dates.
I tried to define this by code but unfortunately im hitting a wall with trying to define technical and biological replicates.
Below is my code that defines replicates and first replicates (=index case) but for the rest it would be amazing if someone could help me. Its kind of a brain twister so kudos to anyone solving this!
Thanks a lot!
Sebastian
df<- data.frame(
  sample = c(1,2,3,4,5,6,7,8, 9, 10, 11, 12),
  individual = c("a", "a", "a", "b", "b", "b", "c", "c", "c", "f", "d", "e"),
  date_collected = c(1.1, 1.1, 1.1, 1.1, 1.1, 1.2, 1.2, 1.1, 1.1, 1.2, 1.1, 1.1),
  date_processed = c(2.1, 2.1, 2.1, 2.2, 2.1, 2.1, 2.1, 2.1, 2.1, 2.2, 2.2, 2.1 ))

#differentiate biological and technical replicates
df$has_replicate <- FALSE #all that have a replicate
df$is_first_of_replicates <- FALSE #primary sample
df$is_technical_replicate_same_run <- FALSE #same sample, same date processed
df$is_technical_replicate_different_run <- FALSE #same sample,     different date processed
df$is_biological_replicate_same_run <- FALSE #same individual, different date collected, same day proc
df$is_biological_replicate_different_run <- FALSE #same individual, diff date col, dif day proc

#check all samples that have replicates = same individual (including first one)
replicates_index <- which(df$individual %in%         df$individual[which(duplicated(df$individual))])
#mark
df[replicates_index, ]$has_replicate <- TRUE

#define first samples (by checking which ones are not the first ones)
replicates_not_first_index <- duplicated(df$individual)
df[replicates_index, ]$sample #all that have replicates incl first
df[replicates_not_first_index, ]$sample #all replicates that are not first
#find replicates that are first = present in rep but not in not first
firstsIDs_ <- setdiff(df[replicates_index, ]$sample,     df[replicates_not_first_index, ]$sample)
#get index
firsts_index <- which(df$sample %in% firstsIDs_)
#mark
df[firsts_index, ]$is_first_of_replicates <- TRUE

expected output
df$is_technical_replicate_same_run # TRUE if is replicate & date.collected same & date processed is the same
df$is_technical_replicate_different_run # TRUE if is replicate & date.collected same & date processed is different
df$is_biological_replicate_same_run # TRUE if is replicate & date collected is different & date processed is the same
df$is_biological_replicate_different_run # TRUE if is replicate & date collected is different & date processed is different


Q: Simple question of how models deal with control variables Apologies for the very simple question, it's something I've had trouble wrapping my head around: How does a model (e.g. logistic regression) deal with control variables - if the purpose is to keep a control variable constant, how does it choose which level (of that variable) to keep constant, or does it run the model for every level of that variable and somehow produce a single output?
For example:
Say I have an opportunistic dataset of locations where birds have put their nests. I've put an example sample below, but pretend there are many more data points. My dependent variable is the "Location" of the bird's nest, and the independent variable is the "Weather" and "Distance to water" - I want to see whether these factors influence the choice of location for their nest. I know that "Year" and "Species (of bird)" will also influence this, however as I am not studying those factors I want to control for them.
Will the model, therefore, run on every possible combination of keeping both Year and Species constant (i.e. Species CB, the Year 2018. Species CB, the Year 2019 ... Species ETD, Year. 2018)?

Species
Location
Weather
Year
Distance to water (m)

CB
A
Rain
2019
12

CB
B
Rain
2019
2

ETD
B
Dry
2020
18

ER
A
Dry
2018
7

ETD
B
Rain
2020
16

CB
A
Rain
2018
23

ER
A
Rain
2018
9

ER
B
Dry
2020
10

Or does the model do fancy statistics to determine which combination of control variables will lead to significance for the non-control variables? Please explain this in terms of what RSTUDIO does.


Q: C# Tuple list inside class inside class not set to instance of object I'm trying to use a tuple list inside a custom class that wraps some methods from mutliple classes inside a game. I'm getting an 'object reference not set to instance of object error' just after the "ENTERED ADD METHOD A-1" is displayed in the cosole from the 1st Add method of the wrapper class. Clearly, Im not setting up the list correctly, but I can't see where the issue is. Any help would be appreciated as I'm new to working with 'classes'.
// wrappers & classes
KilledActorsWrapper KilledActors = new KilledActorsWrapper();

    public class KilledActorsWrapper
#region KilledActorsWrapper class
{
    public KilledActorsWrapper()
    {   // constructor
        if (Type.GetType("KilledActorsWrapper") == null)    // check to see if class has been initiated
        {   //class with the given name does not exist so instantiate it
            List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>> m_KilledActors =
                        new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>();
            m_KilledActors.Clear();
            ConsoleWriteline("INITIALISED KILLEDACTORS LIST");
        }
        else
        {   // class with the given name exists so show an error, cannot initate the class twice
            ColoredConsoleWrite(ConsoleColor.DarkGreen, "INITIALISING KILLEDACTORS LIST FAILED");
            throw new Exception("KilledActorsWrapper class already exists. Are you typing to initiate a second instance of this class?");
        }
    }

    public void Add(AiActor killedActor, List<DamagerScore> damages)
    {
        ConsoleWriteline("ENTERED ADD METHOD A");
        Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>> tuple = new Tuple<AiActor, AiDamageInitiator, NamedDamageTypes,
            List<DamagerScore>>(killedActor, null, NamedDamageTypes.AirbrakeDriveFailure, damages);
        ConsoleWriteline("ENTERED ADD METHOD A-1");
        m_KilledActors.Add(tuple);
        ConsoleWriteline("ENTERED ADD METHOD A-2");
    }

    public void Add(AiActor killedActor, AiDamageInitiator initiator, NamedDamageTypes damageType)
    {
        ConsoleWriteline("ENTERED ADD METHOD B");
        Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>> tuple = new Tuple<AiActor, AiDamageInitiator, NamedDamageTypes,
            List<DamagerScore>>(killedActor, initiator, damageType, null);
        ConsoleWriteline("ENTERED ADD METHOD B-1");
        this.m_KilledActors.Add(tuple);
        ConsoleWriteline("ENTERED ADD METHOD B-2");
    }

    public int Count
    {
        get { return m_KilledActors.Count; }
    }

    public List<DamagerScore> GetDamagerScore(AiActor killedActor)
    {
        for (int i = 0; i < m_KilledActors.Count; i++)
        {
            if (m_KilledActors[i].Item1 == killedActor)
            {
                return (List<DamagerScore>)m_KilledActors[i].Item1;
            }
        }
        return null;
    }

    public List<AiDamageInitiator> GetDamageInitiators(AiActor killedActor)
    {
        List<AiDamageInitiator> damageinitiators = null;
        for (int i = 0; i < m_KilledActors.Count; i++)
        {
            if (m_KilledActors[i].Item1 == killedActor)
            {
                damageinitiators.Add((AiDamageInitiator)m_KilledActors[i].Item2);
            }
        }
        return damageinitiators;
    }

    public List<NamedDamageTypes> GetNamedDamageTypes(AiActor actor)
    {
        List<NamedDamageTypes> nameddamagetypes = null;
        for (int i = 0; i < m_KilledActors.Count; i++)
        {
            if (m_KilledActors[i].Item1 == actor)
            {
                nameddamagetypes.Add((NamedDamageTypes)m_KilledActors[i].Item3);
            }
        }
        return nameddamagetypes;
    }

    public void Clear()
    {
        m_KilledActors.Clear();
    }
    private List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>> m_KilledActors { get; set; }
}
#endregion

public override void OnActorDead(int missionNumber, string shortName, AiActor actor, List<DamagerScore> damages)
#region process when an actor dies
{
    base.OnActorDead(missionNumber, shortName, actor, damages);
    KilledActors.Add(actor, damages); // call the wrapper class
}

public override void  OnActorDamaged(int missionNumber, string shortName, AiActor actor, AiDamageInitiator initiator, NamedDamageTypes damageType)
{
    base.OnActorDamaged(missionNumber, shortName, actor, initiator, damageType);
    KilledActors.Add(actor, initiator, damageType); // call the wrapper class

}

A: Either m_KilledActors or tuple is not defined.
In this case the bug is in your constructor
List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>> m_KilledActors = new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>();

This causes a duplicate definition of m_KilledActors.. change it to just
m_KilledActors = new List<Tuple<AiActor, AiDamageInitiator, NamedDamageTypes, List<DamagerScore>>>();


Q: Live lock on Linux UNIX socket, what to do? We operate an Linux application that forks a large number (more than 1000) of child processes. These child processes communicate with master process over UNIX datagram socket (one shared among all child processes). The UNIX datagram socket is used besides other communications also for logging. The whole system works fine until the app has to react to a massive external error - let's say a crash of application database. We observed that in such a situation, child processes start to generate a huge amount of error log events, which is probably correct since each child is impacted by that crash. After few minutes, the load increases above 8000 with 80-100% CPU system (not user!) consumption. The state is recoverable only if the app is killed or more commonly, the box becomes unusable due to slow responses and has to be rebooted.
The investigation of core dumps shows that child processes are blocked in send() syscall on the UNIX socket, speaking to master process. The UNIX socket is configured as a non-blocking and the app implement proper handling of EAGAIN. More in-depth analysis indicates that there is a live lock condition in the kernel. Obviously, processes are competing for access to some resource related to UNIX socket.
Questions: Did you ever meet this or similar behavior before? Do we miss anything about UNIX socket parallelism?
Versions:
 - CentOS Linux release 7.3.1611 (Core).
 - Kernel Linux 3.10.0-514.16.1.el7.x86_64 x86_64.

A: There is clearly room for improvement on the kernel side here and chances are it's a reasonably low hanging fruit. I'm not going to speculate. Chances are the problem will be easily visible with flamegraphs.
However, considerations of the sort in this context are a red herring. For the sake of argument let's assume the kernel pushes all these error messages with 0 overhead. You have generated gigabytes of repetitive error messages adding no value.
Instead, when there is a major event just log it once and then log again that it is cleared (e.g. note the connection to the database died, note when it got back up, but don't log on each query that it is dead). Alternatively you can log this periodically or with ratelimit. Either way, just spamming is the wrong thing to do.
The sheer number of children (1000+?) seems extremely excessive and puts a question mark on the validity of the design of this project. Can you elaborate what's happening there?


Q: Combine Google_Org_Chart with Mysql Im all new at PHP..
i have a task to make an organizational chart (just like google chart) but it is rendered from mysql, just like as follows org chart
and this is my database: sql
here is code from google chart.. `

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

            <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
            <title>
              Google Visualization API Sample
            </title>

Anybody knows something?? Any help would be appreciated.. Thanks..
Regards,
Aryo

A: You can try something like this:
<?php
// set database connection parameters
$databaseName = '<name of database>';
$username = '<user>';
$password = '<password>';
try {
    $db = new PDO("mysql:dbname=$databaseName", $username, $password);
}
catch (PDOException $e) {
    echo $e->getMessage();
    exit();
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = $db->prepare('SELECT id, nama, parent_id FROM tbl_dummy');
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);

$flag = true;
$table = array();
$table['cols'] = array(
    array('label' => 'ID', 'type' => 'number'),
    array('label' => 'Name', 'type' => 'string'),
    array('label' => 'Parent ID', 'type' => 'number')
);
$table['rows'] = array();

foreach ($results as $row) {
    $temp = array();
    $temp[] = array('v' => (int) $row['id']);
    $temp[] = array('v' => $row['nama']);
    $temp[] = array('v' => (int) $row['parent_id']);
    $table['rows'][] = array('c' => $temp);
}
$jsonTable = json_encode($table);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>
        Google Visualization API Sample
        </title>


Q: Google Website Optimizer Validation Warning I have been using Google website optimizer(GWO) to run a multivariate test on my web page. When I either do offline or online validation, I receive a warning stating there is multiple occurrences of my page sections. For example, if one of my page sections was Description Changes, optimizer would say I have two or more occurrences of that script.
I have gone through and checked through my code and have no duplicated any of the page section scripts. Even though GWO states that are multiple occurrences I can still create the experiment.
Does anyone know how to fix multiple occurrences from happening or if there are multiple occurrences if it affects the results.

A: Might be a bit late, but the issue might be that you have a latin-1 character set:

See the following post in the google forums:
http://www.google.com/support/forum/p/websiteoptimizer/thread?tid=70b4938cf4de24f2&hl=en


Q: Batch API, inviting friends I'm trying to invite all fans of a page to a facebook event using the batch API. It's the first time I'm using this API, and at this time I have nothing to test this part of code... can someone tell me how to test without using a real page, with real fans... or tell me if it looks correct ?
 //Getting all the likers of the page
 $result = $facebookObj->api(array(
     'method' => 'fql.query',
     'query' => 'select uid,name from user where uid in ( select uid from page_fan where uid in (select uid2 from friend where uid1 = me()) and page_id = '.$fbPage.')'
 ));

//If liker are more than 50 we use batch request
if($numLikers >50){

    // split array into several part of 50 users accounts
    $splitLikers = array_chunk($result, 50);
    // count how many arrays are generated by the array_chunk
    $countSplit = count($splitLikers);

    //Start a loop through the numbers of groups of 50 users  (or less if last group contains less than 50 users
    for($a=0; $a<$countSplit; $a++){
       //Second loop to go through the 50 likers in one group
       for($b=0; $b<count($splitLikers[$a]); $b++){
           // construct an array containing the whole group
           $queries[$a] = array('method' => 'POST', 'relative_url' => $event_fbID . "/invited/" . $splitLikers[$a][$b]['uid']);

       }
       //Send POST batch request with the array above
       $ret_val = $facebookObj->api('/?batch='.json_encode($queries[$a]), 'POST');
    }

}else{

    foreach ($result as $value) {
        $ret_val = $facebookObj->api($event_fbID . "/invited/" . $value['uid'],'POST');
        if($ret_val) {
            // Success
            $numInvited++;
       }
   }
}

A: Your code seems ok, but dont forget you may need to add the access token to the batch request
like:
$params['access_token']=[USER_ACCESS_TOKEN];

$ret_val = $facebookObj->api('/?batch='.json_encode($queries[$a]), 'POST', $params);

And for testing you may want to create a new page with a couple of friends added and test it.
Also remember you need to handle the response, the batch request will response with an array with the same length that the batch array, and each object may be a diferent code, true if it was send.
Also you can try your FQL code in the Graph Explorer (clic here)
Seems ok, but it shows a extrange result.


Q: How do I stop my program from jumping to a different if-Statement after receiving an invalid input? I´m new to Stackoverflow and to Python. As my first own program I wrote a text game where you enter (a) or (b) and decide this way which decision your character makes. Its working out quite well, but I have one problem. If the user enters, for example, "a" on the first decision, "b" on the second decision, but something invalid on the third, the next valid input will trigger the first decision again instead of the third. I tried to make a short version which portrays my problem. Any help is appreciated.
def test():
    while True:
        input_zero = input("1. > ")
        if input_zero == "a":
            print("a")
            input_a = input("2. > ")
            if input_a == "a":
                print("a, a")
                break
            elif input_a == "b":
                print("a, b")
                break
            else:
                print("Invalid input.")
        elif input_zero == "b":
            print("b")
            input_b = input("2. > ")
            if input_b == "a":
                print("b, a")
                break
            elif input_b == "b":
                print("b, b")
                break
            else:
                print("Invalid input.")
        else:
            print("Invalid input.")

test()

A: So, packaging your choices into a dictionary, similar to that shown below, should make it slightly easier to manage the choices here, I think (there's almost certainly a better way than this). Then add to the empty string each time a choice is made and try to access the dictionary. If the choice is in the dictionary then it will recover a text string and an end-state, which will enable us to end the game when we need to.
This approach also makes testing easier by using itertools to generate all possible combinations of states so you can work out which are missing. If an end_state is found (a value of 1 in the second position of the tuple), then you get the game over message and it closes the loop. If the element isn't in the dictionary, then the last selection was removed and the invalid_input function is called.
def test():

    choice_dict = {"a": (dP_lvl1.path_a, 0),
                   "b": (dP_lvl1.path_b, 0),
                   "c": (dP_lvl1.path_c, 1)
                   "bb": (dP_lvl2.path_bb, 0),
                   "aa": (dP_lvl2.path_aa, 0),
                   "ba": (dP_lvl2.path_ba, 0),
                   "ab": (dP_lvl2.path_ab, 0),
                   "aaa": (dP_lvl3.path_aaa, 0),
                   "aab": (dP_lvl3.path_aab 0),
                   "aba": (dP_lvl3.path_aba, 0),
                   "abb": (dP_lvl3.path_abb, 0),
                   "bab": (dP_lvl3.path_bab, 0),
                   "bba": (dP_lvl3.path_bba} 0),
                   "bbb": (dP_lvl3.path_bbb, 0),
                   "aaaa": (dP_lvl4.path_aaaa, 0),
                   "abaa": (dP_lvl4.path_abaa, 0),
                   "aaba": (dP_lvl4.path_aaba, 0),
                   "aaab": (dP_lvl4.path_aaab, 1),
                   "bbba": (dP_lvl4.path_bbba, 0),
                   "bbab": (dP_lvl4.path_bbab, 0),
                   "babb": (dP_lvl4.path_babb, 0),
                   "abbb": (dP_lvl4.path_abbb, 0),
                   "abba": (dP_lvl4.path_abba, 1),
                   "abab": (dP_lvl4.path_abab, 0),
                   "aabb": (dP_lvl4.path_aabb, 0),
                   "baab": (dP_lvl4.path_baab, 0),
                   "bbaa": (dP_lvl4.path_bbaa, 1),
                   "baba": (dP_lvl4.path_baba, 0),
                   "baaa": (dP_lvl4.path_baaa, 0),
               "bbbb": (dP_lvl4.path_bbbb, 0),}
    # etc. you get the idea

    decisions = ""
    playing = True
    while playing:
        decision = input("choose an option 'a' or 'b':")
        decisions += decision

        try:
            data, end_state = choice_dict[decisions]
            print(data)
            if end_state:
                playing = False
                print("Game over")
            else:
                continue
        except KeyError:
            decisions = decisions[:-1]
            invalid_input()