问:
Extract the sub string from end offline to a special character in batch file
HI i am trying to get the sub string ZoomIn10X,ZoomIn20X,ZoomIn30X etc, from a file which contain following lines below and out put that to another file

```<code>Job Name : STANALONE/1234/JobId/Date/ZoomIn10X

Job Name : STANALONE/1234/JobId/Date/ZoomIn20X

Job Name : STANALONE/JobId/Date/ZoomIn30X

Job Name : STANALONE/1234/JobId/Date/ZoomIn40X

Job Name : STANALONE/1234/Date/ZoomIn10X
</code>```

i Have tried

```<code>for /F "tokens=*" %%A in (input.txt) do (

   echo %%A r "/" "\n" %%A | tail -1 >> output.txt

)
</code>```

but its not working as properly.Can you please help

答:
I think the others answers are not using batch only syntax.

The following solution should work if you have the input.txt file as you have written (I have added even option to use the solution as variable):

EDIT:

Added comments for the script:

```<code>@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
REM your input.txt file looks like this
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn10X
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn20X
REM Job Name : STANALONE/JobId/Date/ZoomIn30X
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn40X
REM Job Name : STANALONE/1234/Date/ZoomIn10X

REM if you wished to use variable
REM SET final_name=""

FOR /F "tokens=2 delims=:" %%A IN (input.txt) DO (
    SET temp_var=%%A
    FOR /F "tokens=4 delims=/" %%B IN ("!temp_var!") DO (
        SET temp_var_B=%%B
        IF "!temp_var_B!" EQU "Date" (
            FOR /F "tokens=5 delims=^/" %%C IN ("!temp_var!") DO (
                ECHO %%C >> output.txt
                REM if you wished to use variable
                REM SET final_name=!final_name!,%%C
            )
        ) ELSE (
           ECHO %%B >> output.txt
           REM if you wished to use variable
           REM SET final_name=!final_name!,%%B
        )
    )
)
ECHO All collected variables: !final_name!
ENDLOCAL
</code>```

This is somewhat inefficient solution, much better you can find below, but collects also variables.  It uses the fact that you can split string multiple times and if you have different string length you can still extract it based on the string, if it is the same, like in your case a "Date".  First FOR splits the string based on ":" character and the other FORs based on "/" char.  There are two FORs as you have different length of the extracted string.

EDIT :

I think I was too quick to find a solution.  When I thought about it I recognized it as very "crude" solution.  I'll also comment it better as I have posted only the code.

The more efficient solution:

```<code>@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
REM your input.txt file looks like this
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn10X
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn20X
REM Job Name : STANALONE/JobId/Date/ZoomIn30X
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn40X
REM Job Name : STANALONE/1234/Date/ZoomIn10X

FOR /F "tokens=2 delims=:" %%A IN (input.txt) DO (
   SET var=%%A
   IF EXIST input.txt (
       ECHO !var:~-9! >> output.txt
   ) ELSE (
       ECHO !var:~-9! > output.txt
   )
)
ENDLOCAL
</code>```

Description:

First comes the FOR /F with "tokens=2" (takes a second part) and "delims=:" uses a ":" as delimiter.

The core of the solution uses the fact that you have at the end constant size string (9 characters to be exact) which you want to extract - !var:~-9!. Uses expanded variable and takes 9 characters from the end of the string which was selected with the FOR statement.

The solution needs to have the SETLOCAL ENABLEDELAYEDEXPANSION there as it uses the expansion.

There is also a IF EXISTS clause so it will create a new file every time you run it.  That is not a vital part of the script and you may comment it out.

Body:
HI i am trying to get the sub string ZoomIn10X,ZoomIn20X,ZoomIn30X etc, from a file which contain following lines below and out put that to another file

Job Name : STANALONE/1234/JobId/Date/ZoomIn10X

Job Name : STANALONE/1234/JobId/Date/ZoomIn20X

Job Name : STANALONE/JobId/Date/ZoomIn30X

Job Name : STANALONE/1234/JobId/Date/ZoomIn40X

Job Name : STANALONE/1234/Date/ZoomIn10X

i Have tried

for /F "tokens=*" %%A in (input.txt) do (

   echo %%A r "/" "\n" %%A | tail -1 >> output.txt

)

but its not working as properly.Can you please help

Body:
I think the others answers are not using batch only syntax.

The following solution should work if you have the input.txt file as you have written (I have added even option to use the solution as variable):

EDIT:

Added comments for the script:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
REM your input.txt file looks like this
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn10X
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn20X
REM Job Name : STANALONE/JobId/Date/ZoomIn30X
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn40X
REM Job Name : STANALONE/1234/Date/ZoomIn10X

REM if you wished to use variable
REM SET final_name=""

FOR /F "tokens=2 delims=:" %%A IN (input.txt) DO (
    SET temp_var=%%A
    FOR /F "tokens=4 delims=/" %%B IN ("!temp_var!") DO (
        SET temp_var_B=%%B
        IF "!temp_var_B!" EQU "Date" (
            FOR /F "tokens=5 delims=^/" %%C IN ("!temp_var!") DO (
                ECHO %%C >> output.txt
                REM if you wished to use variable
                REM SET final_name=!final_name!,%%C
            )
        ) ELSE (
           ECHO %%B >> output.txt
           REM if you wished to use variable
           REM SET final_name=!final_name!,%%B
        )
    )
)
ECHO All collected variables: !final_name!
ENDLOCAL

This is somewhat inefficient solution, much better you can find below, but collects also variables.  It uses the fact that you can split string multiple times and if you have different string length you can still extract it based on the string, if it is the same, like in your case a "Date".  First FOR splits the string based on ":" character and the other FORs based on "/" char.  There are two FORs as you have different length of the extracted string.

EDIT :

I think I was too quick to find a solution.  When I thought about it I recognized it as very "crude" solution.  I'll also comment it better as I have posted only the code.

The more efficient solution:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
REM your input.txt file looks like this
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn10X
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn20X
REM Job Name : STANALONE/JobId/Date/ZoomIn30X
REM Job Name : STANALONE/1234/JobId/Date/ZoomIn40X
REM Job Name : STANALONE/1234/Date/ZoomIn10X

FOR /F "tokens=2 delims=:" %%A IN (input.txt) DO (
   SET var=%%A
   IF EXIST input.txt (
       ECHO !var:~-9! >> output.txt
   ) ELSE (
       ECHO !var:~-9! > output.txt
   )
)
ENDLOCAL

Description:

First comes the FOR /F with "tokens=2" (takes a second part) and "delims=:" uses a ":" as delimiter.

The core of the solution uses the fact that you have at the end constant size string (9 characters to be exact) which you want to extract - !var:~-9!. Uses expanded variable and takes 9 characters from the end of the string which was selected with the FOR statement.

The solution needs to have the SETLOCAL ENABLEDELAYEDEXPANSION there as it uses the expansion.

There is also a IF EXISTS clause so it will create a new file every time you run it.  That is not a vital part of the script and you may comment it out.


来源: stackexchange

问:
Pandas index isin method
I'm having throuble working with the isin method when working with pandas indexes, it always returns False.

```<code>from pandas import DataFrame
df = DataFrame(data=[['a', 1], ['b', 2], ['c', 3]], index=['N01', 'N02', 'N03'])
df.index.isin(['01', '02'])
</code>```

returns

```<code>array([False, False, False], dtype=bool)
</code>```

答:
df.index.isin(['01', '02']) method  in your example is checking if each of the values in the index is equal to one of the values in the range (similar to SQL).

Therefore in your case the check is:
'N01'=='01' or 'N01' == '02'
which is False

The correct usage of .isin() in your case would be:

```<code>from pandas import DataFrame
df = DataFrame(data=[['a', 1], ['b', 2], ['c', 3]], index=['N01', 'N02', 'N03'])
df.index.isin(['N01', 'N02'])
</code>```

which will result in
array([True, True, False], dtype=bool)

ContentLicense: CC BY-SA 3.0

Title: Pandas index isin method

Body:
I'm having throuble working with the isin method when working with pandas indexes, it always returns False.

from pandas import DataFrame
df = DataFrame(data=[['a', 1], ['b', 2], ['c', 3]], index=['N01', 'N02', 'N03'])
df.index.isin(['01', '02'])

returns

array([False, False, False], dtype=bool)

Body:
df.index.isin(['01', '02']) method  in your example is checking if each of the values in the index is equal to one of the values in the range (similar to SQL).

Therefore in your case the check is:
'N01'=='01' or 'N01' == '02'
which is False

The correct usage of .isin() in your case would be:

from pandas import DataFrame
df = DataFrame(data=[['a', 1], ['b', 2], ['c', 3]], index=['N01', 'N02', 'N03'])
df.index.isin(['N01', 'N02'])

which will result in
array([True, True, False], dtype=bool)


问:
Start / Stop a Windows Service from a non-Administrator user account
I have a WindowsService named, say, BST. And I need to give a non-Administrator user, UserA, the permissions to Start/Stop this particular service. My service runs on a variety of Windows OS, starting from Windows Server 2003 to Windows 7.

How can I do this?

I Googled and found some stuff about giving permissions using the command [sc sdset], but I am not exactly sure about the parameters. I do not want to set the permissions for a group, but ONLY to a particular user, UserA in this case.

答: Windows Service runs using a local system account.It can start automatically as the user logs into the system or it can be started manually.However, a windows service say BST can be run using a particular user account on the machine.This can be done as follows:start services.msc and go to the properties of your windows service,BST.From there you can give the login parameters of the required user.Service then runs with that user account and no other user can run that service.</p>

ContentLicense: CC BY-SA 2.5


问:
ArrayList, JList, DefaultListModel, adding elements, displaying them etc
How can I change the output from JTextArea to JList?
The reason: deleting elements, sorting them and editing them is easier.
If I simply change the JTextArea to JList I have the problem of printing the ArrayList in the output area.

This is my code (I cut out certain (probably irrelevant) parts):

