text:
Q: I get the following failures on some devices help! I get the following failures on some devices.
java.lang.Error  a.a.a.a.b.N.a
java.lang.Error: FATAL EXCEPTION [main]
    Unity version     : 2017.4.35f1
    Device model      : samsung SM-N950F
    Device fingerprint: samsung/greatltexx/greatlte:9/PPR1.180610.011/N950FXXS8DSL3:user/release-keys
    Caused by
      at a.a.a.a.b.N.a (SourceFile:38)
      at a.a.a.a.b.K.shouldOverrideUrlLoading (SourceFile:1)
      at android.webkit.WebViewClient.shouldOverrideUrlLoading (WebViewClient.java:77)
      at org.chromium.android_webview.AwContentsClientBridge.shouldOverrideUrlLoading (PG:16)
      at android.os.MessageQueue.nativePollOnce (Native Method)
      at android.os.MessageQueue.next (MessageQueue.java:326)
      at android.os.Looper.loop (Looper.java:181)
      at android.app.ActivityThread.main (ActivityThread.java:7073)
      at java.lang.reflect.Method.invoke (Native Method)
      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
      at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:965)
    Caused by: java.lang.ClassNotFoundException:
      at dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:134)
      at java.lang.ClassLoader.loadClass (ClassLoader.java:379)
      at java.lang.ClassLoader.loadClass (ClassLoader.java:312)

A: Based on the information provided at the comments section seems that you're having a very common error due editor statistics collection.
Here you have a fix for it (disabling those statistics seems to solve the problem, as stated by the user who posted the comment at Unity Forum). Also, if you aren't using latest Unity version (and your project allows you to), try to update Unity to latest version as this error may be fixed in a latest version of Unity.
Hope this helps you!
P.S: If you try to update your Unity version remember to create a backup of the project.


text:
Q: Loop for document.getElementById in javascript I have two tabs in html.
In the 1st tab i have some options, such as textarea, option list, checkbox...
I want my app to show/transfer whatever i choose (in the 1st tab) to the 2nd tab as text, when i click an "ok" button.
In the js script i put the following function:
function myFunction() {
  var r="";
  var x="";
  var y="";
  var z="";

  var i;
  for (i=0; i++){
    var x = document.getElementById("myTextarea").value;
    var y = document.getElementById("mySelect").value;
    var z = document.getElementById("mySelect2").value;
    var r = x + " " + y +" " + z ;
  }
  document.getElementById("result").innerHTML = r;

}

where the result is shown in the 2nd tab as follows:

My problem is that it doesn't show every time what I choose in the 1st tab, but every time I click the "ok" button, the 2nd tab shows my last options. In other words I want the 2nd tab to show all of my options every time I click 'ok'. It is obvious that i make a mistake in the loop for. But what is it?
Please help me...

A: Since you only want to add a string per click, you should not need a loop. Instead add content to the existing content using either innerHTML += ..., or better: use DOM methods to add a text node to the DOM.
Here is how that could look:

function addToResult() {
    var x = document.getElementById("myTextarea").value;
    var y = document.getElementById("mySelect").value;
    var z = document.getElementById("mySelect2").value;
    var r = x + " - " + y + " - " + z;
    var result = document.getElementById("result");
    result.appendChild(document.createTextNode(r));
    result.appendChild(document.createElement("br"));
}
var addButton = document.getElementById("add");
addButton.addEventListener("click", addToResult);
<textarea id="myTextarea"></textarea>

<select id="mySelect">
    <option>choice 1</option>
    <option>choice 2</option>
</select>
<select id="mySelect2">
    <option>choice A</option>
    <option>choice B</option>
</select>

<button id="add">Add</button>

A: You could use insertAdjacentHTML method to add more content.

function $(selector) {
  return document.querySelector(selector)
}

function addToResult() {
    var x = $("#myTextarea").value;
    var y = $("#mySelect").value;
    var z = $("#mySelect2").value;
    var r = x + " - " + y + " - " + z;

    $("#result").insertAdjacentHTML('beforeend', r)
}
var addButton = document.getElementById("add");
addButton.addEventListener("click", addToResult);
<textarea id="myTextarea"></textarea>

<select id="mySelect">
    <option>choice 1</option>
    <option>choice 2</option>
</select>
<select id="mySelect2">
    <option>choice A</option>
    <option>choice B</option>
</select>

<button id="add">Add</button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Telnetlib response problem for a read_all to explain to you I reproduce a telnet client in python and so I start by logging in and entering the identifiers (password and username) then I test a command to see if it works (dir ) . The problem is that I want to display the details at the end with the read_all but as soon as I get to this point I have no answer then the freeze program I looked for many solutions on stackoverflow but none helped me
import telnetlib
import sys
import socket
import time

tel = telnetlib.Telnet("localhost",  23, timeout = 1)
tel.open("localhost" , 23)

tel.read_until(b"Username:")
tel.write(("Username").encode('ascii') + b"\n")

tel.read_until(b"Password:")
tel.write(("Password").encode('ascii') + b"\n")

time.sleep(5)

tel.read_until(b">")
tel.write(("dir").encode('ascii') + b"\n")

print(tel.read_all().decode('ascii'))

tel.close()


text:
Q: WCAG12.1:Frame is missing descriptive title I have build silverlight navigation application .
When I run the application , I can see it in the Internet Explorer but I have 2 errors :
   WCAG12.1:Frame is missing descriptive title.<frameset>,<frame>,or <noframes> does not  contain descriptive title text.
   Add a descriptive title (title="x").You can also use the Frames Properties dialog to add a title.

One of the points to .aspx file and the second one point to .HTML file. I have tried to add a title but nothing helps...
can anyone tell me what I have to do?
.aspx file :
<%@ Page Language="C#" AutoEventWireup="true" %>

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

<title>MyProjectName</title>

     <form id="form1" runat="server" style="height:100%">

         <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
      <param name="source" value="ClientBin/MyProjectName.xap"/>
      <param name="onError" value="onSilverlightError" />
      <param name="background" value="white" />
      <param name="minRuntimeVersion" value="4.0.50826.0" />
      <param name="autoUpgrade" value="true" />

      </object>

       </form>

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

 <title>MyProjectName</title>

     <form  id="form1" runat="server" style="height:100%">

         <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
      <param name="source" value="ClientBin/MyProjectName.xap"/>
      <param name="onError" value="onSilverlightError" />
      <param name="background" value="white" />
      <param name="minRuntimeVersion" value="4.0.50826.0" />
      <param name="autoUpgrade" value="true" />

      </object>

      </form>

A: The solution is to write in the iframe object different title.


text:
Q: Jquery: Setting/removing two attributes at once I am upcoming learner with jquery. Does anyone know how to give set two attributes at once that fit into the below example?
For the moment I am only able to give it one attribute. My goal is to able to give two attributes to a select box  'disabled' and 'hidden'
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);

Same things goes for removing the attributes: 'disabled' and 'hidden'
obj.next('.update').html(data.list).removeAttr('disabled');

A: obj.nextAll('.update')
 .attr({
    disabled: true,
    hidden: true
 })
 .html('<option value="">----</option>');

According to @nnnnnn comment .prop() might be more appropriate than .attr()
i.e
obj.nextAll('.update')
 .prop({
    disabled: true,
    hidden: true
 })
 .html('<option value="">----</option>');

DEMO for adding multiple attr
To remove
// from jQuery1.7, it can be a space-separated list of attributes.

obj.next('.update').html(data.list).removeAttr('disabled hidden');

DEMO for remove multiple attr

A: You can do something like this:
obj.attr({ firstAttr:firstVal,  secondAttr:secondVal});


text:
Q: onActivityResult is not getting called on back pressed I am developing an app that goes from an activity to child activity and when back button is pressed it goes back to parent activity with two data i.e. row number and column number from a grid. The values are getting stored in the variables but when the back button is pressed the onActivityResult method is not getting called.
Parent activity: onClick method
`
view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("MainActivity", "beginning");
                startActivityForResult(new Intent(getApplicationContext(), GridActivity.class), REQUEST_CODE);
            }
        });`

Parent activity: onActivityResult method
@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d("MainActivity", "receiving data");
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("MainActivity", "receiving data1");
        if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            Log.d("MainActivity", "result ok");
            if(data != null) {
                if (data.getIntExtra(COL_VALUE_TOKEN, 999) != 999) {
                    rowValue.setText(data.getIntExtra(ROW_VALUE_TOKEN, 999));
                    colValue.setText(data.getIntExtra(COL_VALUE_TOKEN, 999));
                    Log.d("MainActivity", "data not 999");
                } else {
                    rowValue.setText("-");
                    colValue.setText("-");
                    Log.d("MainActivity", "data 999");
                }
            }
        }
    }

Child activity: onClick method
(findViewById(R.id.btn_ok)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

Child activity: onBackPressed method
@Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra(COL_VALUE_TOKEN, currentCol);
        intent.putExtra(ROW_VALUE_TOKEN, currentRow);
        setResult(RESULT_OK, intent);
        Log.d("MainActivity", "sending data"+currentCol+currentRow);
        finish();
    }

Manifest file:
<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".GridActivity"
            android:parentActivityName=".MainActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

A: You need to do something like this:
override fun onBackPressed() {
        setResult(Activity.RESULT_CANCELED)
        finish()
    }


text:
Q: Skipping without having errors if an item doesn't exist in Javascript I am iterating arrays within arrays what I have. Some inner arrays does not have certain attribute called "validations" and some does. Whenever my loop hits an array with no certain attribute, it throws an error saying "no validations" and stop looping.
I'm calling this function:
$scope.groups[a].sections[0].fields[1]["validations"]

I wonder if there's a way to skip current array if the array does not have validations.
Thanks

A: When a property is not defined, it evaluates to undefined when addressed. As a boolean, undefined evaluates to false.
if ($scope.groups[a].sections[0].fields[1]["validations"]) {
  ...
}


text:
Q: Mahout Java API to find centroid of clusters generated using k-means I had clustered a list of points into k clusters using the k-means algorithm in Mahout. How do we find the centroid of a particular cluster? Is there any java Mahout API calls for finding this?

