text:
Q: Angular router events is not firing when navigating with routerLink I have a component where I need to check the current route url using code like:
ngOnInit() {
    this.router.events.subscribe((val: any) => {
        if (val instanceof NavigationStart) {
        }
    });
}

For some reason when navigating to that component with [routerLink]="['/person/edit', perosn.id] the router event does not getting fired when clicking the link for a first time event if I refresing the page.
Then if I click the link again the event getting fired.
Any thoughts why it is does not getting fired at first?

A: ngOnInit() is only called once after a component is instantiated, but not when the route changes.
You can inject the router and subscribe to it's events or params to get notified about route changes.
constructor(private route: ActivatedRoute) { }
ngOnInit() {
     this.route.params.subscribe(val: any) => {
        if (val instanceof NavigationStart) {
        }
    });
}


text:
Q: How to search for a needle in multi-dimensional array in php? I have some different type of php arrays which can have sensitive data at any level of nesting. I want to unset this sensitive keys. How should I go about this?
For e.g. sensitive data keys can be account_no, acc_no etc
Sample request array1:
[
    'ClientCode'   => "abcom",
    'MerchantCode' => "Code1",
    'acc_no'       =>  "12345"
]

This array should become
[
    'ClientCode'   =>  "abcom"
    'MerchantCode' =>  "Code1"

]

Sample request array2:
  [
      'customer_name' => "Umesh",
      'age' => 24,
      'customer_details' => [
          'mob_no' => "989729069",
          'account_no' => '1235'
      ]
  ]

This array should become
[
      'customer_name' => "Umesh",
      'age'           => 24,
      'customer_details' => [
          'mob_no' => "989729069"
      ]
]

A: The best solution for any level of nesting is a recursive function:
$your_array = array(
  'client'  => '1234',
  'acc_no'  => '12345',
  'test'    => array(
    'acc_no'  => '12',
    'acc'    => '12345'
  )
);

function unset_sensitive_keys( &$array, $delete_keys )  {
  foreach( $array as $key => &$value ) {
    if( is_array( $value ) )  {
      unset_sensitive_keys( $value, $delete_keys );
    } else {
      if( in_array( $key, $delete_keys )  ) {
        unset($array[$key]);
      }
    }
  }
}

unset_sensitive_keys( $your_array, array( 'acc_no', 'account_no' ) );

A: Solution without loop
In the first array:
unset($arr['acc_no']);

In the second array:
unset($arr['customer_details']['account_no']);

Solution using loops
First array:
foreach($arr1 as $key => $value) {
   if($key === 'acc_no') {
      unset($arr1['acc_no']);
   }
}

Second array:
foreach($arr2 as $key => $value) {
    if($key === 'customer_details') {
        unset($arr2['customer_details']['account_no']);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: CFLs and Incandescent Lightbulbs in household light fixture I have a few light fixtures around the house where there are multiple sockets per fixture - 4 sockets/fixture in the kitchen, dining room, bathroom ceiling light fixtures.  I began the process of converting these over to using all CFL bulbs, but wanted to use up the supply of incandescent (Edison) bulbs I previously had. Thus, in some fixtures, there were 2 CFLs and 2 Edison bulbs.
I have noticed that when bulbs have failed in those fixtures, it was usually the Edison bulbs.  Is there a particular reason(s) why having CFLs and Edison bulbs in the same fixture might be bad?
Assume that each bulb is rated for the same actual wattage.

A: 2000 hour typical life for "Edison" (incandescent) bulbs, 12,000 typical for CFLs, yes, the incandescent bulbs are going to be most likely to fail first...
The only bad thing about using both kinds in one fixture is that it will make things warmer for the CFLs, which may hurt their life slightly. The fixture as a whole will run somewhat cooler, as the CFLs throw less heat than equivalent incandescents.


text:
Q: Symbol clarification Okay, so I've read a few different meanings for the exclamation point in a statement. For example: $$!\exists x \in O \ni 2x < 5$$
The only question I have is about the Exclamation point in front of the "there exists" symbol. I know it's also used in permutations, but that's a slightly different concept (I think)
Any clarification would be fantastic, thank you

A: When the exclamation point is "used in permutations", as you put it, it signifies a factorial.
When the exclamation point is used with a "there exists" symbol $\exists$, it means "there exists a unique..." (Wikipedia link) However, it should go in the order $\exists!$, not $!\exists$ like you've written.


text:
Q: How to split a String of numbers and chars, only by chars i need to split a String into parts of number sequences and chars between them. Something like this:
input:    "123+34/123(23*12)/100"

output[]:["123","+","34","/","123","(","23","*","12",")","/","100"]

Is this somehow possible, or is it possible to split a String by multiple chars? Otherwise, is it possible to loop through a String in Java?

A: You can use a regular expression.
String input = "123+34/123(23*12)/100";
Pattern pattern = Pattern.compile("\\d+|[\\+\\-\\/\\*\\(\\)]");
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
    System.out.println(matcher.group());
}

A: Use a lookahead assertion based regex for splitting the input string.
String input = "123+34/123(23*12)/100";
System.out.println(Arrays.toString(input.split("(?<=[/)+*])\\B(?=[/)+*])|\\b")));

Output:
[123, +, 34, /, 123, (, 23, *, 12, ), /, 100]


text:
Q: assembleRelease task dependency - Ask for keystore password To avoid writing the keystore password in plain text, I'm trying to add a dependency to the assembleRelease task created by the android Gradle plugin.
I've checked the Gradle documentation Manipulating existing tasks but I'm unable to place the dependency where it should
This is my task, defined in $root$/myApp/build.gradle above the android plugin.
task readPasswordFromInput << {
    def console = System.console()

    ext.keystorePassword = console.readLine('\n\n\n> Enter keystore password: ')
}

apply plugin: 'android'

Then, I've tried the two possibilities offered by Gradle: task.dependsOn and task.doFirst, but none works. The latter appears to be ignored, while dependsOn does add the dependency, but too late in the dependency chain. Running ./gradlew tasks --all prints this
:assembleRelease - Assembles all Release builds [libs:ActionBarSherlock:bundleRelease, libs:DataDroid:bundleRelease, libs:SlidingMenu:bundleRelease]
    :compileRelease
    ...
    [SEVERAL TASKS]
    ...
    :packageRelease
    ...
    [SEVERAL TASKS]
    ...
    :readPasswordFromInput

The problem is, the keystore password is needed in the task packageRelease
Just as a side note, this works as I want
buildTypes {
        release {
            def console = System.console()

            ext.keystorePassword = console.readLine('\n\n\n> IF building release apk, enter keystore password: ')

            debuggable false

            signingConfigs.release.storePassword = ext.keystorePassword
            signingConfigs.release.keyPassword = ext.keystorePassword

            signingConfig signingConfigs.release
        }
    }

but it asks for the password every single time you use gradlew, no matter if it's a clean or an assemble
Thanks!
EDIT
Thanks to @Intae Kim, here's my build.gradle version 2.0
task readPasswordFromInput << {
    def console = System.console()

    ext.keystorePassword = console.readLine('\n\n\n> Enter keystore password: ')

    android.signingConfigs.release.storePassword = ext.keystorePassword
    android.signingConfigs.release.keyPassword = ext.keystorePassword
}

tasks.whenTaskAdded { task ->
    if (task.name == 'validateReleaseSigning') {
        task.dependsOn readPasswordFromInput
    }
}

apply plugin: 'android'

Then, the buildTypes
release {
    debuggable false

    signingConfig signingConfigs.release

    runProguard true
    proguardFile 'my-file.txt'
}

Gradle executes correctly, but it only generates a release-unsigned.apk

A: This is my complete solution for release key signing.

*

*It detects if console is not available in daemon mode.

*It hides passwords.

Use gradle --no-daemon assembleRelease if you are using daemon mode.
buildscript {
    repositories {
        mavenCentral()
    }

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

tasks.whenTaskAdded { task ->
    if (task.name == 'validateReleaseSigning')
        task.dependsOn keystoreInfo
}

apply plugin: 'android'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 18
    buildToolsVersion '18.0.1'

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 18
    }

    signingConfigs {
        release {
            release {
                storeFile file('release.keystore')
                storePassword ''
                keyAlias ''
                keyPassword ''
            }
        }

        buildTypes {
            release {
                debuggable false
                signingConfig signingConfigs.release
            }
        }
    }
}

task keystoreInfo << {
    def console = System.console()
    if (console == null)
        throw new IllegalStateException('no console available, use --no-daemon flag')

    def storeFile = console.readLine('Keystore: ')
    def storePassword = console.readPassword('Keystore password: ')
    def keyAlias = console.readLine('Key alias: ')
    def keyPassword = console.readPassword('Key password: ')

    android.signingConfigs.release.storeFile = file(storeFile)
    android.signingConfigs.release.storePassword = new String(storePassword)
    android.signingConfigs.release.keyAlias = keyAlias
    android.signingConfigs.release.keyPassword = new String(keyPassword)
}

Gist http://gist.github.com/grzegorz-zur/6416924

A: I've created solution, which works fine for me, you can test it out
android {
    signingConfigs {
        release {
            storeFile = file('android.keystore')
            keyAlias = "my_key_alias"
        }
    }

    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
    }
}

task readPasswordFromInput << {
    if(!project.hasProperty('keyStore') || !project.hasProperty('keyPass') || !project.hasProperty('storePass')) {
        println "\n\$ Enter signing details manually or run with \"-PkeyStore={key.store.name} -PstorePass={StoreSecretPassword} -PkeyPass={KeySecretPassword}\""
    }

    if(!project.hasProperty('keyStore')) {
        def newKeyStore = System.console().readLine("\n\$ Enter keystore location or enter (default: android.keystore): ")
        if(newKeyStore != '') android.signingConfigs.release.storeFile = file('${newKeyStore}')
    } else {
        android.signingConfigs.release.storeFile = file(project.keyStore)
    }

    android.signingConfigs.release.storePassword = project.hasProperty('storePass') ? project.storePass : new String(System.console().readPassword("\$ Store password: "))
        android.signingConfigs.release.keyPassword = project.hasProperty('keyPass') ? project.keyPass : new String(System.console().readPassword("\$ Key password: "))
}

tasks.whenTaskAdded { task ->
    if (task.name == 'validateReleaseSigning') {
        task.dependsOn readPasswordFromInput
    }
}