```<code>package personFiles;

import java.awt.*;
import java.util.List;
import java.awt.event.*;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.event.*;

@SuppressWarnings("serial")
public class Osoblje extends JFrame {
    private JTextArea outputJTA = new JTextArea("");
    private JScrollPane outputJTAScrollPane = new JScrollPane(outputJTA);

    List<Person> personList = new ArrayList<>();

    public Osoblje(String title) {
        // Frame-Initialisierung
        super(title);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        int frameWidth = 310;
        int frameHeight = 269;
        setSize(frameWidth, frameHeight);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (d.width - getSize().width) / 2;
        int y = (d.height - getSize().height) / 2;
        setLocation(x, y);
        setResizable(false);
        Container cp = getContentPane();
        cp.setLayout(null);
        // Anfang Komponenten

        outputJTAScrollPane.setBounds(8, 8, 129, 217);
        cp.add(outputJTAScrollPane);

        setVisible(true);
    } // end of public Osoblje

    // Anfang Methoden

    public static void main(String[] args) {
        new Osoblje("Osoblje");
    } // end of main

    public void newPersonJB_ActionPerformed(ActionEvent evt) {
        personList.add(new Person(idJTF.getText(), nameJTF.getText(), surnameJTF.getText(), ageJTF.getText(), genderJTF.getText())); //create new person
    } // end of newPersonJB_ActionPerformed

    public void pokaziJB_ActionPerformed(ActionEvent evt) {
        outputJTA.setText(personList + "\n"); //display personList
    } // end of pokaziJB_ActionPerformed

}
</code>```

答:
You're using java.awt.List instead of java.util.List.

Solution:

```<code>java.util.List<Main> m = new ArrayList<Main>();
</code>```

Or do more strict imports like:

```<code>import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Container;
</code>```

Instead of:

```<code>import java.awt.*;
</code>```

Body:
How can I change the output from JTextArea to JList?
The reason: deleting elements, sorting them and editing them is easier.
If I simply change the JTextArea to JList I have the problem of printing the ArrayList in the output area.

This is my code (I cut out certain (probably irrelevant) parts):

package personFiles;

import java.awt.*;
import java.util.List;
import java.awt.event.*;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.event.*;

@SuppressWarnings("serial")
public class Osoblje extends JFrame {
    private JTextArea outputJTA = new JTextArea("");
    private JScrollPane outputJTAScrollPane = new JScrollPane(outputJTA);

    List<Person> personList = new ArrayList<>();

    public Osoblje(String title) {
        // Frame-Initialisierung
        super(title);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        int frameWidth = 310;
        int frameHeight = 269;
        setSize(frameWidth, frameHeight);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (d.width - getSize().width) / 2;
        int y = (d.height - getSize().height) / 2;
        setLocation(x, y);
        setResizable(false);
        Container cp = getContentPane();
        cp.setLayout(null);
        // Anfang Komponenten

        outputJTAScrollPane.setBounds(8, 8, 129, 217);
        cp.add(outputJTAScrollPane);

        setVisible(true);
    } // end of public Osoblje

    // Anfang Methoden

    public static void main(String[] args) {
        new Osoblje("Osoblje");
    } // end of main

    public void newPersonJB_ActionPerformed(ActionEvent evt) {
        personList.add(new Person(idJTF.getText(), nameJTF.getText(), surnameJTF.getText(), ageJTF.getText(), genderJTF.getText())); //create new person
    } // end of newPersonJB_ActionPerformed

    public void pokaziJB_ActionPerformed(ActionEvent evt) {
        outputJTA.setText(personList + "\n"); //display personList
    } // end of pokaziJB_ActionPerformed

}

Body:
You're using java.awt.List instead of java.util.List.

Solution:

java.util.List<Main> m = new ArrayList<Main>();

Or do more strict imports like:

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Container;

Instead of:

import java.awt.*;


问:
nspredicate iphone question
i have the following code

```<code>NSPredicate* predicate = [NSPredicate predicateWithFormat:@"Word== %@", randomWord];
rows = [[courseArray filteredArrayUsingPredicate:predicate]retain];
</code>```

I am using this in a search bar. I have two questions - how can i make the NSPredicate so it takes every word that begins with the characters typed rather than having a value equal another? e.g I have "Men, Many,Morons, Now,Never" in the array,  and when i type "M" i want "Men,Many,Morons" to be added. Furthermore, how can i predicate more than 1 value? so it compares between two formats?

thanks...

答:
You need create all of the predicate which you want to compare and append all predicate to array. after that you can use NSCompoundPredicate for or,and condition.

like that

```<code>NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"is_neutered = 0"],
    [NSCompoundPredicate orPredicateWithSubPredicates:feedDays]]];
</code>```

Title: nspredicate iphone question

Body:
i have the following code

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"Word== %@", randomWord];
rows = [[courseArray filteredArrayUsingPredicate:predicate]retain];

I am using this in a search bar. I have two questions - how can i make the NSPredicate so it takes every word that begins with the characters typed rather than having a value equal another? e.g I have "Men, Many,Morons, Now,Never" in the array,  and when i type "M" i want "Men,Many,Morons" to be added. Furthermore, how can i predicate more than 1 value? so it compares between two formats?

thanks...

Body:
You need create all of the predicate which you want to compare and append all predicate to array. after that you can use NSCompoundPredicate for or,and condition.

like that

NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[[NSPredicate predicateWithFormat:@"is_neutered = 0"],
    [NSCompoundPredicate orPredicateWithSubPredicates:feedDays]]];


问:
Create a list of repeated consecutive numbers regarding number from another list
I want to create a list with repeated consecutive numbers from zero regarding numbers from list1

```<code>list1 = [3,5,4,1,2,2]
</code>```

Expected list should have 3 zeros, 5 ones, 4 twos, and so on.

```<code>list2 = [0,0,0,1,1,1,1,1,2,2,2,2,3,4,4,5,5]
</code>```

答:
You can use a nested list comprehension using range to make the repetitions:

```<code>lst = [i for i in range(len(list1)) for _ in range(list1[i])]
print lst
# [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 5, 5]
</code>```

And there's the more intuitive itertools approach:

```<code>from itertools import repeat, count

c = count()
lst = [x for i in list1 for x in repeat(next(c), i)]
</code>```

Body:
I want to create a list with repeated consecutive numbers from zero regarding numbers from list1

list1 = [3,5,4,1,2,2]

Expected list should have 3 zeros, 5 ones, 4 twos, and so on.

list2 = [0,0,0,1,1,1,1,1,2,2,2,2,3,4,4,5,5]

Body:
You can use a nested list comprehension using range to make the repetitions:

lst = [i for i in range(len(list1)) for _ in range(list1[i])]
print lst
# [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 5, 5]

And there's the more intuitive itertools approach:

from itertools import repeat, count

c = count()
lst = [x for i in list1 for x in repeat(next(c), i)]


问:
Is it possible to make an update method fire an action only once without a flag? LibGDX
In LibGDX's update method, is it possible to make an action happen only once when told to, without doing this? :</p>

```<code>private boolean shouldBeFired = false;
    @Override
    public void update(float dt) {
        if(shouldBeFired)
            fire();
            shouldBeFired = false;
}
</code>```

答:
If number of flags is the problem you can use int or even more optimal you can use enum for your requirement.

```<code>enum MyFlag{
    NONE,FIRST,SECOND,THIRD,FOURTH
}

MyFlag myFlag=MyFlag.NONE;

@Override
public void update(float dt) {
    if(myFlag==MyFlag.FIRST) {
        fire();
        myFlag=MyFlag.values()[myFlag.ordinal()+1]; // incremental change

        //or manually change

        myFlag=MyFlag.NONE;
    }
}
</code>```

Number of constant flag under one roof is good option for optimal development.

Body:
In LibGDX's update method, is it possible to make an action happen only once when told to, without doing this? :

private boolean shouldBeFired = false;
    @Override
    public void update(float dt) {
        if(shouldBeFired)
            fire();
            shouldBeFired = false;
}

Body:
If number of flags is the problem you can use int or even more optimal you can use enum for your requirement.

enum MyFlag{
    NONE,FIRST,SECOND,THIRD,FOURTH
}

MyFlag myFlag=MyFlag.NONE;

@Override
public void update(float dt) {
    if(myFlag==MyFlag.FIRST) {
        fire();
        myFlag=MyFlag.values()[myFlag.ordinal()+1]; // incremental change

        //or manually change

        myFlag=MyFlag.NONE;
    }
}

Number of constant flag under one roof is good option for optimal development.


问:
Getting App Crashed error when deploying Rails application to Heroku
I followed all the guidelines given on the heroku blog for deploying a Rails app. I also my app got pushed successfully and created an app in my account. But when I try to run my site it gives me the following error:

```<code>App crashed
This application is temporarily offline.

If you're the administrator of this app, please check your heroku logs for the
backtrace.
</code>```

I tried to check the logs and here's what I got

```<code>C:\Users\raw\Desktop\html\rohit>heroku logs
Missing the Rails 2.3.8 gem. Please `gem install -v=2.3.8 rails`, update your RAILS_GEM_
VERSION setting in config/environment.rb for the Rails version you do have installed, or
 comment out RAILS_GEM_VERSION to use the latest version installed.

==> dyno-3674485.log (crash) <==
Missing the Rails 2.3.8 gem. Please `gem install -v=2.3.8 rails`, update your RAILS_GEM_
VERSION setting in config/environment.rb for the Rails version you do have installed, or
 comment out RAILS_GEM_VERSION to use the latest version installed.

-----> Rails can't find the expected version.

       Check to ensure you have specified the correct version of Rails in your
       Gemfile or .gems.  See http://docs.heroku.com/gems for details.

       You may also be affected by a gem dependency issue with rack.
       See http://docs.heroku.com/gem-dependency for details.

       Examine the backtrace above this message to debug.
</code>```

II have made a .gems file in my Rails_App directory:

```<code>rails -v '2.3.8'
pg
rack -v '1.1.0'
haml -v '3.0.13'
formtastic -v '0.9.8'
authlogic -v '2.1.5'
subdomain-fu -v '0.5.4'
compass -v '0.10.2'
compass-colors -v '0.3.1'
paperclip -v '2.3.3'
activemerchant -v '1.9.0'
icalendar
</code>```

What can I do to get this to work?

答:
My Heroku app, running on bamboo-ree-1.8.7 stack, (run heroku info to determine what stack you are running), I have the following configuration:

first line of my .gems file

```<code>rails --version 2.3.8
</code>```

You may also need to add the following to your config/environment.rb file

```<code>config.gem 'rails', :version => '2.3.8'
</code>```

You will need to do another git push to heroku for these changes to take effect.

Body:
I followed all the guidelines given on the heroku blog for deploying a Rails app. I also my app got pushed successfully and created an app in my account. But when I try to run my site it gives me the following error:

App crashed
This application is temporarily offline.

If you're the administrator of this app, please check your heroku logs for the
backtrace.

I tried to check the logs and here's what I got

C:\Users\raw\Desktop\html\rohit>heroku logs
Missing the Rails 2.3.8 gem. Please `gem install -v=2.3.8 rails`, update your RAILS_GEM_
VERSION setting in config/environment.rb for the Rails version you do have installed, or
 comment out RAILS_GEM_VERSION to use the latest version installed.

==> dyno-3674485.log (crash) <==
Missing the Rails 2.3.8 gem. Please `gem install -v=2.3.8 rails`, update your RAILS_GEM_
VERSION setting in config/environment.rb for the Rails version you do have installed, or
 comment out RAILS_GEM_VERSION to use the latest version installed.

-----> Rails can't find the expected version.

       Check to ensure you have specified the correct version of Rails in your
       Gemfile or .gems.  See http://docs.heroku.com/gems for details.

       You may also be affected by a gem dependency issue with rack.
       See http://docs.heroku.com/gem-dependency for details.

       Examine the backtrace above this message to debug.

II have made a .gems file in my Rails_App directory:

rails -v '2.3.8'
pg
rack -v '1.1.0'
haml -v '3.0.13'
formtastic -v '0.9.8'
authlogic -v '2.1.5'
subdomain-fu -v '0.5.4'
compass -v '0.10.2'
compass-colors -v '0.3.1'
paperclip -v '2.3.3'
activemerchant -v '1.9.0'
icalendar

What can I do to get this to work?

Body:
My Heroku app, running on bamboo-ree-1.8.7 stack, (run heroku info to determine what stack you are running), I have the following configuration:

first line of my .gems file

rails --version 2.3.8

You may also need to add the following to your config/environment.rb file

config.gem 'rails', :version => '2.3.8'

You will need to do another git push to heroku for these changes to take effect.


问:
App closing on button click
My app is trying to make some calculations and checking for a condition and printing the array of numbers which satisfy the condition.But the app is closing on click.Please help..

```<code>package com.example.ganesha.app1;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import static android.R.attr.button;

public class MainActivity extends AppCompatActivity {
    private Button result;
    private EditText cap,pwfac,dis,solution;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        result = (Button) findViewById(R.id.resbut);
        cap = (EditText) findViewById(R.id.capacity);
        pwfac = (EditText) findViewById(R.id.powerfactor);
        dis = (EditText) findViewById(R.id.distance);
        solution = (EditText) findViewById(R.id.result);
        //mytextview = (TextView)findViewById(R.id.result)

        result.setOnClickListener(new View.OnClickListener() {

          @Override
          public void onClick(View view) {
            Double capacity = Double.valueOf(cap.getText().toString());
            Double powerfactor = Double.valueOf(pwfac.getText().toString());
            Double distance = Double.valueOf(dis.getText().toString());
            Double amps = capacity / (718.80 * powerfactor);
            Double minimum = 24.9;
            Double ampspermtr=amps/distance;
            Double[] cases = {26.8156, 16.4013, 10.2083, 6.8180, 4.0509, 2.5470, 1.6151, 1.1689, 0.8673, 0.6075, 0.4458, 0.3616, 0.3028, 0.2532, 0.2082, 0.1812, 0.1604, 0.1461, 0.1359};
            Double [] volts=new Double[19];
            for(int i = 0; i <19; i++)
            {
                volts[i]=cases[i]*ampspermtr;
            }

            Double [] wires={1.50,2.50,4.0,6.0,10.0,16.0,25.0,35.0,50.0,70.0,95.0,120.0,150.0,185.0,240.0,300.0,400.0,500.0,630.0};
            final Double [] allpossible = new Double[19];
            int c=0;
            for(int j=0;j<19;j++)
            {
                if(volts[j]<minimum)
                {
                    allpossible[c]=wires[j];

                }
                c++;
            }
            final int g= c;

            for(int p=0;p<g;p++)
            {
               String value = Double.toString(allpossible[g]);
               solution.append(value);
            }
        }
    });
</code>```

It is based on electrical Engineering.Can someone find the mistake and help me out

答:
Actually there some Exception occurred in you calculation in
  OnClick of Button you should write the Calculation code surround
  with try catch block like Below

```<code>try{
Double capacity = Double.valueOf(cap.getText().toString());
            Double powerfactor = Double.valueOf(pwfac.getText().toString());
            Double distance = Double.valueOf(dis.getText().toString());
            Double amps = capacity / (718.80 * powerfactor);
            Double minimum = 24.9;
            Double ampspermtr=amps/distance;
            Double[] cases = {26.8156, 16.4013, 10.2083, 6.8180, 4.0509, 2.5470, 1.6151, 1.1689, 0.8673, 0.6075, 0.4458, 0.3616, 0.3028, 0.2532, 0.2082, 0.1812, 0.1604, 0.1461, 0.1359};
            Double [] volts=new Double[19];
            for(int i = 0; i <19; i++)
            {
                volts[i]=cases[i]*ampspermtr;

            }
            Double [] wires={1.50,2.50,4.0,6.0,10.0,16.0,25.0,35.0,50.0,70.0,95.0,120.0,150.0,185.0,240.0,300.0,400.0,500.0,630.0};
            final Double [] allpossible = new Double[19];
            int c=0;
            for(int j=0;j<19;j++)
            {
                if(volts[j]<minimum)
                {
                    allpossible[c]=wires[j];

                }
                c++;
            }
            final int g= c;

            for(int p=0;p<g;p++)
         {

             String value = Double.toString(allpossible[g]);
             solution.append(value);
         }
        }

}Catch(Exception ex){
// handle your Exception here
}
</code>```

Title: App closing on button click

Body:
My app is trying to make some calculations and checking for a condition and printing the array of numbers which satisfy the condition.But the app is closing on click.Please help..

package com.example.ganesha.app1;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import static android.R.attr.button;

public class MainActivity extends AppCompatActivity {
    private Button result;
    private EditText cap,pwfac,dis,solution;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        result = (Button) findViewById(R.id.resbut);
        cap = (EditText) findViewById(R.id.capacity);
        pwfac = (EditText) findViewById(R.id.powerfactor);
        dis = (EditText) findViewById(R.id.distance);
        solution = (EditText) findViewById(R.id.result);
        //mytextview = (TextView)findViewById(R.id.result)

        result.setOnClickListener(new View.OnClickListener() {

          @Override
          public void onClick(View view) {
            Double capacity = Double.valueOf(cap.getText().toString());
            Double powerfactor = Double.valueOf(pwfac.getText().toString());
            Double distance = Double.valueOf(dis.getText().toString());
            Double amps = capacity / (718.80 * powerfactor);
            Double minimum = 24.9;
            Double ampspermtr=amps/distance;
            Double[] cases = {26.8156, 16.4013, 10.2083, 6.8180, 4.0509, 2.5470, 1.6151, 1.1689, 0.8673, 0.6075, 0.4458, 0.3616, 0.3028, 0.2532, 0.2082, 0.1812, 0.1604, 0.1461, 0.1359};
            Double [] volts=new Double[19];
            for(int i = 0; i <19; i++)
            {
                volts[i]=cases[i]*ampspermtr;
            }

            Double [] wires={1.50,2.50,4.0,6.0,10.0,16.0,25.0,35.0,50.0,70.0,95.0,120.0,150.0,185.0,240.0,300.0,400.0,500.0,630.0};
            final Double [] allpossible = new Double[19];
            int c=0;
            for(int j=0;j<19;j++)
            {
                if(volts[j]<minimum)
                {
                    allpossible[c]=wires[j];

                }
                c++;
            }
            final int g= c;

            for(int p=0;p<g;p++)
            {
               String value = Double.toString(allpossible[g]);
               solution.append(value);
            }
        }
    });

It is based on electrical Engineering.Can someone find the mistake and help me out

Body:
Actually there some Exception occurred in you calculation in
  OnClick of Button you should write the Calculation code surround
  with try catch block like Below

try{
Double capacity = Double.valueOf(cap.getText().toString());
            Double powerfactor = Double.valueOf(pwfac.getText().toString());
            Double distance = Double.valueOf(dis.getText().toString());
            Double amps = capacity / (718.80 * powerfactor);
            Double minimum = 24.9;
            Double ampspermtr=amps/distance;
            Double[] cases = {26.8156, 16.4013, 10.2083, 6.8180, 4.0509, 2.5470, 1.6151, 1.1689, 0.8673, 0.6075, 0.4458, 0.3616, 0.3028, 0.2532, 0.2082, 0.1812, 0.1604, 0.1461, 0.1359};
            Double [] volts=new Double[19];
            for(int i = 0; i <19; i++)
            {
                volts[i]=cases[i]*ampspermtr;

            }
            Double [] wires={1.50,2.50,4.0,6.0,10.0,16.0,25.0,35.0,50.0,70.0,95.0,120.0,150.0,185.0,240.0,300.0,400.0,500.0,630.0};
            final Double [] allpossible = new Double[19];
            int c=0;
            for(int j=0;j<19;j++)
            {
                if(volts[j]<minimum)
                {
                    allpossible[c]=wires[j];

                }
                c++;
            }
            final int g= c;

            for(int p=0;p<g;p++)
         {

             String value = Double.toString(allpossible[g]);
             solution.append(value);
         }
        }

}Catch(Exception ex){
// handle your Exception here
}


问:
Start script when new element on directory
I want to convert every new wav file coming into an input dir to another dir on mp3. I've been look how to convert those file but, I don't know how to add a listener on the input dir or if it's even possible?

Edit:
Sorry, I've forget to share you the code I already have. I use ffmpeg to convert audio file

```<code>import os, sys, glob

FFMPEG_PATH = "C:\\ffmpeg\\bin"

fileName = ""
fileExt = ""

wavdir = ""
mp3dir = ""

for file in glob.glob('wav/*.wav'):

    # get the name  without .ext
    fileName = os.path.basename(file)
    fileName = fileName.split(".")[0]

    # verify if no mp3 file with thesame name exist
    if not os.path.isfile('./mp3/'+fileName+".mp3"):

        # set var with the 2 types files dir
        wavdir = file
        mp3dir = "mp3/"+fileName+".mp3"

        # start the convertion with ffmpeg by commande line
        os.system("ffmpeg -i "+wavdir+" "+mp3dir)
</code>```