A: i could find centroid using the following code.
SequenceFile.Reader reader1 = new SequenceFile.Reader(fs, new Path(
                "output/clusters-1/part-r-00000"),
                conf);
    IntWritable key1 = new IntWritable();
    ClusterWritable value1 = new ClusterWritable();
    while (reader1.next(key1, value1)) {

        System.out.println(value1.getValue().getCenter()+ " ------------ "
                + key1.toString());
    }
    reader1.close();


text:
Q: Grails Plugins and Team City This is my current scenario:
I have checked in my grails app code + Groovy Folder + Grails Folder using GIT to teamcity.
Now when I try to run it Teamcity trows me this error:
[13:33:35]: Error reading remote plugin list [java.net.ConnectException: Connection refused: connect], building locally...
[13:33:35]: Plugins list cache doesn't exist creating..
[13:33:36]: Unable to list plugins, please check you have a valid internet connection: Connection refused: connect
[13:33:37]: Reading remote plugin list ...

[13:33:38]: Plugins list cache doesn't exist creating..
[13:33:39]: Unable to list plugins, please check you have a valid internet connection: Connection refused: connect
[13:33:39]: Plugin 'db-util' was not found in repository. If it is not stored in a configured repository you will need to install it manually. Type 'grails list-plugins' to find out what plugins are available.
[13:33:39]: [delete] Deleting directory C:\Documents and Settings\RiskSystemsBuildSA\.grails\1.2.2\projects\f8c726f1e64e048c\plugins\tomcat-1.2.2
[13:33:41]: Process exited with code 1
[13:33:41]: Build finished

I think I will have to package the plugins inside my app and then check them in GIT.
Please let me know your say on this matter.
Much Appreciated.
p.s.Teamcity correctly picks up the installed groovy and grails as I store .\grails and .\groovy in my teamcity environmen variables.

A: Well I finally achieved it. I added a line in the build.config file:
grails.project.plugins.dir="./grails/plugins"

This basically creates a dir plugins inside your project directories and downlaods all the zips in here. Next I checked in all the zips and the plugin directory in GIT. Since, everything was checked-in, teamcity didn't have any reason to moan about.
Everything else is going smooth now.


text:
Q: Session variable for particular page/url I am using ASP.NET..........
It is possible to create a session variable on page load just for a particular page/url?
The problem that I have is: The user comes to page 1 and the session variable becomes A, then he opens page 2 in a new tab and the session variable because B on both page 1 and page 2.
So when the user needs the session variable on page 1 it does not work because the variable have changed!

A: You can have more than one session variable. Just name the one on page A Session["variableA"] and the one on page B Session["variableB"].
Or am I misunderstanding?

A: There's no way to do that. Session variables are meant for the user's whole session. If you want to store page-specific information you need to round trip it between the server and the client on every request, for example by using the page's ViewState.
Tabbed browsing is a widespread feature these days and you have to design your sites so that they work correctly even if the user keeps switching tabs when interacting with your site.


text:
Q: Magento 1.9 - Shipping Calculator - Messages On the view cart page I do not use the Show Method if Not Applicable option as this can be messy and irrelevant.  Therefore, if there are no available quotes Magento does not show any message by default.  What file would it be best to return an error message from to advise the customer there are no shipping methods available?

A: In app/design/frontend/YOURTHEME/default/template/checkout/cart/shipping.html
Find the endif (approx line 120) for conditional statement if (($_shippingRateGroups = $this->getEstimateRates())): and add an else condition
Example:
    <?php else:?>
    <?php echo $this->__('There are no shipping methods available.<br/>Please use our contact form to obtain a shipping quote.'); ?>

    <?php endif; ?>


text:
Q: Make Angular / RxJS more readable I'm relatively new to RxJs and angular in general and wanted to know if there's a way to simplify the following code so it still does the same thing but is easier to read or is this as good as it can be?
private configureDS() {

let params$ = this.params$.pipe(debounceTime(300));
this.user$
  .pipe(
    mergeMap(user =>
      from(this.loadPosts(user)).pipe(map(posts => ({ user, posts })))
    ),
    combineLatest(this.dates$, params$),
    switchMap(([{ user, posts }, dates, params]) =>
      from(
        this.loadData(dates.date, dates.endDate, user, posts, params)
      ).pipe(map(data => ({ dates, data })))
    )
  )
  .subscribe(({ dates, data }) => this.displayData(data, dates));

this.paramsSubject.next(this.params);

}

A: You can try something like this to improve readability a bit
let params$ = this.params$.pipe(debounceTime(300));
let userPosts$ = this.user$
  .pipe(
    mergeMap(user =>
      from(this.loadPosts(user)).pipe(map(posts => ({ user, posts })))
    ),
  );

combineLatest(userPosts$, this.dates$, params$)
.pipe(
    switchMap(([{ user, posts }, dates, params]) =>
      from(
        this.loadData(dates.date, dates.endDate, user, posts, params)
      ).pipe(map(data => ({ dates, data })))
    )
)
.subscribe(({ dates, data }) => this.displayData(data, dates));

This basically uses the combineLatest function instead of the combineLatest operator (which is depracted since RxJs 6).
Still there are some things not really clear to me. For instance, why to you use the from function with this.loadPosts(user)? Usually from takes an iterable as input and returns a stream which emits per each element of the iterable - is loadPosts returning an iterable?
I ask these questions because maybe readability can be improved reviewing a bit the design of the chain.


text:
Q: Spring Boot - Bean creation exception I'm creating a sample application using using Spring boot and maven. The auto-wiring using @Autowire is not working. I'm getting the following exception:
[2015-10-16 16:39:51.233] boot - 3216  INFO [main] --- AnnotationConfigApplicationContext: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5f0fd5a0: startup date [Fri Oct 16 16:39:51 IST 2015]; root of context hierarchy
[2015-10-16 16:39:51.921] boot - 3216  WARN [main] --- AnnotationConfigApplicationContext: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testApp': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.bean.TestBean com.test.TestApp.testBean; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.bean.TestBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) [spring-context-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686) [spring-boot-1.2.5.RELEASE.jar:1.2.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) [spring-boot-1.2.5.RELEASE.jar:1.2.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957) [spring-boot-1.2.5.RELEASE.jar:1.2.5.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946) [spring-boot-1.2.5.RELEASE.jar:1.2.5.RELEASE]
at com.test.TestApp.main(TestApp.java:22) [classes/:?]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.bean.TestBean com.test.TestApp.testBean; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.bean.TestBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:   {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ~[spring-beans-4.1.7.RELEASE.jar:4.1.7.RELEASE]
... 15 more

TestApp.java
@SpringBootApplication
@EnableAutoConfiguration
public class TestApp {

@Autowired
private TestBean testBean;

public static void main(String[] args) {
    ApplicationContext context = SpringApplication.run(TestApp.class, args);
    context.getBean(TestApp.class);
  }
}

TestBean.java
@Component
public class TestBean {

@PostConstruct
public void init() {
    System.out.println("init from TestBean");
}
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
  }
}

Can anyone help me ?

A: The default @SpringBootApplication enables component scan only for the package of the application class and all subpackages. Since the package of TestApp is com.test, and the package of TestBean is com.bean, component scan won't detect the bean class.
Solution:
If you are using Spring Boot 1.2.x:
Either add the following annotation to your TestApp class:
@ComponentScan({"com.test", "com.bean"})

or move the TestBean to a subpackage of com.test, e.g. com.test.bean
If you are already using Spring Boot 1.3.x:
Add the following parameter to your @SpringBootApplication annotation:
@SpringBootApplication(scanBasePackages = {"com.test", "com.bean"})

A: It seems that Spring is not aware of your TestBean so @Autowired cannot find it in the bean registry.
In order to make the @Autowired work add @ComponentScan after @EnableAutoConfiguration annotation.
If you defined TestBean in your-app-context.xml try adding this
@ImportResource(value={"your-app-context.xml"})

after @EnableAutoConfiguration annotation.
So, for example, if your-app-context.xml was in the META-INF/spring folder located into src/main/resources of your Eclipse project, the correct line would be:
@ImportResource(value={"/META-INF/spring/your-app-context.xml"})

It will expose all the beans declared in that context to Spring Boot.


text:
Q: A RenderFlex overflowed by 299423 pixels on the bottom. problem seems to be made by the Column
I'm new to flutter , or programming to be clear .
I was following a course , doing the same as the Instructor , the app worked for him , but when i try to run it ,this error shows up .
Edit: tried to change Column to ListView but an error showed up .
 [![// @dart=2.9

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import './question.dart';
import './answer.dart';

class Quiz extends StatelessWidget {
  final List<Map<String, Object>> questions;
  final int questionIndex;
  final Function answerQuestion;

  Quiz(
      {@required this.questions,
      @required this.answerQuestion,
      @required this.questionIndex});

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: \[
        Question(
          questions\[questionIndex\]\['questionText'\],
        ),
        ...(questions\[questionIndex\]\['answers'\] as List<Map<String, Object>>)
            .map((answer) {
          return Answer(() => answerQuestion(answer\['score'\]), answer\['text'\]);
        }).toList()
      \],
    );
  }
}][2]][2]

A: SingleChildScrollView( ) is for is for single child (and you have multiple)
Consider replacing your Column (children : [...]) with
ListView(

   children: [...]

);

rather than wrapping Column in SingleChildScrollView() this way you won't run into issues down the road


text:
Q: Google AMP, how can i implement a classic popup with cookie? do someone has an idea about this? Because it seems that custom javascript is not allowed. Plus, the pages will be cached in the "cloudflare.com" way. thanks.

A: Discussed here:
https://github.com/ampproject/amphtml/issues/740
Will be implemented as part of this apparently (though not done yet):
https://github.com/ampproject/amphtml/issues/902
For now I would say https://github.com/ampproject/amphtml/issues is the best place to check for AMP related info.


