问:
How to convert *.RESX XML file to JSON file in C#
How can I convert *.RESX XML file to JSON file in C#?

I have regular RESX file. For example:

```<code><?xml version="1.0" encoding="utf-8"?>
<root>
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
    <data xml:space="preserve" name="KEY_1">
        <value>Text A</value>
    </data>
    <data xml:space="preserve" name="KEY_2">
        <value>Text B</value>
    </data>
</root>
</code>```

I need to convert this file to JSON file:

```<code>{
  "Texts": [
    {
      "id": "KEY_1",
      "text": "Text A"
    },
    {
      "id": "KEY_2",
      "text": "Text B"
    }
  ]
}
</code>```

As you can see for conversion is relevant only part with data:

```<code>    <data xml:space="preserve" name="KEY_1">
        <value>Text A</value>
    </data>
    <data xml:space="preserve" name="KEY_2">
        <value>Text B</value>
    </data>
</code>```

Everything else is irrelevant for transformation.

Name in data attribute XML => is id in JSON file.

Value in XML=> is text in JSON file.

EDIT:
I have solution, but I think that it can be done better

```<code>using System.Xml;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace XMLtoJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            // To convert an XML node contained in string xml into a JSON string
            var xml = File.ReadAllText(@"C:\Test\ClientLocalization.en-US.resx");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            XmlNodeList node = doc.GetElementsByTagName("data");
            foreach (XmlNode item in node)
            {
                var value = item.InnerText.Trim();
                var keyName = item.Attributes.Cast<XmlAttribute>().FirstOrDefault(f => f.Name == "name");
                if (keyName != null)
                {
                    var key = keyName.InnerText.Trim();
                    result.Add(key, value);
                }
            }

            string res = @"{ ""Text"" : [ ";
            foreach (var item in result)
            {
                res += "{";
                res += $" \"id\":\"{item.Key}\",\"text\":\"{item.Value}\"";
                res += "},";
            }
            res = res.Remove(res.Length - 1);
            res += @" ]} ";
        }

    }
}
</code>```

答:
Instead of using XmlDocument, I would use XElement as it is much more LINQ-friendly.  Use XElement.Parse to load the XML, then select the nodes you are interested in and shape them into an anonymous object structure that mirrors the JSON you want.  Finally, use your favorite JSON serializer (such as Json.Net or JavaScriptSerializer) to create the JSON from there.  I don't recommend hand-rolling your own JSON, as it is very error prone.

```<code>using Newtonsoft.Json;

var xml = File.ReadAllText(@"C:\Test\ClientLocalization.en-US.resx");

var obj = new
{
    Texts = XElement.Parse(xml)
        .Elements("data")
        .Select(el => new
        {
            id = el.Attribute("name").Value,
            text = el.Element("value").Value.Trim()
        })
        .ToList()
};

string json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);

// OR:
//JavaScriptSerializer jss = new JavaScriptSerializer();
//string json = jss.Serialize(obj);

Console.WriteLine(json);
</code>```

Fiddle: https://dotnetfiddle.net/ZIaCjd

Body:
How can I convert *.RESX XML file to JSON file in C#?

I have regular RESX file. For example:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
    <data xml:space="preserve" name="KEY_1">
        <value>Text A</value>
    </data>
    <data xml:space="preserve" name="KEY_2">
        <value>Text B</value>
    </data>
</root>

I need to convert this file to JSON file:

{
  "Texts": [
    {
      "id": "KEY_1",
      "text": "Text A"
    },
    {
      "id": "KEY_2",
      "text": "Text B"
    }
  ]
}

As you can see for conversion is relevant only part with data:

    <data xml:space="preserve" name="KEY_1">
        <value>Text A</value>
    </data>
    <data xml:space="preserve" name="KEY_2">
        <value>Text B</value>
    </data>

Everything else is irrelevant for transformation.

Name in data attribute XML => is id in JSON file.

Value in XML=> is text in JSON file.

EDIT:
I have solution, but I think that it can be done better

using System.Xml;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace XMLtoJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            // To convert an XML node contained in string xml into a JSON string
            var xml = File.ReadAllText(@"C:\Test\ClientLocalization.en-US.resx");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            XmlNodeList node = doc.GetElementsByTagName("data");
            foreach (XmlNode item in node)
            {
                var value = item.InnerText.Trim();
                var keyName = item.Attributes.Cast<XmlAttribute>().FirstOrDefault(f => f.Name == "name");
                if (keyName != null)
                {
                    var key = keyName.InnerText.Trim();
                    result.Add(key, value);
                }
            }

            string res = @"{ ""Text"" : [ ";
            foreach (var item in result)
            {
                res += "{";
                res += $" \"id\":\"{item.Key}\",\"text\":\"{item.Value}\"";
                res += "},";
            }
            res = res.Remove(res.Length - 1);
            res += @" ]} ";
        }

    }
}

Body:
Instead of using XmlDocument, I would use XElement as it is much more LINQ-friendly.  Use XElement.Parse to load the XML, then select the nodes you are interested in and shape them into an anonymous object structure that mirrors the JSON you want.  Finally, use your favorite JSON serializer (such as Json.Net or JavaScriptSerializer) to create the JSON from there.  I don't recommend hand-rolling your own JSON, as it is very error prone.

using Newtonsoft.Json;

var xml = File.ReadAllText(@"C:\Test\ClientLocalization.en-US.resx");

var obj = new
{
    Texts = XElement.Parse(xml)
        .Elements("data")
        .Select(el => new
        {
            id = el.Attribute("name").Value,
            text = el.Element("value").Value.Trim()
        })
        .ToList()
};

string json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);

// OR:
//JavaScriptSerializer jss = new JavaScriptSerializer();
//string json = jss.Serialize(obj);

Console.WriteLine(json);

Fiddle: https://dotnetfiddle.net/ZIaCjd


来源: stackexchange

问:
Python CSV files: Printing all a user's details
I am writing a piece of code wherein my user does a quiz and all that information is stored in a CSV file. I then, in another program, have the user input a username and, if it matches, it will print the scores etc for that user. However, I had the same user do the quiz again and, instead of printing all the quizzes and scores that user did, it just prints the latest one.

To show:
My CSV file looks like this

Ser15 A Sci-Med

Ser15 C Sci-Med

These are the rows. I want my program to print all the quizzes and grades 'Ser15' had, but it just prints the lastest.
How do I make my program print all of them? Here is my code below...

```<code>     def Report1():
        found=False
        UserFind=input("Please enter a username")
        with open("Report.csv","r") as c:
            for row in c:
                details=row.split(",")
                if UserFind in details[0]:
                    found=True
                else:
                  pass
            if found==True:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
            else:
                print("User doesn't exist or wrong details...")
</code>```

This is my result:

```<code>Please enter a choice: 3
Please enter a usernameSer15
Ser15
C
Sci-Med

These are your user's details!
</code>```

As you can see it prints their latest information, not all of them...

This is part of my project so any help is much appreciated!

答:
```<code>def Report1():
    found=False
    UserFind=input("Please enter a username")
    with open("Report.csv","r") as c:
        for row in c:
            details=row.split(",")
            if UserFind in details[0]:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
                found= True
        if not found:
            print("User doesn't exist or wrong details...")
</code>```

Thank you to Accumulation!

ContentLicense: CC BY-SA 3.0

Body:
I am writing a piece of code wherein my user does a quiz and all that information is stored in a CSV file. I then, in another program, have the user input a username and, if it matches, it will print the scores etc for that user. However, I had the same user do the quiz again and, instead of printing all the quizzes and scores that user did, it just prints the latest one.

To show:
My CSV file looks like this

Ser15 A Sci-Med

Ser15 C Sci-Med

These are the rows. I want my program to print all the quizzes and grades 'Ser15' had, but it just prints the lastest.
How do I make my program print all of them? Here is my code below...

     def Report1():
        found=False
        UserFind=input("Please enter a username")
        with open("Report.csv","r") as c:
            for row in c:
                details=row.split(",")
                if UserFind in details[0]:
                    found=True
                else:
                  pass
            if found==True:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
            else:
                print("User doesn't exist or wrong details...")

This is my result:

Please enter a choice: 3
Please enter a usernameSer15
Ser15
C
Sci-Med

These are your user's details!

As you can see it prints their latest information, not all of them...

This is part of my project so any help is much appreciated!

Body:
def Report1():
    found=False
    UserFind=input("Please enter a username")
    with open("Report.csv","r") as c:
        for row in c:
            details=row.split(",")
            if UserFind in details[0]:
                print(details[0])
                print(details[1])
                print(details[2])
                print("These are your user's details!")
                found= True
        if not found:
            print("User doesn't exist or wrong details...")

Thank you to Accumulation!


问:
Remove space and Uppercase first letter

I made this program which shall turn around sentences like:
User Input: Hello i´m hungry. Where is the fridge.
System Output: Hungry i´m Hello. Fridge the is Where.

But there is space between the last word and "." in the reversed sentence. How can i remove? And how can i make the first word a uppercase word?

```<code>    package etzale;

public class etzale {

    public static void main(String[] args) {

        StringBuilder outputString= new StringBuilder();

        String satz;

        System.out.print("Bitte geben Sie einen String ein: ");
        String text="Hallo mir gehts gut. Wie gehts dir. mir gehts spitze.";

        while(text.indexOf(".")>=0){

            satz=text.substring(0, text.indexOf("."));
            text=text.substring(text.indexOf(".")+1);

            String []s= satz.split(" ");
            for(int i=s.length-1; i>=0; i--){

               outputString.append(s[i]);

               if(s[0]==" ");

               outputString.append(" ");

               }

          outputString.append(".");
          outputString.append(" ");

        }
        System.out.print(outputString);
}
}
</code>```

How can i erase the space between the last word and "." in each sentence?

```<code>Actual Input: Mit gehts gut. Wie gehts dir. Mir gehts spitze.
Actual Output: gut gehts mir  . dir gehts Wie  . spitze gehts Mir  .
</code>```

答:
I already answer another you almost similar question: Reverse all words, set "." and do the same for the next sentences, my solution covered this case also try it:</p>