答:
This is highly suboptimal, but should do the job</p>

```<code>import os, time

SLEEPTIME = 0.5
TARGET_DIRECTORY = 'path_of_your_folder'

while True:
    time.sleep(SLEEPTIME)
    files = os.listdir(TARGET_DIRECTORY)
    for file in files:
        if file.endswith('.wav'):
            CONVERT
</code>```

Body:
I want to convert every new wav file coming into an input dir to another dir on mp3. I've been look how to convert those file but, I don't know how to add a listener on the input dir or if it's even possible?

Edit:
Sorry, I've forget to share you the code I already have. I use ffmpeg to convert audio file

import os, sys, glob

FFMPEG_PATH = "C:\\ffmpeg\\bin"

fileName = ""
fileExt = ""

wavdir = ""
mp3dir = ""

for file in glob.glob('wav/*.wav'):

    # get the name  without .ext
    fileName = os.path.basename(file)
    fileName = fileName.split(".")[0]

    # verify if no mp3 file with thesame name exist
    if not os.path.isfile('./mp3/'+fileName+".mp3"):

        # set var with the 2 types files dir
        wavdir = file
        mp3dir = "mp3/"+fileName+".mp3"

        # start the convertion with ffmpeg by commande line
        os.system("ffmpeg -i "+wavdir+" "+mp3dir)

Body:
This is highly suboptimal, but should do the job

import os, time

SLEEPTIME = 0.5
TARGET_DIRECTORY = 'path_of_your_folder'

while True:
    time.sleep(SLEEPTIME)
    files = os.listdir(TARGET_DIRECTORY)
    for file in files:
        if file.endswith('.wav'):
            CONVERT


问:
How to create a full day event in fullcalendar
I am really stuck with this.How can i create a full day event in fullcalendar when clicked on a day.</p>

```<code>dayClick: function (date, allDay, jsEvent, view) {

  var eventTitle = prompt('Provide Event title');

  if (eventTitle) {
    $('#calendar').fullCalendar('renderEvent', {
      title : eventTitle,
      allDay : true,
      stick : true,
    });
  }
}
</code>```

答:
You haven't actually said what's going wrong with this code, but it seems fairly obvious that you missed out the start and end dates. Otherwise how will the calendar know where you want to place the event? It doesn't take any implication from the fact that you called "renderEvent" from inside the "dayClick" method, that's just a coincidence. "renderEvent" can be called anytime and is independent. It expects you to tell it everything about the event you want to add.

If you'd checked your browser console after you tried to add the event, you'd have noticed an error "Cannot read property 'stripTime' of undefined" which would hopefully have given you a clue about the nature of the error, being related to time. You could also trace it back in the source to see what it was doing and what you had omitted to do.

Anyway, since you want this to be an all-Day event for a single day, you can use the date property supplied by the callback quite easily:

```<code>dayClick: function (date, allDay, jsEvent, view) {

  var eventTitle = prompt('Provide Event title');

  if (eventTitle) {
    $('#calendar').fullCalendar('renderEvent', {
      title : eventTitle,
      allDay : true,
      start: date, //specify start date
      stick : true,
    });
  }
}
</code>```

Note that, as per https://fullcalendar.io/docs/event_data/Event_Object/, only "start" is required. "end" is optional and I haven't used it. If you specify "allDay: true" and only supply a start date, then fullCalendar will assume it's an all-day event for a single day.

For future reference: If you want to allow more flexibility in adding events (e.g. not all-day ones), you should use the "select" callback instead to allow users to specify the exact start and end times for the event by dragging their mouse on the calendar. https://fullcalendar.io/docs/selection/select_callback/

Body:
I am really stuck with this.How can i create a full day event in fullcalendar when clicked on a day.

dayClick: function (date, allDay, jsEvent, view) {

  var eventTitle = prompt('Provide Event title');

  if (eventTitle) {
    $('#calendar').fullCalendar('renderEvent', {
      title : eventTitle,
      allDay : true,
      stick : true,
    });
  }
}

Body:
You haven't actually said what's going wrong with this code, but it seems fairly obvious that you missed out the start and end dates. Otherwise how will the calendar know where you want to place the event? It doesn't take any implication from the fact that you called "renderEvent" from inside the "dayClick" method, that's just a coincidence. "renderEvent" can be called anytime and is independent. It expects you to tell it everything about the event you want to add.

If you'd checked your browser console after you tried to add the event, you'd have noticed an error "Cannot read property 'stripTime' of undefined" which would hopefully have given you a clue about the nature of the error, being related to time. You could also trace it back in the source to see what it was doing and what you had omitted to do.

Anyway, since you want this to be an all-Day event for a single day, you can use the date property supplied by the callback quite easily:

dayClick: function (date, allDay, jsEvent, view) {

  var eventTitle = prompt('Provide Event title');

  if (eventTitle) {
    $('#calendar').fullCalendar('renderEvent', {
      title : eventTitle,
      allDay : true,
      start: date, //specify start date
      stick : true,
    });
  }
}

Note that, as per https://fullcalendar.io/docs/event_data/Event_Object/, only "start" is required. "end" is optional and I haven't used it. If you specify "allDay: true" and only supply a start date, then fullCalendar will assume it's an all-day event for a single day.

For future reference: If you want to allow more flexibility in adding events (e.g. not all-day ones), you should use the "select" callback instead to allow users to specify the exact start and end times for the event by dragging their mouse on the calendar. https://fullcalendar.io/docs/selection/select_callback/


问:
PHP range() function in .NET?
I need to generate a list of sequential numbers.  I know Ruby you can do 1..10 or PHP you can do range(1, 10).  Anything like that in .Net already, or do I have to write it?   Thanks.</p>

答:
Would this work for you?</p>

```<code>public List<int> Range(int start, int finish)
{
  List<int> retList = new List<int>();
  for(int i = start; i <= finish; i++)
  {
     retList.Add(i);
  }
  return retList;
}
</code>```

OwnerDisplayName: Kevin

Title: PHP range() function in .NET?

Body:
Would this work for you?

public List<int> Range(int start, int finish)
{
  List<int> retList = new List<int>();
  for(int i = start; i <= finish; i++)
  {
     retList.Add(i);
  }
  return retList;
}


问:
The correct way to start animation as soon as fragment loads
I got a fragment in which there's an animation of a count down clock. I want to start the animation as soon as the fragment loads without any intervention from the user.

What I do now is calling the following method in onCreateView:

```<code>private void startCountDownAnimation()
{
    final int totalSeconds = secondsToStart + minutesToStart * 60;
    mRingProgressBar.setTotalSeconds(totalSeconds);
    HandlerThread handlerThread = new HandlerThread("countdown");
    handlerThread.start();

    Handler handler = new Handler(handlerThread.getLooper());
    handler.post(new Runnable()
    {
        @Override
        public void run()
        {
            timer.scheduleAtFixedRate(new TimerTask()
            {
                //int secondsPassed = 0;
                int secondsLeft = totalSeconds;

                @Override
                public void run()
                {
                    if(secondsLeft == 0)
                    {
                        //fragment transaction
                        timer.cancel();
                    }
                    //final int currentProgress = Math.round(((float) secondsPassed)/((float) totalSeconds)*100f);
                    getActivity().runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            mRingProgressBar.setSeconds(secondsLeft);
                            secondsLeft--;
                            //secondsPassed++;
                        }
                    });
                }
            }, 0, 1000);

        }
    });
}
</code>```

This seems to work including when the app goes to the background.

I just want to know if what I'm doing is the correct way to handle the animation:

1) Is onCreate the correct place to call this method?

2) Can I have some issues of the app going to the background or if the screen blackens after a while?

3)Anything else I should change?

答:
You should not use a Timer inside an Handler as the Timer is already asynchronous. The Timer is known to generate memory leaks so I'd suggest to use a CountDownTimer instead.
You should probably create the timer in onCreate and start it in onResume and stop it in onPause. Then you update the view in the onTick but you probably need to check if the view is available or not (view != null)</p>

Body:
I got a fragment in which there's an animation of a count down clock. I want to start the animation as soon as the fragment loads without any intervention from the user.

What I do now is calling the following method in onCreateView:

private void startCountDownAnimation()
{
    final int totalSeconds = secondsToStart + minutesToStart * 60;
    mRingProgressBar.setTotalSeconds(totalSeconds);
    HandlerThread handlerThread = new HandlerThread("countdown");
    handlerThread.start();

    Handler handler = new Handler(handlerThread.getLooper());
    handler.post(new Runnable()
    {
        @Override
        public void run()
        {
            timer.scheduleAtFixedRate(new TimerTask()
            {
                //int secondsPassed = 0;
                int secondsLeft = totalSeconds;

                @Override
                public void run()
                {
                    if(secondsLeft == 0)
                    {
                        //fragment transaction
                        timer.cancel();
                    }
                    //final int currentProgress = Math.round(((float) secondsPassed)/((float) totalSeconds)*100f);
                    getActivity().runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            mRingProgressBar.setSeconds(secondsLeft);
                            secondsLeft--;
                            //secondsPassed++;
                        }
                    });
                }
            }, 0, 1000);

        }
    });
}

This seems to work including when the app goes to the background.

I just want to know if what I'm doing is the correct way to handle the animation:

1) Is onCreate the correct place to call this method?

2) Can I have some issues of the app going to the background or if the screen blackens after a while?

3)Anything else I should change?


问:
css class not working properly
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>
  <h1>Audio Projects</h1>
    <blockquote>
     <h3>

              Class D Amplifier

      </h3>
      <div class="wrapper">
          <div class="left">
              <img src="Damp/Damp_front.JPG"/>
          </div>
          <div class="right">
              Some text that should be next to image
          </div>
      </div>
  </blockquote>
