问:
Importing schema from json with optional value
I'm trying to create a table from a json datasource.

The problem is that there is a field in the json data that is not always present for every entry and looks like this.

```<code>[ { "k1" : "someValue",
    "optK" : { "nestedK" : true } },
  { "k1" : "someOtherValue" }
]
</code>```

When I try to specify the optional field in the schema, all the entries without that field have all null value in the table:

```<code>columns:  k1        |  optK
row1:   "someValue"    [true]
row2:    null           null
</code>```

is it possible to write a schema such that I would have null only in the column where the value is missing?

Like this:

```<code>columns:  k1            |  optK
row1:   "someValue"       "optV"
row2:   "someOtherValue"   null
</code>```

My current code:

```<code>import org.apache.spark.sql.expressions.scalalang._
import org.apache.spark.sql.types._
import org.apache.spark.sql.{DataFrame, Dataset, SparkSession}

val session = SparkSession.builder().enableHiveSupport().getOrCreate()

val schema = StructType(Seq(
  StructField("k1", StringType, false),
  StructField("optK", StructType(Seq(StructField("nestedK", BooleanType, false))), false)
))

val df = session.read.schema(schema).json("data.json")
df.registerTempTable("Mr_Table")
</code>```

答:
There are several issues in your code/input data:

Input data - JSON keys aren't in quote.

You can use avoid this problem, by one of the following options:

Updating the input data by adding quotes to the json keys

Using .option("allowUnquotedFieldNames",true) in the following way:

```<code>val df = session.read.option("allowUnquotedFieldNames",true).schema(schema).json("data.json")
</code>```

A string field in the input data was defined as boolean in the schema schema should be updated to be:

val schema = StructType(Seq(
  StructField("k1", StringType, false),
  StructField("optK", StructType(Seq(StructField("nestedK", StringType, false))), false)
))

JSON data format, I've update the sample json input to be in json lines format:

{ k1 : "someValue", optK : { nestedK : "optV" } }
{ k1 : "someOtherValue" }
```

<hr>

<p>Running the modify code shows the following:</p>

```Spark context available as 'sc' (master = yarn, app id = application_xxx).
Spark session available as 'spark'.
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.2.0
      /_/

Using Scala version 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_141)
scala> :paste
// Entering paste mode (ctrl-D to finish)
import org.apache.spark.sql.expressions.scalalang._
import org.apache.spark.sql.types._
import org.apache.spark.sql.{DataFrame, Dataset, SparkSession}
val schema = StructType(Seq(
  StructField("k1", StringType, false),
  StructField("optK", StructType(Seq(StructField("nestedK", StringType, false))), false)
))
val df = spark.read.option("allowUnquotedFieldNames",true).schema(schema).json("s3 location of data.json")
// Exiting paste mode, now interpreting.

import org.apache.spark.sql.expressions.scalalang._
import org.apache.spark.sql.types._
import org.apache.spark.sql.{DataFrame, Dataset, SparkSession}
schema: org.apache.spark.sql.types.StructType = StructType(StructField(k1,StringType,false), StructField(optK,StructType(StructField(nestedK,StringType,false)),false))
df: org.apache.spark.sql.DataFrame = [k1: string, optK: struct<nestedK: string>]

scala> df.show
+--------------+------+
|            k1|  optK|
+--------------+------+
|     someValue|[optV]|
|someOtherValue|  null|
+--------------+------+
```

Body:
I'm trying to create a table from a json datasource.

The problem is that there is a field in the json data that is not always present for every entry and looks like this.

[ { "k1" : "someValue",
    "optK" : { "nestedK" : true } },
  { "k1" : "someOtherValue" }
]

When I try to specify the optional field in the schema, all the entries without that field have all null value in the table:

columns:  k1        |  optK
row1:   "someValue"    [true]
row2:    null           null

is it possible to write a schema such that I would have null only in the column where the value is missing?

Like this:

columns:  k1            |  optK
row1:   "someValue"       "optV"
row2:   "someOtherValue"   null

My current code:

import org.apache.spark.sql.expressions.scalalang._
import org.apache.spark.sql.types._
import org.apache.spark.sql.{DataFrame, Dataset, SparkSession}

val session = SparkSession.builder().enableHiveSupport().getOrCreate()

val schema = StructType(Seq(
  StructField("k1", StringType, false),
  StructField("optK", StructType(Seq(StructField("nestedK", BooleanType, false))), false)
))

val df = session.read.schema(schema).json("data.json")
df.registerTempTable("Mr_Table")

Body:
There are several issues in your code/input data:

Input data - JSON keys aren't in quote.

You can use avoid this problem, by one of the following options:

Updating the input data by adding quotes to the json keys

Using .option("allowUnquotedFieldNames",true) in the following way:

val df = session.read.option("allowUnquotedFieldNames",true).schema(schema).json("data.json")

A string field in the input data was defined as boolean in the schema schema should be updated to be:

val schema = StructType(Seq(
  StructField("k1", StringType, false),
  StructField("optK", StructType(Seq(StructField("nestedK", StringType, false))), false)
))

JSON data format, I've update the sample json input to be in json lines format:

{ k1 : "someValue", optK : { nestedK : "optV" } }
{ k1 : "someOtherValue" }

Running the modify code shows the following:

Spark context available as 'sc' (master = yarn, app id = application_xxx).
Spark session available as 'spark'.
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 2.2.0
      /_/

Using Scala version 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_141)
scala> :paste
// Entering paste mode (ctrl-D to finish)
import org.apache.spark.sql.expressions.scalalang._
import org.apache.spark.sql.types._
import org.apache.spark.sql.{DataFrame, Dataset, SparkSession}
val schema = StructType(Seq(
  StructField("k1", StringType, false),
  StructField("optK", StructType(Seq(StructField("nestedK", StringType, false))), false)
))
val df = spark.read.option("allowUnquotedFieldNames",true).schema(schema).json("s3 location of data.json")
// Exiting paste mode, now interpreting.

import org.apache.spark.sql.expressions.scalalang._
import org.apache.spark.sql.types._
import org.apache.spark.sql.{DataFrame, Dataset, SparkSession}
schema: org.apache.spark.sql.types.StructType = StructType(StructField(k1,StringType,false), StructField(optK,StructType(StructField(nestedK,StringType,false)),false))
df: org.apache.spark.sql.DataFrame = [k1: string, optK: struct<nestedK: string>]

scala> df.show
+--------------+------+
|            k1|  optK|
+--------------+------+
|     someValue|[optV]|
|someOtherValue|  null|
+--------------+------+


来源: stackexchange

问:
How to update template on @click

Code

I have the following code. I want to update the results-box with a random selected choice. How would I update the template on a @click event.

```<code><template>
  <div class="container">
    <button @click="getDecision()" class="ui primary button">Discover</button>
    <p id="results-box"></p>
  </div>
</template>

<script>
  export default {
    name: "SlapButton",
    data() {
      return {

      }
    },
    methods: {
      getDecision: function () {
        var decisions = [
          "choice 1",
          "choice 2",
          "choice 3",
          "choice 4",
          "choice 5",
          "choice 6"
        ]
        var randNum = Math.floor((Math.random() * decisions.length) + 0);
        var randChoice = decisions[randNum];
      }
    }
  }

</script>
</code>```

Question

When the user clicks on the button getDecision() is called and it selects a random choice from the the decisions array. How do I display this random choice randChoice within the p tag #results-box.

答:
Here is a demo  and another micro example

Basically. You'll need a variable that will hold the randChoice once you define this variable inside data (){} object, just give it the value inside your method like this:

```<code>export default {
  name: "SlapButton",
  data() {
    return {
      randomChoice: false
    }
  },
  methods: {
    getDecision: function () {
      var decisions = [
        "choice 1",
        "choice 2",
        "choice 3",
        "choice 4",
        "choice 5",
        "choice 6"
      ]
      var randNum = Math.floor((Math.random() * decisions.length) + 0);
      this.randomChoice = decisions[randNum];
    }
  }
}
</code>```

Now just show this data in your element like this:

```<code><p id="results-box"> {{randomChoice}} </p>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to update template on @click

Body:
Code

I have the following code. I want to update the results-box with a random selected choice. How would I update the template on a @click event.

<template>

    <button @click="getDecision()" class="ui primary button">Discover</button>

</template>

Question

When the user clicks on the button getDecision() is called and it selects a random choice from the the decisions array. How do I display this random choice randChoice within the p tag #results-box.

Body:
Here is a demo  and another micro example

Basically. You'll need a variable that will hold the randChoice once you define this variable inside data (){} object, just give it the value inside your method like this:

export default {
  name: "SlapButton",
  data() {
    return {
      randomChoice: false
    }
  },
  methods: {
    getDecision: function () {
      var decisions = [
        "choice 1",
        "choice 2",
        "choice 3",
        "choice 4",
        "choice 5",
        "choice 6"
      ]
      var randNum = Math.floor((Math.random() * decisions.length) + 0);
      this.randomChoice = decisions[randNum];
    }
  }
}

Now just show this data in your element like this:

<p id="results-box"> {{randomChoice}} </p>


问:
How to match such type
I have:

```<code>infixr 9 |||
data a ||| b = A a|B b deriving (Eq, Data, Show)

class IsTag a where
  anyTag :: a
</code>```

and I keep in this a|||b some values, which are instances of IsTag, for example: A (B (A x)) - the deep of nesting can be any, sure. And I want to write function which detects that x is equal to anyTag, so it takes a|||b and returns Bool - is underlying value (x in the example) equal to anyTag of x's instance or not. How to write such function? I can't do pattern-matching due to errors like "infinite type", etc. I added deriving Data to a|||b and to x's type in the hope that it will be possible to use something from Data, but I can't understand how to fold/traverse via such recursive type.

答:
It won't get much better than this:

```<code>{-# LANGUAGE DefaultSignatures #-}
class IsAnyTag a where
    isAnyTag :: a -> Bool
    default isAnyTag :: (Eq a, IsTag a) => a -> Bool
    isAnyTag = (anyTag ==)

instance (IsAnyTag a, IsAnyTag b) => IsAnyTag (a ||| b) where
    isAnyTag (A a) = isAnyTag a
    isAnyTag (B b) = isAnyTag b

-- and one more line of `instance IsAnyTag X` for each `X` that
-- is an instance of `IsTag`
</code>```

The main drawback here is that this requires that the types on both sides of the ||| will have to be IsAnyTag instances, even though you are testing only one side. Them's the breaks with static type checking.

Title: How to match such type

Body:
I have:

infixr 9 |||
data a ||| b = A a|B b deriving (Eq, Data, Show)

class IsTag a where
  anyTag :: a