```<code>import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) {
        final String userInput = "Hello i´m hungry. Where is the fridge.";
        final String expectedResult = "Hungry i´m Hello. Fridge the is Where.";
        String[] sentences = userInput.split("\\. ");
        String reversedSentences = Stream.of(sentences)
                .map(sentenceString -> new Sentence(sentenceString))
                .map(Sentence::reverse)
                .map(Sentence::firstLetterToUpperCase)
                .map(Sentence::removeAllDots)
                .map(Sentence::dotInTheEnd)
                .map(Sentence::toString)
                .collect(Collectors.joining(" "));
        System.out.println(reversedSentences.equals(expectedResult)); //returns true
    }

}

final class Sentence {
    private final String sentence;

    Sentence(String sentence) {
        this.sentence = sentence;
    }

    Sentence reverse() {
        String[] words = sentence.split(" ");
        Collections.reverse(Arrays.asList(words));
        return new Sentence(String.join(" ", words));
    }

    Sentence firstLetterToUpperCase() {
        String firstLetter = sentence.substring(0, 1);
        String anotherPart = sentence.substring(1);
        return new Sentence(firstLetter.toUpperCase() + anotherPart);
    }

    Sentence dotInTheEnd() {
        return new Sentence(sentence + ".");
    }

    Sentence removeAllDots() {
        return new Sentence(sentence.replaceAll("\\.", ""));
    }

    public String toString() {
        return sentence;
    }
}
</code>```

Title: Remove space and Uppercase first letter

Body:
I made this program which shall turn around sentences like:
User Input: Hello i´m hungry. Where is the fridge.
System Output: Hungry i´m Hello. Fridge the is Where.

But there is space between the last word and "." in the reversed sentence. How can i remove? And how can i make the first word a uppercase word?

    package etzale;

public class etzale {

    public static void main(String[] args) {

        StringBuilder outputString= new StringBuilder();

        String satz;

        System.out.print("Bitte geben Sie einen String ein: ");
        String text="Hallo mir gehts gut. Wie gehts dir. mir gehts spitze.";

        while(text.indexOf(".")>=0){

            satz=text.substring(0, text.indexOf("."));
            text=text.substring(text.indexOf(".")+1);

            String []s= satz.split(" ");
            for(int i=s.length-1; i>=0; i--){

               outputString.append(s[i]);

               if(s[0]==" ");

               outputString.append(" ");

               }

          outputString.append(".");
          outputString.append(" ");

        }
        System.out.print(outputString);
}
}

How can i erase the space between the last word and "." in each sentence?

Actual Input: Mit gehts gut. Wie gehts dir. Mir gehts spitze.
Actual Output: gut gehts mir  . dir gehts Wie  . spitze gehts Mir  .

Body:
I already answer another you almost similar question: Reverse all words, set "." and do the same for the next sentences, my solution covered this case also try it:

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) {
        final String userInput = "Hello i´m hungry. Where is the fridge.";
        final String expectedResult = "Hungry i´m Hello. Fridge the is Where.";
        String[] sentences = userInput.split("\\. ");
        String reversedSentences = Stream.of(sentences)
                .map(sentenceString -> new Sentence(sentenceString))
                .map(Sentence::reverse)
                .map(Sentence::firstLetterToUpperCase)
                .map(Sentence::removeAllDots)
                .map(Sentence::dotInTheEnd)
                .map(Sentence::toString)
                .collect(Collectors.joining(" "));
        System.out.println(reversedSentences.equals(expectedResult)); //returns true
    }

}

final class Sentence {
    private final String sentence;

    Sentence(String sentence) {
        this.sentence = sentence;
    }

    Sentence reverse() {
        String[] words = sentence.split(" ");
        Collections.reverse(Arrays.asList(words));
        return new Sentence(String.join(" ", words));
    }

    Sentence firstLetterToUpperCase() {
        String firstLetter = sentence.substring(0, 1);
        String anotherPart = sentence.substring(1);
        return new Sentence(firstLetter.toUpperCase() + anotherPart);
    }

    Sentence dotInTheEnd() {
        return new Sentence(sentence + ".");
    }

    Sentence removeAllDots() {
        return new Sentence(sentence.replaceAll("\\.", ""));
    }

    public String toString() {
        return sentence;
    }
}


问:
why adding a new id column with monotonically increasing id break after 352
I am using pyspark 2.2.0. To add a new column of incrementing value.  I have used following code:

```<code>new_df = df.withColumn('Id', monotonically_increasing_id())
</code>```

But it breaks after row number 352 like this:

Any option to fix this ?

答: As mentioned in spark documentation, monotonically_increasing_id may not be consecutive. You can convert dataframe to rdd and use rdd.zipWithIndex() instead for adding incremental value.

Body:
I am using pyspark 2.2.0. To add a new column of incrementing value.  I have used following code:

new_df = df.withColumn('Id', monotonically_increasing_id())

But it breaks after row number 352 like this:

Any option to fix this ?


问:
GetPixel,SetPixel and DrawImage does not work well for me
I was trying to create simple program that would perform some trivial operation with given image.
For some reason, it works only for the first time (when the app is launched):

//pseudo code

```<code>Bitmap im=Bitmap.FromFile("D:\\x.BMP");
Color [,] ColorArray=new [im.Width,im.Height];
private override voide OnPaint(EventArgs e)
{

  for(int X=0;X<im.Width;X++)
  {
      for(int Y=0;Y<im.Height;Y++)
      {
        ColorArray[X,Y]=im.GetPixel[X,Y];
      }

  }
  for(int X=0;X<im.Width;X++)
  {
      for(int Y=0;Y<im.Height;Y++)
      {
        Color c=ColorArray[X,Y];
        ...
        //some code that adds 100 to R,G,B
        im.SetPixel(X,Y,c);
      }

  }

  e.Graphics.DrawImage(im);
}
</code>```

答:
[EDIT]

I have modified my sample code.  With the previous version, it could be hard to see the difference from one iteration to the next (especially with the bmp I was using for testing).  This one allows you to change color gradually by pressing 1, 2, or 3 on the Num Pad.  As others have mentioned, SetPixel/GetPixel is slow, so each KeyUp event does take some time to run.

This works fine for me.

Create a new Windows Forms project.  Drop this code in.  Make sure you have "x.bmp" available.  Each time you press 1, 2, or 3 on the number pad (you might need turn on Num Lock), the colors of the bitmap change slightly:

```<code>  public partial class Form1 : Form
  {
    Bitmap bm;
    Color [,] colors;

    public Form1()
    {
      bm = (Bitmap)Bitmap.FromFile("x.bmp");
      colors = new Color[bm.Width, bm.Height];

      InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
      e.Graphics.DrawImage(bm,new Point(0,0));
    }

    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
      //Change the colors a little bit on each KeyUp.
      //On NumPad1, change red.
      //On NumPad2, change green.
      //On NumPad3, change blue.
      //Mod with 256 to ensure a value between 0 and 255.
      int rInc = 0;
      int gInc = 0;
      int bInc = 0;

      switch (e.KeyCode)
      {
        case Keys.NumPad1:
          rInc = 20;
          break;
        case Keys.NumPad2:
          gInc = 20;
          break;
        case Keys.NumPad3:
          bInc = 20;
          break;
        default:
          break;
      }

      for (int x = 0; x < bm.Width; x++)
      {
        for (int y = 0; y < bm.Height; y++)
        {
          colors[x, y] = bm.GetPixel(x, y);
        }
      }

      for (int x = 0; x < bm.Width; x++)
      {
        for (int y = 0; y < bm.Height; y++)
        {
          Color c = colors[x, y];

          int r = (c.R + rInc) % 256;
          int g = (c.G + gInc) % 256;
          int b = (c.B + bInc) % 256;

          c = Color.FromArgb(255, r, g, b);
          bm.SetPixel(x, y, c);
        }
      }

      Invalidate();
    }

  }
</code>```

It's not very sophisticated, but it does what you asked with real code that closely matches your pseudocode.

ContentLicense: CC BY-SA 2.5

Body:
I was trying to create simple program that would perform some trivial operation with given image.
For some reason, it works only for the first time (when the app is launched):

//pseudo code

Bitmap im=Bitmap.FromFile("D:\\x.BMP");
Color [,] ColorArray=new [im.Width,im.Height];
private override voide OnPaint(EventArgs e)
{

  for(int X=0;X<im.Width;X++)
  {
      for(int Y=0;Y<im.Height;Y++)
      {
        ColorArray[X,Y]=im.GetPixel[X,Y];
      }

  }
  for(int X=0;X<im.Width;X++)
  {
      for(int Y=0;Y<im.Height;Y++)
      {
        Color c=ColorArray[X,Y];
        ...
        //some code that adds 100 to R,G,B
        im.SetPixel(X,Y,c);
      }

  }

  e.Graphics.DrawImage(im);
}

Body:
[EDIT]

I have modified my sample code.  With the previous version, it could be hard to see the difference from one iteration to the next (especially with the bmp I was using for testing).  This one allows you to change color gradually by pressing 1, 2, or 3 on the Num Pad.  As others have mentioned, SetPixel/GetPixel is slow, so each KeyUp event does take some time to run.

This works fine for me.

Create a new Windows Forms project.  Drop this code in.  Make sure you have "x.bmp" available.  Each time you press 1, 2, or 3 on the number pad (you might need turn on Num Lock), the colors of the bitmap change slightly:

  public partial class Form1 : Form
  {
    Bitmap bm;
    Color [,] colors;

    public Form1()
    {
      bm = (Bitmap)Bitmap.FromFile("x.bmp");
      colors = new Color[bm.Width, bm.Height];

      InitializeComponent();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
      e.Graphics.DrawImage(bm,new Point(0,0));
    }

    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
      //Change the colors a little bit on each KeyUp.
      //On NumPad1, change red.
      //On NumPad2, change green.
      //On NumPad3, change blue.
      //Mod with 256 to ensure a value between 0 and 255.
      int rInc = 0;
      int gInc = 0;
      int bInc = 0;

      switch (e.KeyCode)
      {
        case Keys.NumPad1:
          rInc = 20;
          break;
        case Keys.NumPad2:
          gInc = 20;
          break;
        case Keys.NumPad3:
          bInc = 20;
          break;
        default:
          break;
      }

      for (int x = 0; x < bm.Width; x++)
      {
        for (int y = 0; y < bm.Height; y++)
        {
          colors[x, y] = bm.GetPixel(x, y);
        }
      }

      for (int x = 0; x < bm.Width; x++)
      {
        for (int y = 0; y < bm.Height; y++)
        {
          Color c = colors[x, y];

          int r = (c.R + rInc) % 256;
          int g = (c.G + gInc) % 256;
          int b = (c.B + bInc) % 256;

          c = Color.FromArgb(255, r, g, b);
          bm.SetPixel(x, y, c);
        }
      }

      Invalidate();
    }

  }