text:
Q: Only some classes in my CSS file are being read and used I'm working on a theme for WordPress and trying to make some functionality changes, however, it seems like some CSS classes are not using the style outlined in my code while others are.
HTML & PHP Code

<?php

        woocommerce_quantity_input(
            array(
                'min_value'   => apply_filters( 'woocommerce_quantity_input_min', $product->get_min_purchase_quantity(), $product ),
                'max_value'   => apply_filters( 'woocommerce_quantity_input_max', $product->get_max_purchase_quantity(), $product ),
                'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( wp_unslash( $_POST['quantity'] ) ) : $product->get_min_purchase_quantity(), // WPCS: CSRF ok, input var ok.
            )
        );

        do_action( 'woocommerce_after_add_to_cart_quantity' );
        ?>

            <button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>

CSS Code:
.quantityContainer{
    display: flex !important;
}

.quantity{
    float: left;
}

.flex-grow-1{
    flex-grow: 1 !important;
}

The problem is that both the .quantity and .flex-grow-1 classes are being effected by the style but the .quantityContainer class isn't.
I've attached some images to show the Chrome Dev Tools code.
Flex Grow Class with CSS
Quantity Class with CSS
Quantity Container class without CSS
Page URL: https://toolsandmachinery.co.uk/product/scan-combiflex-330/
I've tried:

*

*Changing Class Names

*Changing from Class to ID Changing

*Changing CSS code location (to master style.css)

Thanks a lot.

A: I think, but I'm not 100% certain, that your problem is with your attempt at a CSS comment:
// Styling to make quantity field and button inline
.quantityContainer{
    display: flex !important;
}

CSS doesn't support this type of commenting, you must use /* ... */ syntax instead. I think for whatever reason this is invalidating the next line which is the one you say isn't being applied.
Correct way:
/* Styling to make quantity field and button inline */
.quantityContainer{
    display: flex !important;
}


text:
Q: Vba to break up text within a cell? Text to columns not working How can I break up text within a cell with vba? I exported emails to an excel file using a vba and the information exported in one of the cells is formatted as seen below:
Name * xxxxxx
Country of residence * xxxxxx Email * xxxxx@gmail.com mailto:xxxxxxx@gmail.com
Mobile phone number * 0xxxxxx
Do you want to become a member of Assoc? Yes Check all that apply *

Members
Education
Ethical Conduct
Events
Regulation

I tried the solution below and it's not working.
From article: If you need to build a formula to remove these line breaks all you need to know is that this 'character' is character 10 in Excel. You can create this character in an Excel cell with the formula =CHAR(10).
So to remove it we can use the SUBSTITUTE formula and replace CHAR(10) with nothing ( shown as "").
https://www.auditexcel.co.za/blog/removing-line-breaks-from-cells-the-alt-enters/#:~:text=Building%20a%20formula%20to%20remove%20the%20ALT%20ENTER%20line%20breaks,-If%20you%20need&text=You%20can%20create%20this%20character,cell%20with%20no%20line%20breaks.

A: My understanding is that you dump an email into 1 excel cell and are hoping to separate a series of strings [Country, Email, Etc.] that are separated by a line break?
I suggest using the split function to separate the strings into an array, then loop through that array to put the information in the desired cells. Mind you this will only work if the items are in the same order everytime, if the order can change then you will need to add a data verification step. i.e. if inStr("@",[Range]) then its an email...
Split([string to split], [delimiter])
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/split-function
Dim strEmail as String 'Email dump
Dim arrEmail() as String 'Array for looping
Dim ItemsInArray as Integer 'Used to hold array count
Dim i as Integer 'Counter

strEmail = ActiveSheet.Cells("[Column,Row]") 'Cell your email dumps to
arrEmail = Split(strEmail, char(10)) 'Populate array
ItemsInArray = UBound(arrEmail) 'Get upper bound of array (total item count)

For i = 0 to ItemsInArray
    ActiveSheet.Cells("[Column,Row]") = arrEmail(i)
    Column + 1
Next i

when i = 0 its a country code
when i = 1 its an email
when i = 2 its a phone #
etc....


text:
Q: Audio streaming from Google Cloud Storage and CDNs - costs So I'm making an app that involves streaming audio(radio-like) from the Google Cloud Storage and was looking into the costs. It seems it would be much too expensive as is.
e.g. Lets say I have 10MB audio files, a user listens to 20 files a day and I have 2000 active users. That's 400GBs or $48/day. i.e. ~$1440/month just for that.
I then looked into putting a CDN in front of it, to minimize direct reads from the Storage. Now initially that made sense to me. The CDN would cache the audio files and the clients would be getting the files from the cache most of the time. However, as I was looking at Fastly's pricing (Fastly is a Google partner and seems like a good fit) I noticed that they seem to be pricing bandwidth usage to their cache at the exact same rate as Google cloud does ($0.12/GB). So unless I'm reading this wrong, putting up the CDN would not save me ANY money. Now I get that there are other reasons why putting a CDN in front of it could be a good idea, but am I really reading this right?
Also, if you have any other tips on how I should set this up, I'm all ears.

A: Estimating the invoice of such a service is a complex matter. To get an informed answer and tips regarding possible implementation paths I would suggest reaching out to a GCP Sales representative. Similarly you should contact the Fastly team to get a precise picture of their pricing model.
Moreover, any estimate we could make here would be outdated as soon as any of the respective pricing model changes, which would invalidate the answer and probably drive future readers to wrong conclusions.


text:
Q: iOS, how to backup file (coredata and plist) to iCloud, and retrieve? I have an App that has almost completed, except iCloud support. Now my user's data consists of coredata (called sqlite?) and some plist files. User's activity change these files all the time. I want my App could backup these files to the user's iCloud account. How could I do it?
I always refer to Apple official documents, I'm reading this tutorial but still in vague.
I'm wondering whether it is a quick example?
Thanks
////////////////////////Edited//////////////////////////
One day left but no answer or comment at all. Didn't I make my self clear?
Well, I just want my iCould restore all user's data and backup if needed. I don't need them to be auto-sync but trigered by user's action.
Please help.


text:
Q: How to use NSManaged object class using NSObject class I have NSObject  class name TrackInfo which contains tracks info like name , artist name,thumb image etc.
I use this class as downloading data and save information to that class after parsing data.
Now I have another tab in which, I have to show some data. This is same kind of data like trackInfo. But when app is in OFFLINE, I have to make NSManagedObject. It is same as trackinfo.
Can I use NSObject class instead of NSManagedObject or Vice-Versa ?
What I basically wants to do is, I have to display track info from one class either Trackinfo (NSObject class) or NSManagedObjectClass which is used to save data when app is in offline.

A: Short answer is yes, you can. How? You can find a useful discussion Organising Core Data for iOS.
The long answer can be grabbed within the documentation.

NSManagedObject is a generic class that implements all the basic
  behavior required of a Core Data model object. It is not possible to
  use instances of direct subclasses of NSObject (or any other class not
  inheriting from NSManagedObject) with a managed object context. You
  may create custom subclasses of NSManagedObject, although this is not
  always required. If no custom logic is needed, a complete object graph
  can be formed with NSManagedObject instances.
A managed object is associated with an entity description (an instance
  of NSEntityDescription) that provides metadata about the object
  (including the name of the entity that the object represents and the
  names of its attributes and relationships) and with a managed object
  context that tracks changes to the object graph. It is important that
  a managed object is properly configured for use with Core Data. If you
  instantiate a managed object directly, you must call the designated
  initializer (initWithEntity:insertIntoManagedObjectContext:).

About your question, it depends on what you need to achieve. If your goal is to perform a sync mechanism between your device and the server, you should set up 1) a model with a TrackInfo entity 2) a Core Data stack that relies on a persistent store like SQLite. Then you should modify TrackInfo to take into account modifications to that entity. For example, a dirty flag property (0 or 1) or a timestamp. When you do a modification on your TrackInfo you update that property. When the connection is restored you need to query against that property and sync with the server. If you choose the timestamp, the server should say what is the latest timestamp to query against.


text:
Q: optimizing dynamic programming in matlab I have a problem with a dynamic programming solution which I'm trying to implement in matlab and was trying to see if there's a better (run-time-wise) implementation than the one I could come up with.
The problem (all values are in the real):
input: let X be a T-by-d matrix, W be a k-by-d matrix and A by a k-by-k matrix.
output: Y T-by-1 array s.t for row i in X Y(i) is the number of a row in W which maximizes our goal.
A(i,j) gives us the cost of choosing row j if the previous row we chose was i.
To calculate the weight of the output, for each row i in X we sum the dot-product of the Y(i) row of W and add the relevant cost from A.
Our goal is to maximaize the said weight.
Dynamic solution:

*

*instantiate a k-by-T matrix

*Fill the first column of the matrix with the results of dot-producting the first row of X with each row of W

*for each of the same columns (denote as i) fill with the dot-producting of the i row of X with each row of W and add the cost of A(j,i) where j is the row index of the cell in previous column with maximum value

*backtrack from the last column, each time choosing the row index of the cell with the highest value
Matlab implementation (with instantiation of variables):
T = 8;
d = 10;
k = 20;
X = rand(T,d);
W = rand(k,d);
A = rand(k);
Y = zeros(T,1);
weight_table = zeros(k,T);

weight_table(:,1) = W*X(1,:)';

for t = 2 : T
    [~, prev_ind] = max(weight_table(:,t-1));
    weight_table(:,t) = W*X(t,:)' + A(:,prev_ind);
end

[~, Y] = max(weight_table);

A: Since there is data dependency across iterations, I would advise keeping the loop, but pre-calculate few things like the product of W and transpose of each row of X. This is done here (showing just the weight_table calculation part as the rest of the code stays the same as in the original post) -
weight_table = zeros(k,T);
weight_table(:,1) = W*X(1,:)';
WXt = W*X.'; %//' Pre-calculate
for t = 2 : T
    [~, prev_ind] = max(weight_table(:,t-1));
    weight_table(:,t) = WXt(:,t) + A(:,prev_ind); %// Use pre-calculated values and thus avoid that multiplication across each iteration
end