and I keep in this a|||b some values, which are instances of IsTag, for example: A (B (A x)) - the deep of nesting can be any, sure. And I want to write function which detects that x is equal to anyTag, so it takes a|||b and returns Bool - is underlying value (x in the example) equal to anyTag of x's instance or not. How to write such function? I can't do pattern-matching due to errors like "infinite type", etc. I added deriving Data to a|||b and to x's type in the hope that it will be possible to use something from Data, but I can't understand how to fold/traverse via such recursive type.

Body:
It won't get much better than this:

{-# LANGUAGE DefaultSignatures #-}
class IsAnyTag a where
    isAnyTag :: a -> Bool
    default isAnyTag :: (Eq a, IsTag a) => a -> Bool
    isAnyTag = (anyTag ==)

instance (IsAnyTag a, IsAnyTag b) => IsAnyTag (a ||| b) where
    isAnyTag (A a) = isAnyTag a
    isAnyTag (B b) = isAnyTag b

-- and one more line of `instance IsAnyTag X` for each `X` that
-- is an instance of `IsTag`

The main drawback here is that this requires that the types on both sides of the ||| will have to be IsAnyTag instances, even though you are testing only one side. Them's the breaks with static type checking.


问:
Remove twig include on specific template
I'm trying to work this out and failing.

Say i have a base.twig where i want to output a heading. I want this on every child template that extends base.twig but one. Is it possible to remove an include from a page after running an extend?

base.twig

```<code>{% include "partial/heading.twig" %}
</code>```

template-without-the-damned-thing.tig

```<code>{% extends 'base.twig' %}

{% some form or magic to make that damned heading not come out %}
</code>```

答:
No, you can't 'uninclude' a template.

But there is an alternative: put the title in a block and override it by the child template:

partial/heading.twig

```<code>{%- block heading -%}
    <h1>Your title</h1>
    <div>..</div>
{%- endblock heading -%}
</code>```

template-without-the-damned-thing.twig

```<code>{% extend 'base.twig.html' %}
{%- block heading -%}
{%- endblock heading -%}
</code>```

Body:
I'm trying to work this out and failing.

Say i have a base.twig where i want to output a heading. I want this on every child template that extends base.twig but one. Is it possible to remove an include from a page after running an extend?

base.twig

{% include "partial/heading.twig" %}

template-without-the-damned-thing.tig

{% extends 'base.twig' %}

{% some form or magic to make that damned heading not come out %}

Body:
No, you can't 'uninclude' a template.

But there is an alternative: put the title in a block and override it by the child template:

partial/heading.twig

{%- block heading -%}
    <h1>Your title</h1>
    <div>..</div>
{%- endblock heading -%}

template-without-the-damned-thing.twig

{% extend 'base.twig.html' %}
{%- block heading -%}
{%- endblock heading -%}


问:
How do frameworks like codeigniter do their page caching?
I know that codeigniter seems to save the view output for a specified number of minutes, and if s user requests that page again within that many minutes, it will serve the saved version of the page instead of processing the request again. It seems to save all output from the view in a file, but how does it do that? And then, how does it know what the expire time for these cached files are?

On top of that, how would one create login security for pages using this type of cache model?

Any insight would be greatly appreciated. Thanks!

答:
At line 177 of CodeIgniter.php in core/:

```<code>if ($EXT->_call_hook('cache_override') === FALSE)
    {
        if ($OUT->_display_cache($CFG, $URI) == TRUE)
        {
            exit;
        }
    }
</code>```

It checks for a cached file and displays this instead of processing the controller/action code.

You can also read how the cached file is checked for expiration by the Output class before it is being displayed.

```<code>function _display_cache(&$CFG, &$URI)
{
    $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');

    // Build the file path.  The file name is an MD5 hash of the full URI
    $uri =  $CFG->item('base_url').
            $CFG->item('index_page').
            $URI->uri_string;

    $filepath = $cache_path.md5($uri);

    if ( ! @file_exists($filepath))
    {
        return FALSE;
    }

    if ( ! $fp = @fopen($filepath, FOPEN_READ))
    {
        return FALSE;
    }

    flock($fp, LOCK_SH);

    $cache = '';
    if (filesize($filepath) > 0)
    {
        $cache = fread($fp, filesize($filepath));
    }

    flock($fp, LOCK_UN);
    fclose($fp);

    // Strip out the embedded timestamp
    if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
    {
        return FALSE;
    }

    // Has the file expired? If so we'll delete it.
    if (time() >= trim(str_replace('TS--->', '', $match['1'])))
    {
        if (is_really_writable($cache_path))
        {
            @unlink($filepath);
            log_message('debug', "Cache file has expired. File deleted");
            return FALSE;
        }
    }

    // Display the cache
    $this->_display(str_replace($match['0'], '', $cache));
    log_message('debug', "Cache file is current. Sending it to browser.");
    return TRUE;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
At line 177 of CodeIgniter.php in core/:

if ($EXT->_call_hook('cache_override') === FALSE)
    {
        if ($OUT->_display_cache($CFG, $URI) == TRUE)
        {
            exit;
        }
    }

It checks for a cached file and displays this instead of processing the controller/action code.

You can also read how the cached file is checked for expiration by the Output class before it is being displayed.

function _display_cache(&$CFG, &$URI)
{
    $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');

    // Build the file path.  The file name is an MD5 hash of the full URI
    $uri =  $CFG->item('base_url').
            $CFG->item('index_page').
            $URI->uri_string;

    $filepath = $cache_path.md5($uri);

    if ( ! @file_exists($filepath))
    {
        return FALSE;
    }

    if ( ! $fp = @fopen($filepath, FOPEN_READ))
    {
        return FALSE;
    }

    flock($fp, LOCK_SH);

    $cache = '';
    if (filesize($filepath) > 0)
    {
        $cache = fread($fp, filesize($filepath));
    }

    flock($fp, LOCK_UN);
    fclose($fp);

    // Strip out the embedded timestamp
    if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
    {
        return FALSE;
    }

    // Has the file expired? If so we'll delete it.
    if (time() >= trim(str_replace('TS--->', '', $match['1'])))
    {
        if (is_really_writable($cache_path))
        {
            @unlink($filepath);
            log_message('debug', "Cache file has expired. File deleted");
            return FALSE;
        }
    }

    // Display the cache
    $this->_display(str_replace($match['0'], '', $cache));
    log_message('debug', "Cache file is current. Sending it to browser.");
    return TRUE;
}


问:
Conquering Active Directory's 1000 record limit
PowerShell is capable of pulling  list of 1492 records. When I using Python with ldap3 module I'm bumping into 1000 records limit. Please help me change Python code to exceed the limit.

PowerShell input: get-aduser -filter  * -SearchBase "OU=SMZ USERS,OU=SMZ,OU=EUR,DC=my_dc,DC=COM" | Measure-Object

output:
Count    : 1492
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

```<code>import json
from ldap3 import Server, \
Connection, \
AUTO_BIND_NO_TLS, \
SUBTREE, \
ALL_ATTRIBUTES

def get_ldap_info(u):
with Connection(Server('my_server', port=636, use_ssl=True),
                auto_bind=AUTO_BIND_NO_TLS,
                read_only=True,
                check_names=True,
                user='my_login', password='my_password') as c:

    c.search(search_base='OU=SMZ Users,OU=SMZ,OU=EUR,DC=my_dc,DC=com',
             search_filter='(&(samAccountName=' + u + '))',
             search_scope=SUBTREE,
             attributes=ALL_ATTRIBUTES,
             size_limit = 0,
             paged_criticality = True,
             paged_size = None,
             #attributes = ['cn'],
             get_operational_attributes=True)

    content = c.response_to_json()
result = json.loads(content)
i = 0
for item in result["entries"]:
    i += 1
print(i)
get_ldap_info('*')
</code>```

答:
If you change your code to using the paged_search method of the extend.standard namespace instead you should be able to retrieve all the results you are looking for.

Just be aware that you will need to treat the response object differently.

```<code>def get_ldap_info(u):
with Connection(Server('XXX', port=636, use_ssl=True),
                auto_bind=AUTO_BIND_NO_TLS,
                read_only=True,
                check_names=True,
                user='XXX', password='XXX') as c:

    results = c.extend.standard.paged_search(search_base='dc=XXX,dc=XXX,dc=XXX',
             search_filter='(&(samAccountName=' + u + '))',
             search_scope=SUBTREE,
             attributes=ALL_ATTRIBUTES,
             #attributes = ['cn'],
             get_operational_attributes=True)

i = 0
for item in results:
    #print(item)
    i += 1
print(i)
get_ldap_info('*')
</code>```

Body:
PowerShell is capable of pulling  list of 1492 records. When I using Python with ldap3 module I'm bumping into 1000 records limit. Please help me change Python code to exceed the limit.

PowerShell input: get-aduser -filter  * -SearchBase "OU=SMZ USERS,OU=SMZ,OU=EUR,DC=my_dc,DC=COM" | Measure-Object

output:
Count    : 1492
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

import json
from ldap3 import Server, \
Connection, \
AUTO_BIND_NO_TLS, \
SUBTREE, \
ALL_ATTRIBUTES

def get_ldap_info(u):
with Connection(Server('my_server', port=636, use_ssl=True),
                auto_bind=AUTO_BIND_NO_TLS,
                read_only=True,
                check_names=True,
                user='my_login', password='my_password') as c:

    c.search(search_base='OU=SMZ Users,OU=SMZ,OU=EUR,DC=my_dc,DC=com',
             search_filter='(&(samAccountName=' + u + '))',
             search_scope=SUBTREE,
             attributes=ALL_ATTRIBUTES,
             size_limit = 0,
             paged_criticality = True,
             paged_size = None,
             #attributes = ['cn'],
             get_operational_attributes=True)

    content = c.response_to_json()
result = json.loads(content)
i = 0
for item in result["entries"]:
    i += 1
print(i)
get_ldap_info('*')

Body:
If you change your code to using the paged_search method of the extend.standard namespace instead you should be able to retrieve all the results you are looking for.

Just be aware that you will need to treat the response object differently.

def get_ldap_info(u):
with Connection(Server('XXX', port=636, use_ssl=True),
                auto_bind=AUTO_BIND_NO_TLS,
                read_only=True,
                check_names=True,
                user='XXX', password='XXX') as c:

    results = c.extend.standard.paged_search(search_base='dc=XXX,dc=XXX,dc=XXX',
             search_filter='(&(samAccountName=' + u + '))',
             search_scope=SUBTREE,
             attributes=ALL_ATTRIBUTES,
             #attributes = ['cn'],
             get_operational_attributes=True)

i = 0
for item in results:
    #print(item)
    i += 1
print(i)
get_ldap_info('*')


问:
Regex in jmeter to not match string containing substring
My Response data is -

MyString=01015400007715243552T2867X01051005012447/3/1207/7\u0026index=2

MyString=014274X9000010152435500000MT2867X0154992365418/3/1207/7\u0026index=3

where i want to write a regex to match first string and ignore second string,below is my requirement.

As i highlighted in second string if the value contains X9 i should not match that string.

I tried many regex ,but dint help me much.
i tried MyString=(.*[^X9].+?)u0026
Please can someone help me

答:
You can try using the following regular expression:

```<code>MyString=(?:(?!X9).)*\\u0026
</code>```

Demo:

References:

JMeter: Regular Expressions

Using RegEx (Regular Expression Extractor) with JMeter

Perl: Matching string not containing PATTERN

Perl 5 Regex Cheat sheet

Body:
You can try using the following regular expression:

MyString=(?:(?!X9).)*\\u0026

Demo:

References:

JMeter: Regular Expressions

Using RegEx (Regular Expression Extractor) with JMeter

Perl: Matching string not containing PATTERN

Perl 5 Regex Cheat sheet


问:
how to hide column in export
How to hide the select all(checkbox) column in excel or csv export.</p>

```<code>{
    checkboxSelection: true,
    suppressMenu: true,
    suppressSorting: true,
    suppressFilter: true,
    width: 30,
    pinned: true,
    suppressExcelExport :true,
    headerCellRenderer: this.selectAllRenderer
},
</code>```

答:
below code will solve your problem</p>

```<code>var columnsForExport=[];
var allColumns=gridOption.columnApi.getAllColumns();

allColumns.forEach((element:any) => {
    if(element.colId!="#"){
        columnsForExport.push(element.colId)
    }
});
</code>```

Title: how to hide column in export

Body:
How to hide the select all(checkbox) column in excel or csv export.

{
    checkboxSelection: true,
    suppressMenu: true,
    suppressSorting: true,
    suppressFilter: true,
    width: 30,
    pinned: true,
    suppressExcelExport :true,
    headerCellRenderer: this.selectAllRenderer
},

Body:
below code will solve your problem

var columnsForExport=[];
var allColumns=gridOption.columnApi.getAllColumns();

allColumns.forEach((element:any) => {
    if(element.colId!="#"){
        columnsForExport.push(element.colId)
    }
});


问:
No output from my react app
I am very interested in learning Reactjs, i watched some tutorials on YouTube.

I also followed some other tutorials on the internet like this tutorial.

My main issue is when i try to run the first example from the tutorial mentioned above, the code gives no result, have i missed something ? (i use IntelliJ IDEA.)

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>React tutorial</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>

<div id="content"></div>

<script type="text/jsx">

    var TimerExample = React.createClass({

        getInitialState: function(){

            // This is called before our render function. The object that is
            // returned is assigned to this.state, so we can use it later.

            return { elapsed: 0 };
        },

        componentDidMount: function(){

            // componentDidMount is called by react when the component
            // has been rendered on the page. We can set the interval here:

            this.timer = setInterval(this.tick, 50);
        },

        componentWillUnmount: function(){

            // This method is called immediately before the component is removed
            // from the page and destroyed. We can clear the interval here:

            clearInterval(this.timer);
        },

        tick: function(){

            // This function is called every 50 ms. It updates the
            // elapsed counter. Calling setState causes the component to be re-rendered

            this.setState({elapsed: new Date() - this.props.start});
        },

        render: function() {

            var elapsed = Math.round(this.state.elapsed / 100);

            // This will give a number with one digit after the decimal dot (xx.x):
            var seconds = (elapsed / 10).toFixed(1);

            // Although we return an entire <p> element, react will smartly update
            // only the changed parts, which contain the seconds variable.

            return <p>This example was started <b>{seconds} seconds</b> ago.</p>;
        }
    });

    ReactDOM.render(
            <TimerExample start={Date.now()} />,
        document.getElementById('content')
    );
</script>

</body>
</html>
</code>```

答:
Am i missed something?

Yes, you mixed two important parts: "React" and "ReactDOM". Initially react was a single lib that contained all the code but after v0.14 single lib has been splitted into two parts "react" and "react-dom".

For more details check this: React vs ReactDOM?

Solution to your problem:

You are using v0.13 so use React.render instead of ReactDOM.render. Another possible solution is use these scripts (separate libs):

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</code>```

Also you don't need JQuery, so you can remove the reference.

Suggestion: Check the doc for more updates and better ways.

Working snippet by using React.render:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>React tutorial</title>

```

Title: No output from my react app

Body:
I am very interested in learning Reactjs, i watched some tutorials on YouTube.

I also followed some other tutorials on the internet like this tutorial.

My main issue is when i try to run the first example from the tutorial mentioned above, the code gives no result, have i missed something ? (i use IntelliJ IDEA.)

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>React tutorial</title>

Body:
Am i missed something?

Yes, you mixed two important parts: "React" and "ReactDOM". Initially react was a single lib that contained all the code but after v0.14 single lib has been splitted into two parts "react" and "react-dom".

For more details check this: React vs ReactDOM?

Solution to your problem:

You are using v0.13 so use React.render instead of ReactDOM.render. Another possible solution is use these scripts (separate libs):

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Also you don't need JQuery, so you can remove the reference.

Suggestion: Check the doc for more updates and better ways.

Working snippet by using React.render:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>React tutorial</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
</head>
<body>

<div id="content"></div>

<script type="text/jsx">

    var TimerExample = React.createClass({

        getInitialState: function(){

            // This is called before our render function. The object that is
            // returned is assigned to this.state, so we can use it later.

            return { elapsed: 0 };
        },

        componentDidMount: function(){

            // componentDidMount is called by react when the component
            // has been rendered on the page. We can set the interval here:

            this.timer = setInterval(this.tick, 50);
        },

        componentWillUnmount: function(){

            // This method is called immediately before the component is removed
            // from the page and destroyed. We can clear the interval here:

            clearInterval(this.timer);
        },

        tick: function(){

            // This function is called every 50 ms. It updates the
            // elapsed counter. Calling setState causes the component to be re-rendered

            this.setState({elapsed: new Date() - this.props.start});
        },

        render: function() {

            var elapsed = Math.round(this.state.elapsed / 100);

            // This will give a number with one digit after the decimal dot (xx.x):
            var seconds = (elapsed / 10).toFixed(1);

            // Although we return an entire <p> element, react will smartly update
            // only the changed parts, which contain the seconds variable.

            return <p>This example was started <b>{seconds} seconds</b> ago.</p>;
        }
    });

    React.render(
            <TimerExample start={Date.now()} />,
        document.getElementById('content')
    );
</script>

</body>
</html>


问:
How do I run a function over and over by using parameters?
My case:

```<code>function randomLetter(){
    var random = letter[Math.floor(Math.random()*26)];
    return random;
}

function randomWord(wordLength){
    var random = randomLetter() + randomLetter() + randomLetter();
    return random;
}
</code>```

How do I write a code that run the randomLetter() function x times using parametes.

Example: I write 3 in the parameter, and the function will give me three random letters.

So instead of writing randomLetter() + randomLetter() + randomLetter(), I will just write randomWord(3), and I will get three random letters.

答:
Another approach, which buffers each letter into an array and returns the joined array.</p>

```<code>function randomWord(wordLength){
    var letters = [];

    for (var i = 0; i < wordLength; i++) {
        letters.push(randomLetter());
    }

    return letters.join("");
}
</code>```

Body:
My case:

function randomLetter(){
    var random = letter[Math.floor(Math.random()*26)];
    return random;
}

function randomWord(wordLength){
    var random = randomLetter() + randomLetter() + randomLetter();
    return random;
}

How do I write a code that run the randomLetter() function x times using parametes.

Example: I write 3 in the parameter, and the function will give me three random letters.

So instead of writing randomLetter() + randomLetter() + randomLetter(), I will just write randomWord(3), and I will get three random letters.

Body:
Another approach, which buffers each letter into an array and returns the joined array.

function randomWord(wordLength){
    var letters = [];

    for (var i = 0; i < wordLength; i++) {
        letters.push(randomLetter());
    }

    return letters.join("");
}


问:
How to derive the equation of a density distribution in SAS?
I am using the following procedure to get the density plot of transaction counts:

```<code>PROC SGPLOT DATA = Tran_Restaurant ;
  density Transaction_Count/ scale=density ;
  "Restaurant Transaction Count";
  XAXIS LABEL = 'Transaction_Count' GRID VALUES = (0 TO 100 BY 10);
RUN;
</code>```

Sample Data:

```<code>Customer_ID   Transaction_Count
1213x         23
2131x         14
</code>```

Customer_ID is distinct in the data set.
So, from the plot for each transaction_count we can get the number of customers.

I wanted to get the equation of the density curve? Is it possible to do that in SAS?

答:
You can use ODS OUTPUT to get the specific data points into a dataset; like so:

```<code>ods output sgplot=datapoints;
proc sgplot ... ;
run;
ods output close;
</code>```

It won't give you the equation, however.  The equation is given in the documentation; you'd just have to calculate the parameters in PROC MEANS or somewhere else, I suppose.  I don't know of a way to get SGPLOT to give you them directly.

Body:
I am using the following procedure to get the density plot of transaction counts:

PROC SGPLOT DATA = Tran_Restaurant ;
  density Transaction_Count/ scale=density ;
  "Restaurant Transaction Count";
  XAXIS LABEL = 'Transaction_Count' GRID VALUES = (0 TO 100 BY 10);
RUN;

Sample Data:

Customer_ID   Transaction_Count
1213x         23
2131x         14

Customer_ID is distinct in the data set.
So, from the plot for each transaction_count we can get the number of customers.

I wanted to get the equation of the density curve? Is it possible to do that in SAS?

Body:
You can use ODS OUTPUT to get the specific data points into a dataset; like so:

ods output sgplot=datapoints;
proc sgplot ... ;
run;
ods output close;

It won't give you the equation, however.  The equation is given in the documentation; you'd just have to calculate the parameters in PROC MEANS or somewhere else, I suppose.  I don't know of a way to get SGPLOT to give you them directly.


答:
For this you could use a for loop like:

```<code>function randomWord(wordLength){
  var random =''
  for (var i = 0, i<wordLength, i++) {
    random += randomLetter();
  }
  return random;
}
</code>```

the first parameter in the parentheses after the 'for' keyword initializes the i variable with 0. The next value i<wordLength is the stop condition, which will test at the beginning of each run if the condition is still true, otherwise it will stop looping. The third i++ is what runs every time a loop finishes, in this case it increments i by one, which is identical to i = i + 1.

here is some more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

Title: How do I run a function over and over by using parameters?

Body:
For this you could use a for loop like:

function randomWord(wordLength){
  var random =''
  for (var i = 0, i<wordLength, i++) {
    random += randomLetter();
  }
  return random;
}

the first parameter in the parentheses after the 'for' keyword initializes the i variable with 0. The next value i<wordLength is the stop condition, which will test at the beginning of each run if the condition is still true, otherwise it will stop looping. The third i++ is what runs every time a loop finishes, in this case it increments i by one, which is identical to i = i + 1.

here is some more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration


问:
Determine the size of an InputStream
My current situation is: I have to read a file and put the contents into InputStream. Afterwards I need to place the contents of the InputStream into a byte array which requires (as far as I know) the size of the InputStream. Any ideas?

As requested, I will show the input stream that I am creating from an uploaded file

```<code>InputStream uploadedStream = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
java.util.List items = upload.parseRequest(request);
java.util.Iterator iter = items.iterator();

while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();
    if (!item.isFormField()) {
        uploadedStream = item.getInputStream();
        //CHANGE uploadedStreambyte = item.get()
    }
}
</code>```

The request is a HttpServletRequest object, which is like the FileItemFactory and ServletFileUpload is from the Apache Commons FileUpload package.

答:
```<code>    try {
        InputStream connInputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int size = connInputStream.available();
</code>```

int available ()
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

InputStream - Android SDK | Android Developers

Title: Determine the size of an InputStream

Body:
My current situation is: I have to read a file and put the contents into InputStream. Afterwards I need to place the contents of the InputStream into a byte array which requires (as far as I know) the size of the InputStream. Any ideas?

As requested, I will show the input stream that I am creating from an uploaded file

InputStream uploadedStream = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
java.util.List items = upload.parseRequest(request);
java.util.Iterator iter = items.iterator();

while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();
    if (!item.isFormField()) {
        uploadedStream = item.getInputStream();
        //CHANGE uploadedStreambyte = item.get()
    }
}