It's not very sophisticated, but it does what you asked with real code that closely matches your pseudocode.


问:
Mysql Joining data from 3 tables
I can't seem to figure out what join I need to do. I have 3 tables which have all the information. I've map out the steps but I'm unsure what to do now, I need to display all the books listed from a specific author.

There is 3 tables I need to use

Author - which contains author_code, fname & lname.

Book - which contains book_code, title, publisher_code, type, price and paperback

Wrote - which contains book_code, author_number and sequence

Here's the code so far, really I know I should use author name but i can't figure it out.

```<code>SELECT BOOK_CODE
FROM WROTE
WHERE AUTHOR_NUM = 20
LEFT JOIN AUTHOR
ON WROTE.AUTHOR_NUM = AUTHOR.AUTHOR_NUM;
</code>```

答:
```<code>SELECT Book.book_code
FROM Book
LEFT JOIN WROTE ON WROTE.book_code = Book.book_code
LEFT JOIN AUTHOR ON AUTHOR.author_code = WROTE.author_number
WHERE AUTHOR.author_code IN (123,456)
</code>```

Title: Mysql Joining data from 3 tables

Body:
I can't seem to figure out what join I need to do. I have 3 tables which have all the information. I've map out the steps but I'm unsure what to do now, I need to display all the books listed from a specific author.

There is 3 tables I need to use

Author - which contains author_code, fname & lname.

Book - which contains book_code, title, publisher_code, type, price and paperback

Wrote - which contains book_code, author_number and sequence

Here's the code so far, really I know I should use author name but i can't figure it out.

SELECT BOOK_CODE
FROM WROTE
WHERE AUTHOR_NUM = 20
LEFT JOIN AUTHOR
ON WROTE.AUTHOR_NUM = AUTHOR.AUTHOR_NUM;


问:
How to recover deleted files that were deleted during merging

I was trying to delete all the migration files on the master branch.  Git prompted:

```<code>error: Merging is not possible because you have unmerged files.
hint: Fix them up in the work tree, and then use 'git add/rm <file>'
hint: as appropriate to mark resolution and make a commit.
fatal: Exiting because of an unresolved conflict.
</code>```

since I did not need the migration files, I typed:

```<code>git rm . -r
</code>```

Git prompted:

```<code>error: the following files have changes staged in the index:
/middleware.py
project_management/models.py
sales/migrations/0001_initial.py
</code>```

(use --cached to keep the file, or -f to force removal)

Thinking that the conflicts are just due to those migration files, I typed:

```<code>git rm . -r -f
</code>```

Now, git has removed ALL my files, including models, templates, views, static files, etc.

```<code>rm '.gitignore'
rm 'accounts/__init__.py'
rm 'accounts/__pycache__/__init__.cpython-36.pyc'
rm 'accounts/__pycache__/backends.cpython-36.pyc'
rm 'accounts/admin.py'
rm 'accounts/apps.py'
rm 'accounts/backends.py'
rm 'accounts/forms/__init__.py'
rm 'accounts/forms/authenticate.py'
rm 'accounts/forms/register.py'
rm 'accounts/migrations/0001_initial.py'
rm 'accounts/migrations/__init__.py'
rm 'accounts/models.py'
rm 'accounts/templates/login.html'
rm 'accounts/templates/signup.html'
rm 'accounts/tests.py'
rm 'accounts/urls.py'
rm 'accounts/views.py'
</code>```

Now, when I do

```<code>git status
</code>```

It tells me this:
    On branch master
All conflicts fixed but you are still merging.
  (use "git commit" to conclude merge)

Changes to be committed:

```<code>    deleted:    .gitignore
    deleted:    accounts/__init__.py
    deleted:    accounts/__pycache__/__init__.cpython-36.pyc
    deleted:    accounts/__pycache__/backends.cpython-36.pyc
    deleted:    accounts/admin.py
    deleted:    accounts/apps.py
    deleted:    accounts/backends.py
    deleted:    accounts/forms/__init__.py
    deleted:    accounts/forms/authenticate.py
    deleted:    accounts/forms/register.py
    deleted:    accounts/migrations/0001_initial.py
    deleted:    accounts/migrations/0002_auto_20170212_1028.py
    deleted:    accounts/migrations/__init__.py
    deleted:    accounts/models.py
    deleted:    accounts/templates/login.html
    deleted:    accounts/templates/signup.html
    deleted:    accounts/tests.py
    deleted:    accounts/urls.py
    deleted:    accounts/views.py
    ...
    Untracked files:
    (use "git add <file>..." to include in what will be committed)

    accounts/
    commonapp/
</code>```

There are more than 10 apps, with more than 50 models, etc. but for the sake simplicity, I have not list them all here.

Is there a way to undo these deletions?  This is months worth of my time, so I really appreciate your help.

答: git reset --hard will recover the files for you. It will also remove all changes that are staged. So if you've anything you want to keep, copy those files out before the reset.

Body:
I was trying to delete all the migration files on the master branch.  Git prompted:

error: Merging is not possible because you have unmerged files.
hint: Fix them up in the work tree, and then use 'git add/rm <file>'
hint: as appropriate to mark resolution and make a commit.
fatal: Exiting because of an unresolved conflict.

since I did not need the migration files, I typed:

git rm . -r

Git prompted:

error: the following files have changes staged in the index:
/middleware.py
project_management/models.py
sales/migrations/0001_initial.py

(use --cached to keep the file, or -f to force removal)

Thinking that the conflicts are just due to those migration files, I typed:

git rm . -r -f

Now, git has removed ALL my files, including models, templates, views, static files, etc.

rm '.gitignore'
rm 'accounts/__init__.py'
rm 'accounts/__pycache__/__init__.cpython-36.pyc'
rm 'accounts/__pycache__/backends.cpython-36.pyc'
rm 'accounts/admin.py'
rm 'accounts/apps.py'
rm 'accounts/backends.py'
rm 'accounts/forms/__init__.py'
rm 'accounts/forms/authenticate.py'
rm 'accounts/forms/register.py'
rm 'accounts/migrations/0001_initial.py'
rm 'accounts/migrations/__init__.py'
rm 'accounts/models.py'
rm 'accounts/templates/login.html'
rm 'accounts/templates/signup.html'
rm 'accounts/tests.py'
rm 'accounts/urls.py'
rm 'accounts/views.py'

Now, when I do

git status

It tells me this:
    On branch master
All conflicts fixed but you are still merging.
  (use "git commit" to conclude merge)

Changes to be committed:

    deleted:    .gitignore
    deleted:    accounts/__init__.py
    deleted:    accounts/__pycache__/__init__.cpython-36.pyc
    deleted:    accounts/__pycache__/backends.cpython-36.pyc
    deleted:    accounts/admin.py
    deleted:    accounts/apps.py
    deleted:    accounts/backends.py
    deleted:    accounts/forms/__init__.py
    deleted:    accounts/forms/authenticate.py
    deleted:    accounts/forms/register.py
    deleted:    accounts/migrations/0001_initial.py
    deleted:    accounts/migrations/0002_auto_20170212_1028.py
    deleted:    accounts/migrations/__init__.py
    deleted:    accounts/models.py
    deleted:    accounts/templates/login.html
    deleted:    accounts/templates/signup.html
    deleted:    accounts/tests.py
    deleted:    accounts/urls.py
    deleted:    accounts/views.py
    ...
    Untracked files:
    (use "git add <file>..." to include in what will be committed)

    accounts/
    commonapp/

There are more than 10 apps, with more than 50 models, etc. but for the sake simplicity, I have not list them all here.

Is there a way to undo these deletions?  This is months worth of my time, so I really appreciate your help.


问:
Ionic dynamic component creation?
Is there a way using Ionic to dynamically create a component? For example, I have a few pages where a login prompt should be displayed. I have my component added to my module but don't know where I should go next in order to get this to display when certain events are called.

Any help as to where I should go now, I'm super confused on what I should do.

答:
I suggest two options:

Show a new page using ionic tabs, modal, or push and put social login control on all of them.

Use a single component, and put each page that you wanna show in an Ionic slides or div, and then only show the page that is relevant (using slideTo for slides or *ngIf for div). The social login can be added outside of the slides/div so it would be visible in all pages. You can put it in a footer.

Title: Ionic dynamic component creation?


