问:
Difference between ArrayList<String>() and mutableListOf<String>() in Kotlin
```<code>private val repositories = mutableListOf<String>()

private val repositories = ArrayList<String>()
</code>```

Both are mutable list, then what is the point of two keywords mutableListOf or ArrayList?

or is there any major difference?

答:
mutableListOf<T>() is an inline function invocation that returns a
 MutableList<T>. As of today, mutableListOf does return an instance of ArrayList.

ArrayList<String>() is a constructor invocation and cannot be inlined.

In other words, given:

```<code> val a = mutableListOf<String>()
 val b = ArrayList<String>()
</code>```

a is of type MutableList<String>

b is of type ArrayList<String>

At runtime, both a and b will hold an instance of ArrayList.

Note that inlining is particularly useful when combined with type reification, which justifies the existence of listOf, mutableListOf and the like.

Body:
private val repositories = mutableListOf<String>()

private val repositories = ArrayList<String>()

Both are mutable list, then what is the point of two keywords mutableListOf or ArrayList?

or is there any major difference?

Body:
mutableListOf<T>() is an inline function invocation that returns a
 MutableList<T>. As of today, mutableListOf does return an instance of ArrayList.

ArrayList<String>() is a constructor invocation and cannot be inlined.

In other words, given:

 val a = mutableListOf<String>()
 val b = ArrayList<String>()

a is of type MutableList<String>

b is of type ArrayList<String>

At runtime, both a and b will hold an instance of ArrayList.

Note that inlining is particularly useful when combined with type reification, which justifies the existence of listOf, mutableListOf and the like.


来源: stackexchange

问:
How can I access Docker set Environment Variables From a Cron Job
I've recently tried running a cron job from within a linked docker container and run into an issue. My main docker container is linked to a postgres container and its port number is set as an environment variable by docker upon the containers creation. This environment variable is not set in ~/.profile or any other source file that I could load when running my cron job. How can I then access these environment variables from my cron job?

Thanks!

答:
To escape any weird characters that could break your script, and according to reasoning from Mark's answer, add this line to your entrypoint.sh:

```<code>env | sed -r "s/'/\\\'/gm" | sed -r "s/^([^=]+=)(.*)\$/\1'\2'/gm" \ > /etc/environment
</code>```

This way, if you have any variable like affinity:container==My container's friend, it will be converted to affinity:container='=My container\'s friend, and so on.

ContentLicense: CC BY-SA 3.0

Body:
To escape any weird characters that could break your script, and according to reasoning from Mark's answer, add this line to your entrypoint.sh:

env | sed -r "s/'/\\\'/gm" | sed -r "s/^([^=]+=)(.*)\$/\1'\2'/gm" \ > /etc/environment

This way, if you have any variable like affinity:container==My container's friend, it will be converted to affinity:container='=My container\'s friend, and so on.


问:
send PHP code in database
I am trying to post php code from my messages table. But it is not posting. For example:

```<code><textarea name="update">User can write php codes here for sending</textarea>
<div class="send">Send</div>
</code>```

When i click send button the text code <?php echo $message;?> must be in my messages table row post_text . But post_text is empty, you can see it in the screenshot.

What is the problem here. What i shoud do to fix this problem? Anyone can help me here ?

```<code><?php
include_once '../inc/inc.php';
if(isset($_POST['update'])) {

   $update=mysqli_real_escape_string($db,$_POST['update']);
   if($update){
      $data=$DoDo->InsertText($uid,$update);
      echo $update;
   }
}
?>
</code>```

InsertText function

```<code>public function InsertText($uid, $update) {

    $time=time();
    $ip=$_SERVER['REMOTE_ADDR'];
    mysqli_query($this->db,"SET character_set_client=utf8") or die(mysqli_error($this->db));
    mysqli_query($this->db,"SET character_set_connection=utf8") or die(mysqli_error($this->db));

    $query = mysqli_query($this->db,"SELECT post_id,post_text FROM `posts` WHERE uid_fk='$uid' order by post_id desc limit 1") or die(mysqli_error($this->db));
    $result = mysqli_fetch_array($query, MYSQLI_ASSOC);

     $query = mysqli_query($this->db,"INSERT INTO `posts` (post_text, uid_fk,time) VALUES (N'$update', '$uid','$time')") or die(mysqli_error($this->db));

     //The newquery to select for message
     $newquery = mysqli_query($this->db,"SELECT M.post_id, M.uid_fk, M.post_text, M.time,U.username FROM posts M, users U where M.uid_fk=U.uid and M.uid_fk='$uid' order by M.post_id desc limit 1 ") or die(mysqli_error($this->db));
     $result = mysqli_fetch_array($newquery, MYSQLI_ASSOC);
     return $result;
}
</code>```

Note: This problem will be come when i send just php code. If i send
  normal text then normal text sending from post_text.

I want to send php code like this screenshot.

答:
In your update query, you did not check the right variable;

```<code>$update=mysqli_real_escape_string($db,$_POST['update']);
   if($update){
      $data=$DoDo->InsertText($uid,$update);
      echo $update;
   }
</code>```

also in your insert query you have a funny character, remove the N

```<code>VALUES ('$update', '$uid','$time')"

$query = mysqli_query($this->db,"INSERT INTO `posts` (post_text, uid_fk,`time`) VALUES ('$update', '$uid','$time')") or die(mysqli_error($this->db));
</code>```

Do this below

```<code>    <textarea name="update"><?php echo '<?php echo $message;?>';?></textarea>
</code>```

Title: send PHP code in database

Body:
I am trying to post php code from my messages table. But it is not posting. For example:

<textarea name="update">User can write php codes here for sending</textarea>

Send

When i click send button the text code <?php echo $message;?> must be in my messages table row post_text . But post_text is empty, you can see it in the screenshot.

What is the problem here. What i shoud do to fix this problem? Anyone can help me here ?

<?php
include_once '../inc/inc.php';
if(isset($_POST['update'])) {

   $update=mysqli_real_escape_string($db,$_POST['update']);
   if($update){
      $data=$DoDo->InsertText($uid,$update);
      echo $update;
   }
}
?>

InsertText function

public function InsertText($uid, $update) {

    $time=time();
    $ip=$_SERVER['REMOTE_ADDR'];
    mysqli_query($this->db,"SET character_set_client=utf8") or die(mysqli_error($this->db));
    mysqli_query($this->db,"SET character_set_connection=utf8") or die(mysqli_error($this->db));

    $query = mysqli_query($this->db,"SELECT post_id,post_text FROM `posts` WHERE uid_fk='$uid' order by post_id desc limit 1") or die(mysqli_error($this->db));
    $result = mysqli_fetch_array($query, MYSQLI_ASSOC);

     $query = mysqli_query($this->db,"INSERT INTO `posts` (post_text, uid_fk,time) VALUES (N'$update', '$uid','$time')") or die(mysqli_error($this->db));

     //The newquery to select for message
     $newquery = mysqli_query($this->db,"SELECT M.post_id, M.uid_fk, M.post_text, M.time,U.username FROM posts M, users U where M.uid_fk=U.uid and M.uid_fk='$uid' order by M.post_id desc limit 1 ") or die(mysqli_error($this->db));
     $result = mysqli_fetch_array($newquery, MYSQLI_ASSOC);
     return $result;
}

Note: This problem will be come when i send just php code. If i send
  normal text then normal text sending from post_text.

I want to send php code like this screenshot.

Body:
In your update query, you did not check the right variable;

$update=mysqli_real_escape_string($db,$_POST['update']);
   if($update){
      $data=$DoDo->InsertText($uid,$update);
      echo $update;
   }

also in your insert query you have a funny character, remove the N

VALUES ('$update', '$uid','$time')"

$query = mysqli_query($this->db,"INSERT INTO `posts` (post_text, uid_fk,`time`) VALUES ('$update', '$uid','$time')") or die(mysqli_error($this->db));

Do this below

    <textarea name="update"><?php echo '<?php echo $message;?>';?></textarea>


问:
How to store text as paragraphs in SQLite database in a iPhone app?
In my iPhone app, I have a requirement to store a huge amount of text. I have paragraphs of text to be stored in my database along with the newline characters.

What should I do to store the text as paragraphs in SQLite database?

For example, I want to store paragraphs like the ones below in:

(the mother of the faithful believers) The commencement of the Divine Inspiration to Allah's Apostle was in the form of good dreams which came true like bright day light, and then the love of seclusion was bestowed upon him. He used to go in seclusion in the cave of Hira where he used to worship (Allah alone) continuously for many days before his desire to see his family. He used to take with him the journey food for the stay and then come back to (his wife) Khadija to take his food like-wise again till suddenly the Truth descended upon him while he was in the cave of Hira. The angel came to him and asked him to read. The Prophet replied, "I do not know how to read.

The Prophet added, "The angel caught me (forcefully) and pressed me so hard that I could not bear it any more. He then released me and again asked me to read and I replied, 'I do not know how to read.'

Basically I want to save the paragraphs in database in the same format with carriage returns.

答:
On the face of it, SQLite doesn't treat newlines any differently than other characters;  you can just store the test as-is.

The issue, though, is why are you storing large volumes of raw text in SQLite?  If you want to search it or organize it somehow, SQLite (nor Core Data) is probably not the best choice without first massaging the text into some other form.  Or, alternatively, you'd want to store the raw text on disk then keep some kind of searchable index in the database.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Getting greek character in plot axis
I am making barplots for different metal concentration in various materials, and need the axis to say μg/g. I've searched for how to implement greek characters into different plots, but I don't seem able to actually do so. It looks like I should be able to use (expression(paste)) - can anyone help me?

This is an extract of my current script:

```<code>BP.Ag <- ggplot(data=dat, aes(x=Material, y=Ag, fill=Sample.Material)) +
  geom_bar(stat="identity", position="dodge") + theme_bw() +
  scale_fill_brewer(palette = "Set1") + ylab("Silver (μg/g)") + guides(fill=FALSE) + theme(axis.text.x = element_text(angle = 45, hjust = 1))
</code>```

Thanks!

答:
A similar question was asked here: Adding greek character to axis title

Your ylab should be something like +ylab(expression(paste("Silver ", mu,"g/g")))

Title: Getting greek character in plot axis

Body:
I am making barplots for different metal concentration in various materials, and need the axis to say μg/g. I've searched for how to implement greek characters into different plots, but I don't seem able to actually do so. It looks like I should be able to use (expression(paste)) - can anyone help me?