The request is a HttpServletRequest object, which is like the FileItemFactory and ServletFileUpload is from the Apache Commons FileUpload package.

Body:
    try {
        InputStream connInputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int size = connInputStream.available();

int available ()
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

InputStream - Android SDK | Android Developers


答:
Or recursion:

var letters = "abcdefghijklmnopqrstuvwxyz"
function randomLetter() {
  return letters.charAt(Math.floor((Math.random() * 100)) % letters.length)
}

function getLetters(count) {
  if (count-- < 1) return "";
  return getLetters(count) + randomLetter() + ","
}

document.getElementById("output").innerText = getLetters(4)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output" /></code>```

Body:
Or recursion:

var letters = "abcdefghijklmnopqrstuvwxyz"
function randomLetter() {
  return letters.charAt(Math.floor((Math.random() * 100)) % letters.length)
}

function getLetters(count) {
  if (count-- < 1) return "";
  return getLetters(count) + randomLetter() + ","
}

document.getElementById("output").innerText = getLetters(4)

<div id="output" />


问:
Bash as a C lib?
I've got a project where I want to do some stuff that would be trivial in bash but where I want/need a binary with has zero external dependencies. So, has anyone written a self contained lib (i.e. not a wrapper around system()) that lets you do bash like stuff from inside C?

Off hand, the things I expect to need are: cp, rm, wget, tftp, ar, tar, guzip and maybe dpkg but I think I can side step that one.

To answer the comments: I'm looking for something along the lines of a statically linked busy-box but where I don't need a shell file as a program for it and where things I don't use automatically don't even get linked in.

答: I fully agree with Busybox. Additionally, if you get the source code for dpkg, you'll find a small library inside that gives you access to most of its functionality.</p>

Title: Bash as a C lib?


问:
Python - string and tuple comparison
How to compare a string and a tuple, raise an error if the string has repeated letters , for example ('PTMP',('P','T','M'))  will say raise ValueError(...) but if the tuple had an extra P, like in  ('P','T','M','P') the answer would be valid?

```<code>def whatever(string,tup):
    for j in string:
        if j not in tup:
            raise ValueError('')
        for u in tup:
            if j not in tup: raise ValueError('')
</code>```

答:
If the characters are supposed to be in the same order in the string and the tuple then this will work for you:</p>

```<code>if (len(x) == len(y) and all(x[i] == y[i] for i in range(len(x)))):
    raise ValueError()
else:
    # Be happy
</code>```

Title: Python - string and tuple comparison

Body:
How to compare a string and a tuple, raise an error if the string has repeated letters , for example ('PTMP',('P','T','M'))  will say raise ValueError(...) but if the tuple had an extra P, like in  ('P','T','M','P') the answer would be valid?

def whatever(string,tup):
    for j in string:
        if j not in tup:
            raise ValueError('')
        for u in tup:
            if j not in tup: raise ValueError('')

Body:
If the characters are supposed to be in the same order in the string and the tuple then this will work for you:

if (len(x) == len(y) and all(x[i] == y[i] for i in range(len(x)))):
    raise ValueError()
else:
    # Be happy


问:
continue not working? [c++]
Hi guys I've run into a problem,for some reason a blank string is being printed or you could also say nothing is being printed when I try to print out the string,this only occurs when I include a capital letter in the string such as acB if I type acb it sorts and prints them with no problems,I added a continue statement in to the for loop because I thought this would skip the rest of the code and go to the next iteration if that block of code got executed but to no avail anyway here is my code.</p>

```<code>void order(char *str,int size){

     bool sorted = false;

     while(!sorted){

        sorted = true;

        for(int i = 0; i < size-1; i++){

              if(str[i] >= 'A' && str[i] <= 'Z'){

                if((str[i+1])-32 < str[i]){

                    char temp2 = str[i];
                    str[i] = str[i+1];
                    str[i+1] = temp2;
                    sorted = false;
                    continue;
                }
              }
              if(str[i+1] < str[i]){

                char temp = str[i];
                str[i] = str[i+1];
                str[i+1] = temp;

                sorted = false;
            }
        }
     }
}
int main()
{
    char str[] = "aCb";
    int size = sizeof(str) / sizeof(char);
    order(str,size-1);
    cout << str << endl;
}
</code>```

答:
```<code>    void order(char *str,int size){

     bool sorted = false;

     while(!sorted){

        sorted = true;

        for(int i = 0; i < size - 1; i++){

          if(str[i+1] >= 'A' && str[i+1] <= 'Z' && str[i] > 'Z'){
            if(str[i+1] < str[i] - 32){
              char temp2 = str[i];
              str[i] = str[i+1];
              str[i+1] = temp2;
              sorted = false;
              continue;
            }
          }
          else{
            if(str[i] >= 'A' && str[i] <= 'Z' && str[i + 1] >= 'Z'){
              if(str[i+1] -32 < str[i]){
                char temp2 = str[i];
                str[i] = str[i+1];
                str[i+1] = temp2;
                sorted = false;
                continue;
              }
            }

            if(str[i+1] < str[i]){
              char temp2 = str[i];
              str[i] = str[i+1];
              str[i+1] = temp2;
              sorted = false;
              continue;
            }
          }
        }
     }
}

int main()
{
    char str[] = "aCB";
    int size = sizeof(str) / sizeof(char);
    order(str,size-1);
    cout << str << endl;
}
</code>```

First IF: Checks if the first letter is lowercase and the second letter is uppercase.

Second IF: Checks if the first letter is uppercase and the second letter is lowercase.

Third IF: then both letters are uppercase or lowercase.

Title: continue not working? [c++]

Body:
Hi guys I've run into a problem,for some reason a blank string is being printed or you could also say nothing is being printed when I try to print out the string,this only occurs when I include a capital letter in the string such as acB if I type acb it sorts and prints them with no problems,I added a continue statement in to the for loop because I thought this would skip the rest of the code and go to the next iteration if that block of code got executed but to no avail anyway here is my code.

void order(char *str,int size){

     bool sorted = false;

     while(!sorted){

        sorted = true;

        for(int i = 0; i < size-1; i++){

              if(str[i] >= 'A' && str[i] <= 'Z'){

                if((str[i+1])-32 < str[i]){

                    char temp2 = str[i];
                    str[i] = str[i+1];
                    str[i+1] = temp2;
                    sorted = false;
                    continue;
                }
              }
              if(str[i+1] < str[i]){

                char temp = str[i];
                str[i] = str[i+1];
                str[i+1] = temp;

                sorted = false;
            }
        }
     }
}
int main()
{
    char str[] = "aCb";
    int size = sizeof(str) / sizeof(char);
    order(str,size-1);
    cout << str << endl;
}

Body:
    void order(char *str,int size){

     bool sorted = false;

     while(!sorted){

        sorted = true;

        for(int i = 0; i < size - 1; i++){

          if(str[i+1] >= 'A' && str[i+1] <= 'Z' && str[i] > 'Z'){
            if(str[i+1] < str[i] - 32){
              char temp2 = str[i];
              str[i] = str[i+1];
              str[i+1] = temp2;
              sorted = false;
              continue;
            }
          }
          else{
            if(str[i] >= 'A' && str[i] <= 'Z' && str[i + 1] >= 'Z'){
              if(str[i+1] -32 < str[i]){
                char temp2 = str[i];
                str[i] = str[i+1];
                str[i+1] = temp2;
                sorted = false;
                continue;
              }
            }

            if(str[i+1] < str[i]){
              char temp2 = str[i];
              str[i] = str[i+1];
              str[i+1] = temp2;
              sorted = false;
              continue;
            }
          }
        }
     }
}

int main()
{
    char str[] = "aCB";
    int size = sizeof(str) / sizeof(char);
    order(str,size-1);
    cout << str << endl;
}

First IF: Checks if the first letter is lowercase and the second letter is uppercase.

Second IF: Checks if the first letter is uppercase and the second letter is lowercase.

Third IF: then both letters are uppercase or lowercase.


问:
Angular response is undefined
Trying to retrieve using angular the json found at: "https://api.github.com/users/angular", more precisely the id property from that json.
Any thoughts on why this fails (in debug mode I get a

'response is not defined'

):

```<code><html ng-app="myViewer">
<head>
<script data-require="angular.js@*" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
</head>

<body ng-controller="MyController">
    {{ result.id }}
    {{ err }}
</body>

<script type="text/javascript">
(function() {

    var app = angular.module("myViewer", []);

    var MyController = function($scope, $http)
    {
        $http.get("https://api.github.com/users/angular")
        .then(function1, onerr);

        var function1 = function(response)
        {
            $scope.result = response.data;
        }
        var onerr = function(reason)
        {
            $scope.err = "nightmare";
        }

    }

    app.controller("MyController", ["$scope", "$http", MyController]);
}());

</script>
</html>
</code>```

I expect the result to be the id that you can see by copying that link in your browser.

答:
Here is a working fiddler https://jsfiddle.net/paka2/8roj37q9/1/

```<code>angular.module("myViewer", []).controller("myCtrl", function($scope,$http){
this.result = {};
this.err ;
         $http.get("https://api.github.com/users/angular")
        .then(function1, onerr) ;
    function function1 (response)
    {
      $scope.result = response.data;
    }
    function onerr (reason)
    {
      $scope.err = "nightmare";
    }
});
</code>```

Hope it helps!!

Title: Angular response is undefined

Body:
Trying to retrieve using angular the json found at: "https://api.github.com/users/angular", more precisely the id property from that json.
Any thoughts on why this fails (in debug mode I get a

'response is not defined'

):

    {{ result.id }}
    {{ err }}

I expect the result to be the id that you can see by copying that link in your browser.

Body:
Here is a working fiddler https://jsfiddle.net/paka2/8roj37q9/1/

angular.module("myViewer", []).controller("myCtrl", function($scope,$http){
this.result = {};
this.err ;
         $http.get("https://api.github.com/users/angular")
        .then(function1, onerr) ;
    function function1 (response)
    {
      $scope.result = response.data;
    }
    function onerr (reason)
    {
      $scope.err = "nightmare";
    }
});

Hope it helps!!


问:
Unity Minimize Battery Usage
I'm trying to make a simple non-game app that is a couple different UI pages to simplify. Is it possible to make this in unity and not be a heavy battery destroyer?

I know that unity is a game engine at its core and is not ideal for non-game apps, but its so freakin user friendly and customizable I would rather use Unity than anything else if i can. I guess I'm wondering if it's viable to make this kind of app in Unity, or/and possible to reduce battery usage so that it becomes more viable.

If its not a viable in any form to make a small non-game app using Unity then I will sadly understand, just looking for expert input on the topic and its viability.

Thanks

p.s. If Unity is not viable, is there any other c# or similar cross platform you'd recommend for the job?

答:
The Quality Settings inspector (menu: Edit > Project Settings > Quality) is used to select the quality level in the editor for the chosen device. It is split into two main areas - at the top, there is the following matrix:

You can click on the name of a quality level to select it for editing, which is done in the panel below the settings matrix:

Source:
https://docs.unity3d.com/Manual/class-QualitySettings.html

Retrieved at 5 Dec 2017

Title: Unity Minimize Battery Usage


问:
Angular 2 *ngIf not reevaluation on model change
I have a navbar with 2 buttons. I wish to only show the button for the other page and disable the button for the current page.

On opening the settings page, the settings button is hidden. When I click the profile button, it doesn't disable and settings button doesn't appear.

Here's the component class code:

export class SettingsComponent implements OnInit {
   isSettingsProfile = false;
   isSettingsHome = false;

   ngOnInit() {
       this.isSettingsHome = true;
       this.isSettingsProfile = false;
   }

   OnNavBarClick(button: string) {
       if (button = "settings") {
           console.log ('setting home true/ profile false')
           this.isSettingsHome = true;
           this.isSettingsProfile = false;
       }
       else if (button = "profiles") {
           console.log ('setting home false/ profile true')
           this.isSettingsProfile = true;
           this.isSettingsHome = false;
       }

   }```
</div>
</div>
</p>

<p>And the navbar html:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <ul class="nav navbar-nav navbar-right">
            <li> Home</li>
            <li *ngIf="!isSettingsHome" class="active">Settings</li>
            <li *ngIf="!isSettingsProfile">Profile</li>
        </ul></code>```

Any suggestions?

答:
I had this issue when implementing a breadcrumb component and have applied the solution proposed in this SO answer. I had to change to

```<code>import { ChangeDetectorRef } from '@angular/core';
</code>```

because I use angular4 and then call

detectChanges()

at the end of your function OnNavBarClick()

Body:
I have a navbar with 2 buttons. I wish to only show the button for the other page and disable the button for the current page.

On opening the settings page, the settings button is hidden. When I click the profile button, it doesn't disable and settings button doesn't appear.

Here's the component class code:

export class SettingsComponent implements OnInit {
   isSettingsProfile = false;
   isSettingsHome = false;

   ngOnInit() {
       this.isSettingsHome = true;
       this.isSettingsProfile = false;
   }

   OnNavBarClick(button: string) {
       if (button = "settings") {
           console.log ('setting home true/ profile false')
           this.isSettingsHome = true;
           this.isSettingsProfile = false;
       }
       else if (button = "profiles") {
           console.log ('setting home false/ profile true')
           this.isSettingsProfile = true;
           this.isSettingsHome = false;
       }

   }

And the navbar html:

 Home

Settings

Profile

Any suggestions?

Body:
I had this issue when implementing a breadcrumb component and have applied the solution proposed in this SO answer. I had to change to

import { ChangeDetectorRef } from '@angular/core';

because I use angular4 and then call

detectChanges()

at the end of your function OnNavBarClick()


问:
Bat To ini converter
Basically what I want to do is rename the batch file to .ini instead of .bat and put 1= for the first line and 2= before the second and so on and so on.

My batch file:

```<code>@echo off

color F0

cls

:strt

echo Drag your file in this window to make a ini from it.

set /p file=File path with " " :

del config.ini

for /F "usebackq tokens=* delims=*" %%j in (%file%) do echo 1=%%j>>config.ini

for /F "usebackq tokens=* delims=* skip=1" %%j in (%file%) do echo 2=%%j>>config.ini

for /F "usebackq tokens=* delims=* skip=2" %%j in (%file%) do echo 3=%%j>>config.ini

exit
</code>```

and my result is this when I use a random text file:

```<code>1=lol1

1=lol2

1=lol3

1=lol4

2=lol1

2=lol2

2=lol3

2=lol4

3=lol1

3=lol2

3=lol3

3=lol4
</code>```

and what I want is this:

```<code>1=lol1

2=lol2

3=lol3
</code>```

while the original .txt is:

```<code>lol1

lol2

lol3

lol4
</code>```

so it basically works but it does not stop at the end of the first line it writes it writes the whole file how do I solve this? Cause I'm out of options.

答:
answer found sry but this works better for me maybe this will help someone tho's.
Finished product below.</p>

```<code>@echo off
setLocal EnableDelayedExpansion
color F0
@mode con cols=52 lines=10
cls
echo Drag your file in this window to make a ini from it.
echo Remember if you type it in use "path" with the " "
echo.
set /p file=
echo.
for /F "usebackq tokens=* delims=*" %%j in (%file%) do (
set /a n+=1
if !n!==1 (
 echo !n!=%%j>config.ini
) else (
  echo !n!=%%j>>config.ini
)
)
exit
</code>```

Title: Bat To ini converter

Body:
Basically what I want to do is rename the batch file to .ini instead of .bat and put 1= for the first line and 2= before the second and so on and so on.

My batch file:

@echo off

color F0

cls

:strt

echo Drag your file in this window to make a ini from it.

set /p file=File path with " " :

del config.ini

for /F "usebackq tokens=* delims=*" %%j in (%file%) do echo 1=%%j>>config.ini

for /F "usebackq tokens=* delims=* skip=1" %%j in (%file%) do echo 2=%%j>>config.ini

for /F "usebackq tokens=* delims=* skip=2" %%j in (%file%) do echo 3=%%j>>config.ini

exit

and my result is this when I use a random text file:

1=lol1

1=lol2

1=lol3

1=lol4

2=lol1

2=lol2

2=lol3

2=lol4

3=lol1

3=lol2

3=lol3

3=lol4

and what I want is this:

1=lol1

2=lol2

3=lol3

while the original .txt is:

lol1

lol2

lol3

lol4

so it basically works but it does not stop at the end of the first line it writes it writes the whole file how do I solve this? Cause I'm out of options.

Body:
answer found sry but this works better for me maybe this will help someone tho's.
Finished product below.

@echo off
setLocal EnableDelayedExpansion
color F0
@mode con cols=52 lines=10
cls
echo Drag your file in this window to make a ini from it.
echo Remember if you type it in use "path" with the " "
echo.
set /p file=
echo.
for /F "usebackq tokens=* delims=*" %%j in (%file%) do (
set /a n+=1
if !n!==1 (
 echo !n!=%%j>config.ini
) else (
  echo !n!=%%j>>config.ini
)
)
exit


问:
Insert column if it doesn't exist
I am trying to insert a new column in my database if it isn't inserted earlier.
My column looks like this

```<code>ALTER TABLE dbo.tSafeUnit ADD HasAccess24_7 tinyint not null default 0
</code>```

I want the column to be inserted only if it is not in the table.

My line of code only inserts it but doesn't check if it exists.

答:
If you are using MS SQL server, then you can do it like below :</p>

```<code>IF COL_LENGTH('tSafeUnit', 'HasAccess24_7') IS NULL
BEGIN
    ALTER TABLE dbo.tSafeUnit
    ADD HasAccess24_7 tinyint not null default 0
END
</code>```

ContentLicense: CC BY-SA 4.0

Title: Insert column if it doesn't exist

Body:
I am trying to insert a new column in my database if it isn't inserted earlier.
My column looks like this

ALTER TABLE dbo.tSafeUnit ADD HasAccess24_7 tinyint not null default 0

I want the column to be inserted only if it is not in the table.

My line of code only inserts it but doesn't check if it exists.

Body:
If you are using MS SQL server, then you can do it like below :

IF COL_LENGTH('tSafeUnit', 'HasAccess24_7') IS NULL
BEGIN
    ALTER TABLE dbo.tSafeUnit
    ADD HasAccess24_7 tinyint not null default 0
END


问:
How to mock rest client inside a Spring boot integration test
In a spring boot integration test annotated with @SpringBootTest and ran with @RunWith(SpringRunner.class) I can drop real http post calls to my rest controller via @Autowired TestRestTemplate restTemplate and restTemplate.postForEntity(...)

This works fine, just at the end of the controller -> service -> restclient chain I have a rest client bean, which is calling a 3rd party rest endpoint using RestTemplates inside, so I have to mock this endpoint. I found this lib com.github.tomakehurst.wiremock.client.WireMock, which can be used for this, but was wondering whether there is not a nice spring boot way like for example the way to test a rest client with @RestClientTestto achieve this. I tried to mock the MockRestServiceServer so that I can write expectations and responses on it, but it does not seem to get it. The rest templates inside my rest client are always created as real, thus my call to the 3rd party endpoint fails.

答:
You can inject the mock in the @Before using ReflectionTestUtils

```<code>@Inject
private Service service;

@Mock
private RestClient restClient;

@Before
public void setup() {
    ReflectionTestUtils.setField(service, "restClient", restClient);
}
</code>```

Body:
You can inject the mock in the @Before using ReflectionTestUtils

@Inject
private Service service;

@Mock
private RestClient restClient;

@Before
public void setup() {
    ReflectionTestUtils.setField(service, "restClient", restClient);
}


问:
Problem with PHP sessions
Update Solved problem!

After examining the code, the freaking problem was I was missing the }else{} after

```<code>header ('location:referraldone.php?say=blankfields');
}
</code>```

.

I'm really lost at the moment with this session code. I don't understand why the session isn't working. Where did I go wrong? I'm trying to take the data entered in the fields to the next page when someone makes an error not filling an required field. Codes are below:

```<code><?php

if (!$_POST['cname'] | !$_POST['cphone'] | !$_POST['caddress'] | !$_POST['ccity'] | !$_POST['cstate'] | !$_POST['czip'] | !$_POST['cbirthday']) {

$rname = $_REQUEST['rname'];
$rdate = $_REQUEST['rdate'];
$ragency = $_REQUEST['ragency'];
$rphone = $_REQUEST['rphone'];
$cname = $_REQUEST['cname'];
$cphone = $_REQUEST['cphone'];
$caddress = $_REQUEST['caddress'];
$ccity = $_REQUEST['ccity'];
$cstate = $_REQUEST['cstate'];
$czip = $_REQUEST['czip'];
$cbirthday = $_REQUEST['cbirthday'];
$medmemid = $_REQUEST['medmemid'];
$medclaim = $_REQUEST['medclaim'];
$marital = $_REQUEST['marital'];
$income = $_REQUEST['income'];
$gender = $_REQUEST['gender'];
$race = $_REQUEST['race'];
$caregiver = $_REQUEST['caregiver'];
$relationship = $_REQUEST['relationship'];
$memphone = $_REQUEST['memphone'];
$physician = $_REQUEST['physician'];
$phyphone = $_REQUEST['phyphone'];

session_start();
$_SESSION['rname'] = $rname;
$_SESSION['rdate'] = $rdate;
$_SESSION['ragency'] = $ragency;
$_SESSION['rphone'] = $rphone;
$_SESSION['cname'] = $cname;
$_SESSION['cphone'] = $cphone;
$_SESSION['caddress'] = $caddress;
$_SESSION['ccity'] = $ccity;
$_SESSION['cstate'] = $cstate;
$_SESSION['czip'] = $czip;
$_SESSION['cbirthday'] = $cbirthday;
$_SESSION['medmemid'] = $medmemid;
$_SESSION['medclaim'] = $medclaim;
$_SESSION['marital'] = $marital;
$_SESSION['income'] = $income;
$_SESSION['gender'] = $gender;
$_SESSION['race'] = $race;
$_SESSION['caregiver'] = $caregiver;
$_SESSION['relationship'] = $relationship;
$_SESSION['memphone'] = $memphone;
$_SESSION['physician'] = $physician;
$_SESSION['phyphone'] = $phyphone;

header ('location:referraldone.php?say=blankfields');
}

?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <table style="text-align:left; width: 500px; left:45px; position:relative; padding:2px; border:1px solid #1A1A1A">
    <tr>
        <td colspan="2" style="vertical-align:top; text-align:center; border:1px solid #1A1A1A; background-color:#A52A2A; color:#FFFFFF;">REFERRAL FORM</td>
    </tr>
    <tr>
    <td colspan="2"><center>Choose us as your Home Care Agency!<br />We provide services 24 hours per day, 7 days a week.<br /><br />Please submit form below and your respond time<br />will be 48 hours.<br /><br /><strong>*Bold Fields Required</strong><br /><br /></td>
    </tr>
    <tr>
        <td valign="top">Reffered By:<br /><input name="rname" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Reffered Date:<br /><input name="rdate" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Reffered Agency:<br /><input name="ragency" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="rphone" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Client Name:</strong><br /><input name="cname" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Phone:</strong><br /><input name="cphone" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Address:</strong><br /><input name="caddress" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* City:</strong><br /><input name="ccity" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* State:</strong><br /><input name="cstate" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Zip Code:</strong><br /><input name="czip" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Birthday:</strong><br /><input name="cbirthday" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Medicaid Member ID:<br /><input name="medmemid" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Medicare Claim:<br /><input name="medclaim" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Marital Status:<br /><input name="marital" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Monthly Income:<br /><input name="income" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Gender:<br /><input name="gender" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Race:<br /><input name="race" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Caregiver Name:<br /><input name="caregiver" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Relationship:<br /><input name="relationship" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="memphone" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Physician:<br /><input name="physician" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="phyphone" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top" style="color:#C00000"><br />Please make sure all the <strong>BOLD</strong> fields are completed before submitting form.<br /><br /></td>
    </tr>
    <tr>
        <td align="right"><input type="reset" value="Clear Fields"> <input type="submit" name="send" value="Send" /></td>
    </tr>
    </table>
</form>
</code>```

Here's the error page that should take the session data and fill the fields with it, but it doesn't:

```<code><?php
$sb = "5";

$say = $_REQUEST['say'];

$rname = $_SESSION['rname'];
$rdate = $_SESSION['rdate'];
$ragency = $_SESSION['ragency'];
$rphone = $_SESSION['rphone'];
$cname = $_SESSION['cname'];
$cphone = $_SESSION['cphone'];
$caddress = $_SESSION['caddress'];
$ccity = $_SESSION['ccity'];
$cstate = $_SESSION['cstate'];
$czip = $_SESSION['czip'];
$cbirthday = $_SESSION['cbirthday'];
$medmemid = $_SESSION['medmemid'];
$medclaim = $_SESSION['medclaim'];
$marital = $_SESSION['marital'];
$income = $_SESSION['income'];
$gender = $_SESSION['gender'];
$race = $_SESSION['race'];
$caregiver = $_SESSION['caregiver'];
$relationship = $_SESSION['relationship'];
$memphone = $_SESSION['memphone'];
$physician = $_SESSION['physician'];
$phyphone = $_SESSION['phyphone'];

if(isset($say)){
    switch ($say){
        case "formsent":
        $return = "Referral Form Sent. Your respond time will be 48 hours.";
        break;
        case "blankfields":
        $return = "All <strong>Bold</strong> Fields Required";
        break;
        default:
        break;
    }
}

if (isset($_POST['send'])) {

    if (!$_POST['cname'] | !$_POST['cphone'] | !$_POST['caddress'] | !$_POST['ccity'] | !$_POST['cstate'] | !$_POST['czip'] | !$_POST['cbirthday']) {

$rname = $_REQUEST['rname'];
$rdate = $_REQUEST['rdate'];
$ragency = $_REQUEST['ragency'];
$rphone = $_REQUEST['rphone'];
$cname = $_REQUEST['cname'];
$cphone = $_REQUEST['cphone'];
$caddress = $_REQUEST['caddress'];
$ccity = $_REQUEST['ccity'];
$cstate = $_REQUEST['cstate'];
$czip = $_REQUEST['czip'];
$cbirthday = $_REQUEST['cbirthday'];
$medmemid = $_REQUEST['medmemid'];
$medclaim = $_REQUEST['medclaim'];
$marital = $_REQUEST['marital'];
$income = $_REQUEST['income'];
$gender = $_REQUEST['gender'];
$race = $_REQUEST['race'];
$caregiver = $_REQUEST['caregiver'];
$relationship = $_REQUEST['relationship'];
$memphone = $_REQUEST['memphone'];
$physician = $_REQUEST['physician'];
$phyphone = $_REQUEST['phyphone'];

session_start();
$_SESSION['rname'] = $rname;
$_SESSION['rdate'] = $rdate;
$_SESSION['ragency'] = $ragency;
$_SESSION['rphone'] = $rphone;
$_SESSION['cname'] = $cname;
$_SESSION['cphone'] = $cphone;
$_SESSION['caddress'] = $caddress;
$_SESSION['ccity'] = $ccity;
$_SESSION['cstate'] = $cstate;
$_SESSION['czip'] = $czip;
$_SESSION['cbirthday'] = $cbirthday;
$_SESSION['medmemid'] = $medmemid;
$_SESSION['medclaim'] = $medclaim;
$_SESSION['marital'] = $marital;
$_SESSION['income'] = $income;
$_SESSION['gender'] = $gender;
$_SESSION['race'] = $race;
$_SESSION['caregiver'] = $caregiver;
$_SESSION['relationship'] = $relationship;
$_SESSION['memphone'] = $memphone;
$_SESSION['physician'] = $physician;
$_SESSION['phyphone'] = $phyphone;

header ('location:referraldone.php?say=blankfields');
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <table style="text-align:left; width: 500px; left:45px; position:relative; padding:2px; border:1px solid #1A1A1A">
    <tr>
        <td colspan="2" style="vertical-align:top; text-align:center; border:1px solid #1A1A1A; background-color:#A52A2A; color:#FFFFFF;">REFERRAL FORM</td>
    </tr>
    <tr>
    <td colspan="2"><center>Choose us as your Home Care Agency!<br />We provide services 24 hours per day, 7 days a week.<br /><br />Please submit form below and your respond time<br />will be 48 hours.<br /><br /><strong>*Bold Fields Required</strong><br /><br /></td>
    </tr>
    <tr>
        <td valign="top">Reffered By:<br /><input name="rname" type="text" value="<?php echo $rname; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Reffered Date:<br /><input name="rdate" type="text" value="<?php echo $rdate; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Reffered Agency:<br /><input name="ragency" type="text" value="<?php echo $ragency; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="rphone" type="text" style=value="rphone" "width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Client Name:</strong><br /><input name="cname" type="text" value="<?php echo $cname; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Phone:</strong><br /><input name="cphone" type="text" value="<?php echo $cphone; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Address:</strong><br /><input name="caddress" type="text" value="<?php echo $caddress; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* City:</strong><br /><input name="ccity" type="text" value="<?php echo $ccity; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* State:</strong><br /><input name="cstate" type="text" value="<?php echo $cstate; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Zip Code:</strong><br /><input name="czip" type="text" value="<?php echo $czip; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br /><strong>* Birthday:</strong><br /><input name="cbirthday" type="text" value="<?php echo $cbirthday; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Medicaid Member ID:<br /><input name="medmemid" type="text" value="<?php echo $medmemid; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Medicare Claim:<br /><input name="medclaim" type="text" value="<?php echo $medclaim; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Marital Status:<br /><input name="marital" type="text" value="<?php echo $marital; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Monthly Income:<br /><input name="income" type="text" value="<?php echo $income; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Gender:<br /><input name="gender" type="text" value="<?php echo $gender; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Race:<br /><input name="race" type="text" value="<?php echo $race; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Caregiver Name:<br /><input name="caregiver" type="text" value="<?php echo $caregiver; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Relationship:<br /><input name="relationship" type="text" value="<?php echo $relationship; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="memphone" type="text" value="<?php echo $phone; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Physician:<br /><input name="physician" type="text" value="<?php echo $physician; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top"><br />Phone:<br /><input name="phyphone" type="text" value="<?php echo $phyphone; ?>" style="width:98%" /></td>
    </tr>
    <tr>
        <td valign="top" style="color:#C00000"><br />Please make sure all the <strong>BOLD</strong> fields are completed before submitting form.<br /><br /></td>
    </tr>
    <tr>
        <td align="right"><input type="reset" value="Clear Fields"> <input type="submit" name="send" value="Send" /></td>
    </tr>
    </table>
</form>
</code>```

答:
additional to the things that has already been talked about: You'll need to put the session-ID into the URL you redirect to, to have it present if cookies cannot be used.

```<code>header ('location:referraldone.php?say=blankfields&'.SID);
</code>```

This will not be done automatic, even not when you use session.use_trans_sid

Title: Problem with PHP sessions

Body:
Update Solved problem!

After examining the code, the freaking problem was I was missing the }else{} after

header ('location:referraldone.php?say=blankfields');
}