问:
nullpointer in Ksession when i add drools to existing system
I'm trying to add a drools part to an existing java system .. but probably i'm doing something wrong  ( i'm very newbie)...
I added a kmodule.xml file to the classpath so done

```<code><?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns = "http://jboss.org/kie/6.0.0/kmodule">
     <kbase name = "rules" packages = "rules">
 <ksession name = "ksession-rules" />
    </kbase>
</kmodule>
</code>```

a sample.drl file so done

```<code>package com.xxx.drools
   declare Record
       field1: String @key
       field2: String @key
       field3: String @key
   end
   rule "CHECK_EVENT"
   When
         record: Record (field1 not in (1,46,25,26,264,6,9,13,44,73,125,130))
    then
         System.out.println ("blah blah blah");
   end
</code>```

and in the java code

```<code>KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
FactType amarecord = kSession.getKieBase().getFactType( "com.xxx.drools",
            "Record" );
</code>```

The problem is a null pointer in the last line because  kSession is null.
Does anyone know how to help me? thank you very much

答:
Package declaration in kmodule and drl file do not correspond.

Either change in sample drl

package com.xxx.drools
to
package rules

or change in kmodule.xml

<kbase name = "rules" packages = "rules"> to <kbase name = "rules" packages = "com.xxx.drools">

Body:
I'm trying to add a drools part to an existing java system .. but probably i'm doing something wrong  ( i'm very newbie)...
I added a kmodule.xml file to the classpath so done

<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns = "http://jboss.org/kie/6.0.0/kmodule">
     <kbase name = "rules" packages = "rules">
 <ksession name = "ksession-rules" />
    </kbase>
</kmodule>

a sample.drl file so done

package com.xxx.drools
   declare Record
       field1: String @key
       field2: String @key
       field3: String @key
   end
   rule "CHECK_EVENT"
   When
         record: Record (field1 not in (1,46,25,26,264,6,9,13,44,73,125,130))
    then
         System.out.println ("blah blah blah");
   end

and in the java code

KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
FactType amarecord = kSession.getKieBase().getFactType( "com.xxx.drools",
            "Record" );

The problem is a null pointer in the last line because  kSession is null.
Does anyone know how to help me? thank you very much


问:
Bash: how to automatically insert spacing characters according to indent?
I've got lots of debug statements making for unreadable stacktraces (not my call) like this:

```<code> 00:53:59,906  - j.util.indexing.FileBasedIndex - START INDEX SHUTDOWN
 00:53:09,192  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/macros.xml
 00:53:09,195  - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/quicklists.xml file is null
 00:53:09,195  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/quicklists.xml
 00:53:09,696  - ij.openapi.wm.impl.IdeRootPane - App initialization took 5584 ms
 00:53:11,677  -                  TestNG Runner - Create TestNG Template Configuration
 00:53:13,628  - indexing.UnindexedFilesUpdater - Unindexed files update started
 00:53:15,370  - indexing.UnindexedFilesUpdater - Unindexed files update done
 00:53:20,873  - tor.impl.FileEditorManagerImpl - Project opening took 10569 ms
 00:53:31,862  - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/intentionSettings.xml file is null
 00:53:31,862  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/intentionSettings.xml
 00:54:00,723  - j.util.indexing.FileBasedIndex - END INDEX SHUTDOWN
</code>```

And I want them to look like this:

```<code> 00:53:59,906  - j.util.indexing.FileBasedIndex - START INDEX SHUTDOWN
 00:53:09,192  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/macros.xml
 00:53:09,195  - s.impl.stores.FileBasedStorage -   Document was not loaded for $APP_CONFIG$/quicklists.xml file is null
 00:53:09,195  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/quicklists.xml
 00:53:09,696  - ij.openapi.wm.impl.IdeRootPane -     App initialization took 5584 ms
 00:53:11,677  -                  TestNG Runner -       Create TestNG Template Configuration
 00:53:13,628  - indexing.UnindexedFilesUpdater -        Unindexed files update started
 00:53:15,370  - indexing.UnindexedFilesUpdater -        Unindexed files update done
 00:53:20,873  - tor.impl.FileEditorManagerImpl -     Project opening took 10569 ms
 00:53:31,862  - s.impl.stores.FileBasedStorage -    Document was not loaded for $APP_CONFIG$/intentionSettings.xml file is null
 00:53:31,862  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/intentionSettings.xml
 00:54:00,723  - j.util.indexing.FileBasedIndex - END INDEX SHUTDOWN
</code>```

Now my code is formatted automatically so I know exactly how many characters there are in my source code for indent level.

What I want to do is replace automatically every line in my code looking like:

```<code>log.debug("some silly debug line");
</code>```

with:

```<code>log.debug(" " + "some silly debug line");
</code>```

or:

```<code>log.debug("  " + "some silly debug line");
</code>```

depending on the number of indents before the log.debug line.

I'm pretty sure some Bash/shell magic can do this automatically.

Basically I'd start with a:

```<code>find . -iname "*java" -exec ...
</code>```

then I'd like to insert " " on lines starting with log.debug depending on the indent level of these lines.

How would I go about it?

EDIT

Damn: it needs to be able to run several times, without re-shifting the lines already containing log.debug(" " +).  It gets more complicated but now thanks to the good answer I've got something to start from :)

Note: before yelling and shooting as to why this ain't a good idea, read my comment(s)

答:
You can try this awk script:

x.awk

```<code>/log.debug/ {
    logStart = match($0, "log");
    spaces = substr($0, 0, logStart);
    gap = "\"" spaces "\"";
    parenStart = match($0, "(");
    firstHalf = substr($0, 0, parenStart);
    lastHalf = substr($0, parenStart, length($0) - parenStart);
    print firstHalf gap " + " lastHalf;
    next;
}
{
    print;
}
</code>```

awk -f x.awk orig.java > new.java

Easy way to do this would be:

```<code>cd /code/root
mkdir /tmp/newcode
cp -R * /tmp/newcode
for i in `find . -name "*.java"`
do
    awk -f x.awk > /tmp/newcode/$i
done
</code>```

Should just copy over the original code on top of the new code, and not have to fight with making directories or any of that.

Untested, there can easily be a one off error in the splitting of the line, but it should get your started.

Body:
I've got lots of debug statements making for unreadable stacktraces (not my call) like this:

 00:53:59,906  - j.util.indexing.FileBasedIndex - START INDEX SHUTDOWN
 00:53:09,192  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/macros.xml
 00:53:09,195  - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/quicklists.xml file is null
 00:53:09,195  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/quicklists.xml
 00:53:09,696  - ij.openapi.wm.impl.IdeRootPane - App initialization took 5584 ms
 00:53:11,677  -                  TestNG Runner - Create TestNG Template Configuration
 00:53:13,628  - indexing.UnindexedFilesUpdater - Unindexed files update started
 00:53:15,370  - indexing.UnindexedFilesUpdater - Unindexed files update done
 00:53:20,873  - tor.impl.FileEditorManagerImpl - Project opening took 10569 ms
 00:53:31,862  - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/intentionSettings.xml file is null
 00:53:31,862  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/intentionSettings.xml
 00:54:00,723  - j.util.indexing.FileBasedIndex - END INDEX SHUTDOWN

And I want them to look like this:

 00:53:59,906  - j.util.indexing.FileBasedIndex - START INDEX SHUTDOWN
 00:53:09,192  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/macros.xml
 00:53:09,195  - s.impl.stores.FileBasedStorage -   Document was not loaded for $APP_CONFIG$/quicklists.xml file is null
 00:53:09,195  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/quicklists.xml
 00:53:09,696  - ij.openapi.wm.impl.IdeRootPane -     App initialization took 5584 ms
 00:53:11,677  -                  TestNG Runner -       Create TestNG Template Configuration
 00:53:13,628  - indexing.UnindexedFilesUpdater -        Unindexed files update started
 00:53:15,370  - indexing.UnindexedFilesUpdater -        Unindexed files update done
 00:53:20,873  - tor.impl.FileEditorManagerImpl -     Project opening took 10569 ms
 00:53:31,862  - s.impl.stores.FileBasedStorage -    Document was not loaded for $APP_CONFIG$/intentionSettings.xml file is null
 00:53:31,862  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/intentionSettings.xml
 00:54:00,723  - j.util.indexing.FileBasedIndex - END INDEX SHUTDOWN

Now my code is formatted automatically so I know exactly how many characters there are in my source code for indent level.

What I want to do is replace automatically every line in my code looking like:

log.debug("some silly debug line");

with:

log.debug(" " + "some silly debug line");

or:

log.debug("  " + "some silly debug line");

depending on the number of indents before the log.debug line.

I'm pretty sure some Bash/shell magic can do this automatically.

Basically I'd start with a:

find . -iname "*java" -exec ...

then I'd like to insert " " on lines starting with log.debug depending on the indent level of these lines.

How would I go about it?

EDIT

Damn: it needs to be able to run several times, without re-shifting the lines already containing log.debug(" " +).  It gets more complicated but now thanks to the good answer I've got something to start from :)

Note: before yelling and shooting as to why this ain't a good idea, read my comment(s)

Body:
You can try this awk script:

x.awk

/log.debug/ {
    logStart = match($0, "log");
    spaces = substr($0, 0, logStart);
    gap = "\"" spaces "\"";
    parenStart = match($0, "(");
    firstHalf = substr($0, 0, parenStart);
    lastHalf = substr($0, parenStart, length($0) - parenStart);
    print firstHalf gap " + " lastHalf;
    next;
}
{
    print;
}

awk -f x.awk orig.java > new.java

Easy way to do this would be:

cd /code/root
mkdir /tmp/newcode
cp -R * /tmp/newcode
for i in `find . -name "*.java"`
do
    awk -f x.awk > /tmp/newcode/$i
done

Should just copy over the original code on top of the new code, and not have to fight with making directories or any of that.

Untested, there can easily be a one off error in the splitting of the line, but it should get your started.


问:
PHP: Update multiple MySQL fields in single query
I am basically just trying to update multiple values in my table. What would be the best way to go about this? Here is the current code:

```<code>$postsPerPage = $_POST['postsPerPage'];
$style = $_POST['style'];

mysql_connect ("localhost", "user", "pass") or die ('Error: ' . mysql_error());
mysql_select_db ("db");

mysql_query("UPDATE settings SET postsPerPage = $postsPerPage WHERE id = '1'") or die(mysql_error());
</code>```

The other update I want to include is:

```<code>mysql_query("UPDATE settings SET style = $style WHERE id = '1'") or die(mysql_error());
</code>```

Thanks!

答:
I guess you can use:</p>

```<code>$con = new mysqli("localhost", "my_user", "my_password", "world");
$sql = "UPDATE `some_table` SET `txid`= '$txid', `data` = '$data' WHERE `wallet` = '$wallet'";
if ($mysqli->query($sql, $con)) {
    print "wallet $wallet updated";
}else{
    printf("Errormessage: %s\n", $con->error);
}
$con->close();
</code>```

Body:
I am basically just trying to update multiple values in my table. What would be the best way to go about this? Here is the current code:

$postsPerPage = $_POST['postsPerPage'];
$style = $_POST['style'];

mysql_connect ("localhost", "user", "pass") or die ('Error: ' . mysql_error());
mysql_select_db ("db");

mysql_query("UPDATE settings SET postsPerPage = $postsPerPage WHERE id = '1'") or die(mysql_error());

The other update I want to include is:

mysql_query("UPDATE settings SET style = $style WHERE id = '1'") or die(mysql_error());

Thanks!

Body:
I guess you can use:

$con = new mysqli("localhost", "my_user", "my_password", "world");
$sql = "UPDATE `some_table` SET `txid`= '$txid', `data` = '$data' WHERE `wallet` = '$wallet'";
if ($mysqli->query($sql, $con)) {
    print "wallet $wallet updated";
}else{
    printf("Errormessage: %s\n", $con->error);
}
$con->close();


问:
Kotlin Null safety warning Unexpected tokens (use ; to seperate expressions on the same line)
I was trying Elvis operator in Kotlin code in my application and received following warning:

```<code>Unexpected tokens (use ; to seperate expressions on the same line)
</code>```

Code:

```<code>    var key: String = "KEY is"
    /* "check" is name of String variable which can be null
    Warning coming on following statement*/
    var str : String = check?key.replace("KEY", "ABDS-ASDSA-DSSS")?:check
</code>```

Any ideas how to resolve this?

答:
kotlin does not support ternary operator.

and even check is not boolean variable in your case make it boolean or use like

```<code>var check: String = "something here"
 var key: String = "KEY is"
/*Warning coming on following statement*/
 var str : String = key.replace("KEY", "ABDS-ASDSA-DSSS")?:check
</code>```

Body:
I was trying Elvis operator in Kotlin code in my application and received following warning:

Unexpected tokens (use ; to seperate expressions on the same line)

Code:

    var key: String = "KEY is"
    /* "check" is name of String variable which can be null
    Warning coming on following statement*/
    var str : String = check?key.replace("KEY", "ABDS-ASDSA-DSSS")?:check

Any ideas how to resolve this?

Body:
kotlin does not support ternary operator.

and even check is not boolean variable in your case make it boolean or use like

var check: String = "something here"
 var key: String = "KEY is"
/*Warning coming on following statement*/
 var str : String = key.replace("KEY", "ABDS-ASDSA-DSSS")?:check


问:
OpenCPU Delete Session
I am creating multiple sessions in OpenCPU that produces some decently sized files (MB range).  These files are stored on disk and accumulate over time. The disk on my system runs out after creating too many sessions over a short time. Once the disk is full,t he following error is returned when trying to run a new session:

```<code>Failed to create tempdir /tmp/RtmpLaEI3K/ocpu-temp/x0bcd653371. Check directory permissions.
</code>```

Is there a way to delete sessions when I no longer need the files so that the disk won't fill up?  I'm currently running OpenCPU in standalone mode by executing the below R script:

```<code>install.packages("opencpu",repos = "http://cran.us.r-project.org")
library("MyCustomProject")

ocpu_start_app("MyCustomProject")
</code>```

I was unable to find anything in the OpenCPU API docs for deleting sessions.

答:
After more research I believe the answer is no, cleaning sessions explicitly is not currently supported.

A work around was to create a new R method that was exposed as an HTTP endpoint.  This method would determine the temporary work directory used by opencpu by calling the tempdir() method.  It would then receive the session id as an input argument and use it to delete all files in the temporary directory associated with the session.

Title: OpenCPU Delete Session

Body:
I am creating multiple sessions in OpenCPU that produces some decently sized files (MB range).  These files are stored on disk and accumulate over time. The disk on my system runs out after creating too many sessions over a short time. Once the disk is full,t he following error is returned when trying to run a new session:

Failed to create tempdir /tmp/RtmpLaEI3K/ocpu-temp/x0bcd653371. Check directory permissions.

Is there a way to delete sessions when I no longer need the files so that the disk won't fill up?  I'm currently running OpenCPU in standalone mode by executing the below R script:

install.packages("opencpu",repos = "http://cran.us.r-project.org")
library("MyCustomProject")

ocpu_start_app("MyCustomProject")

I was unable to find anything in the OpenCPU API docs for deleting sessions.


问:
Instr Function Not Finding Substring
I have the following VBA code, which returns "0" for the InStr function:

```<code>If InStr("ICD-10 & CPT OPC NHSN", "JCMC ICD-10 & CPT OPC NHSN Sep-17 new.xlsx") > 0 Then
   'Do something
End If
</code>```

However, the following code, using the WorksheetFunction.Find function, does locate the substring at position 6:

```<code>If Application.WorksheetFunction.Find("ICD-10 & CPT OPC NHSN", "JCMC ICD-10 & CPT OPC NHSN Sep-17 new.xlsx") > 0 Then
    'Do something
End If
</code>```

Why is the WorksheetFunction returning 6 while the InStr function not locating the substring?

答:
If you look at the documentation for the InStr function you will see that the first of the two mandatory parameters is the string to be searched, and the second parameter is the string being looked for.

string1   Required. String expression being searched.

  string2   Required. String expression sought.

So your code needs to be

```<code>If InStr("JCMC ICD-10 & CPT OPC NHSN Sep-17 new.xlsx", "ICD-10 & CPT OPC NHSN") > 0 Then
   'Do something
End If
</code>```

Title: Instr Function Not Finding Substring

Body:
I have the following VBA code, which returns "0" for the InStr function:

If InStr("ICD-10 & CPT OPC NHSN", "JCMC ICD-10 & CPT OPC NHSN Sep-17 new.xlsx") > 0 Then
   'Do something
End If

However, the following code, using the WorksheetFunction.Find function, does locate the substring at position 6:

If Application.WorksheetFunction.Find("ICD-10 & CPT OPC NHSN", "JCMC ICD-10 & CPT OPC NHSN Sep-17 new.xlsx") > 0 Then
    'Do something
End If

Why is the WorksheetFunction returning 6 while the InStr function not locating the substring?

Body:
If you look at the documentation for the InStr function you will see that the first of the two mandatory parameters is the string to be searched, and the second parameter is the string being looked for.

string1   Required. String expression being searched.

  string2   Required. String expression sought.

So your code needs to be

If InStr("JCMC ICD-10 & CPT OPC NHSN Sep-17 new.xlsx", "ICD-10 & CPT OPC NHSN") > 0 Then
   'Do something
End If


问:
MQ messages disappeared
I was able to browse the messages in the queues of a particular Queue Manager. At that time my listener ports down to process the messages. So I turned my listener ports to UP and restarted the servers. Now, I can not find any of the messages.

What is the reason for this problem? Please help.

Thanks :))