For bigger inputs like - T = 800; d = 1000; k = 2000;, I am getting 8-10x performance improvement with it on my system.


text:
Q: .NET Reflection to Identify Property Relationship supposedly I have the following class below:
public class Car
{
    public Car()
    {

    }
}

public class Motor
{
    public Motor()
    {

    }
}

public class Vehicle
{
    public Vehicle()
    {
        SuperCar = new Car();
    }

    public Car SuperCar { get; set; }
    public string TestName { get; set; }
}

Let's see the codes below:
 Vehicle vehicle = new Vehicle();
 Car superCar = vehicle.SuperCar;

Now, if we are only given Car instance which is superCar, is it possible to know from Reflection that superCar instance is actually belong to one of the Vehicle's properties?
Ok. Thanks for your comments. I think it's possible through Reflection.
So, if we extend the codes:
PropertyInfo[] props = vehicle.GetType().GetProperties();

Provided, we are only given:
PropertyInfo propInfo = props[0];

We could know this propInfo actually belong to which class by using MemberInfo:
Console.WriteLine(((System.Reflection.MemberInfo)(propInfo)).DeclaringType.Name);

It would return Vehicle.

Thanks!

A: Short answer
No, it is not possible. Reflection is a way of reading static metadata of the assembly and types within. Information about type properties is an example of such metadata. But information like - "which objects are referencing some object" - is not a static metadata. It is a runtime data and in general it is not accessible in .NET. Other thing is, it really doesn't have to. There is always better way to design things (like references pointing its parents). In other words, you really never and ever should need to do that so better remember that it is not possible.
Long answer
Saying above, I would like to point out that surprisingly, what are you trying to do is possible with help of astonishing Microsoft.Diagnostics.Runtime library. As authors says:

ClrMD is a set of advanced APIs for programmatically inspecting a crash dump of a .NET program much in the same way as the SOS Debugging Extensions (SOS). It allows you to write automated crash analysis for your applications and automate many common debugger tasks.

In fact, you can also attach to self process and analyze it during normal work. Below code is quite hacky and should be never used probably, but it works and shows how powerful is .NET world:
public bool IsReferencedByAnyVehicle(Car car)
{
    ulong ptr;
    // Nasty way of getting address
    unsafe
    {
        TypedReference tr = __makeref(car);
        ptr = (ulong)(**(IntPtr**)(&tr));
        Console.WriteLine(ptr);
    }

    // Attach to the process itself, hence only AttachFlag.Passive flag is possible
    var process = Process.GetCurrentProcess();
    using (var dataTarget = DataTarget.AttachToProcess(process.Id, 250, AttachFlag.Passive))
    {
        string dacLocation = dataTarget.ClrVersions[0].TryGetDacLocation();
        ClrRuntime runtime = dataTarget.CreateRuntime(dacLocation);

        ClrHeap heap = runtime.GetHeap();
        // Get all Vehicle objects from heap that has reference to ptr
        var refs = heap.EnumerateObjects()
            .Select(obj => new
            {
                Type = heap.GetObjectType(obj),
                ObjectAddress = obj
            })
            .Where(t => t.Type != null &&
                        t.Type.Name.EndsWith("Vehicle") &&
                        GetReferences(t.Type, t.ObjectAddress).Contains(ptr))
            .Any();
        // Cleanup
        runtime.Flush();
        return refs;
    }
}

public List<ulong> GetReferences(ClrType type, ulong objRef)
{
    var result = new List<ulong>();
    type.EnumerateRefsOfObjectCarefully(objRef, (addr, _) => result.Add(addr));
    return result;
}

then for simple test:
Vehicle vehicle = new Vehicle();
Car superCar = vehicle.SuperCar;
Car localCar = new Car();

bool isSuperCar = IsReferencedByAnyVehicle(superCar); // true
bool isLocalCar = IsReferencedByAnyVehicle(localCar); // false

Note: For attaching to itself, only AttachFlag.Passive is possible which is described as:

Performs a "passive" attach, meaning no debugger is actually attached to the target process. The process is not paused, so queries for quickly changing data (such as the contents of the GC heap or callstacks) will be highly inconsistent** unless the user pauses the process through other means.

so results may be not always deterministic.

A: No, not really, but you can find out if your object reference is actually pointing to the same object.
        if (Object.ReferenceEquals(superCar, vehicle.SuperCar))
        {
            System.Diagnostics.Debug.WriteLine("Yes it is");
        }


text:
Q: how to change the value of  in javascript? i have an element in html as shown below.

i want to change the value of lang according to particular condition.
I tried as given below.but its not working.

Could anyone help me for changing the value of lang attribute of span?

A: document.getElementById('HLPMTXT1').setAttribute('lang', 'HLPMTXT2');

Not all attributes can be accessed through the object properties

A: You should use setAttribute(name, value) to do that, so your code would look like:
document.getElementById("HLPMTXT1").setAttribute("lang", "HLPMTXT2");

You can also use getAttribute(name) to retrieve the value using JavaScript.

*

*https://developer.mozilla.org/en/DOM/element.setAttribute

*https://developer.mozilla.org/en/DOM/element.getAttribute
Edit: It's also possible that your script is not working because you're trying to access the element before it exists in the DOM. Best way to insure that your element exists is by either: a) putting your script tag after the element, b) using the unload event to delay execution of your JS until everything is loaded, or c) use the DOMContentLoaded event. The latter, however, is a bit tricky to get to work cross-browser (without reusing somebody else's code that already addresses those problems) so you might want to read up on it first.


text:
Q: "How can X be" vs. "how does X can be" I have a Spanish friend, who wrote the following sentence:

"How does foo, bar, baz can be compared?"

I corrected it to read:

"How can foo, bar, baz be compared?"

Other than the obvious, he has asked me to explain why the first is wrong, and the second (maybe) is correct.
Any help?

A: The phrase "how does ...?" is singular, so the reader will always expect a single entity to follow. For example: "How does magnetism work?" or "How does a bird fly?"
The plural version would be "how do ...?" as in: "How do flowers grow?" or "How do John and Mary know each-other?"
In either case, using the verb "do" implies that there is a single, correct answer to the question. In your sentence (unless I have misinterpreted it), the intent is to ask a more open-ended question. This meaning is expressed by using "can" instead of "do".
To illustrate, if you were to ask: "How do foo, bar and baz compare?" A single answer is expected. As in: "Foo is better than bar, but baz is the best because ...". Asking the question using "can" instead of "do" allows the reader more freedom in answering. For example: "How can foo, bar and baz be compared?" "Foo, bar and baz can be compared using the Kwyjibo algorithm, or by simply comparing their relative weights."
On a side note, I would always use "and" between the last two items in a list: "foo, bar and baz" instead of simply "foo, bar, baz". I don't know if there is a strict rule for such lists, but I find that the "and" reads better because I would always say it that way if I were speaking instead of writing.

A: In modern English "do" is obligatory for forming negations and questions, unless there is an auxiliary verb (or the substantive verb is "be", or for some speakers "have").
A passive is formed with the auxiliary "be", so it is not negated with "do":
"A, B and C are compared"
"How are A, B and C compared?" (Not "How do A, B and C be compared?")

If another auxiliary, such as "can" is used, the same thing happens, whether or not there is also a passive auxiliary:
"A, B and C can be compared"
"How can A, B and C be compared?" (not "How does A, B and C can be compared?")

On the other hand, it is common in speech to express passive meaning by the word "get", as in
 "A, B and C get compared"

but "get" does not behave like an auxiliary, and does require "do":
 "Do A, B and C get compared?" (not "Get A, B and C compared?").


text:
Q: angular js empty error response Trying to do some basic REST services from angular, but all I get back is an empty error response.
I open the index.html directly on my PC (not sure if this is the issue), and then click 'login'  which eventually calls my controller:
$scope.doLogin = function()
  {
   var pr = $http.get('http://localHost:7777/BuilderDBSvc/login', {params: {user: $scope.userid, pass: $scope.password} })
     .success(function(data)
      {
       console.log(data);
       domains = data;
      })
      .error(function(data, status, headers, config)
      {
       console.log(data)
       console.log(status)
       console.log(headers)
       console.log(config)
      });
   pr.then(function(data)
     {
      $scope.user = data.data;
     });
  };

Using firefox to debug, I put breakpoints inside all 3 functions: success error and then.  But only 'error' is triggered. And the request always shows up in red, but with a 200 response code.  The response data shows a size of 23 bytes, but the value is always blank.
However, if I type the URL and parameters directly in my browser window, it works fine, and displays the expected json string.
Ive used this pattern before, but with nodejs and angularjs working together. but this time the REST provider is a non-java application.  I would suspect that is the problem, but when I enter the REST url directly in my browser it works fine.
What am I missing here?
Are there any better tools i can use to help debug this?

note:
yes this is a very insecure way to do authentication, but its my starting point.

A: Is highly probable that your ploblem is by opening the index.html from your explorer because the request will not come from localhost and by that the localhost server will block the request against cross origin request in chrome console youll probably see a message saying

XMLHttpRequest cannot load 'http://localhost:7777'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'your index.html location' is therefore not allowed access.

to avoid that you should make request from http://localhost to http://localhost (same server) or tell your server to accept cross origin requests


text:
Q: Periodic Tasks in C# without the use of ThreadPool Is there a way to execute a periodic task/thread in C# without the using of a thread pool (this is one of the main requirements I have).
The expected scenario is as the following:

*

*The periodic thread blocks/waits for a timer event (from the system).

*The system notifies the thread when the timer expires.

*The thread executes some code.

*The thread blocks/waits for the next timer event from the system (note that if the thread missed one or more timer events, this is ok).

The closest thing I found to this is the System.Forms.Timer, but the issue is that its accuracy is limited to 55ms which is not enough for me.
The System.Timers.Timer seems to be able to handle this via the SynchronizingObject property. However, I'm not really sure how to implement a ISynchronizeInvoke according to the above scenario. All of the code samples I found for implementing ISynchronizeInvoke seem too complicated for handling such a simple scenario.
Is there a way to easily implement this feature in C# as in the above scenario (without using threadpools) and more accurate than the System.Forms.Timer?

A: Windows timers have a default resolution of 15.6 ms, from their documentation:

The default system-wide timer resolution in Windows is 15.6 ms, which
  means that every 15.6 ms the operating system receives a clock
  interrupt from the system timer hardware. When the clock interrupt
  fires, Windows updates the timer tick count and checks whether a
  scheduled timer object has expired. Some applications require that
  timer expiration is serviced more frequently than once every 15.6 ms.

They also state:

Applications can call timeBeginPeriod to increase the timer
  resolution. The maximum resolution of 1 ms is used to support
  graphical animations, audio playback, or video playback. This not only
  increases the timer resolution for the application to 1 ms, but also
  affects the global system timer resolution, because Windows uses at
  least the highest resolution (that is, the lowest interval) that any
  application requests. Therefore, if only one application requests a
  timer resolution of 1 ms, the system timer sets the interval (also
  called the "system timer tick") to at least 1 ms. For more
  information, see "timeBeginPeriod Function" on the MSDN® website.

So if you really need high resolution timers, you can use the timeBeginPeriod call to affect the global system timer, but know that it will affect the batter life/power consuption of the device on which it is working.
Also, there are the QueryPerformanceCounter and QueryPerformanceFrequency calls that can be used to get lower levels of precision in .net, like in this example: http://www.codeproject.com/Articles/571289/Obtaining-Microsecond-Precision-in-NET

A: Multimedia Timers will provide you with the highest resolution of all timers. If you really and truly need 10ms or less resolution, that will be the only way to go.
If you find that you do not need the resolution provided by Multimedia Timers, you will find that Waitable Timers will give you the ability to code a loop that waits for a timer to expire within a single thread.
You also may choose Timer Queues which provide a large number of timers without the resource overhead of the other timers, but by default uses the system thread pool.

A: Have you tried to simply sleep your thread?
int msecSleepTime = 25;  // number of milliseconds to sleep
Thread.Sleep(msecSleepTime);  // sleep the current thread for the given number of milliseconds

A: Quickest response from System.Timers.Timer on my system w/o reconfiguring the system's timer is ~16 ms.  Set your Timer.Interval value to (int)( target interval / 16 ) * 16 then have the thread sleep for the remaining duration (and if you really need better accuracy, an interpreted language such as C# is not the correct choice):
class Program
{
    private static Timer _timer = new Timer();
    private static DateTime _last = DateTime.Now;
    private const int IntendedInterval = 25;

    static void Main(string[] args)
    {
        _timer.AutoReset = false;
        _timer.Interval = (int)(IntendedInterval / 16) * 16;
        _timer.Elapsed += _timer_Elapsed;
        _timer.Start();

        Console.ReadLine();
    }

    static void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        var now = DateTime.Now;
        var duration = now - _last;

        var sleep = IntendedInterval - duration.TotalMilliseconds;

        if (0 < sleep )
        {
            System.Threading.Thread.Sleep(( int )sleep);
        }

        _timer.Start();

        now = DateTime.Now;
        duration = now - _last;
        _last = now;

        Console.WriteLine(duration.TotalMilliseconds.ToString());
    }
}