.

I'm really lost at the moment with this session code. I don't understand why the session isn't working. Where did I go wrong? I'm trying to take the data entered in the fields to the next page when someone makes an error not filling an required field. Codes are below:

<?php

if (!$_POST['cname'] | !$_POST['cphone'] | !$_POST['caddress'] | !$_POST['ccity'] | !$_POST['cstate'] | !$_POST['czip'] | !$_POST['cbirthday']) {

$rname = $_REQUEST['rname'];
$rdate = $_REQUEST['rdate'];
$ragency = $_REQUEST['ragency'];
$rphone = $_REQUEST['rphone'];
$cname = $_REQUEST['cname'];
$cphone = $_REQUEST['cphone'];
$caddress = $_REQUEST['caddress'];
$ccity = $_REQUEST['ccity'];
$cstate = $_REQUEST['cstate'];
$czip = $_REQUEST['czip'];
$cbirthday = $_REQUEST['cbirthday'];
$medmemid = $_REQUEST['medmemid'];
$medclaim = $_REQUEST['medclaim'];
$marital = $_REQUEST['marital'];
$income = $_REQUEST['income'];
$gender = $_REQUEST['gender'];
$race = $_REQUEST['race'];
$caregiver = $_REQUEST['caregiver'];
$relationship = $_REQUEST['relationship'];
$memphone = $_REQUEST['memphone'];
$physician = $_REQUEST['physician'];
$phyphone = $_REQUEST['phyphone'];

session_start();
$_SESSION['rname'] = $rname;
$_SESSION['rdate'] = $rdate;
$_SESSION['ragency'] = $ragency;
$_SESSION['rphone'] = $rphone;
$_SESSION['cname'] = $cname;
$_SESSION['cphone'] = $cphone;
$_SESSION['caddress'] = $caddress;
$_SESSION['ccity'] = $ccity;
$_SESSION['cstate'] = $cstate;
$_SESSION['czip'] = $czip;
$_SESSION['cbirthday'] = $cbirthday;
$_SESSION['medmemid'] = $medmemid;
$_SESSION['medclaim'] = $medclaim;
$_SESSION['marital'] = $marital;
$_SESSION['income'] = $income;
$_SESSION['gender'] = $gender;
$_SESSION['race'] = $race;
$_SESSION['caregiver'] = $caregiver;
$_SESSION['relationship'] = $relationship;
$_SESSION['memphone'] = $memphone;
$_SESSION['physician'] = $physician;
$_SESSION['phyphone'] = $phyphone;

header ('location:referraldone.php?say=blankfields');
}

