问:
500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request
i have Xfilesharing (perl) script here the official site of it (https://sibsoft.net/xfilesharing.html)

i installed it on server, and i have javaScript plugin work with php file
i should put the JavaScript in HTML page then call php file to do something, i try the php file on my localhot and it's work 100%, but along without perl script.

when i upload it to server the following message come to me

```<code>The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, webmaster@*****.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
</code>```

i google it and found some solutions like change permissions and i change it to 0777 but it's not work.

also i changed the name of .htaccess file to .htaccess2 to see what's happened but nothing work.

this .htaccess file

```<code>deny from 10.0.0.182

AddDefaultCharset utf-8
RewriteEngine on

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_CGI_AUTHORIZATION:%1]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule    ^([0-9A-Za-z]{12})(\/.+|\.html?|$)   /cgi-bin/index_dl.cgi?op=download1&id=$1&fname=$2 [L]

RewriteRule    ^embed-([0-9A-Za-z]{12})\.html$      /cgi-bin/index_dl.cgi?op=video_embed&file_code=$1 [L]
RewriteRule    ^embed-([0-9A-Za-z]{12})-(\d+)x(\d+)\.html$      /cgi-bin/index_dl.cgi?op=video_embed&file_code=$1&w=$2&h=$3 [L]
RewriteRule    ^embedmp3-([0-9A-Za-z]{12})\.html$   /cgi-bin/index_dl.cgi?op=mp3_embed&file_code=$1 [L]

RewriteRule    ^mp3embed-([0-9A-Za-z]{12})\.mp3$    /cgi-bin/index_dl.cgi?op=mp3_embed2&file_code=$1 [L]
RewriteRule    ^vidembed-([0-9A-Za-z]{12})      /cgi-bin/index_dl.cgi?op=video_embed2&file_code=$1 [L]

RewriteRule    ^box$                    /cgi-bin/index_box.cgi [L]
RewriteRule    ^dl$                 /cgi-bin/index_dl.cgi [L]
RewriteRule    ^download$               /cgi-bin/index_dl.cgi?op=download1 [L]

RewriteRule    ^$                   /cgi-bin/index.cgi [L]
RewriteRule    ^free([0-9]+)\.html$         /cgi-bin/index.cgi?op=registration&aff_id=$1 [L]
#RewriteRule    ^checkfiles\.html$          /cgi-bin/index.cgi?op=checkfiles [L]
RewriteRule    ^contact\.html$              /cgi-bin/index.cgi?op=contact [L]
RewriteRule    ^premium\.html$              /cgi-bin/index.cgi?op=payments [L]
RewriteRule    ^login\.html$                /cgi-bin/index.cgi?op=login [L]
RewriteRule    ^catalogue(.*)\.html$            /cgi-bin/index.cgi?op=catalogue&date=$1 [L]
RewriteRule    ^news([0-9]*)\.html$         /cgi-bin/index.cgi?op=news&page=$1 [L]
RewriteRule    ^n([0-9]+)-.*\.html$         /cgi-bin/index.cgi?op=news_details&news_id=$1 [L]
RewriteRule    ^faq\.html$              /cgi-bin/index.cgi?op=page&tmpl=faq [L]
RewriteRule    ^DMCA\.html$             /cgi-bin/index.cgi?op=page&tmpl=DMCA [L]
RewriteRule    ^tos\.html$              /cgi-bin/index.cgi?op=page&tmpl=tos [L]
RewriteRule    ^links\.html$                /cgi-bin/index.cgi?op=links [L]
RewriteRule    ^make_money\.html$           /cgi-bin/index.cgi?op=make_money [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule    ^pages/([a-z0-9\-\_]+).html      /cgi-bin/index.cgi?op=page&tmpl=$1$2 [L]

RewriteCond %{QUERY_STRING} .*page=[0-9]+.*
RewriteRule     ^users/([0-9A-Za-z\-_]{4,64})/?([0-9]+|$)   /cgi-bin/index.cgi [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule     ^users/([0-9A-Za-z\-_]{4,64})/?([0-9]+|$)   /cgi-bin/index.cgi?op=user_public&usr_login=$1&fld_id=$2 [L,NC]
RewriteRule     ^u/([0-9A-Za-z\-_]+)            /cgi-bin/index_dl.cgi?op=deurl&id=$1 [L,NC]
RewriteRule     ^d/([0-9A-Za-z\-_]+)                    /cgi-bin/index_dl.cgi?op=deurl&id=$1&mode=2 [L,NC]

RewriteRule    \.pm$                    /404.html [L]

ErrorDocument 404 /404.html

<IfModule mod_php5.c>
        php_flag engine off
</IfModule>
</code>```

anyone can help me ?

答:
Hi guys i solve it by change permissions to 0644, this was from my server configurations
thanks</p>

Body:
i have Xfilesharing (perl) script here the official site of it (https://sibsoft.net/xfilesharing.html)

i installed it on server, and i have javaScript plugin work with php file
i should put the JavaScript in HTML page then call php file to do something, i try the php file on my localhot and it's work 100%, but along without perl script.

when i upload it to server the following message come to me

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, webmaster@*****.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

i google it and found some solutions like change permissions and i change it to 0777 but it's not work.

also i changed the name of .htaccess file to .htaccess2 to see what's happened but nothing work.

this .htaccess file

deny from 10.0.0.182

AddDefaultCharset utf-8
RewriteEngine on

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_CGI_AUTHORIZATION:%1]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule    ^([0-9A-Za-z]{12})(\/.+|\.html?|$)   /cgi-bin/index_dl.cgi?op=download1&id=$1&fname=$2 [L]

RewriteRule    ^embed-([0-9A-Za-z]{12})\.html$      /cgi-bin/index_dl.cgi?op=video_embed&file_code=$1 [L]
RewriteRule    ^embed-([0-9A-Za-z]{12})-(\d+)x(\d+)\.html$      /cgi-bin/index_dl.cgi?op=video_embed&file_code=$1&w=$2&h=$3 [L]
RewriteRule    ^embedmp3-([0-9A-Za-z]{12})\.html$   /cgi-bin/index_dl.cgi?op=mp3_embed&file_code=$1 [L]

RewriteRule    ^mp3embed-([0-9A-Za-z]{12})\.mp3$    /cgi-bin/index_dl.cgi?op=mp3_embed2&file_code=$1 [L]
RewriteRule    ^vidembed-([0-9A-Za-z]{12})      /cgi-bin/index_dl.cgi?op=video_embed2&file_code=$1 [L]

RewriteRule    ^box$                    /cgi-bin/index_box.cgi [L]
RewriteRule    ^dl$                 /cgi-bin/index_dl.cgi [L]
RewriteRule    ^download$               /cgi-bin/index_dl.cgi?op=download1 [L]

RewriteRule    ^$                   /cgi-bin/index.cgi [L]
RewriteRule    ^free([0-9]+)\.html$         /cgi-bin/index.cgi?op=registration&aff_id=$1 [L]
#RewriteRule    ^checkfiles\.html$          /cgi-bin/index.cgi?op=checkfiles [L]
RewriteRule    ^contact\.html$              /cgi-bin/index.cgi?op=contact [L]
RewriteRule    ^premium\.html$              /cgi-bin/index.cgi?op=payments [L]
RewriteRule    ^login\.html$                /cgi-bin/index.cgi?op=login [L]
RewriteRule    ^catalogue(.*)\.html$            /cgi-bin/index.cgi?op=catalogue&date=$1 [L]
RewriteRule    ^news([0-9]*)\.html$         /cgi-bin/index.cgi?op=news&page=$1 [L]
RewriteRule    ^n([0-9]+)-.*\.html$         /cgi-bin/index.cgi?op=news_details&news_id=$1 [L]
RewriteRule    ^faq\.html$              /cgi-bin/index.cgi?op=page&tmpl=faq [L]
RewriteRule    ^DMCA\.html$             /cgi-bin/index.cgi?op=page&tmpl=DMCA [L]
RewriteRule    ^tos\.html$              /cgi-bin/index.cgi?op=page&tmpl=tos [L]
RewriteRule    ^links\.html$                /cgi-bin/index.cgi?op=links [L]
RewriteRule    ^make_money\.html$           /cgi-bin/index.cgi?op=make_money [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule    ^pages/([a-z0-9\-\_]+).html      /cgi-bin/index.cgi?op=page&tmpl=$1$2 [L]

RewriteCond %{QUERY_STRING} .*page=[0-9]+.*
RewriteRule     ^users/([0-9A-Za-z\-_]{4,64})/?([0-9]+|$)   /cgi-bin/index.cgi [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule     ^users/([0-9A-Za-z\-_]{4,64})/?([0-9]+|$)   /cgi-bin/index.cgi?op=user_public&usr_login=$1&fld_id=$2 [L,NC]
RewriteRule     ^u/([0-9A-Za-z\-_]+)            /cgi-bin/index_dl.cgi?op=deurl&id=$1 [L,NC]
RewriteRule     ^d/([0-9A-Za-z\-_]+)                    /cgi-bin/index_dl.cgi?op=deurl&id=$1&mode=2 [L,NC]

RewriteRule    \.pm$                    /404.html [L]

ErrorDocument 404 /404.html

<IfModule mod_php5.c>
        php_flag engine off
</IfModule>

anyone can help me ?


来源: stackexchange

问:
NuGet: 'X' already has a dependency defined for 'Y'
I'm getting the following error in NuGet while trying to install package Microsoft.AspNet.Server.IIS

```<code>Attempting to resolve dependency 'Microsoft.AspNet.Loader.IIS.Interop (≥ 1.0.0-alpha4-10330)'.
Attempting to resolve dependency 'Microsoft.AspNet.Loader.IIS (≥ 1.0.0-alpha4-10330)'.
'Microsoft.AspNet.Loader.IIS' already has a dependency defined for 'Microsoft.AspNet.FeatureModel'.
</code>```

How to resolve it?

UPDATE:
Also, I'm getting the following:

```<code>Attempting to resolve dependency 'Microsoft.Framework.DependencyInjection (≥ 1.0.0-alpha4-10326)'.
'Microsoft.Framework.DependencyInjection' already has a dependency defined for 'Microsoft.Framework.ConfigurationModel'.
</code>```

答:
I tried the update, but it did not work for me. Helped:

Uninstall NuGet => Tools => Extensions and update => Installed

Install NuGet

Reload Visual Studio

ContentLicense: CC BY-SA 4.0

Body:
I'm getting the following error in NuGet while trying to install package Microsoft.AspNet.Server.IIS

Attempting to resolve dependency 'Microsoft.AspNet.Loader.IIS.Interop (≥ 1.0.0-alpha4-10330)'.
Attempting to resolve dependency 'Microsoft.AspNet.Loader.IIS (≥ 1.0.0-alpha4-10330)'.
'Microsoft.AspNet.Loader.IIS' already has a dependency defined for 'Microsoft.AspNet.FeatureModel'.

How to resolve it?

UPDATE:
Also, I'm getting the following:

Attempting to resolve dependency 'Microsoft.Framework.DependencyInjection (≥ 1.0.0-alpha4-10326)'.
'Microsoft.Framework.DependencyInjection' already has a dependency defined for 'Microsoft.Framework.ConfigurationModel'.


问:
reading file to a list
i have a text file  like this

```<code>a1,b1,30.04.2017
c1,d1,30.05.2017
</code>```

i want to add every line to a list, the first two columns will be string variables s1 and s2 and the third one will be converted to a variable showing a date

i am not experienced at all and usually i find my answers searching here. i can only find examples reading  lines containing the name of the variable and the value,

i think i will need to use the code below

```<code> List<string> fileLines = new List<string>();

using (var reader = new StreamReader(fileName))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {

    }
}
</code>```

i cannot do the things inside the bracket, namely ,
parse the line ,
assign first column  to variable s1
assign second column to variable s2
convert the third to date and assign it to d1
then add line to list

thanks in advance

答:
Using Linq :</p>

```<code>var query = from line in File.ReadAllLines(filename)
where !string.IsNullOrEmpty(line)
let words = line.Split(";")
select new { Item1 = words[0], Item2 = words[1], Date = DateTime.ParseExact(words[2], "dd.MM.yyyy", null) };
</code>```

ContentLicense: CC BY-SA 3.0

Title: reading file to a list

Body:
i have a text file  like this

a1,b1,30.04.2017
c1,d1,30.05.2017

i want to add every line to a list, the first two columns will be string variables s1 and s2 and the third one will be converted to a variable showing a date

i am not experienced at all and usually i find my answers searching here. i can only find examples reading  lines containing the name of the variable and the value,

i think i will need to use the code below

 List<string> fileLines = new List<string>();

using (var reader = new StreamReader(fileName))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {

    }
}

i cannot do the things inside the bracket, namely ,
parse the line ,
assign first column  to variable s1
assign second column to variable s2
convert the third to date and assign it to d1
then add line to list

thanks in advance

Body:
Using Linq :

var query = from line in File.ReadAllLines(filename)
where !string.IsNullOrEmpty(line)
let words = line.Split(";")
select new { Item1 = words[0], Item2 = words[1], Date = DateTime.ParseExact(words[2], "dd.MM.yyyy", null) };


问:
extract information from csv by using python
I am trying to extract how many songs are release in every year from csv. my data looks like this

```<code>no,artist,name,year
"1","Bing Crosby","White Christmas","1942"
"2","Bill Haley & his Comets","Rock Around the Clock","1955"
"3","Sinead O'Connor","Nothing Compares 2 U","1990","35.554"
"4","Celine Dion","My Heart Will Go On","1998","35.405"
"5","Bryan Adams","(Everything I Do) I Do it For You","1991"
"6","The Beatles","Hey Jude","1968"
"7","Whitney Houston","I Will Always Love You","1992","34.560"
"8","Pink Floyd","Another Brick in the Wall (part 2)","1980"
"9","Irene Cara","Flashdance... What a Feeling","1983"
"10","Elton John","Candle in the Wind '97","1992"
</code>```

my files consists of 3000 lines data with additional fields but i am interested to extract how many songs are released in every year

i tried to extract the year and songs and my code is here, but I am new in python and therefore I don't know how to solve my problem. my code is

```<code>from itertools import islice
import csv

filename = '/home/rob/traintask/top3000songs.csv'
data = csv.reader(open(filename))
# Read the column names from the first line of the file
fields = data.next()[3]  // I tried to read the year columns
print fields
count = 0
for row in data:
    # Zip together the field names and values
    items = zip(fields, row)
    item = {}   \\ here I am lost, i think i should make a dict and set year as key and no of songs as values, but I don't know how to do it
    # Add the value to our dictionary
    for (name, value) in items:
        item[name] = value.strip()
        print 'item: ', item
</code>```

I am doing it completely wrong. but If somebody give me some hints or help that how i can count no of songs released in a year. i will be thankful.

答:
2 very simple lines of code:

```<code>import pandas as pd
my_csv=pd.read_csv(filename)
</code>```

and to get the number of songs per year:

```<code>songs_per_year= my_csv.groupby('year')['name'].count()
</code>```

Body:
I am trying to extract how many songs are release in every year from csv. my data looks like this

no,artist,name,year
"1","Bing Crosby","White Christmas","1942"
"2","Bill Haley & his Comets","Rock Around the Clock","1955"
"3","Sinead O'Connor","Nothing Compares 2 U","1990","35.554"
"4","Celine Dion","My Heart Will Go On","1998","35.405"
"5","Bryan Adams","(Everything I Do) I Do it For You","1991"
"6","The Beatles","Hey Jude","1968"
"7","Whitney Houston","I Will Always Love You","1992","34.560"
"8","Pink Floyd","Another Brick in the Wall (part 2)","1980"
"9","Irene Cara","Flashdance... What a Feeling","1983"
"10","Elton John","Candle in the Wind '97","1992"

my files consists of 3000 lines data with additional fields but i am interested to extract how many songs are released in every year

i tried to extract the year and songs and my code is here, but I am new in python and therefore I don't know how to solve my problem. my code is

from itertools import islice
import csv

filename = '/home/rob/traintask/top3000songs.csv'
data = csv.reader(open(filename))
# Read the column names from the first line of the file
fields = data.next()[3]  // I tried to read the year columns
print fields
count = 0
for row in data:
    # Zip together the field names and values
    items = zip(fields, row)
    item = {}   \\ here I am lost, i think i should make a dict and set year as key and no of songs as values, but I don't know how to do it
    # Add the value to our dictionary
    for (name, value) in items:
        item[name] = value.strip()
        print 'item: ', item

I am doing it completely wrong. but If somebody give me some hints or help that how i can count no of songs released in a year. i will be thankful.

Body:
2 very simple lines of code:

import pandas as pd
my_csv=pd.read_csv(filename)

and to get the number of songs per year:

songs_per_year= my_csv.groupby('year')['name'].count()


问:
Java hangman end loop
Please help me, I need to know how to end this loop three times. But how, if you know please tell me I've been working day and night. And may the Code be with you all!(Star Wars)           </p>

```<code>System.out.println("If you want to leave, type \"quit\"");
System.out.println("If you want to play again,type\"yes\" ");

Scanner input = new Scanner(System.in);
String s=input.next();
if(s.equals("quit")) {
    System.out.println("Thanks for playing the game!");
    System.exit(0);
}
if (s.equals("yes")) {
    String userInput = input.nextLine();
    userInput = userInput.toUpperCase();
    startGame();
</code>```

<p>Here is the full code:         </p>

```<code>import static Hello.Hangman.startGame;

import java.util.Scanner;
import java.util.Arrays;

public class Hangman {
    public static void main(String[] args) {
        Hangman game = new Hangman();
        Hangman.startGame();
    }

    public static void startGame() {
        Scanner Input = new Scanner(System.in);
        String first, reverse = "";
        String second, reverse2 = "";
        Scanner in = new Scanner(System.in);

        System.out.println("Welcome to Hangman!");
        System.out.println("Enter your first name.");
        first = in.nextLine();
        System.out.println("Enter your last name to play.");
        second = in.nextLine();

        int length = first.length();
        int length2 = second.length();
        for (int i = length - 1; i >= 0; i--)
            reverse = reverse + first.charAt(i);
        reverse = reverse.substring(0, 1).toUpperCase()++ reverse.substring(1).toLowerCase();
        for (int i = length2 - 1; i >= 0; i--)
            reverse2 = reverse2 + second.charAt(i);
        reverse2 = reverse2.substring(0, 1).toUpperCase() + reverse2.substring(1).toLowerCase();

        System.out.println("Your name entered in reverse    is: " + reverse + " " + reverse2);
        System.out.println("Press enter to continue:");
        in.nextLine();

        String[] CollectionOfWords =
                {"", "world", "about", "again", "heart", "pizza",
                        "earth", "stars", "light", "music", "party",
                        "seven", "three", "happy", "water", "amber",
                        "apple", "piano", "green", "mouth", "suger",
                        "stone", "japan", "china", "after", "smile",
                        "south", "house", "stake", "guess", "wrong",
                        "thing", "write", "white", "black", "lemon",
                        "anime", "stick", "outer", "input", "grand",
                        "lives", "twice", "print", "hangs", "woman",
                        "power", "today", "india", "night", "candy",
                        "puppy", "latin", "vegan", "phone", "april",
                        "forum", "birth", "other", "chris", "irish",
                        "paste", "queen", "grace", "crazy", "plant",
                        "knife", "spike", "darth", "vader", "eagle",
                        "egypt", "range", "fists", "fight", "glory",
                        "March", "smart", "magic", "codes", "rolls",
                        "match", "honor", "glass", "board", "teams",
                        "bully", "zebra", "under", "mango", "brain",
                        "dirty", "eight", "zeros", "train", "cycle",
                        "break", "necks", "terms", "slide", "large"};

        int randNumber = (int) Math.ceil(Math.random() * CollectionOfWords.length);
        int counter = 5;
        String radmWord = CollectionOfWords[randNumber];

        char[] genRadmLetter = radmWord.toCharArray();
        char[] genRadmLetter2 = radmWord.toCharArray();
        for (int x = 0; x < genRadmLetter.length; x++) {
            genRadmLetter[x] = '-';
        }

        System.out.println(String.valueOf(genRadmLetter));
        System.out.println("Hello" + " " + reverse + " " + reverse2 + " " + "guess a letter");
        char guessedLetter = Input.next().charAt(0);
        int RW = radmWord.indexOf(guessedLetter);

        if (RW >= 0) {

            genRadmLetter[RW] = guessedLetter;
            System.out.println(genRadmLetter);

        }

        if (RW == -1) {
            System.out.println("Wrong letter, try again.");
            counter = counter - 1;
            System.out.println("Lives left: " + counter);
        }

        while (counter != 0) {

            System.out.println("Guess a letter.");
            guessedLetter = Input.next().charAt(0);
            RW = radmWord.indexOf(guessedLetter);

            if (RW >= 0) {

                genRadmLetter[RW] = guessedLetter;
                System.out.println(genRadmLetter);

            }

            if (RW == -1) {
                System.out.println("Wrong letter, try again.");
                counter = counter - 1;
                System.out.println("Lives left: " + counter);
            }

            boolean result = Arrays.equals(genRadmLetter, genRadmLetter2);
            if (result == true) {

                return;
            }
            for (int i = 0; i < genRadmLetter.length; i++) {
                if (radmWord.charAt(i) == guessedLetter) {
                    genRadmLetter[i] = guessedLetter;
                    result = true;
                }
            }
            if (counter == 0) {
                break;
            }

        }

        if (counter == 0) {
            System.out.println("You lost. The word was: " + radmWord);
            playAgain();

            if (RW == 0)
                System.out.println("Well done, you have guessed the word.");
            System.out.println("Your final score is: " + counter);

        }
    }

    public static boolean playAgain() {

        while (true) {

            System.out.println("If you want to leave, type \"quit\"");
            System.out.println("If you want to play again,type\"yes\" ");

            Scanner input = new Scanner(System.in);
            String s = input.next();
            if (s.equals("quit")) {
                System.out.println("Thanks for playing the game!");
                System.exit(0);
            }
            if (s.equals("yes")) {

                String userInput = input.nextLine();
                userInput = userInput.toUpperCase();
                startGame();

            } else {

            }
        }
    }
}
</code>```

答:
instead

```<code>while (true) {
</code>```

you can have counter

```<code>int count=0;
while (count<3) {
count++;
</code>```

Title: Java hangman end loop

Body:
Please help me, I need to know how to end this loop three times. But how, if you know please tell me I've been working day and night. And may the Code be with you all!(Star Wars)

System.out.println("If you want to leave, type \"quit\"");
System.out.println("If you want to play again,type\"yes\" ");

Scanner input = new Scanner(System.in);
String s=input.next();
if(s.equals("quit")) {
    System.out.println("Thanks for playing the game!");
    System.exit(0);
}
if (s.equals("yes")) {
    String userInput = input.nextLine();
    userInput = userInput.toUpperCase();
    startGame();

Here is the full code:

import static Hello.Hangman.startGame;

import java.util.Scanner;
import java.util.Arrays;

public class Hangman {
    public static void main(String[] args) {
        Hangman game = new Hangman();
        Hangman.startGame();
    }

    public static void startGame() {
        Scanner Input = new Scanner(System.in);
        String first, reverse = "";
        String second, reverse2 = "";
        Scanner in = new Scanner(System.in);

        System.out.println("Welcome to Hangman!");
        System.out.println("Enter your first name.");
        first = in.nextLine();
        System.out.println("Enter your last name to play.");
        second = in.nextLine();

        int length = first.length();
        int length2 = second.length();
        for (int i = length - 1; i >= 0; i--)
            reverse = reverse + first.charAt(i);
        reverse = reverse.substring(0, 1).toUpperCase()++ reverse.substring(1).toLowerCase();
        for (int i = length2 - 1; i >= 0; i--)
            reverse2 = reverse2 + second.charAt(i);
        reverse2 = reverse2.substring(0, 1).toUpperCase() + reverse2.substring(1).toLowerCase();

        System.out.println("Your name entered in reverse    is: " + reverse + " " + reverse2);
        System.out.println("Press enter to continue:");
        in.nextLine();

        String[] CollectionOfWords =
                {"", "world", "about", "again", "heart", "pizza",
                        "earth", "stars", "light", "music", "party",
                        "seven", "three", "happy", "water", "amber",
                        "apple", "piano", "green", "mouth", "suger",
                        "stone", "japan", "china", "after", "smile",
                        "south", "house", "stake", "guess", "wrong",
                        "thing", "write", "white", "black", "lemon",
                        "anime", "stick", "outer", "input", "grand",
                        "lives", "twice", "print", "hangs", "woman",
                        "power", "today", "india", "night", "candy",
                        "puppy", "latin", "vegan", "phone", "april",
                        "forum", "birth", "other", "chris", "irish",
                        "paste", "queen", "grace", "crazy", "plant",
                        "knife", "spike", "darth", "vader", "eagle",
                        "egypt", "range", "fists", "fight", "glory",
                        "March", "smart", "magic", "codes", "rolls",
                        "match", "honor", "glass", "board", "teams",
                        "bully", "zebra", "under", "mango", "brain",
                        "dirty", "eight", "zeros", "train", "cycle",
                        "break", "necks", "terms", "slide", "large"};

        int randNumber = (int) Math.ceil(Math.random() * CollectionOfWords.length);
        int counter = 5;
        String radmWord = CollectionOfWords[randNumber];

        char[] genRadmLetter = radmWord.toCharArray();
        char[] genRadmLetter2 = radmWord.toCharArray();
        for (int x = 0; x < genRadmLetter.length; x++) {
            genRadmLetter[x] = '-';
        }

        System.out.println(String.valueOf(genRadmLetter));
        System.out.println("Hello" + " " + reverse + " " + reverse2 + " " + "guess a letter");
        char guessedLetter = Input.next().charAt(0);
        int RW = radmWord.indexOf(guessedLetter);

        if (RW >= 0) {

            genRadmLetter[RW] = guessedLetter;
            System.out.println(genRadmLetter);

        }

        if (RW == -1) {
            System.out.println("Wrong letter, try again.");
            counter = counter - 1;
            System.out.println("Lives left: " + counter);
        }

        while (counter != 0) {

            System.out.println("Guess a letter.");
            guessedLetter = Input.next().charAt(0);
            RW = radmWord.indexOf(guessedLetter);

            if (RW >= 0) {

                genRadmLetter[RW] = guessedLetter;
                System.out.println(genRadmLetter);

            }

            if (RW == -1) {
                System.out.println("Wrong letter, try again.");
                counter = counter - 1;
                System.out.println("Lives left: " + counter);
            }

            boolean result = Arrays.equals(genRadmLetter, genRadmLetter2);
            if (result == true) {

                return;
            }
            for (int i = 0; i < genRadmLetter.length; i++) {
                if (radmWord.charAt(i) == guessedLetter) {
                    genRadmLetter[i] = guessedLetter;
                    result = true;
                }
            }
            if (counter == 0) {
                break;
            }

        }

        if (counter == 0) {
            System.out.println("You lost. The word was: " + radmWord);
            playAgain();

            if (RW == 0)
                System.out.println("Well done, you have guessed the word.");
            System.out.println("Your final score is: " + counter);

        }
    }

    public static boolean playAgain() {

        while (true) {

            System.out.println("If you want to leave, type \"quit\"");
            System.out.println("If you want to play again,type\"yes\" ");

            Scanner input = new Scanner(System.in);
            String s = input.next();
            if (s.equals("quit")) {
                System.out.println("Thanks for playing the game!");
                System.exit(0);
            }
            if (s.equals("yes")) {

                String userInput = input.nextLine();
                userInput = userInput.toUpperCase();
                startGame();

            } else {

            }
        }
    }
}

Body:
instead

while (true) {

you can have counter

int count=0;
while (count<3) {
count++;


问:
Cannot show the "block" by using JavaScript
I cannot show the block "login" after the page has loaded.
I already tried using visibility or display to make the "block" hidden or not.

And already tried to put the script part into different place:

<!DOCTYPE html>

  <meta charset="utf-8" />
  <link rel="stylesheet" type="text/css" href="../css/common.css">

  <title>City's Video</title>

      <form method="post" action="home.html">
        Name: <input type="text" name="name">
 Password: <input type="password" name="password">

        <input type="submit" name="Login" value="Login"> <input type="reset" value="reset">
      </form>

```

答:
getElementsByClassName would return a collection of HTML elements. So, we need to iterate over the collection or be more specific on which element is needed.

Alternative approach would be to use document.querySelectorAll or document.querySelector.

Sample snippet below:

window.onload = function() {

  document.querySelectorAll("#logvid > .login").forEach(function(element, index, array) {
    element.style.display = 'block';
    element.style.border = "1px solid green";
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.login {
  display: none;
}</code>```

    <form method="post" action="home.html">
      Name: <input type="text" name="name">
 Password: <input type="password" name="password">

      <input type="submit" name="Login" value="Login"> <input type="reset" value="reset">
    </form>

```

Body:
getElementsByClassName would return a collection of HTML elements. So, we need to iterate over the collection or be more specific on which element is needed.

Alternative approach would be to use document.querySelectorAll or document.querySelector.

Sample snippet below:

window.onload = function() {

  document.querySelectorAll("#logvid > .login").forEach(function(element, index, array) {
    element.style.display = 'block';
    element.style.border = "1px solid green";
  });
}

.login {
  display: none;
}

<div id="logvid">
  <div class="login">
    <form method="post" action="home.html">
      Name: <input type="text" name="name"><br> Password: <input type="password" name="password"><br><br>
      <input type="submit" name="Login" value="Login"> <input type="reset" value="reset">
    </form>
  </div>
</div>


问:
Javascript select option application
I am trying to create the select application using Javascipt only. I got to know about this code on internet

```<code><!DOCTYPE html>
<html>
<head>
    <title>Select Options</title>
</head>
<body>

<h2>Choose your car</h2>
<hr>

Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Hyundai">Hyundai</option>
    <option value="Honda">Honda</option>
    <option value="Maruti">Maruti</option>
</select>

<hr>

Choose Car Model
<select id="slct2" ></select>

</body>

<script type="text/javascript">

    function populate(s1,s2){
        var s1,s2;
        s1 = document.getElementById(s1);
        s2 = document.getElementById(s2);

        if(s1.value=='Hyundai'){
            optionArray=['Please Select Car','i10','i20','Verna']
        } else
        if(s1.value=='Honda'){
            optionArray=['Please Select Car','Amaze','Jazz','City']
        } else
        if(s1.value=='Maruti'){
            optionArray=['Please Select Car','Swift','Dezire','Ciaze']
        }

        for (var i = 0; i < optionArray.length; i++) {
        var store = optionArray[i];
        var createNewEl = document.createElement('option');
        createNewEl.innerHTML = store;
        s2.appendChild(createNewEl);
        }

    }

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

This is the full code I use now to write this apllication but I everytime I select option from car make ** and when I select another option fromcar make**, it does not delete the previous options from car model and the list gets increased so on everytime I select option from car make

答:
s2.appendChild(createNewEl); adds to a list of whatever

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_node_appendchild

Title: Javascript select option application

Body:
I am trying to create the select application using Javascipt only. I got to know about this code on internet

<!DOCTYPE html>

    <title>Select Options</title>

Choose your car

Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Hyundai">Hyundai</option>
    <option value="Honda">Honda</option>
    <option value="Maruti">Maruti</option>
</select>

Choose Car Model
<select id="slct2" ></select>

This is the full code I use now to write this apllication but I everytime I select option from car make ** and when I select another option fromcar make**, it does not delete the previous options from car model and the list gets increased so on everytime I select option from car make


问:
difficulty to plot a hist of chi-square~(1) over a simulated chi-square confidence interval
I am trying to code example 10.3.2 from statistical inference by casella. ( I attached the example here ).

I have issue with producing the same plot.  any help?

to simulate the data and  the comparison table:

```<code> n=25
lam<-5
nsim<-10000
set.seed(442256)

poisson<-function(nsim,n,lam){
    ratio<-c()

distributionMean = NULL
for (i in 1 : nsim) distributionMean = c(distributionMean, mean(rpois( n, lam)))

 d<- 2*n*((lam-distributionMean)-distributionMean*log(lam/distributionMean))
        ratio<-c(ratio,d)
        return(ratio )
    }

logLi<-poisson(10000,25,5)

m<-matrix(0,2, 4)
m[1,1]=quantile(p1,0.80)
m[2,1]=qchisq(.80, df=1)

m[1,2]=quantile(p1,0.90)
m[2,2]=qchisq(.90, df=1)

m[1,3]=quantile(p1,0.95)
m[2,3]=qchisq(.95, df=1)

m[1,4]=quantile(p1,0.99)
m[2,4]=qchisq(.99, df=1)
    row.names(m)<-c("simulated", "Chi-square")
    colnames(m)<-c("80_perc", "90_perc","95_perc","99_perc")
</code>```

答:
Do you want the table?  Try this.

```<code>simulated <- quantile(logLi, c(0.8, 0.9, 0.95, 0.99))
chisquare <- qchisq(c(0.8, 0.9, 0.95, 0.99), df = 1)

rbind(simulated, chisquare)
</code>```

And the code for the graph is below.

```<code>a <- hist(logLi, freq=FALSE, xlim = c(0,4),
          breaks = seq(0, ceiling(max(logLi)), by = 0.1))
lines(a$mids, dchisq(a$mids, df = 1))
</code>```

Body:
I am trying to code example 10.3.2 from statistical inference by casella. ( I attached the example here ).

I have issue with producing the same plot.  any help?

to simulate the data and  the comparison table:

 n=25
lam<-5
nsim<-10000
set.seed(442256)

poisson<-function(nsim,n,lam){
    ratio<-c()

distributionMean = NULL
for (i in 1 : nsim) distributionMean = c(distributionMean, mean(rpois( n, lam)))

 d<- 2*n*((lam-distributionMean)-distributionMean*log(lam/distributionMean))
        ratio<-c(ratio,d)
        return(ratio )
    }

logLi<-poisson(10000,25,5)

m<-matrix(0,2, 4)
m[1,1]=quantile(p1,0.80)
m[2,1]=qchisq(.80, df=1)

m[1,2]=quantile(p1,0.90)
m[2,2]=qchisq(.90, df=1)

m[1,3]=quantile(p1,0.95)
m[2,3]=qchisq(.95, df=1)

m[1,4]=quantile(p1,0.99)
m[2,4]=qchisq(.99, df=1)
    row.names(m)<-c("simulated", "Chi-square")
    colnames(m)<-c("80_perc", "90_perc","95_perc","99_perc")

Body:
Do you want the table?  Try this.

simulated <- quantile(logLi, c(0.8, 0.9, 0.95, 0.99))
chisquare <- qchisq(c(0.8, 0.9, 0.95, 0.99), df = 1)

rbind(simulated, chisquare)

And the code for the graph is below.

a <- hist(logLi, freq=FALSE, xlim = c(0,4),
          breaks = seq(0, ceiling(max(logLi)), by = 0.1))
lines(a$mids, dchisq(a$mids, df = 1))


问:
Round numbers in array to 2 decimals
In a array of numbers that have 4 decimals, how can I round them with only 2 decimals? I'm also using a str_replace to replace commas with dots.

```<code>foreach($data as $key => $value) {

  $vf .= str_replace(",", ".", round($value['vf'])); // gives 1.111, 2.222 etc
  $vf .= str_replace(",", ".", round($value['vf'],2)); // does nothing
}
</code>```

How can I round the values to a number with 2 digits, like 1.11?

答:
You can use number_format.

```<code>$n = 12.34567890;
echo number_format($n, 2, '.');
// 12.35
</code>```

You can even use it to add a thousands separator:

```<code>$n = 12345.67890;
echo number_format($n, 2, '.', ',');
// 12,345.68
</code>```

Or you can use round.

```<code>$n = 12.34567890;
echo round($n, 2);
// 12.35
</code>```

Title: Round numbers in array to 2 decimals

Body:
In a array of numbers that have 4 decimals, how can I round them with only 2 decimals? I'm also using a str_replace to replace commas with dots.

foreach($data as $key => $value) {

  $vf .= str_replace(",", ".", round($value['vf'])); // gives 1.111, 2.222 etc
  $vf .= str_replace(",", ".", round($value['vf'],2)); // does nothing
}

How can I round the values to a number with 2 digits, like 1.11?

Body:
You can use number_format.

$n = 12.34567890;
echo number_format($n, 2, '.');
// 12.35

You can even use it to add a thousands separator:

$n = 12345.67890;
echo number_format($n, 2, '.', ',');
// 12,345.68

Or you can use round.

$n = 12.34567890;
echo round($n, 2);
// 12.35


问:
Difference Between arr1.concat(arr2) And [].concat(arr1, arr2)
In JavaScript, I've encountered code written in two primary ways for concatenating two (or more) arrays that employ the .concat() method on the Array object. (Assume, in what follows, that arr1 and arr2 are generic arrays given as the arguments to the .concat() method). At times, I see

```<code>arr1.concat(arr2)
</code>```

while, at others, I see the following used:

```<code>[].concat(arr1, arr2)
</code>```

I have not, in practice, found there to be any observable difference between the two manners of expression. Neither mutates the original array(s). Both return an identical output.

What differences, if any, are there? Is one more performant over the other? Do Best Practices advise one in particular?

Many thanks for all help/feedback!

EDIT

Shoutout for the JSPerf benchmarking test. It seems, as was noted by some in comments, that arr1.concat(arr2) is the preferred (and more natural syntax) as compared to [].concat(arr1, arr2). (I suppose that comes a bit subjectively, but feel most would agree in retrospect). Even so, there's added value to be had in choosing the former syntax over the latter if for no other reason than the marginally improved performance that it comes with.

答:
If both arr1 and arr2 are plain arrays, there is absolutely no difference. It's merely two notations for the same thing, one more object-oriented and the other more functional. One might argue that [].concat(…) is less efficient because it has to construct and iterate an empty array, but that should hardly be measurable.

The difference is observable though when arr1 is not an Array. Obviously it might call a different concat method then, or even throw when there is none (or when arr1 is null or undefined); but also when it calls the Array.prototype.concat method the arr1 won't be checked for being spreadable.

Body:
In JavaScript, I've encountered code written in two primary ways for concatenating two (or more) arrays that employ the .concat() method on the Array object. (Assume, in what follows, that arr1 and arr2 are generic arrays given as the arguments to the .concat() method). At times, I see

arr1.concat(arr2)

while, at others, I see the following used:

[].concat(arr1, arr2)

I have not, in practice, found there to be any observable difference between the two manners of expression. Neither mutates the original array(s). Both return an identical output.

What differences, if any, are there? Is one more performant over the other? Do Best Practices advise one in particular?

Many thanks for all help/feedback!

EDIT

Shoutout for the JSPerf benchmarking test. It seems, as was noted by some in comments, that arr1.concat(arr2) is the preferred (and more natural syntax) as compared to [].concat(arr1, arr2). (I suppose that comes a bit subjectively, but feel most would agree in retrospect). Even so, there's added value to be had in choosing the former syntax over the latter if for no other reason than the marginally improved performance that it comes with.


问:
Repeating local notifications iOS 10
Has anyone been successful at scheduling a repeating hourly local notification with UNUserNotificationCenter without creating multiple request?

I need to be able to schedule hourly notifications to go off at a specific minute from which the first notification is set to go off. I am able to do this using the old UILocalNotification framework but I want to be able to take advantage of notification extensions, titles, subtitles etc that come along with the new notifications framework.

If it's not possible to schedule a single request that repeats hourly at a specific time, has anyone found a way to achieve this using multiple requests? And doing so without requiring the user to action against the first notification?

My other concern with scheduling multiple requests is that my app allows a user to create multiple reminders and I don't want to limit the user due to the 64 notification cap

Edit:
My current use case is, it's 6:30am and I want to schedule a notification to trigger at 10:43 pm and from that point repeat hourly at 43 minutes past every hour. This is currently achievable with UILocalNotification using repeatInterval and setting the units to hour, so it will fire at that time and every hour after

答:
In sentence

to schedule a notification to trigger at 10:43 pm and from that point
  repeat hourly at 43 minutes past every hour

only "from that point" is impossible.

You can create UNNotificationRequest with UNCalendarNotificationTrigger with DateComponents(minute: 43, second: 00) which will start firing at XX:43:00 every hour since request will be added to UNUserNotificationCenter.

The only problem left is to add it in period from 09:44pm to 10:42pm so it will not start firing too early. I don't see beautiful way to accomplish that, but if push notification is good enough for you - it can be a trigger that will add request to notification center.

Title: Repeating local notifications iOS 10


问:
Neo4j - Java heap space. Wrong query or settings?
i have a problem with neo4j.
I don't know if problem is my query or something else.

Intro

I have to build an application that store bus/train routes.
This is my schema:

Nodes:

Organizaton: company that have routes/bus etc..

Route: A bus route like: Paris - Berlin.

Vehicle(Bus in this case): Fisical bus with a unique license plate.

Stops: point in a map with latitude and longitude.

Important Relationships:

NEXT: This is a really important relationship.

NEXT relationships contains those properties:

startHour

startMinutes

endHour

endMinutes

dayOfWeek (from 0 to 6 - Sun, Mon etc..)

vehicleId

Problem

My query is:

```<code>MATCH (s1:Stop {id: {departureStopId}}), (s2:Stop {id: {arrivalStopId}})
OPTIONAL MATCH (s1)-[nexts:NEXT*]->(s2)
WHERE ALL(i in nexts WHERE toInt(i.dayOfWeek) = {dayOfWeek} AND toInt(i.startHour) >= {hour})
RETURN nexts
LIMIT 10
</code>```

For example: I wanna found all nexts relationships where dayOfWeek is Sunday (0) and property startHour > 11

After that I usually parse and validate final object on my nodejs backend.

This works when i was at the start.. with 1k relationships..
Now i have 10k relationships and my query have a TIMEOUT problem or queries are solved in 30s.. too much time...
I have no idea how to solve this.
I use neo4j with docker and i tried to read settings docs but i have no idea how Java works.

Can you help me guys?

UPDATE

Thank you all guys!
For now i solved with "allShortestPaths" but I think i will rename all relationships (like Michael Hunger said).

答:
It's not settings; it's the fact that your query must visit each and every node in the graph in order to satisfy the query.

The problem would show itself in a relational database when a TABLE SCAN had to be used instead of an index.

I think the solution is to add buckets for hours, like you already have for days. If you have to have minutes, make 96 fifteen minute buckets to cover a day. That will give the query optimizer its best chance.

Body:
i have a problem with neo4j.
I don't know if problem is my query or something else.

Intro

I have to build an application that store bus/train routes.
This is my schema:

Nodes:

Organizaton: company that have routes/bus etc..

Route: A bus route like: Paris - Berlin.

Vehicle(Bus in this case): Fisical bus with a unique license plate.

Stops: point in a map with latitude and longitude.

Important Relationships:

NEXT: This is a really important relationship.

NEXT relationships contains those properties:

startHour

startMinutes

endHour

endMinutes

dayOfWeek (from 0 to 6 - Sun, Mon etc..)

vehicleId

Problem

My query is:

MATCH (s1:Stop {id: {departureStopId}}), (s2:Stop {id: {arrivalStopId}})
OPTIONAL MATCH (s1)-[nexts:NEXT*]->(s2)
WHERE ALL(i in nexts WHERE toInt(i.dayOfWeek) = {dayOfWeek} AND toInt(i.startHour) >= {hour})
RETURN nexts
LIMIT 10

For example: I wanna found all nexts relationships where dayOfWeek is Sunday (0) and property startHour > 11

After that I usually parse and validate final object on my nodejs backend.

This works when i was at the start.. with 1k relationships..
Now i have 10k relationships and my query have a TIMEOUT problem or queries are solved in 30s.. too much time...
I have no idea how to solve this.
I use neo4j with docker and i tried to read settings docs but i have no idea how Java works.

Can you help me guys?

UPDATE

Thank you all guys!
For now i solved with "allShortestPaths" but I think i will rename all relationships (like Michael Hunger said).


问:
PHP: Is it better to concatenate on 1 line or multiple lines? Or is there a difference?
Is there a difference or is one better than the other of the following:

```<code>$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';
</code>```

Or

```<code>$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';
</code>```

Is there a speed difference or is there a reason why you'd pick one over the other?

答:
Won't make a difference. Both are concatenation, so whatever is easiest to read is what you should use.

If you're after best-performing, try using an array and then implode it when you've finished.

```<code>$var = array();
$var[] = "line 1\n";
$var[] = "line 2\n";
$var[] = "line 3";
$var = implode('', $var);
</code>```

Any way you do it the speed difference will be negligible unless you are working with thousands of big strings.

OwnerDisplayName: Darryl Hein

ContentLicense: CC BY-SA 2.5

Body:
Is there a difference or is one better than the other of the following:

$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';

Or

$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';

Is there a speed difference or is there a reason why you'd pick one over the other?

LastEditorDisplayName: Paul Dixon

Body:
Won't make a difference. Both are concatenation, so whatever is easiest to read is what you should use.

If you're after best-performing, try using an array and then implode it when you've finished.

$var = array();
$var[] = "line 1\n";
$var[] = "line 2\n";
$var[] = "line 3";
$var = implode('', $var);

Any way you do it the speed difference will be negligible unless you are working with thousands of big strings.

OwnerDisplayName: Christopher Nadeau


问:
Creating a Partial Class for a Form
I would like to create a partial class for my form. I have a lot of events, and it  gets messy, so I would like to break up sections into their own files.

The problem: When I create a partial class of my form, say:

```<code>Partial Public Class Form1

End Class
</code>```

Visual Studio decides I need another form for this partial class.

Questions:

1. How do I create a partial class for a form?

2. If I cant do that, how can I break up all the events in my form into different files?

答:
Yeah, it does.  As soon as you drop a control on this phantom form, you'll get the design-time code (InitializeComponent) generated into that source code file.  This is compatibility behavior for .NET 1.x, it didn't support the Partial keyword.  Which will break the build, there are now two of them.  It is somewhat avoidable with careful clicking, but you know it's going to happen sooner or later.

Other things go wrong too btw, the designer can no longer track an event handler when you move it from one file to another.  And will readily let you add another, a much trickier source of bugs.

This just doesn't work very well, abandon hope of relying on it to solve your problem.

The generic diagnostic is that a convoluted user interface begets convoluted code.  But that ship has sailed, no doubt.  A more structural solution is pursuing the MVC model, separating the data from the view of the data.  You'll still have a lot of event handlers but they won't do anything more than calling a method of a class that does the real work.  Whose source code can of course live in another source code file.  The typical hangup is that Windows Forms has no support whatsoever built in for this, you have to craft it by hand.  Nothing similar to the MVVM model in WPF.

Something that can work well is isolating control + code into a separate UserControl.  You have to do so carefully though, you don't want to have to add a bunch of properties and events that expose internal controls.

Title: Creating a Partial Class for a Form

Body:
I would like to create a partial class for my form. I have a lot of events, and it  gets messy, so I would like to break up sections into their own files.

The problem: When I create a partial class of my form, say:

Partial Public Class Form1

End Class

Visual Studio decides I need another form for this partial class.

Questions:

1. How do I create a partial class for a form?

2. If I cant do that, how can I break up all the events in my form into different files?


问:
Multiple database support in C#
My application need to support multiple databases. Currently, it supports Postgres now I am adding support for Orcle and may be SqlServer in upcoming days.

Before asking any question lets look at codes.

IDbParser :

```<code>public interface IDbParser
{
    IDbConnection GetDbConnection(string ServerName, string DbPortNumber, string Username, string Password, string DatabaseName);
    IDbCommand GetDbCommand(string query, IDbConnection sqlConnection);
    IDataParameter CreateParameter(string key, object value);
    string GetDbQuery(DbQueries query);
}
</code>```

OracleDbParser :

```<code>public class OracleParser : IDbParser
{
    #region >>> Queries
    private string SELECTGROUPSESSIONS = "....";
    ........
    #endregion

    public IDbCommand GetDbCommand(string query, IDbConnection sqlConnection)
    {
        var command = new OracleCommand();
        command.CommandText = query;
        command.Connection = (OracleConnection)sqlConnection;
        command.CommandType = CommandType.Text;
        command.CommandTimeout = 300;
        return command;
    }

    public IDataParameter CreateParameter(string key, object value)
    {
        return new OracleParameter(key, value);
    }

    public IDbConnection GetDbConnection(string ServerName, string DbPortNumber, string Username, string Password, string DatabaseName)
    {
        connString = String.Format("Data Source=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1})))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={2}))); Connection Timeout=60; User Id={3};Password={4};",
                                                ServerName, DbPortNumber, DatabaseName, Username, Password);
        return new OracleConnection(connString);
    }

    public string GetDbQuery(DbQueries query)
    {
        switch (query)
        {
            case DbQueries.SELECTGROUPSESSIONS:
                return SELECTGROUPSESSIONS;
            ................
            ..............
            default:
                return String.Empty;
        }
    }
}
</code>```

Similarly, there is parser for Postgres :

```<code>public class PostgresParser : IDbParser
{
    #region >>> Queries
    private string SELECTGROUPSESSIONS = "....";
    ........
    #endregion

   public IDbCommand GetDbCommand(string query, IDbConnection sqlConnection)
    {
        var command = new NpgsqlCommand();
        command.CommandText = query;
        command.Connection = (NpgsqlConnection)sqlConnection;
        command.CommandType = CommandType.Text;
        return command;
    }

    public IDataParameter CreateParameter(string key, object value)
    {
        return new NpgsqlParameter(key, value);
    }

    public IDbConnection GetDbConnection(string ServerName, string DbPortNumber, string Username, string Password, string DatabaseName)
    {
        string connString = String.Format("Server={0};Port={1};Timeout=60;CommandTimeout=300;" +
                                            "User Id={2};Password={3};Database={4};",
                                            ServerName, DbPortNumber, Username, Password, DatabaseName);
        return new NpgsqlConnection(connString);
    }

    public string GetDbQuery(DbQueries query)
    {
        switch (query)
        {
            case DbQueries.SELECTGROUPSESSIONS:
                return SELECTGROUPSESSIONS;
            ................
            ..............
            default:
                return String.Empty;
        }
    }
}
</code>```

DatabaseParserFactory:

```<code> public class DatabaseParserFactory
{
    public static IDbParser GetDbParser(string dbType)
    {
        CUCMDbType dbTypeName;
        Enum.TryParse(dbType.ToLower(), out dbTypeName);
        switch (dbTypeName)
        {
            case CUCMDbType.oracle:
                return new OracleParser();
            case CUCMDbType.postgres:
                return new PostgresParser();
            default:
                return new PostgresParser();
        }
    }
}
</code>```

Query execution :

```<code> public void Query(string queryStatement, DbParameterColl parameters, Action<IDataReader> processReader)
    {
        using (SqlConnection)
        {
            IDbCommand selectCommand = null;
            selectCommand = _factory.GetDbCommand(queryStatement, SqlConnection);
            selectCommand.Parameters.Clear();

            using (selectCommand)
            {
                if (parameters != null)
                {
                    foreach (var param in parameters)
                    {
                        selectCommand.Parameters.Add(_factory.CreateParameter(param.Key, param.Value));
                    }
                }

                try
                {
                    using (var reader = selectCommand.ExecuteReader())
                    {
                        processReader(reader);
                    }

                }
                catch (Exception ex)
                {
                    Logger.DebugFormat("Unable to execute the query. Query : {0} . Exception: {1}", queryStatement, ex);
                    Debug.WriteLine("\n\n>> Error on executing reader. Exception :\n " + ex);
                }
            }
        }
    }
</code>```

FYI: There will only be SELECT queries and no other commands.

I am passing parameter's value as an object. Well, currently there is no problem assigning the parameters and executing the query. But in most of the blogs and in stackoverflow I could see that people have been suggesting to specify the Input direction, and most specifically Input type/DbType. Do I need to specify DbType ? Currently, my code runs fine with no errors. But I am afraid, it might break down in production.

Moreover I have no control over the type of parameter, it could be anything.
So what do you guys suggest? Or is there any better approach of doing this ?

答:
First, you should take a look at DbProviderFactories - most of your code duplicates that already-existing standard functionality. Note that it is not yet available in .NET Core (but will be).

Regarding your question, in general you don't need to specify the parmeter direction - it's assumed to be the default. Database drivers can typically infer the database type from the CLR value you assign to a parameter, but it's a good idea to explicitly specify DbType just to be sure.

Title: Multiple database support in C#

Body:
My application need to support multiple databases. Currently, it supports Postgres now I am adding support for Orcle and may be SqlServer in upcoming days.

Before asking any question lets look at codes.

IDbParser :

public interface IDbParser
{
    IDbConnection GetDbConnection(string ServerName, string DbPortNumber, string Username, string Password, string DatabaseName);
    IDbCommand GetDbCommand(string query, IDbConnection sqlConnection);
    IDataParameter CreateParameter(string key, object value);
    string GetDbQuery(DbQueries query);
}

OracleDbParser :

public class OracleParser : IDbParser
{
    #region >>> Queries
    private string SELECTGROUPSESSIONS = "....";
    ........
    #endregion

    public IDbCommand GetDbCommand(string query, IDbConnection sqlConnection)
    {
        var command = new OracleCommand();
        command.CommandText = query;
        command.Connection = (OracleConnection)sqlConnection;
        command.CommandType = CommandType.Text;
        command.CommandTimeout = 300;
        return command;
    }

    public IDataParameter CreateParameter(string key, object value)
    {
        return new OracleParameter(key, value);
    }

    public IDbConnection GetDbConnection(string ServerName, string DbPortNumber, string Username, string Password, string DatabaseName)
    {
        connString = String.Format("Data Source=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1})))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={2}))); Connection Timeout=60; User Id={3};Password={4};",
                                                ServerName, DbPortNumber, DatabaseName, Username, Password);
        return new OracleConnection(connString);
    }

    public string GetDbQuery(DbQueries query)
    {
        switch (query)
        {
            case DbQueries.SELECTGROUPSESSIONS:
                return SELECTGROUPSESSIONS;
            ................
            ..............
            default:
                return String.Empty;
        }
    }
}

Similarly, there is parser for Postgres :

public class PostgresParser : IDbParser
{
    #region >>> Queries
    private string SELECTGROUPSESSIONS = "....";
    ........
    #endregion

   public IDbCommand GetDbCommand(string query, IDbConnection sqlConnection)
    {
        var command = new NpgsqlCommand();
        command.CommandText = query;
        command.Connection = (NpgsqlConnection)sqlConnection;
        command.CommandType = CommandType.Text;
        return command;
    }

    public IDataParameter CreateParameter(string key, object value)
    {
        return new NpgsqlParameter(key, value);
    }

    public IDbConnection GetDbConnection(string ServerName, string DbPortNumber, string Username, string Password, string DatabaseName)
    {
        string connString = String.Format("Server={0};Port={1};Timeout=60;CommandTimeout=300;" +
                                            "User Id={2};Password={3};Database={4};",
                                            ServerName, DbPortNumber, Username, Password, DatabaseName);
        return new NpgsqlConnection(connString);
    }

    public string GetDbQuery(DbQueries query)
    {
        switch (query)
        {
            case DbQueries.SELECTGROUPSESSIONS:
                return SELECTGROUPSESSIONS;
            ................
            ..............
            default:
                return String.Empty;
        }
    }
}

DatabaseParserFactory:

 public class DatabaseParserFactory
{
    public static IDbParser GetDbParser(string dbType)
    {
        CUCMDbType dbTypeName;
        Enum.TryParse(dbType.ToLower(), out dbTypeName);
        switch (dbTypeName)
        {
            case CUCMDbType.oracle:
                return new OracleParser();
            case CUCMDbType.postgres:
                return new PostgresParser();
            default:
                return new PostgresParser();
        }
    }
}

Query execution :

 public void Query(string queryStatement, DbParameterColl parameters, Action<IDataReader> processReader)
    {
        using (SqlConnection)
        {
            IDbCommand selectCommand = null;
            selectCommand = _factory.GetDbCommand(queryStatement, SqlConnection);
            selectCommand.Parameters.Clear();

            using (selectCommand)
            {
                if (parameters != null)
                {
                    foreach (var param in parameters)
                    {
                        selectCommand.Parameters.Add(_factory.CreateParameter(param.Key, param.Value));
                    }
                }

                try
                {
                    using (var reader = selectCommand.ExecuteReader())
                    {
                        processReader(reader);
                    }

                }
                catch (Exception ex)
                {
                    Logger.DebugFormat("Unable to execute the query. Query : {0} . Exception: {1}", queryStatement, ex);
                    Debug.WriteLine("\n\n>> Error on executing reader. Exception :\n " + ex);
                }
            }
        }
    }

FYI: There will only be SELECT queries and no other commands.

I am passing parameter's value as an object. Well, currently there is no problem assigning the parameters and executing the query. But in most of the blogs and in stackoverflow I could see that people have been suggesting to specify the Input direction, and most specifically Input type/DbType. Do I need to specify DbType ? Currently, my code runs fine with no errors. But I am afraid, it might break down in production.

Moreover I have no control over the type of parameter, it could be anything.
So what do you guys suggest? Or is there any better approach of doing this ?


问:
User asks twice and the second time the user gets different answer?
Well, my code is a little bit long so I just put the first part when you see x ==1 part actually it has seven parts like this. My aim is like you chose 1A and it gives you the table (that part I did it.) What I want is if the user writes 1A again the system must say sorry. How can I do this without using any packages?</p>

```<code>import java.util.Scanner;
class deneme{
    public  void printTable(String [ ][ ] seat){
        for(int r=0; r<seat.length; r++){
            for(int c = 0; c< seat[0].length; c++){
                System.out.print(seat[r][c]);
            }
            System.out.println();
        }
    }

   public static void main(String[] args) {
    deneme k = new deneme();
       String [][] seat = {{"1","A","B","C","D"},{"2","A","B","C","D"},{"3","A","B","C","D"},{"4","A","B","C","D"},{"5","A","B","C","D"},{"6","A","B","C","D"},{"7","A","B","C","D"}};
     Scanner read = new Scanner(System.in);
     int x = 6;
     String s;
     String d;

        while(x <= 7){
            System.out.println("Please choose your seat number (1 to 7).But if you want to terminate the program please write 0");
            s = read.nextLine();
            x = Integer.parseInt(s);
            System.out.println("Please choose your seat row (A to D)");
            d = read.nextLine();

        if(x == 1){
            if((d.equals("A")|| d.equals("a"))){
                seat[0][1] = "X";
                k.printTable(seat);

            }

            else if((d.equals("B")|| d.equals("b")) ){
                seat[0][2] = "X";
                System.out.println("Your seat is chosen ");
                k.printTable(seat);

            }

            else if((d.equals("C")|| d.equals("c")) ){
                seat[0][3] = "X";
                System.out.println(" Your seat is chosen ");
                k.printTable(seat);

            }

            else if((d.equals("D")|| d.equals("d")) ){
                seat[0][4] = "X";
                System.out.println(" Your seat is chosen " );
                k.printTable(seat);

            }

        }
</code>```

答:
You need a Map data structure (holds the data as key-value pair) to store which seats have been already booked.

You can refer the below steps for solving your problem using Map:

(1) When the user inputs the seat-number, check if it exists in the Map object

(2) If it exists, ie., already booked then show an error message

(3) If it doesn't exist, then allow the user to book and store it in Map

I have provided pseudocode code below which uses Map:

```<code>public class Deneme {

    private static Map<String, String> seatsUsed = new HashMap<>();

    public static void main(String[] args) {

        //add other code here

        while(x <= 7){

          //add other code here

       if(seatsUsed.get(x+d) != null) {
           System.out.println(" Sorry, seat alrady booked");
        }

       if(x == 1){
            if((d.equals("A")|| d.equals("a"))){
                seat[0][1] = "X";
                k.printTable(seat);
                seatsUsed.put(x+d, "Y");//Y indicates that booked
       }

      //add other code

      }
    }
</code>```

Also, as a side note, you have got lots of issues with your code as mentioned below:

(1) Follow Java naming conventions Class names starts with uppercase

(2) Your code is hard to follow, try to refactor into smaller methods

(3) Use existing String/other API methods effectively like you can use equalsIgnoreCase instead of writing d.equals("A")|| d.equals("a")

Body:
Well, my code is a little bit long so I just put the first part when you see x ==1 part actually it has seven parts like this. My aim is like you chose 1A and it gives you the table (that part I did it.) What I want is if the user writes 1A again the system must say sorry. How can I do this without using any packages?

import java.util.Scanner;
class deneme{
    public  void printTable(String [ ][ ] seat){
        for(int r=0; r<seat.length; r++){
            for(int c = 0; c< seat[0].length; c++){
                System.out.print(seat[r][c]);
            }
            System.out.println();
        }
    }

   public static void main(String[] args) {
    deneme k = new deneme();
       String [][] seat = {{"1","A","B","C","D"},{"2","A","B","C","D"},{"3","A","B","C","D"},{"4","A","B","C","D"},{"5","A","B","C","D"},{"6","A","B","C","D"},{"7","A","B","C","D"}};
     Scanner read = new Scanner(System.in);
     int x = 6;
     String s;
     String d;

        while(x <= 7){
            System.out.println("Please choose your seat number (1 to 7).But if you want to terminate the program please write 0");
            s = read.nextLine();
            x = Integer.parseInt(s);
            System.out.println("Please choose your seat row (A to D)");
            d = read.nextLine();

        if(x == 1){
            if((d.equals("A")|| d.equals("a"))){
                seat[0][1] = "X";
                k.printTable(seat);

            }

            else if((d.equals("B")|| d.equals("b")) ){
                seat[0][2] = "X";
                System.out.println("Your seat is chosen ");
                k.printTable(seat);

            }

            else if((d.equals("C")|| d.equals("c")) ){
                seat[0][3] = "X";
                System.out.println(" Your seat is chosen ");
                k.printTable(seat);

            }

            else if((d.equals("D")|| d.equals("d")) ){
                seat[0][4] = "X";
                System.out.println(" Your seat is chosen " );
                k.printTable(seat);

            }

        }

Body:
You need a Map data structure (holds the data as key-value pair) to store which seats have been already booked.

You can refer the below steps for solving your problem using Map:

(1) When the user inputs the seat-number, check if it exists in the Map object

(2) If it exists, ie., already booked then show an error message

(3) If it doesn't exist, then allow the user to book and store it in Map

I have provided pseudocode code below which uses Map:

public class Deneme {

    private static Map<String, String> seatsUsed = new HashMap<>();

    public static void main(String[] args) {

        //add other code here

        while(x <= 7){

          //add other code here

       if(seatsUsed.get(x+d) != null) {
           System.out.println(" Sorry, seat alrady booked");
        }

       if(x == 1){
            if((d.equals("A")|| d.equals("a"))){
                seat[0][1] = "X";
                k.printTable(seat);
                seatsUsed.put(x+d, "Y");//Y indicates that booked
       }

      //add other code

      }
    }

Also, as a side note, you have got lots of issues with your code as mentioned below:

(1) Follow Java naming conventions Class names starts with uppercase

(2) Your code is hard to follow, try to refactor into smaller methods

(3) Use existing String/other API methods effectively like you can use equalsIgnoreCase instead of writing d.equals("A")|| d.equals("a")


答:
you can use do while loop</p>

```<code>      `int ch=0;
      do{if (s.equals("yes")) {
        String userInput = input.nextLine();
       userInput = userInput.toUpperCase();
        startGame();ch++;
        }
    while(ch<3);`
</code>```

Title: Java hangman end loop

Body:
you can use do while loop

      `int ch=0;
      do{if (s.equals("yes")) {
        String userInput = input.nextLine();
       userInput = userInput.toUpperCase();
        startGame();ch++;
        }
    while(ch<3);`


问:
How to set  to default property given 's property already define in css
My web pages have a lot of  without class and their property were set in css as below:

```<code>a{
text-decoration:none;
color:black;
}

a:hover, a:active{
color:green;
}
</code>```

And now I have  tags that with class="tnc" and I want it to have the default property which is blue color text with underline and when active it change to red color text.

I tried this but not work:

```<code>a.tnc{
color: initial;
text-decoration: initial;
}

a.tnc:hover, a.tnc:active{
color: initial;
}
</code>```

Any help is appreciated. :)

a:hover, a:active{
 color:green;
}

a.tnc{
 color: initial !important;
 text-decoration: initial;
}

a.tnc:hover, a.tnc:active{
 color: initial;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>I agree with the terms and conditions</code>```

答:
The value initial doesn't work like that.

The initial value is a defined value per CSS property; not per HTML element.

Go to MDN for the color property:

Initial value Varies from one browser to another

So for the color property: if you want a uniform color - you shouldn't use the value initial.

So to get the correct styles for the tnc class - just reset the properties with  the necessary values:

```<code>a.tnc{
  color: blue;
  text-decoration: underline;
}

a.tnc:hover {
  color: red;
}
</code>```

a{
text-decoration:none;
color:black;
}

a:hover, a:active{
color:green;
}

a.tnc{
color: blue;
text-decoration: underline;
}

a.tnc:hover{
color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Default Anchor<br>
Anchor with class tnc<br></code>```

Title: How to set <a class="class"> to default property given <a>'s property already define in css

Body:
My web pages have a lot of  without class and their property were set in css as below:

a{
text-decoration:none;
color:black;
}

a:hover, a:active{
color:green;
}

And now I have  tags that with class="tnc" and I want it to have the default property which is blue color text with underline and when active it change to red color text.

I tried this but not work:

a.tnc{
color: initial;
text-decoration: initial;
}

a.tnc:hover, a.tnc:active{
color: initial;
}

Any help is appreciated. :)

a:hover, a:active{
 color:green;
}

a.tnc{
 color: initial !important;
 text-decoration: initial;
}

a.tnc:hover, a.tnc:active{
 color: initial;
}

I agree with the terms and conditions

Body:
The value initial doesn't work like that.

The initial value is a defined value per CSS property; not per HTML element.

Go to MDN for the color property:

Initial value Varies from one browser to another

So for the color property: if you want a uniform color - you shouldn't use the value initial.

So to get the correct styles for the tnc class - just reset the properties with  the necessary values:

a.tnc{
  color: blue;
  text-decoration: underline;
}

a.tnc:hover {
  color: red;
}

a{
text-decoration:none;
color:black;
}

a:hover, a:active{
color:green;
}

a.tnc{
color: blue;
text-decoration: underline;
}

a.tnc:hover{
color: red;
}

<a href="#">Default Anchor</a><br>
<a href="#" class="tnc">Anchor with class tnc</a><br>


问:
Java: replacement in a string according to multiple rules
I have the following task. There is a string. I must do replacement in it according to 6 rules till it is possible to make a replacement in a string.

The solution I found is below. It works right. The problem is that its performance is low. How else can I make replacement according to multiple rules? Is there any algorithm?

P.S. This task is from codility site. I got 100% correctness and 25% performance for my solution.

```<code>class Test {

    private Map<String,String> rules;

    private void initRules(){
        rules=new HashMap<>();
        rules.put("AB", "AA");
        rules.put("BA", "AA");
        rules.put("CB", "CC");
        rules.put("BC", "CC");
        rules.put("AA", "A");
        rules.put("CC", "C");
    }

    public String test(String S) {
        initRules();
        loop:while(true){
            String oldString=S;
            for (Map.Entry<String, String> rule : rules.entrySet())
            {
                S=S.replace(rule.getKey(), rule.getValue());
            }
            if (oldString==S){
                break loop;
            };
        }
        return S;
    }
}

 public class NewMain {

    public static void main(String[] args) {
        Test test=new Test();
        System.out.println("Result:"+test.test("ABBCC"));;
    }

}
</code>```

答:
I followed the reasoning of @vish4071 .

I look for sub-Strings of "B" and "A" only , I know this segment will be become "A" . Same for sub-Strings "B" and "C" only.

"BAABBABAB" becomes "A" due to replace("AB" by "AA"),replace("BA" by "AA"), replace("AA" by "A")

input: "BBBAABABBBCCBCBBCACB"

"BBBAABABBB" "CCBCBBC" "A" "CB"

"A"          "C"       "A" "C"

output : "ACAC"

The two algorithms keep track when the sub String "A" changes from/to "C". I append the known previous char. Because change detection is based on "A" to "C" or "C" to "A", you don't previous char in the first sub-string. After the loop , you have to append with last previous char.

Runtime complexity : O(n)

Space complexity :   O(1)

Here is the implementation in Java.

```<code>  public static String solution(String S) {

        final char C = 'C';
        final char A = 'A';

        // if contains only B return itself
        if(!S.contains("A") || !S.contains("C")) return S;

    String res = "";
    boolean hasLetterChanged = false;
    char prevChar = 'D';
    for(char c : S.toCharArray()){
        if (c == A){
            if (prevChar == C){hasLetterChanged = true;}
        }else if(c == C){
            if (prevChar == A){hasLetterChanged = true;}
        }
        if(hasLetterChanged){
            res = res + prevChar;
            hasLetterChanged = false;
        }
        if(c == A || c == C){
            prevChar = c;
        }
    }

    return res + prevChar;
}
</code>```

Here is the implementation in Python 2.7 ( compatible with 3x) .

```<code>def solution(S):
    if not(S.__contains__('C') and S.__contains__('A')): return S

    has_char_changed = False
    prev_char = 'B'
    A = 'A'
    C = 'C'
    res = ""
    for c in S:
        if c == A:
            if prev_char == C:
                has_char_changed = True
        elif c == C:
            if prev_char == A:
                has_char_changed = True

        if has_char_changed:
            res = res + prev_char
            has_char_changed = False

        if c == A or c == C:
            prev_char = c

    return res + prev_char

if __name__ == '__main__':
    assert solution("ABBCC") == "AC"
    assert solution("BCBCABB") == "CA"
    assert solution("BBBAABABBBCCBCBBCACB") == "ACAC"
    assert solution("BBBBBBB") == "BBBBBBB"
</code>```

Body:
I have the following task. There is a string. I must do replacement in it according to 6 rules till it is possible to make a replacement in a string.

The solution I found is below. It works right. The problem is that its performance is low. How else can I make replacement according to multiple rules? Is there any algorithm?

P.S. This task is from codility site. I got 100% correctness and 25% performance for my solution.

class Test {

    private Map<String,String> rules;

    private void initRules(){
        rules=new HashMap<>();
        rules.put("AB", "AA");
        rules.put("BA", "AA");
        rules.put("CB", "CC");
        rules.put("BC", "CC");
        rules.put("AA", "A");
        rules.put("CC", "C");
    }

    public String test(String S) {
        initRules();
        loop:while(true){
            String oldString=S;
            for (Map.Entry<String, String> rule : rules.entrySet())
            {
                S=S.replace(rule.getKey(), rule.getValue());
            }
            if (oldString==S){
                break loop;
            };
        }
        return S;
    }
}

 public class NewMain {

    public static void main(String[] args) {
        Test test=new Test();
        System.out.println("Result:"+test.test("ABBCC"));;
    }

}

Body:
I followed the reasoning of @vish4071 .

I look for sub-Strings of "B" and "A" only , I know this segment will be become "A" . Same for sub-Strings "B" and "C" only.

"BAABBABAB" becomes "A" due to replace("AB" by "AA"),replace("BA" by "AA"), replace("AA" by "A")

input: "BBBAABABBBCCBCBBCACB"

"BBBAABABBB" "CCBCBBC" "A" "CB"

"A"          "C"       "A" "C"

output : "ACAC"

The two algorithms keep track when the sub String "A" changes from/to "C". I append the known previous char. Because change detection is based on "A" to "C" or "C" to "A", you don't previous char in the first sub-string. After the loop , you have to append with last previous char.

Runtime complexity : O(n)

Space complexity :   O(1)

Here is the implementation in Java.

  public static String solution(String S) {

        final char C = 'C';
        final char A = 'A';

        // if contains only B return itself
        if(!S.contains("A") || !S.contains("C")) return S;

    String res = "";
    boolean hasLetterChanged = false;
    char prevChar = 'D';
    for(char c : S.toCharArray()){
        if (c == A){
            if (prevChar == C){hasLetterChanged = true;}
        }else if(c == C){
            if (prevChar == A){hasLetterChanged = true;}
        }
        if(hasLetterChanged){
            res = res + prevChar;
            hasLetterChanged = false;
        }
        if(c == A || c == C){
            prevChar = c;
        }
    }

    return res + prevChar;
}

Here is the implementation in Python 2.7 ( compatible with 3x) .

def solution(S):
    if not(S.__contains__('C') and S.__contains__('A')): return S

    has_char_changed = False
    prev_char = 'B'
    A = 'A'
    C = 'C'
    res = ""
    for c in S:
        if c == A:
            if prev_char == C:
                has_char_changed = True
        elif c == C:
            if prev_char == A:
                has_char_changed = True

        if has_char_changed:
            res = res + prev_char
            has_char_changed = False

        if c == A or c == C:
            prev_char = c

    return res + prev_char

if __name__ == '__main__':
    assert solution("ABBCC") == "AC"
    assert solution("BCBCABB") == "CA"
    assert solution("BBBAABABBBCCBCBBCACB") == "ACAC"
    assert solution("BBBBBBB") == "BBBBBBB"


问:
Leave a cell blank if condition is false
Other questions have touched on this and offered solutions that are not viable for a very large data set. I have a formula like the following across 9 columns:

```<code>=IF(A1=A2, B2, "zz")
</code>```

I then autofill about 3.5 million cells + copy -> paste values. Then I find and replace "zz" with "empty cell". However, finding and replacing a million or so "zz" strings is a very slow process. I'd rather not write anything there in the first place. So my question is, how to I write the following formula:

```<code>=IF(A1=A2, B2, 'leave cell alone and write nothing there at all')
</code>```

Excel seems to be incapable of not touching a cell in case of FALSE (or TRUE for that matter).

答:
Let NULL be the name of a cell that has "" in it, and BLANK be the name of a cell that is truly blank.

NULL is not truly blank; ISBLANK(NULL) will return FALSE.  But note that '=' takes blank and null cells to be identical.  So for any cell C1:

```<code>(C1="")
(C1=BLANK)
(C1=NULL)
</code>```

will all return TRUE if C1 is truly blank OR if it contains "".  (I find this simpler than using COUNTBLANK(C1)>0, which has been suggested elsewhere.)

Body:
Other questions have touched on this and offered solutions that are not viable for a very large data set. I have a formula like the following across 9 columns:

=IF(A1=A2, B2, "zz")

I then autofill about 3.5 million cells + copy -> paste values. Then I find and replace "zz" with "empty cell". However, finding and replacing a million or so "zz" strings is a very slow process. I'd rather not write anything there in the first place. So my question is, how to I write the following formula:

=IF(A1=A2, B2, 'leave cell alone and write nothing there at all')

Excel seems to be incapable of not touching a cell in case of FALSE (or TRUE for that matter).

Body:
Let NULL be the name of a cell that has "" in it, and BLANK be the name of a cell that is truly blank.

NULL is not truly blank; ISBLANK(NULL) will return FALSE.  But note that '=' takes blank and null cells to be identical.  So for any cell C1:

(C1="")
(C1=BLANK)
(C1=NULL)

will all return TRUE if C1 is truly blank OR if it contains "".  (I find this simpler than using COUNTBLANK(C1)>0, which has been suggested elsewhere.)


问:
Ionic 2 - Http POST body parameters not being sent
I am using Ionic 2 Beta 11. I am trying to send a request to an external API which will return a JSON response. I have overcome CORS issues and I am communicating with the API however I can not send the body information that is required. I have tried formatting the body variable in the following ways, each with no success:

As an object: {email: this.email, password: this.password}

As a stringified object: JSON.stringify({email: this.email, password: this.password})

As a string: 'email=' + this.email + '&password=' + this.password

Here is my code:

```<code>import {Component}                                      from '@angular/core';
import {NavController, MenuController}                  from 'ionic-angular';
import {Http, Headers, RequestOptions}                  from '@angular/http';
import 'rxjs/Rx';

@Component({
  templateUrl: 'build/pages/login/login.html'
})
export class LoginPage {
  nav: NavController;
  username: string;
  password: string;

  constructor(nav: NavController, private http: Http) {
    this.nav = nav;
  }

  doLogin() {
    let body = JSON.stringify({
      email: this.username,
      password: this.password });
    let headers = new Headers({
      'NDAPI-Key': 'XXXXXXXXXX',
      'NDAPI-Host': 'XXXXXXXXXXX' });
    let options = new RequestOptions({ headers: headers });

    this.http
        .post('/api', body, options)
        .map(res => res.json())
        .subscribe(
            data => {
              console.log(data);
            },
            err => {
              console.log("ERROR!: ", err);
            }
        );
  }
}
</code>```

答:
Angular2 Ionic 2 HTTP Post Method

```<code>import {Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

constructor(public http:Http) { }

postCall()
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let data=JSON.stringify({username:"raja"});
this.http.post('http://localhost/ionic/postResponse.php',data,headers)
.map(res => res.json())
.subscribe(res => {
alert("success "+res);
}, (err) => {
alert("failed");
});
}

}
</code>```

For more info visit https://ampersandacademy.com/tutorials/ionic-framework-version-2/send-data-and-receive-data-in-the-ionic-2-framework-using-angular2-http-post-method

Body:
I am using Ionic 2 Beta 11. I am trying to send a request to an external API which will return a JSON response. I have overcome CORS issues and I am communicating with the API however I can not send the body information that is required. I have tried formatting the body variable in the following ways, each with no success:

As an object: {email: this.email, password: this.password}

As a stringified object: JSON.stringify({email: this.email, password: this.password})

As a string: 'email=' + this.email + '&password=' + this.password

Here is my code:

import {Component}                                      from '@angular/core';
import {NavController, MenuController}                  from 'ionic-angular';
import {Http, Headers, RequestOptions}                  from '@angular/http';
import 'rxjs/Rx';

@Component({
  templateUrl: 'build/pages/login/login.html'
})
export class LoginPage {
  nav: NavController;
  username: string;
  password: string;

  constructor(nav: NavController, private http: Http) {
    this.nav = nav;
  }

  doLogin() {
    let body = JSON.stringify({
      email: this.username,
      password: this.password });
    let headers = new Headers({
      'NDAPI-Key': 'XXXXXXXXXX',
      'NDAPI-Host': 'XXXXXXXXXXX' });
    let options = new RequestOptions({ headers: headers });

    this.http
        .post('/api', body, options)
        .map(res => res.json())
        .subscribe(
            data => {
              console.log(data);
            },
            err => {
              console.log("ERROR!: ", err);
            }
        );
  }
}

Body:
Angular2 Ionic 2 HTTP Post Method

import {Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

constructor(public http:Http) { }

postCall()
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let data=JSON.stringify({username:"raja"});
this.http.post('http://localhost/ionic/postResponse.php',data,headers)
.map(res => res.json())
.subscribe(res => {
alert("success "+res);
}, (err) => {
alert("failed");
});
}

}

For more info visit https://ampersandacademy.com/tutorials/ionic-framework-version-2/send-data-and-receive-data-in-the-ionic-2-framework-using-angular2-http-post-method


问:
extract information from csv by using python
I am trying to extract how many songs are release in every year from csv. my data looks like this

```<code>no,artist,name,year
"1","Bing Crosby","White Christmas","1942"
"2","Bill Haley & his Comets","Rock Around the Clock","1955"
"3","Sinead O'Connor","Nothing Compares 2 U","1990","35.554"
"4","Celine Dion","My Heart Will Go On","1998","35.405"
"5","Bryan Adams","(Everything I Do) I Do it For You","1991"
"6","The Beatles","Hey Jude","1968"
"7","Whitney Houston","I Will Always Love You","1992","34.560"
"8","Pink Floyd","Another Brick in the Wall (part 2)","1980"
"9","Irene Cara","Flashdance... What a Feeling","1983"
"10","Elton John","Candle in the Wind '97","1992"
</code>```

my files consists of 3000 lines data with additional fields but i am interested to extract how many songs are released in every year

i tried to extract the year and songs and my code is here, but I am new in python and therefore I don't know how to solve my problem. my code is

```<code>from itertools import islice
import csv

filename = '/home/rob/traintask/top3000songs.csv'
data = csv.reader(open(filename))
# Read the column names from the first line of the file
fields = data.next()[3]  // I tried to read the year columns
print fields
count = 0
for row in data:
    # Zip together the field names and values
    items = zip(fields, row)
    item = {}   \\ here I am lost, i think i should make a dict and set year as key and no of songs as values, but I don't know how to do it
    # Add the value to our dictionary
    for (name, value) in items:
        item[name] = value.strip()
        print 'item: ', item
</code>```

I am doing it completely wrong. but If somebody give me some hints or help that how i can count no of songs released in a year. i will be thankful.

答:
You can use a Counter object from the collections module..

```<code>>>> from collections import Counter
>>> from csv import reader
>>>
>>> YEAR = 3
>>> with open('file.txt') as f:
...     next(f, None) # discard header
...     year2rel = Counter(int(line[YEAR]) for line in reader(f))
...
>>> year2rel
Counter({1992: 2, 1942: 2, 1955: 1, 1990: 1, 1991: 1, 1968: 1, 1980: 1, 1983: 1})
</code>```

Body:
I am trying to extract how many songs are release in every year from csv. my data looks like this

no,artist,name,year
"1","Bing Crosby","White Christmas","1942"
"2","Bill Haley & his Comets","Rock Around the Clock","1955"
"3","Sinead O'Connor","Nothing Compares 2 U","1990","35.554"
"4","Celine Dion","My Heart Will Go On","1998","35.405"
"5","Bryan Adams","(Everything I Do) I Do it For You","1991"
"6","The Beatles","Hey Jude","1968"
"7","Whitney Houston","I Will Always Love You","1992","34.560"
"8","Pink Floyd","Another Brick in the Wall (part 2)","1980"
"9","Irene Cara","Flashdance... What a Feeling","1983"
"10","Elton John","Candle in the Wind '97","1992"

my files consists of 3000 lines data with additional fields but i am interested to extract how many songs are released in every year

i tried to extract the year and songs and my code is here, but I am new in python and therefore I don't know how to solve my problem. my code is

from itertools import islice
import csv

filename = '/home/rob/traintask/top3000songs.csv'
data = csv.reader(open(filename))
# Read the column names from the first line of the file
fields = data.next()[3]  // I tried to read the year columns
print fields
count = 0
for row in data:
    # Zip together the field names and values
    items = zip(fields, row)
    item = {}   \\ here I am lost, i think i should make a dict and set year as key and no of songs as values, but I don't know how to do it
    # Add the value to our dictionary
    for (name, value) in items:
        item[name] = value.strip()
        print 'item: ', item

I am doing it completely wrong. but If somebody give me some hints or help that how i can count no of songs released in a year. i will be thankful.

Body:
You can use a Counter object from the collections module..

>>> from collections import Counter
>>> from csv import reader
>>>
>>> YEAR = 3
>>> with open('file.txt') as f:
...     next(f, None) # discard header
...     year2rel = Counter(int(line[YEAR]) for line in reader(f))
...
>>> year2rel
Counter({1992: 2, 1942: 2, 1955: 1, 1990: 1, 1991: 1, 1968: 1, 1980: 1, 1983: 1})


问:
Is Python also divided into LTS and stable versions?
Does Long-term surppot version and stable version exist in Python 2.x or Python 3.x version? And if so, what are the criteria?</p>

答:
not currently

see PEP407 status: "deferred"

https://www.python.org/dev/peps/pep-0407/


问:
cygwin doesn't execute make
I am very new to cygwin and recently installed it because I need to compile some fortran files. I installed all libraries (and its dependencies) I need, but when I execute make to run the makefile, nothing is happening:

```<code>user@PC1 ~
$ make

user@PC1 ~
$
</code>```

No error, no nothing. When I directly execute the file contained in the makefile: same result. All files required are contained in my folder where I run make. However, the package seems to be installed just fine when I call where make or which make. I reinstalled everything multiple times, but still nothing is happening. I then tried to bind the MinGW make so I can use it in cygwin and by calling this version of make, I receive the error I'd expect:

```<code>user@PC1 ~
$ mymake
C:\mingw\bin\mingw32-make.exe: *** No targets specified and no makefile found.  Stop.
</code>```

Unfortunately, I need the make-package from cygwin itself to work, but I have no idea what's going on. Any hints? Calling make.exe doesn't work either.

Update: I just installed cygwin and all required packages on my laptop and there everything works as intended...no problems in runing make.

答:
I had the same problem and managed to fix this following those steps:

Open the cygwin setup and completely uninstall make (reinstalling failed for me). If you haven't deleted the download folder yet, you can select "Install from Local Directory" to make things faster.

Once uninstalled, re-run the setup again and check make, install the dependencies if needed.

Tested with make version 4.2.1-1 on my system, and got it working again.

Title: cygwin doesn't execute make

Body:
I am very new to cygwin and recently installed it because I need to compile some fortran files. I installed all libraries (and its dependencies) I need, but when I execute make to run the makefile, nothing is happening:

user@PC1 ~
$ make

user@PC1 ~
$

No error, no nothing. When I directly execute the file contained in the makefile: same result. All files required are contained in my folder where I run make. However, the package seems to be installed just fine when I call where make or which make. I reinstalled everything multiple times, but still nothing is happening. I then tried to bind the MinGW make so I can use it in cygwin and by calling this version of make, I receive the error I'd expect:

user@PC1 ~
$ mymake
C:\mingw\bin\mingw32-make.exe: *** No targets specified and no makefile found.  Stop.

Unfortunately, I need the make-package from cygwin itself to work, but I have no idea what's going on. Any hints? Calling make.exe doesn't work either.

Update: I just installed cygwin and all required packages on my laptop and there everything works as intended...no problems in runing make.


问:
For comma-separated
I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting whether or not an input field contained the following type of format:

At least one alphanumeric tag which can contain spaces (e.g. "Test Tag" but not "Test@Tag")

Each tag separated by a single comma (e.g. "Cars, Vehicle, Large Dog, Bed" but not "Cars, Vehicle, Tiger)

An example of what I mean is this, these would be valid tags:

```<code>boy, man,girl, woman,tyrannosaurus rex, lion
</code>```

And these would be invalid tags:

```<code>hat, cat, rat, c3po, @gmail
</code>```

Because there are invalid characters in "@gmail".

It should also be able to accept just a single tag, as long as the characters are alphanumeric.

答:
Assuming you want to allow _ and not allow whitespace at the beginning or the end this would be the shortest solution:

```<code>/^\w(\s*,?\s*\w)*$/
</code>```

Introducing whitespace at the ends:

```<code>/^\s*\w(\s*,?\s*\w)*\s*$/
</code>```

Removing _ from the allowed characters:

```<code>/^\s*[a-z0-9](\s*,?\s*[a-z0-9])*\s*$/
</code>```

This is the brute-force regex I initially posted. It translates your requirements to regex syntax. I would like to leave it here for reference.

```<code>/^\s*([a-z0-9]+(\s[a-z0-9]+)*)(\s*,\s*([a-z0-9]+(\s[a-z0-9]+)*))*\s*$/
</code>```

Title: For comma-separated

Body:
I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting whether or not an input field contained the following type of format:

At least one alphanumeric tag which can contain spaces (e.g. "Test Tag" but not "Test@Tag")

Each tag separated by a single comma (e.g. "Cars, Vehicle, Large Dog, Bed" but not "Cars, Vehicle, Tiger)

An example of what I mean is this, these would be valid tags:

boy, man,girl, woman,tyrannosaurus rex, lion

And these would be invalid tags:

hat, cat, rat, c3po, @gmail

Because there are invalid characters in "@gmail".

It should also be able to accept just a single tag, as long as the characters are alphanumeric.

Body:
Assuming you want to allow _ and not allow whitespace at the beginning or the end this would be the shortest solution:

/^\w(\s*,?\s*\w)*$/

Introducing whitespace at the ends:

/^\s*\w(\s*,?\s*\w)*\s*$/

Removing _ from the allowed characters:

/^\s*[a-z0-9](\s*,?\s*[a-z0-9])*\s*$/

This is the brute-force regex I initially posted. It translates your requirements to regex syntax. I would like to leave it here for reference.

/^\s*([a-z0-9]+(\s[a-z0-9]+)*)(\s*,\s*([a-z0-9]+(\s[a-z0-9]+)*))*\s*$/


答:
Before assigning "X" to seat[0][1], you can check if it is already "X". Then, you can print "Sorry"</p>

```<code>if(x == 1)
    {
         if((d.equals("A")|| d.equals("a")))
         {
            if(seat[0][1].equals("X"))
            {
            //Print Sorry
            }
           else
            {
              seat[0][1] = "X";
              k.printTable(seat);
           }
       }
    }
</code>```

Title: User asks twice and the second time the user gets different answer?

Body:
Before assigning "X" to seat[0][1], you can check if it is already "X". Then, you can print "Sorry"

if(x == 1)
    {
         if((d.equals("A")|| d.equals("a")))
         {
            if(seat[0][1].equals("X"))
            {
            //Print Sorry
            }
           else
            {
              seat[0][1] = "X";
              k.printTable(seat);
           }
       }
    }