text:
Q: CSS grid float alignment This is what I want:

And this is what I have (I want the bottom left box scooted up):

Here is my CSS so far.
.grid {
  padding:0px;
  margin:10px auto;
  width:100%;
  background-size: 100%;
}

.grid li {
  display: block;
  width:  361px;
  float: left;
  background: #fff;
  margin:6px 19px 6px 0px;
  margin-top: 12px;
  padding: 10px;
  font-family: 'Roboto', sans-serif;
  -webkit-box-shadow: 0px 2px 1px rgba(50, 50, 50, 0.4);
  -moz-box-shadow:    0px 2px 1px rgba(50, 50, 50, 0.4);
  box-shadow:         0px 2px 1px rgba(50, 50, 50, 0.4);
  opacity: 0;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}


text:
Q: View Problem when I include NavigationView I have a view problem and I can't solve him :
Here is my code :
var body: some View {

    NavigationView{
        ZStack {
            VStack(spacing:0){
                HStack{
                    if !self.showSearchBar{
                        Text("Conversations").fontWeight(.bold).font(.title).foregroundColor(.white)
                    }

                    Spacer(minLength: 0)

                    HStack{
                        if self.showSearchBar{
                            Image(systemName:"magnifyingglass").padding(.horizontal,8)

                            TextField("Cherchez une conversation", text: self.$txt)

                            Button {
                                withAnimation {
                                    self.showSearchBar.toggle()
                                }

                            } label: {
                                Image(systemName: "xmark").foregroundColor(.black)
                            }
                            .padding(.horizontal,8)

                        }
                        else {
                            Button(action:{
                                withAnimation {
                                    self.showSearchBar.toggle()
                                }

                            }) {
                                Image(systemName:"magnifyingglass").foregroundColor(.black).padding(10)
                            }
                        }
                    }
                    .padding(self.showSearchBar ? 10 : 0)
                    .background(Color.white)
                    .cornerRadius(20)

                }.padding(.top,  15)
                .padding(.horizontal)
                .padding(.bottom,10)

                Spacer()
            }

            List{
                ForEach(0..<groupes.count){groupe in
                    HStack{
                        ForEach(0..<discussionsImages.count){ image in

                            Image(uiImage: discussionsImages[image])
                                .resizable()
                                .frame(width: 50, height: 50)
                                .clipShape(RoundedRectangle(cornerRadius: 25))
                        }
                        VStack(alignment: .leading, spacing: 10) {
                            Text(groupes[groupe].name)
                                .font(.system(size: 22))
                                .fontWeight(.heavy)
                            Text(groupes[groupe].latestMessage.text)
                                .foregroundColor(Color.black.opacity(0.3))
                        }

                    }

                }

            }.padding(.top,70)
            .listStyle(GroupedListStyle())

                .onAppear(perform: {
                    for i in 0..<groupes.count{
                        let otherEmail = groupes[i].profileImageData
                        let safeEmail = DatabaseManager.safeEmail(emailAdress: otherEmail)
                        StorageManager.shared.downloadURL(for: safeEmail) { (result) in
                            switch result{
                            case .failure(let error):
                                print("failed to get url:\(error)")
                            case .success(let url):
                                if let data = try? Data(contentsOf: url) {
                                    // Create Image and Update Image View
                                    discussionsImages.append(UIImage(data: data)!)
                                }

                            }
                        }
                    }

                    ConversationModel.shared.getAllConversation { (result) in
                        switch result{
                        case .failure(let error):
                            print(error)

                        case .success(let groupe):
                            groupes = groupe
                        }
                    }
                })
            VStack(alignment:.trailing) {

                Spacer()
                HStack {
                    Spacer()
                    Button(action: {
                        //aller a la ConversationSearchView
                        showSheet.toggle()
                    }) {

                        Image(systemName: "plus")
                            .foregroundColor(.white)
                            .padding()

                            .background(Color("blue"))
                            .clipShape(RoundedRectangle(cornerRadius: 15))
                            .frame(width: 30, height: 30)
                    }.padding(.bottom,80)
                    .padding(.trailing,25)
                    .fullScreenCover(isPresented: $showSheet) {
                        ConversationsSearchView( showNewChat: $showNewChat)
                        }

                }
            }
        }.background(Color("blue").edgesIgnoringSafeArea(.top))
    }
        .navigationBarHidden(true)
        .navigationBarBackButtonHidden(true)

}

The problem is that when I put NavigationView ( and I need it to go to another view ), all my view will be shifted down : Here is the view
I can obtain what I've expected when I remove the NavigationView here
How can I keep NavigationView without been shifted down ?


text:
Q: How to increase length of remote command script or how to send file from server to agent for zabbix I'm trying to implement a function with Zabbix API, the basic requirement is: create command script(string or script file both are OK, no matter save on Server or Agent) -> execute on Agent;
I find 2 way to do it with Remote Command:
1) Global Script: I can use it by calling script.execute directly, but "Remote commands are limited to 255 characters", it's not enough to create a script/command as our demand; and it's harder if we need use Python, #python -c "..." cannot run ok if Python script is complex a little, and use shell command to create *.py file on agent need more characters;
Global Script are saved in scripts table, but changing table structure by increasing length from 255 to 1024 is not a good idea according to comments in https://www.zabbix.com/forum/showthread.php?t=51869;
2) Custom Script: there is no limitation on command characters, but I had to config it in a Action, and wait for triggering it.
On the another hand, even Remote Command can create script file on agent, it's still not convenient, is there any way to sent file from Zabbix Server to Agent by Zabbix own function?
I want to ask it on Zabbix Forums, but I have no permission to create new Post/Thread, so I go to here.
Is there any one can give me some help about this?

A: That isn't really a feature of a monitoring system. You might be able to abuse the system.run key - have a script that splits your target script in ~200 byte blocks, then have them concatenated on the agent by running remote commands or zabbix_get like so (and be careful with newlines):
zabbix_get -s target.host -k "system.run[echo \"$script_part\" >> /script_location]"

That would be quite terrible and hackish, though.
While there is a feature request to introduce agent configuration management in Zabbix, have I already mentioned that it is not really a task for a monitoring system? You might want to look into system management tools like Puppet, Chef and others.


text:
Q: How to add the configurable product to cart from the product list page I want to add the configurable product to cart from the product list page itself.
When I select a color from swatch and add the product to cart, It is Redirecting to details page and able to add the product to cart from there. I need to add it directly from list page.

A: I don't know if that exactly what you want but you can do that with extension that manage addToCart function with ajax like this one :
https://ecommerce.aheadworks.com/magento-extensions/ajax-cart-pro.html
With this your customer stay on the same page without any redirection.


text:
Q: What does inclusion-minimal maximizer mean? In set theory, combinatorial optimization etc, I came across the term called inclusion-minimal maximizer. What is it's definition?