This is an extract of my current script:

BP.Ag <- ggplot(data=dat, aes(x=Material, y=Ag, fill=Sample.Material)) +
  geom_bar(stat="identity", position="dodge") + theme_bw() +
  scale_fill_brewer(palette = "Set1") + ylab("Silver (μg/g)") + guides(fill=FALSE) + theme(axis.text.x = element_text(angle = 45, hjust = 1))

Thanks!


问:
Scale transition in four divs
This question is related to one that i have already created transition-in-div . I didnot get answer for my next issue there so i decided to create new question.
I have four boxes and i want the transition effect in all four boxes.

What i want is whenever i click on any box, the width of that box must increase from its side to the left and right to fit the full width. Right now it only fills some portion of width.
My Code is

```<code><html>
<head>
    <title>Transition</title>
    <style type="text/css">
    .container {
  display: flex;
  justify-content: space-between;
}

.box {
  width:20%;
  height: 200px;
  transition: transform .5s;
  transform-origin: 0 0;
}
#first {
  background-color: red;
}
#second {
  background-color: green;
  transform-origin: 25% 75%;
}
#third {
  background-color: aqua;
  transform-origin: center center;
}
#fourth {
  background-color: blue;
  transform-origin: 100% 0;
}

.scale {
  transform: scaleX(4);
}
    </style>
</head>
<body>
    <div class="container">
        <div id="first" class="box"></div>
        <div id="second" class="box"></div>
        <div id="third" class="box"></div>
        <div id="fourth" class="box"></div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        var containerWidth = $(".container").width();
        $(".box").click(function() {
          var id = $(this).attr("id");
          $(this).addClass('scale');
        });
    });
</script>
</code>```

Jsfiddle

答:
Just tweak around your CSS a lil bit:

Since your .box width is 20%, your scaleX() is 5,

Then just go ahead and fix your Transform-origins so it covers out correctly:
https://jsfiddle.net/m157u2yw/8/

```<code>.box {
  width:20%;
  height: 200px;
  transition: transform .5s;
  transform-origin: 0 0;
}
#first {
  background-color: red;
}
#second {
  background-color: green;
  transform-origin: 33.33%;
}
#third {
  background-color: aqua;
  transform-origin: 66.66%;
}
#fourth {
  background-color: blue;
  transform-origin: 100%;
}
.scale {
  transform: scaleX(5);
}
</code>```

Title: Scale transition in four divs

Body:
This question is related to one that i have already created transition-in-div . I didnot get answer for my next issue there so i decided to create new question.
I have four boxes and i want the transition effect in all four boxes.

What i want is whenever i click on any box, the width of that box must increase from its side to the left and right to fit the full width. Right now it only fills some portion of width.
My Code is

    <title>Transition</title>

Jsfiddle

Body:
Just tweak around your CSS a lil bit:

Since your .box width is 20%, your scaleX() is 5,

Then just go ahead and fix your Transform-origins so it covers out correctly:
https://jsfiddle.net/m157u2yw/8/

.box {
  width:20%;
  height: 200px;
  transition: transform .5s;
  transform-origin: 0 0;
}
#first {
  background-color: red;
}
#second {
  background-color: green;
  transform-origin: 33.33%;
}
#third {
  background-color: aqua;
  transform-origin: 66.66%;
}
#fourth {
  background-color: blue;
  transform-origin: 100%;
}
.scale {
  transform: scaleX(5);
}


问:
Hide URL parameters in AngularJS
I am pretty new to AngularJS.
My question is regarding Hiding paramters in URL.

For Example, i have an URL Like,

```<code>http://localhost:8080/CareerTurn/#/viewExamwiseStudentsReport?exam_id=2&eName=College%20Model%20Exam&mMarks=10&time=00:10
</code>```

I want to show this like,

```<code>http://localhost:8080/CareerTurn/#/viewExamwiseStudentsReport
</code>```

HTML:

```<code><a href="#viewExamwiseStudentsReport?exam_id={{exa.model_exam_id}}&eName={{exa.model_exam_name}}&mMarks={{exa.model_exam_total_marks}}&time={{exa.model_exam_duration}}">
</code>```

I don't want to show parameters in URL but i want to use them in my JS Controller,

How to achieve it?

答:
You can use

```<code>$location.url($location.path());
</code>```

Also

If you want to remove ALL query parameters, do:

```<code>$location.search({});
</code>```

If you want To remove ONE particular query parameter, do:

```<code>$location.search('ParamName', null);
</code>```

Title: Hide URL parameters in AngularJS

Body:
I am pretty new to AngularJS.
My question is regarding Hiding paramters in URL.

For Example, i have an URL Like,

http://localhost:8080/CareerTurn/#/viewExamwiseStudentsReport?exam_id=2&eName=College%20Model%20Exam&mMarks=10&time=00:10

I want to show this like,

http://localhost:8080/CareerTurn/#/viewExamwiseStudentsReport

HTML:

I don't want to show parameters in URL but i want to use them in my JS Controller,

How to achieve it?

Body:
You can use

$location.url($location.path());

Also

If you want to remove ALL query parameters, do:

$location.search({});

If you want To remove ONE particular query parameter, do:

$location.search('ParamName', null);


问:
Chrome opens with "Data;" with selenium
I am a newbie to Selenium and trying to open localhost:3000 page from Chrome via selenium driver.
The code is :

```<code>import com.google.common.base.Function;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumTests {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C://chromedriver_win32//chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("localhost:3000");
    }

}
</code>```

However, this opens my chrome window with a "data;" .
The chrome version is 50.0.2661.94

Any idea what is the exact issue?

答: I was also getting the same issue. I updated ChromeDriver to the latest version and that fixed it.</p>

Title: Chrome opens with "Data;" with selenium

Body:
I am a newbie to Selenium and trying to open localhost:3000 page from Chrome via selenium driver.
The code is :

import com.google.common.base.Function;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumTests {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C://chromedriver_win32//chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("localhost:3000");
    }

}

However, this opens my chrome window with a "data;" .
The chrome version is 50.0.2661.94

Any idea what is the exact issue?


问:
Webpage won't parse PHP code
I'm trying to add some of my own PHP to a nearly-unreadable template file on a forum system. I know it all works perfectly as far as the server config, etc. goes, but PHP simply doesn't parse on this page. JS works fine. Any ideas? It's a simple .html page.</p>

答:
Is it possible that the template file is being read into a variable rather than being included or required? Eg. it's loaded using file_get_contents or something similar?

If this is the case you may need to eval() the template code after it has been loaded as file_get_contents does not parse php code, it just loads the text as it is into a variable. It's a very ugly solution but it may work for you. Please be careful if you do this as it does open up a whole can of security issue worms.

Title: Webpage won't parse PHP code


问:
Overwrite CSS from another files
I've downloaded a big webtemplate with many different css and js files. Now my website looks good but there still some little things I want to change. Like the font-style, colors and other things.

Now my problem is that I'm not able to overwrite the css from another files.

I want to change the font-family of my webpage. Now the normal content inside my
 tags, the navbar and and and... they all got the new font-family. But every  tag still got the old font family. I tried it with:

```<code>font-family: 'Roboto', sans-serif !important;
</code>```

but this haven't changed a thing and I don't really want to overwrite the css files that came from the template.

is there a way that my custom.css gets more important then the other files? Or any other trick?

答:
Change your selector to</p>

```<code>* {font-family: 'Roboto', sans-serif !important;}
</code>```

Title: Overwrite CSS from another files

Body:
I've downloaded a big webtemplate with many different css and js files. Now my website looks good but there still some little things I want to change. Like the font-style, colors and other things.

Now my problem is that I'm not able to overwrite the css from another files.

I want to change the font-family of my webpage. Now the normal content inside my
 tags, the navbar and and and... they all got the new font-family. But every  tag still got the old font family. I tried it with:

font-family: 'Roboto', sans-serif !important;

but this haven't changed a thing and I don't really want to overwrite the css files that came from the template.

is there a way that my custom.css gets more important then the other files? Or any other trick?

Body:
Change your selector to

* {font-family: 'Roboto', sans-serif !important;}


问:
How to use interceptor to add Headers in Retrofit 2.0?
Our team decide to adopt Retrofit 2.0 and I'm doing some initial research on it. I'm a newbie to this library.

I'm wondering how to use interceptor to add customized headers via Retrofits 2.0 in our Android app. There are many tutorials about using interceptor to add headers in Retrofit 1.X, but since the APIs have changed a lot in the latest version, I'm not sure how to adapt those methods in the new version. Also, Retrofit hasn't update its new documentation yet.

For example, in the following codes, how should I implement the Interceptor class to add extra headers? Besides, what exactly is the undocumented Chain object? When will the intercept() be called?

```<code>    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());

            // How to add extra headers?

            return response;
        }
    });

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_API_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
</code>```

答:
You can headers using Interceptors with its built-in methods like this</p>

```<code>   interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            Request.Builder builder = original.newBuilder();

            builder.header("Authorization","Bearer "+ LeafPreference.getInstance(context).getString(LeafPreference.TOKEN));

            Request request = builder.method(original.method(), original.body())
                    .build();
            Log.e("request",request.urlString());
            Log.e("header",request.header("Authorization"));
            return chain.proceed(request);
        }
    });
}
</code>```

Body:
Our team decide to adopt Retrofit 2.0 and I'm doing some initial research on it. I'm a newbie to this library.

I'm wondering how to use interceptor to add customized headers via Retrofits 2.0 in our Android app. There are many tutorials about using interceptor to add headers in Retrofit 1.X, but since the APIs have changed a lot in the latest version, I'm not sure how to adapt those methods in the new version. Also, Retrofit hasn't update its new documentation yet.

For example, in the following codes, how should I implement the Interceptor class to add extra headers? Besides, what exactly is the undocumented Chain object? When will the intercept() be called?

    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());

            // How to add extra headers?

            return response;
        }
    });

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_API_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

Body:
You can headers using Interceptors with its built-in methods like this

   interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            Request.Builder builder = original.newBuilder();

            builder.header("Authorization","Bearer "+ LeafPreference.getInstance(context).getString(LeafPreference.TOKEN));

            Request request = builder.method(original.method(), original.body())
                    .build();
            Log.e("request",request.urlString());
            Log.e("header",request.header("Authorization"));
            return chain.proceed(request);
        }
    });
}