Then you can pass all arguments from CLI on prompt (uses readPassword, so it won't be visible) or you can pass them as CLI arguments to script
gradle assemble
gradle assemble -PkeyStore="~/.android/my.keystore"
gradle assemble -PkeyStore="~/.android/my.keystore" -PstorePass="MyStorePass"
gradle assemble -PkeyStore="~/.android/my.keystore" -PstorePass="MyStorePass" -PkeyPass="MyKeyPass"

A: try:
tasks.whenTaskAdded { task ->
    if (task.name == 'packageRelease') {
        task.dependsOn readPasswordFromInput
    }
}

with your readPasswordFromInput task.
UPDATED:
In this way you can see that following code works.
def runTasks = gradle.startParameter.taskNames
if ('assemble' in runTasks || 'assembleRelease' in runTasks || 'a' in runTasks || 'aR' in runTasks) {
    android.signingConfigs.releaseSign.storeFile = file('/path/to/keystore')
    android.signingConfigs.releaseSign.storePassword = System.console().readLine('KeyStore Password: ')
    android.signingConfigs.releaseSign.keyAlias = ...
    android.signingConfigs.releaseSign.keyPassword = System.console().readLine('Alias Password: ')
    android.buildTypes.release.signingConfig = android.signingConfigs.releaseSign
}

and if you encounter build fail, it may be required to asign an empty keysign config on android.signingConfig:
android {
    ...
    signingConfigs {
        releaseSign
    }
    ...

A: Here is what I do.
task('readPasswordFromInput') << {
    def console = System.console()

    ext.keystorePassword = console.readLine('\n\n\n> Enter keystore password: ')

    android.signingConfigs.release.storePassword = ext.keystorePassword
    android.signingConfigs.release.keyPassword = ext.keystorePassword
}

tasks.whenTaskAdded { task ->
    if (task.name.matches("validateReleaseSigning")) {
        task.dependsOn('readPasswordFromInput')
    }
}

signingConfigs {
    debug {
        storeFile file("my-debug-key.keystore")
    }

    release {
        storeFile file("my-release-key.keystore")
        storePassword ""
        keyAlias "release_key"
        keyPassword ""
    }
}

A: Google recently added an official way to do this, see https://developer.android.com/studio/publish/app-signing.html#secure-shared-keystore
It may not answer my original question (ask for password), but I think it's the better way to simplify the deploy and keep the credentials safe.


text:
Q: Family tree... the genealogy What do we call a man who begins a family. Do we call him an antecedent or great-grand father or ancestor, a lineal antecedent? Or what?
Such as, there is a family Richard. Now, the family got its roots from a man's offspring, Richard. What would we call Richard?

A: You can use the word patriarch, and at least some people will know what you mean. The patriarchs from the Bible were the first men whose descendents eventually became the nation of Israel.


text:
Q: Using id as variable in querySelectorAll() I need to use an id as variable in querySelectorAll() as shown below.
var thismodal = "myModal";
var clicked_id,trueModalId;
function openModal(clicked_id) {
    trueModalId = thismodal + clicked_id;
    document.getElementById(trueModalId).style.display = "block";
    // var thisSlides = "mySlides" + clicked_id;
    if($('trueModalId').find('.modal-content').length) {
        alert(trueModalId);
    }

}

function showSlides(){
    var slides = document.querySelectorAll('trueModalId >.modal-content > .mySlides');
}

How do I make this work?

A: Just like every variable and string concatenation in js works. You forgot the # as an indicator for id though
var trueModalId = "myModal";
var slides = document.querySelectorAll('#' + trueModalId + ' >.modal-content > .mySlides');


text:
Q: Data incomplete while transferring from PHP to Java While trying to send a long string (a Base64 encoded image) from php to java only a fraction of the data is passed over. When I tested the application on my localhost apache server the string was sent over completely and the application worked properly. But when I migrated the code to an external server, only a fraction of the data was received in Java. When I output the data in the browser the long string does display properly.
This is the code I have used to send the data:
//get the data from mysql result
while($row = mysqli_fetch_assoc($result))
{
    // get the fotopath
    $fotoRow = mysqli_fetch_array ( $fotoResult, MYSQL_NUM );
    $foto = $fotoRow[0];

    //replace backslashes
    $fotoFormatted = $foto; //str_replace($backslash, $slash, $foto);

    //get the picture data
    $im = file_get_contents("http://www.mywebsite.com" . $fotoFormatted, true);

    //encode the picture data
    $imdata = base64_encode($im);

    //add the encoded string to the data array
    $row ['foto'] = $imdata;
    $output[] = $row;
}

//output the data as a json array
print(json_encode($output))

This is the code I have used to receive the data:
//get the url to the script to connect with
String link = "http://mywebsite/script.php";

//get the data to send to the script
String data = URLEncoder.encode("userid", "UTF-8") + "="
                + URLEncoder.encode(userid, "UTF-8");

//make a new HttpURLConnection
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);

//make a new OutputStreamWriter with the HttpURLConnection
OutputStreamWriter wr = new OutputStreamWriter(
                   conn.getOutputStream());

//write the data and flush the remaining data
wr.write(data);
wr.flush();

//make a new BufferedReader with the given connection
BufferedReader reader = new BufferedReader(new InputStreamReader(
               conn.getInputStream()));

//define variables
JSONArray jsonArray = null;
String line = null;

//read the data from the server
while ((line = reader.readLine()) != null) {
        jsonArray = new JSONArray(line);
        }

//disconnect the connection
conn.disconnect();

//return the data for further use
return jsonArray;

My question is: Why is the data from the external server incomplete while the data received from the local server is complete and what can I do to solve this problem.

A: I have found the solution, the problem was that spaces were included in the path of some files(pretty bad design i think), because of this a 404 page was being encoded in base64 and in this way the incorrect data was added. in my local server application i had not configured a 404 page so it would just return null and i had a fallback to handle that situation. I replaced all spaces with %20 and the errors were resolved.


text:
Q: Apps Script Properties Service All
I have a Google Sheet linked to a Google Form for data collection and apps script within sheets.I am assigning account numbers belonging to a specific range for every account type to every form submission such that nobody has same account numbers.
I am using documentProperties to store a Key(account type), value(account number) pair in Google Apps script. Recently after few months of smooth functioning, I had to re-authorize the app script because I changed my password. Since then, all my documentProperties have been reset to default values and I am facing the issue of people getting assigned same account numbers.
Has this happened with someone else? I seek help from people who have used Properties Service feature of Google Apps Script.


text:
Q: How to merge data in columns in linq I have a source data in xml format like;
    <plans>
    <plan>
        <id>1</id>
        <name>Test1</name>
        <description>Description for test 1</description>
    </plan>
    <plan>
        <id>2</id>
        <name>Test2</name>
        <description>Description for test 2</description>
    </plan>
    <plan>
        <id>3</id>
        <name>Test3</name>
        <description>Description for test 3</description>
    </plan>
   </plans>

And I have details data which is also in xml format like;
    <plandetails>
    <detail>
        <planid>1</planid>
        <properties>
            <propery>
                <name>Pname1</name>
                <value>Test1Property1</value>
                <name>Pname2</name>
                <value>Test1Property2</value>
                <name>Pname3</name>
                <value>Test1Property3</value>
            </propery>
        </properties>
    </detail>
    <detail>
        <planid>2</planid>
        <properties>
            <propery>
                <name>Pname1</name>
                <value>Test2Property1</value>
                <name>Pname2</name>
                <value>Test2Property2</value>
                <name>Pname3</name>
                <value>Test2Property3</value>
            </propery>
        </properties>
    </detail>
    <detail>
        <planid>3</planid>
        <properties>
            <propery>
                <name>Pname1</name>
                <value>Test3Property1</value>
                <name>Pname2</name>
                <value>Test3Property2</value>
                <name>Pname3</name>
                <value>Test3Property3</value>
            </propery>
        </properties>
    </detail>
</plandetails>

I am trying to get result like;
Name           Test1                   Test2                    Test3                   ....  Test n
Description Description for test 1  Description for test 2   Description for test 3  ....  Description for test n
Pname1       Test1Property1          Test2Property1           Test3Property1          ....  TestnProperty1
Pname2       Test1Property2          Test2Property2           Test3Property2          ....  TestnProperty2
Pname3       Test1Property3          Test2Property3           Test3Property3          ....  TestnProperty3
.
.
.
.

How can I achieve this with LINQ?
Thanks in advance.

A: Depends on the language.  In C# this looks like a job for Zip() or similar.  But you have to get the data out of XML first.

A: I merged the data into a manageable structure but you'll need to format the output.
There really isn't anything special here.  I simply used linq to join on plan.id == detail.planid and stuck the results in an anonymous object.
var xmaster = XElement.Parse(
    @"<plans>
    <plan>
        <id>1</id>
        <name>Test1</name>
        <description>Description for test 1</description>
    </plan>
    <plan>
        <id>2</id>
        <name>Test2</name>
        <description>Description for test 2</description>
    </plan>
    <plan>
        <id>3</id>
        <name>Test3</name>
        <description>Description for test 3</description>
    </plan>
    </plans>");

var xdetail = XElement.Parse(
    @"<plandetails>
        <detail>
            <planid>1</planid>
            <properties>
                <propery>
                    <name>Pname1</name>
                    <value>Test1Property1</value>
                    <name>Pname2</name>
                    <value>Test1Property2</value>
                    <name>Pname3</name>
                    <value>Test1Property3</value>
                </propery>
            </properties>
        </detail>
        <detail>
            <planid>2</planid>
            <properties>
                <propery>
                    <name>Pname1</name>
                    <value>Test2Property1</value>
                    <name>Pname2</name>
                    <value>Test2Property2</value>
                    <name>Pname3</name>
                    <value>Test2Property3</value>
                </propery>
            </properties>
        </detail>
        <detail>
            <planid>3</planid>
            <properties>
                <propery>
                    <name>Pname1</name>
                    <value>Test3Property1</value>
                    <name>Pname2</name>
                    <value>Test3Property2</value>
                    <name>Pname3</name>
                    <value>Test3Property3</value>
                </propery>
            </properties>
        </detail>
    </plandetails>");

var merged = from m in xmaster.Descendants("plan")
            join d in xdetail.Descendants("detail")
                on (int)m.Element("id") equals (int)d.Element("planid")
            select new
            {
                Name = m.Element("name").Value,
                Description = m.Element("description").Value,
                Pnames = d.Descendants("propery").Elements().Where(n => n.Name == "value").Select(v => v.Value)
            };


text:
Q: Adding one JOIN statement changes the value of precedent sum I have this query in sqlfiddle which gives the correct values
But when I add one left joined table the result changes(I tried with right and inner join same bad result) and it's there in  this sqlfiddle
What I miss in this query when adding stockdata?
There is 3 tables defmatiere, ingredients and stockdata
When I use this query:
SELECT dm.nom,SUM(IF(dm.id=ig.matid AND ig.matcuisine= 3,ig.qty,0)) AS bisused
FROM ingredient AS ig
LEFT JOIN DefMatiere AS dm ON ig.matid=dm.id AND ig.matcuisine=3
WHERE dm.id=ig.matid AND dm.type=1 GROUP BY dm.nom

I get the corrects sums
But When I use this query
SELECT dm.nom,SUM(IF(dm.id=ig.matid AND ig.matcuisine= 3,ig.qty,0)) AS bisused,
SUM(DISTINCT IF(dm.id=sd.matid, sd.quantite,0)) AS bisbought
FROM ingredient AS ig
LEFT JOIN DefMatiere AS dm ON ig.matid=dm.id AND ig.matcuisine=3
LEFT JOIN StockData AS sd ON sd.matid=dm.id
WHERE dm.id=ig.matid AND dm.type=1 GROUP BY dm.nom

The sum of bisused is doubled the rest is correct


text:
Q: Sync call in c# I have Following API Call in c# and I want to make it Synchronous and it should wait till it comes backs from other modules where delete logic is performed.

A: I belive the following code is your problem: CallExternalServiceAsync(..)
It should return a task, which you can await if you declare your function async. Otherwise, if you are just interested in waiting, you may call CallExternalServiceAsync(...).Wait(), assuming that it returns a Task.

A: As stated on comments, you might return a Task instead a void and perform the call of the CallExternalServiceAsync method with the await, assuming it's awaitable.
public async Task CallDeleteOrderApi()
{
    var responseMsg = await CallExternalServiceAsync(_apiPath, _validatePath, requestHeader);
}

Have a look at this question which explains how and why using async Task.
Basically, just specify async void return on method declaration when it's on an Event (for example frm_Load on WinForms). On custom methods, always declare it as async Task if you would just return a void (which is actually returning a Task) and async Task<int> if you, for example, want to return an int.


text:
Q: removing negative numbers from a list without creating an new one In this task I can only write the function and the rest of the code is given, so the original list l in the function should be changed without creating a new one. However, as I understood it when I already read through similar questions, this is not a good idea at all.
My try looked like this:
import random

def removeNegatives(listOfIntegers):
   for i in listOfIntegers:
        if i < 0:
            listOfIntegers.remove(i)

#code can not be changed from here on!

l = []

for i in range(0, random.randint(15,25)):
  l.append(random.randint(-15,15))

print ("Before:", l)
removeNegatives(l)
print ("After:", l)

A: As you need to change the list in place, you can loop in reverse to avoid affecting the order while poping elements:
def removeNegatives(listOfIntegers):
    for pos in range(len(listOfIntegers), 0, -1):
        if listOfIntegers[pos-1] < 0:
            listOfIntegers.pop(pos-1)

example output:
Before: [15, 7, -1, 3, -6, -2, 10, -1, 4, 5, -10, -8, 9, 9, 13, -11, 1, -4, -9, -15, -8, 3, 1]
After: [15, 7, 3, 10, 4, 5, 9, 9, 13, 1, 3, 1]

NB. it is more efficient to change the list only once, you can use the following code to overwrite the full list with new (filtered) elements:
def removeNegatives(listOfIntegers):
    listOfIntegers[:] = filter(lambda i: i>0, listOfIntegers)


text:
Q: Cannot apply CSS on angularjs Dialog I am creating a mobile application, where when you click on a button and a dialog window pops up. My problem is that this window is not responsive, and I cannot change its CSS.
Here's the code:
Controller.js
.controller('jargonController', ['$scope','$mdDialog','$mdMedia',function ($scope, $mdDialog, $mdMedia){

 $scope.status = '  ';

  $scope.showTabwtr = function(ev) {
    $mdDialog.show({
      controller: DialogController,
      templateUrl: 'templates/jargon/wtr.tmpl.html',
      parent: angular.element(document.body),
      windowClass: 'center-modal',
      targetEvent: ev,
      clickOutsideToClose:true
    })
        .then(function(answer) {
          $scope.status = 'You said the information was "' + answer + '".';
        }, function() {
          $scope.status = 'You cancelled the dialog.';
        });
  }

Index.html

Template

CSS
.modall {

  margin: auto;
  position: relative;
  max-width: 200px;
  max-height: 80px;
  background: transparent;
}

A: $scope.showTabwtr = function(ev) {
    $mdDialog.show({
      controller: DialogController,
      templateUrl: 'templates/jargon/wtr.tmpl.html',
      parent: angular.element(document.body),
      windowClass: 'center-modal',
      targetEvent: ev,
      cssClass: 'your css name',
      clickOutsideToClose:true
    })

use this cssClass property


text:
Q: binding nested viewmodels: knockout I have nested ViewModels where the MainViewModel holds the instance of the nested VMs.
The code the for the same is here: http://jsfiddle.net/nayanakalkur/2YCsN/19/
view code:

     Back

VM code:
var VM;
$(document).ready(function () {
    VM = new MainViewModel();
    ko.applyBindings(VM,document.getElementById("familyDiv"));
    ko.applyBindings(VM.productModel, document.getElementById("subFamilyAccProduct"));
    FetchProductFamiliesForProductsKO();
});

function FetchProductFamiliesForProductsKO() {
    var data=[{family: 'family1'},{family:'family2'},{family:'family3'}];

    for (var i = 0; i < data.length; i = i + 1) {
        var fam = data[i].family;
        console.log(fam);
        VM.AddProducts(fam, null, fam);
    }
};

ProductMenu= function(name, subProductsMenu1, selectedMenu) {
    var self= this;
    self.productname = ko.observable(name);
    self.submenu = ko.observableArray([]);
    self.selectedProductName = ko.observable();
};

ProductSubMenu=function() {
    var self = this;
    self.submenuName = ko.observable();
    self.submenu2 = ko.observableArray([]);
    self.selectedSubMenuName = ko.observable();
};

ProductSubMenu2= function() {
    var self = this;
    self.submenu2Name = ko.observable();
    self.properties = ko.observableArray([]);
    self.selectedSubMenu2Name = ko.observable();
};

Properties= function() {
    var self = this;
    self.pName = ko.observable();
    self.shortDesc = ko.observable();
    self.longDesc = ko.observable();
    self.additionalDocs = ko.observableArray([]);
};

function MainViewModel() {
    var self= this;
    self.productModel = new ProductMenu();
    self.subMenuModel = new ProductSubMenu();
    self.submenu2Model = new ProductSubMenu2();
    self.propertyModel = new Properties();
    self.AllProductsModel = ko.observableArray([]);

    //if true- show family products, hide sub family products
    self.ReturnToFamilyProduct = ko.observable(true);
    self.ShowSubMenu = ko.observable(false);
    self.showSubMenu2 = ko.observable(false);
    self.ShowBackBtnOnSubMenuClick = ko.observable(false);
    self.IfDocumentsPresent = ko.observable(true);

    //to add product to products array
    self.AddProducts = function (name, subProductsMenu1, selectedMenu) {
        this.AllProductsModel.push(new ProductMenu(name, subProductsMenu1, selectedMenu));
    };

    self.GetSubFamilyForProducts = function (data, event) {
        this.ShowSubMenu = ko.observable(true);
        SubProductMenus1 = [];
        //this.ShowBackBtnOnSubMenuClick = ko.observable(true);
        var currentElement = data;
        $('#subFamilyDiv').show();
        $('#btnBackToFamily').html("back: "+currentElement.productname());
        self.productModel = new ProductMenu();
        self.productModel.productname = ko.observable(currentElement.productname());
        self.selectedProductName = ko.observable(currentElement.productname());
        var data=[{subFamily: 'subFamily1'},{subFamily:'subFamily2'},{subFamily:'subFamily3'}];

            $(data).each(function (index, subFamily) {
                var tt= data[index].subFamily;
                var temp = new ProductSubMenu();
                console.log("subfamily:"+ tt);
                temp.submenuName = tt;
                SubProductMenus1.push(temp);
            });

            self.productModel.submenu = ko.observable(SubProductMenus1);
            ko.utils.arrayForEach(self.AllProductsModel(), function (product) {
                if (product.productname() == currentElement.productname()) {
                    console.log("found"+ product.submenu().length);
                    product.submenu = ko.observable(SubProductMenus1);
                    console.log("found"+ product.submenu().length);
                }
            })

    };
}

The submenu defined under productModel is failing to bind.
Any help would be appreciated.
Thanks!

A: The submenu property contains no items. In this fiddle  I just add a fake item and the resuting view shows a  fakeSubMenu element. So I think you only have add items in the submenu  property and it will work.
This is what I done :
ProductMenu= function(name, subProductsMenu1, selectedMenu) {
    var self= this;
    self.productname = ko.observable(name);
    self.submenu = ko.observableArray([{subMenuName: 'fakeSubMenuName'}]);
    self.selectedProductName = ko.observable();
};

I hope it helps.
See fiddle


text:
Q: Bridge Rectifier Fails When AC Inputs are Shorted I am working on a design that involves powering a 3.3V microcontroller off a doorbell transformer but I am running into an issue with the bridge rectifier failing when the AC inputs to the rectifier are shorted.

There are two basic parts of the design. First, a full-wave bridge rectifier is used to convert the 21V AC supply from the doorbell transformer to roughly 26V DC. A switching regulator is used to deliver 3.3V for powering the microcontroller. A smoothing capacitor reduces the ripple created by the bridge rectifier. That part of the circuit is working as expected and the microntroller can be powered from the doorbell transformer.
The second part of the circuit is simple. To allow the doorbell to be used normally while powering the microcontroller, a switch shorts the AC inputs. This closes the circuit and powers the solenoid in the doorbell that sounds the chime. The issue I am running into is the bridge rectifier failing when the switch is pressed.
I would really appriciate any insight into why the bridge rectifier fails and how the circuit might be modified to prevent the failure.
Bridge rectifier datasheet: DF206ST-G

A: You should not be trying to run your power converter by wiring into the circuit across the doorbell switch. Instead you should be wiring directly across the output of the doorbell transformer.
As you have it now you are powering your converter through the impedance of the existing doorbell. Even you describe that as a solenoid which is an inductive load. When the door bell button is released there is a good chance of an inductive spike of high voltage that is taking out the diodes in your bridge.
This is a diagram of how the wiring for the circuit should be wired instead of tapping across the existing door bell button. Even with this corrected design it would be advisable to check if there are voltage spikes when the switch is released and design in appropriate high voltage spike clamping into your adapter circuit.

A: It's (barely) possible that the bridge rectifier is getting more voltage than it can withstand at the input when the switch is released, due to inductance of the doorbell coil. It would be a lot more likely if the bridge rectifier was rated at 200V.
In any case, you can put a bipolar TVS across the input and clamp any such spikes. Something like 50-100V is fine. Eg. 1.5KE82CA
Edit:
In fact, the 100uF capacitor you have there should absorb any spike, so I'm not convinced this is actually the problem. Perhaps there is an extra ground or something like that. Your added ground may be causing an issue if it is to earth and there is something else similar running from the same transformer.

A:
I would really appriciate any insight into why the bridge rectifier fails and how the circuit might be modified to prevent the failure.

Probably due to the inductive "kick" when the switch is opened.

simulate this circuit – Schematic created using CircuitLab
Figure 1. (a) The basic doorbell. (b) The deluxe illuminated doorbell. (c) The deluxe monitored bell-push.
With the addition of a lamp and LDR (light-dependent resistor) you get what you require without any of the problems of tying two power-supplies together, mixing AC and DC and interfacing a solenoid with a sensitive micro-controller input.
You would need to do some tests to see if the LDR would pull switch at the right point - checking at night and bright sunlight if there is any chance the sensor will be exposed to ambient light.
The capacitor is there to filter out any flicker from the lamp but is probably not required due to the thermal response of an incandescent lamp and the sluggish response of the LDR.

A: It is almost certain that the indictive kick from the solenoid is killing your bridge rectifier as others have pointed out.
However you need to understand why you can get enough energy to kill the bridge rectifier diodes.
The simple point contact switch used in the doorbell will bounce and it's opening an closing is not related to the AC mains cycle at all. Consider that the button is pushed and when released the current flow through the solenoid is at a maximum. This translates into a lot of energy, and certainly enough to cause the diodes reverse voltage to be exceeded.
One simple way to ensure that the energy stored in the solenoid is at a minimum when the button is released is to use a small Triac (you could even use a MOC 3021). I would assume that the solenoid current is at maximum a few hundred mA so there is no problem in powering your MCU in series with e solenoid. Many doorbell pushbuttons are illuminated which results in current through the solenoid anyway.
The circuit below should be easily implemented with access only to the two wires that run to the pushbutton (which I assume may be a limiting factor for you).

simulate this circuit – Schematic created using CircuitLab
The pushbutton fires the Triac at any point in the AC wave, but once conducting the Triac will only turn off when the Solenoid current reaches close to zero. R3/C1 form a snubber and so there should be almost zero inductive kick as the Triac may have a very low holding current (typically in the 0.5 - 4 mA range depending on what you use).
It is worth noting that the supply to your MCU will potentially fall to brownout if the button is held closed ….I assume you are not concerned by this, but you certainly could increase the value of the capacitor to provide a longer holdup time.

A: There is no inductor energy release problem here!  as it will be absorbed by the transformer windings.
The problem is that after the short (created by closing the switch) there is no current getting to the input of the bridge rectifier.  To solve it just move the switch across the bridge rectifier input terminals and connect a resistor and a capacitor across the switch so the bridge rectifier is always supplied by the secondary of the tranny.  The resistor will absorb any spikes, discharge the capacitor and the cap will continue to supply the rectifier whilst the bell button is pressed.

A: You are shorting your AC mains as a means to trigger your circuit. When the button is pressed the circuit discharging the power in your smoothing capacitor back through your bridge rectifier, which is doubling the voltage across the diodes. You basically need a new circuit design.

A: Not obvious why the bridge would electrically fail (see notes at end) - it should have about 60V across it, even when the switch opens.
In your arrangement the power will fail when the switch is pressed.
The series zener below means that you still get power when the button is pressed.
You don't need a bridge really, assuming your curent drain is small, a half wave (single diode) will do. It does need to be a 1N4007 (1000V) as there can be a wicked flyback voltage pulse when the switch opens (+ve). When the switch opens on -ve half cycles the flyback energy goes into C1, which must be big enough to absorb it without the voltage rising too high. You should check this before connecting the regulator.
Note that the bell must draw enough current to supply your load. If it's an electronic "bell" that might not be true, and you will need to put a lamps or resistor across the bell to ensure enough current to the load.

simulate this circuit – Schematic created using CircuitLab
Note that bell transformer have a very high leakage reactance L1, so that they can be safely short circuited without excess current. So unlike normal transformers, they are more of a constant current than a constant voltage.

About the flyback:
When the switch opens, the bell+leakage-reactance current will continue to flow at the same level. If it is 1A when the switch opens, it stays at 1A, and decreases from there. It does not magically become a high current surge.
With a bridge, it will flow into the 100uF cap, whether +ve or -ve.
Now the 100uF cap might be too small, and Vcap will rise too high, but this will damage C or the regulator, not a 600V bridge.
With a half-wave rectifier, the flyback will be a very high -ve voltage if the switch opens on -ve half cycles. On +ve cycles, it will flow through the diode into C1 as above.

Here is a variant with a simple regulator, if your drain is low e.g 10mA. Since I use 1 zener for two functions - at different current, the voltage will go up when the button is pressed, so it might be better to make 5V for an ldo on your mcu board, than to make 3.3V directly.

simulate this circuit


text:
Q: executor memory setting in spark I made standalone cluster and wanted to find the fastest way to process my app.
My machine has 12g ram. Here is some result I tried.
Test A (took 15mins)
1 worker node
spark.executor.memory = 8g
spark.driver.memory = 6g

Test B(took 8mins)
2 worker nodes
spark.executor.memory = 4g
spark.driver.memory = 6g

Test C(took 6mins)
2 worker nodes
spark.executor.memory = 6g
spark.driver.memory = 6g

Test D(took 6mins)
3 worker nodes
spark.executor.memory = 4g
spark.driver.memory = 6g

Test E(took 6mins)
3 worker nodes
spark.executor.memory = 6g
spark.driver.memory = 6g

*

*Compared Test A, Test B just made one more woker (but same memory spend 4*2=8) but It made app fast. Why it happened?

*Test C, D, E tried to spend much more memory than it had. but It worked and even faster. is config memory size just for limiting edge of memory?

*It does not just as fast as adding worker nodes. How should I know profit number of worker and executor memory size?

A: On TestB, your application was running in parallel on 2 CPUs, therefore the total amount of time was almost a half.
Regarding memory - memory setting defines an upper limit Setting a small amount will make your. app to perform more GC, and if eventually your heap gets full, you'll receive an OutOfMemoryException.
Regarding the most suitable configuration - well, it depends. If your task does not consume much RAM - configure Spark to have as much executors as your CPUs.
Otherwise, configure your executors to match the appropriate amount of RAM required.
Keep in mind that those limitations should not be constant, and might be changed by your application requirements.


text:
Q: Dynamic Form Validation in React Native For Form Validation, Instead of using a package I tried to build one myself. So No matter how many fields you have, the validation gets added automatically.
But there is one MINOR issue.
Since the set state is async, I'm only able to get the last typed value after typing one more lettter.
For Example : If I need to show an error "Password must contain atleast 6 characters" , This error gets displayed. But it only goes away if you type the 7th character.
Same with other fields aswell.
I am checking the validation on the onChangeText and onBlur , I also tried with onKeyPress.
Any solution is apreciated.
Here is the code:  I have removed the styles etc. So this code should work for you out of the box.
import React, { useState, useRef } from 'react';
import { Text, View, TextInput } from 'react-native';

const Signup = ({}) => {
   const inputRef = useRef([]);
   const [inputs, setInputs] = useState([
      { id: 0, placeholder: 'First Name', name: 'firstName', type: 'text', hasError: false, errMessage: '' },
      { id: 1, placeholder: 'Last Name', name: 'lastName', type: 'text', hasError: false, errMessage: '' },
      { id: 2, placeholder: 'Email', name: 'email', type: 'email', hasError: false, errMessage: '' },
      { id: 3, placeholder: 'Password', name: 'password', type: 'password', mhasError: false, errMessage: '' },
      {
         id: 4,
         placeholder: 'Confirm Password',
         name: 'confirmPassword',
         type: 'password',
         hasError: false,
         errMessage: '',
      },
   ]);

   const [fields, setFields] = useState({
      firstName: '',
      lastName: '',
      email: '',
      password: '',
      confirmPassword: '',
   });

   const handleChange = (text, fieldName, id, type) => {
      setFields(currentValue => ({
         ...currentValue,
         [fieldName]: text,
      }));
      validateForm(fieldName, id, type);
   };

   const validateForm = (fieldName, id, type) => {
      const ID = id;
      const newInput = [...inputs];

      if (type === 'text') {
         if (fields[fieldName].length === 0 || fields[fieldName] === '') {
            newInput[ID].errMessage = 'Please fill the field';
            newInput[ID].hasError = true;
         } else if (fields[fieldName].length < 3) {
            newInput[ID].hasError = true;
            newInput[ID].errMessage = 'Must be more than 2 letters';
         } else {
            newInput[ID].errMessage = '';
            newInput[ID].hasError = false;
         }
      }
      if (type === 'email') {
         if (fields[fieldName].length === 0 || fields[fieldName] === '') {
            newInput[ID].errMessage = 'Please fill the field';
            newInput[ID].hasError = true;
         } else if (
            !fields[fieldName].match(
               /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
            )
         ) {
            newInput[ID].hasError = true;
            newInput[ID].errMessage = 'Invalid Email';
         } else {
            newInput[ID].errMessage = '';
            newInput[ID].hasError = false;
         }
      }
      if (type === 'password' && fieldName === 'password') {
         if (fields[fieldName].length === 0 || fields[fieldName] === '') {
            newInput[ID].errMessage = 'Please fill the field';
            newInput[ID].hasError = true;
         } else if (fields[fieldName].length < 6) {
            newInput[ID].hasError = true;
            newInput[ID].errMessage = 'Your password must be at least 6 characters';
         } else if (fields[fieldName].search(/[a-z]/i) < 0) {
            newInput[ID].hasError = true;
            newInput[ID].errMessage = 'Your password must contain at least one letter.';
         } else if (fields[fieldName].search(/[0-9]/) < 0) {
            newInput[ID].hasError = true;
            newInput[ID].errMessage = 'Your password must contain at least one digit.';
         } else {
            newInput[ID].errMessage = '';
            newInput[ID].hasError = false;
         }
      }
      if (type === 'password' && fieldName === 'confirmPassword') {
         if (fields['confirmPassword'] !== fields['password']) {
            newInput[ID].errMessage = "Password doesn't match";
            newInput[ID].hasError = true;
         } else {
            newInput[ID].errMessage = '';
            newInput[ID].hasError = false;
         }
      }
      setInputs(newInput);
   };

   return (
      <View style={{ paddingTop: 90 }}>
         <View>
            {inputs &&
               inputs.map((value, index) => (
                  <View key={index}>
                     <TextInput
                        onChangeText={text => {
                           handleChange(text, value.name, value.id, value.type);
                        }}
                        onBlur={() => validateForm(value.name, value.id, value.type)}
                        placeholder={value.placeholder}
                        ref={input => (inputRef.current[value.id] = input)}
                     />
                     {value.hasError && <Text style={{ color: 'red', marginTop: 3 }}>{value.errMessage}</Text>}
                  </View>
               ))}
         </View>
      </View>
   );
};

export default Signup;

A: you are trying to validate the form in a synchronous way but as you mentioned, the setState is asynchronous.
you are using React Functional Component then you should think about The principle of reactivity and use hooks in a proper way.
It means first you should set the fields values in the handler and then listen to the fields values change using useEffect and then validate the form:
// input handler. set field values
const handleChange = (text, fieldName, id, type) => {
  setFields(currentValue => ({
     ...currentValue,
     [fieldName]: text,
  }));
};

// new form validator that doesn't need arguments and should check all fields
// errors and set inputs state when one ore more fields have errors
const validateForm = () => {
  // check all inputs error here and then
  // setInputs(...)
};

// the hook part. it runs every time the filds values changes
useEffect(() => {
  validateForm();
}, [fields]);

if you don't want to change your form validator function you can define new useState and keep the latest changed field's id in it and change this state when a field changed then run useEffect:
const [latestChangedFieldId, setLatestChangedFieldId] = useState('');

// input handler. set field values and change the latest field changed key
const handleChange = (text, fieldName, id, type) => {
  setFields(currentValue => ({
     ...currentValue,
     [fieldName]: text,
  }));

  setLatestChangedFieldId(id)
};

// the hook part. it runs every time the filds values changes
useEffect(() => {
  const currentChangedField = inputs.find((input) => input.id === latestChangedFieldId)

  validateForm(currentChangedField.name, currentChangedField.id, currentChangedField.type);
}, [latestChangedFieldId]);

but you really don't need to get name, id, and type in form validator function with you can track current changing field with only its id property


text:
Q: Event Thrown when Filesize is Exceeded Does DropZone throw an event when you have a max filesize setup and drop a file onto it that exceeds that limit?  I have tried the following events but they do not seem to get triggered.
error, reset, addedfile, removedfile, dropped.
Currently our implementation doesn't do anything when you drop a file too large onto the zone.  We would like to provide feedback that the file exceeded our max limit for file size.

A: It doesn't throw any event, it will return you an error message.
Code snippet from dropzone.js
Dropzone.prototype.accept = function(file, done) {
  if (file.size > this.options.maxFilesize * 1024 * 1024) {
    return done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize));
  }
  .
  .
  .
}

http://www.dropzonejs.com/#config-dictFileTooBig
To throw the error message add maxFilesize: 2, // MB to the config
http://www.dropzonejs.com/#configuration
previewTemplate must contain div element with "dz-error-message" class
previewTemplate: '

✔

✘

'

http://www.dropzonejs.com/#layout

A: var dropZoneDiv = new Dropzone("div#DropZoneDiv", {
        url: "UPLOAD",
        previewTemplate: document.querySelector('#preview-template').innerHTML,
        thumbnailHeight: 100,
        thumbnailWidth: 100,
        addedfile: function (file) {
            if (file.size > (1024 * 1024 * 50)) // not more than 5mb
            {
                this.removeFile(file);
                abp.message.error("Only 50 mb file size is allowed");
            }
        },


text:
Q: Instagram API app after june 1 2016 The Instagram new API policy have become super strict. They are not allowing fetching public content at all. We are literally following all Instagram policies and still cant get approval of public_content.
Is there any workaround or any possibility of fetching the data.
This is the response that I have recieved from instagram

General issues:
Policy Violation (Ad network, Influencer network, Other related): Your
  app should not attempt to build an ad network on Instagram, nor
  transfer any data that you receive from us (including anonymous,
  aggregate, or derived data) to any ad network, data broker, influencer
  network, or other advertising or monetization-related service. In
  working to build a high quality platform, we ask that you comply with
  our Platform Policy
  (http://wwww.instagram.com/about/legal/terms/api/).

A: Yeah, they now grant permissions only to applications with some specific usage cases.
According to Instagram official website, these are:

*

*To help individuals share their own content with 3rd party apps

*To help brands and advertisers understand and manage their audience and digital media rights

*To help broadcasters and publishers discover content, get digital rights to media, and share media with proper attribution

Note that in order to get public_content permission, you need to fall under the 2nd or the 3rd use case. Otherwise, consider changing your application / service in such way that is now uses basic permission and acquires only your users' media.
There is no valid and legal possibility to fetch public data except for successful passing the Instagram permission review.
This official developer documentation page may be useful to you.

A: You need to enable scopes invividually for your client https://api.instagram.com/oauth/authorize?client_id=CLIENT_ID&redirect_uri=APPCALLBACK&access_token=ACCESSTOKEN&response_type=code&scope=public_content in your browser, using your values for the uppercase words? This should enable your registered client to work with the public_content scope.
https://api.instagram.com/oauth/authorize?client_id=xxxxx&redirect_uri=xxxxx&access_token=xxxxx&response_type=code&scope=public_content
your comment
Read the error message, did you supply a valid client-id from your instagram developer account. Did you setup a redirect_uri for that client? Do you authenticate to instagram to get an access token?
This worked for me this weekend. Double check the values you set in the url and call it directly in your browser.


text:
Q: Is it possible to kick off an app from another iphone app? I'd like to start up the App Store from within my iphone app. Is this possible - and how?
Thanks.

A: I believe this URL prefix will launch it.
 itms-apps://

Other apps also have URLs you can use to launch them. You can register your own as well.
http://www.mobileorchard.com/apple-approved-iphone-inter-process-communication/

A: As per this question on stackoverflow, it is not possible.
It may still be possible to communicate with a different app through a URL scheme, if that's what you want to do.  Read about that in this answer.


text:
Q: how to get value of object in javascript I have an object and I want to show its content.
{"text": "active    user
          active  user213123
          idle      user234234234
          loggedout  userafdadf"
},

I did Response = message.split(":")[1]; and I got:
"active    user
          active  user213123
          idle      user234234234
          loggedout  userafdadf"
},

then: var value = message.split("}")[0]; and I got:
"active    user
          active  user213123
          idle      user234234234
          loggedout  userafdadf"

So now how can I get rid of "" so I can have the raw valu of text? and beside that is there any other way to retrive a value of the object? because this way seems crazy..
I put the whole object that I am fetching the "text" from that here: (thats what chrome debugger is showing after console log)
{
getResponseHeader: function ( key ){}
pipe: function ( /* STDone, STFail, STProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 4

    TextContent: "{"text": "active    user
                  active  user213123
                  idle      user234234234
                  loggedout  userafdadf"}"

Suppose they are in message variable and then I did Response = message.TextContent; and after console.log I received:
 TextContent: "{"text": "active    user
              active  user213123
              idle      user234234234
              loggedout  userafdadf"}"

Now I want the raw value of text

A: Why not Just replace it?
myString = myString.replace(/["]/g,'')
console.log(myString);
//or
alert(myString);

In case you want to see it live http://jsfiddle.net/PwGcr/

A: var myObj = {text: "active    user
             active  user213123
             idle      user234234234
             loggedout  userafdadf"
            };

var myText = myObj.text

Just access it like a property on the object

A: TextContent: "{"text": "active    user
          active  user213123
          idle      user234234234
          loggedout  userafdadf"}"

Here the TextContent property is a string, not a JSON object. You should use JSON.parse(message.TextContent) to convert string to JSON object.
var jsonMessage = JSON.parse(message.TextContent);
alert(jsonMessage.text); // will alert the value of **text** property.

Refer http://jsfiddle.net/5MtNf/1/.

A:  var jsonObj={"text": "active  user active  user213123 idle user234234234 loggedout  userafdadf"};
 alert('json obj '+jsonObj["text"]);

A: It's a JSON string. Instead of trying string manipulation on it - parse it into JSON object and use Object's property e.g.
 var obj = JSON.parse(message);
 alert(obj.text);

A: You can use following function to remove all characters from your string.
String.prototype.replaceAll = function(token, newToken, ignoreCase) {
  var _token;
  var str = this + "";
  var i = -1;

  if (typeof token === "string") {

    if (ignoreCase) {

      _token = token.toLowerCase();

      while ((i = str.toLowerCase().indexOf(token, i >= 0 ? i + newToken.length : 0)) !== -1) {
        str = str.substring(0, i) + newToken + str.substring(i + token.length);
      }

    } else {
      return this.split(token).join(newToken);
    }

  }
  return str;
};

A: To omit " from beginning of string you can use:
string.substr(1)

Take a look at this link for working with strings, but I suggest you for working with object look at this.
First way is bad coding style and not correct.

A: I guess you are dealing with some JSON string, if so, you have to turn it into a javascript structure in order to be able to query it :
function parseJSON(json) {
    return (new Function('return ' + json + ';'))();
}
var o = parseJSON('{"test":"some content"}');
o.test // "some content"

However, in your example, there is a comma at the end of the string, this may throw an error. Make sure to remove it before parsing.
Note that there are several ways to parse JSON, this one should work in all modern browsers : https://stackoverflow.com/a/18733016/1636522. Check this link to see which browsers currently support JSON.parse().


text:
Q: Tapestry5 - Show Tree component in the DOM I am using Tapestry 5 and this component to show a list of folders :
http://tapestry.apache.org/5.3/apidocs/org/apache/tapestry5/corelib/components/Tree.html
The problem is that there is only the root element that is shown in the DOM so I can't apply javascript listeners to the rest of the element. And I need to.
Do you have an idea of what to do ?

A: Looking at the coffee script here I can't see any clientside events being fired.
You might have to use the nodeSelected and nodeUnselected events serverside to send scripts to be executed on the client via JavascriptSupport.addScript(...)
eg:
public class MyPage {
   @Inject JavaScriptSupport jss;
   @InjectComponent Tree tree;

   void onNodeSelected(String nodeId) {
      jss.addScript(InitializationPriority.LATE, "alert('%s.%s selected');", tree.getClientId(), nodeId);
   }
   void onNodeUnselected(String nodeId) {
      jss.addScript(InitializationPriority.LATE, "alert('%s.%s un-selected');", tree.getClientId(), nodeId);
   }
}


text:
Q: Attempt at mimicking the python print function using variadic templates not working I came across variadic templates while reading a book and thought it would be pretty cool to implement a python style print function.
Here is the code.
#include <iostream>
#include <string>

#define None " "

template<typename T, typename... Tail>
void print(T head, Tail... tail, const char* end = "\n")
{
    std::cout << head << end;
    if constexpr (sizeof...(tail) > 0)
    {
        print(tail..., end);
    }
}

int main()
{
    // Error: no instance of function template "print" matches the argument list
    print("apple", 0, 0.0f, 'c', true);

    // Error: no instance of function template "print" matches the argument list
    print("apple", 0, 0.0f, 'c', true, None);
}

Expected result from those two function calls:
First:    Second:
apple     apple 0 0.0f 'c' 1
0
0.0f
'c'
1

Removing const char* end = "\n" from the function signature gets the code to compile, but I want that functionality of specifying the last parameter to state whether to print a newline.
Is this possible at all?

A: It is possible, but not in the way you have tried.
You could do something like the following (one possible solution in c++17):

*

*Provide an enum (Ending) which will be used to specify the way of
printing (i.e newline, with space, etc).

*Split function print and one of them will be used to print one argument at a
time, where we will check for the way of printing;

*The other print will be used to call the variadic
arguments
by the caller. Here we're using fold
expressions  to call
the first print overload.

Something like: (Live Demo)
enum struct Ending {  NewLine = 0, Space };

template<Ending end, typename Type>
void print(const Type& arg) noexcept
{
    if constexpr (end == Ending::NewLine)  {
        std::cout << arg << '\n';
    }
    else if constexpr (end == Ending::Space) {
        std::cout << arg << ' ';
    }
}

template <Ending end, typename... Args>
void print(const Args& ... args) noexcept
{
    (print<end>(args), ...);
}

Now you can specify, how to end the line
print<Ending::NewLine>("apple", 0, 0.0f, 'c', true);
print<Ending::Space>("apple", 0, 0.0f, 'c', true);

"You don't like the overload!?" Then we can make it inside a single print  function with help of an immediately invoking lambda function.
(Live Demo)
template <Ending end, typename... Args>
void print(const Args& ... args) noexcept
{
    ([] (Ending, const auto& arg) noexcept {
        if constexpr (end == Ending::NewLine) {
            std::cout << arg << '\n';
        }
        else if constexpr (end == Ending::Space) {
            std::cout << arg << ' ';
        }
    }(end, args), ...);
    //^^^^^^^^^^  ^^^^  ---> Invoke the lambda & expand the fold
}


text:
Q: How to call a method every 2 weeks in PHP without a Crontab I want to update the div in html to display different contents every week with just php and without the use of cron.
How will it be posssible to achieve it ? The following code is for activating the code every 2 month on the 10nth day
but I guess the logic will be different. If possible some hint or example will be great ! I will love to hear from you!
    // check if current day is 10th and month is an even number
if (date('d')==10 && date('m') % 2 == 0) {
    // get todays-date (format: yyyymmdd)
    $today = date('Ymd');
    // get info about last run
    $last_run = variable_get('my_last_run', 0);
    // check last run was not today
    if ($last_run!=$today) {
        // set last run to today
        variable_set('my_last_run', $today);

        /* Place your code here */

    }
}

A: I've just updated your example, now it will work every next Monday:
$weekInYearNumber = (int)date('W');
$weekDayNumber = (int)date('w');
if ($weekDayNumber === 1 && $weekInYearNumber % 2 == 0) {
    // Rest of your code.
}

A: If you can't or don't want to use a cron job for that (which would be the easiest and recommended solution), you can create a PHP script that spends most of the time sleeping, and wakes up to check the date and run whatever you need.
If you don't care about dates and just want to run it every two weeks, you can make it sleep like this:
 sleep(14*24*60*60);

Have your script execute your code after that, and put all that inside an infinite loop. Then just run the script from the console so it doesn't have an execution time limit.
Take into account that the script may stop running for different reasons, for example when servers reboot, so you should monitor the process and re-run it automatically if it's not running or on reboot.

A: This may work for you.
  function runEveryWeek(){
     sleep(/*for 2 weeks*/);
     runEveryWeek();
  }

A: With purpose to display different contents every week, you can use this
$week = (int)date('W');
$odd = ($week % 2) === 0;
if ($ood) {
    // First week.
} else {
    // Second week.
}

A: Are you sure ? Your web page will open for 2 month ?
You can apply one logic
Just save next cron date in database. so your logic will like
<?php

if($databaseDate == date()){
   //Perform acetion here
   // Save your next date here
}
?>

I hope this will solve your problem
If you don't want to do this then you can use PM2
For pm2 you need ssh access of the server.

A: If you want to do it quickly, you can count weeks since the first of january 2018 (because it was monday: any other year started with a monday will be ok), and then check if that number is odd or even:
      $diffBetweenNowAndFirstJan2018 = time() - strtotime("2018-01-01");
      $numberOfWeeksSinceFirstJan2018 = floor($diffBetweenNowAndFirstJan2018 / (60 * 60 * 24 * 7));
      $isNumberOfWeeksOdd = ($numberOfWeeksSinceFirstJan2018 % 2 == 1)

      if($isNumberOfWeeksOdd){
            // it's other week time
    }

In one line:
     if( ( (floor((time() - strtotime("2018-01-01")) / (60 * 60 * 24 * 7))) % 2 == 1) ){
            // it's other week time
    }

You should not use date('W') as Vladmir says, because between new year's eve you could get two "odd" week consecutively.


text:
Q: variable inside int in c giving exceptional output In below given program if I put n=0, then the program is giving right answer but if I write n instead of n=0, the program is giving me wrong answer. If I put k=10 then output is 94 but the correct answer is 55. Why it is adding additional 39?
int main(){
    // program to calculate the sum of 'n' numbers
    int i=1,k,n;
    printf("Enter number: ");
    scanf("%d",&k);
    do{
        n+=i;
        i++;
    }while(i<=k);
    printf("The sum is: %d",n);
    return 0;
}

A: Your loop is adding a value to the current value of n, but you never set the initial value of n.  That means its value is indeterminate, and reading an indeterminate value (in this case when you add to it), when the variable in question never had its address taken triggers undefined behavior.
Initialize n to 0 so you have a valid starting point.
int i=1, k, n=0;


text: Q: Which linux command can I check the full size of the VM? In which command can I check how big is my entire VM? I want to extend one of my disk with extra +40GB, but I'm not sure is there enough space? I need a linux command, thanks.


text:
Q: Graphviz non-overlapping tree I am trying to use Graphviz to produce a tree such as the following:

I have it almost working, as shown below:

My problems are the following:

*

*Subtrees should never overlap, but the PP tree and the (.) tree overlap.

*Subtrees should always be fairly regular, so that if there are multiple children, the edges should go to the left and right of the parent. Again, this does not work properly for the PP tree.

I have fixed (1) by using subgraph clusters, however, this introduces a few new issues. Namely, the edges are not straight, and I can't figure out how to hide the borders without leaving tons of empty space.

Is there a better way to force the tree formatting? It feels like it shouldn't be too unusual.
My code is below (generated by Python, sorry for unhelpful names):
graph {
    subgraph 0 {
        subgraph 1 {
            0 [label=ROOT group=0 shape=plain]
            subgraph 8 {
                1 [label=S group=1 shape=plain]
                subgraph 11 {
                    2 [label=NP group=2 shape=plain]
                    subgraph 15 {
                        3 [label=PRP group=3 shape=plain]
                        4 [label=I shape=plain]
                        3 -- 4
                        4 [label=I group=3]
                    }
                    2 -- 3
                    3 [label=PRP group=2]
                }
                subgraph 24 {
                    5 [label=VP group=5 shape=plain]
                    subgraph 28 {
                        6 [label=VBD group=6 shape=plain]
                        7 [label=solved shape=plain]
                        6 -- 7
                        7 [label=solved group=6]
                    }
                    subgraph 41 {
                        8 [label=NP group=8 shape=plain]
                        subgraph 45 {
                            9 [label=DT group=9 shape=plain]
                            10 [label=the shape=plain]
                            9 -- 10
                            10 [label=the group=9]
                        }
                        subgraph 63 {
                            11 [label=NN group=11 shape=plain]
                            12 [label=problem shape=plain]
                            11 -- 12
                            12 [label=problem group=11]
                        }
                        8 -- 9
                        8 -- 11
                    }
                    subgraph 77 {
                        13 [label=PP group=13 shape=plain]
                        subgraph 81 {
                            14 [label=IN group=14 shape=plain]
                            15 [label=on shape=plain]
                            14 -- 15
                            15 [label=on group=14]
                        }
                        subgraph 89 {
                            16 [label=NP group=16 shape=plain]
                            subgraph 93 {
                                17 [label=DT group=17 shape=plain]
                                18 [label=the shape=plain]
                                17 -- 18
                                18 [label=the group=17]
                            }
                            subgraph 102 {
                                19 [label=NN group=19 shape=plain]
                                20 [label=bus shape=plain]
                                19 -- 20
                                20 [label=bus group=19]
                            }
                            16 -- 17
                            16 -- 19
                        }
                        13 -- 14
                        13 -- 16
                    }
                    5 -- 6
                    5 -- 8
                    5 -- 13
                }
                subgraph 114 {
                    21 [label="." group=21 shape=plain]
                    22 [label="." shape=plain]
                    21 -- 22
                    22 [label="." group=21]
                }
                1 -- 2
                1 -- 5
                1 -- 21
            }
            0 -- 1
            1 [label=S group=0]
        }
    }
    ranksep=0.2
}

A: You are correct, Graphviz has "problems" with trees.  That said, here is your graph, with clusters (peripheries=0), splines=false, and margin=2:
graph {
  graph [splines=false]
    subgraph cluster_0 {
      peripheries=0
      margin=2
        subgraph cluster_1 {
            0 [label=ROOT group=0 shape=plain]
            subgraph cluster_8 {
                1 [label=S group=1 shape=plain]
                subgraph cluster_11 {
                    2 [label=NP group=2 shape=plain]
                    subgraph cluster_15 {
                        3 [label=PRP group=3 shape=plain]
                        4 [label=I shape=plain]
                        3 -- 4
                        4 [label=I group=3]
                    }
                    2 -- 3
                    3 [label=PRP group=2]
                }
                subgraph cluster_24 {
                    5 [label=VP group=5 shape=plain]
                    subgraph cluster_28 {
                        6 [label=VBD group=6 shape=plain]
                        7 [label=solved shape=plain]
                        6 -- 7
                        7 [label=solved group=6]
                    }
                    subgraph cluster_41 {
                        8 [label=NP group=8 shape=plain]
                        subgraph cluster_45 {
                            9 [label=DT group=9 shape=plain]
                            10 [label=the shape=plain]
                            9 -- 10
                            10 [label=the group=9]
                        }
                        subgraph cluster_63 {
                            11 [label=NN group=11 shape=plain]
                            12 [label=problem shape=plain]
                            11 -- 12
                            12 [label=problem group=11]
                        }
                        8 -- 9
                        8 -- 11
                    }
                    subgraph cluster_77 {
                        13 [label=PP group=13 shape=plain]
                        subgraph cluster_81 {
                            14 [label=IN group=14 shape=plain]
                            15 [label=on shape=plain]
                            14 -- 15
                            15 [label=on group=14]
                        }
                        subgraph cluster_89 {
                            16 [label=NP group=16 shape=plain]
                            subgraph cluster_93 {
                                17 [label=DT group=17 shape=plain]
                                18 [label=the shape=plain]
                                17 -- 18
                                18 [label=the group=17]
                            }
                            subgraph cluster_102 {
                                19 [label=NN group=19 shape=plain]
                                20 [label=bus shape=plain]
                                19 -- 20
                                20 [label=bus group=19]
                            }
                            16 -- 17
                            16 -- 19
                        }
                        13 -- 14
                        13 -- 16
                    }
                    5 -- 6
                    5 -- 8
                    5 -- 13
                }
                subgraph cluster_114 {
                    21 [label="." group=21 shape=plain]
                    22 [label="." shape=plain]
                    21 -- 22
                    22 [label="." group=21]
                }
                1 -- 2
                1 -- 5
                1 -- 21
            }
            0 -- 1
            1 [label=S group=0]
        }
    }
    ranksep=0.2
}

Giving:


text:
Q: Access to Java jar from Delphi There's Java jar binary library with described classes/functions making some usefull things (nothing special just plain Java - no JNI). No sources available.
There's a task to call those functions directly from Delphi. How to do that?
P.S. I know nothing about Delphi, but I know a lot about Java.

A: No you can't the way to go is JNI.
A few resources:

*

*Pacifiers series on using JNI from Delphi

*my Talking Java from Delphi talk at the EKON 11 conference

*the Delphi JNI questions on SO
Unless you have too much time on your hands, in which you could decompress the JAR files (they are ZIP files), write your own Java VM in Delphi and go from there ;-)

A: Does the jar file contains a main class that can be called from the command line? If so problem solved Delphi can execute command line operations. If there is no main class you can create one that calls the original jar file.

A: As a fast and simpler alternative to the low level, time consuming and error prone JNI from Delphi option, you should try Java for Delphi.
You'll be working with an object oriented API, would need a fraction of the code when compared to JNI and solve your Delphi/Java integration problem in a few hours instead of days, weeks (or months depending on the use case).
As an example, below is the public declaration of the Delphi type corresponding to java.lang.String with a code extract showing how it can be used.
Don't hesitate to contact J4SOFT, will be glad to help you.
Procedure Sample;
var
  AJavaString: Ijava_lang_String;
  AValue: string;
begin
  AJavaString := Tjava_lang_String.Create('A value');
  AValue :=  AjavaString.ToString;
  if AJavaString.StartsWith('A') then
  ...
end;

...
type
  Tjava_lang_String = class(Tjava_lang_Object, Ijava_lang_String)
  public
    constructor Create;
    constructor Create(p0: string);
    constructor Create(p0: Ijava_lang_StringBuffer);
    constructor Create(p0: Ijava_lang_StringBuilder);
    constructor Create(p0: TjxByte1DArray);
    constructor Create(p0: TjxByte1DArray; p1: Longint);
    constructor Create(p0: TjxByte1DArray; p1: Longint; p2: Longint);
    constructor Create(p0: TjxByte1DArray; p1: Longint; p2: Longint; p3: Longint);
    constructor Create(p0: TjxByte1DArray; p1: Longint; p2: Longint; p3: string);
    constructor Create(p0: TjxByte1DArray; p1: string);
    constructor Create(p0: TjxChar1DArray);
    constructor Create(p0: TjxChar1DArray; p1: Longint; p2: Longint);
    constructor Create(p0: TjxInt1DArray; p1: Longint; p2: Longint);
    function CharAt(p0: Longint): Char;
    function CodePointAt(p0: Longint): Longint;
    function CodePointBefore(p0: Longint): Longint;
    function CodePointCount(p0: Longint; p1: Longint): Longint;
    function CompareTo(p0: string): Longint;
    function CompareToIgnoreCase(p0: string): Longint;
    function Concat(p0: string): string;
    function ContentEquals(p0: Ijava_lang_StringBuffer): Boolean;
    class function CopyValueOf(p0: TjxChar1DArray): string;
    class function CopyValueOf(p0: TjxChar1DArray; p1: Longint; p2: Longint): string;
    function EndsWith(p0: string): Boolean;
    function Equals(p0: Ijava_lang_Object): Boolean; reintroduce;
    function EqualsIgnoreCase(p0: string): Boolean;
    class function Format(p0: string; p1: Tjava_lang_Object1DArray): string;
    function GetBytes: TjxByte1DArray;
    procedure GetBytes(p0: Longint; p1: Longint; p2: TjxByte1DArray; p3: Longint);
    function GetBytes(p0: string): TjxByte1DArray;
    procedure GetChars(p0: Longint; p1: Longint; p2: TjxChar1DArray; p3: Longint);
    function HashCode: Longint;
    function IndexOf(p0: Longint): Longint;
    function IndexOf(p0: Longint; p1: Longint): Longint;
    function IndexOf(p0: string): Longint;
    function IndexOf(p0: string; p1: Longint): Longint;
    function Intern: string;
    function IsEmpty: Boolean;
    function LastIndexOf(p0: Longint): Longint;
    function LastIndexOf(p0: Longint; p1: Longint): Longint;
    function LastIndexOf(p0: string): Longint;
    function LastIndexOf(p0: string; p1: Longint): Longint;
    function Length_: Longint;
    function Matches(p0: string): Boolean;
    function OffsetByCodePoints(p0: Longint; p1: Longint): Longint;
    function RegionMatches(p0: Longint; p1: string; p2: Longint; p3: Longint): Boolean;
    function RegionMatches(p0: Boolean; p1: Longint; p2: string; p3: Longint; p4: Longint): Boolean;
    function Replace(p0: Char; p1: Char): string;
    function ReplaceAll(p0: string; p1: string): string;
    function ReplaceFirst(p0: string; p1: string): string;
    function Split(p0: string): TjxString1DArray;
    function Split(p0: string; p1: Longint): TjxString1DArray;
    function StartsWith(p0: string): Boolean;
    function StartsWith(p0: string; p1: Longint): Boolean;
    function Substring(p0: Longint): string;
    function Substring(p0: Longint; p1: Longint): string;
    function ToCharArray: TjxChar1DArray;
    function ToLowerCase: string;
    function ToString: string;
    function ToUpperCase: string;
    function Trim: string;
    class function ValueOf(p0: Char): string;
    class function ValueOf(p0: Double): string;
    class function ValueOf(p0: Single): string;
    class function ValueOf(p0: Longint): string;
    class function ValueOf(p0: Int64): string;
    class function ValueOf(p0: Ijava_lang_Object): string;
    class function ValueOf(p0: Boolean): string;
    class function ValueOf(p0: TjxChar1DArray): string;
    class function ValueOf(p0: TjxChar1DArray; p1: Longint; p2: Longint): string;
    property CASE_INSENSITIVE_ORDER;
  end;

A: If you decompile binary file and produce some kind of a primitive java source, then you might consider using Java to Pascal converter. This should be doable without much trouble since you said that JAR is nothing special or complex.


text:
Q: Probability that Professor sends k correct addresses A Professor prepares n letters and puts them in envelopes and closes them. Then realizes he has to write addresses, now he randomly writes addresses in the closed envelopes. What is the probability that he sends exactly k letters with correct addresses?
Attempt: Fix the k correct letters. We can choose them in $ n\choose k$ ways. Total number of combination is n!. Could I say answer is $\frac {n\choose k} {n!}$.
I am just getting started with probability, please post answers considering this.

A: As you say, there are $\binom{n}k$ ways to choose which $k$ envelopes will be correctly addressed. That leaves $n-k$ envelopes, each of which must be incorrectly addressed. Thus, we need to know $d_{n-k}$, the number of ways to put an incorrect address on each of $n-k$ envelopes; the total number of ways to get exactly $k$ correctly addressed envelopes will then be $\binom{n}kd_{n-k}$, and the probability will be
$$\frac{\binom{n}kd_{n-k}}{n!}\;.$$
The number $d_\ell$ of ways of putting the wrong address on every one of $\ell$ envelopes is the number of derangements of $\ell$ things. As you can find at the link, it's known that
$$d_\ell=\ell!\sum_{i=0}^\ell\frac{(-1)^i}{i!}\;,$$
so the probability can be written
$$\frac{\binom{n}kd_{n-k}}{n!}=\frac{\frac{n!}{k!(n-k)!}(n-k)!\sum_{i=0}^{n-k}\frac{(-1)^i}{i!}}{n!}=\frac1{k!}\sum_{i=0}^{n-k}\frac{(-1)^i}{i!}\;.\tag{1}$$
As an example, suppose that $n=5$ and $k=3$. There are $\binom53=10$ ways to choose the $3$ envelopes that are to be correctly addressed, and there's clearly just one way to put wrong addresses on the remaining $2$ envelopes, so the desired probability is
$$\frac{10\cdot1}{5!}=\frac1{12}\;.$$
Formula $(1)$ gives the result
$$\frac1{3!}\sum_{i=0}^2\frac{(-1)^i}{i!}=\frac16\left(\frac1{0!}-\frac1{1!}+\frac1{2!}\right)=\frac16\left(1-1+\frac12\right)=\frac1{12}\;,$$
as it should.

A: The number of ways to fix $k$ points in a permutation of $n$ elements is (in your case, correctly assign $k$ addresses out of $n$ random choices) $$D_{n,k}=\frac{n!}{k!}\sum_{m=0}^{n-k}\frac{(-1)^m}{m!}$$
See rencontres numbers (also known as partial derangements).


text:
Q: React Native: Update Flatlist I was wondering how to update the flatlist after calling on my shuffle function. I have tried with the "ExtraData" tag inside the flatlist but haven´t got it to work. Any help would be appreciate!
    const Display = (props) => {
    return (
      <View>
        <View style={{ flexDirection: 'row' }}>
          <Image source={props.img} style={{ width: 200, height: 200 }} />
          <Text>{props.title}</Text>
        </View>
      </View>
    );
}

function Other({ navigation }) {

  function Shuffle(array){
    let x, y, z;
    for(x = 0; x<=2;x++){
      y = Math.floor(Math.random() * 3)
      z=array[x];
      array[x] = array[y]
      array[y] = z
    } console.log(array)
  }

  let Games = [
    { title: "Tic Tac Toe", img: require("./pics/tictac.png") },
    { title: "Connect Four", img: require("./pics/ConnectFour.jpg") },
    { title: "Monopoly", img: require("./pics/mono.png") },
  ];

  return (
    <View>
      <FlatList data={Games} renderItem={({ item }) => <Display source={item} title={item.title} img={item.img}> </Display>} />
      <Button title="Shuffle" onPress={() => {Shuffle(Games)}} />
    </View>
  );
}

A: Your function isn't returning the new shuffled array and assigning it to Games. Best practice would be to store your array in useState so when it updates it forces a re-render and shows correctly.
const [games, setGames] = React.useState([
{ title: "Tic Tac Toe", img: require("./pics/tictac.png") },
{ title: "Connect Four", img: require("./pics/ConnectFour.jpg") },
{ title: "Monopoly", img: require("./pics/mono.png") }]);

Then your onPress function could call your shuffle function with Games, return the new array, then update with something like setGames(returnedArray)
Edit: Sorry just realised you also need extraData prop on FlatList to tell it to re-render. You want to have a state like 'isShuffling' which will be set as your extraData value that you toggle every time you call your shuffle function. Simplest way to do that is change between true/false as the value itself is not really important:
const shuffleFunc = (array) => {
//(shuffle array and return)
...

setGames(returnedArray);
setIsShuffling(prev => !prev);

This should prompt the FlatList to render the new order. I personally got this working by editing the flatlist-simple snack on React Native's FlatList documentation.


text:
Q: TempleOS and multiple CD ROM drives? Does TempleOS v5.03 support Multiple CD-ROM drives? For example I have on

*

*Secondary Master: Supplemental Disk 1

*Primary Slave: Supplemental Disk 2

*Secondary Slave: Supplemental Disk 3

Can I mount them all at the same time? When I boot, I only see T: listed under DrvRep()? I see them all listed under ATARep(),

A: I don't believe it's currently possible, from the Demands Terry says,

Until super-simple block devices are available, hard disk should be placed at IDE primary master 1F0/3F6 and CD/DVD/Blu-ray should be placed at the IDE secondary master 170/376.  Currently, the wicked CIA plays musical chairs with controllers each time you make an install.  With tons of ugly code, I do my best.


text:
Q: how can i achieve the below output (python) Could you please help me reshape the data as below:
input DF
import pandas as pd
df=pd.DataFrame({'1': [14561,'X store','Sales Quantity',1],
                   '2': [14561,'X store','Net Sales',2],
                   '3': [16534,'Y store','Sales Quantity',2],
                   '4': [16534,'Y store','Net Sales',1]})

I would like to achieve the below op
store_code  store_name  sales_total    net_sales_total
14561       X store           1                     2
16534       Y store           2                     1

A: import numpy as np

df = df.transpose()
df.columns = ['store_code', 'store_name', 'sales', 'value']
df = df.pivot_table(index=['store_code','store_name'],
               columns = 'sales',
               values='value',
               aggfunc = np.sum)

df.columns = ['net_sales_total', 'sales_total']

Output
                         net_sales_total    sales_total
store_code  store_name
14561       X store          2                  1
16534       Y store          1                  2

Just notice that store_code and store_name in this case are multi index DataFrame's

A: df.unique and transpose
df=df.transpose()
for i in df.columns:
    print(df[i].unique())

A: df = df.transpose()
print('store_code' + str(df[0].unique()))
print('store_name' + str(df[1].unique()))
print('sales_total' + str(df[2].unique()))
print('net_sales_total' + str(df[3].unique()))


text:
Q: Stopping theorem for continuous martingale I've a question about a proof in my lecture notes. We want to prove the following theorem.

$M=(M_t)_{t\ge 0}$ be a $(P,F)$-martingale, where $P$ is a probability measure and $F=(\mathcal{F}_t)$ a filtration (right continuous). Further we assume that $M$ has right continuous paths and $\sigma,\tau$ are $F$-stopping times with $\sigma\le \tau$. If $\tau$ is bounded or if $M$ is uniformly integrable, then $E[M_\tau|\mathcal{F}_\sigma]=M_{\sigma}$

The proof consists of 3 steps.
1) Here we conclude: We can assume that $M_t=E[M_N|\mathcal{F}_t]$ for all $t\le N$ with some fixed  $N\in [0,\infty]$.
2) Since $\mathcal{F}_\sigma\subset \mathcal{F}_\tau$ and tower property of conditional expectation it's enough to prove: $E[M_N|\mathcal{F}_\tau]=M_\tau$.
3) Here we assume that $\tau$ has only countably many increasingly ordered values $t_n,n\in \mathbb{N}$ and use stopping theorem for discrete time to show $E[M_\tau]=E[M_N]$. For a general $\tau$ we approximate it from "above" and show similarly $E[M_\tau]=E[M_N]$
Now my questions:
to 2): Is this what is meant in 2): if $E[M_N|\mathcal{F}_\tau]=M_\tau$ is true, then
$$E[E[M_N|\mathcal{F}_\tau|\mathcal{F}_\sigma]=E[M_\tau|\mathcal{F}_\sigma]$$
The LHS is equal $E[M_N|\mathcal{F_\sigma}]$. Can I apply here 1) to get $E[M_N|\mathcal{F_\sigma}]=M_\sigma$? I'm not quiet sure, since in 1) we have a $t$, and here $\sigma$ is a stopping time.
to 3): Why does the Theorem follows if I just show $E[M_\tau]=E[M_N]$?
Thanks in advance for your help.
hulik

A: The second step says: if one proves $E[M_N|\mathcal F_\tau]=M_\tau$ for any bounded stopping time(so this is valid for $\sigma$) then for all stopping times $\sigma\leq \tau$ one has the statement of the theorem: $E[M_\tau|\mathcal F_\sigma]=M_\sigma$. So as you wrote $E[M_\tau|\mathcal F_\sigma]=E[E[M_N|\mathcal F_\tau]|\mathcal F_\sigma]=E[M_N|\mathcal F_\sigma]=|\mbox{our assumption!}|=M_\sigma$.
The third step seems very wierd, but you can finish yourself as the following, consider the sequence of ``simple'' stopping times $(\tau_n)_{n \geq 1}$ s.t. $\tau_n \to \tau+, n \to \infty$, so $M_{\tau_n}=E[M_N|\mathcal F_{\tau_n}]$ and take $A \in \mathcal F_\tau\subset \mathcal F_{\tau_n}$, hence $E[M_NI_A]=E[M_{\tau_n}I(A)]$. Now $(M_{\tau_n})_{n \geq 1}$ are uniformly integrable(think why!), so we need only take limit as $n\to\infty$ and we are done.
If you have further questions feel free to ask.


text:
Q: RegEx (?='\\').*$ - Trying to get username from domain\username I have a string like domainA\userNamePaul. I tried this regex (?='\\').*$ but the out put is same as input. I need to get the username without the domain. Any idea what I am doing wrong.

A: You need to use Positive lookbehind,
(?<=\\).*$

DEMO
Explanation:
(?<=                     look behind to see if there is:
  \\                       '\'
)                        end of look-behind
.*                       any character except \n (0 or more times)
$                        before an optional \n, and the end of the
                         string

A: I believe using regex is some kind of overkill here. You can simply split string by \:
string identity = "DOMAIN\\USER";
string user = identity.Split('\\').Last();

or even faster:
string user = identity.Substring(identity.IndexOf('\\') + 1);


text:
Q: How can (-1 >= sizeof(buffer)) ever be true? Program fail to get right results of comparison The program runs into impossible execution routine, where if( len >= sizeof(buff) ) should never be true in reality, however it happens. As is shown by the printf output len:-1__1024: len, whose value is -1, is larger than  sizeof(buff), which is 1024. It's amazing.
select return value -1 ,4
select: Interrupted system call
-1_0x66a1e0
len:-1__1024
*** glibc detected *** /home/fang/Desktop/work/fw: free(): invalid pointer: 0x000000000066a1e0 ***

The following is the execution code.
while (1) {
        if( len >= sizeof(buff) ) {   //here len==-1, sizeof(buff)==1024
            printf("len:%d__%d  %s\n", len, sizeof(buff), tmp1); //oops
            free(tmp1);
            tmp1 = buff;
        }
        len = get_next_event(&tmp1, sizeof(buff));
        printf("%d_%p\n",len, tmp1);
        if( len > 0 ){
            tmp = strtok_r(tmp1, "\n\r", &saveptr);
            // ignore following codes ......

I think the bug is resulted from the stack pollution, but it's hard to find out the secret. To mention more, I list the code of function get_next_event. Wish for your help ^_^
int get_next_event(char **buf, int len)
{
    struct timeval tv;
    int tmp;
    socklen_t sin_size;
    struct sockaddr_in client_addr;

    sin_size = sizeof(client_addr);
    FD_ZERO(&fdsr);
    FD_SET(sock_fd, &fdsr);
    tv.tv_sec = 1;
    tv.tv_usec = 0;
    if (new_fd != 0) {
       FD_SET(new_fd, &fdsr);
    }

    tmp = select(maxsock + 1, &fdsr, NULL, NULL, &tv);
    if (tmp < 0) {
       printf("select return value %d ,%d\n", tmp, errno);
       perror("select");
       return -1;
    } else if (tmp == 0) {
       return 0;
    }

A:
-1, is larger than  sizeof(buff). It's amazing.

It is.
len >= sizeof(buff) is the same as -1 >= sizeof(buff)  same as (size_t)-1 >= sizeof(buff) --> SIZE_MAX >= sizeof(buff) --> which is certainly true.
When an int like len is compared to the unsigned type size_t, the result of sizeof, one of the types is converted to the other based on which have a wider range.
In this case, it is usually the int converts to the unsigned size_t.  (size_t)-1 is the greatest value of size_t and is certainly larger than sizeof(buff).

It is unclear why len == -1 without seeing more code.
Yet in this case, I'd recommend to use size_t len = 0 to mend code.

When printing, use the a matching print specifier like "%zu"
printf("size:%zu\n", sizeof buff);

OP's code, lacking a warning, with printf("%d\n", sizeof(buff)); implies warnings are not fully enabled.  Save time.  Enable all warnings.


text:
Q: Maximum possible value of a positive integer $n$, such that for any choice of seven distinct elements from ${1, 2, .., n},$ there will exist What is the maximum possible value of a positive integer $n$, such that for any choice of seven distinct elements from ${1, 2, ..., n},$ there will exist two numbers $x$  &  $y$ satisfying $1 < x/y \leq 2$
What seems unclear to me are the following points,
A) Is $2y$ supposed to be $\leq$ n ?
B) Is there some standard approach to find the maximum possible value?
Moreover, usually, I try to take a small set to try out the given conditions. In this case, is it possible to take a smaller set and use it to draw conclusions for the larger set?
The answer is $2^7 - 2$

A: Starting with smaller values is the key here. Elimination can be done once a pattern is seen.
On the basis of the conditions given ($1 < x/y \leq 2$), try taking some numbers. Notice that, as mentioned in the comments, Choosing $1$ restricts the entry of $2\times1$
Thereafter, choosing $3$, restricts the entry of all numbers $\leq 2 \times 3$
Finally we are left with $7$. This clearly points to the fact/pattern that we get a number that is of the form $2^t-1$. Continuing the trend, we easily observe that the set $\{1,3,7,15,...,127 = 2^7-1\}$ is a set consisting of seven elements, no two $x,y$ of which satisfy the criteria that $1 < \frac{x}{y} \leq 2$.  Therefore, we know that the answer to the question is at most $127$.
We guess that it is $126$. Indeed, here is a proof. Divide $126$ into the following parts : $S_1 =\{1,2\}$, $S_2 = \{3,4,5,6\}$, $S_3 = \{7,8,...,14\}$, ..., $S_6 = \{63,64,...,126\}$. Now, if you pick any two elements $x,y$ from the same $S_i$, then either $1 < \frac{x}{y} \leq 2$ or $1 < \frac {y}{x} \leq 2$. This can be easily checked.
By the pigeonhole principle, if we pick $7$ elements between $1$ and $126$, two of them must be in the same $S_i$, and hence we are done.


text:
Q: Page content not centered, css, jquery I'm working on a page and for some reason I struggle to center everything within the page:
I've already used everything mentioned on the web.
I'm quit new to css, so any help would be appreciated:
here's the HTML:

This is X,

 Hello Hi Hola Bonjour Ciao Salam

1

For some reason I couldnt post the css...

A: You have CSS in your HTML so I would take that out and put it with the rest of your CSS. To solve as is though you need to give whatever you need to center a width and then use margin:0 auto; eg:

A: You can center a div using margin: 0 auto;. You cannot do that if you use float.

A: Are you trying to center the text or the containers?
Centering a container is usually fairly easy:
div#wrapper {
  margin:auto;
}

A: You need to externalize your styling from within your HTML, which will make things much clearer. You also have some invalid markup in that of which you have posted.
Google a basic CSS tutorial if need be, or head to W3Fools.
However From a quick glance, you need to use:
magin: 0 auto on your wrapper div. The 0 covers the margin for both the bottom and top margin and the auto, well I hope you can guess, will automatically provide an even margin either side of your div. Therfore centering your div.
see my example I have made some changes to your HTML which I assumed are not necessary and were merely attempts of yours to get the result you desire:


text:
Q: How to place a second row of the table at the bottom of the pop up dialog? It may be a silly question and probably I'm aware of solution but seems that I'm stock for now. :(
I'm displaying a pop up jQuery dialog that has a table with 2 rows. 1st row contains drop down list and 2nd row has a button:

            <asp:DropDownList ID="ddlSynchUser" runat="server" ClientIDMode="Static"></asp:DropDownList>

            START SYNCH

When displaying the pop up, button is placed directly under drop down list.
How can I place it at the button of the dialog?

A: I found the way to do it:
I just need to put style="height:152px; vertical-align:bottom; into the second  tag:

            <asp:DropDownList ID="ddlSynchUser" runat="server" ClientIDMode="Static"></asp:DropDownList>

            START SYNCH