问:
Can I use BufferedReader and create an array inside actionListener class?
I've created an actionListener class. in the actionPerformed method, i would like run a code. This code involves importing data from multiple text files, and store them in a 2D array. Then it will print out a list of quotes in the frame. Then it will print out the 5 analysis and let the user choose which one. However, i am currently stuck with the IOException. Plus, some code states gives an error "unreachable code." What does that means? Below is the code for my actionListener class

```<code>import java.awt.event.*;
import java.io.*;
import java.util.*;

public class CrucibleButtonListener implements ActionListener
{
  private Swing g;

public CrucibleButtonListener (Swing g)
{
   this.g = g;
}

public void actionPerformed(ActionEvent e)
{
   this.g.updateTextField(getQuotes());
}

private String getQuotes() throws IOException
{
   BufferedReader inputQuote;
   BufferedReader inputTheme;
   BufferedReader inputCharacterAnalysis;
   BufferedReader inputSignificance;
   BufferedReader inputPlotEnhancement;
   BufferedReader inputSpeaker;

   Scanner in = new Scanner (System.in);
   int howMany=0;
   int quoteSelection;
   int analysisSelection;

   // Count how many lines in the text file
   FileReader fr = new FileReader ("CrucibleQuotations.txt");
   LineNumberReader ln = new LineNumberReader (fr);
   while (ln.readLine() != null)
   {
     howMany++;
   }

  //import information from the text file
  inputQuote = new BufferedReader (new FileReader ("CrucibleQuotations.txt"));
  inputTheme = new BufferedReader (new FileReader("CrucibleTheme.txt"));
  inputCharacterAnalysis = new BufferedReader (new FileReader("CrucibleCharacterAnalysis.txt"));
  inputSignificance = new BufferedReader (new FileReader("CrucibleSignificance.txt"));
  inputPlotEnhancement = new BufferedReader (new FileReader("CruciblePlotEnhancement.txt"));
  inputSpeaker = new BufferedReader (new FileReader("CrucibleSpeaker.txt"));

//Create array based on how many quotes available in the text file
String [][] quotes = new String [howMany][6];

//Store quote information in the array and display the list of quotations
for (int i=0; i<howMany; i++)
{
  quotes [i][0] = inputQuote.readLine();
  return (i+1 + ") " + quotes [i][0]);
  quotes [i][1] = inputTheme.readLine();
  quotes [i][2] = inputCharacterAnalysis.readLine();
  quotes [i][3] = inputSignificance.readLine();
  quotes [i][4] = inputPlotEnhancement.readLine();
  quotes [i][5] = inputSpeaker.readLine();
}

//Ask user to choose the quote they want to analyze
return ("Choose a quotation by inputting the number: ");
quoteSelection = in.nextInt ();

if (quoteSelection!=0)
{
  //Show user selections to analyze
  return ("1. Theme");
  return ("2. Character Analysis");
  return ("3. Significance");
  return ("4. Plot Enhancement");
  return ("5. Speaker");
  analysisSelection = in.nextInt ();

  //Display the analysis
  if (analysisSelection <= 5 || analysisSelection > 0)
  {
    return (quotes [quoteSelection-1][analysisSelection]);
  }
}
}
}
</code>```

Here is the swing class. It only contains a button, which i can't seem to make it work.

```<code>import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.*;

public class Swing
{
  private JLabel label;
  public Swing()
  {
    JFrame frame = new JFrame ("FRAME SAMPLE");
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

    JButton cButton = new JButton("The Crucible");//The JButton name.
    frame.add(cButton);//Add the button to the JFrame.
    cButton.addActionListener(new CrucibleButtonListener(this));
  }
}
</code>```

Main Class:

```<code>public class Main
{
  public static void main (String [] args)
  {
    new Swing();
  }
}
</code>```

答:
Copy & paste is the single worst thing a programmer can do.

Your variables are local for the method main, you can't access them anywhere else. Move them out of the method. If you make them static, then you can access them using MainProgram.inputQuote, etc. However, static variables are in general a bad coding style.

So you'd better move it all into a separate class (let's call it Worker for now) together with the code, and do only the following in MainProgram

```<code>public void main(string[] args) {
    Worker worker = new Worker();
    CrucibleButtonListener l = new CrucibleButtonListener(Worker);
    ...
}
</code>```

In the constructor of CrucibleButtonListener you assign the worker to a field and can access it anytime.

This is a bit more to type, but leads to a good style and flexibility. Get a good book and/or study some good code.

You could use MainProgram directly instead of Worker, but I strongly prefer to minimize the main class. I only let it bind the other classes together. Btw., use some meaningful name instead of "MainProgram". Otherwise you'll end calling all you program like

java MainProgram1

java MainProgram2

java MainProgram3

Body:
I've created an actionListener class. in the actionPerformed method, i would like run a code. This code involves importing data from multiple text files, and store them in a 2D array. Then it will print out a list of quotes in the frame. Then it will print out the 5 analysis and let the user choose which one. However, i am currently stuck with the IOException. Plus, some code states gives an error "unreachable code." What does that means? Below is the code for my actionListener class

import java.awt.event.*;
import java.io.*;
import java.util.*;

public class CrucibleButtonListener implements ActionListener
{
  private Swing g;

public CrucibleButtonListener (Swing g)
{
   this.g = g;
}

public void actionPerformed(ActionEvent e)
{
   this.g.updateTextField(getQuotes());
}

private String getQuotes() throws IOException
{
   BufferedReader inputQuote;
   BufferedReader inputTheme;
   BufferedReader inputCharacterAnalysis;
   BufferedReader inputSignificance;
   BufferedReader inputPlotEnhancement;
   BufferedReader inputSpeaker;

   Scanner in = new Scanner (System.in);
   int howMany=0;
   int quoteSelection;
   int analysisSelection;

   // Count how many lines in the text file
   FileReader fr = new FileReader ("CrucibleQuotations.txt");
   LineNumberReader ln = new LineNumberReader (fr);
   while (ln.readLine() != null)
   {
     howMany++;
   }

  //import information from the text file
  inputQuote = new BufferedReader (new FileReader ("CrucibleQuotations.txt"));
  inputTheme = new BufferedReader (new FileReader("CrucibleTheme.txt"));
  inputCharacterAnalysis = new BufferedReader (new FileReader("CrucibleCharacterAnalysis.txt"));
  inputSignificance = new BufferedReader (new FileReader("CrucibleSignificance.txt"));
  inputPlotEnhancement = new BufferedReader (new FileReader("CruciblePlotEnhancement.txt"));
  inputSpeaker = new BufferedReader (new FileReader("CrucibleSpeaker.txt"));

//Create array based on how many quotes available in the text file
String [][] quotes = new String [howMany][6];

//Store quote information in the array and display the list of quotations
for (int i=0; i<howMany; i++)
{
  quotes [i][0] = inputQuote.readLine();
  return (i+1 + ") " + quotes [i][0]);
  quotes [i][1] = inputTheme.readLine();
  quotes [i][2] = inputCharacterAnalysis.readLine();
  quotes [i][3] = inputSignificance.readLine();
  quotes [i][4] = inputPlotEnhancement.readLine();
  quotes [i][5] = inputSpeaker.readLine();
}

//Ask user to choose the quote they want to analyze
return ("Choose a quotation by inputting the number: ");
quoteSelection = in.nextInt ();

if (quoteSelection!=0)
{
  //Show user selections to analyze
  return ("1. Theme");
  return ("2. Character Analysis");
  return ("3. Significance");
  return ("4. Plot Enhancement");
  return ("5. Speaker");
  analysisSelection = in.nextInt ();

  //Display the analysis
  if (analysisSelection <= 5 || analysisSelection > 0)
  {
    return (quotes [quoteSelection-1][analysisSelection]);
  }
}
}
}

Here is the swing class. It only contains a button, which i can't seem to make it work.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.util.*;

public class Swing
{
  private JLabel label;
  public Swing()
  {
    JFrame frame = new JFrame ("FRAME SAMPLE");
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

    JButton cButton = new JButton("The Crucible");//The JButton name.
    frame.add(cButton);//Add the button to the JFrame.
    cButton.addActionListener(new CrucibleButtonListener(this));
  }
}

Main Class:

public class Main
{
  public static void main (String [] args)
  {
    new Swing();
  }
}

Body:
Copy & paste is the single worst thing a programmer can do.

Your variables are local for the method main, you can't access them anywhere else. Move them out of the method. If you make them static, then you can access them using MainProgram.inputQuote, etc. However, static variables are in general a bad coding style.

So you'd better move it all into a separate class (let's call it Worker for now) together with the code, and do only the following in MainProgram

public void main(string[] args) {
    Worker worker = new Worker();
    CrucibleButtonListener l = new CrucibleButtonListener(Worker);
    ...
}

In the constructor of CrucibleButtonListener you assign the worker to a field and can access it anytime.

This is a bit more to type, but leads to a good style and flexibility. Get a good book and/or study some good code.

You could use MainProgram directly instead of Worker, but I strongly prefer to minimize the main class. I only let it bind the other classes together. Btw., use some meaningful name instead of "MainProgram". Otherwise you'll end calling all you program like

java MainProgram1

java MainProgram2

java MainProgram3


来源: stackexchange

问:
Setting up a loop in SQL
Can someone tell me how to do this as a loop in SQL?

```<code>update Bank set Report_date_next='2014-02-28' where Reporting_date='2014-01-31'
update Bank set Report_date_next='2014-03-31' where Reporting_date='2014-02-28'
update Bank set Report_date_next='2014-04-30' where Reporting_date='2014-03-31'
update Bank set Report_date_next='2014-05-31' where Reporting_date='2014-04-30'
update Bank set Report_date_next='2014-06-30' where Reporting_date='2014-05-31'
update Bank set Report_date_next='2014-07-31' where Reporting_date='2014-06-30'
</code>```

The list goes on for quite a while so I need a counter on how to find the last cell as well similar to the XlDown in VBA.

答:
You're way better off using a CASE statement:

```<code>UPDATE Bank
SET Report_date_next = CASE WHEN Reporting_date = '2014-01-31' THEN '2014-02-28'
                            WHEN Reporting_date = '2014-02-28' THEN '2014-03-31'
                            WHEN ...etc
                        END
</code>```

If you tag your question with the DBMS you're using, there may be an even easier way depending on the functions available to you.

For instance, SQL Server 2012+ you can do:

```<code>UPDATE Bank
SET report_date_next = EOMONTH(Reporting_date,1)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Setting up a loop in SQL

Body:
Can someone tell me how to do this as a loop in SQL?

update Bank set Report_date_next='2014-02-28' where Reporting_date='2014-01-31'
update Bank set Report_date_next='2014-03-31' where Reporting_date='2014-02-28'
update Bank set Report_date_next='2014-04-30' where Reporting_date='2014-03-31'
update Bank set Report_date_next='2014-05-31' where Reporting_date='2014-04-30'
update Bank set Report_date_next='2014-06-30' where Reporting_date='2014-05-31'
update Bank set Report_date_next='2014-07-31' where Reporting_date='2014-06-30'

The list goes on for quite a while so I need a counter on how to find the last cell as well similar to the XlDown in VBA.

Body:
You're way better off using a CASE statement:

UPDATE Bank
SET Report_date_next = CASE WHEN Reporting_date = '2014-01-31' THEN '2014-02-28'
                            WHEN Reporting_date = '2014-02-28' THEN '2014-03-31'
                            WHEN ...etc
                        END

If you tag your question with the DBMS you're using, there may be an even easier way depending on the functions available to you.

For instance, SQL Server 2012+ you can do:

UPDATE Bank
SET report_date_next = EOMONTH(Reporting_date,1)


问:
Is it possible to have the "IF" on a "select" statement or using "Case"?
I have an IF statement that basically gives me concatenation of addresses if value for them is not null. as see below :

```<code>IF @Address1 IS NOT NULL
BEGIN
    IF @Address2 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+@Address2
        ELSE SET @TotalAddress=@Address1;
    IF @Address3 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')
    IF @Address4 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')+CHAR(13)+ISNULL(@Address4, '')
END
</code>```

I was wondering if I can have my code in select statement directly and grab address1,2 and 3 without creating a variable.

答:
No need to use if condition. You can achieve the desired output using ISNULL() and NULLIF() function.

Try this

```<code>DECLARE @address1 varchar(50)= NULL,
        @address2 varchar(50)= '39 Cox Street',
        @address3 varchar(50)= '',
        @address4 varchar(50)= 'Chicago',
        @TotalAddress varchar(max)

SET @TotalAddress = ISNULL(NULLIF(@Address1, '') + CHAR(13), '')
                    +ISNULL(NULLIF(@Address2, '') + CHAR(13), '')
                    +ISNULL(NULLIF(@Address3, '') + CHAR(13), '')
                    +ISNULL(NULLIF(@Address4, ''), '')

PRINT @TotalAddress
</code>```

Body:
I have an IF statement that basically gives me concatenation of addresses if value for them is not null. as see below :

IF @Address1 IS NOT NULL
BEGIN
    IF @Address2 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+@Address2
        ELSE SET @TotalAddress=@Address1;
    IF @Address3 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')
    IF @Address4 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')+CHAR(13)+ISNULL(@Address4, '')
END

I was wondering if I can have my code in select statement directly and grab address1,2 and 3 without creating a variable.

Body:
No need to use if condition. You can achieve the desired output using ISNULL() and NULLIF() function.

Try this

DECLARE @address1 varchar(50)= NULL,
        @address2 varchar(50)= '39 Cox Street',
        @address3 varchar(50)= '',
        @address4 varchar(50)= 'Chicago',
        @TotalAddress varchar(max)

SET @TotalAddress = ISNULL(NULLIF(@Address1, '') + CHAR(13), '')
                    +ISNULL(NULLIF(@Address2, '') + CHAR(13), '')
                    +ISNULL(NULLIF(@Address3, '') + CHAR(13), '')
                    +ISNULL(NULLIF(@Address4, ''), '')

PRINT @TotalAddress


问:
ConstraintLayout cannot be cast to android.widget.TextView
I keep getting a runtime error when I try to launch an activity.

Line where the error happen:

```<code>private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {

        textView1.setText("Csatlakozás...");
        String info = ((TextView) v).getText().toString(); // <-- ERROR HERE
        String address = info.substring(info.length() - 17);
        Intent i = new Intent(DeviceListActivity.this, MainActivity.class);
        i.putExtra(EXTRA_DEVICE_ADDRESS, address);
        startActivity(i);
    }
};
</code>```

Logcat:

java.lang.ClassCastException:
  android.support.constraint.ConstraintLayout cannot be cast to
  android.widget.TextView
                                                                                at
  arduinosensors.example.com.smarthome3.DeviceListActivity$1.onItemClick(DeviceListActivity.java:106)

What is happening here? It was fine until I started to use a custom array adapter with custom row layout.

Edit:

custom_row.xml

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView"
            android:textSize="18sp" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>
</code>```

My adapter:

```<code>public class UsersAdapter extends ArrayAdapter<Adapter> {
    public UsersAdapter(Context context, ArrayList<Adapter> users) {
        super(context, 0, users);
    }

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

        Adapter user = getItem(position);

        if (convertView == null) {
            LayoutInflater sontInflater = LayoutInflater.from(getContext());
            convertView = sontInflater.inflate(R.layout.custom_row,parent,false);
        }

        TextView one = (TextView) convertView.findViewById(R.id.textView);
        TextView two = (TextView) convertView.findViewById(R.id.textView2);

        one.setText(user.name);
        two.setText(user.hometown);

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

答:
From the documentation:

View: The view within the AdapterView that was clicked (this will be a
  view provided by the adapter)

In your case the View is the root ConstraintLayout. And as the error says you can't cast it to TextView. To get the info you can use:

String info = v.findViewById(R.id.textView).getText().toString()

Body:
I keep getting a runtime error when I try to launch an activity.

Line where the error happen:

private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {

        textView1.setText("Csatlakozás...");
        String info = ((TextView) v).getText().toString(); // <-- ERROR HERE
        String address = info.substring(info.length() - 17);
        Intent i = new Intent(DeviceListActivity.this, MainActivity.class);
        i.putExtra(EXTRA_DEVICE_ADDRESS, address);
        startActivity(i);
    }
};

Logcat:

java.lang.ClassCastException:
  android.support.constraint.ConstraintLayout cannot be cast to
  android.widget.TextView
                                                                                at
  arduinosensors.example.com.smarthome3.DeviceListActivity$1.onItemClick(DeviceListActivity.java:106)

What is happening here? It was fine until I started to use a custom array adapter with custom row layout.

Edit:

custom_row.xml

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView"
            android:textSize="18sp" />
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

My adapter:

public class UsersAdapter extends ArrayAdapter<Adapter> {
    public UsersAdapter(Context context, ArrayList<Adapter> users) {
        super(context, 0, users);
    }

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

        Adapter user = getItem(position);

        if (convertView == null) {
            LayoutInflater sontInflater = LayoutInflater.from(getContext());
            convertView = sontInflater.inflate(R.layout.custom_row,parent,false);
        }

        TextView one = (TextView) convertView.findViewById(R.id.textView);
        TextView two = (TextView) convertView.findViewById(R.id.textView2);

        one.setText(user.name);
        two.setText(user.hometown);

        return convertView;
    }
}


问:
What is the wallet path for credentials in web3j?
I am using the readme guide https://github.com/web3j/web3j.

What I am interested is developing smart contracts from my host with Java + Web3j to private Ethereum network which runs on my virtual machine.

There are such lines:

```<code>Web3j web3 = Web3j.build(new HttpService());  // defaults to http://localhost:8545/
Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");
</code>```

How should I create this wallet? Should I generate account on my VM and then copy wallet.json file to my host?

答:
WalletUtils.loadCredentials can be buggy, I would recommend creating the accounts before hand, and then you can extract the private key and use

```<code>Credentials.create(privateKey)
</code>```

You can use the keystore file and use myetherwallet to view your private key.

ContentLicense: CC BY-SA 4.0

Body:
I am using the readme guide https://github.com/web3j/web3j.

What I am interested is developing smart contracts from my host with Java + Web3j to private Ethereum network which runs on my virtual machine.

There are such lines:

Web3j web3 = Web3j.build(new HttpService());  // defaults to http://localhost:8545/
Credentials credentials = WalletUtils.loadCredentials("password", "/path/to/walletfile");

How should I create this wallet? Should I generate account on my VM and then copy wallet.json file to my host?

Body:
WalletUtils.loadCredentials can be buggy, I would recommend creating the accounts before hand, and then you can extract the private key and use

Credentials.create(privateKey)

You can use the keystore file and use myetherwallet to view your private key.


问:
Visual Studio: how to control specific configuration parameters on student PCs?
Can anyone tell me how to control default configuration parameters in VS 2017 C++?  The scenario is that we generate one sample PC with the software we want (Win10, VS2017, et cetera), and this image is cloned onto about 100 PCs in student CS labs.

The two specific things I would like to control are (1) use of precompiled headers and (2) message C4706 (= versus == in an if condition).  There are some others, but these are at top of the list.

I know students could fix this themselves, but so many are confused in the first few weeks of an introductory programming class that I don't want to try that.

A search of MSDN has not been productive, but I probably am using the wrong search terms.

Thank you in advance!

答:
You could also edit the default platform property pages found at \\AppData\Local\Microsoft\MSBuild\v4.0, Microsoft.Cpp.Win32.user.props and Microsoft.Cpp.x64.user.props

I'm not sure how you would automatically distribute those files but so long as you are using MSBuild as the build system anything in those files is picked up prior to project-specific settings.


问:
Task return type with and without Async
I little bit confused on the behavior of the async keyword.

Lets say I have 2 methods,

```<code>public async Task DoSomething1()
{
    await Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}
</code>```

And

```<code>public Task DoSomething2()
{
    return Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}