A: In combinatorial optimization, it is common for solutions to be represented by sets of objects. There may be multiple optimal solutions to a combinatorial optimization problem. Moreover, since these optimal solutions are represented by sets, some optimal solutions may be strictly contained within others. An inclusion-wise minimal maximizer is a set that maximizes your objective function, while simultaneously not being a proper subset of any other maximizer.
For example, consider the following:
*Example: Consider the set X = {-2, -1, 1,2}. Find a subset of A$\subseteq$ X such that

*

*A has at most 2 elements, and

*the product of the elements in A is maximized.

For example, A = {-2,1} will give a product of -2 while A = {-1} will give a product of -1.*
Answer: {-2,-1}, {1,2}, and {2} are all maximizers for this problem. However, only {-2,-1} and {2} are inclusion-wise minimal maximizers.


text:
Q: How to enumerate Spring java configuration classes? I'm using Spring's Java-based configuration in my application. I have a root configuration class that imports a bunch of other configurations, each which may import more configurations and so on:
@Config
@Import(AnotherConfig.class)
class RootConfig {
    // beans
}

@Config
@Import(YetAnotherConfig.class)
class AnotherConfig {
    // beans
}

@Config
class YetAnotherConfig {
    // beans
}

I then bootstrap the system by declaring a AnnotationConfigWebApplicationContext in my web.xml file whose contextConfigLocation is set to RootConfig.
Is there a way to determine the full set of configuration classes that has bootstrapped my application? Some function like this (might take a subclass for ctx...):
List<Class> readConfigClasses(ApplicationContext ctx) {
    // what goes here?
    // should return [ RootConfig.class,
    //                 AnotherConfig.class,
    //                 YetAnotherConfig.class ]
}

Update: @axtavt's answer gets most of the way there, returning the actual configuration objects themselves, which are instances enhanced by CGLIB in my case. Grabbing the superclass of these proxies does the trick:
List<Class<?>> readConfigClasses(final ApplicationContext ctx) {
    List<Class<?>> configClasses = new ArrayList<Class<?>>();
    for (final Object config :
           ctx.getBeansWithAnnotation(Configuration.class).values()) {
        configClasses.add(config.getClass().getSuperclass());
    }
    return configClasses;
}

A: @Configuration classes are managed by Spring like regular beans, therefore you can enumerate them as ctx.getBeansWithAnnotation(Configuration.class).
However, I'm not sure how would it work in complex cases (@Beans in non-@Configuration classes, etc).


text:
Q: How do I disable silverlight cross-domain content protection for WriteableBitmap I have an Esri map in silverlight and I am trying to get a screenshot. However, I am facing cross-domain content protection for writeablebitmap, saying "Pixels are not accessible".
Is there a way that I can disable this? or any other work around in silverlight 3 or 4?

A: I have videos stored on an Amazon cloudfront server with a valid clientaccesspolicy.xml to allow cross domain access for the silverlight host URL and the following function did not allow me to take screen shots of the video and manipulate the pixels until it was replaced with with a WebClient download instead (a WebClient honors the cross domain policy files, you can see it being requested in Fiddler, something that the MediaElement.Source function did not even attempt)
Old none working cross domain code
public LoadVideoFromURL(string url)
{
    var uri = new Uri(url);

    myMediaElement.Source(uri);
}

new working cross domain code
public LoadVideoFromURL(string url)
{
    var uri = new Uri(url);

    //Request the video
    var videoDownloader = new WebClient();

    videoDownloader.OpenReadCompleted += new OpenReadCompletedEventHandler(
                 (s, args) => myMediaElement.SetSource(args.Result));

    videoDownloader.OpenReadAsync(uri);
}

A: you can kind of hack around this by rehosting the image.  basically you can set up a wcf service on your server that acts as a proxy to the map, then when silverlight does the security check on your media source it will see that it is 'hosted' by your server, then it should let you render it to a Writeable bitmap.  though this could obviously greatly increase the load on your server.

A: The simplest way to work around this problem is to make sure that the Silverlight application and the images are hosted from the same domain. Since you are asking this question, I will assume that this is not possible.
Do you control the server where the images are hosted? If so, you can add a Client Access Policy file to enable cross-domain access to the images from your Silverlight app. Then you need to change how you are consuming these images. Instead of setting the Source of the Image element to a URI of the image, use WebClient to download the image as a Stream and set the source of the Image element directly to that Stream. If you do this, you will not run into the cross-domain access violations when trying to access the WriteableBitmap pixels.

A: If the source of the bitmap is another domain, the simple answer is no. I'm not sure how you're trying to take this "screen shot", but it sounds like there are good security reasons to stop this... Of course, full (read/write) pixel access is available normally, when your image is in the local domain.
The right way to resolve this, given you seem to want a screenshot of the user's desktop taken, would be to make the Silverlight app require full trust, which is possible since Silverlight 3 (and expanded in Silverlight 4). This does however require it to be an OOB (out of browser app) I believe.


text:
Q: Any testing tool or framework supporting multiple RPC protocol to test different component I just wanted to know whether there is any testing tool or framework (Open-source preferred) available to test multiple type of APIs of component or module.

In case there is no such things currently available, if someone can suggest how to address this problem (Design)?
Hope I am clear!

A: It is not a framework but you could try out soapui.
If thats not an option, I would say that you need multiple frameworks. For example RestAssured to test REST API's.


text:
Q: Argument Exception Was Unhandled here is my code on form1.
private void flopCards()//view the 2 face down card
{
    string hold1=NumGen.CardGenerator(i)
        ,hold2=NumGen.CardGenerator(i)
    ,hold4=NumGen.CardGenerator(i)
    ,hold5=NumGen.CardGenerator(i);
    holder1.Image = Image.FromFile(hold1, true);
    holder2.Image = Image.FromFile(hold2, true);

}

private void button1_Click(object sender, EventArgs e)
{
    Controls.Remove(button1);
    player();
    bot1();
    GrpBx();
    Get3rd.Click += new EventHandler(Get3rd_Click);
    check.Click += new EventHandler(check_Click);
}

void check_Click(object sender, EventArgs e)
{
    flopCards();
}

what i want to accomplish is when i click the check button I the picture of the holders will be replaced with a card.. there where no error shown at the error list but when i try to run and click the button what i get is an popup where it said"argument exception was unhandled the path is not of a legal form"
please help me!

A: Try this:
string hold1=NumGen.CardGenerator(i);
try
{
    if (File.Exists(hold1))
        Console.WriteLine("The file {0} was found.", hold1);
    else
        Console.WriteLine("Error: The file {0} cannot be found", hold1);
}
catch (ArgumentException ex)
{
    Console.WriteLine("I don't understand the path you supplied.");
    Console.WriteLine(ex.Message);
    Console.WriteLine(ex.ToString());
}

Run your program and check the output window. Hopefully it will help you understand why you can't access your image.


text:
Q: Why does the suggested fix for git push without upstream include the exact command, but the same for git pull doesn't? Whenever you attempt to push to a remote repository without having an upstream, git returns the following (assume that my branch is called 'development-branch'):
fatal: The current branch development-branch has no upstream branch.
To push the current branch and set the remote as upstream, use

     git push --set-upstream origin development-branch

As you can see, git returns an exact command which you can simply copy-paste and run. Alternatively, if you attempt to pull without having an upstream, git returns the following:
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> development-branch

In this case, the command I would need to run is git branch --set-upstream-to=origin/development-branch, but git doesn't return this exactly, instead opting for the <branch> keyword and then the correct branch name. Why? Why not directly return the exact command so it can be simply copy-pasted and run, like the 'git push' suggestion?


text:
Q: Comparing value from a nested dictionaries and list I want to compare values from two variables (dictionary and list). Dictionary has a nested construct, so I have to loop over the all items.
I discovered simple solution, but I am pretty sure that I can do this in a better way (using python).
In a brief I want to find items from user_from_database which are not existing in a user_from_client variable.
My solution:
#variable containing users from client side
users_from_client = {
  "0": {
    "COL1": "whatever",
    "COL2": "val1",
    "COL3": "whatever",
  },
  "1": {
    "COL1": "whatever",
    "COL2": "val2",
    "COL3": "whatever",
  },
  "3": {
    "COL1": "whatever",
    "COL2": "val3",
    "COL3": "whatever",
  }
}

#variable containing users from the database
users_from_database = [
  ["val1"],
  ["val2"],
  ["val5"],
  ["val7"]
]

#This function is used to find element from the nested dictionaries(d)
def _check(element, d, pattern = 'COL2'):
  exist = False
  for k, user in d.iteritems():
    for key, item in user.iteritems():
      if key == pattern and item == element:
        exist = True
  return exist

#Finding which users should be removed from the database
to_remove = []
for user in users_from_db:
  if not _check(user[0], users_from_agent):
    if user[0] not in to_remove:
      to_remove.append(user[0])

#to_remove list contains: [val5, val7"]

What is the better way to give the same result using python approach ?
Probably I don't have to add that I'm a newbie with python (I assume that you are able to see that watching the code above).

A: Just use an error-safe dictionary lookup:
def _check(element, d, pattern = 'COL2'):
    for user in d.itervalues():
        if user.get(pattern) == element:
            return True
    return False

Or as a one liner:
def _check(element, d, pattern = 'COL2'):
    return any(user.get(pattern) == element for user in d.itervalues())

Or trying to do the entire job as a one-liner:
#Finding which users should be removed from the database
to_remove = set(
    name
    for name in users_from_database.itervalues()
    if not any(user.get('COL2') == name for (user,) in users_from_client)
)

assert to_remove == {"val5", "val7"}

sets can make it ever more concise (and efficient):
to_remove = set(
    user for (user,) in users_from_database
) - set(
    user.get('COL2') for user in users_from_client
)

Your data structures are a bit wierd. Consider using:
users_from_client = [
  {
    "COL1": "whatever",
    "COL2": "val1",
    "COL3": "whatever",
  }, {
    "COL1": "whatever",
    "COL2": "val2",
    "COL3": "whatever",
  }, {
    "COL1": "whatever",
    "COL2": "val3",
    "COL3": "whatever",
  }
]