答:
There's a small mathematical error, you are scaling each div to 4x when their size is 20% so their new size is now 80% instead of the full 100% width.

Please consider the following fiddle: https://jsfiddle.net/m157u2yw/7/

For previewing purposes I've made it so if you click on an expanded box it resets back so you can quickly play with it.

I'm using width instead of scale as it will be useful in case these squares actually have some content inside (scaling would distort it).

I'm also adding another class .scale-down to the not-clicked divs to make sure they also animate out leaving the full space to the expanded one.

Title: Scale transition in four divs


问:
Smallest Sum Algorithm
I feel like I may not have been clear enough about the requirements so let me try to make things more clear.

You are provided a dictionary that contains keys that are either single letters or multiple letters. Each key has an associated value. Given an input, you must find the keys that contain the input letters. Return the lowest key values that satisfy this requirement.

Here are a few examples:

Input Dictionary

Key -> Value

a -> 4

b -> 6

e -> 5

abc -> 8

Input: 'a'
Output: 4

Input: 'c'
Output: 8

Input: 'ab'
Output: 8

Input: 'ac'
Output: 8

Input: 'ce'
Output: 13

Input: 'd'
Output: null

Note on the third example, the input is ab. So here, we can either get the letter 'a' from the key 'a' or the key 'abc'. We can either get the letter 'b' from the key 'b' or the key 'abc'. In order to get both keys with the lowest total value, 'abc' with a value of 8 is the correct output.

Note on the fifth example, the input is ce. The letter 'c' is only available in the key 'abc'. The letter 'e' is only available in the key 'e'. The correct output in this situation is 13.

UPDATE: I was able to solve this recursively by starting off with the first letter in the input sequence, finding all keys that contain that letter, and for each key, building a list of all the possible combinations. I was able to track the lowest sum by recursively moving through one letter of the input sequence at a time.

答:
i don't know if i get it right

```<code>private static Dictionary<string, int>  dic=new Dictionary<string, int>()  ;
public static void MinSum()
{

    // here create statements where the key is a single letter
    dic.Add("a", 4);
    dic.Add("b", 6);
    dic.Add("c", 3);
    dic.Add("d", 4);
    dic.Add("e", 5);
    // here add the combination
    dic.Add("abcde", 8);
    dic.Add("abce", 10);
    dic.Add("ae", 2);

    var minSum= GetMinSum( "ae".ToCharArray());
    var minSum2 = GetMinSum("abc".ToCharArray());
    var minSum4 = GetMinSum("a".ToCharArray());

}

public static int GetMinSum(char[] letters)
{
    //If the input is a single letter, then I simply return the value associated with that key
    if (letters.Count() == 1)
        return dic[letters[0].ToString()];

    // sumUp all the single Key elements
    var sumOfSingleKeyElements = dic.Where(x => x.Key.Length == 1 && letters.Contains(x.Key[0])).Sum(v => v.Value);
    // get the min value Key elements that combine the letters above
    //  the " !letters.Except(x.Key.ToCharArray()).Any()" defines if the set letters is a subset of the key
    var minOfCompositeKeyElements = dic.Where(x => x.Key.Length > 1
                        && !letters.Except(x.Key.ToCharArray()).Any()
                        ).Min(v => v.Value);

    return sumOfSingleKeyElements < minOfCompositeKeyElements ? sumOfSingleKeyElements : minOfCompositeKeyElements;
}
</code>```

The minimum sum for the letter combination "a","e" is 2

The minimum sum for the letter combination "a","b","c" is 8

The minimum sum for the letter "a" is 4

Title: Smallest Sum Algorithm

Body:
i don't know if i get it right

private static Dictionary<string, int>  dic=new Dictionary<string, int>()  ;
public static void MinSum()
{

    // here create statements where the key is a single letter
    dic.Add("a", 4);
    dic.Add("b", 6);
    dic.Add("c", 3);
    dic.Add("d", 4);
    dic.Add("e", 5);
    // here add the combination
    dic.Add("abcde", 8);
    dic.Add("abce", 10);
    dic.Add("ae", 2);

    var minSum= GetMinSum( "ae".ToCharArray());
    var minSum2 = GetMinSum("abc".ToCharArray());
    var minSum4 = GetMinSum("a".ToCharArray());

}

public static int GetMinSum(char[] letters)
{
    //If the input is a single letter, then I simply return the value associated with that key
    if (letters.Count() == 1)
        return dic[letters[0].ToString()];

    // sumUp all the single Key elements
    var sumOfSingleKeyElements = dic.Where(x => x.Key.Length == 1 && letters.Contains(x.Key[0])).Sum(v => v.Value);
    // get the min value Key elements that combine the letters above
    //  the " !letters.Except(x.Key.ToCharArray()).Any()" defines if the set letters is a subset of the key
    var minOfCompositeKeyElements = dic.Where(x => x.Key.Length > 1
                        && !letters.Except(x.Key.ToCharArray()).Any()
                        ).Min(v => v.Value);

    return sumOfSingleKeyElements < minOfCompositeKeyElements ? sumOfSingleKeyElements : minOfCompositeKeyElements;
}

The minimum sum for the letter combination "a","e" is 2

The minimum sum for the letter combination "a","b","c" is 8

The minimum sum for the letter "a" is 4


问:
Invalid credentials when trying to authenticate via Facebook
Can't connect via facebook anymore on my rails app

Here is the error I get

GET https://www.myapp.com/auth/failure?message=invalid_credentials&strategy=facebook 404

No changes were made to the app and it worked fine 2 days ago

答: Goto  facebook app and create new credentials and test it.</p>


问:
fullpage.js how to create slide custom image navigation dots?
I am using fullPage.js fullpage slider in my project. but i need the customized image as navigation dots. I searched the fullPage documentation also. but i cant find out the solutions. Anybody know about this, Thanks in advance.</p>

答:
You can use the menu option.
You can create any kind of menu / nav with it and it will add the active class where it should.

From the documentation:

menu: (default false) A selector can be used to specify the menu to link with the sections. This way the scrolling of the sections will activate the corresponding element in the menu using the class active. This won't generate a menu but will just add the active class to the element in the given menu with the corresponding anchor links. In order to link the elements of the menu with the sections, an HTML 5 data-tag (data-menuanchor) will be needed to use with the same anchor links as used within the sections. Example:

Just use a class if you want to have multiple menus / navs.

menu: '.myNav'

Otherwise, you can also use the fullPage.js callbacks or the fullPage.js state classes to activate and desactivate the elements of any nav or menu.

Check this answer here.


问:
Pure css tabs without radio button
I'm trying to adapt this jsfiddle to work without radio button since I cannot use any <form> related tags, and neither javascript!

I "transformed" the <input type='radio'> into  tags, and transform the :checked pseudo class into :target
as you can see in this CodePen.