?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

        REFERRAL FORM

    Choose us as your Home Care Agency!
We provide services 24 hours per day, 7 days a week.

Please submit form below and your respond time
will be 48 hours.

*Bold Fields Required

        Reffered By:
<input name="rname" type="text" style="width:98%" />

Reffered Date:
<input name="rdate" type="text" style="width:98%" />

Reffered Agency:
<input name="ragency" type="text" style="width:98%" />

Phone:
<input name="rphone" type="text" style="width:98%" />

* Client Name:
<input name="cname" type="text" style="width:98%" />

* Phone:
<input name="cphone" type="text" style="width:98%" />

* Address:
<input name="caddress" type="text" style="width:98%" />

* City:
<input name="ccity" type="text" style="width:98%" />

* State:
<input name="cstate" type="text" style="width:98%" />

* Zip Code:
<input name="czip" type="text" style="width:98%" />

* Birthday:
<input name="cbirthday" type="text" style="width:98%" />

Medicaid Member ID:
<input name="medmemid" type="text" style="width:98%" />

Medicare Claim:
<input name="medclaim" type="text" style="width:98%" />

Marital Status:
<input name="marital" type="text" style="width:98%" />

Monthly Income:
<input name="income" type="text" style="width:98%" />

Gender:
<input name="gender" type="text" style="width:98%" />

