问:
Disable encoding of the pipe character on http request
I am trying to send a request to an URL that uses the pipe character in its URL
site.com/page?param=|||

Sending a request to this URL using both Jsoup and URLConnection causes the pipe character to be encoded to %7C, however, the site accept only unencoded |.

I have checked with fiddler, and noticed that Web browsers does not encode the pipe character, so why java libraries (the URI class i guess) has to encode it?
and is there a way to force (or disable the encoding for that particular character) when sending the request?

答:
I have a test,and send request by using Jsoup and URLConnection,i notice that the URLConnection is not encode the url. This is my test code:

```<code>Connection jsoupConnection = Jsoup.connect("http://www.baidu.com/page?param=|||");
Document document = jsoupConnection.get();
URL url=new URL("http://www.baidu.com/page?param=|||");
URLConnection urlConnection = url.openConnection();
InputStream input = urlConnection.getInputStream();
byte[] entity = ByteStreams.toByteArray(input);
</code>```

And i monitor the internet with WireShark.This is http packet while using Jsoup:

```<code>10  0.011680000 192.168.78.128  115.239.210.27  HTTP    357 GET /page?param=%7C%7C%7C HTTP/1.1
</code>```

this is URLConnection:

```<code>27  0.128714000 192.168.78.128  115.239.210.27  HTTP    220 GET /page?param=||| HTTP/1.1
</code>```

So,the Url is not encoded while using URLConnection.

And i look the implemention of method connect in Jsoup,and found the key code:

```<code>private static URL encodeUrl(URL u) {
    try {
        //  odd way to encode urls, but it works!
        final URI uri = new URI(u.getProtocol(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), u.getQuery(), u.getRef());
        return new URL(uri.toASCIIString());
    } catch (Exception e) {
        return u;
    }
}
</code>```

The url is encoded take place in final URI uri = new URI(u.getProtocol(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), u.getQuery(), u.getRef());,and there is no property to control the encoding or not in Jsoup.

So i think you can use the URLConnection rather than Jsoup.

Body:
I have a test,and send request by using Jsoup and URLConnection,i notice that the URLConnection is not encode the url. This is my test code:

Connection jsoupConnection = Jsoup.connect("http://www.baidu.com/page?param=|||");
Document document = jsoupConnection.get();
URL url=new URL("http://www.baidu.com/page?param=|||");
URLConnection urlConnection = url.openConnection();
InputStream input = urlConnection.getInputStream();
byte[] entity = ByteStreams.toByteArray(input);

And i monitor the internet with WireShark.This is http packet while using Jsoup:

10  0.011680000 192.168.78.128  115.239.210.27  HTTP    357 GET /page?param=%7C%7C%7C HTTP/1.1

this is URLConnection:

27  0.128714000 192.168.78.128  115.239.210.27  HTTP    220 GET /page?param=||| HTTP/1.1

So,the Url is not encoded while using URLConnection.

And i look the implemention of method connect in Jsoup,and found the key code:

private static URL encodeUrl(URL u) {
    try {
        //  odd way to encode urls, but it works!
        final URI uri = new URI(u.getProtocol(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), u.getQuery(), u.getRef());
        return new URL(uri.toASCIIString());
    } catch (Exception e) {
        return u;
    }
}

The url is encoded take place in final URI uri = new URI(u.getProtocol(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), u.getQuery(), u.getRef());,and there is no property to control the encoding or not in Jsoup.

So i think you can use the URLConnection rather than Jsoup.


来源: stackexchange

问:
What is the ideal XML Schema for a Tree Structure with nested Nodes?
I need to design a XML-Schema which should work with something like this tree:

It's the first time i have to design XML and i don't find something useful for my problem. I tried it with enumerations, but i think that's not the way to do it.

Is it done with a recursion?

Thx for your help.

答:
I found this Schema: https://cwe.mitre.org/data/xsd/cwe_schema_v3.0.xsd

Perfect Structure for this kind of Tree.

ContentLicense: CC BY-SA 3.0


问:
Change drawer gap between header group and first item menu
I need change the space between header group and first item menu, here's an example:

I have seen a lot of examples and posts but only be can change the space for all items, and I just need to change only for header group.

Any idea?

答:
Changing the values in dimen.xml by overriding the values which are already set in the android support library.

```<code> <dimen name="design_navigation_padding_top_default"
tools:override="true">0dp</dimen>
<dimen name="design_navigation_separator_vertical_padding"tools:override="true">0dp</dimen>
<dimen name="design_navigation_padding_bottom"tools:override="true">0dp</dimen>
</code>```

Body:
Changing the values in dimen.xml by overriding the values which are already set in the android support library.

 <dimen name="design_navigation_padding_top_default"
tools:override="true">0dp</dimen>
<dimen name="design_navigation_separator_vertical_padding"tools:override="true">0dp</dimen>
<dimen name="design_navigation_padding_bottom"tools:override="true">0dp</dimen>


问:
problems with new date
i have the following code which creates a new object:

function Person(firstname, lastname, birth) {
this.name = firstname + " " + lastname;
this.bdate = {
 year: birth.getFullYear(),
 day: birth.getDate(),
 month: "January,Febuary,March,April,May,June,July,August,September,October,November,December".split(",")[birth.getMonth() - 1],
 monthnumber: birth.getMonth(),
 }
this.age = new Date().getFullYear() - birth.getFullYear();
}

var foo = new Person("Jon", "Doe", new Date(1996, 12, 5));
console.log(foo);```
</div>
</div>
</p>

<p>when i do the following code:</p>

```var foo = new Person("Jon", "Doe", new Date(1996, 12, 5));
```

<p>it does exactly what it should do: create a new Person object.</p>

<p>BUT</p>

<p>this is what i get when do foo in console:</p>

```foo
Object { name: "Jon Doe", bdate: Object, age: 20 }
```

<p>when i click on bdate object
i get:</p>

```month: undefined
```

how to fix?
PLUS year is 1997 instead of 1996

EDIT:no it's not duplicate of getutcmonth, that problem is treating 12 AS 0, mine returns undefined for month

ANOTHER EDIT:huh, i guess it acually is duplicate :P still, can you help me?

答:
Month is zero-based. So your Array offset is wrong, and the month must be increased/decreased.

function Person(firstname, lastname, birth) {
this.name = firstname + " " + lastname;
this.bdate = {
 year: birth.getFullYear(),
 day: birth.getDate(),
 month: "January,Febuary,March,April,May,June,July,August,September,October,November,December".split(",")[birth.getMonth()],
 monthnumber: birth.getMonth()+1,
 }
this.age = new Date().getFullYear() - birth.getFullYear();
}

var foo = new Person("Jon", "Doe", new Date(1996, 11, 5));
console.log(foo);```

Title: problems with new date

Body:
i have the following code which creates a new object:

function Person(firstname, lastname, birth) {
this.name = firstname + " " + lastname;
this.bdate = {
 year: birth.getFullYear(),
 day: birth.getDate(),
 month: "January,Febuary,March,April,May,June,July,August,September,October,November,December".split(",")[birth.getMonth() - 1],
 monthnumber: birth.getMonth(),
 }
this.age = new Date().getFullYear() - birth.getFullYear();
}

var foo = new Person("Jon", "Doe", new Date(1996, 12, 5));
console.log(foo);

when i do the following code:

var foo = new Person("Jon", "Doe", new Date(1996, 12, 5));

it does exactly what it should do: create a new Person object.

BUT

this is what i get when do foo in console:

foo
Object { name: "Jon Doe", bdate: Object, age: 20 }

when i click on bdate object
i get:

month: undefined

how to fix?
PLUS year is 1997 instead of 1996

EDIT:no it's not duplicate of getutcmonth, that problem is treating 12 AS 0, mine returns undefined for month

ANOTHER EDIT:huh, i guess it acually is duplicate :P still, can you help me?


问:
Interprocess communication from SQL Server Project
I'm trying to create a SQL Server CLR user-defined function that connects to a 3rd-party service (hosted on the same server as the SQL Server instance).  Is there a way to get WCF named pipes or TCP to work in this situation?  Is there a better way to do this, if I provide an intermediary service?</p>

答:
Don't implement IPC in SQLCLR. The SQL server hosted CLR uses SQL threading primitives and you'll end up starving the SQL worker threads and schedulers.

Do all your IPC from a process outside SQL Server. If you need to communicate with this process from SQL jobs (from stored procedures and triggers) use in-database queuing, either by Tables as Queues or by Service Broker.

ContentLicense: CC BY-SA 2.5


问:
Python / Iterate over content of subprocess.check_output - line by line
I run the following in python:

```<code>list_m = subprocess.check_output(command, shell=True).strip('\n')
</code>```

When I print, it gives me the following content:

```<code>Name     region     sort
b30      us         large
b40      europe     medium
</code>```

I wish to iterate each line and print only the first word, so I will get for the first iteration b30, and for the second b40.

I try to loop over list_m:

```<code>for i in list_m
   print i
</code>```

and it gives me the following:

```<code>N
a
m
e

r
e
</code>```

and continue till medium.

How can I iterate the output each line, and print the first word?

答:
This will do your work

```<code>list(map(lambda x: x.split(' ')[0], list_m.split('\n'))
</code>```

Which is splitting you string line by line, then split by space and get first element.

Body:
I run the following in python:

list_m = subprocess.check_output(command, shell=True).strip('\n')

When I print, it gives me the following content:

Name     region     sort
b30      us         large
b40      europe     medium

I wish to iterate each line and print only the first word, so I will get for the first iteration b30, and for the second b40.

I try to loop over list_m:

for i in list_m
   print i

and it gives me the following:

N
a
m
e

r
e

and continue till medium.

How can I iterate the output each line, and print the first word?

Body:
This will do your work