but it does not work :-(

And also solution I used to show first Tab is not usable

Can suggest what's wrong?

Thanks
Joe

答:
Alright, using the :target pseudo-class we can achieve this.

EDIT: I added a wrapper div so you can use position absolute on the panels. This allows you to have the first panel open and switch between them.

.wrapper {
  position: relative;
}
.tab-container {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  background: red;
}

.tab-container:first-child { display: block }

:target { display: block }

/* just for demo */

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  display: inline-block;
  margin-right: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Tab 1</li>
  <li>Tab 2</li>
  <li>Tab 3</li>
</ul>

<div class="wrapper">
  <div id="tab-1-container" class="tab-container">
    Tab 1 content
  </div>

  <div id="tab-2-container" class="tab-container">
  Tab 2 content
  </div>

  <div id="tab-3-container" class="tab-container">
  Tab 3 content
  </div>
</div></code>```

Title: Pure css tabs without radio button

Body:
Alright, using the :target pseudo-class we can achieve this.

EDIT: I added a wrapper div so you can use position absolute on the panels. This allows you to have the first panel open and switch between them.

.wrapper {
  position: relative;
}
.tab-container {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  background: red;
}

.tab-container:first-child { display: block }

:target { display: block }

/* just for demo */

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  display: inline-block;
  margin-right: 1rem;
}

<ul>
  <li><a href="#tab-1-container">Tab 1</a></li>
  <li><a href="#tab-2-container">Tab 2</a></li>
  <li><a href="#tab-3-container">Tab 3</a></li>
</ul>

<div class="wrapper">
  <div id="tab-1-container" class="tab-container">
    Tab 1 content
  </div>

  <div id="tab-2-container" class="tab-container">
  Tab 2 content
  </div>

  <div id="tab-3-container" class="tab-container">
  Tab 3 content
  </div>
</div>


问:
ko.computed do not fire function upon instantiating
Hi is there a way to not fire the function when instantiating a ko.computed

example is

i have this ko.computed

```<code>ko.computed(function(){ alert(this.Test); } , this);
</code>```

so basically if i instantiated this computed this will fire the function defined there
is there a way not to fire it upon instantiation? and only fire it when dependency change?

答:
You can also use a knockout pureComputed for this. A pure computed only evaluates when there's a dependency.

Example:

var person, fullName,
    getFullName = function() {
       return person().firstName() + " " + person().lastName();
    };

person = ko.observable(null);

// This won't work, because the computed evaluates and getFullName doesn't
// check for `null`
try {
  fullName = ko.computed(getFullName);
} catch (err) {
  console.log("Regular computed:");
  console.log(err.message);
}

// This will work because there's no dependency to `fullName` yet
// At `applyBindings`, `fullName` needs to be evaluated
fullName = ko.pureComputed(getFullName);

person({
  firstName: ko.observable("Jane"),
  lastName: ko.observable("Doe")
});

ko.applyBindings({ heading: fullName })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<h3 data-bind="text: heading"></h3>  </code>```

Body:
Hi is there a way to not fire the function when instantiating a ko.computed

example is

i have this ko.computed

ko.computed(function(){ alert(this.Test); } , this);

so basically if i instantiated this computed this will fire the function defined there
is there a way not to fire it upon instantiation? and only fire it when dependency change?

Body:
You can also use a knockout pureComputed for this. A pure computed only evaluates when there's a dependency.

Example:

var person, fullName,
    getFullName = function() {
       return person().firstName() + " " + person().lastName();
    };

person = ko.observable(null);

// This won't work, because the computed evaluates and getFullName doesn't
// check for `null`
try {
  fullName = ko.computed(getFullName);
} catch (err) {
  console.log("Regular computed:");
  console.log(err.message);
}

// This will work because there's no dependency to `fullName` yet
// At `applyBindings`, `fullName` needs to be evaluated
fullName = ko.pureComputed(getFullName);

person({
  firstName: ko.observable("Jane"),
  lastName: ko.observable("Doe")
});

ko.applyBindings({ heading: fullName })

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<h3 data-bind="text: heading"></h3>


问:
What is the current Crashlytics version?
This line is automatically generated by Gradle. I want to avoid using +, so I need the most recent stable version of Crashlytics.

```<code>compile "com.crashlytics.android:crashlytics:1.+"
</code>```

答:
get the latest version from maven metadata:

https://maven.fabric.io/public/com/crashlytics/sdk/android/crashlytics/maven-metadata.xml

.. same with the fabric plugin:

https://maven.fabric.io/public/io/fabric/tools/gradle/maven-metadata.xml

Body:
This line is automatically generated by Gradle. I want to avoid using +, so I need the most recent stable version of Crashlytics.

compile "com.crashlytics.android:crashlytics:1.+"


问:
c# - DataGridView add row runtime error cell's model
I have a DataGridView component that I use to show some value to the user. It is made of 5 columns: 4 strings and 1 check box. This is my code to create columns and add them to the conrtol:

```<code>// class variables
const int NUM_COLUMNS = 5;
DataGridViewColumn[] columns;
DataGridViewCheckBoxColumn checkColumn;
List <String> columnsHeaderName;

 // init method
 private void init_dataGridView()
    {
        // init all components
        columnsHeaderName = new List<string>();
        columns = new DataGridViewColumn[NUM_COLUMNS - 1]; // minus one becouse last one is a check box column
        checkColumn = new DataGridViewCheckBoxColumn(); // last one
        // columns descriptions
        columnsHeaderName.Add("File path");
        columnsHeaderName.Add("Sampling");
        columnsHeaderName.Add("Start Date");
        columnsHeaderName.Add("End Date");
        columnsHeaderName.Add("Select");

        for (int i = 0; i < NUM_COLUMNS - 1; i++)
        {
            // create, configure and add n-1 columns
            columns[i] = new DataGridViewColumn();
            columns[i].Name = Convert.ToString(i);
            columns[i].HeaderText = columnsHeaderName[i];
            columns[i].ReadOnly = true;
            this.dataGridView1.Columns.Add(columns[i]);
        }
         // create, configure and add last column
        checkColumn.Name = Convert.ToString(NUM_COLUMNS - 1);// (NUM_COLUMNS - 1).ToString();
        checkColumn.HeaderText = columnsHeaderName[NUM_COLUMNS - 1];
        checkColumn.Width = 50;
        checkColumn.ReadOnly = false;
        checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
        this.dataGridView1.Columns.Add(checkColumn);
    }
</code>```

The problem appears when I try to add a new row to my table

```<code> private void LoadFileButton_Click(object sender, EventArgs e)
    {
        string file = "";
        DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
        if (result == DialogResult.OK) // Test result.
        {
           file = openFileDialog1.FileName;
            Console.WriteLine(file);
            dataGridView1.Rows.Add(new object[] { "value 1", "value 2", "value 3", "value 4", true });
        }
    }
</code>```

The call to dataGridView1.Rows.Add() method throws me an exception. The description of the exception is: "At least one of the columns has not any cell's model"

Really I don't understand what I am doing wrong. Hope some ine can help me. Thanks in advance.

答:
You cannot add DataGridViewColumn
If you try and run below code:

```<code>DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = "xyz";
col.HeaderText = "XYZ";
col.ReadOnly = true;
this.dataGridView1.Columns.Add(col);
</code>```

It will work because we are adding DataGridViewTextBoxColumn not DataGridViewColumn

So possible fix is

```<code>for (int i = 0; i < NUM_COLUMNS - 1; i++)
            {
                // create, configure and add n-1 columns
                columns[i] = new DataGridViewTextBoxColumn(); // or some other type that you want
                columns[i].Name = Convert.ToString(i);
                columns[i].HeaderText = columnsHeaderName[i];
                columns[i].ReadOnly = true;
                this.dataGridView1.Columns.Add(columns[i]);
            }
</code>```

Body:
I have a DataGridView component that I use to show some value to the user. It is made of 5 columns: 4 strings and 1 check box. This is my code to create columns and add them to the conrtol:

// class variables
const int NUM_COLUMNS = 5;
DataGridViewColumn[] columns;
DataGridViewCheckBoxColumn checkColumn;
List <String> columnsHeaderName;

 // init method
 private void init_dataGridView()
    {
        // init all components
        columnsHeaderName = new List<string>();
        columns = new DataGridViewColumn[NUM_COLUMNS - 1]; // minus one becouse last one is a check box column
        checkColumn = new DataGridViewCheckBoxColumn(); // last one
        // columns descriptions
        columnsHeaderName.Add("File path");
        columnsHeaderName.Add("Sampling");
        columnsHeaderName.Add("Start Date");
        columnsHeaderName.Add("End Date");
        columnsHeaderName.Add("Select");

        for (int i = 0; i < NUM_COLUMNS - 1; i++)
        {
            // create, configure and add n-1 columns
            columns[i] = new DataGridViewColumn();
            columns[i].Name = Convert.ToString(i);
            columns[i].HeaderText = columnsHeaderName[i];
            columns[i].ReadOnly = true;
            this.dataGridView1.Columns.Add(columns[i]);
        }
         // create, configure and add last column
        checkColumn.Name = Convert.ToString(NUM_COLUMNS - 1);// (NUM_COLUMNS - 1).ToString();
        checkColumn.HeaderText = columnsHeaderName[NUM_COLUMNS - 1];
        checkColumn.Width = 50;
        checkColumn.ReadOnly = false;
        checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values
        this.dataGridView1.Columns.Add(checkColumn);
    }

The problem appears when I try to add a new row to my table

 private void LoadFileButton_Click(object sender, EventArgs e)
    {
        string file = "";
        DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
        if (result == DialogResult.OK) // Test result.
        {
           file = openFileDialog1.FileName;
            Console.WriteLine(file);
            dataGridView1.Rows.Add(new object[] { "value 1", "value 2", "value 3", "value 4", true });
        }
    }

The call to dataGridView1.Rows.Add() method throws me an exception. The description of the exception is: "At least one of the columns has not any cell's model"

Really I don't understand what I am doing wrong. Hope some ine can help me. Thanks in advance.

Body:
You cannot add DataGridViewColumn
If you try and run below code:

DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.Name = "xyz";
col.HeaderText = "XYZ";
col.ReadOnly = true;
this.dataGridView1.Columns.Add(col);

It will work because we are adding DataGridViewTextBoxColumn not DataGridViewColumn

So possible fix is

for (int i = 0; i < NUM_COLUMNS - 1; i++)
            {
                // create, configure and add n-1 columns
                columns[i] = new DataGridViewTextBoxColumn(); // or some other type that you want
                columns[i].Name = Convert.ToString(i);
                columns[i].HeaderText = columnsHeaderName[i];
                columns[i].ReadOnly = true;
                this.dataGridView1.Columns.Add(columns[i]);
            }


问:
IOS Photos framework
I want to retrieve all the photos from all the local albums on the device. Basically all the photos that are on the device
Will the list of local identifiers be unique ?
What is the best approach for this using the photos framework.

My question is not duplicate since the other question talks about also cloud assets and assets that are not on the device. When retrieving actual data of the image it returns null data when trying to fetch synchronize.

答:
```<code>PHFetchResult *smartAlbums;
smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

    for (NSInteger i =0; i < smartAlbums.count; i++)
{
    @autoreleasepool
    {
        PHAssetCollection *assetCollection = smartAlbums[i];
        //Camera Roll
        //All Photos //Moments
        NSLog(@"assetCollection.localizedTitle---%@",assetCollection.localizedTitle);

        // here you will get camera roll photos

        if([assetCollection.localizedTitle isEqualToString:@"Camera Roll"] || [assetCollection.localizedTitle isEqualToString:@"All Photos"] )
        {
            PHFetchOptions *options1 = [[PHFetchOptions alloc] init];
            options1.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
            options1.predicate = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];

            // here you will get all assets of your camera roll images in assetsFetchResult
            PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:options1];
        }
    }
}
</code>```

Title: IOS Photos framework


问:
Protractor can't use local properties declared with this. inside .then statement
I've been trying to best organise my Protractor e2e tests in a reusable manner using the Page Object model. At the start of every Page Object I will define the elements on the page, followed by the local functions. e.g:

```<code>'use strict';

var examplePage = function() {
    // Locators
    this.button1   = $('#button1')
    this.element1  = $('#element1');
    this.element2  = $('.element2');

    // Error Messages
    this.ERROR_ONE = 'There was an error!';

    // Protractor ExpectedConditions instance
    var until = protractor.ExpectedConditions;

    this.doSomeStuff = function() {
        this.button1.click().then(function() {
            browser.wait(until.visibilityOf(this.element1), global.TIMEOUT_INTERVAL_SHORT, this.ERROR_ONE);
            return this.element1;
        });
    };
};
module.exports = examplePage;
</code>```

My code above is just an example. My real code is very similar.

Sometimes in my code I may need to control the order that the functions are executed to stop the functions from executing too early. However, this causes a completely local scope inside the .then statement. For example, the 'this.ERROR_ONE' property becomes inaccessible so I can't maintain my error messages and 'this.element1' becomes inaccessible.

Has anybody else encountered this and found a solution to this problem? It becomes messy to maintain the same value all over my Page Objects.

答:
Protractor team has a good tutorial on PageObject pattern for Protractor frameworks. You cannot use this to declare variables.

You can directly access the objects as shown in the above tutorial -

```<code>var examplePage = function() {
    // Locators
    var button1   = $('#button1');
    var element1  = $('#element1');
    var element2  = $('.element2');

    // Error Messages
    var ERROR_ONE = 'There was an error!';

    // Protractor ExpectedConditions instance
    var until = protractor.ExpectedConditions;

    this.doSomeStuff = function() {
        this.button1.click().then(function() {
            browser.wait(until.visibilityOf(element1), global.TIMEOUT_INTERVAL_SHORT, ERROR_ONE);
            return element1;
        });
    };
};
module.exports = examplePage;
</code>```

Body:
I've been trying to best organise my Protractor e2e tests in a reusable manner using the Page Object model. At the start of every Page Object I will define the elements on the page, followed by the local functions. e.g:

'use strict';

var examplePage = function() {
    // Locators
    this.button1   = $('#button1')
    this.element1  = $('#element1');
    this.element2  = $('.element2');

    // Error Messages
    this.ERROR_ONE = 'There was an error!';

    // Protractor ExpectedConditions instance
    var until = protractor.ExpectedConditions;

    this.doSomeStuff = function() {
        this.button1.click().then(function() {
            browser.wait(until.visibilityOf(this.element1), global.TIMEOUT_INTERVAL_SHORT, this.ERROR_ONE);
            return this.element1;
        });
    };
};
module.exports = examplePage;

My code above is just an example. My real code is very similar.

Sometimes in my code I may need to control the order that the functions are executed to stop the functions from executing too early. However, this causes a completely local scope inside the .then statement. For example, the 'this.ERROR_ONE' property becomes inaccessible so I can't maintain my error messages and 'this.element1' becomes inaccessible.

Has anybody else encountered this and found a solution to this problem? It becomes messy to maintain the same value all over my Page Objects.

Body:
Protractor team has a good tutorial on PageObject pattern for Protractor frameworks. You cannot use this to declare variables.

You can directly access the objects as shown in the above tutorial -

var examplePage = function() {
    // Locators
    var button1   = $('#button1');
    var element1  = $('#element1');
    var element2  = $('.element2');

    // Error Messages
    var ERROR_ONE = 'There was an error!';

    // Protractor ExpectedConditions instance
    var until = protractor.ExpectedConditions;

    this.doSomeStuff = function() {
        this.button1.click().then(function() {
            browser.wait(until.visibilityOf(element1), global.TIMEOUT_INTERVAL_SHORT, ERROR_ONE);
            return element1;
        });
    };
};
module.exports = examplePage;


问:
send PHP code in database
I am trying to post php code from my messages table. But it is not posting. For example:

```<code><textarea name="update">User can write php codes here for sending</textarea>
<div class="send">Send</div>
</code>```

When i click send button the text code <?php echo $message;?> must be in my messages table row post_text . But post_text is empty, you can see it in the screenshot.

What is the problem here. What i shoud do to fix this problem? Anyone can help me here ?

```<code><?php
include_once '../inc/inc.php';
if(isset($_POST['update'])) {

   $update=mysqli_real_escape_string($db,$_POST['update']);
   if($update){
      $data=$DoDo->InsertText($uid,$update);
      echo $update;
   }
}
?>
</code>```

InsertText function

```<code>public function InsertText($uid, $update) {

    $time=time();
    $ip=$_SERVER['REMOTE_ADDR'];
    mysqli_query($this->db,"SET character_set_client=utf8") or die(mysqli_error($this->db));
    mysqli_query($this->db,"SET character_set_connection=utf8") or die(mysqli_error($this->db));

    $query = mysqli_query($this->db,"SELECT post_id,post_text FROM `posts` WHERE uid_fk='$uid' order by post_id desc limit 1") or die(mysqli_error($this->db));
    $result = mysqli_fetch_array($query, MYSQLI_ASSOC);

     $query = mysqli_query($this->db,"INSERT INTO `posts` (post_text, uid_fk,time) VALUES (N'$update', '$uid','$time')") or die(mysqli_error($this->db));

     //The newquery to select for message
     $newquery = mysqli_query($this->db,"SELECT M.post_id, M.uid_fk, M.post_text, M.time,U.username FROM posts M, users U where M.uid_fk=U.uid and M.uid_fk='$uid' order by M.post_id desc limit 1 ") or die(mysqli_error($this->db));
     $result = mysqli_fetch_array($newquery, MYSQLI_ASSOC);
     return $result;
}
</code>```

Note: This problem will be come when i send just php code. If i send
  normal text then normal text sending from post_text.

I want to send php code like this screenshot.

答:
change this

```<code> VALUES (N'$update', '$uid','$time')"
</code>```

to

```<code>VALUES ('$update', '$uid','$time')"
</code>```

Title: send PHP code in database

Body:
I am trying to post php code from my messages table. But it is not posting. For example:

<textarea name="update">User can write php codes here for sending</textarea>

Send

When i click send button the text code <?php echo $message;?> must be in my messages table row post_text . But post_text is empty, you can see it in the screenshot.

What is the problem here. What i shoud do to fix this problem? Anyone can help me here ?

<?php
include_once '../inc/inc.php';
if(isset($_POST['update'])) {

   $update=mysqli_real_escape_string($db,$_POST['update']);
   if($update){
      $data=$DoDo->InsertText($uid,$update);
      echo $update;
   }
}
?>

InsertText function

public function InsertText($uid, $update) {

    $time=time();
    $ip=$_SERVER['REMOTE_ADDR'];
    mysqli_query($this->db,"SET character_set_client=utf8") or die(mysqli_error($this->db));
    mysqli_query($this->db,"SET character_set_connection=utf8") or die(mysqli_error($this->db));

    $query = mysqli_query($this->db,"SELECT post_id,post_text FROM `posts` WHERE uid_fk='$uid' order by post_id desc limit 1") or die(mysqli_error($this->db));
    $result = mysqli_fetch_array($query, MYSQLI_ASSOC);

     $query = mysqli_query($this->db,"INSERT INTO `posts` (post_text, uid_fk,time) VALUES (N'$update', '$uid','$time')") or die(mysqli_error($this->db));

     //The newquery to select for message
     $newquery = mysqli_query($this->db,"SELECT M.post_id, M.uid_fk, M.post_text, M.time,U.username FROM posts M, users U where M.uid_fk=U.uid and M.uid_fk='$uid' order by M.post_id desc limit 1 ") or die(mysqli_error($this->db));
     $result = mysqli_fetch_array($newquery, MYSQLI_ASSOC);
     return $result;
}

Note: This problem will be come when i send just php code. If i send
  normal text then normal text sending from post_text.

I want to send php code like this screenshot.

Body:
change this

 VALUES (N'$update', '$uid','$time')"

to

VALUES ('$update', '$uid','$time')"


问:
VBA - HTMLDocument (Internet Explorer *.website)
to get the HTML Document of an opened IE i use the following code:

```<code>Function getOpenIEByTitle(Title As String) As InternetExplorer
    On Error Resume Next
    Dim sh As Object
    Set sh = CreateObject("Shell.Application")
    For Each getOpenIEByTitle In sh.Windows
        If TypeName(getOpenIEByTitle.document) = "HTMLDocument" Then
            If getOpenIEByTitle.document.Title = Title Then
                Exit Function
            End If
        End If
    Next
End Function
</code>```

This works fine!

BUT:

I can't find the Window if i start a *.website-File with "iexplore.exe" -w "*.website"

Can some one help me?

Are there other solutions?

Can i get the HTMLDocument of any running iexplore.exe if i can provide the right PID?

Creating a new InternetExplorer-Application is not a solution for my environment. Or can i start a pinned Website from VBA?

答:
If you know URL or part of URL try this:</p>

```<code>Public Function GetIEInstance(URLAddress) As SHDocVw.WebBrowser
    Dim objShellWindows as ShDocVw.ShellWindows
    Dim ShellWindow as ShDocVw.WebBrowser

    Set objShellWindows = new ShDocVw.ShellWindows

    For Each ShellWindow in objShellWindows
        If InStr(ShellWindow.Name, "Internet Explorer") > 0 Then
            If ShellWindow.LocationURL Like "*" & URLAddress & "*" Then
                Set GetIEInstance = ShellWindow.Application
                Exit Function
            End If
        End If
    Next ShellWindow

End Function
</code>```

Body:
to get the HTML Document of an opened IE i use the following code:

Function getOpenIEByTitle(Title As String) As InternetExplorer
    On Error Resume Next
    Dim sh As Object
    Set sh = CreateObject("Shell.Application")
    For Each getOpenIEByTitle In sh.Windows
        If TypeName(getOpenIEByTitle.document) = "HTMLDocument" Then
            If getOpenIEByTitle.document.Title = Title Then
                Exit Function
            End If
        End If
    Next
End Function

This works fine!

BUT:

I can't find the Window if i start a *.website-File with "iexplore.exe" -w "*.website"

Can some one help me?

Are there other solutions?

Can i get the HTMLDocument of any running iexplore.exe if i can provide the right PID?

Creating a new InternetExplorer-Application is not a solution for my environment. Or can i start a pinned Website from VBA?

Body:
If you know URL or part of URL try this:

Public Function GetIEInstance(URLAddress) As SHDocVw.WebBrowser
    Dim objShellWindows as ShDocVw.ShellWindows
    Dim ShellWindow as ShDocVw.WebBrowser

    Set objShellWindows = new ShDocVw.ShellWindows

    For Each ShellWindow in objShellWindows
        If InStr(ShellWindow.Name, "Internet Explorer") > 0 Then
            If ShellWindow.LocationURL Like "*" & URLAddress & "*" Then
                Set GetIEInstance = ShellWindow.Application
                Exit Function
            End If
        End If
    Next ShellWindow

End Function


问:
How can I find the number of keys in a hash in Perl?
How do I find the number of keys in a hash, like using <code>$#</code> for arrays? </p>

答:
```<code>print scalar keys %hash;
</code>```

or

```<code>$X = keys %hash;
print $X;
</code>```

keys %hash returns the value of keys in the list context that further changes into the scalar context (when assigning to scalar variable).

Body: How do I find the number of keys in a hash, like using $# for arrays?

Body:
print scalar keys %hash;

or

$X = keys %hash;
print $X;

keys %hash returns the value of keys in the list context that further changes into the scalar context (when assigning to scalar variable).


问:
after restarting terminal, the old ruby version set up
I installed ruby version to my computer 2.1.5, but I have to set up each time with the commands, (eval "$(rbenv init -)) each time I restart the terminal on my mac(system version set back). I set up the system with rbenv and try to use the global command also, but did not work.

Many thanks

答:
It sounds you have to edit .profle or .bash ... or whatever file that uses OSx to initialize the environment in terminal.

I recommend you use RVM

It will solve this and other possible issues


问:
How to store text as paragraphs in SQLite database in a iPhone app?
In my iPhone app, I have a requirement to store a huge amount of text. I have paragraphs of text to be stored in my database along with the newline characters.

What should I do to store the text as paragraphs in SQLite database?

For example, I want to store paragraphs like the ones below in:

(the mother of the faithful believers) The commencement of the Divine Inspiration to Allah's Apostle was in the form of good dreams which came true like bright day light, and then the love of seclusion was bestowed upon him. He used to go in seclusion in the cave of Hira where he used to worship (Allah alone) continuously for many days before his desire to see his family. He used to take with him the journey food for the stay and then come back to (his wife) Khadija to take his food like-wise again till suddenly the Truth descended upon him while he was in the cave of Hira. The angel came to him and asked him to read. The Prophet replied, "I do not know how to read.

The Prophet added, "The angel caught me (forcefully) and pressed me so hard that I could not bear it any more. He then released me and again asked me to read and I replied, 'I do not know how to read.'

Basically I want to save the paragraphs in database in the same format with carriage returns.

答:
so do you want to split the text into paragraph and store each in its own row like:

```<code>(paragraph_number, text_of_paragraph)
</code>```

that would be:

```<code>create table paragraphs (paragraph_number, text_of_paragraph);
</code>```

then in what ever language you use split the text into a list of (pn, tp) named l and do like:

```<code>executemany("insert into paragraphs values (?, ?)", l)
</code>```

or do like:

```<code>for p in l:
    execute("insert into paragraphs values (?, ?)", p)
</code>```

Body:
so do you want to split the text into paragraph and store each in its own row like:

(paragraph_number, text_of_paragraph)

that would be:

create table paragraphs (paragraph_number, text_of_paragraph);

then in what ever language you use split the text into a list of (pn, tp) named l and do like:

executemany("insert into paragraphs values (?, ?)", l)

or do like:

for p in l:
    execute("insert into paragraphs values (?, ?)", p)


问:
What is the difference between session variables and global variables in php?
What is the difference between session variables and global variables in PHP?</p>

答:
global is just a keyword to access a variable that is declared in the top level scope and isn't available in the actual scope. This hasn't anything to do with the session: do not persist between pages.

```<code>$a = "test";
function useGlobalVar(){
    echo $a;   // prints nothing, $a is not availabe in this scope
    global $a;
    echo $a;   // prints "test"
}
</code>```

$GLOBALS is another way to access top-level scope variables without using the global keyword:

```<code>$a = "test";
function useGlobalVar(){
    echo $GLOBAL['a'];   // prints "test"
}
</code>```

There's a bit of of confusion between global and superglobals: Superglobals (like $GLOBALS, $_REQUEST, $_SERVER) are available in any scope without you having to make a global declaration. Again, they do not persist between pages (with the exception of $_SESSION).

$_SESSION is a Superglobal array that persist across different pages.

Body:
global is just a keyword to access a variable that is declared in the top level scope and isn't available in the actual scope. This hasn't anything to do with the session: do not persist between pages.

$a = "test";
function useGlobalVar(){
    echo $a;   // prints nothing, $a is not availabe in this scope
    global $a;
    echo $a;   // prints "test"
}

$GLOBALS is another way to access top-level scope variables without using the global keyword:

$a = "test";
function useGlobalVar(){
    echo $GLOBAL['a'];   // prints "test"
}

There's a bit of of confusion between global and superglobals: Superglobals (like $GLOBALS, $_REQUEST, $_SERVER) are available in any scope without you having to make a global declaration. Again, they do not persist between pages (with the exception of $_SESSION).

$_SESSION is a Superglobal array that persist across different pages.


问:
Missing CodeLens references count in Visual Studio Community edition 2015 and 2017

Is there a reason why the references count (code lens) is missing in Visual Studio Community edition?

Is is possible to enable it in the options?

Here is a screenshot of Visual Studio 2015 and 2017 Community edition:

Here is a screenshot of Visual Studio 2013:

source: dailydotnettips.com

答: I'm not allowed to Comment on R. Richards answer above, so posting this as a separate answer:  CodeLens references disappeared for me too when I upgraded my VS Pro to 2017. But only on my Desktop ("same" upgrade behaved differently on my laptop, where CodeLens settings apparently unaffected). Anyway, very easy to resolve just Enable CodeLens under Text Editor : All Languages</p>


问:
Display message success after docker-compose up is done
I run many services in my docker-compse.yml. I'd like to display a message to let user know when docker-compose up is done?
I tried to echo message with command but my container exited with code 0

```<code>command: bash -c "echo Congratulation! You can use your containers now"
</code>```

Is there anyway to let user know when docker-compose up is done?
Many thanks!

答:
create a shell file echo.sh that contains
echo "Your message"

In Docker file add
CMD ["/dockerRepo/echo.sh"]

Body:
I run many services in my docker-compse.yml. I'd like to display a message to let user know when docker-compose up is done?
I tried to echo message with command but my container exited with code 0

command: bash -c "echo Congratulation! You can use your containers now"

Is there anyway to let user know when docker-compose up is done?
Many thanks!


答: Instead  if($login){ use  if($update){

Title: send PHP code in database

Body: Instead  if($login){ use  if($update){


问:
How to populate FXML tableview with an Observable List
So far I have created a GUI using JavaFX SceneBuilder, which includes an anchor pane containing a two-column TableView.
I have linked events on GUI objects (eg buttons) to event handling code in the FXMLDocumentController. In the controller, when a selected button is clicked, I create an ObservableList from a table stored in an embedded derby database. That works fine.

I'm simply stuck on populating the TableView with the Observable list and despite extensive searches and tutorials I can't find a coherent suggestion that works to achieve the above or even if it is achievable

答: I found the problem to be the PersonOverview AnchorPane Controller class was pointing to a different project. I set the attribute to Empty and the app worked.</p>


问:
stopPropagation vs. stopImmediatePropagation
What's the difference between event.stopPropagation() and event.stopImmediatePropagation()?

答:
1)event.stopPropagation():
 =>It is used to stop executions of its corresponding parent handler only.

2) event.stopImmediatePropagation():
  => It is used to stop the execution of its corresponding parent handler and also handler or function attached to itself except the current handler.
  => It also stops all the handler attached to the current element of entire DOM.

Here is the example: Jsfiddle!

Thanks,
-Sahil


问:
any free SQL Server 2005 express database schema generation and reverse engineering tool?
thanks for your time and sharing.

Please guide me is there some free tool (to use with SQL Server 2005 Express edition) that can generate data base schema by making diagrame and reverse engineering of an existing database ?

Thanks for guiding me.

答:
How about

Microsoft SQL Server Management Studio Express

Download it here


问:
Footer occasionally and randomly moving to right side of page as column
Just wondered if anyone has ever experienced this, sometimes when viewing a page that i've just edited, the footer (which consists of multiple stacked divs) turns itself into columns and appears at the right of my screen, squashing my page content. Sometimes this happens after I've entered faulty code (for example, a '>' instead of a '<'), which is fair enough, but sometimes I just want to change the format of a featured image in my CSS and it does it then too.

I've tried clearing my cache. This error is consistent and appears every time I run certain code, it's just very random what kind of code creates the error.

Has anyone else experienced this?

EDIT: here is my footer.php code, which has worked perfectly for weeks up until today, would not know what other code would be relevant:

```<code>    <div class="personeel group">
        <div class="container group">
            <?php echo do_shortcode("[insert page='accountmanagers']"); ?>
        </div>
    </div>
    <div class="nieuws group">
        <div class="container">
            <?php echo do_shortcode("[insert page='nieuws-front-page']"); ?>
        </div>
    </div>
    <footer class="group">
        <div class="container">
            <div class="row">
                <section class="col-lg-4 col-md-4 col-sm-12">
                    <div class="sectie first">
                        <h3>Over ons</h3>
                        <div class="row">
                            <section class="col-xs-12 col-sm-6">
                                <div class="kolom">
                                    <ul>
                                        <li>Over Match</li>
                                        <li>Accountmanagers</li>
                                        <li>Vormen van bemiddeling</li>
                                        <li>Kwaliteit</li>
                                    </ul>
                                </div>
                            </section>
                            <section class="col-xs-12 col-sm-6">
                                <div class="kolom">
                                    <ul>
                                        <li>Branches</li>
                                        <li>Certicering</li>
                                        <li>Match holding</li>
                                        <li>Contact</li>
                                    </ul>
                                </div>
                            </section>
                        </div>
                    </div>
                </section>
                <section class="col-lg-4 col-md-4 col-sm-12">
                    <div class="sectie second">
                        <h3>Bedrijven</h3>
                        <ul>
                            <li>Arbeidskrachten</li>
                            <li>Vacature plaatsen</li>
                            <li>Vormen van bemiddeling</li>
                        </ul>
                    </div>
                </section>
                <section class="col-lg-4 col-md-4 col-sm-12">
                    <div class="sectie third">
                        <h3>Baan zoeken</h3>
                        <div class="row">
                            <section class="col-xs-12 col-sm-6">
                                <div class="kolom">
                                    <ul>
                                        <li>Vacatures</li>
                                        <li>Inschrijven</li>
                                        <li>Werken bij Match</li>
                                        <li>Snel aan de slag</li>
                                    </ul>
                                </div>
                            </section>
                            <section class="col-xs-12 col-sm-6">
                                <div class="kolom">
                                    <ul>
                                        <li>Vormen van bemiddeling</li>
                                        <li>CV uploaden</li>
                                    </ul>
                                </div>
                            </section>
                        </div>
                    </div>
                </section>
            </div>
        </div>
    </footer>
    <div class="copyright">
        <p>Copyright 2017 - Match | Sitemap | Webdesign One Squad</p>
    </div>
</div>

<?php wp_footer(); ?>
</code>```

single-jobpost.php (plugin template, error occurs):

```<code><?php
/**
 * The Template for displaying job details
 *
 * Override this template by copying it to yourtheme/simple_job_board/single-jobpost.php
 *
 * @author      PressTigers
 * @package     Simple_Job_Board
 * @subpackage  Simple_Job_Board/Templates
 * @version     1.1.0
 * @since       2.2.0
 * @since       2.2.3   Enqueued Front Styles & Revised the HTML structure.
 * @since       2.2.4   Enqueued Front end Scripts.
 * @since       2.3.0   Added "sjb_archive_template" filter.
 */
get_header();

ob_start();
global $post;

/**
 * Enqueue Frontend Scripts.
 *
 * @since   2.2.4
 */
do_action('sjb_enqueue_scripts');

/**
 * Hook -> sjb_before_main_content
 *
 * @hooked sjb_job_listing_wrapper_start - 10
 * - Output Opening div of Main Container.
 * - Output Opening div of Content Area.
 *
 * @since   2.2.0
 * @since   2.2.3   Removed the content wrapper opening div.
 */
do_action('sjb_before_main_content');
?>

<!-- Start Content Wrapper
================================================== -->
<div class="sjb-page">
    <div class="sjb-detail">
        <div class="list-data">
            <?php
            while ( have_posts() ) : the_post();
                /**
                 * Template -> Content Single Job Listing:
                 *
                 * - Company Meta
                 * - Job Description
                 * - Job Features
                 * - Job Application Form
                 */
                get_simple_job_board_template('content-single-job-listing.php');
            endwhile;
            ?>
        </div>
        <div class="clearfix"></div>
    </div>
</div>
<!-- ==================================================
End Content Wrapper -->

<?php
/**
 * Hook -> sjb_after_main_content
 *
 * @hokoed sjb_job_listing_wrapper_end - 10
 *
 * - Output Closing div of Main Container.
 * - Output Closing div of Content Area.
 *
 * @since   2.2.0
 * @since   2.2.3   Removed the content wrapper closing div
 */
do_action('sjb_after_main_content');

$html_archive = ob_get_clean();

/**
 * Modify the Jobs Archive Page Template.
 *
 * @since   2.3.0
 *
 * @param   html    $html_archive   Jobs Archive Page HTML.
 */
echo apply_filters('sjb_single_template', $html_archive);

get_footer();
</code>```

nieuws.php (my own template, error does not occur):

```<code><?php
    /*
     Template Name: Nieuws-template
    */
?>
<?php get_header(); ?>
<div id="not-front-page" class="content">
    <img src = '<?php bloginfo('template_directory'); ?>/images/nieuwspagina-header.png' class="not-front-page-header" />
    <div class="container">
    <?php if ( have_posts() ) : ?>
        <?php while ( have_posts() ) : the_post(); ?>
            <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                <div class="post-header">
                    <h2><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
                </div><!--.post-header-->
                <div class="entry clear">
                    <?php if ( function_exists( 'add_theme_support' ) ) the_post_thumbnail(); ?>
                    <?php the_content(); ?>
                    <?php edit_post_link(); ?>
                    <?php wp_link_pages(); ?>
                </div><!--. entry-->
            </div><!-- .post-->
        <?php endwhile; /* rewind or continue if all posts have been fetched */ ?>
        <?php else : ?>
    <?php endif; ?>
    </div>
    <?php wp_footer(); // Crucial footer hook! ?>
<?php get_footer('front-page'); ?>
</code>```

答:
As I mentioned above it all seemed to have to do with

```<code>body {
   display: flex
}
</code>```

Once I got rid of this the footer went back underneath. I had to use some workarounds to get my sidebar just right but it seems to be OK for now. Thanks :)

Body:
Just wondered if anyone has ever experienced this, sometimes when viewing a page that i've just edited, the footer (which consists of multiple stacked divs) turns itself into columns and appears at the right of my screen, squashing my page content. Sometimes this happens after I've entered faulty code (for example, a '>' instead of a '<'), which is fair enough, but sometimes I just want to change the format of a featured image in my CSS and it does it then too.

I've tried clearing my cache. This error is consistent and appears every time I run certain code, it's just very random what kind of code creates the error.

Has anyone else experienced this?

EDIT: here is my footer.php code, which has worked perfectly for weeks up until today, would not know what other code would be relevant:

            <?php echo do_shortcode("[insert page='accountmanagers']"); ?>

            <?php echo do_shortcode("[insert page='nieuws-front-page']"); ?>

Over ons

Over Match

Accountmanagers

Vormen van bemiddeling

Kwaliteit

Branches

Certicering

Match holding

Contact

Bedrijven

Arbeidskrachten

Vacature plaatsen

Vormen van bemiddeling

Baan zoeken

Vacatures

Inschrijven

Werken bij Match

Snel aan de slag

Vormen van bemiddeling

CV uploaden

Copyright 2017 - Match | Sitemap | Webdesign One Squad

<?php wp_footer(); ?>

single-jobpost.php (plugin template, error occurs):

<?php
/**
 * The Template for displaying job details
 *
 * Override this template by copying it to yourtheme/simple_job_board/single-jobpost.php
 *
 * @author      PressTigers
 * @package     Simple_Job_Board
 * @subpackage  Simple_Job_Board/Templates
 * @version     1.1.0
 * @since       2.2.0
 * @since       2.2.3   Enqueued Front Styles & Revised the HTML structure.
 * @since       2.2.4   Enqueued Front end Scripts.
 * @since       2.3.0   Added "sjb_archive_template" filter.
 */
get_header();

ob_start();
global $post;

/**
 * Enqueue Frontend Scripts.
 *
 * @since   2.2.4
 */
do_action('sjb_enqueue_scripts');

/**
 * Hook -> sjb_before_main_content
 *
 * @hooked sjb_job_listing_wrapper_start - 10
 * - Output Opening div of Main Container.
 * - Output Opening div of Content Area.
 *
 * @since   2.2.0
 * @since   2.2.3   Removed the content wrapper opening div.
 */
do_action('sjb_before_main_content');
?>

            <?php
            while ( have_posts() ) : the_post();
                /**
                 * Template -> Content Single Job Listing:
                 *
                 * - Company Meta
                 * - Job Description
                 * - Job Features
                 * - Job Application Form
                 */
                get_simple_job_board_template('content-single-job-listing.php');
            endwhile;
            ?>

<?php
/**
 * Hook -> sjb_after_main_content
 *
 * @hokoed sjb_job_listing_wrapper_end - 10
 *
 * - Output Closing div of Main Container.
 * - Output Closing div of Content Area.
 *
 * @since   2.2.0
 * @since   2.2.3   Removed the content wrapper closing div
 */
do_action('sjb_after_main_content');

$html_archive = ob_get_clean();

/**
 * Modify the Jobs Archive Page Template.
 *
 * @since   2.3.0
 *
 * @param   html    $html_archive   Jobs Archive Page HTML.
 */
echo apply_filters('sjb_single_template', $html_archive);

get_footer();

nieuws.php (my own template, error does not occur):

<?php
    /*
     Template Name: Nieuws-template
    */
?>
<?php get_header(); ?>

    <img src = '<?php bloginfo('template_directory'); ?>/images/nieuwspagina-header.png' class="not-front-page-header" />

    <?php if ( have_posts() ) : ?>
        <?php while ( have_posts() ) : the_post(); ?>
            <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

<a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>

                    <?php if ( function_exists( 'add_theme_support' ) ) the_post_thumbnail(); ?>
                    <?php the_content(); ?>
                    <?php edit_post_link(); ?>
                    <?php wp_link_pages(); ?>

        <?php endwhile; /* rewind or continue if all posts have been fetched */ ?>
        <?php else : ?>
    <?php endif; ?>

    <?php wp_footer(); // Crucial footer hook! ?>
<?php get_footer('front-page'); ?>

Body:
As I mentioned above it all seemed to have to do with

body {
   display: flex
}

Once I got rid of this the footer went back underneath. I had to use some workarounds to get my sidebar just right but it seems to be OK for now. Thanks :)


问:
How to put titles for each field of a ListView item in Android
I have a Listview with a custom adapter , which displays person's data like

Barak Obama 2008

But I want to put a header with Name Surname Date but properly alligned

A draft example:

ListView Items with titles

How Can I achieve this?

thank you

答:
You can use TableLayout to show your Data as your requirement. I've replicated your demand. Here are the codes.

1) MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView lstview=(ListView)findViewById(R.id.listView);
    // Inflate header view
    ViewGroup headerView = (ViewGroup)getLayoutInflater().inflate(R.layout.header_layout, lstview,false);
    // Add header view to the ListView
    lstview.addHeaderView(headerView);
    // Get the string array defined in strings.xml file
    String[] date = {"29-03-17", "29-03-17"};
    String[] amount = {"5", "2"};
    String[] dept = {"14", "4"};
    // Create an adapter to bind data to the ListView
    CustomListViewAdapter adapter=new CustomListViewAdapter(this,R.layout.row_listview, R.id.tvDate, date, amount, dept);
    // Bind data to the ListView
    lstview.setAdapter(adapter);
}
</code>```

2) CustomListViewAdapter.java

```<code>    public class CustomListViewAdapter extends ArrayAdapter<String> {
    int groupid;
    String[] date;
    String[] amount;
    String[] dept;
    ArrayList<String> desc;
    Context context;
    public CustomListViewAdapter(Context context, int vg, int id, String[] date, String[] amount, String[] dept){
        super(context,vg, id, date);
        this.context=context;
        groupid=vg;
        this.date=date;
        this.amount=amount;
        this.dept=dept;

    }
    // Hold views of the ListView to improve its scrolling performance
    static class ViewHolder {
        public TextView tvDate;
        public TextView tvAmount;
        public TextView tvDept;

    }

    public View getView(int position, View convertView, ViewGroup parent) {

        View rowView = convertView;
        // Inflate the rowlayout.xml file if convertView is null
        if(rowView==null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            rowView= inflater.inflate(groupid, parent, false);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.tvDate= (TextView) rowView.findViewById(R.id.tvDate);
            viewHolder.tvAmount= (TextView) rowView.findViewById(R.id.tvAmount);
            viewHolder.tvDept= (TextView) rowView.findViewById(R.id.tvDept);
            rowView.setTag(viewHolder);

        }
        // Set text to each TextView of ListView item
        ViewHolder holder = (ViewHolder) rowView.getTag();
        holder.tvDate.setText(date[position]);
        holder.tvAmount.setText(amount[position]);
        holder.tvDept.setText(dept[position]);

        return rowView;
    }

}
</code>```

3) HeaderLayout (header_layout.xml)

```<code>    <?xml version="1.0" encoding="utf-8"?>

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:stretchColumns="*"
     >
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        >
        <TextView
            android:id="@+id/tvDate"
            android:layout_column="0"
            android:padding="10sp"
            android:gravity="left"
            android:layout_span="1"
            android:text="Date"
            android:layout_gravity="center">
        </TextView>
        <TextView
            android:id="@+id/tvAmount"
            android:layout_column="1"
            android:padding="10sp"
            android:gravity="left"
            android:layout_span="1"
            android:text="Amount"
            android:layout_gravity="center">
        </TextView>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvDept"
            android:layout_column="2"
            android:layout_span="1"
            android:text="Dept"
            android:layout_gravity="center" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvDelete"
            android:layout_column="3"
            android:layout_span="1"
            android:text="Delete"
            android:layout_gravity="center" />
    </TableRow>