答:
There are two possibilities here.  The first as Yeradis has noted is that the messages expired.  You can verify this simply enough while browsing the messages.  Look at the expiry field.

The other possibility is that your listener is consuming the messages and then either discarding them or requeuing them.  It is not uncommon to find a listener that consumes messages and then, either because they did not match a selector or failed some other validation immediately and silently discards them.  It is difficult to diagnose this short of running a trace.  If you have the MO71 SupportPac installed, you can look at the queue stats in real time to see how many GET operations were executed against the queue.

Messages can be requeued if the listener backs the message out until the backout count threshold is exceeded and then moves the message to an exception queue or to the DLQ. In this case the messages will be found in one of these queues.

Title: MQ messages disappeared


问:
Why i cannot get 100 ether in pet-shop?
I have done 8 steps in pet-shop in Truffle:

In the box titled "New RPC URL" enter http://localhost:9545 and click Save.

The network name at the top will switch to say "Private Network".
Click the left-pointing arrow next to "Settings" to close out of the page and return to the Accounts page.

Each account created by Truffle Develop is given 100 ether. You'll notice it's slightly less on the first account because some gas was used when the contract itself was deployed.

but i cannot find 100 ether in MetaMask, it is still 0 ether in account1.

Can you help me?

答: Make sure you have the correct seed phrase entered in step 6: In the box marked Wallet Seed, enter the mnemonic that was displayed when launching Truffle Develop:

Title: Why i cannot get 100 ether in pet-shop?


问:
How to visible TextView in CardView?
I have a cardView in recyclerView, so I need to push the button "Explore" and open the cardView and see TextView, it is like this example.

So, what should I use to do that?

答:
If you are just using CardView, do this in your on onClickListener of cardview:

```<code>TransitionManager.beginDelayedTransition(cardview);
detailsView.setVisibility(View.VISIBLE);
</code>```

By default keep the visibility of your detailsView to be GONE in your xml.

If you are using CardViews inside a ListView or RecyclerView see answer for recommended way of doing it: RecyclerView expand/collapse items

Title: How to visible TextView in CardView?

Body:
If you are just using CardView, do this in your on onClickListener of cardview:

TransitionManager.beginDelayedTransition(cardview);
detailsView.setVisibility(View.VISIBLE);

By default keep the visibility of your detailsView to be GONE in your xml.

If you are using CardViews inside a ListView or RecyclerView see answer for recommended way of doing it: RecyclerView expand/collapse items


问:
How do you add a variable.value as the parameter of range()?
I'm trying to merge the first three empty rows and write Activity# in the three merged cells. I can't even figure out how to select 3 custom cells to get them ready for merging. I checked everywhere online but range(A1:B2) is always given a definitive range. How do I write for example: range(variable_A1:variable_B2)?

This is my code so far:

```<code>Private Sub OKButton_Click()

'Make Sheet1 active
Sheet1.Activate

Dim beginning
Dim ending
Dim selection

beginning = Cells(empty_row.Value, 2)
ending = Cells(empty_row.Value + 2, 2)

'this is supposed to select 3 cells, but it doesn't work
selection = Range("beginning:ending").Select
'figure out how to merge cells below

Cells(empty_row.Value, 2).Value = "Activity" & Activity_number.Value

Dim i As Integer
For i = 1 To nb_subs.Value
    Cells(empty_row.Value + i + 2, 2).Value = "Sub-Activity" & i
Next i
</code>```

答:
```<code>Private Sub OKButton_Click()

Dim beginning As Range
Dim ending As Range
Dim selection As Range

With Sheet1

    Set beginning = .Cells(empty_row.Value, 2)
    Set ending = .Cells(empty_row.Value + 2, 2)

    'this is supposed to select 3 cells, but it doesn't work
    Set selection = .Range(beginning, ending)
    selection.Merge

    selection.Value = "Activity" & Activity_number.Value

    Dim i As Integer
    For i = 1 To nb_subs.Value
        .Cells(empty_row.Value + i + 2, 2).Value = "Sub-Activity" & i
    Next i
End With
</code>```