Race:
<input name="race" type="text" style="width:98%" />

Caregiver Name:
<input name="caregiver" type="text" style="width:98%" />

Relationship:
<input name="relationship" type="text" style="width:98%" />

Phone:
<input name="memphone" type="text" style="width:98%" />

Physician:
<input name="physician" type="text" style="width:98%" />

Phone:
<input name="phyphone" type="text" style="width:98%" />

Please make sure all the BOLD fields are completed before submitting form.

        <input type="reset" value="Clear Fields"> <input type="submit" name="send" value="Send" />

</form>

Here's the error page that should take the session data and fill the fields with it, but it doesn't:

<?php
$sb = "5";

$say = $_REQUEST['say'];

$rname = $_SESSION['rname'];
$rdate = $_SESSION['rdate'];
$ragency = $_SESSION['ragency'];
$rphone = $_SESSION['rphone'];
$cname = $_SESSION['cname'];
$cphone = $_SESSION['cphone'];
$caddress = $_SESSION['caddress'];
$ccity = $_SESSION['ccity'];
$cstate = $_SESSION['cstate'];
$czip = $_SESSION['czip'];
$cbirthday = $_SESSION['cbirthday'];
$medmemid = $_SESSION['medmemid'];
$medclaim = $_SESSION['medclaim'];
$marital = $_SESSION['marital'];
$income = $_SESSION['income'];
$gender = $_SESSION['gender'];
$race = $_SESSION['race'];
$caregiver = $_SESSION['caregiver'];
$relationship = $_SESSION['relationship'];
$memphone = $_SESSION['memphone'];
$physician = $_SESSION['physician'];
$phyphone = $_SESSION['phyphone'];