#variable containing users from the database
users_from_database = set(
  "val1",
  "val2",
  "val5",
  "val7"
)

Which reduces your code to:
to_remove = users_from_database - set(
    user.get('COL2') for user in users_from_client
)

A: Well I don't know of any super elegant way to do this, but there are some minor improvements you can make to your code.
First off, you aren't using k, so you might as well iterate over just the values. Second, you don't need to keep track of exists, you can just return immediately when you find a match. Lastly, if you're checking for a key,value pair, you can just test if the tuple is contained in items.
def _check(element, d, pattern = 'COL2'):
  for user in d.itervalues():
    if (pattern, element) in user.items():
      return True
  return False

A: You can create inverted dict for fast lookup and place it in cache for example..
>>> from collections import defaultdict
>>>
>>> users_inverted = defaultdict(list)
>>> for pk, user in users_from_client.iteritems():
...  for key in user.iteritems():
...   users_inverted[key].append(int(pk))
...
>>> users_inverted
defaultdict(<type 'list'>, {('COL3', 'whatever'): [1, 0, 3], ('COL2', 'val1'): [0], ('COL1', 'whatever'): [1, 0, 3], ('COL2', 'val2'): [1], ('COL2', 'val3'): [3]})

and then lookup for users will be very fast:
>>> def _check(element, pattern = 'COL2'):
...  return bool(users_inverted[(pattern, element)])
>>>
>>> _check('whatever', 'COL3')
True
>>> _check('whatever', 'COL333')
False

and as a plus besides speed you get a list of users for each attributes pair


text:
Q: How to store .txt file data in different columns of a CSV file using BASH? I have a .txt file with the following data structure:
Scan Times:
 33.3 seconds
 77.4 seconds
 33.3 seconds
 77.4 seconds

Check Times:
 110.30 seconds
 72.99 seconds
 72.16 seconds
 110.30 seconds

Move Times:
 73.66 seconds
 90.77 seconds
 72.87 seconds
 71.75 seconds

Switch Times:
 92.0 seconds
 78.6 seconds
 77.8 seconds
 84.9 seconds

I now want to take that .txt file and create a CSV file that has the following format.

I have a very basic layout so far with my bash script but I am not sure how to proceed:
inputFiles=("./Successes/SuccessSummary.txt" "./Failures/FailSummary.txt")
touch results.csv

for file in "${inputFiles[@]}"
do
    while IFS= read -r line
    do
        #echo $line
        if [ "$line" = "Scan Times:" ]
        then
        fi

        if [ "$line" = "Check Times:" ]
        then
        fi

        if [ "$line" = "Move Times:" ]
        then
        fi

        if [ "$line" = "Switch Distances:" ]
        then
        fi
    done < "$file"
done

A: pr -4T file

Scan Times:   Check Times:      Move Times:       Switch Times:
 33.3 seconds      110.30 seconds    73.66 seconds     92.0 seconds
 77.4 seconds      72.99 seconds     90.77 seconds     78.6 seconds
 33.3 seconds      72.16 seconds     72.87 seconds     77.8 seconds
 77.4 seconds      110.30 seconds    71.75 seconds     84.9 seconds

The empty line in each column will also be displayed.
Previously, you can make the necessary changes in the text, for example, using sed:
sed '/^\s*$/d;s/seconds//' file | pr -4T

Scan Times:   Check Times:  Move Times:   Switch Times:
 33.3          110.30        73.66         92.0
 77.4          72.99         90.77         78.6
 33.3          72.16         72.87         77.8
 77.4          110.30        71.75         84.9

Added:
It should be remembered that the utility was created for printing and has a number of default flags that are not entirely suitable for such cases.
-T eliminate pagination and omit page headers and trailers.
-wN Setting the page width. (default: -w 72).
Added2:
Or an example of how you can write each row to an awk array:
awk '
/^\s*$/ {i=0; next}
        {A[i]= A[++i] sprintf("%*s", 12,$($NF ~ /:$/?0:1))}
END     {for(i in A) print A[i]}
' file

 Scan Times:Check Times: Move Times:Switch Times:
        33.3      110.30       73.66        92.0
        77.4       72.99       90.77        78.6
        33.3       72.16       72.87        77.8
        77.4      110.30       71.75        84.9

A: Using Raku (formerly known as Perl_6):
raku -e '.join("\t").put for [Z] lines.map(*.trim).batch(6);'

OUTPUT:
Scan Times: Check Times:    Move Times: Switch Times:
33.3 seconds    110.30 seconds  73.66 seconds   92.0 seconds
77.4 seconds    72.99 seconds   90.77 seconds   78.6 seconds
33.3 seconds    72.16 seconds   72.87 seconds   77.8 seconds
77.4 seconds    110.30 seconds  71.75 seconds   84.9 seconds

Briefly, lines are trim-med (element-wise) and batch-ed (collectively) according to column length (6), producing 4 batches. Then the [Z] operator consecutively "zips" together one element from each batch. In a final formatting step, elements are join()-ed together with tabs to create a TSV file.
[Note: The batch operator will work on incomplete batches; if you only want complete batches, use rotor instead of batch. (However, rotor will fail silently on an incomplete final batch unless you set :partial)].
Remove " seconds" with a second Raku one-liner below, (...or add a subst() call to the first one-liner above):
perl6 -pe 's:g/" seconds"//;'

https://raku.org/


text:
Q: Unintentional thread synchronization when writing to file If I have a tread that counts to 1000 and prints out the result like so:
public class MyRunnable implements Runnable{
    @Override
    public  void run() {
        for (int i=0;i<1000;i++){
            System.out.println(i+" ");
        }
    }
}

And in main I do something like:
new Thread(new MyRunnable()).start();
new Thread(new MyRunnable()).start();

the results get jumbled up, since I'm not synchronizing.
But, if my thread looks like:
public class MyRunnable implements Runnable{
    Writer w;
    MyRunnable(Writer w){
        this.w=w;
    }

    @Override
    public  void run() {
        for (int i=0;i<1000;i++){
            try{
                w.write(String.valueOf(i));
                w.write (" ") ;
            }//&catch the exception
        }
    }
}

and my in main I have this this:
  try (Writer writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream("Thread.txt"), "utf-8"))) {
       Thread t1 =new Thread(new MyRunnable(writer));
       Thread t2 =new Thread(new MyRunnable(writer));
       t1.start();
       t2.start();
       t1.join();
       t2.join();
   }    //catch the exception,etc.