list(map(lambda x: x.split(' ')[0], list_m.split('\n'))

Which is splitting you string line by line, then split by space and get first element.


问:
Difference between typealias and val for object
For a class, it is clear that we can not use val to refer to a type.

For example,

```<code>class LongName {
    ...
}

typealias A = LongName // OK
val B = LongName // compile error
val C = LongName() // compiles, but it refers to an instance, not the class itself
</code>```

However, for an (singleton) object, both compiles. In addition, both can be used for its members.

```<code>object LongName {
    val a = "123"
}

typealias A = LongName
val B = LongName

...

// In a function,
println(A.a) // compiles
println(B.a) // compiles
</code>```

What is difference between them?

答:
You can refer to the single instance of an object by its name, in this case, as LongName (this is why you can assign it to a val):

```<code>println(LongName.a)

val longName = LongName
println(longName.a)
</code>```

And you can also refer to its type as LongName (this is why you can create a typealias for it):

```<code>fun doStuff(longName: LongName) {}

typealias LN = LongName
fun doStuff(longName: LN) {}
</code>```

Body:
For a class, it is clear that we can not use val to refer to a type.

For example,

class LongName {
    ...
}

typealias A = LongName // OK
val B = LongName // compile error
val C = LongName() // compiles, but it refers to an instance, not the class itself

However, for an (singleton) object, both compiles. In addition, both can be used for its members.

object LongName {
    val a = "123"
}

typealias A = LongName
val B = LongName

...

// In a function,
println(A.a) // compiles
println(B.a) // compiles

What is difference between them?

Body:
You can refer to the single instance of an object by its name, in this case, as LongName (this is why you can assign it to a val):

println(LongName.a)

val longName = LongName
println(longName.a)

And you can also refer to its type as LongName (this is why you can create a typealias for it):

fun doStuff(longName: LongName) {}

typealias LN = LongName
fun doStuff(longName: LN) {}


问:
Android Chronometer - Save time
I´m using a Chronometer in my Android App. I can start it, stop it and continue counting after pushing the start button again:

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_projektbeschreibung, container, false);

    if (savedInstanceState != null){
        stoppedmillis = savedInstanceState.getLong(STATE_TIME);
        hh = savedInstanceState.getString(STATE_HH);
        mm = savedInstanceState.getString(STATE_MM);
        ss = savedInstanceState.getString(STATE_SS);

    }

    mChronometer = (Chronometer) rootView.findViewById(R.id.chronometer2);
    mChronometer.setText(hh + ":" + mm + ":" + ss);
    mChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        @Override
        public void onChronometerTick(Chronometer cArg) {
            long time = SystemClock.elapsedRealtime() - cArg.getBase() ;
            int h = (int) (time / 3600000);
            int m = (int) (time - h * 3600000) / 60000;
            int s = (int) (time - h * 3600000 - m * 60000) / 1000;
            hh = h < 10 ? "0" + h : h + "";
            mm = m < 10 ? "0" + m : m + "";
            ss = s < 10 ? "0" + s : s + "";
            cArg.setText(hh + ":" + mm + ":" + ss);

        }
    });

    ((Button) rootView.findViewById(R.id.startbutton)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //if first start
            if(stoppedmillis == 0) {
                mChronometer.setBase(SystemClock.elapsedRealtime());

            } else {//Point A
                long pausetime = (SystemClock.elapsedRealtime() - stoppedmillis);
                mChronometer.setBase(mChronometer.getBase() + pausetime);
            }
            mChronometer.start();

        }
    });

    ((Button) rootView.findViewById(R.id.stopbutton)).setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
        mChronometer.stop();
        stoppedmillis = SystemClock.elapsedRealtime();
        }
    });
</code>```

After a screen rotation (so the Activity restarts) the chronometer starts counting from the point of 00:00:00 again. My first try was to save the stoppedmillis with a onSaveInstanceState method like the following:

```<code> public void onSaveInstanceState(Bundle savedInstanceState){
    savedInstanceState.putLong(STATE_TIME, stoppedmillis);
    savedInstanceState.putString(STATE_HH, hh);
    savedInstanceState.putString(STATE_MM, mm);
    savedInstanceState.putString(STATE_SS,ss);

    super.onSaveInstanceState(savedInstanceState);
}
</code>```

Now, I can get the value of the stoppedmillis after a restart, but I don't know how to set the Base for the Chronometer with the help of the stoppedmillis. At Point A in the Code you can see how it works with stopping the Chronometer with a button but this part of code does not working after a screen rotation.

答:
I know that this is old. Although, I have created a simple application using a chronometer and done the following and it has kept counting across screen rotation. It is spot on with Andrew's original answer. Here is how I outlined it:

```<code>Chronometer mChronometer; // this is a global variable

@Override
protected void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     mChronometer = (Chronometer)findViewById(R.id.chronometer);

    if(savedInstanceState != null){

       mChronometer.setBase(savedInstanceState.getLong("ChronoTime"));
       mChronometer.start();
          }

    }
</code>```

Now set up onSaveInstanceState:

```<code>  @Override
  public void onSaveInstanceState (Bundle savedInstanceState){
     super.onSaveInstanceState(savedInstanceState);

     savedInstanceState.putLong("ChronoTime", mChronometer.getBase());
   }
</code>```

Title: Android Chronometer - Save time

Body:
I´m using a Chronometer in my Android App. I can start it, stop it and continue counting after pushing the start button again:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_projektbeschreibung, container, false);

    if (savedInstanceState != null){
        stoppedmillis = savedInstanceState.getLong(STATE_TIME);
        hh = savedInstanceState.getString(STATE_HH);
        mm = savedInstanceState.getString(STATE_MM);
        ss = savedInstanceState.getString(STATE_SS);

    }

    mChronometer = (Chronometer) rootView.findViewById(R.id.chronometer2);
    mChronometer.setText(hh + ":" + mm + ":" + ss);
    mChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
        @Override
        public void onChronometerTick(Chronometer cArg) {
            long time = SystemClock.elapsedRealtime() - cArg.getBase() ;
            int h = (int) (time / 3600000);
            int m = (int) (time - h * 3600000) / 60000;
            int s = (int) (time - h * 3600000 - m * 60000) / 1000;
            hh = h < 10 ? "0" + h : h + "";
            mm = m < 10 ? "0" + m : m + "";
            ss = s < 10 ? "0" + s : s + "";
            cArg.setText(hh + ":" + mm + ":" + ss);

        }
    });

    ((Button) rootView.findViewById(R.id.startbutton)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //if first start
            if(stoppedmillis == 0) {
                mChronometer.setBase(SystemClock.elapsedRealtime());

            } else {//Point A
                long pausetime = (SystemClock.elapsedRealtime() - stoppedmillis);
                mChronometer.setBase(mChronometer.getBase() + pausetime);
            }
            mChronometer.start();

        }
    });

    ((Button) rootView.findViewById(R.id.stopbutton)).setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
        mChronometer.stop();
        stoppedmillis = SystemClock.elapsedRealtime();
        }
    });

After a screen rotation (so the Activity restarts) the chronometer starts counting from the point of 00:00:00 again. My first try was to save the stoppedmillis with a onSaveInstanceState method like the following:

 public void onSaveInstanceState(Bundle savedInstanceState){
    savedInstanceState.putLong(STATE_TIME, stoppedmillis);
    savedInstanceState.putString(STATE_HH, hh);
    savedInstanceState.putString(STATE_MM, mm);
    savedInstanceState.putString(STATE_SS,ss);

    super.onSaveInstanceState(savedInstanceState);
}

Now, I can get the value of the stoppedmillis after a restart, but I don't know how to set the Base for the Chronometer with the help of the stoppedmillis. At Point A in the Code you can see how it works with stopping the Chronometer with a button but this part of code does not working after a screen rotation.

Body:
I know that this is old. Although, I have created a simple application using a chronometer and done the following and it has kept counting across screen rotation. It is spot on with Andrew's original answer. Here is how I outlined it:

Chronometer mChronometer; // this is a global variable

@Override
protected void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     mChronometer = (Chronometer)findViewById(R.id.chronometer);

    if(savedInstanceState != null){

       mChronometer.setBase(savedInstanceState.getLong("ChronoTime"));
       mChronometer.start();
          }

    }

Now set up onSaveInstanceState:

  @Override
  public void onSaveInstanceState (Bundle savedInstanceState){
     super.onSaveInstanceState(savedInstanceState);

     savedInstanceState.putLong("ChronoTime", mChronometer.getBase());
   }


问:
UML about packages
Ok, I'm preparing an exam and I need the answer to this question, that I couldn't find in the book. Hope that you can help me.

What is needed for the A package to access the B package? (1 of the 2 answers is the right one)

A will import B and B will export the elements establishing the visibilities that fit better

We just need an <<import>> from A to B

Thank you very much

答:
You will need an <<import>> as stated in the UML spec on p. 32 in an example:

In Figure 7.9, a number of PackageImports are shown. The public members of Types are imported into ShoppingCart and then further imported into WebShop. However, the members of Auxiliary are only privately imported by ShoppingCart and cannot be referenced using unqualified names from WebShop.

Title: UML about packages


问:
XAMPP - Server and client cannot communicate
I have written a very simple PHP program for adding data to MySQL RDBMS. The file works when I upload it to my hosting server.

I am using XAMPP Control Panel v3.2.2 for testing. In it I am using Apache and MySQL. When I try to submit the form I am getting following error
Cannot POST /connect.php.

While opening localhost/test/connect.php through a browser, it shows following error Fatal error: Function name must be a string in ..\xampp\htdocs\test\connect.php on line 7

Here's the line 7 $firstName = $_POST('firstName');

What to do to test my file using XAMPP Control Panel before uploading them to server?

答: I was accessing the PHP with Brackets. So, it ran on a server independent from Apache within XAMPP. So, if you are using XAMPP make sure you place your files in htdocs and the path in your browser's address bar should look something like localhost/folder(within htdocs)/file.html. If you are facing the stated problem and this is not the case then follow above answer and do read the comments.


问:
How can I use SeekBar's OnSeekBarChangeListener to seek to a specific point in a MediaPlayer object?
I have some Android code to stream an audio file from the internet and play the stream after 10 seconds.

I am using a SeekBar to view the buffering status and playing status. I want to play the audio starting from the middle of the buffered stream. For that, I move the SeekBar point to the middle, but I cannot play the audio from the middle; it will go back and start from the beginning. How can I get the seeked position and how can I play the audio from that particular position?

Here is my SeekBar code. How can I make this code use the OnSeekBarChangeListener properly?

```<code>seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
        // TODO Auto-generated method stub
        if (arg2 && mediaPlayer.isPlaying()) {
            //myProgress = oprogress;
            arg1=mediaPlayer.getCurrentPosition();
            mediaPlayer.seekTo(arg1);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }

});
</code>```

答:
```<code>arg1=mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(arg1);
</code>```

You are forcing the player to seek to the current position, and not to the positon retuned by the Seekbar

Remove the line: arg1=mediaPlayer.getCurrentPosition(); and it should work. Of course after MediaPlayer.prepare() set SeekBar.setMax(MediaPlayer.getDuration()), so seeking will be accurate.

Body:
I have some Android code to stream an audio file from the internet and play the stream after 10 seconds.

I am using a SeekBar to view the buffering status and playing status. I want to play the audio starting from the middle of the buffered stream. For that, I move the SeekBar point to the middle, but I cannot play the audio from the middle; it will go back and start from the beginning. How can I get the seeked position and how can I play the audio from that particular position?

Here is my SeekBar code. How can I make this code use the OnSeekBarChangeListener properly?

seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
        // TODO Auto-generated method stub
        if (arg2 && mediaPlayer.isPlaying()) {
            //myProgress = oprogress;
            arg1=mediaPlayer.getCurrentPosition();
            mediaPlayer.seekTo(arg1);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
    }

});

Body:
arg1=mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(arg1);

You are forcing the player to seek to the current position, and not to the positon retuned by the Seekbar

Remove the line: arg1=mediaPlayer.getCurrentPosition(); and it should work. Of course after MediaPlayer.prepare() set SeekBar.setMax(MediaPlayer.getDuration()), so seeking will be accurate.


问:
keep everything upto last column but remove character before last space in last column
How can I remove all characters in last column upto last space?

```<code>20160101|193.150.22.1|57381|0.0.0.0/0|57381 42708 29468 41136 41136 41136 3292
</code>```

The result should be as below:

```<code>20160101|193.150.22.1|57381|0.0.0.0/0|3292
</code>```

Body:
How can I remove all characters in last column upto last space?

20160101|193.150.22.1|57381|0.0.0.0/0|57381 42708 29468 41136 41136 41136 3292

The result should be as below:

20160101|193.150.22.1|57381|0.0.0.0/0|3292

Body:
You can achieve this for instance with sed:

echo "20160101|193.150.22.1|57381|0.0.0.0/0|57381 42708 29468 41136 41136 41136 3292" | sed -e 's/\(|.*|\).* \(.*\)/\1\2/'

gives:

20160101|193.150.22.1|57381|0.0.0.0/0|3292

EDIT:

If you want to get the result with only bash-internal functionality, you can use bash substring removal

s="20160101|193.150.22.1|57381|0.0.0.0/0|57381 42708 29468 41136 41136 41136 3292"
echo "${s%|*}|${s##* }"

also gives the desired result.


问:
Bit shift in array and write score to another array
I write method to bit shift by one in array and save to second array. Let me explain on below example:

```<code> unsigned int firstNumber[2]  = { 0x00000001, 0x8FFFFFFF };
 unsigned int resultNumber[2];