if(isset($say)){
    switch ($say){
        case "formsent":
        $return = "Referral Form Sent. Your respond time will be 48 hours.";
        break;
        case "blankfields":
        $return = "All Bold Fields Required";
        break;
        default:
        break;
    }
}

if (isset($_POST['send'])) {

    if (!$_POST['cname'] | !$_POST['cphone'] | !$_POST['caddress'] | !$_POST['ccity'] | !$_POST['cstate'] | !$_POST['czip'] | !$_POST['cbirthday']) {

$rname = $_REQUEST['rname'];
$rdate = $_REQUEST['rdate'];
$ragency = $_REQUEST['ragency'];
$rphone = $_REQUEST['rphone'];
$cname = $_REQUEST['cname'];
$cphone = $_REQUEST['cphone'];
$caddress = $_REQUEST['caddress'];
$ccity = $_REQUEST['ccity'];
$cstate = $_REQUEST['cstate'];
$czip = $_REQUEST['czip'];
$cbirthday = $_REQUEST['cbirthday'];
$medmemid = $_REQUEST['medmemid'];
$medclaim = $_REQUEST['medclaim'];
$marital = $_REQUEST['marital'];
$income = $_REQUEST['income'];
$gender = $_REQUEST['gender'];
$race = $_REQUEST['race'];
$caregiver = $_REQUEST['caregiver'];
$relationship = $_REQUEST['relationship'];
$memphone = $_REQUEST['memphone'];
$physician = $_REQUEST['physician'];
$phyphone = $_REQUEST['phyphone'];

session_start();
$_SESSION['rname'] = $rname;
$_SESSION['rdate'] = $rdate;
$_SESSION['ragency'] = $ragency;
$_SESSION['rphone'] = $rphone;
$_SESSION['cname'] = $cname;
$_SESSION['cphone'] = $cphone;
$_SESSION['caddress'] = $caddress;
$_SESSION['ccity'] = $ccity;
$_SESSION['cstate'] = $cstate;
$_SESSION['czip'] = $czip;
$_SESSION['cbirthday'] = $cbirthday;
$_SESSION['medmemid'] = $medmemid;
$_SESSION['medclaim'] = $medclaim;
$_SESSION['marital'] = $marital;
$_SESSION['income'] = $income;
$_SESSION['gender'] = $gender;
$_SESSION['race'] = $race;
$_SESSION['caregiver'] = $caregiver;
$_SESSION['relationship'] = $relationship;
$_SESSION['memphone'] = $memphone;
$_SESSION['physician'] = $physician;
$_SESSION['phyphone'] = $phyphone;

header ('location:referraldone.php?say=blankfields');
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

        REFERRAL FORM

    Choose us as your Home Care Agency!
We provide services 24 hours per day, 7 days a week.

Please submit form below and your respond time
will be 48 hours.

*Bold Fields Required

        Reffered By:
<input name="rname" type="text" value="<?php echo $rname; ?>" style="width:98%" />

Reffered Date:
<input name="rdate" type="text" value="<?php echo $rdate; ?>" style="width:98%" />

Reffered Agency:
<input name="ragency" type="text" value="<?php echo $ragency; ?>" style="width:98%" />

Phone:
<input name="rphone" type="text" style=value="rphone" "width:98%" />

* Client Name:
<input name="cname" type="text" value="<?php echo $cname; ?>" style="width:98%" />

* Phone:
<input name="cphone" type="text" value="<?php echo $cphone; ?>" style="width:98%" />

* Address:
<input name="caddress" type="text" value="<?php echo $caddress; ?>" style="width:98%" />

* City:
<input name="ccity" type="text" value="<?php echo $ccity; ?>" style="width:98%" />

* State:
<input name="cstate" type="text" value="<?php echo $cstate; ?>" style="width:98%" />

* Zip Code:
<input name="czip" type="text" value="<?php echo $czip; ?>" style="width:98%" />

* Birthday:
<input name="cbirthday" type="text" value="<?php echo $cbirthday; ?>" style="width:98%" />

Medicaid Member ID:
<input name="medmemid" type="text" value="<?php echo $medmemid; ?>" style="width:98%" />

Medicare Claim:
<input name="medclaim" type="text" value="<?php echo $medclaim; ?>" style="width:98%" />

Marital Status:
<input name="marital" type="text" value="<?php echo $marital; ?>" style="width:98%" />

Monthly Income:
<input name="income" type="text" value="<?php echo $income; ?>" style="width:98%" />

Gender:
<input name="gender" type="text" value="<?php echo $gender; ?>" style="width:98%" />

Race:
<input name="race" type="text" value="<?php echo $race; ?>" style="width:98%" />

Caregiver Name:
<input name="caregiver" type="text" value="<?php echo $caregiver; ?>" style="width:98%" />

Relationship:
<input name="relationship" type="text" value="<?php echo $relationship; ?>" style="width:98%" />

Phone:
<input name="memphone" type="text" value="<?php echo $phone; ?>" style="width:98%" />

Physician:
<input name="physician" type="text" value="<?php echo $physician; ?>" style="width:98%" />

Phone:
<input name="phyphone" type="text" value="<?php echo $phyphone; ?>" style="width:98%" />

Please make sure all the BOLD fields are completed before submitting form.

        <input type="reset" value="Clear Fields"> <input type="submit" name="send" value="Send" />

</form>

Body:
additional to the things that has already been talked about: You'll need to put the session-ID into the URL you redirect to, to have it present if cookies cannot be used.

header ('location:referraldone.php?say=blankfields&'.SID);

This will not be done automatic, even not when you use session.use_trans_sid


问:
Adding / Query / Parse SQLite using Anko
tl;dr: I'm having issues trying to get my code to work, now I can create the database using Anko and insert the columns but when I try to insert the data and when I open the database on sqliteman my columns are empty I also don't know how to retrieve the data in strings/Int to send to a View

This apparently works fine I can see my database created with all the columns with the right name

```<code>class MySqlHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "db_main") {

companion object {
    private var instance: MySqlHelper? = null

    @Synchronized
    fun getInstance(ctx: Context): MySqlHelper {
        if (instance == null) {
            instance = MySqlHelper(ctx.applicationContext)
        }
        return instance!!
    }
}

override fun onCreate(db: SQLiteDatabase) {
    db.createTable("db_main", true,
            "_id" to INTEGER + PRIMARY_KEY + AUTOINCREMENT + NOT_NULL,
            "name" to TEXT,
            "day" to INTEGER)

}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
       }

// Access property for Context
val Context.database: MySqlHelper
    get() = getInstance(applicationContext)

}
</code>```

This should work but it doesn't Although I have all the columns in the database and I don't get any error messages they're not being added

The code below is called in MainActivity

```<code>val db = MySqlHelper(this)

fun addtosqllite(title: String, datepicker: DatePicker) {

db.use {
        insert("db_main",
                "_id" to 1,
                "name" to title,
                "day" to  datepicker.dayOfMonth)
     }
}
</code>```

I have no idea how to do this
I need to retrieve the data from the database. I've been Reading the documentation but I don't know how to implement this

Let's say that I have three columns _id, name and day
I was doing something like

```<code>db.select("main_db","_id","name","day").exec {
parseSingle //something goes here to send the data to String/Int
}
</code>```

答:
I hope it's not too late. You can try this :</p>

```<code>database.use {
  select("main_db", "_id", "name","day").exec {
   parseList( object : MapRowParser<Map<String, Any?>> {
    override fun parseRow(columns: Map<String, Any?>): Map<String, Any?> {
      Log.e("Your result", columns.toString())
        return columns
      }
    }
   )
 }
</code>```

Body:
tl;dr: I'm having issues trying to get my code to work, now I can create the database using Anko and insert the columns but when I try to insert the data and when I open the database on sqliteman my columns are empty I also don't know how to retrieve the data in strings/Int to send to a View

This apparently works fine I can see my database created with all the columns with the right name

class MySqlHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "db_main") {

companion object {
    private var instance: MySqlHelper? = null

    @Synchronized
    fun getInstance(ctx: Context): MySqlHelper {
        if (instance == null) {
            instance = MySqlHelper(ctx.applicationContext)
        }
        return instance!!
    }
}

override fun onCreate(db: SQLiteDatabase) {
    db.createTable("db_main", true,
            "_id" to INTEGER + PRIMARY_KEY + AUTOINCREMENT + NOT_NULL,
            "name" to TEXT,
            "day" to INTEGER)

}

override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
       }

// Access property for Context
val Context.database: MySqlHelper
    get() = getInstance(applicationContext)

}