The results look normal: the threads somehow got synchronized. I imagine it's because I pass writer as a parameter, but could someone explain it better? And, out of curiosity, is there any way around it?
EDIT: My apologies, it seems i hurried too much. I tried to simplify MyThread and removed too much code. but i just realized that the situation i described only happens if i try to open and read a file in run() method. So run actually looks like this:
public  void run() {
    try {
                Scanner scanner = new Scanner(f); //f is new File (filename)
                while (scanner.hasNext())
                {
                    String str = scanner.next();
                    if (str.equals("word")) //code counts "word" appearance
                        count++;
                }
                scanner.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
             for (int i=0;i<1000;i++){
                try{
                    w.write(String.valueOf(i));
                    w.write (" ") ;
                }//&catch the exception
            } //continue by writing the count

I suppose this means the problem is actually in reading the file?

A: The write(String) method of Writer (which BufferedWriter extends from) is synchronized.

A: This one will produce output in a non-synchronized manner. It is similar to yours, so I think there is something you are omitting.
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 */
public class ThreadTest {
    final static int N = 1000;

    static Runnable countDown(Writer writer){
        return ()->{
            for(int i = 0; i<N; i++){
                try{
                    writer.write(String.format("%d\t", i));
                } catch(Exception exc){

                }
            }

            try {
                writer.write("\n");
            } catch (IOException e) {
                e.printStackTrace();
            }
        };
    }

    public static void main(String[] args){
        try(
            Writer writer = Files.newBufferedWriter(Paths.get("test.txt"), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)
        ){
            Thread a = new Thread(countDown(writer));
            Thread b = new Thread(countDown(writer));
            a.start();
            b.start();
            a.join();
            b.join();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

Then the output becomes:
0   0   1   1   2   2   3   3   4   4   5   6   5   6   7   7   8   8   9   10  9   10  11  11  12  13  12  13  14  14  15  15  16  16  17  17  18  18  19  19  20  20  21  21  22  22  23  23  24  24  25  25  26  26  27  27  28  28  29  29  30  30  31  32  31  33  32  34  33  35  34  36  37  35  38  36  39  37  40  38  41  39  42  40  43  41  42  44  43  45  44  46  45  47  46  48  47  49  50  48  49  51  50  52  53  51  54  52  55  56  53  57  54  58  55  59  56  60  57  61  58  62  59  63  60  64  61  62  65  63  66  64  67  65  68  66  69  67  70  68  71  69  72  70  73  71  74  72  75  73  76  74  77  75  78  76  77  79  78  80  79  81  80  82  81  83  84  82  85  83  86  84  87  85  88  86  89  87  90  88  91  89  92  90  93  91  94  92  95  93  96  97  94  98  95  99  96  100 97  101 98  102 99  103 100 104 101 105 102 106 103 107 104 108 105 109 106 110 107 111 108 112 109 113 110 114 111 115 112 116 113 117 114 118 115 119 116 120 117 121 118 122 119 123 120 124 121 125 122 126 123 127 124 128 125 129 126 130 127 131 128 132 129 133 130 134 131 135 132 136 133 137 134 138 135 139 136 140 137 141 138 142 139 143 140 144 141 145 142 146 143 147 144 148 145 149 146 150 147 151 148 152 149 153 150 154 151 155 152 156 153 157 154 158 155 159 156 160 157 158 161 162 159 163 160 164 161 165 162 166 163 167 164 168 165 169 166 170 167 171 168 172 169 173 170 174 171 175 172 176 173 177 174 178 175 179 176 180 177 181 178 182 179 183 180 184 181 185 182 186 183 187 184 188 185 189 186 190 187 191 188 192 189 193 190 191 194 192 195 193 196 194 197 195 198 196 199 197 200 198 201 199 202 203 200 204 201 205 202 206 203 207 204 208 209 205 210 206 211 207 212 213 208 214 209 215 210 216 211 217 212 218 213 219 214 220 215 221 216 222 217 223 218 224 219 225 220 226 221 227 222 228 223 229 224 230 225 231 226 232 227 233 234 228 235 236 229 237 230 238 231 239 232 233 240 234 241 235 242 236 243 237 244 238 245 239 246 247 240 241 248 242 249 243 250 244 251 245 252 253 246 247 254 248 255 249 256 250 257 258 251 259 252 253 260 261 254 262 255 256 257 263 258 264 259 265 260 266 261 267 262 268 263 269 264 270 265 271 266 272 267 273 268 274 269 275 270 276 271 277 272 278 273 279 274 280 275 281 276 282 277 283 278 284 279 285 280 286 281 287 282 288 283 289 284 290 285 291 286 292 287 293 288 294 289 295 290 296 291 297 292 298 293 299 294 300 295 301 296 302 297 303 298 304 299 305 300 306 301 307 302 308 303 309 304 310 305 311 306 312 307 313 308 314 309 315 310 316 311 312 317 313 318 314 319 315 320 316 321 317 318 322 323 319 324 320 325 321 326 322 327 323 328 324 329 325 330 326 331 327 332 328 333 329 334 330 335 331 336 332 337 333 338 334 339 335 340 336 341 337 342 338 343 339 344 340 345 341 346 342 347 343 348 344 349 345 350 346 351 347 352 348 353 349 354 350 355 351 352 356 353 357 354 358 355 359 356 360 357 361 358 362 359 363 364 360 365 361 366 362 363 367 364 368 365 369 366 370 367 371 368 372 369 373 370 374 371 375 372 376 373 377 374 378 375 379 376 380 377 381 378 382 379 383 380 384 381 385 382 386 383 387 388 384 389 385 390 386 391 392 387 393 388 394 395 389 396 390 397 398 399 400 391 401 392 402 403 393 404 394 405 406 395 407 408 396 409 397 410 411 398 412 399 413 414 400 415 401 416 417 402 418 403 419 420 404 421 405 422 423 406 424 407 425 426 408 427 409 428 410 429 430 411 431 432 412 433 413 434 414 435 415 436 416 437 417 438 418 439 419 440 420 441 421 442 422 443 423 444 424 445 425 446 426 447 427 448 428 449 429 450 430 451 431 452 432 453 433 454 434 455 435 456 436 457 437 458 438 459 439 460 440 461 441 462 442 463 443 464 444 465 445 466 446 467 447 468 448 469 449 470 450 471 451 472 452 473 453 474 454 475 455 476 456 477 457 478 458 479 480 459 481 482 460 483 484 461 485 486 462 487 463 488 489 464 490 491 465 492 466 493 494 467 495 496 468 497 469 498 499 470 500 501 471 502 472 503 504 473 505 474 506 507 475 508 476 509 510 477 511 478 512 513 479 514 480 515 516 481 517 482 518 519 483 520 484 521 522 523 485 524 486 525 526 487 527 488 528 529 489 530 531 490 532 491 533 492 534 535 493 536 537 494 538 495 539 540 496 541 497 542 543 498 544 499 545 546 500 547 548 501 549 502 550 551 503 552 504 553 554 505 555 506 556 557 507 558 508 559 560 509 561 562 510 563 511 564 565 512 566 513 567 568 514 569 515 570 516 571 572 517 573 518 574 519 575 576 520 577 521 578 579 522 580 581 523 582 524 583 525 584 585 526 586 527 587 588 528 589 529 590 591 530 592 593 531 594 532 595 596 533 597 534 598 599 535 600 536 601 602 537 603 538 604 605 539 606 540 607 541 608 609 542 610 543 611 612 544 613 614 545 615 546 616 617 547 618 548 619 620 549 621 550 622 623 551 624 552 625 626 553 627 554 628 629 555 630 631 556 632 557 633 634 558 635 636 559 637 560 638 639 561 640 641 562 642 563 643 644 564 645 565 646 647 566 648 567 649 650 568 651 652 569 653 654 570 655 571 656 657 572 658 659 573 660 574 661 662 575 663 664 576 665 577 666 667 578 668 579 669 670 580 671 672 581 673 582 674 675 583 676 584 677 678 585 679 680 586 681 682 587 683 684 588 685 589 686 590 687 591 592 688 593 594 689 595 690 596 691 597 692 598 693 599 694 600 695 696 601 697 602 698 603 699 604 700 605 701 606 702 607 703 608 704 609 705 610 706 611 707 612 708 613 709 710 614 711 615 712 616 713 617 714 618 715 619 716 620 717 621 718 622 719 720 623 721 722 624 723 625 724 725 626 726 627 727 728 628 729 629 730 731 630 732 631 733 734 632 735 633 736 737 634 738 635 739 740 636 741 637 742 743 638 744 639 745 746 640 747 641 748 749 642 750 643 751 752 644 753 645 754 755 646 756 647 757 758 648 759 649 760 761 650 762 763 651 764 765 652 766 653 767 768 654 769 655 770 771 656 772 657 773 774 658 775 659 776 777 660 778 661 779 780 662 781 663 782 783 664 784 665 785 786 666 787 788 667 789 668 790 669 791 792 670 793 671 794 795 672 796 673 797 798 674 799 800 675 801 676 802 677 803 804 678 805 806 679 807 808 680 809 681 810 811 682 812 683 813 814 684 815 685 816 817 686 818 687 819 820 688 821 689 822 823 690 824 691 825 826 692 827 693 828 829 694 830 695 831 832 696 833 697 834 835 698 836 699 837 838 700 839 701 840 841 702 842 703 843 704 844 705 845 706 846 707 847 708 848 709 849 710 850 711 851 712 852 853 713 854 714 855 715 856 716 857 717 858 718 859 719 860 720 861 721 862 722 863 723 864 724 865 725 866 726 867 727 868 728 869 729 870 730 871 731 872 732 873 733 874 734 875 735 876 736 877 737 878 738 879 739 880 740 881 741 882 742 883 743 884 744 885 745 886 746 887 747 748 888 889 749 890 891 750 892 893 751 894 895 752 896 753 897 898 754 899 900 755 901 902 756 903 757 904 905 758 906 907 759 908 760 909 910 761 911 912 762 913 914 763 915 916 764 917 765 918 919 766 920 921 767 922 923 768 924 769 925 926 770 927 928 771 929 772 930 931 773 932 774 933 934 775 935 936 776 937 777 938 939 778 940 779 941 780 942 943 781 944 945 782 946 783 947 948 784 949 785 950 951 786 952 787 953 954 788 955 789 956 957 790 958 791 959 960 792 961 793 962 794 963 964 795 965 796 966 797 967 798 968 969 799 970 971 800 972 801 973 974 802 975 976 803 977 804 978 979 805 980 981 806 982 807 983 984 808 809 985 986 810 987 811 988 812 813 989 990 814 991 815 992 816 993 817 818 994 819 995 996 820 997 821 998 822 823 999
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999

Which, as you can see ends up jumbled.
In the case of your Scanner, since you are making two Scanner for the same file on windows you are essentially synchronizing on the file. eg. The read/write condition ends up looking like this:
try{
    synchronized(f){
        Scanner s = new Scanner(f);
        System.out.println("starting");
        while(s.hasNext()){
            System.out.println(s.next().length());
        }
        System.out.println("finished");
        s.close();
    }
}catch(Exception e){e.printStackTrace();}

The result of this is that, one thread reads the file, finishes and starts counting, at that point the other thread starts reading the file. Reading the file takes much longer than counting down.

A: It's not clear what you want exactly. But if you just want t1 and t2 to mix up their numbers you should make sure they start exactly at the same time. An easy way to do that is to use a CountdownLatch that you store in your threads like this:
public class MyRunnable implements Runnable{
        Writer w;
        CountDownLatch countDownLatch;
        MyRunnable(Writer w, CountDownLatch countDownLatch){
            this.w=w;
            this.countDownLatch=countDownLatch;
        }

        @Override
        public  void run() {
            countDownLatch.await();
            for (int i=0;i<1000;i++){
                try{
                    w.write(String.valueOf(i));
                    w.write (" ") ;
                }//&catch the exception
            }
        }
}

And that you create before the thread and launch when they are created:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream("Thread.txt"), "utf-8"))) {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    Thread t1 =new Thread(new MyRunnable(writer, countDownLatch));
    Thread t2 =new Thread(new MyRunnable(writer), countDownLatch);
    t1.start();
    t2.start();
    countDownLatch.countDown(); //Start the threads
    t1.join();
    t2.join();
}    //catch the exception,etc.

This will make sure that the time taken for the thread creation doesn't influence your test and that both threads actually start at the same time.


text:
Q: Issues with Login form I am making a login form in django. When I am running the app and filled the username and password fields. The page always redirected to one condition (whether the username is right or not).
The code is as :
def home(request):

   if request.method == 'POST':
      username = request.POST.get('user_name')
      password = request.POST.get('password')
      user = authenticate(user_name=username, password=password)
      if user is not None:
        if user.is_active:
           login(request, user)
        # success
           return render_to_response('registration/main_page.html',{'form':login},context_instance=RequestContext(request))
        else:
         #user was not active
           return render_to_response('registration/q.html')
      else:
        # not a valid user
           return render_to_response('registration/home.html')

   else:
       # URL was accessed directly
           return render_to_response('registration/w.html')

It always redirected to home.html
else:
             #user was not active
              return render_to_response('registration/home.html')

Why it happens?

A: authenticate() function takes username not user_name.
Try this: user = authenticate(username=username, password=password)
Also, instead of if user is not None: you can write if user :

A: It seems your function returns a None object here:
if user is not None

You can add print statements to pin it down,
if request.method == 'POST':
      username = request.POST.get('user_name')
      password = request.POST.get('password')

      print username # what does it return?

      user = authenticate(user_name=username, password=password)

      print user # what does it return?

      if user is not None:
          #...