Body:
I'm trying to merge the first three empty rows and write Activity# in the three merged cells. I can't even figure out how to select 3 custom cells to get them ready for merging. I checked everywhere online but range(A1:B2) is always given a definitive range. How do I write for example: range(variable_A1:variable_B2)?

This is my code so far:

Private Sub OKButton_Click()

'Make Sheet1 active
Sheet1.Activate

Dim beginning
Dim ending
Dim selection

beginning = Cells(empty_row.Value, 2)
ending = Cells(empty_row.Value + 2, 2)

'this is supposed to select 3 cells, but it doesn't work
selection = Range("beginning:ending").Select
'figure out how to merge cells below

Cells(empty_row.Value, 2).Value = "Activity" & Activity_number.Value

Dim i As Integer
For i = 1 To nb_subs.Value
    Cells(empty_row.Value + i + 2, 2).Value = "Sub-Activity" & i
Next i


问:
Animate layout change of bottom sheet
In my application I use a bottom sheet (from the support library) which works great. Now I would like to animate a layout change while the sheet is dragged up. For this I have created a subclass of BottomSheetCallback (this is normaly an inner class of a Fragment so not all objects used in this calss are initialized here):

```<code>public class MyBehavior extends BottomSheetBehavior.BottomSheetCallback {

    Transition transition;
    float lastOffset = 0;
    Scene scene;

    public PlayerBehavior() {
        TransitionInflater inflater = TransitionInflater.from(getContext());
        transition = inflater.inflateTransition(R.transition.player);
        //transition.setDuration(300);

        scene = fullLayout;

        transition.setInterpolator(new Interpolator() {
            @Override
            public float getInterpolation(float v) {
                return lastOffset;
            }
        });
    }

    @Override
    public void onStateChanged(@NonNull View bottomSheet, int newState) {
        if(newState == BottomSheetBehavior.STATE_DRAGGING) {
            TransitionManager.go(scene, transition);
        }
    }

    @Override
    public void onSlide(View bottomSheet, final float slideOffset) {
        scene = (slideOffset > lastOffset) ? smallLayout : fullLayout;
        lastOffset = slideOffset;
    }
}
</code>```

As you can see I also created two Scene from different layout files and a custom Transition to animate between the scenes with the TransitionManager. My problem is that the Transition should be based on the slideOffset parameter (in range of 0-1) but the TransitionManager uses the Animation class in the background which is normally time based in Android.

I tried to create the custom Intapolator but this does not work properly. So how can I create a Transition which is based on an external variable and not on time?

答:
Based on your description, I think you are trying to achieve something like google maps bottom sheet behaviour. The layout changes as the bottomsheet is dragged up.

If that is what you are trying to achieve then you don't need to enforce custom animations, as the bottomsheetdialog itself has those animation behaviour when incorporated inside a parent Coordinator Layout.

Here is a sample code of how I'm implementing the same behaviour. It also makes the FloatingActionButton invisible when the bottomsheet is dragged up to full screen size :

Create a bottomsheetdialog that you want to use inside your main layout

```<code>public class CustomBottomDialog extends BottomSheetDialogFragment {

String mSomeName;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // if some arguments are passed from the calling activity
    mSomeName = getArguments().getString("some_name");

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View bottomSheet = inflater.inflate(R.layout.bottomsheet_layout, container, false);
     // initialise your bottomsheet_layout items here
    TextView tvName = bottomSheet.findViewById(R.id.display_name);
    tvName.setText(mSomeName);
    tvName.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           // do something here
            ((MainActivity)getActivity()).doSomething();
        }
    });

    return bottomSheet;
}
}
</code>```

bottomsheet_layout:

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.FloatingActionButton
android:id="@+id/nav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/navigation_tilt_grey"
app:backgroundTint="@color/colorAccent"
app:elevation="3dp"
app:fabSize="normal"
android:layout_marginEnd="@dimen/activity_horizontal_margin"
app:layout_anchor="@+id/live_dash"
app:layout_anchorGravity="top|right" />

<!--BottomSheet-->

<android.support.v4.widget.NestedScrollView
android:id="@+id/live_dash"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F3F3F3"
android:clipToPadding="true"
app:layout_behavior="android.support.design.widget.BottomSheetBe
havior"
tools:layout_editor_absoluteY="150dp">

<!--Include your items here, the height of all items combined
will take the main screen layout size with animation-->

</android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>
</code>```

Calling this BottomSheet from your activity:

```<code>public void notifyBottomSheet(String somename){

BottomSheetDialogFragment customDialogFragment = new CustomBottomDialog();
Bundle args = new Bundle();
args.putString("some_name", somename);
customDialogFragment.setArguments(args);
customDialogFragment.show(getSupportFragmentManager(), customDialogFragment.getTag());
customDialogFragment.setCancelable(false); // if you don't wish to hide
}
</code>```

Hope this solves what you are trying to achieve.

Title: Animate layout change of bottom sheet

Body:
In my application I use a bottom sheet (from the support library) which works great. Now I would like to animate a layout change while the sheet is dragged up. For this I have created a subclass of BottomSheetCallback (this is normaly an inner class of a Fragment so not all objects used in this calss are initialized here):

public class MyBehavior extends BottomSheetBehavior.BottomSheetCallback {

    Transition transition;
    float lastOffset = 0;
    Scene scene;

    public PlayerBehavior() {
        TransitionInflater inflater = TransitionInflater.from(getContext());
        transition = inflater.inflateTransition(R.transition.player);
        //transition.setDuration(300);

        scene = fullLayout;

        transition.setInterpolator(new Interpolator() {
            @Override
            public float getInterpolation(float v) {
                return lastOffset;
            }
        });
    }

    @Override
    public void onStateChanged(@NonNull View bottomSheet, int newState) {
        if(newState == BottomSheetBehavior.STATE_DRAGGING) {
            TransitionManager.go(scene, transition);
        }
    }

    @Override
    public void onSlide(View bottomSheet, final float slideOffset) {
        scene = (slideOffset > lastOffset) ? smallLayout : fullLayout;
        lastOffset = slideOffset;
    }
}

As you can see I also created two Scene from different layout files and a custom Transition to animate between the scenes with the TransitionManager. My problem is that the Transition should be based on the slideOffset parameter (in range of 0-1) but the TransitionManager uses the Animation class in the background which is normally time based in Android.

I tried to create the custom Intapolator but this does not work properly. So how can I create a Transition which is based on an external variable and not on time?

Body:
Based on your description, I think you are trying to achieve something like google maps bottom sheet behaviour. The layout changes as the bottomsheet is dragged up.

If that is what you are trying to achieve then you don't need to enforce custom animations, as the bottomsheetdialog itself has those animation behaviour when incorporated inside a parent Coordinator Layout.

Here is a sample code of how I'm implementing the same behaviour. It also makes the FloatingActionButton invisible when the bottomsheet is dragged up to full screen size :

Create a bottomsheetdialog that you want to use inside your main layout

public class CustomBottomDialog extends BottomSheetDialogFragment {

String mSomeName;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // if some arguments are passed from the calling activity
    mSomeName = getArguments().getString("some_name");

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View bottomSheet = inflater.inflate(R.layout.bottomsheet_layout, container, false);
     // initialise your bottomsheet_layout items here
    TextView tvName = bottomSheet.findViewById(R.id.display_name);
    tvName.setText(mSomeName);
    tvName.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           // do something here
            ((MainActivity)getActivity()).doSomething();
        }
    });

    return bottomSheet;
}
}

bottomsheet_layout:

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.FloatingActionButton
android:id="@+id/nav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/navigation_tilt_grey"
app:backgroundTint="@color/colorAccent"
app:elevation="3dp"
app:fabSize="normal"
android:layout_marginEnd="@dimen/activity_horizontal_margin"
app:layout_anchor="@+id/live_dash"
app:layout_anchorGravity="top|right" />

<!--BottomSheet-->

<android.support.v4.widget.NestedScrollView
android:id="@+id/live_dash"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F3F3F3"
android:clipToPadding="true"
app:layout_behavior="android.support.design.widget.BottomSheetBe
havior"
tools:layout_editor_absoluteY="150dp">

<!--Include your items here, the height of all items combined
will take the main screen layout size with animation-->

</android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

Calling this BottomSheet from your activity:

public void notifyBottomSheet(String somename){

BottomSheetDialogFragment customDialogFragment = new CustomBottomDialog();
Bundle args = new Bundle();
args.putString("some_name", somename);
customDialogFragment.setArguments(args);
customDialogFragment.show(getSupportFragmentManager(), customDialogFragment.getTag());
customDialogFragment.setCancelable(false); // if you don't wish to hide
}

Hope this solves what you are trying to achieve.


问:
Manipulating object in array changes object outside of array?
I don't understand why this behavior is happening. Lets say I define an object and make an array of 3 of this object. If I modify the objects in the array, it affects all instances of the object? Could someone explain why this is? Also, how do I make an array with independent "Copies" of the object to get the desired behavior? Thanks!

example

```<code>testObject = {"value1":"a","value2":"b"};
objArray = [];
for(i=0; i < 3; i++){
   var newobj = testObject; //make a new testObject
   objArray.push(newobj); //push new object to array
   }
delete objArray[0].value2 // Desired, delete value 2 ONLY from array object 0
objArray[2].value2 //Undefined? Why is value2 missing from object 2
testObject.value2 //Undefined? Why is value2 missing from original object?
</code>```

答:
As opposed to primitives (strings, numbers, booleans, symbols null, undefined), objects in javascript are passed by reference. Variables serve as placeholders/pointers to these objects. To create a copy of an object without the risk of mutation you'd use spread (barring compatibility):

```<code>const newObject = { ...testObject };
</code>```

or traditionally, Object.assign(), passing an empty object literal to avoid mutability of the original testObject:

```<code>const newObject = Object.assign({}, testObject);
</code>```

As far as deep cloning, MDN suggests using a combination of JSON.parse() and JSON.stringify(). So for example:

```<code>const testObject = { value: "a", other: { value2: b } };