</code>```

From my understanding both methods are awaitable. But when I write a method that has a Task return type without the async keyword I need to return a Task otherwise the compiler generates an error. Its a common thing that a method should return its type. But when I use it with the async keyword the compiler generates another error that you can't return a Task. So what does it mean? I am totally confused here.

答:
(...) “async”. This keyword
  allows that inside the method the word “await” can be used, and
  modifies how its result is handled by the method. That’s it.

The method runs synchronously until it finds the word “await” and that
  word is the one that takes care of asynchrony. “Await” is an operator
  that receives a parameter: an awaitable (an asynchronous operation)
  behaves in this way:

From here

Title: Task return type with and without Async

Body:
I little bit confused on the behavior of the async keyword.

Lets say I have 2 methods,

public async Task DoSomething1()
{
    await Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}

And

public Task DoSomething2()
{
    return Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}

From my understanding both methods are awaitable. But when I write a method that has a Task return type without the async keyword I need to return a Task otherwise the compiler generates an error. Its a common thing that a method should return its type. But when I use it with the async keyword the compiler generates another error that you can't return a Task. So what does it mean? I am totally confused here.


问:
New line character in notepad
I am using openCSV to generate .txt file. I am able to generate the file successfully, but the new line character which i have given were not reflecting in the notepad. But when open the same file in notepad++ it is working fine. Is there any approach to make it work in the notepad..</p>

答:
One option is to first open the generated file in Notepad++ and search for the regular expression

```<code>(?!\r)(.)\n
</code>```

And replace it with

```<code>$1\r\n
</code>```

Then save the file and open it in Windows notepad.

Another option is to use \r\n as your new line character when you generate the file, if that is an option in your particular situation.

Title: New line character in notepad

Body:
One option is to first open the generated file in Notepad++ and search for the regular expression

(?!\r)(.)\n

And replace it with

$1\r\n

Then save the file and open it in Windows notepad.

Another option is to use \r\n as your new line character when you generate the file, if that is an option in your particular situation.


问:
fetch_assoc returns last inserted elements
For some reasons mysql returns only last inserted element in table,could anyone give a tip what's wrong with my code? i'm just practicing php and trying to figure out best ways to make functions easily reusable(just practicing oop i mean). i know this is a bad way but it's only for practice purposes.</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>Test Title</title>
</head>
<body>
    <?php
        class Database{
            public $db;

            public function __construct($host,$username,$password,$dbname){

                $this->db=new MySQLi($host,$username,$password,$dbname);

            }
            public function getData(){
                $query="SELECT * FROM artisan";
                $result=$this->db->query($query);
                if($result->num_rows>0){
                    while($row=$result->fetch_assoc()){
                        echo "ID: ".$row["id"]. "-Username: ".$row["username"]. ", "."Email: ".$row["email"]."<br>";
                    }
                }else{
                    echo "No results found!";
                }

            }
            public function getContent(){
                $query="SELECT * FROM content";
                $result=$this->db->query($query);
                $values=array();
                if($result->num_rows>0){
                    while($row=$result->fetch_assoc()){
                    $values=array(
                        "title"=>$row['title'],
                        "body"=>$row['body']
                    );
                }

            }
            return $values;
            }
        }
        $database=new Database('localhost','root','','test');
        $database->getData();
        $values=$database->getContent();

     ?>

     <style type="text/css">
        .container{
            text-align:center;
        }
     </style>
     <div class="container">
      <?php

        for($i=0;$i<count($values);$i++){
        echo $values["title"]."<br>";
        echo $values["body"]."<br>";
      }
       ?>
     </div>
</body>
</html>
</code>```

答:
You should add each row to $values instead of replacing it each time.

Where you have:

```<code>$values=array(
      "title"=>$row['title'],
      "body"=>$row['body']
);
</code>```

Change it to:

```<code>$values[] = array(
      "title"=>$row['title'],
      "body"=>$row['body']
);
</code>```

And then where you have the display:

```<code>for($i=0;$i<count($values);$i++){
    echo $values["title"]."<br>";
    echo $values["body"]."<br>";
}
</code>```

Change to:

```<code>foreach($values as $value){
    echo $value["title"]."<br>";
    echo $value["body"]."<br>";
}
</code>```

Or using a FOR:

```<code>for($i=0;$i<count($values);$i++){
    echo $values[$i]["title"]."<br>";
    echo $values[$i]["body"]."<br>";
}
</code>```

Body:
For some reasons mysql returns only last inserted element in table,could anyone give a tip what's wrong with my code? i'm just practicing php and trying to figure out best ways to make functions easily reusable(just practicing oop i mean). i know this is a bad way but it's only for practice purposes.

<!DOCTYPE html>

    <title>Test Title</title>

    <?php
        class Database{
            public $db;

            public function __construct($host,$username,$password,$dbname){

                $this->db=new MySQLi($host,$username,$password,$dbname);

            }
            public function getData(){
                $query="SELECT * FROM artisan";
                $result=$this->db->query($query);
                if($result->num_rows>0){
                    while($row=$result->fetch_assoc()){
                        echo "ID: ".$row["id"]. "-Username: ".$row["username"]. ", "."Email: ".$row["email"]."
";
                    }
                }else{
                    echo "No results found!";
                }

            }
            public function getContent(){
                $query="SELECT * FROM content";
                $result=$this->db->query($query);
                $values=array();
                if($result->num_rows>0){
                    while($row=$result->fetch_assoc()){
                    $values=array(
                        "title"=>$row['title'],
                        "body"=>$row['body']
                    );
                }

            }
            return $values;
            }
        }
        $database=new Database('localhost','root','','test');
        $database->getData();
        $values=$database->getContent();

     ?>

      <?php

        for($i=0;$i<count($values);$i++){
        echo $values["title"]."
";
        echo $values["body"]."
";
      }
       ?>

Body:
You should add each row to $values instead of replacing it each time.

Where you have:

$values=array(
      "title"=>$row['title'],
      "body"=>$row['body']
);

Change it to:

$values[] = array(
      "title"=>$row['title'],
      "body"=>$row['body']
);

And then where you have the display:

for($i=0;$i<count($values);$i++){
    echo $values["title"]."<br>";
    echo $values["body"]."<br>";
}

Change to:

foreach($values as $value){
    echo $value["title"]."<br>";
    echo $value["body"]."<br>";
}

Or using a FOR:

for($i=0;$i<count($values);$i++){
    echo $values[$i]["title"]."<br>";
    echo $values[$i]["body"]."<br>";
}


问:
Deploying CodeIgniter 1.7.2 application on IIS 7
I developed a Codeigniter 1.7.2 on wamp and it's almost completed. Now I am trying to host it on IIS 7 (because the control panel that is offered to me only has IIS in it) I am getting errors. This is what i get:

```<code>Warning: require(system/codeigniter/Common.php) [function.require]: failed to open stream: No such file or directory in c:\abc\wwwroot\system\codeigniter\CodeIgniter.php on line 38

Warning: require(system/codeigniter/Common.php) [function.require]: failed to open stream: No such file or directory in c:\abc\wwwroot\system\codeigniter\CodeIgniter.php on line 38

Fatal error: require() [function.require]: Failed opening required 'system/codeigniter/Common.php' (include_path='C:\Program Files (x86)\PHP\pear;./;./includes;./pear') in c:\abc\wwwroot\system\codeigniter\CodeIgniter.php on line 38
</code>```

I am totally confused what error it is giving and what should I do to solve it.

I already searched the web and found it has some htaccess problem. This is my htaccess file:

```<code>Options +FollowSymLinks
IndexIgnore */*

<ifmodule mod_rewrite.c>
RewriteEngine on

    # if a directory or a file exists, use it directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # otherwise forward it to index.php
    RewriteRule ^(.*)$ index.php/$1 [L]

</ifmodule>
</code>```

I don't know how to convert it and what to write in web.config. I am using websitepanel for deploying website.

答:
Maybe this is it? You should find the below code in your index.php of your webroot. The question would be, have you specified a full server path? Make sure you are using the full server path, not just from the webroot, or from your domain folder in the *$system_folder* and *$application_folder* variables in your index.php file. I hope this helps/</p>

```<code>/*
|---------------------------------------------------------------
| SET THE SERVER PATH
|---------------------------------------------------------------
|
| Let's attempt to determine the full-server path to the "system"
| folder in order to reduce the possibility of path problems.
| Note: We only attempt this if the user hasn't specified a
| full server path.
|
*/
if (strpos($system_folder, '/') === FALSE)
{
    if (function_exists('realpath') AND @realpath(dirname(__FILE__)) !== FALSE)
    {
        $system_folder = realpath(dirname(__FILE__)).'/'.$system_folder;
    }
}
else
{
    // Swap directory separators to Unix style for consistency
    $system_folder = str_replace("\\", "/", $system_folder);
}
</code>```

Body:
I developed a Codeigniter 1.7.2 on wamp and it's almost completed. Now I am trying to host it on IIS 7 (because the control panel that is offered to me only has IIS in it) I am getting errors. This is what i get:

Warning: require(system/codeigniter/Common.php) [function.require]: failed to open stream: No such file or directory in c:\abc\wwwroot\system\codeigniter\CodeIgniter.php on line 38

Warning: require(system/codeigniter/Common.php) [function.require]: failed to open stream: No such file or directory in c:\abc\wwwroot\system\codeigniter\CodeIgniter.php on line 38

Fatal error: require() [function.require]: Failed opening required 'system/codeigniter/Common.php' (include_path='C:\Program Files (x86)\PHP\pear;./;./includes;./pear') in c:\abc\wwwroot\system\codeigniter\CodeIgniter.php on line 38

I am totally confused what error it is giving and what should I do to solve it.

I already searched the web and found it has some htaccess problem. This is my htaccess file:

Options +FollowSymLinks
IndexIgnore */*

<ifmodule mod_rewrite.c>
RewriteEngine on

    # if a directory or a file exists, use it directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # otherwise forward it to index.php
    RewriteRule ^(.*)$ index.php/$1 [L]

</ifmodule>

I don't know how to convert it and what to write in web.config. I am using websitepanel for deploying website.

Body:
Maybe this is it? You should find the below code in your index.php of your webroot. The question would be, have you specified a full server path? Make sure you are using the full server path, not just from the webroot, or from your domain folder in the *$system_folder* and *$application_folder* variables in your index.php file. I hope this helps/

/*
|---------------------------------------------------------------
| SET THE SERVER PATH
|---------------------------------------------------------------
|
| Let's attempt to determine the full-server path to the "system"
| folder in order to reduce the possibility of path problems.
| Note: We only attempt this if the user hasn't specified a
| full server path.
|
*/
if (strpos($system_folder, '/') === FALSE)
{
    if (function_exists('realpath') AND @realpath(dirname(__FILE__)) !== FALSE)
    {
        $system_folder = realpath(dirname(__FILE__)).'/'.$system_folder;
    }
}
else
{
    // Swap directory separators to Unix style for consistency
    $system_folder = str_replace("\\", "/", $system_folder);
}

ContentLicense: CC BY-SA 2.5


问:
Interpreting the amax parameter in scipy's line_search
In SciPy 1.0.0, according to its documentation, scipy.optimize.line_search has an optional parameter amax which determines the "Maximum step size".

As such, I would expect that the first return value, alpha, would always be less than the given amax, but this is not the case, as the following example illustrates:

```<code>from scipy.optimize import line_search

def f(x):
    return x[0]**2 + x[1]**2

def df(x):
    return 2*x

x = np.array([4, 5])
line_search(f, df, x, -df(x), amax=0.001)
# Returns (0.5, 3, 1, 0.0, 41.0, array([ 0.,  0.]))
</code>```

In this, the value of alpha is 0.5 but the value of amax is 0.001, which is less than 0.5.

Another interpretation might be that amax limits the distance between the output values x_new and x0, but this is also not the case.

Am I misinterpreting the documentation, or is this a bug in SciPy? And, if it is working as intended, what is the correct interpretation of amax, and is there some other way to limit the range of alphas in which to perform the line search?

答:
As sascha said, the current implementation of line_search (SciPy 1.0.0) does not handle amax correctly. Specifically, the function scalar_search_wolfe2 breaks out of the loop for i in xrange(maxiter) if a suitable alpha is found, while the check for amax appears later in the loop and is not reached.

Workarounds:

Use the older routine line_search_wolfe1, which is a wrapper for MINPACK's line search. It enforces not only amax but also amin, minimal step size.

```<code>from scipy.optimize.linesearch import line_search_wolfe1
line_search_wolfe1(f, df, x, -df(x), amax=0.001)
</code>```

This returns (None, 1, 0, 41.0, 41.0, array([ 8, 10])) where None means that no suitable step was found. This is the correct answer: no step size of size at most 0.001 satisfies the Wolfe conditions.

Pass the requirement on the step as extra_condition argument to the line_search routine.

```<code>line_search(f, df, x, -df(x), extra_condition=lambda a, x, f, g: a <= 0.001)
</code>```

This returns (None, 13, 1, None, 41.0, None) which again is correct: there is no suitable step size.

Perhaps you don't really mean to impose Wolfe's condition? Getting None as a (correct) answer isn't very helpful, after all. If so, use Armijo backtracking. The parameters are different: it does not ask for df function, but it does ask for the gradient and value at the initial point of the search. The parameter alpha0 is the initial and maximal step size, the algorithm will only reduce it if necessary.

```<code>from scipy.optimize.linesearch import line_search_armijo
line_search_armijo(f, x, -df(x), df(x), f(x), alpha0=0.001)
</code>```

returns (0.001, 1, 40.836164000000004)  meaning the step size is 0.001, there was 1 function evaluation, and the function value after the step is 40.8... which is of course smaller than 41 it was initially.

I don't see the documentation of line_search_armijo on the SciPy website, but we can read its docstring on Github.

Body:
In SciPy 1.0.0, according to its documentation, scipy.optimize.line_search has an optional parameter amax which determines the "Maximum step size".

As such, I would expect that the first return value, alpha, would always be less than the given amax, but this is not the case, as the following example illustrates:

from scipy.optimize import line_search

def f(x):
    return x[0]**2 + x[1]**2

def df(x):
    return 2*x

x = np.array([4, 5])
line_search(f, df, x, -df(x), amax=0.001)
# Returns (0.5, 3, 1, 0.0, 41.0, array([ 0.,  0.]))

In this, the value of alpha is 0.5 but the value of amax is 0.001, which is less than 0.5.

Another interpretation might be that amax limits the distance between the output values x_new and x0, but this is also not the case.

Am I misinterpreting the documentation, or is this a bug in SciPy? And, if it is working as intended, what is the correct interpretation of amax, and is there some other way to limit the range of alphas in which to perform the line search?

Body:
As sascha said, the current implementation of line_search (SciPy 1.0.0) does not handle amax correctly. Specifically, the function scalar_search_wolfe2 breaks out of the loop for i in xrange(maxiter) if a suitable alpha is found, while the check for amax appears later in the loop and is not reached.

Workarounds:

Use the older routine line_search_wolfe1, which is a wrapper for MINPACK's line search. It enforces not only amax but also amin, minimal step size.

from scipy.optimize.linesearch import line_search_wolfe1
line_search_wolfe1(f, df, x, -df(x), amax=0.001)

This returns (None, 1, 0, 41.0, 41.0, array([ 8, 10])) where None means that no suitable step was found. This is the correct answer: no step size of size at most 0.001 satisfies the Wolfe conditions.

Pass the requirement on the step as extra_condition argument to the line_search routine.

line_search(f, df, x, -df(x), extra_condition=lambda a, x, f, g: a <= 0.001)

This returns (None, 13, 1, None, 41.0, None) which again is correct: there is no suitable step size.

Perhaps you don't really mean to impose Wolfe's condition? Getting None as a (correct) answer isn't very helpful, after all. If so, use Armijo backtracking. The parameters are different: it does not ask for df function, but it does ask for the gradient and value at the initial point of the search. The parameter alpha0 is the initial and maximal step size, the algorithm will only reduce it if necessary.

from scipy.optimize.linesearch import line_search_armijo
line_search_armijo(f, x, -df(x), df(x), f(x), alpha0=0.001)

returns (0.001, 1, 40.836164000000004)  meaning the step size is 0.001, there was 1 function evaluation, and the function value after the step is 40.8... which is of course smaller than 41 it was initially.

I don't see the documentation of line_search_armijo on the SciPy website, but we can read its docstring on Github.


问:
Specify stops in gradient opacity (mask-image)
From this question, I was able to get the code below to work.

However, it's not exactly like I want.  I want it to fade out sooner.  After some research, it looks like gradient (and webkit-gradient) have been replaced with linear-gradient.  I tried to use that, but it doesn't seem to work with mask-image.

So, how can I make an image fade out with specific stops?  For example 0 opacity at 0%, .25 opacity at 75%, .5 opacity at 100%. (In other words, you wouldn't see the red and blue stripes until 75% of the way down the image)

img {
  position: absolute;
  z-index: 5;
  top: 0; left: 0;
  -webkit-mask-image:
    -webkit-gradient(
      linear,
      left top,
      left bottom,
      from(
        rgba(0,0,0,1)
      ), to(
        rgba(0,0,0,0)
      )
    )

}

#bg1 {
  position: absolute;
  left: 0; width: 50px;
  height: 360px;
  background-color: red;
}
#bg2 {
  position: absolute;
  left: 50px; width: 50px;
  height: 360px;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://www.gstatic.com/webp/gallery/1.jpg">
<div id="bg1"></div>
<div id="bg2"></div></code>```

答:
linear-gradient() will do

img {
  position: absolute;
  z-index: 5;
  top: 0; left: 0;
  -webkit-mask-image: linear-gradient(rgba(0, 0, 0, 1) 25%, rgba(0, 0, 0, 0.5) 75%, transparent);
  mask-image: linear-gradient(rgba(0, 0, 0, 1) 25%, rgba(0, 0, 0, 0.5) 75%, transparent);
}

#bg1 {
  position: absolute;
  left: 0; width: 50px;
  height: 360px;
  background-color: red;
}
#bg2 {
  position: absolute;
  left: 50px; width: 50px;
  height: 360px;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://www.gstatic.com/webp/gallery/1.jpg">
<div id="bg1"></div>
<div id="bg2"></div></code>```

Body:
linear-gradient() will do

img {
  position: absolute;
  z-index: 5;
  top: 0; left: 0;
  -webkit-mask-image: linear-gradient(rgba(0, 0, 0, 1) 25%, rgba(0, 0, 0, 0.5) 75%, transparent);
  mask-image: linear-gradient(rgba(0, 0, 0, 1) 25%, rgba(0, 0, 0, 0.5) 75%, transparent);
}

#bg1 {
  position: absolute;
  left: 0; width: 50px;
  height: 360px;
  background-color: red;
}
#bg2 {
  position: absolute;
  left: 50px; width: 50px;
  height: 360px;
  background-color: blue;
}

<img src="http://www.gstatic.com/webp/gallery/1.jpg">
<div id="bg1"></div>
<div id="bg2"></div>


问:
How can you trace execution of an embedded system emulted in QEMU?
I've built  OpenWrt for x86 and I'm using QEMU to run it virtually.I'm trying to debug this system in real time.  I need to see things like network traffic flowing etc.

I can attach gdb remotely and execute (mostly) step by step with break points. I really want trace points though. I don't want to pause execution and loose network flow. When I tried setting trace points using tstart, I see the message "Target does not support this command". I did a bit of reading of the gdb documentation and from what I can tell the gdb stub that runs to intercept normal execution in QEMU does not support trace points.