</TableLayout>
</code>```

4) RowLayout for each ListView row (row_listview.xml)

```<code>        <?xml version="1.0" encoding="utf-8"?>
        <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:stretchColumns="*">

        <TableRow
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvDate"
            android:layout_column="0"
            android:padding="10sp"
            android:gravity="left"
            android:layout_span="1"
            android:text="Date"
            android:layout_gravity="center">
        </TextView>
        <TextView
            android:id="@+id/tvAmount"
            android:layout_column="1"
            android:padding="10sp"
            android:gravity="left"
            android:layout_span="1"
            android:text="Amount"
            android:layout_gravity="center">
        </TextView>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvDept"
            android:layout_column="2"
            android:layout_span="1"
            android:text="Dept"
            android:layout_gravity="center" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageButton"
            android:layout_column="3"
            android:layout_span="1"
            android:src="@android:drawable/ic_delete" />

          </TableRow>

         </TableLayout>
</code>```

5) Output:

Hope this helps.

Body:
You can use TableLayout to show your Data as your requirement. I've replicated your demand. Here are the codes.

1) MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView lstview=(ListView)findViewById(R.id.listView);
    // Inflate header view
    ViewGroup headerView = (ViewGroup)getLayoutInflater().inflate(R.layout.header_layout, lstview,false);
    // Add header view to the ListView
    lstview.addHeaderView(headerView);
    // Get the string array defined in strings.xml file
    String[] date = {"29-03-17", "29-03-17"};
    String[] amount = {"5", "2"};
    String[] dept = {"14", "4"};
    // Create an adapter to bind data to the ListView
    CustomListViewAdapter adapter=new CustomListViewAdapter(this,R.layout.row_listview, R.id.tvDate, date, amount, dept);
    // Bind data to the ListView
    lstview.setAdapter(adapter);
}

2) CustomListViewAdapter.java

    public class CustomListViewAdapter extends ArrayAdapter<String> {
    int groupid;
    String[] date;
    String[] amount;
    String[] dept;
    ArrayList<String> desc;
    Context context;
    public CustomListViewAdapter(Context context, int vg, int id, String[] date, String[] amount, String[] dept){
        super(context,vg, id, date);
        this.context=context;
        groupid=vg;
        this.date=date;
        this.amount=amount;
        this.dept=dept;

    }
    // Hold views of the ListView to improve its scrolling performance
    static class ViewHolder {
        public TextView tvDate;
        public TextView tvAmount;
        public TextView tvDept;

    }

    public View getView(int position, View convertView, ViewGroup parent) {

        View rowView = convertView;
        // Inflate the rowlayout.xml file if convertView is null
        if(rowView==null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            rowView= inflater.inflate(groupid, parent, false);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.tvDate= (TextView) rowView.findViewById(R.id.tvDate);
            viewHolder.tvAmount= (TextView) rowView.findViewById(R.id.tvAmount);
            viewHolder.tvDept= (TextView) rowView.findViewById(R.id.tvDept);
            rowView.setTag(viewHolder);

        }
        // Set text to each TextView of ListView item
        ViewHolder holder = (ViewHolder) rowView.getTag();
        holder.tvDate.setText(date[position]);
        holder.tvAmount.setText(amount[position]);
        holder.tvDept.setText(dept[position]);

        return rowView;
    }

}

3) HeaderLayout (header_layout.xml)

    <?xml version="1.0" encoding="utf-8"?>

    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:stretchColumns="*"
     >
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        >
        <TextView
            android:id="@+id/tvDate"
            android:layout_column="0"
            android:padding="10sp"
            android:gravity="left"
            android:layout_span="1"
            android:text="Date"
            android:layout_gravity="center">
        </TextView>
        <TextView
            android:id="@+id/tvAmount"
            android:layout_column="1"
            android:padding="10sp"
            android:gravity="left"
            android:layout_span="1"
            android:text="Amount"
            android:layout_gravity="center">
        </TextView>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvDept"
            android:layout_column="2"
            android:layout_span="1"
            android:text="Dept"
            android:layout_gravity="center" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvDelete"
            android:layout_column="3"
            android:layout_span="1"
            android:text="Delete"
            android:layout_gravity="center" />
    </TableRow>

</TableLayout>

4) RowLayout for each ListView row (row_listview.xml)

        <?xml version="1.0" encoding="utf-8"?>
        <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:stretchColumns="*">

        <TableRow
           android:layout_width="match_parent"
           android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvDate"
            android:layout_column="0"
            android:padding="10sp"
            android:gravity="left"
            android:layout_span="1"
            android:text="Date"
            android:layout_gravity="center">
        </TextView>
        <TextView
            android:id="@+id/tvAmount"
            android:layout_column="1"
            android:padding="10sp"
            android:gravity="left"
            android:layout_span="1"
            android:text="Amount"
            android:layout_gravity="center">
        </TextView>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvDept"
            android:layout_column="2"
            android:layout_span="1"
            android:text="Dept"
            android:layout_gravity="center" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageButton"
            android:layout_column="3"
            android:layout_span="1"
            android:src="@android:drawable/ic_delete" />

          </TableRow>

         </TableLayout>

5) Output:

Hope this helps.


问:
What does SET FOREIGN_KEY_CHECKS=0; do
what does SET FOREIGN_KEY_CHECKS=0; do. Because when I was in sqlite I have used this command. Now when Ichanged my database to sqlite all my employee id which has many references in table is set to manual employee code.

```<code>Employee Id: 4606