const newObject = JSON.parse(JSON.stringify(testObject));
</code>```

Body:
I don't understand why this behavior is happening. Lets say I define an object and make an array of 3 of this object. If I modify the objects in the array, it affects all instances of the object? Could someone explain why this is? Also, how do I make an array with independent "Copies" of the object to get the desired behavior? Thanks!

example

testObject = {"value1":"a","value2":"b"};
objArray = [];
for(i=0; i < 3; i++){
   var newobj = testObject; //make a new testObject
   objArray.push(newobj); //push new object to array
   }
delete objArray[0].value2 // Desired, delete value 2 ONLY from array object 0
objArray[2].value2 //Undefined? Why is value2 missing from object 2
testObject.value2 //Undefined? Why is value2 missing from original object?

Body:
As opposed to primitives (strings, numbers, booleans, symbols null, undefined), objects in javascript are passed by reference. Variables serve as placeholders/pointers to these objects. To create a copy of an object without the risk of mutation you'd use spread (barring compatibility):

const newObject = { ...testObject };

or traditionally, Object.assign(), passing an empty object literal to avoid mutability of the original testObject:

const newObject = Object.assign({}, testObject);

As far as deep cloning, MDN suggests using a combination of JSON.parse() and JSON.stringify(). So for example:

const testObject = { value: "a", other: { value2: b } };

const newObject = JSON.parse(JSON.stringify(testObject));


问:
Core 2 EF - Redirect to Detail Page after Edit
I want to redirect back to the details page after an Edit. By default, after scaffolding, the code looks something like:

```<code>public async Task<IActionResult> Edit(int id, RecordClass recordClass)
{
    //Update Code
    return RedirectToAction(nameof(Index));
}
</code>```

However, since I already have the ID, I want to redirect straight to the record detail page. I tried most of the RedirectToActions:

But I would either get an error, an empty Details page, or it would redirect back to Edit page with parameter. None redirected to Details with paramater.

I also tried RedirectToPage and RedirectToRoute, but none work for this purpose.

Now, I got this to work with the following code:

```<code>public async Task<IActionResult> Edit(int id, RecordClass recordClass)
{
    //Update Code
    return RedirectToAction(nameof(Details) + "/" + students.IdStudent.ToString());
}
</code>```

Altought it works, it looks horrible and I'm not sure this is the correct way of doing it.

Suggestions?

答:
Just pass id parameter like this;

```<code>return RedirectToAction(nameof(Details), new { id = students.IdStudent.ToString() });
</code>```

Body:
I want to redirect back to the details page after an Edit. By default, after scaffolding, the code looks something like:

public async Task<IActionResult> Edit(int id, RecordClass recordClass)
{
    //Update Code
    return RedirectToAction(nameof(Index));
}

However, since I already have the ID, I want to redirect straight to the record detail page. I tried most of the RedirectToActions:

But I would either get an error, an empty Details page, or it would redirect back to Edit page with parameter. None redirected to Details with paramater.

I also tried RedirectToPage and RedirectToRoute, but none work for this purpose.

Now, I got this to work with the following code:

public async Task<IActionResult> Edit(int id, RecordClass recordClass)
{
    //Update Code
    return RedirectToAction(nameof(Details) + "/" + students.IdStudent.ToString());
}

Altought it works, it looks horrible and I'm not sure this is the correct way of doing it.

Suggestions?

Body:
Just pass id parameter like this;

return RedirectToAction(nameof(Details), new { id = students.IdStudent.ToString() });


问:
HashMap: One Key, multiple Values
How I can get the third value for the first key in this map? Is this possible?</p>

答:
HashMap – Single Key and Multiple Values Using List</p>

```<code>Map<String, List<String>> map = new HashMap<String, List<String>>();

  // create list one and store values

    List<String> One = new ArrayList<String>();
    One.add("Apple");
    One.add("Aeroplane");

    // create list two and store values
    List<String> Two = new ArrayList<String>();
    Two.add("Bat");
    Two.add("Banana");

    // put values into map
    map.put("A", One);
    map.put("B", Two);
    map.put("C", Three);
</code>```

Title: HashMap: One Key, multiple Values

Body:
HashMap – Single Key and Multiple Values Using List

Map<String, List<String>> map = new HashMap<String, List<String>>();

  // create list one and store values

    List<String> One = new ArrayList<String>();
    One.add("Apple");
    One.add("Aeroplane");

    // create list two and store values
    List<String> Two = new ArrayList<String>();
    Two.add("Bat");
    Two.add("Banana");

    // put values into map
    map.put("A", One);
    map.put("B", Two);
    map.put("C", Three);


问:
Alternative Y combinator definition
I've spent some time wrapping my head around the Y combinator lately, and I've found that it is usually defined (more or less) as follows (this is in C#, but the language of choice isn't important):

```<code>public delegate TResult SelfApplicable<TResult>(SelfApplicable<TResult> r);

public static TResult U<TResult>(SelfApplicable<TResult> r)
{
    return r(r);
}

public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return U<Func<TArg1, TReturn>>(r => arg1 => f(U(r))(arg1));
}
</code>```

While that's perfectly functional (pun intended), it would seem that my definition is much simpler:

```<code>public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return f(n => Y(f)(n));
}
</code>```

Is there any reason why the latter definition is not as common (I have yet to find it on the net)? Would it perhaps have something to do with defining Y in terms of itself?

答:
I’m not sure what your question is but I guess the reason that neither the Y combinator nor your solution are seen much in the wild is twofold:

anonymous recursive functions are really rare; in particular since C# doesn’t have great (read: none at all) support for tail recursion.

There’s a much easier (more readable for the uninitiated) way of defining pseudo-“anonymous” recursive lambdas in C#:

```<code>Func<int, int> fac = null;
fac = x => x == 0 ? 1 : fac(x - 1) * x;
</code>```

Granted, this is not anonymous but it’s “close enough” for practical purposes.

Title: Alternative Y combinator definition

Body:
I've spent some time wrapping my head around the Y combinator lately, and I've found that it is usually defined (more or less) as follows (this is in C#, but the language of choice isn't important):

public delegate TResult SelfApplicable<TResult>(SelfApplicable<TResult> r);

public static TResult U<TResult>(SelfApplicable<TResult> r)
{
    return r(r);
}

public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return U<Func<TArg1, TReturn>>(r => arg1 => f(U(r))(arg1));
}

While that's perfectly functional (pun intended), it would seem that my definition is much simpler:

public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return f(n => Y(f)(n));
}

Is there any reason why the latter definition is not as common (I have yet to find it on the net)? Would it perhaps have something to do with defining Y in terms of itself?

Body:
I’m not sure what your question is but I guess the reason that neither the Y combinator nor your solution are seen much in the wild is twofold:

anonymous recursive functions are really rare; in particular since C# doesn’t have great (read: none at all) support for tail recursion.

There’s a much easier (more readable for the uninitiated) way of defining pseudo-“anonymous” recursive lambdas in C#:

Func<int, int> fac = null;
fac = x => x == 0 ? 1 : fac(x - 1) * x;

Granted, this is not anonymous but it’s “close enough” for practical purposes.


问:
Shell script with a cron job to kill a python file named healthcheck.py if not running and start the service again?
I am new to UNIX / Linux and need a shell script to kill a programs if it is not running. The program's name is healthcheck.py. This program is supposed to run this health check service for routers. But for every 8 hours the service is dropping with an error so I thought of putting it in cronjob that check if the service is running every minute and if it doesn't, I need a shell script to start the process. Currently I am doing it manually using these commands:

```<code>#getting the pid
 pid= ps - ef | grep -i python healthcheck.py

#kill the healthcheck.py process with the pid we got from above command
kill -9 "pid"

#running the service again
nohup python healthcheck.py &
</code>```

答: Under Fedora you would use a systemd script for this.</p>

Body:
I am new to UNIX / Linux and need a shell script to kill a programs if it is not running. The program's name is healthcheck.py. This program is supposed to run this health check service for routers. But for every 8 hours the service is dropping with an error so I thought of putting it in cronjob that check if the service is running every minute and if it doesn't, I need a shell script to start the process. Currently I am doing it manually using these commands:

#getting the pid
 pid= ps - ef | grep -i python healthcheck.py

#kill the healthcheck.py process with the pid we got from above command
kill -9 "pid"

#running the service again
nohup python healthcheck.py &


问:
spring data jpa pagination with sub query not woking
below is the query which is working fine

```<code> @Query("SELECT city.id as id,city.latitude as latitude, city.longitude as longitude, \n" +
        "(SELECT cityTrans.name " +
        "   FROM city.listOfCityTrans as cityTrans " +
        "   WHERE cityTrans.languageId=:languageId AND cityTrans.cityId=city.id)" +
        " AS name, \n" +
        "(SELECT provinceTrans.name " +
        "   FROM city.province AS province JOIN province.listOfProvinceTrans AS provinceTrans " +
        "   WHERE provinceTrans.languageId=:languageId AND provinceTrans.provinceId=city.provinceId)" +
        " AS provinceName, \n" +
        "(SELECT countryTrans.name " +
        "   FROM city.province AS province JOIN province.country.listOfCountryTrans AS countryTrans " +
        "   WHERE countryTrans.languageId=:languageId AND countryTrans.countryId=city.provinceId)" +
        " AS countryName, province.id as provinceId,province.countryId as countryId \n" +
        " FROM City as city")
Page<CitySummary> findCities(@Param("languageId") Integer languageId, Pageable pageable);
</code>```

but when i pass sort param ?sort=name

then it is creating wrong query

```<code>SELECT city.id as id,city.latitude as latitude, city.longitude as longitude,
\n(SELECT cityTrans.name    FROM city.listOfCityTrans as cityTrans    WHERE
cityTrans.languageId=:languageId AND cityTrans.cityId=city.id) AS name,
\n(SELECT provinceTrans.name    FROM city.province AS province JOIN
province.listOfProvinceTrans AS provinceTrans    WHERE
provinceTrans.languageId=:languageId AND
provinceTrans.provinceId=city.provinceId) AS provinceName, \n(SELECT
countryTrans.name    FROM city.province AS province JOIN
province.country.listOfCountryTrans AS countryTrans    WHERE
countryTrans.languageId=:languageId AND
countryTrans.countryId=city.provinceId) AS countryName, province.id as
provinceId,province.countryId as countryId \n FROM
com.pro.api.model.City as city order by cityTrans.name asc
                                        ^