From here I started looking at other tools and ran across PANDA (https://github.com/panda-re/panda). As I understand PANDA will capture a complete system trace in a log and allow for replay. I think this tool is supposed to do what I need, but I cannot seem to replay the results. I see the logs, I just can't replay them.

Now, I'm a bit stuck on what other tools/options I might have to actually trace a running embedded system. Are there any good tools you can recommend? Or perhaps another method I've missed?

答:
If you want to see the system calls and signals use strace.
Strace can also be used with running process and it can put the output in a log file if required.</p>


问:
How can I force my jenkinsfile parallel steps to use different agents?
I have a Jenkinsfile. It has parallel stages. Those stages need to run on agents with a label pool_of_builder_nodes.

The problem is, it always runs both run on the SAME agent with different executors! (technically both apply to the label). Short of explicitly picking agents by name, how can I force it to use different agents for parallel stages?

The thing I'm doing doesn't work well with multiple instances on the same host (but the agents CAN do other things at the same time, so I don't necessarily want to restrict them to a single executor).

```<code>pipeline {
    agent none // each stage has its own agent defined

    stages {
        stage('Parallel steps') {
            parallel {
                stage('Build Release') {
                    agent {
                        label 'pool_of_builder_nodes'
                    }
                    steps {
                        // do the thing!
                    }
                }
                stage('Build Debug') {
                    agent {
                        label 'pool_of_builder_nodes'
                    }
                    steps {
                        // also do the thing!
                    }
                }
            }
        }
    }
}
</code>```

答:
The only way I could find to do this was sub-optimal, but worked.

Re-factor each Stage into its own independent job. Have each stage invoke that job with the build step.

Install the Throttle Concurrent Builds plugin.

Configure each job to use the same 'Throttle Category' and then set "Maximum Concurrent Builds Per Node" to 1.

The end result is that each stage is actually an independent job, and the plugin won't let more than one instance run on the same node.

Body:
I have a Jenkinsfile. It has parallel stages. Those stages need to run on agents with a label pool_of_builder_nodes.

The problem is, it always runs both run on the SAME agent with different executors! (technically both apply to the label). Short of explicitly picking agents by name, how can I force it to use different agents for parallel stages?

The thing I'm doing doesn't work well with multiple instances on the same host (but the agents CAN do other things at the same time, so I don't necessarily want to restrict them to a single executor).

pipeline {
    agent none // each stage has its own agent defined

    stages {
        stage('Parallel steps') {
            parallel {
                stage('Build Release') {
                    agent {
                        label 'pool_of_builder_nodes'
                    }
                    steps {
                        // do the thing!
                    }
                }
                stage('Build Debug') {
                    agent {
                        label 'pool_of_builder_nodes'
                    }
                    steps {
                        // also do the thing!
                    }
                }
            }
        }
    }
}


问:
Conversion failed error when joining on a table with a created field
I have a table (DateDimension) with a field (MonthYear) that is a varchar.  The values look like this:

12 2017
11 2017
10 2017
9 2017

I have another table (SupplierData) with a field (GR Date) that is a varchar that I am using to create a field (ReportingPeriod) to use as a join to the DateDimension table.

Here is the code for ReportingPeriod:

```<code>ReportingPeriod = Cast(DatePart(Month, [GR Date]) As varchar(2)) + ' ' + Cast(DatePart(Year, [GR Date]) As Varchar(4))
</code>```

When I try to create my join like this:

```<code>INNER JOIN dbo.DateDimension dd ON dd.MonthYear = a.ReportingPeriod
</code>```

I receive this error:

Conversion failed when converting date and/or time from character string.

How can I resolve this?

答:
Sounds like your error is caused by a bad value for GR Date. The best solution is to make sure you're using correct datatypes, but you could also use try_cast() instead as it will return null instead of throwing an error when the value can't be converted.

```<code>ReportingPeriod = Cast(DatePart(Month, try_cast([GR Date] as date)) As varchar(2))
  + ' '
  + Cast(DatePart(Year, try_cast([GR Date] as date)) As Varchar(4))
</code>```

In Sql Server 2012 and up: each of these will return null when the conversion fails instead of an error.

try_convert(datatype,val)

try_cast(val as datatype)

try_parse(val as datatype [using culture])

Body:
I have a table (DateDimension) with a field (MonthYear) that is a varchar.  The values look like this:

12 2017
11 2017
10 2017
9 2017

I have another table (SupplierData) with a field (GR Date) that is a varchar that I am using to create a field (ReportingPeriod) to use as a join to the DateDimension table.

Here is the code for ReportingPeriod:

ReportingPeriod = Cast(DatePart(Month, [GR Date]) As varchar(2)) + ' ' + Cast(DatePart(Year, [GR Date]) As Varchar(4))

When I try to create my join like this:

INNER JOIN dbo.DateDimension dd ON dd.MonthYear = a.ReportingPeriod

I receive this error:

Conversion failed when converting date and/or time from character string.

How can I resolve this?

Body:
Sounds like your error is caused by a bad value for GR Date. The best solution is to make sure you're using correct datatypes, but you could also use try_cast() instead as it will return null instead of throwing an error when the value can't be converted.

ReportingPeriod = Cast(DatePart(Month, try_cast([GR Date] as date)) As varchar(2))
  + ' '
  + Cast(DatePart(Year, try_cast([GR Date] as date)) As Varchar(4))

In Sql Server 2012 and up: each of these will return null when the conversion fails instead of an error.

try_convert(datatype,val)

try_cast(val as datatype)

try_parse(val as datatype [using culture])


问:
LetsEncrypt certbot multiple renew-hooks
I'm automating an SSL certificate renewal from LetsEncrypt's certbot. The actual renewal is working, but I need to automate restarting services so that they load the renewed certificates. I was wondering if you can use multiple --renew-hook parameters within the cronjob for letsencrypt renew?

How to automate restarting services upon certificate renewal?

答:
You can also set hooks (and others options if you like) as global options in the file /etc/letsencrypt/cli.ini (see documentation) like this:

```<code># Global config for letsencrypt runs
#
# Note that these options apply automatically to all use of Certbot for
# obtaining or renewing certificates, so options specific to a single
# certificate on a system with several certificates should not be placed
# here.

renew-hook = service postfix reload
post-hook = service nginx reload
</code>```

You must create the file first on most systems. Letsencrypt comes without.

You can also create certificate specific version in every renewal folder if you don't like to go global.

Body:
You can also set hooks (and others options if you like) as global options in the file /etc/letsencrypt/cli.ini (see documentation) like this:

# Global config for letsencrypt runs
#
# Note that these options apply automatically to all use of Certbot for
# obtaining or renewing certificates, so options specific to a single
# certificate on a system with several certificates should not be placed
# here.

renew-hook = service postfix reload
post-hook = service nginx reload

You must create the file first on most systems. Letsencrypt comes without.

You can also create certificate specific version in every renewal folder if you don't like to go global.


问:
Keeping Texture2D object(s) for interpolation HLSL
Recently someone added a module to OBS Studio which lets anyone incorporate their own shaders into OBS. I've never touched on writing shaders, but after reading some material, I get the gist, it's a function that returns a bit of memory representing the RGBA values of a specific pixel.

Here's the issue, I'm too new to this, it looks to me like there's a few different high level shader languages? I have no clue which one OBS Studio is using, the author of https://github.com/nleseul/obs-shaderfilter doesn't seem to know either. Any pointers to what syntax / what documentation would be of course greatly appreciated.

What I'm aiming to do is a very dumbed down motion blur. Namely though my goal is that I'd like to keep a few frames in a buffer of some sort to work with, I figure that'd be a pretty useful thing to do for other effects...and that's where I'm stuck. Here's what I've got following from Shaders for Game Programmers and Artists pg.87 adapted to work w/ the shader plugin*

```<code>uniform float4 blur_factor;
texture2d previmage;
//texture2d image; //this is the input data we're playing around with

float4 mainImage(VertData v_in) : TARGET
{
    float4 originalFrame = image.Sample(textureSampler, v_in.uv);
    float4 oldFrame = previmage.Sample(textureSampler, v_in.uv);

    //this function's going pixel by pixel, I should be pushing
    //to the frame buffer here* or there should be some way of modifying
    //the frame buffer pixel by pixel, second option makes more sense to do
    if(v_in.uv.x == 1 && v_in.uv.y == 1){
        //it couldn't have been this easy...it's never this easy
        //uncommenting the line below clearly causes a problem, I don't have a debugger for this
        //previmage = image;
        //this doesn't work either, wishful thinking
        //previmage = texture2d(image);
    }
    //this may not actually be the function to use for a motion blur but at the very least it's mixing two textures together so that I'd have a proof of concept working*
    return lerp(originalFrame,oldFrame,blur_factor);
}
</code>```

答:
So, fortunately it turns out that when a shader fails the error is actually output to OBS's logs. I had a gut feeling that something was up w/ declaring variables globally. For the initial code I wrote I got this:

```<code>10:53:49.413: C:\Program Files (x86)\obs-studio\bin\64bit\ (Pixel shader, technique Draw, pass 0)(38,40-50): error X3004: undeclared identifier 'blur_factor'
10:53:49.413: C:\Program Files (x86)\obs-studio\bin\64bit\ (Pixel shader, technique Draw, pass 0)(38,12-51): error X3013: 'lerp': no matching 3 parameter intrinsic function
10:53:49.413: C:\Program Files (x86)\obs-studio\bin\64bit\ (Pixel shader, technique Draw, pass 0)(38,12-51): error X3013: Possible intrinsic functions are:
10:53:49.413: C:\Program Files (x86)\obs-studio\bin\64bit\ (Pixel shader, technique Draw, pass 0)(38,12-51): error X3013:     lerp(float|half|min10float|min16float, float|half|min10float|min16float, float|half|min10float|min16float)
</code>```

So in short...lerp was in fact NOT what I was looking to use, didn't properly call it with the right data types to begin with. So after tossing that I decided to write the shader assuming I could make an array of texture2d's ...

```<code>texture2d previmage[8];

float4 mainImage(VertData v_in) : TARGET{
   //...etc etc
   //manipulating the array, copying over the texture2d OBS provides
}
</code>```

Then I get this:

```<code>11:12:46.880: C:\Program Files (x86)\obs-studio\bin\64bit\ (Pixel shader, technique Draw, pass 0)(27,3-31): error X3025: global variables are implicitly constant, enable compatibility mode to allow modification
</code>```

Oh...so...global variables in HLSL have a weird behavior that I wouldn't know about, and it makes this approach a bit mute...can't modify constant values, and I need some sort of frame buffer.

Potential solution? Static Variables!

```<code>float4 mainImage(VertData v_in) : TARGET
{
    int i = 0;
    static texture2d previmage[8] = {image,image,image,image,image,image,image,image};

    if(v_in.uv.x == 1 && v_in.uv.y == 1){
        for(i = 0; i <= 6; i++){
            previmage[i+1] = previmage[i];
        }
        previmage[0] = image;
    }

    float4 sum = 0;
    float4 samples[8];

    for(i = 0; i < 8; i++){
        samples[i] = previmage[i].Sample(textureSampler, v_in.uv);
        sum += samples[i];
    }

    return sum / 8.0;
}
</code>```

Now...well at least the thing isn't throwing errors and it's rendering to the screen, unfortunately...I don't / can't see the effect...there's potentially a semantic error in here* or...maybe 8 frames isn't enough to really make for a noticeable motion blur.

Body:
Recently someone added a module to OBS Studio which lets anyone incorporate their own shaders into OBS. I've never touched on writing shaders, but after reading some material, I get the gist, it's a function that returns a bit of memory representing the RGBA values of a specific pixel.

Here's the issue, I'm too new to this, it looks to me like there's a few different high level shader languages? I have no clue which one OBS Studio is using, the author of https://github.com/nleseul/obs-shaderfilter doesn't seem to know either. Any pointers to what syntax / what documentation would be of course greatly appreciated.

What I'm aiming to do is a very dumbed down motion blur. Namely though my goal is that I'd like to keep a few frames in a buffer of some sort to work with, I figure that'd be a pretty useful thing to do for other effects...and that's where I'm stuck. Here's what I've got following from Shaders for Game Programmers and Artists pg.87 adapted to work w/ the shader plugin*

uniform float4 blur_factor;
texture2d previmage;
//texture2d image; //this is the input data we're playing around with

float4 mainImage(VertData v_in) : TARGET
{
    float4 originalFrame = image.Sample(textureSampler, v_in.uv);
    float4 oldFrame = previmage.Sample(textureSampler, v_in.uv);

    //this function's going pixel by pixel, I should be pushing
    //to the frame buffer here* or there should be some way of modifying
    //the frame buffer pixel by pixel, second option makes more sense to do
    if(v_in.uv.x == 1 && v_in.uv.y == 1){
        //it couldn't have been this easy...it's never this easy
        //uncommenting the line below clearly causes a problem, I don't have a debugger for this
        //previmage = image;
        //this doesn't work either, wishful thinking
        //previmage = texture2d(image);
    }
    //this may not actually be the function to use for a motion blur but at the very least it's mixing two textures together so that I'd have a proof of concept working*
    return lerp(originalFrame,oldFrame,blur_factor);
}

Body:
So, fortunately it turns out that when a shader fails the error is actually output to OBS's logs. I had a gut feeling that something was up w/ declaring variables globally. For the initial code I wrote I got this:

10:53:49.413: C:\Program Files (x86)\obs-studio\bin\64bit\ (Pixel shader, technique Draw, pass 0)(38,40-50): error X3004: undeclared identifier 'blur_factor'
10:53:49.413: C:\Program Files (x86)\obs-studio\bin\64bit\ (Pixel shader, technique Draw, pass 0)(38,12-51): error X3013: 'lerp': no matching 3 parameter intrinsic function
10:53:49.413: C:\Program Files (x86)\obs-studio\bin\64bit\ (Pixel shader, technique Draw, pass 0)(38,12-51): error X3013: Possible intrinsic functions are:
10:53:49.413: C:\Program Files (x86)\obs-studio\bin\64bit\ (Pixel shader, technique Draw, pass 0)(38,12-51): error X3013:     lerp(float|half|min10float|min16float, float|half|min10float|min16float, float|half|min10float|min16float)

So in short...lerp was in fact NOT what I was looking to use, didn't properly call it with the right data types to begin with. So after tossing that I decided to write the shader assuming I could make an array of texture2d's ...

texture2d previmage[8];

float4 mainImage(VertData v_in) : TARGET{
   //...etc etc
   //manipulating the array, copying over the texture2d OBS provides
}

Then I get this:

11:12:46.880: C:\Program Files (x86)\obs-studio\bin\64bit\ (Pixel shader, technique Draw, pass 0)(27,3-31): error X3025: global variables are implicitly constant, enable compatibility mode to allow modification

Oh...so...global variables in HLSL have a weird behavior that I wouldn't know about, and it makes this approach a bit mute...can't modify constant values, and I need some sort of frame buffer.

Potential solution? Static Variables!

float4 mainImage(VertData v_in) : TARGET
{
    int i = 0;
    static texture2d previmage[8] = {image,image,image,image,image,image,image,image};

    if(v_in.uv.x == 1 && v_in.uv.y == 1){
        for(i = 0; i <= 6; i++){
            previmage[i+1] = previmage[i];
        }
        previmage[0] = image;
    }

    float4 sum = 0;
    float4 samples[8];

    for(i = 0; i < 8; i++){
        samples[i] = previmage[i].Sample(textureSampler, v_in.uv);
        sum += samples[i];
    }

    return sum / 8.0;
}

Now...well at least the thing isn't throwing errors and it's rendering to the screen, unfortunately...I don't / can't see the effect...there's potentially a semantic error in here* or...maybe 8 frames isn't enough to really make for a noticeable motion blur.


问:
POST doesn't write to database
I have my requestaccess view below, which will write to my database if I remove the if request.method == 'POST', but if i keep it in.  The request is never written. I'm trying to understand why the POST isn't occurring and how to make it happen?

```<code>def requestaccess(request):

    owner = User.objects.get (formattedusername=request.user.formattedusername)

    reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc')
    reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True)
    checkedlist = request.GET.getlist('report_id')
    reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)

    coid = User.objects.filter(coid = request.user.coid).filter(formattedusername=request.user.formattedusername)
    facilitycfo =  QvDatareducecfo.objects.filter(dr_code__exact = coid , active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
    divisioncfo =  QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
    selectedaccesslevel = '7'
    if request.method == 'POST':
        selectedaccesslevel = request.POST.get('accesslevelid')
        print(selectedaccesslevel)
    selectedphi = '0'
    if request.method == 'POST':
        selectedphi = request.POST.get('phi')
        print(selectedphi)
    if request.method == 'POST':
        for i in checkedlist:
            requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
                                      ,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi, access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00')
            requestsave.save()

    args = {'retreivecheckbox': reportlist, 'cfo7':facilitycfo, 'cfo5':divisioncfo, 'checkedlist':checkedlist }

    return render(request,'accounts/requestaccess.html', args)
#    return render(request, 'accounts/requestaccess.html', args)
</code>```

My request.method == 'POST' statements never return the correct value only the hard coded one for a test.

My template requestaccess.html can be found below.  I can see the POST request for the ajax function being updated as i change the select options and when I click on the button.

```<code>{% extends 'base.html' %}

  {% block head %}
  <title> Access Request Form </title>
  {% endblock %}

  {% block body %}

    <div class="container">
      <div class="row">
        <div class="col">
          <h2>{{ user.username }}</h2></br>
          <ul>
            <li>Employee First Name: {{ user.first_name }}</li>
            <li>Employee Last Name: {{ user.last_name }}</li>
            <li>Coid: {{ user.coid }}</li>
            <li>Facility: {{ user.facility }}</li>
            <li>Title: {{user.title}}</li>

          </ul>
        </div>
        <div class="col">

  <form action = "{% url 'requestaccess' %}" form method = "POST">
    {% csrf_token %}
          <h2>Applications:</h3></br>

            {% for app in retreivecheckbox %}
            <li><input type="checkbox" name="report_id" value ="{{app.report_id}}" checked> {{ app }}
              </li>
            {% endfor %}
        </div>

      </div>

      <div class="row">
        <div class="col">
          <label for="accesslevel"><h3>Access Level</h3></label>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
            <option value=""> Please select your access level  </option>
            <option value="7"> Facility  </option>
            <option value="5"> Division  </option>
            <option value = "3"> Corporate  </option>
            <option value = "6"> Market  </option>
            <option value = "4"> Group  </option>
</select>

        </div>
        <div class="col">

          <label for="phi"><h3>PHI</h3></label>

          <select class="form-control my_select" id="phi" title = "phi" >
            <option value = ""> Please select if you need access to PHI data </option>
            <option value = "0"> No  </option>
            <option value = "1"> Yes  </option>

          </select>

        </div>
      </div>

        <div class="row">
  <div class="container">
    <div class="row">
      <div class="col">
 </br> </br>

  <button href="{% url 'submitted' %}" class="btn btn-primary my_select" type = "submit"> Submit </button>
              <script>
          $(document).ready(function () {
              $('.my_select').on('change', function () {
                  var phi = $('#phi').val();
                  var accesslevelid = $('#accesslevelid ').val();
                  $.ajax({ url: "{% url 'requestaccess' %}",
                          headers: { 'X-CSRFToken': '{{ csrf_token }}' },
                          data: {
                            phi: phi,
                            accesslevelid: accesslevelid,
                          },
                          type: 'POST',
                          success: function (result) {
                            ;
                          },
                        });
                });
            });
          </script>
</div>

  </form>

  {% endblock %}
</code>```

Below is the console which shows the POST:

```<code>[07/Dec/2017 13:21:14] "GET /account/requestaccess/?report_id=84&report_id=87&report_id=88 HTTP/1.
3

[07/Dec/2017 13:21:22] "POST /account/requestaccess/ HTTP/1.1" 200 3928
3
1
</code>```

After I click the submit button it gives me the following:

[07/Dec/2017 13:33:59] "POST /account/requestaccess/ HTTP/1.1" 200 3776
None
None

Edit:

Changing the javascript to on('click' instead of on('change' produces the same value of None.

答:
checkedlist = request.GET.getlist('report_id') is the culprit. You're populating that from the GET request, and when you POST, those aren't carried over in any way.

As a result, checkedlist is None and the save statement never fires.

Title: POST doesn't write to database

Body:
I have my requestaccess view below, which will write to my database if I remove the if request.method == 'POST', but if i keep it in.  The request is never written. I'm trying to understand why the POST isn't occurring and how to make it happen?

def requestaccess(request):

    owner = User.objects.get (formattedusername=request.user.formattedusername)

    reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername, active = 1).values('report_name_sc')
    reportIds = QVReportAccess.objects.filter(ntname = owner.formattedusername).values_list('report_id', flat=True)
    checkedlist = request.GET.getlist('report_id')
    reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True)

    coid = User.objects.filter(coid = request.user.coid).filter(formattedusername=request.user.formattedusername)
    facilitycfo =  QvDatareducecfo.objects.filter(dr_code__exact = coid , active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
    divisioncfo =  QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
    selectedaccesslevel = '7'
    if request.method == 'POST':
        selectedaccesslevel = request.POST.get('accesslevelid')
        print(selectedaccesslevel)
    selectedphi = '0'
    if request.method == 'POST':
        selectedphi = request.POST.get('phi')
        print(selectedphi)
    if request.method == 'POST':
        for i in checkedlist:
            requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
                                      ,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi, access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00')
            requestsave.save()

    args = {'retreivecheckbox': reportlist, 'cfo7':facilitycfo, 'cfo5':divisioncfo, 'checkedlist':checkedlist }

    return render(request,'accounts/requestaccess.html', args)
#    return render(request, 'accounts/requestaccess.html', args)

My request.method == 'POST' statements never return the correct value only the hard coded one for a test.

My template requestaccess.html can be found below.  I can see the POST request for the ajax function being updated as i change the select options and when I click on the button.

{% extends 'base.html' %}

  {% block head %}
  <title> Access Request Form </title>
  {% endblock %}

  {% block body %}

{{ user.username }}

Employee First Name: {{ user.first_name }}

Employee Last Name: {{ user.last_name }}

Coid: {{ user.coid }}

Facility: {{ user.facility }}

Title: {{user.title}}

  <form action = "{% url 'requestaccess' %}" form method = "POST">
    {% csrf_token %}

Applications:

            {% for app in retreivecheckbox %}

<input type="checkbox" name="report_id" value ="{{app.report_id}}" checked> {{ app }}

            {% endfor %}

Access Level

<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
            <option value=""> Please select your access level  </option>
            <option value="7"> Facility  </option>
            <option value="5"> Division  </option>
            <option value = "3"> Corporate  </option>
            <option value = "6"> Market  </option>
            <option value = "4"> Group  </option>
</select>

PHI

          <select class="form-control my_select" id="phi" title = "phi" >
            <option value = ""> Please select if you need access to PHI data </option>
            <option value = "0"> No  </option>
            <option value = "1"> Yes  </option>

          </select>

  <button href="{% url 'submitted' %}" class="btn btn-primary my_select" type = "submit"> Submit </button>

  </form>

  {% endblock %}

Below is the console which shows the POST:

[07/Dec/2017 13:21:14] "GET /account/requestaccess/?report_id=84&report_id=87&report_id=88 HTTP/1.
3

[07/Dec/2017 13:21:22] "POST /account/requestaccess/ HTTP/1.1" 200 3928
3
1

After I click the submit button it gives me the following:

[07/Dec/2017 13:33:59] "POST /account/requestaccess/ HTTP/1.1" 200 3776
None
None

Edit:

Changing the javascript to on('click' instead of on('change' produces the same value of None.


问:
Multiple File Exists Checking? A Better way?
I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.

Right now I am doing this script as follows:

```<code>if (file_exists($img = $node.".png")) {  }
else if (file_exists($img = $node.".jpg")) {  }
else if (file_exists($img = $node.".gif")) {  }
else
{
    $img = 'RANDOM.png';
}
</code>```

There has to be a better way than this... anyone have any ideas?

答:
```<code>$list = array_filter(array("$node.png", "$node.jpg", "$node.gif"), 'file_exists');
if (!$img = array_shift($list)) {
    $img = 'RANDOM.png';
}
</code>```

Alternatives :

```<code>$list = scandir(".");
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#", $list);
</code>```

This returns a list of file names that start with $node and with a .jpg, .png or .gif suffix.

If the directory contains many entries, if may be faster to use glob() first:

```<code>$list = glob("$node.*"); // take care to escape $node here
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#");
</code>```

The preg_grep() can also be replaced by

```<code>$list = array_intersect($list, array("$node.png", "$node.jpg", "$node.gif"));
</code>```

Or with a loop:

```<code>$img = null;
foreach(array('png','jpg','gif') as $ext) {
    if (!file_exists("$node.$ext")) continue;
    $img = "$node.$ext"; break;
}
$img = $img ? $img : "RANDOM.png";
</code>```

Body:
I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.

Right now I am doing this script as follows:

if (file_exists($img = $node.".png")) {  }
else if (file_exists($img = $node.".jpg")) {  }
else if (file_exists($img = $node.".gif")) {  }
else
{
    $img = 'RANDOM.png';
}

There has to be a better way than this... anyone have any ideas?

Body:
$list = array_filter(array("$node.png", "$node.jpg", "$node.gif"), 'file_exists');
if (!$img = array_shift($list)) {
    $img = 'RANDOM.png';
}

Alternatives :

$list = scandir(".");
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#", $list);

This returns a list of file names that start with $node and with a .jpg, .png or .gif suffix.

If the directory contains many entries, if may be faster to use glob() first:

$list = glob("$node.*"); // take care to escape $node here
$list = preg_grep("#".preg_quote($node,'#')."\.(jpg|png|gif)$#");

The preg_grep() can also be replaced by

$list = array_intersect($list, array("$node.png", "$node.jpg", "$node.gif"));

Or with a loop:

$img = null;
foreach(array('png','jpg','gif') as $ext) {
    if (!file_exists("$node.$ext")) continue;
    $img = "$node.$ext"; break;
}
$img = $img ? $img : "RANDOM.png";


问:
Gradually change background of navigation as the user scrolls down
So i wanted to make this simple navigation go from background transparent to background bright green gradually. I got the idea of using the $(window).scrollTop() jQuery function to get the distance from top and divide it by 10 to get a smooth transition, but it still feels kinda snappy when i run it in chrome and firefox.

Is there another (smoother and more modern) way of doing this?

I really wanted to make the design very simple to induce the flat design art and give the website a lot of functionality to give it a modern vibe of simple but practical.

FYI:

i dont want dropdowns, expansions etc. so dont suggest them.
Also dont judge the color.
The activator link is for mobile(where i have a dropdown). so dont be bothered to mind it.

Markup:

```<code><nav>
                <a id="activator"></a>
                <ul>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">Courses</a></li>
                    <li><a href="#">Contact</a></li>
                    <li><a href="#">Log out</a></li>
                </ul>
    </nav>
</code>```

Style:

```<code><style>
nav{
    position: fixed;
    width: 100%;
    z-index: 2;
    height: 2em;
}
nav ul{
    overflow: hidden;
    background: #1adc8c;
    height: auto;
}
nav ul li{
    float: none;
    text-align: center;
    width: 100%;
    margin: 0%;
    padding: 0px;
    font-weight: bold;
    font-size: 1.1em;
}
nav ul li a{
    display: block;
    color: #FFF;
    text-decoration: none;
    font-family: sans-serif;
    font-size: 1.2em;
    padding: 20px;
}
</style>
</code>```

JQ and JS:

```<code>if(window.innerWidth > 400){
        $(window).scroll(function(){
        var fromTop = $(this).scrollTop();
        if(fromTop >= 100){
            $("nav").css({
                "background" : "rgba(26, 220, 140,0." + fromTop/10 + ")"
            });
            if(fromTop >= 600){
                $("nav").css({
                    "background" : "rgba(26,220,140,1)"
                });
            }
        }else{
            $("nav").css({
                "background" : ""
            });
        }
        });
    }
</code>```

答:
You'd probably be better off simply toggling a CSS-class (e.g. .alternative), depending on how far you've scrolled. This, in conjunction with a CSS transition would allow you to make a smooth, well, transition.

Please see the following code snippet for a working example of this.

$(window).scroll(function() {
  var fromTop = $(this).scrollTop()
  if (fromTop >= 100) {
    $('nav').addClass('alternative')
  } else {
    $('nav').removeClass('alternative')
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>nav {
  position: fixed;
  width: 100%;
  z-index: 2;
  height: 2em;
  background-color: transparent;
  transition: background-color 0.5s;
}

nav.alternative {
  background-color: #1adc8c;
}

nav ul {
  overflow: hidden;
  background: #1adc8c;
  height: auto;
}

nav ul li {
  float: none;
  text-align: center;
  width: 100%;
  margin: 0%;
  padding: 0px;
  font-weight: bold;
  font-size: 1.1em;
}

nav ul li a {
  display: block;
  color: #FFF;
  text-decoration: none;
  font-family: sans-serif;
  font-size: 1.2em;
  padding: 20px;
}

.spacer {
  min-height: 500px;
}</code>```

Home

Courses

Contact

Log out

```

Body:
So i wanted to make this simple navigation go from background transparent to background bright green gradually. I got the idea of using the $(window).scrollTop() jQuery function to get the distance from top and divide it by 10 to get a smooth transition, but it still feels kinda snappy when i run it in chrome and firefox.

Is there another (smoother and more modern) way of doing this?

I really wanted to make the design very simple to induce the flat design art and give the website a lot of functionality to give it a modern vibe of simple but practical.

FYI:

i dont want dropdowns, expansions etc. so dont suggest them.
Also dont judge the color.
The activator link is for mobile(where i have a dropdown). so dont be bothered to mind it.

Markup:

Home

Courses

Contact

Log out

Style:

JQ and JS:

if(window.innerWidth > 400){
        $(window).scroll(function(){
        var fromTop = $(this).scrollTop();
        if(fromTop >= 100){
            $("nav").css({
                "background" : "rgba(26, 220, 140,0." + fromTop/10 + ")"
            });
            if(fromTop >= 600){
                $("nav").css({
                    "background" : "rgba(26,220,140,1)"
                });
            }
        }else{
            $("nav").css({
                "background" : ""
            });
        }
        });
    }

Body:
You'd probably be better off simply toggling a CSS-class (e.g. .alternative), depending on how far you've scrolled. This, in conjunction with a CSS transition would allow you to make a smooth, well, transition.

Please see the following code snippet for a working example of this.

$(window).scroll(function() {
  var fromTop = $(this).scrollTop()
  if (fromTop >= 100) {
    $('nav').addClass('alternative')
  } else {
    $('nav').removeClass('alternative')
  }
})

nav {
  position: fixed;
  width: 100%;
  z-index: 2;
  height: 2em;
  background-color: transparent;
  transition: background-color 0.5s;
}

nav.alternative {
  background-color: #1adc8c;
}

nav ul {
  overflow: hidden;
  background: #1adc8c;
  height: auto;
}

nav ul li {
  float: none;
  text-align: center;
  width: 100%;
  margin: 0%;
  padding: 0px;
  font-weight: bold;
  font-size: 1.1em;
}

nav ul li a {
  display: block;
  color: #FFF;
  text-decoration: none;
  font-family: sans-serif;
  font-size: 1.2em;
  padding: 20px;
}

.spacer {
  min-height: 500px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <a id="activator"></a>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">Courses</a></li>
    <li><a href="#">Contact</a></li>
    <li><a href="#">Log out</a></li>
  </ul>
</nav>

<div class="spacer"></div>


问:
ShellCheck warning: "Iterating over ls output is fragile. Use globs. [SC2045]"
I am getting a ShellCheck warning [SC2045] for the second line in the code below. Is it fine to ignore it as I am making sure the directory is not empty before I try the last ls?

```<code> if [ "$(ls -A "$retryDir")" ]  ; then
    for thisRetryFile in $(ls "$retryDir"/*.tar.gz) ; do
        scp -o ConnectTimeout=30  "$thisRetryFile"  \
              "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
    done
 fi
</code>```

UPDATE:
After reading the post comments. I have changed the line to:

```<code>for thisRetryFile in "$retryDir"/*.tar.gz ; do
</code>```

This has removed the warnings.

答:
Use the loop with a glob, and also set nullglob to avoid executing scp in case the pattern doesn't match anything.
And you don't need the outer if condition either,
since the for with nullglob effectively takes care of that:

```<code>shopt -s nullglob

for thisRetryFile in "$retryDir"/*.tar.gz; do
    scp -o ConnectTimeout=30  "$thisRetryFile" \
          "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
done
</code>```

If you want to catch the case when no file matches the pattern,
you can write like this, without using shopt -s nullglob:

```<code>for thisRetryFile in "$retryDir"/*.tar.gz; do
    if [ -f "$thisRetryFile" ]; then
        scp -o ConnectTimeout=30  "$thisRetryFile" \
            "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
        break
    else
        echo "warn: no tar.gz file in dir: $retryDir"
    fi
done
</code>```

Body:
I am getting a ShellCheck warning [SC2045] for the second line in the code below. Is it fine to ignore it as I am making sure the directory is not empty before I try the last ls?

 if [ "$(ls -A "$retryDir")" ]  ; then
    for thisRetryFile in $(ls "$retryDir"/*.tar.gz) ; do
        scp -o ConnectTimeout=30  "$thisRetryFile"  \
              "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
    done
 fi

UPDATE:
After reading the post comments. I have changed the line to:

for thisRetryFile in "$retryDir"/*.tar.gz ; do

This has removed the warnings.

Body:
Use the loop with a glob, and also set nullglob to avoid executing scp in case the pattern doesn't match anything.
And you don't need the outer if condition either,
since the for with nullglob effectively takes care of that:

shopt -s nullglob

for thisRetryFile in "$retryDir"/*.tar.gz; do
    scp -o ConnectTimeout=30  "$thisRetryFile" \
          "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
done

If you want to catch the case when no file matches the pattern,
you can write like this, without using shopt -s nullglob:

for thisRetryFile in "$retryDir"/*.tar.gz; do
    if [ -f "$thisRetryFile" ]; then
        scp -o ConnectTimeout=30  "$thisRetryFile" \
            "$remoteUser@$remoteHost:$remotePath" >> "$BACKUPLOG"
        break
    else
        echo "warn: no tar.gz file in dir: $retryDir"
    fi
done


答:
Try adding the

```<code>transition: all 200ms;
will-change: background;
</code>```

properties to you nav class to make it look smooth. you can see these examples on codepen 1 , 2, 3

if (window.innerWidth > 400) {
  $(window).scroll(function() {
    var fromTop = $(this).scrollTop();
    if (fromTop >= 100) {
      $("nav").css({
        "background": "rgba(26, 220, 140,0." + fromTop / 10 + ")"
      });
      if (fromTop >= 600) {
        $("nav").css({
          "background": "rgba(26,220,140,1)"
        });
      }
    } else {
      $("nav").css({
        "background": ""
      });
    }
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.long-div {
  height: 500vh;
}

nav {
  position: fixed;
  width: 100%;
  z-index: 2;
  height: 4em;
  transition: all 500ms;
  will-change: background;
}

nav ul {
  overflow: hidden;
  width: 100%;
  height: auto;
  list-style-type: none;
}

nav ul li {
  float: left;
  text-align: center;
  margin: 0%;
  padding: 0px;
  font-weight: bold;
  font-size: 1.1em;
}

nav ul li a {
  display: block;
  color: #000;
  text-decoration: none;
  font-family: sans-serif;
  font-size: 1.2em;
  padding: 5px;
}</code>```

      Home

      Courses

      Contact

      Log out

```

Title: Gradually change background of navigation as the user scrolls down

Body:
Try adding the

transition: all 200ms;
will-change: background;

properties to you nav class to make it look smooth. you can see these examples on codepen 1 , 2, 3

if (window.innerWidth > 400) {
  $(window).scroll(function() {
    var fromTop = $(this).scrollTop();
    if (fromTop >= 100) {
      $("nav").css({
        "background": "rgba(26, 220, 140,0." + fromTop / 10 + ")"
      });
      if (fromTop >= 600) {
        $("nav").css({
          "background": "rgba(26,220,140,1)"
        });
      }
    } else {
      $("nav").css({
        "background": ""
      });
    }
  });
}

.long-div {
  height: 500vh;
}

nav {
  position: fixed;
  width: 100%;
  z-index: 2;
  height: 4em;
  transition: all 500ms;
  will-change: background;
}

nav ul {
  overflow: hidden;
  width: 100%;
  height: auto;
  list-style-type: none;
}

nav ul li {
  float: left;
  text-align: center;
  margin: 0%;
  padding: 0px;
  font-weight: bold;
  font-size: 1.1em;
}

nav ul li a {
  display: block;
  color: #000;
  text-decoration: none;
  font-family: sans-serif;
  font-size: 1.2em;
  padding: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <a id="activator"></a>
  <ul>
    <li>
      <a href="#">Home</a>
    </li>
    <li>
      <a href="#">Courses</a>
    </li>
    <li>
      <a href="#">Contact</a>
    </li>
    <li>
      <a href="#">Log out</a>
    </li>
  </ul>
</nav>
<div class="long-div">
</div>


问:
How Do I Make Hidden Property In Base Class Get Only
I have the following situation and I want to know how I can make the property SomeNumber to be read only from instances of class A? BTW, I am using C# latest stable build, or not 7.2 c#, so I can't use private protected modifier.

So I don't want to be able to set SomeNumber on accident from class A. I know it can be written in another way to achieve it but can I make the setter in class A's property only visible to class B's property setter? So you can still read SomeNumber from instances of A. Thanks.

I want to to this because I have multiple classes, not only B, derived from class A that hides the base property and they all need to run their own methods when setting SomeNumber.

```<code>class A
{
    private int someNumber;
    internal int SomeNumber
    {
        get { return someNumber; }
        set
        {
            someNumber = value;
            SomethingNotSpecificForDerivedClasses();//I prefer not to move this to each derived setter! There are more derived classes than just B, fyi
        }//I NEED TO MODIFY THE ACCESS OF THIS
    }

    private void SomethingNotSpecificForDerivedClasses()
    {
        ...
    }
}
class B : A
{
    new internal int SomeNumber//hides base member
    {
        get { return base.SomeNumber; }
        set
        {
            base.SomeNumber = value;//ONLY THIS SETTER SHOULD BE ALLOWED TO DO THIS
            SomethingINeedToRunWhenSettingSomeNumber();
        }
    }

    private void SomethingINeedToRunWhenSettingSomeNumber()
    {
        ...
    }
}
</code>```

答:
Just like with any other override method, you need to make your base class method virtual, and use the 'override' keyword on your subclass.

Within the class, you can then call the base class' method to set the value, so it will run the base-class setter.

Your end result could look like this:

```<code>Class A
{
    private int someNumber;
    internal virtual int SomeNumber
    {
        get { return someNumber; }
        set { someNumber = value; }
    }
}
Class B : A
{
    internal override int SomeNumber
    {
        get { return base.SomeNumber; }
        set
        {
            base.someNumber = value;
            SomethingINeedToRunWhenSettingSomeNumber();
        }
    }

    private void SomethingINeedToRunWhenSettingSomeNumber()
    {
        ...
    }
}
</code>```

Body:
I have the following situation and I want to know how I can make the property SomeNumber to be read only from instances of class A? BTW, I am using C# latest stable build, or not 7.2 c#, so I can't use private protected modifier.

So I don't want to be able to set SomeNumber on accident from class A. I know it can be written in another way to achieve it but can I make the setter in class A's property only visible to class B's property setter? So you can still read SomeNumber from instances of A. Thanks.

I want to to this because I have multiple classes, not only B, derived from class A that hides the base property and they all need to run their own methods when setting SomeNumber.

class A
{
    private int someNumber;
    internal int SomeNumber
    {
        get { return someNumber; }
        set
        {
            someNumber = value;
            SomethingNotSpecificForDerivedClasses();//I prefer not to move this to each derived setter! There are more derived classes than just B, fyi
        }//I NEED TO MODIFY THE ACCESS OF THIS
    }

    private void SomethingNotSpecificForDerivedClasses()
    {
        ...
    }
}
class B : A
{
    new internal int SomeNumber//hides base member
    {
        get { return base.SomeNumber; }
        set
        {
            base.SomeNumber = value;//ONLY THIS SETTER SHOULD BE ALLOWED TO DO THIS
            SomethingINeedToRunWhenSettingSomeNumber();
        }
    }

    private void SomethingINeedToRunWhenSettingSomeNumber()
    {
        ...
    }
}

Body:
Just like with any other override method, you need to make your base class method virtual, and use the 'override' keyword on your subclass.

Within the class, you can then call the base class' method to set the value, so it will run the base-class setter.

Your end result could look like this:

Class A
{
    private int someNumber;
    internal virtual int SomeNumber
    {
        get { return someNumber; }
        set { someNumber = value; }
    }
}
Class B : A
{
    internal override int SomeNumber
    {
        get { return base.SomeNumber; }
        set
        {
            base.someNumber = value;
            SomethingINeedToRunWhenSettingSomeNumber();
        }
    }

    private void SomethingINeedToRunWhenSettingSomeNumber()
    {
        ...
    }
}


答:
you are reassigning $values to the last array you created each time, instead you should be adding the array you created to $values. use $values[] like below:</p>

```<code>public function getContent(){
            $query="SELECT * FROM content";
            $result=$this->db->query($query);
            $values=array();
            if($result->num_rows>0){
                while($row=$result->fetch_assoc()){
                $values[]=array(
                    "title"=>$row['title'],
                    "body"=>$row['body']
                );
            }

        }
</code>```

Title: fetch_assoc returns last inserted elements

Body:
For some reasons mysql returns only last inserted element in table,could anyone give a tip what's wrong with my code? i'm just practicing php and trying to figure out best ways to make functions easily reusable(just practicing oop i mean). i know this is a bad way but it's only for practice purposes.

<!DOCTYPE html>

    <title>Test Title</title>

    <?php
        class Database{
            public $db;

            public function __construct($host,$username,$password,$dbname){

                $this->db=new MySQLi($host,$username,$password,$dbname);

            }
            public function getData(){
                $query="SELECT * FROM artisan";
                $result=$this->db->query($query);
                if($result->num_rows>0){
                    while($row=$result->fetch_assoc()){
                        echo "ID: ".$row["id"]. "-Username: ".$row["username"]. ", "."Email: ".$row["email"]."
";
                    }
                }else{
                    echo "No results found!";
                }

            }
            public function getContent(){
                $query="SELECT * FROM content";
                $result=$this->db->query($query);
                $values=array();
                if($result->num_rows>0){
                    while($row=$result->fetch_assoc()){
                    $values=array(
                        "title"=>$row['title'],
                        "body"=>$row['body']
                    );
                }

            }
            return $values;
            }
        }
        $database=new Database('localhost','root','','test');
        $database->getData();
        $values=$database->getContent();

     ?>

      <?php

        for($i=0;$i<count($values);$i++){
        echo $values["title"]."
";
        echo $values["body"]."
";
      }
       ?>

Body:
you are reassigning $values to the last array you created each time, instead you should be adding the array you created to $values. use $values[] like below:

public function getContent(){
            $query="SELECT * FROM content";
            $result=$this->db->query($query);
            $values=array();
            if($result->num_rows>0){
                while($row=$result->fetch_assoc()){
                $values[]=array(
                    "title"=>$row['title'],
                    "body"=>$row['body']
                );
            }

        }