</article></code>```

答:
Option 1, my preferred way of doing this:

Remove the float in .left  take the inline left margin out of the .right and give both .left and .right

```<code>display: inline-block;
</code>```

Giving you

```<code>div.left{
    width: 200px;
    /*float:left;*/
    display: inline-block;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    display: inline-block;
    width: 520px;
    margin-left: 20px;
}
</code>```

For those two classes

Option 2:

Give both a float:left

```<code>div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    width: 520px;
    margin-left: 20px;
}
</code>```

This should cause them to stack in the same way that inline-block does, but floats can cause trouble later. In either case you have to limit the width on .right or the text will prefer to be full width and not be inline, but rather be below the image. The total width of the two divs has to be less than the available width in .wrapper

Title: css class not working properly

Body:
i'm redesigning my website. and doing that i'm finding myself in some problems using the css code i wrote.

i use div's to get an image and some text next to each other.
i'm unable to get the text moved to the correct place (see pictures) the margin-left doesn't seem to work when it is in the css file but it works when directly embedded in the div tags, am i doing something wrong?

also i'dd like to add that i don't need to set the image size in the html code but its in the css code is this possible?

What i get

What i want

body
{
 background:#333 url(bg.jpg) repeat top left;
 font-family:Arial;
 color:white;
 text-align:center;
}

body header.heading
{
 width:1150px;
 /*background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;*/
 margin:0 auto;
 z-index:0;

}

body.Content
{
 width:1150px;
}

main
{
width:1150px;
 margin: 0 auto;
}

section
{
 text-align:left;
 margin:0 auto;
}

header nav
{
 width:1150px;
 background:transparent url(../images/menu/MEbanner.jpg) no-repeat top;
 background-size: 1150 100px;
 padding-top:101px;
 margin:0 auto;
 z-index:0;
}

header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

header nav li {
    float: left;
    border-right: 1px solid #bbb;
}

header nav li:last-child {
    border-right: none;
}

/*header nav li a {
    display: block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}*/

/* Change the link color to #111 (black) on hover */
header nav li a:hover {
    background-color: #111;
}

header nav li.active {
    background-color: #4CAF50;
}

header nav li a, .dropbtn {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 20px 16px;
    text-decoration: none;
}

header nav li a:hover, .dropdown:hover .dropbtn {
    background-color:  #111;
}

header nav li.dropdown {
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

nav
{
 text-align:left;
 margin:0 auto;
}

.hidden {display:none}

hr
{
 border-left: none;
 border-right: none;
 height:4px;
 margin: 2em 0 2em 0;
}

main a:link {color:#fff;}      /* unvisited link */

main a:visited {color:#fff;}  /* visited link */

main a:hover {color:#159;}  /* mouse over link */

blockquote{
 color:white;
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
}

h2
{
 font-size: 30px;
 color:Black;
}

h1,h2,h3,h4
{
 font-family: 'Open Sans Condensed', sans-serif;
 color:#4CAF50;
 text-decoration:underline;
}

h2, h3
{
 font-size: 1.6em;
 letter-spacing: -1px;
 margin: 0 0 0.75em 0;
}

h3
{
 font-size:1.3em;
}

h1
{
 font:bold;
}

h4
{
 font-size:1em;
 margin: 0.5em 0 0.5em;
 padding-left:1em;
}

.green
{
 border-left: 8px solid;
 border-color: #0BD676;/*#0DFF8C;*/
 padding-left:10px;
 color: #4CAF50;
 margin-left:40px;
 font-style:oblique;
}

article.centeralign
{
 text-align:center;
}

div.wrapper{
 width: 800px;
 overflow: hidden;
}

div.toolsWrapper{
 width: 980px;
 overflow: hidden;
}

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    margin-left: 20px;
}

div.cc
 {
  width:200px;
  text-align:right;
  font-size:10px;
 }

div.ccf
 {
  text-align:center;
  font-size:12px;
 }

iframe
{
 text-align:center;
 float:center;
}

/* ===========================
   ====== Contact Form =======
   =========================== */

input, textarea {
 padding: 10px;
 border: 1px solid #E5E5E5;
 width: 200px;
 color: #999999;
 box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 8px;
}

textarea {
 width: 400px;
 height: 150px;
 max-width: 400px;
 line-height: 18px;
}

input:hover, textarea:hover,
input:focus, textarea:focus {
 border-color: 1px solid #C9C9C9;
 box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
 -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 8px;
}

.form label {
 margin-left: 10px;
 color: #999999;
}

/* ===========================
   ====== Submit Button ======
   =========================== */

.submit input {
 width: 100px;
 height: 40px;
 background-color: #474E69;
 color: #FFF;
 border-radius: 3px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
}

table, th, td {
    border: 1px solid black;
    border-color:white;
}

th, td {
    padding: 15px;
}

.blue{
  background: url(blue.png) no-repeat left center;
    color: #109CEF;
    padding: 0px 40px 0px 20px;
  font-style:oblique;
 }

.red{
  background: url(red.png) no-repeat left center;
  color:#FF0000;
  padding: 0px 40px 0px 20px;
  font-style:oblique;
}

Audio Projects

              Class D Amplifier

              Some text that should be next to image

Body:
Option 1, my preferred way of doing this:

Remove the float in .left  take the inline left margin out of the .right and give both .left and .right

display: inline-block;

Giving you

div.left{
    width: 200px;
    /*float:left;*/
    display: inline-block;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    display: inline-block;
    width: 520px;
    margin-left: 20px;
}

For those two classes

Option 2:

Give both a float:left

div.left{
    width: 200px;
    float:left;
    margin-right:40px;
    padding-left:40px;
}

div.right{
    float:left;
    width: 520px;
    margin-left: 20px;
}

This should cause them to stack in the same way that inline-block does, but floats can cause trouble later. In either case you have to limit the width on .right or the text will prefer to be full width and not be inline, but rather be below the image. The total width of the two divs has to be less than the available width in .wrapper


答: Make a while True loop. Then in the loop you make another loop with for item in os.listdir(yourdir) in there you move every item and then you can make time.sleep(1) to reduce lag.

Title: Start script when new element on directory


问:
how to create html table in php
I have the following snippet of code that basically uses explode to split out these values:

```<code><?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
   $pieces = explode(";", $line);
   echo $pieces[0];
   echo $pieces[1];
   echo $pieces[2];
   echo $pieces[3];
//print_r($line);
}
?>
</code>```

Data: (prod.txt)

```<code>PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2
</code>```

Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.

```<code>PREFIX  PART   FILE
abc     null   /myprojects/school/out/data/feed_abc_2010120810.gz2
efg     sdsu   mail_efg.dat.2010120810.gz2
</code>```

答:
Not the prettiest solution, just an example:</p>

```<code>echo '<table><tr><td>PREFIX</td><td>PART</td><td>FILE</td></tr>';
foreach ($Inputfile as $line)
{
    $pieces = explode(';', $line);
    echo sprintf(
        '<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
        ltrim($pieces[0], 'PREFIX='),
        ltrim($pieces[1], 'PART='),
        ltrim($pieces[2], 'FILE=')
    );
}
echo '</table>';
</code>```

Title: how to create html table in php

Body:
I have the following snippet of code that basically uses explode to split out these values:

<?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
   $pieces = explode(";", $line);
   echo $pieces[0];
   echo $pieces[1];
   echo $pieces[2];
   echo $pieces[3];
//print_r($line);
}
?>

Data: (prod.txt)

PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2

Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.

PREFIX  PART   FILE
abc     null   /myprojects/school/out/data/feed_abc_2010120810.gz2
efg     sdsu   mail_efg.dat.2010120810.gz2

Body:
Not the prettiest solution, just an example:

echo '<table><tr><td>PREFIX</td><td>PART</td><td>FILE</td></tr>';
foreach ($Inputfile as $line)
{
    $pieces = explode(';', $line);
    echo sprintf(
        '<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
        ltrim($pieces[0], 'PREFIX='),
        ltrim($pieces[1], 'PART='),
        ltrim($pieces[2], 'FILE=')
    );
}
echo '</table>';


问:
How do I get a Dlookup result to display within another textbox on an Access database?
I have created on a database a Dlookup function to change the email address of a manager whenever the managers area is selected. It works fine but now that the control source is the Dlookup it doesn't save the results any more in the personal table.

I read up on http://p2p.wrox.com/access-vba/77907-how-save-results-dlookup-function.html a method to have a separate hidden box which displays the results from the table, which works but my trouble is now connecting the Dlookup result to the other text box.

I obviously cant control source the Dlookup result so I've instead tried to make it an before update event using the following code;

```<code>Option Compare Database

Private Sub ASMail_AfterUpdate()
ASMEmail.Value = ASMail.Value
End Sub
</code>```

However this has not taken effect at all. The textbox does not change whenever I adjust the Dlookup results, and I've tried the same code in the other Change event which didn't work either.

答:
You don't need a separate hidden textbox.

Leave the textbox control source of the manager's email linked to the personal table field and simply update the textbox value to the DLookup value when the manager area is selected.

I don't know how the manager area is selected, but as a combobox example, it would be like this:

```<code>Private Sub Combo_AfterUpdate()
    Me.ASMEmail.Value = Nz(DLookup("Value", "Domain", "Criteria"), vbNullString)
End Sub
</code>```

Body:
I have created on a database a Dlookup function to change the email address of a manager whenever the managers area is selected. It works fine but now that the control source is the Dlookup it doesn't save the results any more in the personal table.

I read up on http://p2p.wrox.com/access-vba/77907-how-save-results-dlookup-function.html a method to have a separate hidden box which displays the results from the table, which works but my trouble is now connecting the Dlookup result to the other text box.

I obviously cant control source the Dlookup result so I've instead tried to make it an before update event using the following code;

Option Compare Database

Private Sub ASMail_AfterUpdate()
ASMEmail.Value = ASMail.Value
End Sub

However this has not taken effect at all. The textbox does not change whenever I adjust the Dlookup results, and I've tried the same code in the other Change event which didn't work either.

Body:
You don't need a separate hidden textbox.

Leave the textbox control source of the manager's email linked to the personal table field and simply update the textbox value to the DLookup value when the manager area is selected.

I don't know how the manager area is selected, but as a combobox example, it would be like this:

Private Sub Combo_AfterUpdate()
    Me.ASMEmail.Value = Nz(DLookup("Value", "Domain", "Criteria"), vbNullString)
End Sub


问:
Should I encapsulate id field with my own type?
Considering below snippets:

```<code>class User {
  String id;

  ...other fields
}
</code>```

```<code>class Id extends String {

}

class User {
  Id id;