</code>```

And result should be:

```<code>unsigned int resultNumber[2] = { 0x00000000, 0xC7FFFFFF };
</code>```

Below this is my function:

```<code>void bitShiftByOneInRight_1(unsigned int firstNumber[2], unsigned int resultNumber[2])
{
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {
        resultNumber[i] = 0;
        //  example        11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        resultNumber[i] = firstNumber[i] >> 1;
        resultNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled  = lastBit;
    }
}
</code>```

I get answer as the same array firstNumber[2]:

```<code>unsigned int resultNumber[2] = { 0x00000001, 0x8FFFFFFF };
</code>```

Simple example, we have array:
 [0b00000001, 0b01111111] then answer should be
 [0b00000000, 0b10111111]

Furthermore when function is this form, which mean use one argument as input and output method, work correctly:

```<code>void bitShiftByOneInRight(unsigned int firstNumber[2]) {
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {

        //  example         11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        firstNumber[i] = firstNumber[i] >> 1;
        firstNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled = lastBit;
    }

}
</code>```

Anyone know what I make wrong?
Each answer is welcome for me! Thanks

答:
Something like:

```<code>#include <stdio.h>

void shift_right(unsigned *dst, unsigned *src, size_t len) {
  if (len == 0) return;
  for (size_t i = len - 1; i > 0; i--)
    dst[i] = (src[i] >> 1) + (src[i - 1] & 1u) * ~(~0u >> 1);
  dst[0] = src[0] >> 1;
}

int main(void) {
  unsigned int firstNumber[]  = { 0x00000001u, 0x8FFFFFFFu }, secondNumber[2];
  shift_right(secondNumber, firstNumber, 2);
  printf("%08x, %08x", secondNumber[0], secondNumber[1]);
}
</code>```

This can be called with source and destination as the same array.

It works for all widths of unsigned.

Although some will question using multiplication, it turns out gcc does a great job of optimizing this to a shift and add that are essentially the same as vicatcu@'s, but auto-adjusted for width.

Body:
I write method to bit shift by one in array and save to second array. Let me explain on below example:

 unsigned int firstNumber[2]  = { 0x00000001, 0x8FFFFFFF };
 unsigned int resultNumber[2];

And result should be:

unsigned int resultNumber[2] = { 0x00000000, 0xC7FFFFFF };

Below this is my function:

void bitShiftByOneInRight_1(unsigned int firstNumber[2], unsigned int resultNumber[2])
{
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {
        resultNumber[i] = 0;
        //  example        11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        resultNumber[i] = firstNumber[i] >> 1;
        resultNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled  = lastBit;
    }
}

I get answer as the same array firstNumber[2]:

unsigned int resultNumber[2] = { 0x00000001, 0x8FFFFFFF };

Simple example, we have array:
 [0b00000001, 0b01111111] then answer should be
 [0b00000000, 0b10111111]

Furthermore when function is this form, which mean use one argument as input and output method, work correctly:

void bitShiftByOneInRight(unsigned int firstNumber[2]) {
    unsigned int lastBitEnabled = 0;
    unsigned int mask = 1;

    for (unsigned int i = 0; i < 2; i++) {

        //  example         11001101 & 00000001 for uint8_t
        unsigned int lastBit = (firstNumber[i] & mask) << (sizeof(unsigned int)*8 - 1);

        firstNumber[i] = firstNumber[i] >> 1;
        firstNumber[i] = firstNumber[i] | lastBitEnabled;
        lastBitEnabled = lastBit;
    }

}

Anyone know what I make wrong?
Each answer is welcome for me! Thanks

Body:
Something like:

#include <stdio.h>

void shift_right(unsigned *dst, unsigned *src, size_t len) {
  if (len == 0) return;
  for (size_t i = len - 1; i > 0; i--)
    dst[i] = (src[i] >> 1) + (src[i - 1] & 1u) * ~(~0u >> 1);
  dst[0] = src[0] >> 1;
}

int main(void) {
  unsigned int firstNumber[]  = { 0x00000001u, 0x8FFFFFFFu }, secondNumber[2];
  shift_right(secondNumber, firstNumber, 2);
  printf("%08x, %08x", secondNumber[0], secondNumber[1]);
}

This can be called with source and destination as the same array.

It works for all widths of unsigned.

Although some will question using multiplication, it turns out gcc does a great job of optimizing this to a shift and add that are essentially the same as vicatcu@'s, but auto-adjusted for width.


问:
How can I erase the window background in an owner drawn static control?
I am currently developing a kind of "WinMerge" clone, and currently I am trying to implement a custom scrollbar which should later represent both compared files as a rectangle in the background each.

This is what it looks like at the startup:

However, after scrolling around a little bit, this is what I end up with:

As you can clearly see, only those parts look correct which I explicitely paint over in my paint routine:

```<code>void LocationPane::OnPaint(CDCHandle dc)
{
    DefWindowProc();

    dc = GetDC();

    DrawLocationPaneFigures(dc);
}
</code>```

This is how my control is configured in my .rc file:

```<code>CONTROL         "",IDC_LOCATIONPANE,"Static",SS_OWNERDRAW | SS_NOTIFY | WS_BORDER | WS_GROUP,7,21,91,541
</code>```

As you can see, it is an owner drawn control.

How can I erase the background for this control while repainting it?

答:
A static control with SS_OWNERDRAW style receives a WM_DRAWITEM message when it needs to be redrawn.

So first you need to replace your OnPaint() handler by a handler for WM_DRAWITEM. Instead of calling GetDC() use the device context supplied to you in the DRAWITEMSTRUCT.

To erase the background it's generally best to do it as part of the regular painting code to reduce flickering (by calling FillRect() for instance).

I suggest to always draw the whole client area of your control. Then you may handle WM_ERASEBKGND to return TRUE without calling DefWindowProc() to reduce flickering even more.

Body:
I am currently developing a kind of "WinMerge" clone, and currently I am trying to implement a custom scrollbar which should later represent both compared files as a rectangle in the background each.

This is what it looks like at the startup:

However, after scrolling around a little bit, this is what I end up with:

As you can clearly see, only those parts look correct which I explicitely paint over in my paint routine:

void LocationPane::OnPaint(CDCHandle dc)
{
    DefWindowProc();

    dc = GetDC();

    DrawLocationPaneFigures(dc);
}

This is how my control is configured in my .rc file:

CONTROL         "",IDC_LOCATIONPANE,"Static",SS_OWNERDRAW | SS_NOTIFY | WS_BORDER | WS_GROUP,7,21,91,541

As you can see, it is an owner drawn control.

How can I erase the background for this control while repainting it?


问:
Javascript - Better Alternate to Recursive call
I have this following problem.
I need to calculate a number x based on time t, x would be represented as M(t).
We have the following

M(0) = 1

M(1) = 1

M(2) = 2

M(2t) = M(t) + M(t + 1) + t (for t > 1)

M(2t + 1) = M(t - 1) + M(t) + 1 (for t >= 1)

With that being said the first thing i had in mind to implement this is by using recursion

```<code>function CalculateForTime(t) {
    if (t == 0 || t == 1) {
        return 1;
    }
    else if (t == 2) {
        return 2;
    }
    else if (t % 2 == 0) {
        t = t / 2;
        return CalculateForTime(t) + CalculateForTime(t + 1) + t;
    }
    else {
        t = (t - 1) / 2;
        return CalculateForTime(t - 1) + CalculateForTime(t) + 1;
    }
}
</code>```

This works however it breaks when running on a large number t for example 1^20

I tried looking into tail call recursion or substituting the recursion approach to an iteration approach but couldn't really figure it out.

If tail recursion or iteration is the way to go then please I need help on converting this. If not then I'm open to different methods on making this more optimized.

Thank you,
Omar.

答:
You could use memoization to avoid recalculating the same values again and again. See https://addyosmani.com/blog/faster-javascript-memoization/

This is the same as what others suggested, except that it separates the algorithm from the caching of values.

```<code>function memoize(func){
    var cache = {};
    return function( arg ){
         if(arg in cache) {
             return cache[arg];
         } else {
             return cache[arg] = func( arg );
         }
     }
  }

  // Overwrite with a function that remember previous results
  CalculateForTime = memoize(CalculateForTime);