Manual employee code: 10002
</code>```

So value in Salaryslip table must be 4606 for employee id but now its 10002

答:
It is session-based, when set the way you did in your question.

https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html

According to this, FOREIGN_KEY_CHECKS is "Both" for scope. This means it can be set for session:

SET FOREIGN_KEY_CHECKS=0;

or globally:

SET GLOBAL FOREIGN_KEY_CHECKS=0;

Title: What does SET FOREIGN_KEY_CHECKS=0; do

Body:
what does SET FOREIGN_KEY_CHECKS=0; do. Because when I was in sqlite I have used this command. Now when Ichanged my database to sqlite all my employee id which has many references in table is set to manual employee code.

Employee Id: 4606

Manual employee code: 10002

So value in Salaryslip table must be 4606 for employee id but now its 10002


问:
Datepickerdialog don't open when its empty
In the app the fields are not open by click when its empty. Its possible if the field is already filled for intance with 23-03-2017. The code give no error. Tested on different API levels. Who can help me?</p>

```<code>                break;
            case InstrumentItem.S_FREEDATE:
            case InstrumentItem.S_BUYDATE:
            case InstrumentItem.S_CERTDATE:
            case InstrumentItem.S_EXPDATE:
                holder.valueLabel.setFocusable(false);
                holder.valueLabel.setOnClickListener(view ->  {
                    try {
                        showDatePickerDialog(holder.valueLabel.getText().toString(), (datePicker, year, month, day) -> {
                            String dateInFormat = getDateInFormat(year, month, day);
                            holder.valueLabel.setText(dateInFormat);
                            mItems.get(position).value = dateInFormat;

                        }).show();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                });
                break;
</code>```

答:
The reason why it was not working, there was no date. I fixed it with the option to pick the device date (current date), the DatePickerdialog opens.</p>

```<code>                        try {
                            String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
                            holder.valueLabel.setText(date);
                            mItems.get(position).value = date;
</code>```

Body:
In the app the fields are not open by click when its empty. Its possible if the field is already filled for intance with 23-03-2017. The code give no error. Tested on different API levels. Who can help me?

                break;
            case InstrumentItem.S_FREEDATE:
            case InstrumentItem.S_BUYDATE:
            case InstrumentItem.S_CERTDATE:
            case InstrumentItem.S_EXPDATE:
                holder.valueLabel.setFocusable(false);
                holder.valueLabel.setOnClickListener(view ->  {
                    try {
                        showDatePickerDialog(holder.valueLabel.getText().toString(), (datePicker, year, month, day) -> {
                            String dateInFormat = getDateInFormat(year, month, day);
                            holder.valueLabel.setText(dateInFormat);
                            mItems.get(position).value = dateInFormat;

                        }).show();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                });
                break;

Body:
The reason why it was not working, there was no date. I fixed it with the option to pick the device date (current date), the DatePickerdialog opens.

                        try {
                            String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
                            holder.valueLabel.setText(date);
                            mItems.get(position).value = date;


问:
Method that returns new object of anonymous class
Let say that I have interface I1 like this:

```<code>interface I1 {
   public void setNumber(int num);
}
</code>```

I want to create let say public class named MyClass that will include method getI1 that will return new object of anonymous class that implements interface I1.

答:
how about this?

```<code>public I1 getI1() {
  return new I1() {
    public void setNumber(int num) {
      //do something
    }
  };
}
</code>```

alternativaly you could use instead of new I1() any class which implements I1

here's an example which uses the interface Runnable and the class Thread, which implements Runnable

```<code>public static void main(String[] args) {
  System.out.println("main > start");

  System.out.println("main > r = getRunnable()");
  Runnable r = getRunnable();

  System.out.println("main > r.run()");
  r.run();
  System.out.println("main > Stop");
}

public static Runnable getRunnable() {
  return new Thread() {
    public void run() {
      System.out.println("run > Start");
      //do something
      System.out.println("run > Stop");
    }
  };
}
</code>```

output is

```<code>main > start
main > r = getRunnable()
main > r.run()
run > Start
run > Stop
main > Stop
</code>```

Body:
Let say that I have interface I1 like this:

interface I1 {
   public void setNumber(int num);
}

I want to create let say public class named MyClass that will include method getI1 that will return new object of anonymous class that implements interface I1.

Body:
how about this?

public I1 getI1() {
  return new I1() {
    public void setNumber(int num) {
      //do something
    }
  };
}

alternativaly you could use instead of new I1() any class which implements I1

here's an example which uses the interface Runnable and the class Thread, which implements Runnable

public static void main(String[] args) {
  System.out.println("main > start");

  System.out.println("main > r = getRunnable()");
  Runnable r = getRunnable();

  System.out.println("main > r.run()");
  r.run();
  System.out.println("main > Stop");
}

public static Runnable getRunnable() {
  return new Thread() {
    public void run() {
      System.out.println("run > Start");
      //do something
      System.out.println("run > Stop");
    }
  };
}

output is

main > start
main > r = getRunnable()
main > r.run()
run > Start
run > Stop
main > Stop