  ...other fields
}
</code>```

Which one should I use? I've never seen anoyone using their own Id type. Now I'm thinking: are there any drawbacks to do it?

答:
This technique is called microtyping, sometimes tiny typing. It tends to make your code more expressive and thus safer and more readable.
However it also creates another layer of indirection: The reader of your code has to learn what an Id is to fully understand it. She probably already knows what a String is.

Generally I highly recommend microtyping. There are probably cases where it could be overdone but I haven't found one so far. So don't worry.

Concerning your specific implementation: In some languages like Java it is not possible to derive from standard classes like String. In other languages like C++ it is possible but not recommended. Therefore I would rather use composition instead of inheritance:

```<code>class Id {
    private String id;
    ...
}
</code>```

Body:
Considering below snippets:

class User {
  String id;

  ...other fields
}

class Id extends String {

}

class User {
  Id id;

  ...other fields
}

Which one should I use? I've never seen anoyone using their own Id type. Now I'm thinking: are there any drawbacks to do it?

Body:
This technique is called microtyping, sometimes tiny typing. It tends to make your code more expressive and thus safer and more readable.
However it also creates another layer of indirection: The reader of your code has to learn what an Id is to fully understand it. She probably already knows what a String is.

Generally I highly recommend microtyping. There are probably cases where it could be overdone but I haven't found one so far. So don't worry.

Concerning your specific implementation: In some languages like Java it is not possible to derive from standard classes like String. In other languages like C++ it is possible but not recommended. Therefore I would rather use composition instead of inheritance:

class Id {
    private String id;
    ...
}


问:
Clustering, Sharding or simple Partition / Replication
We have created a Facebook application and it got a lot of virality. The problem is that our database started getting REALLY FULL (some tables have more than 25 million rows now). It got to the point that the app just stopped working because there was a queue of thousands and thousands of writes to be made.

I need to implement a solution for scaling this app QUICKLY but I'm not sure if I should pursue Sharding or Clustering since I'm not sure what are the pro's and con's of each of them and I was thinking of doing a Partition / Replication approach but I think that doesn't help if the load is on the writes?

答:
Clustering/Sharding/Partitioning comes when single node has reached to the point where its hardware cannot bear the load. But your hardware has still room to expand.
This is the first lesson I learnt when I started being hit by such issues </p>

ContentLicense: CC BY-SA 4.0


问:
Transpose in Excel while encounter "--------"
I have some data in the same column like the picture below, which split by ---------

I want to transpose the column data to row format divided by -------, which like the picture below.

Anyone could give me a hint would be highly appreciated.
And I don't mind using python to solve this problem.

答:
In B15 copied across to suit:

```<code>=IF($A15="---",OFFSET($A15,COLUMN()-16,),"")
</code>```

and then all formulae copied down to suit. May be convenient then to Copy, Paste Special Values, filter to select --- and copy as required into another sheet.

--- represents however many hyphens are appropriate.

Body:
In B15 copied across to suit:

=IF($A15="---",OFFSET($A15,COLUMN()-16,),"")

and then all formulae copied down to suit. May be convenient then to Copy, Paste Special Values, filter to select --- and copy as required into another sheet.

--- represents however many hyphens are appropriate.


问:
Debugging test cases when they are combination of Robot framework and python selenium
Currently I'm using Eclipse with Nokia/Red plugin which allows me to write robot framework test suites. Support is Python 3.6 and Selenium for it.
My project is called "Automation" and Test suites are in .robot files.
Test suites have test cases which are called "Keywords".

Test Cases

Create New Vehicle

```<code>Create new vehicle with next ${registrationno} and ${description}
Navigate to data section
</code>```

Those "Keywords" are imported from python library and look like:

```<code>@keyword("Create new vehicle with next ${registrationno} and ${description}")
def create_new_vehicle_Simple(self,registrationno, description):
    headerPage = HeaderPage(TestCaseKeywords.driver)
    sideBarPage = headerPage.selectDaten()
    basicVehicleCreation = sideBarPage.createNewVehicle()
    basicVehicleCreation.setKennzeichen(registrationno)
    basicVehicleCreation.setBeschreibung(description)
    TestCaseKeywords.carnumber = basicVehicleCreation.save()
</code>```

The problem is that when I run test cases, in log I only get result of this whole python function, pass or failed. I can't see at which step it failed- is it at first or second step of this function.

Is there any plugin or other solution for this case to be able to see which exact python function pass or fail? (of course, workaround is to use in TC for every function a keyword but that is not what I prefer)

答:
If you are wanting to know which statement in the python-based keyword failed, you simply need to have it throw an appropriate error. Robot won't do this for you, however. From a reporting standpoint, a python based keyword is a black box. You will have to explicitly add logging messages, and return useful errors.

For example, the call to sideBarPage.createNewVehicle() should throw an exception such as "unable to create new vehicle". Likewise, the call to basicVehicleCreation.setKennzeichen(registrationno) should raise an error like "failed to register the vehicle".

If you don't have control over those methods, you can do the error handling from within your keyword:

```<code>@keyword("Create new vehicle with next ${registrationno} and ${description}")
def create_new_vehicle_Simple(self,registrationno, description):
    headerPage = HeaderPage(TestCaseKeywords.driver)
    sideBarPage = headerPage.selectDaten()
    try:
        basicVehicleCreation = sideBarPage.createNewVehicle()
    except:
        raise Exception("unable to create new vehicle")

    try:
        basicVehicleCreation.setKennzeichen(registrationno)
    except:
        raise exception("unable to register new vehicle")

    ...
</code>```

Body:
Currently I'm using Eclipse with Nokia/Red plugin which allows me to write robot framework test suites. Support is Python 3.6 and Selenium for it.
My project is called "Automation" and Test suites are in .robot files.
Test suites have test cases which are called "Keywords".

Test Cases

Create New Vehicle

Create new vehicle with next ${registrationno} and ${description}
Navigate to data section

Those "Keywords" are imported from python library and look like:

@keyword("Create new vehicle with next ${registrationno} and ${description}")
def create_new_vehicle_Simple(self,registrationno, description):
    headerPage = HeaderPage(TestCaseKeywords.driver)
    sideBarPage = headerPage.selectDaten()
    basicVehicleCreation = sideBarPage.createNewVehicle()
    basicVehicleCreation.setKennzeichen(registrationno)
    basicVehicleCreation.setBeschreibung(description)
    TestCaseKeywords.carnumber = basicVehicleCreation.save()

The problem is that when I run test cases, in log I only get result of this whole python function, pass or failed. I can't see at which step it failed- is it at first or second step of this function.

Is there any plugin or other solution for this case to be able to see which exact python function pass or fail? (of course, workaround is to use in TC for every function a keyword but that is not what I prefer)

Body:
If you are wanting to know which statement in the python-based keyword failed, you simply need to have it throw an appropriate error. Robot won't do this for you, however. From a reporting standpoint, a python based keyword is a black box. You will have to explicitly add logging messages, and return useful errors.

For example, the call to sideBarPage.createNewVehicle() should throw an exception such as "unable to create new vehicle". Likewise, the call to basicVehicleCreation.setKennzeichen(registrationno) should raise an error like "failed to register the vehicle".

If you don't have control over those methods, you can do the error handling from within your keyword:

@keyword("Create new vehicle with next ${registrationno} and ${description}")
def create_new_vehicle_Simple(self,registrationno, description):
    headerPage = HeaderPage(TestCaseKeywords.driver)
    sideBarPage = headerPage.selectDaten()
    try:
        basicVehicleCreation = sideBarPage.createNewVehicle()
    except:
        raise Exception("unable to create new vehicle")

    try:
        basicVehicleCreation.setKennzeichen(registrationno)
    except:
        raise exception("unable to register new vehicle")

    ...


问:
The Constructor is undefined? Enum error
```<code>public Tipo getTipo() {
    return this.Importo < 0.0 ? Tipo.USCITA : Tipo.ENTRATA;
}

public int compareTo(Movimento m) {
    if (this.idConto != this.idConto) {
        return this.idConto - this.idConto;
    }
    return this.DataMov.compareTo(this.DataMov);
}

public static enum Tipo {
    ENTRATA,// here i have this error : The constructor Movimento.Tipo() is undefined
    USCITA;// here is the same : The constructor Movimento.Tipo() is undefined

    private Tipo(String string2, int n2) {
    }
}
</code>```

I already have constructor that I need, what else I need to write?

答:
You wrote a constructor that takes two arguments, but no default constructor.  That means the compiler will not provide a no-arg constructor.  You should provide one or remove the private constructor.

I see no reason for the private constructor with two arguments.  You don't have any private data members in your enum.

Why is your enum static?  Remove that.

```<code>public enum Tipo {
    ENTRATA, USCITA;

}
</code>```

Body:
public Tipo getTipo() {
    return this.Importo < 0.0 ? Tipo.USCITA : Tipo.ENTRATA;
}

public int compareTo(Movimento m) {
    if (this.idConto != this.idConto) {
        return this.idConto - this.idConto;
    }
    return this.DataMov.compareTo(this.DataMov);
}

public static enum Tipo {
    ENTRATA,// here i have this error : The constructor Movimento.Tipo() is undefined
    USCITA;// here is the same : The constructor Movimento.Tipo() is undefined

    private Tipo(String string2, int n2) {
    }
}

I already have constructor that I need, what else I need to write?

Body:
You wrote a constructor that takes two arguments, but no default constructor.  That means the compiler will not provide a no-arg constructor.  You should provide one or remove the private constructor.

I see no reason for the private constructor with two arguments.  You don't have any private data members in your enum.

Why is your enum static?  Remove that.

public enum Tipo {
    ENTRATA, USCITA;

}


问:
how to assign jquery variable to php variable in Laravel
Inside a toolbar.blade I have this:

```<code><script>
$('.form-control').on('change',function(){
var TourDate = document.getElementById('TourDate').value;
if($('#TourDate_hidden').val()=="" || $('#TourID').val()==""){
    return;
  }
keyword= '_kfdTourDate:equal:'+$('#TourDate_hidden').val()+'|';
keyword+= '_kfnTourID:equal:'+$('#TourID').val();

reloadData( '#{{ $pageModule }}',"{{ $pageUrl }}/data?search="+keyword);
console.log(TourDate);
});
</script>
</code>```

Also I have a text input and a selectbox in toolbar.blade.
the input and selectbox look like this:

```<code>    <input type="text" class="form-control" name="TourDate"
id="TourDate" data-value="{{$testdate}}">

@if(count($tourTypes))
  <select name="_kfdTourID" id="TourID" onkeyup='saveValue(this);'>
    @foreach($tourTypes as $tourType)
      <optgroup label="{{ $tourType->_kftDescription }}">
          @if(count($tourType->tours))
          @foreach($tourType->tours as $tour)
          <option value="{{ $tour->_kpnID }}">{{ $tour->tDescription }}</option>
          @endforeach
          @endif
      </optgroup>
    @endforeach
  </select>