This should work but it doesn't Although I have all the columns in the database and I don't get any error messages they're not being added

The code below is called in MainActivity

val db = MySqlHelper(this)

fun addtosqllite(title: String, datepicker: DatePicker) {

db.use {
        insert("db_main",
                "_id" to 1,
                "name" to title,
                "day" to  datepicker.dayOfMonth)
     }
}

I have no idea how to do this
I need to retrieve the data from the database. I've been Reading the documentation but I don't know how to implement this

Let's say that I have three columns _id, name and day
I was doing something like

db.select("main_db","_id","name","day").exec {
parseSingle //something goes here to send the data to String/Int
}

Body:
I hope it's not too late. You can try this :

database.use {
  select("main_db", "_id", "name","day").exec {
   parseList( object : MapRowParser<Map<String, Any?>> {
    override fun parseRow(columns: Map<String, Any?>): Map<String, Any?> {
      Log.e("Your result", columns.toString())
        return columns
      }
    }
   )
 }


问:
no remote repository specified from new rails apps
I am trying to add new rails apps to an existing example repository. I've done this before. I'm using a current Debian on Google Cloud Platform Compute Engine Instance, using Rails 5.1.4 and git 2.11.0.

In short, I can add a new rails app, but if I try to add/commit/push from inside that application's directories, I get errors. If I add/commit/push from above the top level directory for the application, everything works.

Recreating this is simple. I use:

```<code>rails new foo
</code>```

to create a new rails app. I then add the app, commit, and push:

```<code>git add .
git commit -m "testing"
git push
</code>```

Which results in the following output (abbreviated):

[master 95cb836] testing

76 files changed, 1197 insertions(+)

create mode 100644 railapps/foo/.gitignore

create mode 100644 railapps/foo/Gemfile

...

At this point I have no problems. However, when I go into that app and try to do a pull or push, I get the following errors:

```<code>git pull
</code>```

fatal: No remote repository specified.  Please, specify either a URL or a

remote name from which new revisions should be fetched.

```<code>git push
</code>```

Either specify the URL from the command-line or configure a remote repository
  using

git remote add

and then push using the remote name

```<code>git push <name>
</code>```

OK, simple enough, just specify the remote, right?

```<code>git remote add origin git@github.com:pathto/myrepo.git

git push --set-upstream origin master
</code>```

Which results in:

error: src refspec master does not match any.

error: failed to push some refs to 'git@github.com:pathto/myrepo.git'

答:
You should not use the --set-upstream option in this case.
Just use :

```<code>git push origin master
</code>```

Body:
I am trying to add new rails apps to an existing example repository. I've done this before. I'm using a current Debian on Google Cloud Platform Compute Engine Instance, using Rails 5.1.4 and git 2.11.0.

In short, I can add a new rails app, but if I try to add/commit/push from inside that application's directories, I get errors. If I add/commit/push from above the top level directory for the application, everything works.

Recreating this is simple. I use:

rails new foo

to create a new rails app. I then add the app, commit, and push:

git add .
git commit -m "testing"
git push

Which results in the following output (abbreviated):

[master 95cb836] testing

76 files changed, 1197 insertions(+)

create mode 100644 railapps/foo/.gitignore

create mode 100644 railapps/foo/Gemfile

...

At this point I have no problems. However, when I go into that app and try to do a pull or push, I get the following errors:

git pull

fatal: No remote repository specified.  Please, specify either a URL or a

remote name from which new revisions should be fetched.

git push

Either specify the URL from the command-line or configure a remote repository
  using

git remote add

and then push using the remote name

git push <name>

OK, simple enough, just specify the remote, right?

git remote add origin git@github.com:pathto/myrepo.git

git push --set-upstream origin master

Which results in:

error: src refspec master does not match any.

error: failed to push some refs to 'git@github.com:pathto/myrepo.git'

Body:
You should not use the --set-upstream option in this case.
Just use :

git push origin master


问:
How to get all full CREATE TABLE statements from a mysql dump
I got this so far:

```<code>$ bzcat mysqldump.pplware.sql.bz2 | grep -A 10 "^CREATE TABLE.*"
CREATE TABLE `wp_ak_twitter` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tw_id` varchar(255) NOT NULL,
  `tw_text` varchar(255) NOT NULL,
  `tw_reply_username` varchar(255) DEFAULT NULL,
  `tw_reply_tweet` varchar(255) DEFAULT NULL,
  `tw_created_at` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `tw_id` (`tw_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
--
CREATE TABLE `wp_audit_trail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `operation` varchar(40) NOT NULL DEFAULT '',
  `user_id` int(11) NOT NULL,
  `ip` int(11) unsigned NOT NULL DEFAULT '0',
  `happened_at` datetime NOT NULL,
  `item_id` int(11) DEFAULT NULL,
  `data` longtext,
  `title` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9442523 DEFAULT CHARSET=latin1;
</code>```

..and so on.
But the 10 line limit is arbitrary, and some of the CREATE TABLES are shorter and some are longer. How can I get all full CREATE TABLE definitions?

答:
How about printing lines between patterns: CREATE TABLE and ; semi-colon:-

```<code>bzcat mysqldump.pplware.sql.bz2 | awk '/CREATE TABLE/{f=1}/\;/{f=0}f||/\;/'
</code>```

OR

```<code>bzcat mysqldump.pplware.sql.bz2 | awk '/CREATE TABLE/,/\;/'
</code>```

Body:
I got this so far:

$ bzcat mysqldump.pplware.sql.bz2 | grep -A 10 "^CREATE TABLE.*"
CREATE TABLE `wp_ak_twitter` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tw_id` varchar(255) NOT NULL,
  `tw_text` varchar(255) NOT NULL,
  `tw_reply_username` varchar(255) DEFAULT NULL,
  `tw_reply_tweet` varchar(255) DEFAULT NULL,
  `tw_created_at` datetime NOT NULL,
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `tw_id` (`tw_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
--
CREATE TABLE `wp_audit_trail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `operation` varchar(40) NOT NULL DEFAULT '',
  `user_id` int(11) NOT NULL,
  `ip` int(11) unsigned NOT NULL DEFAULT '0',
  `happened_at` datetime NOT NULL,
  `item_id` int(11) DEFAULT NULL,
  `data` longtext,
  `title` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9442523 DEFAULT CHARSET=latin1;

..and so on.
But the 10 line limit is arbitrary, and some of the CREATE TABLES are shorter and some are longer. How can I get all full CREATE TABLE definitions?

Body:
How about printing lines between patterns: CREATE TABLE and ; semi-colon:-

bzcat mysqldump.pplware.sql.bz2 | awk '/CREATE TABLE/{f=1}/\;/{f=0}f||/\;/'

OR

bzcat mysqldump.pplware.sql.bz2 | awk '/CREATE TABLE/,/\;/'


问:
Using Java to parse record with new lines
I would like to write a method to parse the following records from a file. It is possible for me read each line, start the record at "{" and end it at "}" and process each line in between. However, I was wondering if there was a more elegant way of processing records.

{\n
    "name": "Jeff Hamilton",\n
    "address": "101 Main St.",\n
    "id":"701"\n
},\n
{\n
    "name": "Peet Rizzo",\n
    "address": "109 Main St.",\n
    "id": "1003"\n
}\n

答:
You can split this string into an array.

```<code>String newArray[]= str.split("\n },\n {\n");
</code>```

You can also use a regex here.

Alternatively, a better approach would be to use JSON parsers.
I usually use GSON for serialization/deserialization but you can use any.

Body:
You can split this string into an array.

String newArray[]= str.split("\n },\n {\n");

You can also use a regex here.

Alternatively, a better approach would be to use JSON parsers.
I usually use GSON for serialization/deserialization but you can use any.