</code>```

Pardon any typos, answered from phone

Body:
I have this following problem.
I need to calculate a number x based on time t, x would be represented as M(t).
We have the following

M(0) = 1

M(1) = 1

M(2) = 2

M(2t) = M(t) + M(t + 1) + t (for t > 1)

M(2t + 1) = M(t - 1) + M(t) + 1 (for t >= 1)

With that being said the first thing i had in mind to implement this is by using recursion

function CalculateForTime(t) {
    if (t == 0 || t == 1) {
        return 1;
    }
    else if (t == 2) {
        return 2;
    }
    else if (t % 2 == 0) {
        t = t / 2;
        return CalculateForTime(t) + CalculateForTime(t + 1) + t;
    }
    else {
        t = (t - 1) / 2;
        return CalculateForTime(t - 1) + CalculateForTime(t) + 1;
    }
}

This works however it breaks when running on a large number t for example 1^20

I tried looking into tail call recursion or substituting the recursion approach to an iteration approach but couldn't really figure it out.

If tail recursion or iteration is the way to go then please I need help on converting this. If not then I'm open to different methods on making this more optimized.

Thank you,
Omar.

Body:
You could use memoization to avoid recalculating the same values again and again. See https://addyosmani.com/blog/faster-javascript-memoization/

This is the same as what others suggested, except that it separates the algorithm from the caching of values.

function memoize(func){
    var cache = {};
    return function( arg ){
         if(arg in cache) {
             return cache[arg];
         } else {
             return cache[arg] = func( arg );
         }
     }
  }

  // Overwrite with a function that remember previous results
  CalculateForTime = memoize(CalculateForTime);

Pardon any typos, answered from phone


问:
Where is cached RDD stored (i.e. in a distributed way or on a single node)?
When we cache an RDD in Spark, is it then stored in a distributed way or on a single node? In which systems memory is it stored?</p>

答: The data remains distributed and is not stored in a single node after a cache operation. The cache or persists option doesnt change/affect the distribution of an RDD. the distribution  per and post cache operation remains the same.


问:
How to split this String using mysql Query?
I have a table called "article"

```<code>ID       Date
1        3rd June 2017
2        2nd April 2016
3        21st June 2017
4        31st December 2015
</code>```

and I want to find all the ID's where Date has June in it ,Therefore Result should be

```<code>ID
1
3
</code>```

P.S -I tried doing this but I am stuck at this point , here is my Query

```<code>SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(Date, ' ', 2), ' ', -1) as month
from article
where article.month='June'
</code>```

答:
You can use date functions in MySQL if you intend to make any more elaborate date comparisons later on:

```<code>select id from article where MONTH(STR_TO_DATE(Date,'%D %M %Y'))=6
</code>```

where 6 corresponds to the 6th month (june).

Body:
I have a table called "article"

ID       Date
1        3rd June 2017
2        2nd April 2016
3        21st June 2017
4        31st December 2015

and I want to find all the ID's where Date has June in it ,Therefore Result should be

ID
1
3

P.S -I tried doing this but I am stuck at this point , here is my Query

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(Date, ' ', 2), ' ', -1) as month
from article
where article.month='June'

Body:
You can use date functions in MySQL if you intend to make any more elaborate date comparisons later on:

select id from article where MONTH(STR_TO_DATE(Date,'%D %M %Y'))=6

where 6 corresponds to the 6th month (june).


问:
i want to link one page which is inside the folder to another page which is outside the folder
enter image description here

I really need your help here because this is confusing me now. i am in the customesignup.php inside the customer folder. Now i want to link this page to index.php which is outside the customer folder. And that page of index.php is not in any folder it is just hanging outside of the customer folder as you can see in the above picture. help please. .

答: linktext as relative path or as absolute path if this is web root folder linktext

Body: <a href="../index.php>linktext</a> as relative path or as absolute path if this is web root folder <a href="/index.php>linktext</a>


问:
how to use one insert command with different data types
I'm working on a web application for a subject my question is: I have a file to use the insert command but I have different thing I want to insert, I want to insert users in a table and schedule appointments in another, do i have to make two different files for two commands or is there an easier way to do it?</p>

答:
You can easily do it in one file.That's not a big deal.I think you want to say something else but you are saying something else.By the way,as per your question,
there will be two

```<code>mysqli_query()
</code>```

One for for inserting users in a table and other for scheduling appointments in the same file.

Body:
You can easily do it in one file.That's not a big deal.I think you want to say something else but you are saying something else.By the way,as per your question,
there will be two

mysqli_query()

One for for inserting users in a table and other for scheduling appointments in the same file.


问:
Pymysql insert foreign key error
My table weather

```<code>create table weather (
            time timestamp default current_timestamp on update current_timestamp,
            id smallint,
            tpr float(3,1),
            wet float(3,1),
            uv tinyint(2),
            foreign key (id) references database.station(pk));
</code>```

Table station

```<code>CREATE TABLE station(
pk SMALLINT(5) NOT NULL AUTO_INCREMENT,
name VARCHAR(5),
lng DOUBLE(10,6),
lat DOUBLE(10,6),
PRIMARY KEY(pk));
</code>```

When I use the pymysql to insert the id to the weather.

I made the two functions below:

```<code>conn = pymysql.connect()#ignore the details
def get_id_from_station():
    sql = """SELECT pk FROM  station """
    conn.cursor().execute(sql)
    id = conn.cursor().fetchone()[0]
    weather_saved(id)

def weather_saved(id):
    #get the time,tpr,wet,uv value
    sql = """INSERT INTO weather (time,id,tpr,wet,uv) VALUES (%s,%s,%s,%s,%s)"""
    db.execute(sql, (time, id,tpr, wet, uv))
</code>```

But the weather table didn't update.

What's the wrong?

答:
Here is code that updates the weather table. I used python 2.7 but it should be the same. I think your problem might be that you didn't commit the insert. </p>

```<code>import pymysql

conn = pymysql.connect(...)

def get_id_from_station():
    sql = """SELECT pk FROM  station """

    cursor = conn.cursor()
    cursor.execute(sql)
    row = cursor.fetchone()
    weather_saved(row)

import time
import datetime

def weather_saved(id):
    #get the time,tpr,wet,uv value
    sql = """INSERT INTO weather (time,id,tpr,wet,uv) VALUES (%s,%s,%s,%s,%s)"""
    cursor = conn.cursor()
    ts = time.time()
    timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    cursor.execute(sql, (timestamp, id,7, 7, 7))
    conn.commit()

get_id_from_station()
</code>```

Title: Pymysql insert foreign key error

Body:
My table weather

create table weather (
            time timestamp default current_timestamp on update current_timestamp,
            id smallint,
            tpr float(3,1),
            wet float(3,1),
            uv tinyint(2),
            foreign key (id) references database.station(pk));

Table station

CREATE TABLE station(
pk SMALLINT(5) NOT NULL AUTO_INCREMENT,
name VARCHAR(5),
lng DOUBLE(10,6),
lat DOUBLE(10,6),
PRIMARY KEY(pk));

When I use the pymysql to insert the id to the weather.

I made the two functions below:

conn = pymysql.connect()#ignore the details
def get_id_from_station():
    sql = """SELECT pk FROM  station """
    conn.cursor().execute(sql)
    id = conn.cursor().fetchone()[0]
    weather_saved(id)

def weather_saved(id):
    #get the time,tpr,wet,uv value
    sql = """INSERT INTO weather (time,id,tpr,wet,uv) VALUES (%s,%s,%s,%s,%s)"""
    db.execute(sql, (time, id,tpr, wet, uv))

But the weather table didn't update.

What's the wrong?

Body:
Here is code that updates the weather table. I used python 2.7 but it should be the same. I think your problem might be that you didn't commit the insert.

import pymysql

conn = pymysql.connect(...)

def get_id_from_station():
    sql = """SELECT pk FROM  station """

    cursor = conn.cursor()
    cursor.execute(sql)
    row = cursor.fetchone()
    weather_saved(row)

import time
import datetime

def weather_saved(id):
    #get the time,tpr,wet,uv value
    sql = """INSERT INTO weather (time,id,tpr,wet,uv) VALUES (%s,%s,%s,%s,%s)"""
    cursor = conn.cursor()
    ts = time.time()
    timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    cursor.execute(sql, (timestamp, id,7, 7, 7))
    conn.commit()

get_id_from_station()


问:
How to properly use Dispose in Unit Of Work Pattern?
I know this question has been asked several times before, but I couldn't get the answer I was looking for.
So, I've implemented the Repository (generic) and UOW pattern, so I can access my DB using EF. Here's part of the UnitOfWork class:

```<code>    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                entities.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
</code>```

The question is: Who is calling the void Dispose method?? I've seen no example of the usage of that method.

this it the upper part of the Unit Of Work class:

```<code>    private BDEntities entities = null;

    public UnitOfWork()
    {
        if (entities == null)
        {
            entities = new BDEntities();
        }
    }
</code>```

Is this right? should I use "Using"? and if yes, than why do I need the Dispose method?

Can you give me an example of a proper and simple usage?

Thank you,
Rotem

答:
The reason why you have not come across any examples about who calls the dispose is because UoW is usually used together with dependency injection and a dependency injection container, like Autofac. And in this case, it is the responsibility of this container to create objects and dispose of them later. Granted, this is not the only way UoW can be used, but it is a common pattern.

As for answering your question: I think the approach that you are taking is more or less right. The UoW class should be the one that wraps the context, so it should be the one to dispose it as well (essentially, the DbContext itself is a UoW).

You can simplify the Dispose method though. Since you do not have any unmanaged and not IDisposable resources (like pointers), it is completely enough to call the Dispose method of the context in the Dispose method of the UoW:

```<code> public void Dispose()
 {
   entities.Dispose();
 }
</code>```

(No other Dispose method, no SuppressFinalize calls).

And yes, you should absolutely use using. And that's exactly why you need a the Dispose() method; only objects that are of a type that implements IDisposable can be used in a using block. If you write a using block, it basically translates to a try-finally block; your code from inside the using block goes into the try block, and in the finally, the Dispose() is called.

Body:
I know this question has been asked several times before, but I couldn't get the answer I was looking for.
So, I've implemented the Repository (generic) and UOW pattern, so I can access my DB using EF. Here's part of the UnitOfWork class:

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                entities.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

The question is: Who is calling the void Dispose method?? I've seen no example of the usage of that method.

this it the upper part of the Unit Of Work class:

    private BDEntities entities = null;

    public UnitOfWork()
    {
        if (entities == null)
        {
            entities = new BDEntities();
        }
    }

Is this right? should I use "Using"? and if yes, than why do I need the Dispose method?

Can you give me an example of a proper and simple usage?

Thank you,
Rotem

Body:
The reason why you have not come across any examples about who calls the dispose is because UoW is usually used together with dependency injection and a dependency injection container, like Autofac. And in this case, it is the responsibility of this container to create objects and dispose of them later. Granted, this is not the only way UoW can be used, but it is a common pattern.

As for answering your question: I think the approach that you are taking is more or less right. The UoW class should be the one that wraps the context, so it should be the one to dispose it as well (essentially, the DbContext itself is a UoW).

You can simplify the Dispose method though. Since you do not have any unmanaged and not IDisposable resources (like pointers), it is completely enough to call the Dispose method of the context in the Dispose method of the UoW:

 public void Dispose()
 {
   entities.Dispose();
 }

(No other Dispose method, no SuppressFinalize calls).

And yes, you should absolutely use using. And that's exactly why you need a the Dispose() method; only objects that are of a type that implements IDisposable can be used in a using block. If you write a using block, it basically translates to a try-finally block; your code from inside the using block goes into the try block, and in the finally, the Dispose() is called.


问:
In Idris, is "Eq a" a type, and can I supply a value for it?
In the following, example1 is standard syntax (as documented), with Eq a as a constraint. In example2, I specify Eq a directly as the type of a parameter, and the compiler accepts it. However it is unclear what I can specify as a value of that type. For a specific type a, eg Nat, I assume it would make sense to somehow specify an implementation of Eq Nat, either the default implementation, or some other named implementation.

```<code>%default total

example1: Eq a => (x : a) -> (y : a) -> Type
example1 {a} x y = ?example1_rhs

example1b: Eq a => (x : a) -> (y : a) -> Type
example1b {a} x y = x == y = True

example2: (a : Type) -> Eq a -> (x : a) -> (y : a) -> Type
example2 a eqa x y = ?example2_rhs

example2b: (a : Type) -> Eq a -> (x : a) -> (y : a) -> Type
example2b a eqa x y = x == y = True

eq_nat : Eq Nat
eq_nat = ?eq_nat_rhs