@endif
</code>```

When I click on text input, a boostrap calendar is poping up, after selecting a date it's showing the selected date inside the input and the page is reloading with the new filtered data trough ajax

e.g. XHR finished loading: GET "http://www.website.com/bookings/data?search=_kfdTourDate:equal:2017-03-11|_kfnTourID:equal:4

After the page is reloaded trough ajax the value inside the input is becoming empty and the first option in the selectbox is being selected automatically.

When I write

```<code>@php
        $testdate = "16/03/2017";
@endphp
</code>```

above the input I can see the date 16/03/2017 inside the input. Also I can print the selected tour date using console.log(TourDate) Even after I refresh the page the date 16/03/2017 stays inside the input. But somehow I cannot assign jquery variable TourDate to php variable testdate. How can I keep the data-value for the input and mark the selected option as selected  after the page is refreshed?

I tried this: keep input value after refresh page but couldn't make it work. I tried almost everything the whole day. I desperately need help to make this work. Thanks in advance for help.

答:
using document.write() you can assign a javascript variable value inside the php variable as

```<code>$phpVariable = "<script>document.write(javascriptVariable);</script>";
</code>```

Body:
Inside a toolbar.blade I have this:

Also I have a text input and a selectbox in toolbar.blade.
the input and selectbox look like this:

    <input type="text" class="form-control" name="TourDate"
id="TourDate" data-value="{{$testdate}}">

@if(count($tourTypes))
  <select name="_kfdTourID" id="TourID" onkeyup='saveValue(this);'>
    @foreach($tourTypes as $tourType)
      <optgroup label="{{ $tourType->_kftDescription }}">
          @if(count($tourType->tours))
          @foreach($tourType->tours as $tour)
          <option value="{{ $tour->_kpnID }}">{{ $tour->tDescription }}</option>
          @endforeach
          @endif
      </optgroup>
    @endforeach
  </select>
@endif

When I click on text input, a boostrap calendar is poping up, after selecting a date it's showing the selected date inside the input and the page is reloading with the new filtered data trough ajax

e.g. XHR finished loading: GET "http://www.website.com/bookings/data?search=_kfdTourDate:equal:2017-03-11|_kfnTourID:equal:4

After the page is reloaded trough ajax the value inside the input is becoming empty and the first option in the selectbox is being selected automatically.

When I write

@php
        $testdate = "16/03/2017";
@endphp

above the input I can see the date 16/03/2017 inside the input. Also I can print the selected tour date using console.log(TourDate) Even after I refresh the page the date 16/03/2017 stays inside the input. But somehow I cannot assign jquery variable TourDate to php variable testdate. How can I keep the data-value for the input and mark the selected option as selected  after the page is refreshed?

I tried this: keep input value after refresh page but couldn't make it work. I tried almost everything the whole day. I desperately need help to make this work. Thanks in advance for help.

Body:
using document.write() you can assign a javascript variable value inside the php variable as

$phpVariable = "<script>document.write(javascriptVariable);</script>";


问:
Extract the sub string from end offline to a special character in batch file
HI i am trying to get the sub string ZoomIn10X,ZoomIn20X,ZoomIn30X etc, from a file which contain following lines below and out put that to another file

```<code>Job Name : STANALONE/1234/JobId/Date/ZoomIn10X

Job Name : STANALONE/1234/JobId/Date/ZoomIn20X

Job Name : STANALONE/JobId/Date/ZoomIn30X

Job Name : STANALONE/1234/JobId/Date/ZoomIn40X

Job Name : STANALONE/1234/Date/ZoomIn10X
</code>```

i Have tried

```<code>for /F "tokens=*" %%A in (input.txt) do (

   echo %%A r "/" "\n" %%A | tail -1 >> output.txt

)
</code>```

but its not working as properly.Can you please help

答:
<pre class="lang-dos prettyprint-override"><code>>output.txt (for /f "delims=" %%a in (input.txt) do echo %%~nxa)
</code>```

<p>Given the input lines, and handling them as paths+files references (yes, they are not, but can be handled as if they were), using the <code>for</code> replaceable parameter modifiers (see <code>for /?</code>) we request the name and extension of the file being referenced. All the output of the <code>for</code> execution is redirected to <code>output.txt</code>.</p>

```<code>[W:\44365640]:# type go.cmd
@echo off
    setlocal enableextensions disabledelayedexpansion

    >output.txt (for /f "delims=" %%a in (input.txt) do echo %%~nxa)

[W:\44365640]:# type input.txt
Job Name : STANALONE/1234/JobId/Date/ZoomIn10X

Job Name : STANALONE/1234/JobId/Date/ZoomIn20X

Job Name : STANALONE/JobId/Date/ZoomIn30X

Job Name : STANALONE/1234/JobId/Date/ZoomIn40X

Job Name : STANALONE/1234/Date/ZoomIn10X

[W:\44365640]:# go
[W:\44365640]:# type output.txt
ZoomIn10X
ZoomIn20X
ZoomIn30X
ZoomIn40X
ZoomIn10X

[W:\44365640]:#
</code>```

Body:
HI i am trying to get the sub string ZoomIn10X,ZoomIn20X,ZoomIn30X etc, from a file which contain following lines below and out put that to another file

Job Name : STANALONE/1234/JobId/Date/ZoomIn10X

Job Name : STANALONE/1234/JobId/Date/ZoomIn20X

Job Name : STANALONE/JobId/Date/ZoomIn30X

Job Name : STANALONE/1234/JobId/Date/ZoomIn40X

Job Name : STANALONE/1234/Date/ZoomIn10X

i Have tried

for /F "tokens=*" %%A in (input.txt) do (

   echo %%A r "/" "\n" %%A | tail -1 >> output.txt

)

but its not working as properly.Can you please help

Body:
>output.txt (for /f "delims=" %%a in (input.txt) do echo %%~nxa)

Given the input lines, and handling them as paths+files references (yes, they are not, but can be handled as if they were), using the for replaceable parameter modifiers (see for /?) we request the name and extension of the file being referenced. All the output of the for execution is redirected to output.txt.

[W:\44365640]:# type go.cmd
@echo off
    setlocal enableextensions disabledelayedexpansion

    >output.txt (for /f "delims=" %%a in (input.txt) do echo %%~nxa)

[W:\44365640]:# type input.txt
Job Name : STANALONE/1234/JobId/Date/ZoomIn10X

Job Name : STANALONE/1234/JobId/Date/ZoomIn20X

Job Name : STANALONE/JobId/Date/ZoomIn30X

Job Name : STANALONE/1234/JobId/Date/ZoomIn40X

Job Name : STANALONE/1234/Date/ZoomIn10X

[W:\44365640]:# go
[W:\44365640]:# type output.txt
ZoomIn10X
ZoomIn20X
ZoomIn30X
ZoomIn40X
ZoomIn10X

[W:\44365640]:#


问:
Why this .js script stops working and is causing a browser freeze?
I've downloaded this Drupal 8 template and the site is at www.plotujeme.sk. It has an responsive navigation with this .js script:

```<code>function sidebar_menu() {

  var windowsize = jQuerywindow.width(),
      jQuerynav = jQuery("nav"),
      slide = {
          clear: function () {
              jQuerybody.removeClass('toggled');
              jQuery('.overlay').hide();
              jQuery('.easy-sidebar-toggle').prependTo("header");
              //jQuery('#search').prependTo("body");
              jQuery('.navbar.easy-sidebar').removeClass('toggled');
              jQuery('#navbar').removeAttr("style");
          },
          start: function () {
              jQuery('.overlay').show();
              jQuerybody.addClass('toggled');
              jQueryhtml.addClass('easy-sidebar-active');
              jQuerynav.addClass('easy-sidebar');
              jQuery('.easy-sidebar-toggle').prependTo(".easy-sidebar");
              //jQuery('#search').prependTo("#navbar");
              jQuery('#navbar').height(jQuerywindow.height()).css({
                  "padding-top": "60px"
              });
          },
          remove: function () {
              jQuerynav.removeClass('easy-sidebar');
          }
      };

  if (windowsize < 1003) {

      jQuerynav.addClass('easy-sidebar');
      jQuery('.easy-sidebar-toggle').on("click", function (e) {
          e.preventDefault();
          if (jQuerybody.hasClass('toggled')) {
              slide.clear();
          } else {
              slide.start();
          }
      });

      /*
      jQueryhtml.on('swiperight', function () {
          slide.start();
      });

      jQueryhtml.on('swipeleft', function () {
          slide.clear();
      }); */

  } else {
      slide.clear();
      slide.remove();
  }
}
</code>```

and:

```<code>jQuery(document).ready(function () {
    "use strict";

    sidebar_menu();

    jQuery(window).resize(function () {
        sidebar_menu();
    });
});
</code>```

Problem is, that if I open responsive navigation by clicking on hamburger button, it works several times and then it stops working, the page and a browser freezes or is unresponsive for a long time. I also noticed that (even in template preview) sometimes it does not work at all and nothing happens after clicking hamburger icon. When I resize window multiple times sometimes it works sometimes not.

Do you see any error in the script that could possibly cause this problem?

Update: I also tried to use jQuery('.easy-sidebar-toggle').off("click"); just before jQuery('.easy-sidebar-toggle').on("click", function() {...}); but got the same results.

答:
```<code>jQuery(window).resize(function () {
    sidebar_menu();
});
</code>```

As a result, whenever sidebar_menu function changes the window size, this function is called again and again, like a recursion, hence the freezing

Body:
I've downloaded this Drupal 8 template and the site is at www.plotujeme.sk. It has an responsive navigation with this .js script:

function sidebar_menu() {

  var windowsize = jQuerywindow.width(),
      jQuerynav = jQuery("nav"),
      slide = {
          clear: function () {
              jQuerybody.removeClass('toggled');
              jQuery('.overlay').hide();
              jQuery('.easy-sidebar-toggle').prependTo("header");
              //jQuery('#search').prependTo("body");
              jQuery('.navbar.easy-sidebar').removeClass('toggled');
              jQuery('#navbar').removeAttr("style");
          },
          start: function () {
              jQuery('.overlay').show();
              jQuerybody.addClass('toggled');
              jQueryhtml.addClass('easy-sidebar-active');
              jQuerynav.addClass('easy-sidebar');
              jQuery('.easy-sidebar-toggle').prependTo(".easy-sidebar");
              //jQuery('#search').prependTo("#navbar");
              jQuery('#navbar').height(jQuerywindow.height()).css({
                  "padding-top": "60px"
              });
          },
          remove: function () {
              jQuerynav.removeClass('easy-sidebar');
          }
      };

  if (windowsize < 1003) {

      jQuerynav.addClass('easy-sidebar');
      jQuery('.easy-sidebar-toggle').on("click", function (e) {
          e.preventDefault();
          if (jQuerybody.hasClass('toggled')) {
              slide.clear();
          } else {
              slide.start();
          }
      });

      /*
      jQueryhtml.on('swiperight', function () {
          slide.start();
      });

      jQueryhtml.on('swipeleft', function () {
          slide.clear();
      }); */

  } else {
      slide.clear();
      slide.remove();
  }
}

and:

jQuery(document).ready(function () {
    "use strict";

    sidebar_menu();

    jQuery(window).resize(function () {
        sidebar_menu();
    });
});

Problem is, that if I open responsive navigation by clicking on hamburger button, it works several times and then it stops working, the page and a browser freezes or is unresponsive for a long time. I also noticed that (even in template preview) sometimes it does not work at all and nothing happens after clicking hamburger icon. When I resize window multiple times sometimes it works sometimes not.

Do you see any error in the script that could possibly cause this problem?

Update: I also tried to use jQuery('.easy-sidebar-toggle').off("click"); just before jQuery('.easy-sidebar-toggle').on("click", function() {...}); but got the same results.

Body:
jQuery(window).resize(function () {
    sidebar_menu();
});

As a result, whenever sidebar_menu function changes the window size, this function is called again and again, like a recursion, hence the freezing


问:
How to generate multiple records based on column?
I have records like below. I would like to convert a single record into two records with values EXTERNAL and INTERNAL each if the 3rd attribute is All.

Input dataset:

```<code>Surender,cts,INTERNAL
Raja,cts,EXTERNAL
Ajay,tcs,All
</code>```

Expected output:

```<code>Surender,cts,INTERNAL
Raja,cts,EXTERNAL
Ajay,tcs,INTERNAL
Ajay,tcs,EXTERNAL
</code>```

My Spark Code :

```<code>case class Customer(name:String,organisation:String,campaign_type:String)

val custRDD = sc.textFile("/user/cloudera/input_files/customer.txt")

val mapRDD = custRDD.map(record => record.split(","))
    .map(arr => (arr(0),arr(1),arr(2))
    .map(tuple => {
      val name            = tuple._1.trim
      val organisation    = tuple._2.trim
      val campaign_type   = tuple._3.trim.toUpperCase
      Customer(name, organisation, campaign_type)
    })

mapRDD.toDF().registerTempTable("customer_processed")

sqlContext.sql("SELECT * FROM customer_processed").show
</code>```

Could Someone help me to fix this issue?

答:
You can use and udf to transform the campaign_type column containing a Seq of strings  to map it to the campaigns type and then explode :

```<code>val campaignType_ : (String => Seq[String]) = {
  case s if s == "ALL" => Seq("EXTERNAL", "INTERNAL")
  case s => Seq(s)
}

val campaignType = udf(campaignType_)

val df = Seq(("Surender", "cts", "INTERNAL"),
  ("Raja", "cts", "EXTERNAL"),
  ("Ajay", "tcs", "ALL"))
  .toDF("name", "organisation", "campaign_type")

val step1 = df.withColumn("campaign_type", campaignType($"campaign_type"))
step1.show
// +--------+------------+--------------------+
// |    name|organisation|       campaign_type|
// +--------+------------+--------------------+
// |Surender|         cts|          [INTERNAL]|
// |    Raja|         cts|          [EXTERNAL]|
// |    Ajay|         tcs|[EXTERNAL, INTERNAL]|
// +--------+------------+--------------------+

val step2 = step1.select($"name", $"organisation", explode($"campaign_type"))
step2.show
// +--------+------------+--------+
// |    name|organisation|     col|
// +--------+------------+--------+
// |Surender|         cts|INTERNAL|
// |    Raja|         cts|EXTERNAL|
// |    Ajay|         tcs|EXTERNAL|
// |    Ajay|         tcs|INTERNAL|
// +--------+------------+--------+
</code>```

EDIT:

You don't actually need a udf, you can use a when().otherwise predicate instead on step1 as followed :

```<code>val step1 = df.withColumn("campaign_type",
when(col("campaign_type") === "ALL", array("EXTERNAL", "INTERNAL")).otherwise(array(col("campaign_type")))
</code>```

Body:
I have records like below. I would like to convert a single record into two records with values EXTERNAL and INTERNAL each if the 3rd attribute is All.

Input dataset:

Surender,cts,INTERNAL
Raja,cts,EXTERNAL
Ajay,tcs,All

Expected output:

Surender,cts,INTERNAL
Raja,cts,EXTERNAL
Ajay,tcs,INTERNAL
Ajay,tcs,EXTERNAL

My Spark Code :

case class Customer(name:String,organisation:String,campaign_type:String)

val custRDD = sc.textFile("/user/cloudera/input_files/customer.txt")

val mapRDD = custRDD.map(record => record.split(","))
    .map(arr => (arr(0),arr(1),arr(2))
    .map(tuple => {
      val name            = tuple._1.trim
      val organisation    = tuple._2.trim
      val campaign_type   = tuple._3.trim.toUpperCase
      Customer(name, organisation, campaign_type)
    })

mapRDD.toDF().registerTempTable("customer_processed")

sqlContext.sql("SELECT * FROM customer_processed").show

Could Someone help me to fix this issue?

Body:
You can use and udf to transform the campaign_type column containing a Seq of strings  to map it to the campaigns type and then explode :

val campaignType_ : (String => Seq[String]) = {
  case s if s == "ALL" => Seq("EXTERNAL", "INTERNAL")
  case s => Seq(s)
}

val campaignType = udf(campaignType_)

val df = Seq(("Surender", "cts", "INTERNAL"),
  ("Raja", "cts", "EXTERNAL"),
  ("Ajay", "tcs", "ALL"))
  .toDF("name", "organisation", "campaign_type")

val step1 = df.withColumn("campaign_type", campaignType($"campaign_type"))
step1.show
// +--------+------------+--------------------+
// |    name|organisation|       campaign_type|
// +--------+------------+--------------------+
// |Surender|         cts|          [INTERNAL]|
// |    Raja|         cts|          [EXTERNAL]|
// |    Ajay|         tcs|[EXTERNAL, INTERNAL]|
// +--------+------------+--------------------+

val step2 = step1.select($"name", $"organisation", explode($"campaign_type"))
step2.show
// +--------+------------+--------+
// |    name|organisation|     col|
// +--------+------------+--------+
// |Surender|         cts|INTERNAL|
// |    Raja|         cts|EXTERNAL|
// |    Ajay|         tcs|EXTERNAL|
// |    Ajay|         tcs|INTERNAL|
// +--------+------------+--------+

EDIT:

You don't actually need a udf, you can use a when().otherwise predicate instead on step1 as followed :

val step1 = df.withColumn("campaign_type",
when(col("campaign_type") === "ALL", array("EXTERNAL", "INTERNAL")).otherwise(array(col("campaign_type")))


问:
C Multidimensional Array: Am I missing something?
I'm currently learning C, and I have just written a draft of a program that allows a user to move a player around a character-based maze/path. I have built the maze/path as multidimensional character array, with a while loop controlling the player's position by replacing certain characters in the array. Here is the multidimensional array I have initialised:

```<code>char maze[5][7] = {
    {"_", "_", "_", "_", "_"},
    {"|", " ", " ", " ", "|"},
    {"|", " ", "|", " ", "|"},
    {"|", " ", "|", "_", "|"},
    {"|", "_", " ", " ", "|"},
    {"|", " ", "|", " ", "|"},
    {"|", "_", "_", "_", "|"}
};
</code>```

However, when I try to compile, I get this error:

```<code>error: '}' expected
</code>```

The first row in the array is apparently missing some sort of closing bracket, although I have checked proper array syntax multiple times and this appears to be correct. What am I missing? Are there any other issues with this?

答:
You are giving wrong dimensions to the array maze[5][7] it is row and column and you definition says 7rows and 5 columns. And you are entering every element as an string. It should be a character which is given inside single quote  like this 'a'. If you will define in double quote it will become string. This will solve your problem

```<code>char maze[7][5] = {
{'_', '_', '_', '_', '_'},
{'|', ' ', ' ', ' ', '|'},
{'|', ' ', '|', ' ', '|'},
{'|', ' ', '|', '_', '|'},
{'|', '_', ' ', ' ', '|'},
{'|', ' ', '|', ' ', '|'},
{'|', '_', '_', '_', '|'}
};
</code>```

Hope this Helps :)

Body:
I'm currently learning C, and I have just written a draft of a program that allows a user to move a player around a character-based maze/path. I have built the maze/path as multidimensional character array, with a while loop controlling the player's position by replacing certain characters in the array. Here is the multidimensional array I have initialised:

char maze[5][7] = {
    {"_", "_", "_", "_", "_"},
    {"|", " ", " ", " ", "|"},
    {"|", " ", "|", " ", "|"},
    {"|", " ", "|", "_", "|"},
    {"|", "_", " ", " ", "|"},
    {"|", " ", "|", " ", "|"},
    {"|", "_", "_", "_", "|"}
};

However, when I try to compile, I get this error:

error: '}' expected

The first row in the array is apparently missing some sort of closing bracket, although I have checked proper array syntax multiple times and this appears to be correct. What am I missing? Are there any other issues with this?

Body:
You are giving wrong dimensions to the array maze[5][7] it is row and column and you definition says 7rows and 5 columns. And you are entering every element as an string. It should be a character which is given inside single quote  like this 'a'. If you will define in double quote it will become string. This will solve your problem

char maze[7][5] = {
{'_', '_', '_', '_', '_'},
{'|', ' ', ' ', ' ', '|'},
{'|', ' ', '|', ' ', '|'},
{'|', ' ', '|', '_', '|'},
{'|', '_', ' ', ' ', '|'},
{'|', ' ', '|', ' ', '|'},
{'|', '_', '_', '_', '|'}
};

Hope this Helps :)