</code>```

can anyone tell why this is happening?

答: I think the MVC to JPA path only works for entity definitions, not Object[] results, so if your City entity doesn't have a name property, then JPA would try to find another field match, which would be the cityTrans

Body:
below is the query which is working fine

 @Query("SELECT city.id as id,city.latitude as latitude, city.longitude as longitude, \n" +
        "(SELECT cityTrans.name " +
        "   FROM city.listOfCityTrans as cityTrans " +
        "   WHERE cityTrans.languageId=:languageId AND cityTrans.cityId=city.id)" +
        " AS name, \n" +
        "(SELECT provinceTrans.name " +
        "   FROM city.province AS province JOIN province.listOfProvinceTrans AS provinceTrans " +
        "   WHERE provinceTrans.languageId=:languageId AND provinceTrans.provinceId=city.provinceId)" +
        " AS provinceName, \n" +
        "(SELECT countryTrans.name " +
        "   FROM city.province AS province JOIN province.country.listOfCountryTrans AS countryTrans " +
        "   WHERE countryTrans.languageId=:languageId AND countryTrans.countryId=city.provinceId)" +
        " AS countryName, province.id as provinceId,province.countryId as countryId \n" +
        " FROM City as city")
Page<CitySummary> findCities(@Param("languageId") Integer languageId, Pageable pageable);

but when i pass sort param ?sort=name

then it is creating wrong query

SELECT city.id as id,city.latitude as latitude, city.longitude as longitude,
\n(SELECT cityTrans.name    FROM city.listOfCityTrans as cityTrans    WHERE
cityTrans.languageId=:languageId AND cityTrans.cityId=city.id) AS name,
\n(SELECT provinceTrans.name    FROM city.province AS province JOIN
province.listOfProvinceTrans AS provinceTrans    WHERE
provinceTrans.languageId=:languageId AND
provinceTrans.provinceId=city.provinceId) AS provinceName, \n(SELECT
countryTrans.name    FROM city.province AS province JOIN
province.country.listOfCountryTrans AS countryTrans    WHERE
countryTrans.languageId=:languageId AND
countryTrans.countryId=city.provinceId) AS countryName, province.id as
provinceId,province.countryId as countryId \n FROM
com.pro.api.model.City as city order by cityTrans.name asc
                                        ^

can anyone tell why this is happening?


问:
Get epoch seconds for specific date in C
How can I get the number of seconds passed since January 1, 1970 for a specific date, for example:"2017-09-14 23:24:46"

```<code>#include <stdio.h>
#include <stdint.h>
#include <time.h>
int main()
{

    struct tm tmVar;
    time_t timeVar;
    sscanf("2017-09-14 23:24:46","%d-%d-%d %d:%d:%d",&tmVar.tm_year
                        ,&tmVar.tm_mon, &tmVar.tm_mday,
                         &tmVar.tm_hour, &tmVar.tm_min,
                         &tmVar.tm_sec);
     tmVar.tm_isdst = 1;
     printf("tm_year :%d\n",tmVar.tm_year);
     printf("tm_month :%d\n",tmVar.tm_mon);
     printf("tm_day :%d\n",tmVar.tm_mday);
     printf("tm_hour :%d\n",tmVar.tm_hour);
     printf("tm_min :%d\n",tmVar.tm_min);
     printf("tm_sec :%d\n",tmVar.tm_sec);
     timeVar = mktime(&tmVar);
     printf("time %d\n",timeVar);
 }
</code>```

The output however is not what I expect:

tm_year :2017

tm_month :9

tm_day :14

tm_hour :23

tm_min :24

tm_sec :46

time 1336625342

According to epochconverter.com, the proper value should be 1510529086.  Why am I not getting this value?

答:
You need to adjust the values stored in your struct.

The tm_year field is years since 1900, so subtract 1900 from this value.

The tm_mon field is months since January, so subtract 1 from this value.

So do the following after populating the struct:

```<code> tmVar.tm_year -= 1900;
 tmVar.tm_mon--;
</code>```

Output:

```<code>tm_year :117
tm_month :8
tm_day :14
tm_hour :23
tm_min :24
tm_sec :46
time 1505445886
</code>```

Body:
How can I get the number of seconds passed since January 1, 1970 for a specific date, for example:"2017-09-14 23:24:46"

#include <stdio.h>
#include <stdint.h>
#include <time.h>
int main()
{

    struct tm tmVar;
    time_t timeVar;
    sscanf("2017-09-14 23:24:46","%d-%d-%d %d:%d:%d",&tmVar.tm_year
                        ,&tmVar.tm_mon, &tmVar.tm_mday,
                         &tmVar.tm_hour, &tmVar.tm_min,
                         &tmVar.tm_sec);
     tmVar.tm_isdst = 1;
     printf("tm_year :%d\n",tmVar.tm_year);
     printf("tm_month :%d\n",tmVar.tm_mon);
     printf("tm_day :%d\n",tmVar.tm_mday);
     printf("tm_hour :%d\n",tmVar.tm_hour);
     printf("tm_min :%d\n",tmVar.tm_min);
     printf("tm_sec :%d\n",tmVar.tm_sec);
     timeVar = mktime(&tmVar);
     printf("time %d\n",timeVar);
 }

The output however is not what I expect:

tm_year :2017

tm_month :9

tm_day :14

tm_hour :23

tm_min :24

tm_sec :46

time 1336625342

According to epochconverter.com, the proper value should be 1510529086.  Why am I not getting this value?

Body:
You need to adjust the values stored in your struct.

The tm_year field is years since 1900, so subtract 1900 from this value.

The tm_mon field is months since January, so subtract 1 from this value.

So do the following after populating the struct:

 tmVar.tm_year -= 1900;
 tmVar.tm_mon--;

Output:

tm_year :117
tm_month :8
tm_day :14
tm_hour :23
tm_min :24
tm_sec :46
time 1505445886


问:
C++ How to break a while find loop?
In this loop I want to add new line (\n) behind evert dot(.).

How to break the loop when new line has been added after each dot?

```<code>while (alltxt.find(".") != string::npos)
    alltxt.replace(alltxt.find("."), 1, ".\n");
</code>```

答:
use the find overload that starts from a position. Something like the following (not tested, just illustrative):

```<code>if(!str.empty())
{
    size_t pos = 0;
    while(true)
    {
    pos = str.find(pos, '.');
    if(std::string::npos==pos)
    break;
    str.insert(++pos, 1, '\n');
    }
    }
</code>```

Using a condition in the while() would require that it be checked twice (you absolutely need to check after the find), this way there is only one test that can come out different.

ContentLicense: CC BY-SA 4.0

Title: C++ How to break a while find loop?

Body:
In this loop I want to add new line (\n) behind evert dot(.).

How to break the loop when new line has been added after each dot?

while (alltxt.find(".") != string::npos)
    alltxt.replace(alltxt.find("."), 1, ".\n");

Body:
use the find overload that starts from a position. Something like the following (not tested, just illustrative):

if(!str.empty())
{
    size_t pos = 0;
    while(true)
    {
    pos = str.find(pos, '.');
    if(std::string::npos==pos)
    break;
    str.insert(++pos, 1, '\n');
    }
    }

Using a condition in the while() would require that it be checked twice (you absolutely need to check after the find), this way there is only one test that can come out different.


问:
Postgres error “ERROR: INSERT has more target columns than expressions”
Whenever I run this code I get an error saying "Error %s % e INSERT has more target columns than expressions" with a ^ showing under fthg. Any idea what the issue is here, considering fthg is already defined? Many thanks!</p>

```<code> cur.execute("CREATE TABLE IF NOT EXISTS soccerleague.games (gameId SERIAL PRIMARY KEY, homeTeamId INTEGER, FOREIGN KEY (homeTeamId) REFERENCES soccerleague.teams(id),awayTeamId INTEGER, FOREIGN KEY (awayTeamId) REFERENCES soccerleague.teams(id), fthg INTEGER, athg INTEGER, ftr VARCHAR, refereeId INTEGER, FOREIGN KEY (refereeId) REFERENCES soccerleague.referees(id), HY INTEGER, AY INTEGER)")

data3 = (teamsDict[homeTeam], teamsDict[awayTeam], fthg, athg, ftr, refereesDict[refereeName], hy, ay)
query3 = "INSERT INTO soccerleague.games (homeTeamId, awayTeamId, fthg, athg, ftr, refereeId, hy, ay) VALUES"
query3 += "('" + str(data3) + "', '" + x + "'),"
query3 = query3[:-1] + ";"
</code>```

答:
The issue is not in the table creation, but when you set the data to be inserted.

The line query3 += "('" + str(data3) + "', '" + x + "')," instructs to insert the content of data3 first, then the content of x which sums to 2 arguments. The insert statement query3 = "INSERT INTO soccerleague.games (homeTeamId, awayTeamId, fthg, athg, ftr, refereeId, hy, ay) VALUES" refers to 8 arguments. To fix the issue, either supply the 8 values (some could be null) or trim down the insert statement to the 2 firsts fields only.

Even though you set data3 to contains all the values you wanted, the insert statement is writing it as a single quoted string, which maps to the 1st field only.

Body:
Whenever I run this code I get an error saying "Error %s % e INSERT has more target columns than expressions" with a ^ showing under fthg. Any idea what the issue is here, considering fthg is already defined? Many thanks!

 cur.execute("CREATE TABLE IF NOT EXISTS soccerleague.games (gameId SERIAL PRIMARY KEY, homeTeamId INTEGER, FOREIGN KEY (homeTeamId) REFERENCES soccerleague.teams(id),awayTeamId INTEGER, FOREIGN KEY (awayTeamId) REFERENCES soccerleague.teams(id), fthg INTEGER, athg INTEGER, ftr VARCHAR, refereeId INTEGER, FOREIGN KEY (refereeId) REFERENCES soccerleague.referees(id), HY INTEGER, AY INTEGER)")

data3 = (teamsDict[homeTeam], teamsDict[awayTeam], fthg, athg, ftr, refereesDict[refereeName], hy, ay)
query3 = "INSERT INTO soccerleague.games (homeTeamId, awayTeamId, fthg, athg, ftr, refereeId, hy, ay) VALUES"
query3 += "('" + str(data3) + "', '" + x + "'),"
query3 = query3[:-1] + ";"