example_of_example2 : Type
example_of_example2 = example2 Nat eq_nat 3 3
</code>```

Resulting holes:

```<code>- + Main.example1_rhs [P]
 `--                  a : Type
                      x : a
                      y : a
             constraint : Eq a
     --------------------------
      Main.example1_rhs : Type

- + Main.example2_rhs [P]
 `--                  a : Type
                    eqa : Eq a
                      x : a
                      y : a
     --------------------------
      Main.example2_rhs : Type

- + Main.eq_nat_rhs [P]
 `-- Eq Nat
</code>```

As far as I can tell, I can't actually use example2b as a function unless I have some way to specify a value for the second parameter of type Eq a.

There are situations where it would be genuinely useful to be able to apply an interface constraint to the value of a parameter (as opposed to the type of a parameter), so I'm hoping that this is a valid feature of Idris.

答:
You could use named implementations:

[eq_nat] Eq Nat where { ... }
...
example_of_example2 : Type
example_of_example2 = example2 Nat eq_nat 3 3
```

<p>A useful application of named implementations are defining multiple implementation of <code>Monoid</code>:</p>

<pre class="lang-idris prettyprint-override"><code>[PlusNatSemi] Semigroup Nat where
  (<+>) x y = x + y

[MultNatSemi] Semigroup Nat where
  (<+>) x y = x * y

[PlusNatMonoid] Monoid Nat using PlusNatSemi where
  neutral = 0

[MultNatMonoid] Monoid Nat using MultNatSemi where
  neutral = 1
</code>```

To comment : To get the default instance

getEq : (a : Type) -> {auto inst : Eq a} -> Eq a
getEq a {inst} = inst
```

<p>Then you can have your default instance:</p>

<pre class="lang-idris prettyprint-override"><code>getEq (List Nat) -- => implementation of Eq...
</code>```

Body:
In the following, example1 is standard syntax (as documented), with Eq a as a constraint. In example2, I specify Eq a directly as the type of a parameter, and the compiler accepts it. However it is unclear what I can specify as a value of that type. For a specific type a, eg Nat, I assume it would make sense to somehow specify an implementation of Eq Nat, either the default implementation, or some other named implementation.

%default total

example1: Eq a => (x : a) -> (y : a) -> Type
example1 {a} x y = ?example1_rhs

example1b: Eq a => (x : a) -> (y : a) -> Type
example1b {a} x y = x == y = True

example2: (a : Type) -> Eq a -> (x : a) -> (y : a) -> Type
example2 a eqa x y = ?example2_rhs

example2b: (a : Type) -> Eq a -> (x : a) -> (y : a) -> Type
example2b a eqa x y = x == y = True

eq_nat : Eq Nat
eq_nat = ?eq_nat_rhs

example_of_example2 : Type
example_of_example2 = example2 Nat eq_nat 3 3

Resulting holes:

- + Main.example1_rhs [P]
 `--                  a : Type
                      x : a
                      y : a
             constraint : Eq a
     --------------------------
      Main.example1_rhs : Type

- + Main.example2_rhs [P]
 `--                  a : Type
                    eqa : Eq a
                      x : a
                      y : a
     --------------------------
      Main.example2_rhs : Type

- + Main.eq_nat_rhs [P]
 `-- Eq Nat

As far as I can tell, I can't actually use example2b as a function unless I have some way to specify a value for the second parameter of type Eq a.

There are situations where it would be genuinely useful to be able to apply an interface constraint to the value of a parameter (as opposed to the type of a parameter), so I'm hoping that this is a valid feature of Idris.

Body:
You could use named implementations:

[eq_nat] Eq Nat where { ... }
...
example_of_example2 : Type
example_of_example2 = example2 Nat eq_nat 3 3

A useful application of named implementations are defining multiple implementation of Monoid:

[PlusNatSemi] Semigroup Nat where
  (<+>) x y = x + y

[MultNatSemi] Semigroup Nat where
  (<+>) x y = x * y

[PlusNatMonoid] Monoid Nat using PlusNatSemi where
  neutral = 0

[MultNatMonoid] Monoid Nat using MultNatSemi where
  neutral = 1

To comment : To get the default instance

getEq : (a : Type) -> {auto inst : Eq a} -> Eq a
getEq a {inst} = inst

Then you can have your default instance:

getEq (List Nat) -- => implementation of Eq...


问:
Bootstrap Input-Group Multiple Textbox Widths
I have 2 textboxes in an input-group, seperated by an input-group-addon span. My problem is, I want textbox 1 to be wider than textbox 2. Textbox 1 is supposed to be the phone number (larger) and textbox 2 is an extension number (slimmer). I have a fiddle below:

https://jsfiddle.net/Lhhj7f5d/

```<code><div class="col-xs-6">
 <div class="input-group">
  <input class="form-control" type="tel" placeholder="Phone Number" />
  <span class="input-group-addon">Ext.</span>
  <input class="form-control" type="text" placeholder="Extension"/>
 </div>
</div>
</code>```

Thanks!

答:
You can set a width to your form

  <input class="form-control" type="tel" placeholder="Phone Number" />
  Ext.
  <input class="form-control" type="text" placeholder="Extension" style="width : 20px;"/>

```

or use css

Body:
I have 2 textboxes in an input-group, seperated by an input-group-addon span. My problem is, I want textbox 1 to be wider than textbox 2. Textbox 1 is supposed to be the phone number (larger) and textbox 2 is an extension number (slimmer). I have a fiddle below:

https://jsfiddle.net/Lhhj7f5d/

  <input class="form-control" type="tel" placeholder="Phone Number" />
  Ext.
  <input class="form-control" type="text" placeholder="Extension"/>

Thanks!

Body:
You can set a width to your form

<div class="col-xs-6">
 <div class="input-group">
  <input class="form-control" type="tel" placeholder="Phone Number" />
  <span class="input-group-addon">Ext.</span>
  <input class="form-control" type="text" placeholder="Extension" style="width : 20px;"/>
 </div>
</div>

or use css


问:
Method is not called, but no error appears
I'm writing my first simple StarCraft Broodwar AI and I have a problem with my 2 custom classes. The idea is to have an array of reservations that stores temporary reservations of minerals and vespene gas, so I can create a reservation when ordering a worker to build a structure so the other workers and buildings don't spend the resources in the meantime until the worker arrives at the building site. The problem is, when the standard BWAPI event listener "onFrame" launches the countDownReservations() method, the individual array rows are not called at all and the rest of the AI isn't processed at all and is effectively broken.

So when I start the bot, nothing happens except for the console printing out "bingo" and
"0 started"
over and over again for every frame.
The line "bingo1" doesn't even appear once, so somehow the program crashes when calling this method "countDown()". Sadly it doesn't give an error at all and there are no pre-compiler warnings whatsoever.

Can anyone explain what's wrong?

Console output:

Java project:

Starcraft bot:

```<code>@Override
public void onFrame() {
    System.out.println("bingo");
    resourceReservations.countDownReservations();

public class ResourceReservations {

    private ResourceReservation[] resourceReservationArray = new ResourceReservation[15];

    public ResourceReservations() {

    }

    // looks through the array for a reservation with 0 time left on it (which should thus be empty)
    // - and overwrites the empty reservation with a new one
    // if no empty reservation can be found, nothing happens and a warning is output to the console
    public void addReservation(int minerals, int gas, int timer) {
        for (int loopCounter = 0; loopCounter < 15; loopCounter++) {
            if (resourceReservationArray[loopCounter].getReservationTime() == 0) {
                resourceReservationArray[loopCounter].setMinerals(minerals);
                resourceReservationArray[loopCounter].setGas(gas);
                resourceReservationArray[loopCounter].setTimerInSeconds(timer);
                break;
            }
        }
        System.out.println("Failed to add a reservation, no free space in array!");
    }

    // sums up all reserved minerals in the array
    public int reservedMinerals() {
        int reservedMinerals = 0;
        for (int loopCounter = 0; loopCounter < 15; loopCounter++) {
            reservedMinerals = reservedMinerals + resourceReservationArray[loopCounter].getMinerals();
        }
        return reservedMinerals;
    }

    // sums up all reserved vespene gas in the array
    public int reservedVespeneGas() {
        int reservedVespeneGas = 0;
        for (int loopCounter = 0; loopCounter < 15; loopCounter++) {
            reservedVespeneGas = reservedVespeneGas + resourceReservationArray[loopCounter].getGas();
        }
        return reservedVespeneGas;
    }

    // count down all the reservations
    public void countDownReservations() {
        for (int loopNumber = 0; loopNumber < 15; loopNumber++) {
            System.out.println(loopNumber + " started");
            resourceReservationArray[loopNumber].countDown();
            System.out.println(loopNumber + " completed");
        }
    }
}

public class ResourceReservation {

    private int minerals = 0;

    private int vespeneGas = 0;

    private int reservationTime = 0;

    public ResourceReservation() {

    }

    // read status - - - - - - - - - - - - - - - - -
    public int getGas() {
        return vespeneGas;
    }
    public int getMinerals() {
        return minerals;
    }
    public int getReservationTime() {
        return reservationTime;
    }

    // update status - - - - - - - - - - - - - - - -
    public void setGas(int newGas) {
        vespeneGas      = newGas;
    }
    public void setMinerals(int newMinerals) {
        minerals        = newMinerals;
    }
    public void setTimerInFrames(int newTimer) {
        reservationTime = newTimer;
    }
    public void setTimerInSeconds(int newTimer) {
        reservationTime = newTimer * 60;
    }

    // clear  - - -  - - - - - - - - - - - - - - - -
    public void initialize() {
        minerals        = 0;
        vespeneGas      = 0;
        reservationTime = 0;
    }

    // count down - -  - - - - - - - - - - - - - - -
    public void countDown() {
        System.out.println("bingo1");
        if (reservationTime > 0) {
            System.out.println("bingo2");
            reservationTime = reservationTime - 1;
            System.out.println("bingo3");
            if (reservationTime == 0) {
                System.out.println("bingo4");
                initialize();
            }
        }
    }
}
</code>```

答:
Ah I just solved it, the problem was that the 15 Reservations didn't exist

Adding this loop to the head of the Reservations class solved the problem:

```<code>    for (int x = 0; x < 15; x++) {
        resourceReservationArray[x] = new ResourceReservation();
    }
</code>```

public class ResourceReservations {

```<code>private ResourceReservation[] resourceReservationArray = new ResourceReservation[15];

public ResourceReservations() {
    for (int x = 0; x < 15; x++) {
        resourceReservationArray[x] = new ResourceReservation();
    }
}
</code>```

Thanks for putting up with me and reminding me of debugging. Hadn't done that in java yet. ^^

Edit: Oh and by the way, I reduced the number of reservations to 5 and haven't seen it overflow yet in about 20 games.

Body:
I'm writing my first simple StarCraft Broodwar AI and I have a problem with my 2 custom classes. The idea is to have an array of reservations that stores temporary reservations of minerals and vespene gas, so I can create a reservation when ordering a worker to build a structure so the other workers and buildings don't spend the resources in the meantime until the worker arrives at the building site. The problem is, when the standard BWAPI event listener "onFrame" launches the countDownReservations() method, the individual array rows are not called at all and the rest of the AI isn't processed at all and is effectively broken.

So when I start the bot, nothing happens except for the console printing out "bingo" and
"0 started"
over and over again for every frame.
The line "bingo1" doesn't even appear once, so somehow the program crashes when calling this method "countDown()". Sadly it doesn't give an error at all and there are no pre-compiler warnings whatsoever.

Can anyone explain what's wrong?

Console output:

Java project:

Starcraft bot:

@Override
public void onFrame() {
    System.out.println("bingo");
    resourceReservations.countDownReservations();

public class ResourceReservations {

    private ResourceReservation[] resourceReservationArray = new ResourceReservation[15];

    public ResourceReservations() {

    }

    // looks through the array for a reservation with 0 time left on it (which should thus be empty)
    // - and overwrites the empty reservation with a new one
    // if no empty reservation can be found, nothing happens and a warning is output to the console
    public void addReservation(int minerals, int gas, int timer) {
        for (int loopCounter = 0; loopCounter < 15; loopCounter++) {
            if (resourceReservationArray[loopCounter].getReservationTime() == 0) {
                resourceReservationArray[loopCounter].setMinerals(minerals);
                resourceReservationArray[loopCounter].setGas(gas);
                resourceReservationArray[loopCounter].setTimerInSeconds(timer);
                break;
            }
        }
        System.out.println("Failed to add a reservation, no free space in array!");
    }

    // sums up all reserved minerals in the array
    public int reservedMinerals() {
        int reservedMinerals = 0;
        for (int loopCounter = 0; loopCounter < 15; loopCounter++) {
            reservedMinerals = reservedMinerals + resourceReservationArray[loopCounter].getMinerals();
        }
        return reservedMinerals;
    }

    // sums up all reserved vespene gas in the array
    public int reservedVespeneGas() {
        int reservedVespeneGas = 0;
        for (int loopCounter = 0; loopCounter < 15; loopCounter++) {
            reservedVespeneGas = reservedVespeneGas + resourceReservationArray[loopCounter].getGas();
        }
        return reservedVespeneGas;
    }

    // count down all the reservations
    public void countDownReservations() {
        for (int loopNumber = 0; loopNumber < 15; loopNumber++) {
            System.out.println(loopNumber + " started");
            resourceReservationArray[loopNumber].countDown();
            System.out.println(loopNumber + " completed");
        }
    }
}

public class ResourceReservation {

    private int minerals = 0;

    private int vespeneGas = 0;

    private int reservationTime = 0;

    public ResourceReservation() {

    }

    // read status - - - - - - - - - - - - - - - - -
    public int getGas() {
        return vespeneGas;
    }
    public int getMinerals() {
        return minerals;
    }
    public int getReservationTime() {
        return reservationTime;
    }

    // update status - - - - - - - - - - - - - - - -
    public void setGas(int newGas) {
        vespeneGas      = newGas;
    }
    public void setMinerals(int newMinerals) {
        minerals        = newMinerals;
    }
    public void setTimerInFrames(int newTimer) {
        reservationTime = newTimer;
    }
    public void setTimerInSeconds(int newTimer) {
        reservationTime = newTimer * 60;
    }

    // clear  - - -  - - - - - - - - - - - - - - - -
    public void initialize() {
        minerals        = 0;
        vespeneGas      = 0;
        reservationTime = 0;
    }

    // count down - -  - - - - - - - - - - - - - - -
    public void countDown() {
        System.out.println("bingo1");
        if (reservationTime > 0) {
            System.out.println("bingo2");
            reservationTime = reservationTime - 1;
            System.out.println("bingo3");
            if (reservationTime == 0) {
                System.out.println("bingo4");
                initialize();
            }
        }
    }
}

Body:
Ah I just solved it, the problem was that the 15 Reservations didn't exist

Adding this loop to the head of the Reservations class solved the problem:

    for (int x = 0; x < 15; x++) {
        resourceReservationArray[x] = new ResourceReservation();
    }

public class ResourceReservations {

private ResourceReservation[] resourceReservationArray = new ResourceReservation[15];

public ResourceReservations() {
    for (int x = 0; x < 15; x++) {
        resourceReservationArray[x] = new ResourceReservation();
    }
}

Thanks for putting up with me and reminding me of debugging. Hadn't done that in java yet. ^^

Edit: Oh and by the way, I reduced the number of reservations to 5 and haven't seen it overflow yet in about 20 games.


问:
Conway's Game of Life recursive step function
To help me begin to understand Haskell, I'm implementing Conway's Game of Life and ran into a snag in my step function trying to build a 2D list. Relevant definitions below:

```<code>data Cell = On | Off deriving (Eq, Show)

type Board = [[Cell]]
type Coord = (Int, Int)
type IndexedBoard = [[(Coord, Cell)]]

testBoard =     [[On, On,  On]
                ,[On, Off, On]
                ,[On, On,  On]]

numNeighbors :: Board -> Coord -> Int
-- Returns the number of live neighbors given a Board and a Coord on that board
-- assume this is implemented correctly, because it's a bunch of code
-- that you don't otherwise need to read, and it passes tests.

addIndexes :: Board -> IndexedBoard
addIndexes xs = [[((x,y), el) | (x,el) <- zip [0..] row] | (y,row) <- zip [0..] xs]
removeIndexes :: IndexedBoard -> Board
removeIndexes = map (map snd)
-- addIndexes testBoard is
-- [ [((0, 0), On), ((1, 0), On),  ((2, 0), On)]
--   ,((0, 1), On), ((1, 1), Off), ((2, 1), On)]
--   ,((0, 2), On), ((1, 2), On),  ((2, 2), On)] ]
-- and removeIndexes . addIndexes = id
</code>```

My step function is where I'm having trouble. I'm not sure how to build the 2D list I expect without mutual recursion (which I'm trying to avoid arbitrarily).

```<code>step :: Board -> Board
step board = removeIndexes . step' . addIndexes $ board where
    step' :: IndexedBoard -> IndexedBoard
    step' [] = []
    step' ([]:rest) = step' rest
    step' (((coord, cell):restrow):rest) = [(coord, newCell (numNeighbors board coord) cell)] : (step' (restrow:rest))
    newCell :: Int -> Cell -> Cell
    newCell 2 On = On
    newCell 3 _ = On
    newCell _ _ = Off
</code>```

I expect the follow output from step testBoard:

```<code>[[On,  Off, On ]
,[Off, Off, Off]
,[On,  Off, On ]]
</code>```

But am instead getting:

```<code>[[On],  [Off], [On]
,[Off], [Off], [Off]
,[On],  [Off], [On]]
</code>```

I understand that's because my recursive case of step' gives [(coord, newCell (numNeighbors board coord) cell)] : ..., but if I pull that out of the list I get the following error:

```<code>[1 of 1] Compiling Main             ( gameoflife.hs, interpreted )

gameoflife.hs:51:44: error:
    • Couldn't match type ‘(Coord, Cell)’ with ‘[(Coord, Cell)]’
      Expected type: IndexedBoard
        Actual type: [(Coord, Cell)]
    • In the expression:
        (coord, newCell (numNeighbors board coord) cell)
        : (step' (restrow : rest))
      In an equation for ‘step'’:
          step' (((coord, cell) : restrow) : rest)
            = (coord, newCell (numNeighbors board coord) cell)
              : (step' (restrow : rest))
      In an equation for ‘step’:
          step board
            = removeIndexes . step' . addIndexes $ board
            where
                step' :: IndexedBoard -> IndexedBoard
                step' [] = []
                step' ([] : rest) = step' rest
                step' (((coord, cell) : restrow) : rest)
                  = (coord, newCell (numNeighbors board coord) cell)
                    : (step' (restrow : rest))
                newCell :: Int -> Cell -> Cell
                newCell 2 On = On
                newCell 3 _ = On
                newCell _ _ = Off

gameoflife.hs:51:96: error:
    • Couldn't match type ‘[(Coord, Cell)]’ with ‘(Coord, Cell)’
      Expected type: [(Coord, Cell)]
        Actual type: IndexedBoard
    • In the second argument of ‘(:)’, namely
        ‘(step' (restrow : rest))’
      In the expression:
        (coord, newCell (numNeighbors board coord) cell)
        : (step' (restrow : rest))
      In an equation for ‘step'’:
          step' (((coord, cell) : restrow) : rest)
            = (coord, newCell (numNeighbors board coord) cell)
              : (step' (restrow : rest))
Failed, modules loaded: none.
</code>```

答:
The last equation for step' is wrong.

```<code>step' (((coord, cell):restrow):rest) = [(coord, newCell (numNeighbors board coord) cell)] : (step' (restrow:rest))
</code>```

For each cell in each row, you produce a new single-cell row as output. If you insist on writing all your recursion by hand, you can fix this by consing onto the first row returned by the recursive call, rather than creating a new row each time:

```<code>step' :: IndexedBoard -> IndexedBoard
step' [] = []
step' ([]:rest) = [] : step' rest
step' (((coord, cell):restrow):rest) =
  let (row:more) = step' (restrow:rest)
  in ((coord, newCell (numNeighbors board coord) cell) : row) : more
</code>```

However, there is a much better approach: all you are doing is trying to apply a function to each of the (Coord, Cell) pairs in your nested list, while maintaining the list's structure. But that's exactly what map is for! You should define a much simpler function that updates a single entry in the list, and then map it over all of them:

```<code>updateCell :: (Coord, Cell) -> (Coord, Cell)
updateCell (coord, cell) = (coord, newCell (numNeighbors board coord) cell)

step' :: IndexedBoard -> IndexedBoard
step' = map (map updateCell)
</code>```

Body:
To help me begin to understand Haskell, I'm implementing Conway's Game of Life and ran into a snag in my step function trying to build a 2D list. Relevant definitions below:

data Cell = On | Off deriving (Eq, Show)

type Board = [[Cell]]
type Coord = (Int, Int)
type IndexedBoard = [[(Coord, Cell)]]

testBoard =     [[On, On,  On]
                ,[On, Off, On]
                ,[On, On,  On]]

numNeighbors :: Board -> Coord -> Int
-- Returns the number of live neighbors given a Board and a Coord on that board
-- assume this is implemented correctly, because it's a bunch of code
-- that you don't otherwise need to read, and it passes tests.

addIndexes :: Board -> IndexedBoard
addIndexes xs = [[((x,y), el) | (x,el) <- zip [0..] row] | (y,row) <- zip [0..] xs]
removeIndexes :: IndexedBoard -> Board
removeIndexes = map (map snd)
-- addIndexes testBoard is
-- [ [((0, 0), On), ((1, 0), On),  ((2, 0), On)]
--   ,((0, 1), On), ((1, 1), Off), ((2, 1), On)]
--   ,((0, 2), On), ((1, 2), On),  ((2, 2), On)] ]
-- and removeIndexes . addIndexes = id

My step function is where I'm having trouble. I'm not sure how to build the 2D list I expect without mutual recursion (which I'm trying to avoid arbitrarily).

step :: Board -> Board
step board = removeIndexes . step' . addIndexes $ board where
    step' :: IndexedBoard -> IndexedBoard
    step' [] = []
    step' ([]:rest) = step' rest
    step' (((coord, cell):restrow):rest) = [(coord, newCell (numNeighbors board coord) cell)] : (step' (restrow:rest))
    newCell :: Int -> Cell -> Cell
    newCell 2 On = On
    newCell 3 _ = On
    newCell _ _ = Off

I expect the follow output from step testBoard:

[[On,  Off, On ]
,[Off, Off, Off]
,[On,  Off, On ]]

But am instead getting:

[[On],  [Off], [On]
,[Off], [Off], [Off]
,[On],  [Off], [On]]

I understand that's because my recursive case of step' gives [(coord, newCell (numNeighbors board coord) cell)] : ..., but if I pull that out of the list I get the following error:

[1 of 1] Compiling Main             ( gameoflife.hs, interpreted )

gameoflife.hs:51:44: error:
    • Couldn't match type ‘(Coord, Cell)’ with ‘[(Coord, Cell)]’
      Expected type: IndexedBoard
        Actual type: [(Coord, Cell)]
    • In the expression:
        (coord, newCell (numNeighbors board coord) cell)
        : (step' (restrow : rest))
      In an equation for ‘step'’:
          step' (((coord, cell) : restrow) : rest)
            = (coord, newCell (numNeighbors board coord) cell)
              : (step' (restrow : rest))
      In an equation for ‘step’:
          step board
            = removeIndexes . step' . addIndexes $ board
            where
                step' :: IndexedBoard -> IndexedBoard
                step' [] = []
                step' ([] : rest) = step' rest
                step' (((coord, cell) : restrow) : rest)
                  = (coord, newCell (numNeighbors board coord) cell)
                    : (step' (restrow : rest))
                newCell :: Int -> Cell -> Cell
                newCell 2 On = On
                newCell 3 _ = On
                newCell _ _ = Off

gameoflife.hs:51:96: error:
    • Couldn't match type ‘[(Coord, Cell)]’ with ‘(Coord, Cell)’
      Expected type: [(Coord, Cell)]
        Actual type: IndexedBoard
    • In the second argument of ‘(:)’, namely
        ‘(step' (restrow : rest))’
      In the expression:
        (coord, newCell (numNeighbors board coord) cell)
        : (step' (restrow : rest))
      In an equation for ‘step'’:
          step' (((coord, cell) : restrow) : rest)
            = (coord, newCell (numNeighbors board coord) cell)
              : (step' (restrow : rest))
Failed, modules loaded: none.

Body:
The last equation for step' is wrong.

step' (((coord, cell):restrow):rest) = [(coord, newCell (numNeighbors board coord) cell)] : (step' (restrow:rest))

For each cell in each row, you produce a new single-cell row as output. If you insist on writing all your recursion by hand, you can fix this by consing onto the first row returned by the recursive call, rather than creating a new row each time:

step' :: IndexedBoard -> IndexedBoard
step' [] = []
step' ([]:rest) = [] : step' rest
step' (((coord, cell):restrow):rest) =
  let (row:more) = step' (restrow:rest)
  in ((coord, newCell (numNeighbors board coord) cell) : row) : more

However, there is a much better approach: all you are doing is trying to apply a function to each of the (Coord, Cell) pairs in your nested list, while maintaining the list's structure. But that's exactly what map is for! You should define a much simpler function that updates a single entry in the list, and then map it over all of them:

updateCell :: (Coord, Cell) -> (Coord, Cell)
updateCell (coord, cell) = (coord, newCell (numNeighbors board coord) cell)

step' :: IndexedBoard -> IndexedBoard
step' = map (map updateCell)


问:
LINQ: custom column names
UPDATE

I'm basically binding the query to a WinForms DataGridView. I want the column headers to be appropriate and have spaces when needed. For example, I would want a column header to be First Name instead of FirstName.

How do you create your own custom column names in LINQ?

For example:

```<code>Dim query = From u In db.Users _
            Select u.FirstName AS 'First Name'
</code>```

答:
I solved my own problem but all of your answers were very helpful and pointed me in the right direction.

In my LINQ query, if a column name had more than one word I would separate the words with an underscore:

```<code>Dim query = From u In Users _
            Select First_Name = u.FirstName
</code>```

Then, within the Paint method of the DataGridView, I replaced all underscores within the header with a space:

```<code>Private Sub DataGridView1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DataGridView1.Paint
    For Each c As DataGridViewColumn In DataGridView1.Columns
        c.HeaderText = c.HeaderText.Replace("_", " ")
    Next
End Sub
</code>```

OwnerDisplayName: Bryan Roth

Title: LINQ: custom column names

Body:
UPDATE

I'm basically binding the query to a WinForms DataGridView. I want the column headers to be appropriate and have spaces when needed. For example, I would want a column header to be First Name instead of FirstName.

How do you create your own custom column names in LINQ?

For example:

Dim query = From u In db.Users _
            Select u.FirstName AS 'First Name'

LastEditorDisplayName: Bryan Roth

Body:
I solved my own problem but all of your answers were very helpful and pointed me in the right direction.

In my LINQ query, if a column name had more than one word I would separate the words with an underscore:

Dim query = From u In Users _
            Select First_Name = u.FirstName

Then, within the Paint method of the DataGridView, I replaced all underscores within the header with a space:

Private Sub DataGridView1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles DataGridView1.Paint
    For Each c As DataGridViewColumn In DataGridView1.Columns
        c.HeaderText = c.HeaderText.Replace("_", " ")
    Next
End Sub


问:
Get True Dimensions of an Image with JQuery
Given a list of image paths how can I iterate through them and find the actual image dimensions?  I assume I have to insert them into the DOM without width or height properties and do a .width and .height on them?</p>

答:
```<code>var paths = ['/path/image.png', 'somewhere/page.jpg'];

$.each(paths, function(i, path) {
    var img = new Image();

    $(img).load(function() {

        var width = img.width,
            height = img.height;

        alert(width + ' × ' + height);

    });

    img.src = path;

});
</code>```

See it on jsFiddle.

Body:
var paths = ['/path/image.png', 'somewhere/page.jpg'];

$.each(paths, function(i, path) {
    var img = new Image();

    $(img).load(function() {

        var width = img.width,
            height = img.height;

        alert(width + ' × ' + height);

    });

    img.src = path;

});

See it on jsFiddle.


问:
InApp purchase work on TestFlight but when downloaded from AppStrore
After a 2 weeks period of beta testing with TestFlight, I have successfully published my app to AppStore today.

After re-downloading from AppStore, in-app purchase products are not loading anymore.

I am using 'react-native-in-app-utils': https://github.com/chirag04/react-native-in-app-utils

```<code>InAppUtils.loadProducts(productsIdentifiers, (error, products) => {
            if (error) {
                console.log(`Error loading produces! ${products}`);
            } else {
                InAppPurchaseIOS._productsLoaded(products);
            }
        });
</code>```

(I know the products are not loading by the UI error)

Did anyone face the same issue? How is it possible to work on TestFlight and not on AppStore?

Thanks in advance

答: 4 hours after the app was published, In-app purchase products became available.</p>

Body:
After a 2 weeks period of beta testing with TestFlight, I have successfully published my app to AppStore today.

After re-downloading from AppStore, in-app purchase products are not loading anymore.

I am using 'react-native-in-app-utils': https://github.com/chirag04/react-native-in-app-utils

InAppUtils.loadProducts(productsIdentifiers, (error, products) => {
            if (error) {
                console.log(`Error loading produces! ${products}`);
            } else {
                InAppPurchaseIOS._productsLoaded(products);
            }
        });

(I know the products are not loading by the UI error)

Did anyone face the same issue? How is it possible to work on TestFlight and not on AppStore?

Thanks in advance


问:
npm module for clarifai not found when I start the node server
```<code>module.js:341
    throw err;
    ^

Error: Cannot find module 'clarifai'
    at Function.Module._resolveFilename (module.js:339:15)
    at Function.Module._load (module.js:290:25)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/Users/shiva/seefood-backend/app.js:4:16)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
</code>```

I get the above message in terminal when I do node app.js. I have installed Clarifai npm package as mentioned on https://developer.clarifai.com/quick-start/ with npm install clarifai but it still gives me this error. Do I need to install the package globally?
Also this is my app.js :

```<code>var express = require('express')
var app = express();
var bodyParser = require('body-parser')
var Clarifai = require('clarifai')
var secrets = require('./secrets')
var keys = secrets.clarifaiConfig()

app.use(bodyParser.json());

var ClarifaiInstance = new Clarifai.App(
  keys.access_key,
  keys.secret_key
)

var store

var foodModel = 'bd367be194cf45149e75f01d59f77ba7'
var fnol = function getPredictionAsJSON(imageURL) {
  ClarifaiInstance.models.predict(foodModel, imageURL).then(
    function(response) {
      store = response.outputs[0].data
      console.log(store + ' from inside the fn');
    },
    function(err) {
      console.error(err);
    }
  );
  return store
}

app.listen(8000, function () {
  console.log('Recognize app listening on port 8000!')

  app.post('/classify', function(req, res) {
    var clarifaiData
    var imageURL = req.body.imageURL
      clarifaiData = fnol(imageURL)
      // console.log('cldata : '+ clarifaiData)
      var responseObject = {imageURL: imageURL, data: clarifaiData }
      // console.log('rObj : '+responseObject)
      res.send((responseObject));
  });

  app.get('/classify', function(req, res) {
    res.json((store));
  });
})
</code>```

答: You shouldn't need to install globally. After installing there would be a node_modules directory at the same location that includes the clarifai package as well as any other dependencies.</p>

Body:
module.js:341
    throw err;
    ^

Error: Cannot find module 'clarifai'
    at Function.Module._resolveFilename (module.js:339:15)
    at Function.Module._load (module.js:290:25)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/Users/shiva/seefood-backend/app.js:4:16)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)

I get the above message in terminal when I do node app.js. I have installed Clarifai npm package as mentioned on https://developer.clarifai.com/quick-start/ with npm install clarifai but it still gives me this error. Do I need to install the package globally?
Also this is my app.js :

var express = require('express')
var app = express();
var bodyParser = require('body-parser')
var Clarifai = require('clarifai')
var secrets = require('./secrets')
var keys = secrets.clarifaiConfig()

app.use(bodyParser.json());

var ClarifaiInstance = new Clarifai.App(
  keys.access_key,
  keys.secret_key
)

var store

var foodModel = 'bd367be194cf45149e75f01d59f77ba7'
var fnol = function getPredictionAsJSON(imageURL) {
  ClarifaiInstance.models.predict(foodModel, imageURL).then(
    function(response) {
      store = response.outputs[0].data
      console.log(store + ' from inside the fn');
    },
    function(err) {
      console.error(err);
    }
  );
  return store
}

app.listen(8000, function () {
  console.log('Recognize app listening on port 8000!')

  app.post('/classify', function(req, res) {
    var clarifaiData
    var imageURL = req.body.imageURL
      clarifaiData = fnol(imageURL)
      // console.log('cldata : '+ clarifaiData)
      var responseObject = {imageURL: imageURL, data: clarifaiData }
      // console.log('rObj : '+responseObject)
      res.send((responseObject));
  });

  app.get('/classify', function(req, res) {
    res.json((store));
  });
})


问:
Apache mod rewrite not working in Mac Sierra
Apache version is 2.4,rewrite mod is active in httpd.conf

AllowOverRide is set to all and require all granted in vhost config

I am just getting a 404 not found error.
Am I missing any setting?

答:
Double check that all the document roots have AllowOveride All. It should listen to the closest node in the folder hierarchy but in my experience wasn't the case.
The primary <Directory /> section in http.conf was defaulted as None.


问:
How to implement a method with an unknown number of arguments?
I have 1 interface and 3 class. I would like the class to be able to both implement the interface which need a transform method. This method must exist but there can't be more than one per class. I don't know the number of parameters taken by this class.

Example :

```<code>public interface A{
    public void transform(Object ... args);
}

public class B implements A{
    public void transform(String a){
        System.out.println(a);
    }
}

public class C implements A{
    public void transform(Integer a, Character b){
        System.out.println(a+b);
    }
}

// super generic case if possible with Objects + primitive
public class D implements A{
    public void transform(int a, String b){
        System.out.println(a+b);
    }
}
</code>```

This doesn't work. But I hope you got the idea. Is something like this possible in java ? How should I call them in a generic way ? Let's say if I have an other method like :

```<code>void callTransf(A a, Object ... objs){
    Method m = a.getClass().getMethods()[0];
    m.invoke(a, objs)
}
</code>```

答:
A practicable solution would be to declare the interface as a generic one:

```<code>public interface Transformation<S, R> {
    R transform(S source);
}
</code>```

The type parameter S plays the source role; the type parameter R plays the result role.

You now can create source and result classes for each different transformation. An example:

```<code>public final class TransformationSourceForA {
    // Here you declare whatever fields and methods you need for an A source.
    // For example:
    int a;
    String b;
}

public final class TransformationResultForA {
    // Here you declare whatever fields and methods you need for an A result.
}
</code>```

With that you declare the transformation as following:

```<code>public final class TransformationA implements Transformation<TransformationSourceForA, TransformationResultForA> {
    @Override
    public TransformationResultForA transform(TransformationSourceForA source) { ... }
}
</code>```

The principle is to delegate the needs for different fields to a class and not to the method's parameter.

Body:
I have 1 interface and 3 class. I would like the class to be able to both implement the interface which need a transform method. This method must exist but there can't be more than one per class. I don't know the number of parameters taken by this class.

Example :

public interface A{
    public void transform(Object ... args);
}

public class B implements A{
    public void transform(String a){
        System.out.println(a);
    }
}

public class C implements A{
    public void transform(Integer a, Character b){
        System.out.println(a+b);
    }
}

// super generic case if possible with Objects + primitive
public class D implements A{
    public void transform(int a, String b){
        System.out.println(a+b);
    }
}

This doesn't work. But I hope you got the idea. Is something like this possible in java ? How should I call them in a generic way ? Let's say if I have an other method like :

void callTransf(A a, Object ... objs){
    Method m = a.getClass().getMethods()[0];
    m.invoke(a, objs)
}

Body:
A practicable solution would be to declare the interface as a generic one:

public interface Transformation<S, R> {
    R transform(S source);
}

The type parameter S plays the source role; the type parameter R plays the result role.

You now can create source and result classes for each different transformation. An example:

public final class TransformationSourceForA {
    // Here you declare whatever fields and methods you need for an A source.
    // For example:
    int a;
    String b;
}

public final class TransformationResultForA {
    // Here you declare whatever fields and methods you need for an A result.
}

With that you declare the transformation as following:

public final class TransformationA implements Transformation<TransformationSourceForA, TransformationResultForA> {
    @Override
    public TransformationResultForA transform(TransformationSourceForA source) { ... }
}

The principle is to delegate the needs for different fields to a class and not to the method's parameter.


问:
Mask string in ViewModel C#
I have a view that pulls a list of everything in the database and it works great.  However there is one bit of information that I have to mask, and no matter what I try I can't seem to mask it.

I want to mask it with 5 * (no matter how long the string) and display the last 4 digits.

Any idea of the best way to accomplish this with what I have?

String example: "SD46346" && "ADFF3342422" && "56-AS4566S"

Controller

```<code>    vm.Accounts = accounts
        .Select(s => new AdminViewModel.Account
        {
            Id= (s._ID.Length > 40 ? Encryptor.Decrypt(s._ID) : s._ID),
        }).ToList();
    return View(vm);
</code>```

ViewModel

```<code>public List<Account> Accounts { get; set;}

public class Account
{
    public string Id { get; set; }
}
</code>```

Things I've tried : Server Error in '/xxxxx' Application. StartIndex cannot be less than zero. Parameter name: startIndex –

```<code>public string DisplayID
{
    get
    {
        return string.Format("*****{0}", Id.Substring(Id.Length - 4));
    }
}
</code>```

UPDATE

It wasn't my code, it was old data that was lost in the database that only had 2 characters.

答:
If you're just after simple replacement for display, you could also add an extra property that you use for display purpose.</p>

```<code>string ID {get;set;}

string DisplayID
{
    get
    {
        return string.Format("*****{0}", ID.substring(ID.Length - 4))
    }
}
</code>```

Title: Mask string in ViewModel C#

Body:
I have a view that pulls a list of everything in the database and it works great.  However there is one bit of information that I have to mask, and no matter what I try I can't seem to mask it.

I want to mask it with 5 * (no matter how long the string) and display the last 4 digits.

Any idea of the best way to accomplish this with what I have?

String example: "SD46346" && "ADFF3342422" && "56-AS4566S"

Controller

    vm.Accounts = accounts
        .Select(s => new AdminViewModel.Account
        {
            Id= (s._ID.Length > 40 ? Encryptor.Decrypt(s._ID) : s._ID),
        }).ToList();
    return View(vm);

ViewModel

public List<Account> Accounts { get; set;}

public class Account
{
    public string Id { get; set; }
}

Things I've tried : Server Error in '/xxxxx' Application. StartIndex cannot be less than zero. Parameter name: startIndex –

public string DisplayID
{
    get
    {
        return string.Format("*****{0}", Id.Substring(Id.Length - 4));
    }
}

UPDATE

It wasn't my code, it was old data that was lost in the database that only had 2 characters.

Body:
If you're just after simple replacement for display, you could also add an extra property that you use for display purpose.

string ID {get;set;}

string DisplayID
{
    get
    {
        return string.Format("*****{0}", ID.substring(ID.Length - 4))
    }
}


问:
How to resolve "undefined function TYPO3\CMS\Core\Localization\Parser\simplexml_load_string()" in TYPO3 8 CMS
Recently I have installed TYPO3 CMS 8 in my local server, after all configuration wizard finally I got error like "Call to undefined function TYPO3\CMS\Core\Localization\Parser\simplexml_load_string()".

Can anyone help me for resolving this error.

答:
I found this in german: https://forum.typo3.org/index.php/t/214932/-typo3-german-gel-st-simplexml-problem-typo3-7-6-und-php-7-auf-ubuntu-server-16-04

SimpleXML is not active by default in PHP 7 on Ubuntu. See
  http://stackoverflow.com/questions/35593521/php-7-simplexml. After
  activate them all works.


问:
How to perform jquery ajax delete operation when delete is to remove an entry in mongodb?
I have a sample nodejs app with api in mondodb connected via mongoose. I get a bunch of responses something like this (Sinple Entry below)

```<code>    {
    name:"Task1"
    status:["pending"]
    0:"pending"
    __v:0
    _id:"592d6a398eb24a9ac85d1184"
   }
</code>```

Now If I have to delete the entry I will create a route like:

```<code>/tasks/_id
</code>```

which I have created in nodejs and it works fine. I need perform a delete operation using an ajax delete operation. How do I create a route like /tasks/_id in ajax that will delete the record. Below is my code.

```<code>     $.ajax({
      type:'DELETE',
      url:'/tasks/' + how to get _id here from mongodb, which could be available only on successful ajax operation,

        success : function( data) {
          console.log('success);
       },
      error : function() {
        console.log('error');

      }
    })
</code>```

答:
First in ajax the property name is 'method' not 'type'. secondly you for delete a record you should have mongodb record id in link or somewhere
like /tasks/mongodbId or /tasks/343sddfsdf3434 in frontend. you can display or print via some loop etc.
or assume var id = task._id;

```<code><a id="link" data-mongo-id="sfsdfs4343dsfds" href="tasks/sfsdfs4343dsfds">link<a/>
</code>```

then you can call ajax method from frontend.

```<code>$.ajax({
      method:'DELETE',
      url:'/tasks/' + $("#link").attr('data-mongo-id'),

        success : function( data) {
          console.log('success);
       },
      error : function() {
        console.log('error');

      }
    })
</code>```

At backend you can use method like

```<code>var express = require('express')
var app = express()

app.delete('tasks/:mongo_id', function (req, res) {
 ///your mongose delete query

Task.findByIdAndRemove(req.params.mongo_id, function (err, task) {

var response = {
    message: "task successfully deleted",
    id: req.mongo_id
};
    res.send(response);
   });

    })
</code>```

Body:
I have a sample nodejs app with api in mondodb connected via mongoose. I get a bunch of responses something like this (Sinple Entry below)

    {
    name:"Task1"
    status:["pending"]
    0:"pending"
    __v:0
    _id:"592d6a398eb24a9ac85d1184"
   }

Now If I have to delete the entry I will create a route like:

/tasks/_id

which I have created in nodejs and it works fine. I need perform a delete operation using an ajax delete operation. How do I create a route like /tasks/_id in ajax that will delete the record. Below is my code.

     $.ajax({
      type:'DELETE',
      url:'/tasks/' + how to get _id here from mongodb, which could be available only on successful ajax operation,

        success : function( data) {
          console.log('success);
       },
      error : function() {
        console.log('error');

      }
    })

Body:
First in ajax the property name is 'method' not 'type'. secondly you for delete a record you should have mongodb record id in link or somewhere
like /tasks/mongodbId or /tasks/343sddfsdf3434 in frontend. you can display or print via some loop etc.
or assume var id = task._id;

<a id="link" data-mongo-id="sfsdfs4343dsfds" href="tasks/sfsdfs4343dsfds">link<a/>

then you can call ajax method from frontend.

$.ajax({
      method:'DELETE',
      url:'/tasks/' + $("#link").attr('data-mongo-id'),

        success : function( data) {
          console.log('success);
       },
      error : function() {
        console.log('error');

      }
    })

At backend you can use method like

var express = require('express')
var app = express()

app.delete('tasks/:mongo_id', function (req, res) {
 ///your mongose delete query

Task.findByIdAndRemove(req.params.mongo_id, function (err, task) {

var response = {
    message: "task successfully deleted",
    id: req.mongo_id
};
    res.send(response);
   });

    })