问:
Unable to install "Android SDK Platform Tools" from SDK Manager
Below error displays during installation:</p>

```<code>Done loading packages.
Preparing to install archives
Downloading Android SDK Platform-tools, revision 26.0.2
Download interrupted: Connection to https://dl.google.com refused
Done. Nothing was installed.
Preparing to install archives
Downloading Android SDK Platform-tools, revision 26.0.2
Download finished with wrong checksum. Expected 98832431e339c82be1fe910a733a3782071200fd, got aa3ef6f18eff4b8f12dbdf980647a6ce6c2ebe8c.
Done. Nothing was installed.
</code>```

答: I had the same checksum issue, until I just updated to Android Studio 3.0. Now the Android SDK Platform-tools 26.0.2 downloads and installs as expected. Not sure if the issue still exists for Android Studio 2.x or it was fixed separately, but it's worth trying again now.</p>

Body:
Below error displays during installation:

Done loading packages.
Preparing to install archives
Downloading Android SDK Platform-tools, revision 26.0.2
Download interrupted: Connection to https://dl.google.com refused
Done. Nothing was installed.
Preparing to install archives
Downloading Android SDK Platform-tools, revision 26.0.2
Download finished with wrong checksum. Expected 98832431e339c82be1fe910a733a3782071200fd, got aa3ef6f18eff4b8f12dbdf980647a6ce6c2ebe8c.
Done. Nothing was installed.


来源: stackexchange

问:
GWT override GSS style in another GSS file
Since my application got larger, I decided that each "module" of my application, will have its own resource file, style file and GSS file. Also styling of for example buttons will be in a different, global GSS file as it is more of an application style, used through the application.

This is not a problem, but when I wanted to do something like this:

```<code>.buttonGroup>.button.active{ background-color: red}
</code>```

in one of the modules, it does not match anything.

Since the button style(buttonGroup, button, active) and behavior (add "active" class on click) is specified in different (global) GSS file, I am not able to change the style of the "active" class.

Here is a simplified example:

```<code>public interface AppResources extends ClientBundle {

    public static AppResources INSTANCE = GWT.create(AppResources.class);

    @Source({"style.gss"})
    AppStyle appStyle();
}
</code>```

Style file:

```<code>public interface AppStyle extends CssResource {

    String buttonGroup();
    String button();
    String active();
}
</code>```

Module:

```<code>public interface ModuleResources extends AppResources{

    public static ModuleResources INSTANCE = GWT.create(ModuleResources.class);

    @Source({"style.gss","module.gss"})
    ModuleStyle moduleStyle();
}
</code>```

Style file:

```<code>public interface ModuleStyle extends AppStyle {
}
</code>```

In GSS files I tried to use @provide and @require (it would not compile without it as it would have missing identifiers or classes).

It then compiles fine, but the buttonGroup, button and even the active class is treated as it belongs to the AppStyle, therefore style.gss styles are used and the rule:

```<code>.buttonGroup>.button.active{ background-color: red}
</code>```

in module.gss is not matching anything as it is probably looking for .hash-ModuleStyle-buttonGroup, .hash-ModuleStyle-button and .hash-ModuleStyle-active classes, whereas the actual styles on the button are .hash-AppStyle-buttonGroup etc.

答: This is actually exactly what @Import is meant to solve!

ContentLicense: CC BY-SA 3.0

Body:
Since my application got larger, I decided that each "module" of my application, will have its own resource file, style file and GSS file. Also styling of for example buttons will be in a different, global GSS file as it is more of an application style, used through the application.

This is not a problem, but when I wanted to do something like this:

.buttonGroup>.button.active{ background-color: red}

in one of the modules, it does not match anything.

Since the button style(buttonGroup, button, active) and behavior (add "active" class on click) is specified in different (global) GSS file, I am not able to change the style of the "active" class.

Here is a simplified example:

public interface AppResources extends ClientBundle {

    public static AppResources INSTANCE = GWT.create(AppResources.class);

    @Source({"style.gss"})
    AppStyle appStyle();
}

Style file:

public interface AppStyle extends CssResource {

    String buttonGroup();
    String button();
    String active();
}

Module:

public interface ModuleResources extends AppResources{

    public static ModuleResources INSTANCE = GWT.create(ModuleResources.class);

    @Source({"style.gss","module.gss"})
    ModuleStyle moduleStyle();
}

Style file:

public interface ModuleStyle extends AppStyle {
}

In GSS files I tried to use @provide and @require (it would not compile without it as it would have missing identifiers or classes).

It then compiles fine, but the buttonGroup, button and even the active class is treated as it belongs to the AppStyle, therefore style.gss styles are used and the rule:

.buttonGroup>.button.active{ background-color: red}

in module.gss is not matching anything as it is probably looking for .hash-ModuleStyle-buttonGroup, .hash-ModuleStyle-button and .hash-ModuleStyle-active classes, whereas the actual styles on the button are .hash-AppStyle-buttonGroup etc.


问:
How to access a button in toolbar?
I have a custome toolbar in application like below there is a button call logout

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_layout"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@android:color/transparent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="24dp">

        <Button
            android:id="@+id/toolbar_logo_image"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="4dp"
            android:layout_centerVertical="true"
            android:background="@drawable/logo" />

        <EditText
            android:id="@+id/toolbar_search_field"
            android:layout_width="280dp"
            android:layout_height="36dp"
            android:textSize="20dp"
            android:hint="Search"
            android:textColorHint="@color/white"
            android:layout_toEndOf="@+id/toolbar_logo_image"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:background="@android:color/transparent"
            android:drawablePadding="2dp"
            android:drawableStart="@drawable/ic_search_24dp"
            tools:textColor="@android:color/black"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>
</code>```

I have include this toolbar in my main activity like below

```<code><include
        android:id="@+id/main_page_toolbar"
        layout="@layout/app_bar_toolbar">
    </include>
</code>```

in my main activity I have get that toolbar like below

```<code>mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
</code>```

How can I access the button in that toolbar I want to create a onclickevent
how can i do that?

答:
Use this xml file for custom toolbar

```<code><android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:background="@color/sky"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

       // here you can put your button  or any tools which you want.

    </RelativeLayout>

</android.support.v7.widget.Toolbar>
</code>```

After that in Your activity

```<code>Toolbar  mToolbar= (Toolbar) findViewById(R.id.toolbar);
Button btn= (Button) mToolbar.findViewById(R.id.toolbar_logo_image);

setSupportActionBar(mToolbar);  // add this line to your code.
</code>```

and in your style.xml change parent="Theme.AppCompat.Light.DarkActionBar"   to  parent="Theme.AppCompat.Light.NoActionBar"

Title: How to access a button in toolbar?

Body:
I have a custome toolbar in application like below there is a button call logout

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_layout"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@android:color/transparent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="24dp">

        <Button
            android:id="@+id/toolbar_logo_image"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="4dp"
            android:layout_centerVertical="true"
            android:background="@drawable/logo" />

        <EditText
            android:id="@+id/toolbar_search_field"
            android:layout_width="280dp"
            android:layout_height="36dp"
            android:textSize="20dp"
            android:hint="Search"
            android:textColorHint="@color/white"
            android:layout_toEndOf="@+id/toolbar_logo_image"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:background="@android:color/transparent"
            android:drawablePadding="2dp"
            android:drawableStart="@drawable/ic_search_24dp"
            tools:textColor="@android:color/black"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>

I have include this toolbar in my main activity like below

<include
        android:id="@+id/main_page_toolbar"
        layout="@layout/app_bar_toolbar">
    </include>

in my main activity I have get that toolbar like below

mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);

How can I access the button in that toolbar I want to create a onclickevent
how can i do that?

Body:
Use this xml file for custom toolbar

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:background="@color/sky"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

       // here you can put your button  or any tools which you want.

    </RelativeLayout>

</android.support.v7.widget.Toolbar>

After that in Your activity

Toolbar  mToolbar= (Toolbar) findViewById(R.id.toolbar);
Button btn= (Button) mToolbar.findViewById(R.id.toolbar_logo_image);

setSupportActionBar(mToolbar);  // add this line to your code.

and in your style.xml change parent="Theme.AppCompat.Light.DarkActionBar"   to  parent="Theme.AppCompat.Light.NoActionBar"


问:
Upper case letters in a URL, should it be advertised that way?
Currently, our URL's look something like this:

```<code>http://helpdesk.ourdomain.com
</code>```

Recently, there has been talk of advertising these URLs (in publications, on websites, etc.) to look like this for readability purposes:

```<code>http://HelpDesk.OurDomain.com
</code>```

Our web server handles going to the URL with upper-case elements in it correctly, meaning when you go to that URL, it rewrites the URL to be all lower-case. However, I was always taught that URL's are meant to be case-sensitive. Keeping that in mind, I would think that advertising the URL's with upper-case letters would not be something that should be done.

Is advertising URL's with upper-case letters in it an okay practice? Why or why not?

答:
Quoting the W3C:

URLs in general are case-sensitive (with the exception of machine names). There may be URLs, or parts of URLs, where case doesn't matter, but identifying these may not be easy. Users should always consider that URLs are case-sensitive.

I would say not, keep it lowercase.

ContentLicense: CC BY-SA 2.5

Body:
Currently, our URL's look something like this:

http://helpdesk.ourdomain.com

Recently, there has been talk of advertising these URLs (in publications, on websites, etc.) to look like this for readability purposes:

http://HelpDesk.OurDomain.com

Our web server handles going to the URL with upper-case elements in it correctly, meaning when you go to that URL, it rewrites the URL to be all lower-case. However, I was always taught that URL's are meant to be case-sensitive. Keeping that in mind, I would think that advertising the URL's with upper-case letters would not be something that should be done.

Is advertising URL's with upper-case letters in it an okay practice? Why or why not?


问:
How to use Select-Object property to expand all the fields in the power shell command
```<code>Get-ChildItem -Path E:\Server_Data\data\2015 -Recurse –File -include "*.txt","*.csv" | Where-Object {$_.Name -like "*transaction*"} | Select-Object -ExpandProperty FullName,LastWriteTime
</code>```

I'm trying to list all files in a folder using Get-ChildItem and Select-Object property. When I try to use FullName variable to list the fully qualified file name, the file name is getting truncated. Tried to use -ExpandProperty to get fully qualified file name. It works for one field but if I try to list both FullName and LastWriteTime, it's not working.

The output from the power shell command will be used in MS SQL Server to load the file names into a specific table.

Please suggest proper syntax for my purpose. Appreciate your help!

答:
If you're using the output in another program, you should be converting to CSV, JSON, or XML rather than copying the formatted output. It may also be possible to insert directly into SQL using PowerShell commands.

```<code>Get-ChildItem -Path E:\Server_Data\data\2015 -Recurse –File -include "*.txt","*.csv" |
Where-Object {$_.Name -like "*transaction*"} |
Select-Object FullName,LastWriteTime |
ConvertTo-Csv -NoTypeInformation
</code>```

Other options for the last command are:

JSON with ConvertTo-Json

XML with ConvertTo-xml -As String -NoTypeInformation

Late answer, but this has existed since PowerShell 3.0, so should have been an option.

Body:
Get-ChildItem -Path E:\Server_Data\data\2015 -Recurse –File -include "*.txt","*.csv" | Where-Object {$_.Name -like "*transaction*"} | Select-Object -ExpandProperty FullName,LastWriteTime

I'm trying to list all files in a folder using Get-ChildItem and Select-Object property. When I try to use FullName variable to list the fully qualified file name, the file name is getting truncated. Tried to use -ExpandProperty to get fully qualified file name. It works for one field but if I try to list both FullName and LastWriteTime, it's not working.

The output from the power shell command will be used in MS SQL Server to load the file names into a specific table.

Please suggest proper syntax for my purpose. Appreciate your help!

Body:
If you're using the output in another program, you should be converting to CSV, JSON, or XML rather than copying the formatted output. It may also be possible to insert directly into SQL using PowerShell commands.

Get-ChildItem -Path E:\Server_Data\data\2015 -Recurse –File -include "*.txt","*.csv" |
Where-Object {$_.Name -like "*transaction*"} |
Select-Object FullName,LastWriteTime |
ConvertTo-Csv -NoTypeInformation

Other options for the last command are:

JSON with ConvertTo-Json

XML with ConvertTo-xml -As String -NoTypeInformation

Late answer, but this has existed since PowerShell 3.0, so should have been an option.


问:
How to change the Figure Canvas Color (PyQt)
How can I set the background color of my figures? I would like to use FigureCanvasQTAgg.</p>

```<code>from PyQt5 import QtCore, QtWidgets, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
from matplotlib.figure import Figure

class FigureCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvasQTAgg.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(
            self,
            QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding,
        )
        FigureCanvas.updateGeometry(self)
</code>```

答:
I have never used matplotlib, nor tested this answer, but guessing here...

```<code>self.setStyleSheet("background-color:red;")
</code>```

?

(based on some other answer)

Body:
How can I set the background color of my figures? I would like to use FigureCanvasQTAgg.

from PyQt5 import QtCore, QtWidgets, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
from matplotlib.figure import Figure

class FigureCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvasQTAgg.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(
            self,
            QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding,
        )
        FigureCanvas.updateGeometry(self)

Body:
I have never used matplotlib, nor tested this answer, but guessing here...

self.setStyleSheet("background-color:red;")

?

(based on some other answer)


问:
Why is array_pop() returning the last item of the array instead of deleting it?
array_pop() is returning the last item of the array instead of deleting the last item of the array. Why is this happening?

```<code>$blam = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$blam = explode("/", $blam);
$blam = array_pop($blam);
print_r($blam);
</code>```

You can test out the php here.

答:
You're overriding the variable. If you need the removed value, change it to

```<code>$foo = array_pop($blam);
</code>```

The function is behaving as expected. From the docs:

array_pop() pops and returns the last value of the array, shortening the array by one element.

When you use

```<code>$blam = array_pop($blam);
</code>```

You're saying:

"Remove the last element from $blam and store it inside $blam",  replacing the previous content with said element.

To elaborate, I think the confusion here is that array_pop does NOT return the new array, it instead returns the removed value, changing the original array.

Body:
array_pop() is returning the last item of the array instead of deleting the last item of the array. Why is this happening?

$blam = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$blam = explode("/", $blam);
$blam = array_pop($blam);
print_r($blam);

You can test out the php here.

Body:
You're overriding the variable. If you need the removed value, change it to

$foo = array_pop($blam);

The function is behaving as expected. From the docs:

array_pop() pops and returns the last value of the array, shortening the array by one element.

When you use

$blam = array_pop($blam);

You're saying:

"Remove the last element from $blam and store it inside $blam",  replacing the previous content with said element.

To elaborate, I think the confusion here is that array_pop does NOT return the new array, it instead returns the removed value, changing the original array.


问:
Authenticate JWT with Guardian 1 and Phoenix 1.3
Ive made a project that can be found here:

https://github.com/rootkc/phx_auth_api

When I try to post to:

```<code>http://0.0.0.0:4000/api/login
</code>```

with the body:

```<code>{ "user": { "username": "kenneth", "password": "kenneth" } }
</code>```

That is a user that is in the database.
I get the response:

```<code>{
"data": {
    "token": "eyJhbGciOiJIUzUxM[...]gbPVHTsSvrCA"
}
</code>```

}

When i then put that token in the header:
Àuthorization: :token
of the call http://0.0.0.0:4000/api/users that has the Guardian pipeline plug
I get back the message: unauthenticated

And i have no idea, what i'm doing wrong. This is my first real Phoenix project and i tried to follow various guide but the {:guardian, "~> 1.0-beta"} seems to be quite new, with bad documentation.

答: I had an typo in my Pipeline. Now everything works as expected.</p>

Body:
Ive made a project that can be found here:

https://github.com/rootkc/phx_auth_api

When I try to post to:

http://0.0.0.0:4000/api/login

with the body:

{ "user": { "username": "kenneth", "password": "kenneth" } }

That is a user that is in the database.
I get the response:

{
"data": {
    "token": "eyJhbGciOiJIUzUxM[...]gbPVHTsSvrCA"
}

}

When i then put that token in the header:
Àuthorization: :token
of the call http://0.0.0.0:4000/api/users that has the Guardian pipeline plug
I get back the message: unauthenticated

And i have no idea, what i'm doing wrong. This is my first real Phoenix project and i tried to follow various guide but the {:guardian, "~> 1.0-beta"} seems to be quite new, with bad documentation.


问:
Joining in MongoDB MapReduce
I have 2 collections.

A:
cid: is a mongo object id, like: ObjectId("xxxxxx")
sid: could be NULL, or a mongo object id as well, like: ObjectId("xxxxxxx")

B:
sid: is a mongo object id, like : ObjectId("xxxxxxxx")
name: is a string, like: "hello"

I want to get all documents in A (no matter sid is null, or not). If sid is null, then name is empty string: "". If NOT, then name is form B basing on sid.

When I looking for the answer, I know the map function should emit the same key on both collections.  BUT, in my case, I CANNOT use sid as key.  If I use sid as key, then I will miss the documents with sid id null (no name).  I think I must use cid as key.

If someone know how to solve it, please let me know.
Thanks.

Update:

```<code>    A:
    [
     {cid: ObjectId("59f7634b6260c927c0a144b0"), sid: ObjectId("59f7634b6260c927c0a144b1")},
     {cid: ObjectId("59f7634b6260c927c0a144b2"), sid: null}
    ]
    B: [{sid: ObjectId("59f7634b6260c927c0a144b1"), name: "hello"}]
</code>```

I want to get

```<code>    [
     {cid: ObjectId("59f7634b6260c927c0a144b0"), sid: ObjectId("59f7634b6260c927c0a144b1"), name: "hello"},
     {cid: ObjectId("59f7634b6260c927c0a144b2"), sid: null, name: ""}
    ]
</code>```

答:
There you go:</p>

```<code>db.getCollection('A').aggregate([{
    $lookup:
    { // lookup data from B using the "sid" fields as the join key
        'from': 'B',
        'localField': 'sid',
        'foreignField': 'sid',
        'as': 'b'
    }
}, {
    $unwind: { // flatten the "b" array
        path: "$b",
        preserveNullAndEmptyArrays: true // make sure we do not drop the non-matched documents from A
    }
}, {
    $project: {
        "_id": 1,
        "cid": 1,
        "sid": 1,
        "hello": { $ifNull: [ "$b.name", "" ] },
    }
}])
</code>```

Title: Joining in MongoDB MapReduce

Body:
I have 2 collections.

A:
cid: is a mongo object id, like: ObjectId("xxxxxx")
sid: could be NULL, or a mongo object id as well, like: ObjectId("xxxxxxx")

B:
sid: is a mongo object id, like : ObjectId("xxxxxxxx")
name: is a string, like: "hello"

I want to get all documents in A (no matter sid is null, or not). If sid is null, then name is empty string: "". If NOT, then name is form B basing on sid.

When I looking for the answer, I know the map function should emit the same key on both collections.  BUT, in my case, I CANNOT use sid as key.  If I use sid as key, then I will miss the documents with sid id null (no name).  I think I must use cid as key.

If someone know how to solve it, please let me know.
Thanks.

Update:

    A:
    [
     {cid: ObjectId("59f7634b6260c927c0a144b0"), sid: ObjectId("59f7634b6260c927c0a144b1")},
     {cid: ObjectId("59f7634b6260c927c0a144b2"), sid: null}
    ]
    B: [{sid: ObjectId("59f7634b6260c927c0a144b1"), name: "hello"}]

I want to get

    [
     {cid: ObjectId("59f7634b6260c927c0a144b0"), sid: ObjectId("59f7634b6260c927c0a144b1"), name: "hello"},
     {cid: ObjectId("59f7634b6260c927c0a144b2"), sid: null, name: ""}
    ]

Body:
There you go:

db.getCollection('A').aggregate([{
    $lookup:
    { // lookup data from B using the "sid" fields as the join key
        'from': 'B',
        'localField': 'sid',
        'foreignField': 'sid',
        'as': 'b'
    }
}, {
    $unwind: { // flatten the "b" array
        path: "$b",
        preserveNullAndEmptyArrays: true // make sure we do not drop the non-matched documents from A
    }
}, {
    $project: {
        "_id": 1,
        "cid": 1,
        "sid": 1,
        "hello": { $ifNull: [ "$b.name", "" ] },
    }
}])


问:
Getting data from Yahoo Finance
I read about the YQL, but I didn't understand how can I get some simple data (like company ticker, market cap, stock price, etc.), for ALL COMPANIES?

And an additional question, how can I get all Yahoo Finance tables and theirs fields that can be queried by YQL?

答:
Since Yahoo Finances API was disabled, I found Alpha Vantage API

This a stock query sample that I'm using with Excel's Power Query:

```<code>https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo
</code>```

Title: Getting data from Yahoo Finance

Body:
Since Yahoo Finances API was disabled, I found Alpha Vantage API

This a stock query sample that I'm using with Excel's Power Query:

https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo

ContentLicense: CC BY-SA 4.0


问:
Reformating an external file and then saving it, from inside a python code
Sorry for the basic question, but my python is a bit rusty after having not worked with it for a few months!

Basically I am trying to run a python code over a list of files which are the output of another code (which unfortunately I cannot alter). The problem is that the code I have written requires the files in "input.txt" to all be on separate lines and currently they are separated by a comma.

Try as I might I haven't been able to write anything that reformats this file inside my code.

The files currently look like:

```<code>file1,file2,file3
</code>```

and I need to get them to look like:

```<code>file1
file2
file3
</code>```

and then re save "input.txt" before using it in:

```<code> for ln in open("input.txt"):
    ch.Add(ln.strip())
</code>```

(where ch is a chain)

Any help would be much appreciated, thanks!

答:
```<code>for x in files.split(','):
     print >> input, x
</code>```

Body:
Sorry for the basic question, but my python is a bit rusty after having not worked with it for a few months!

Basically I am trying to run a python code over a list of files which are the output of another code (which unfortunately I cannot alter). The problem is that the code I have written requires the files in "input.txt" to all be on separate lines and currently they are separated by a comma.

Try as I might I haven't been able to write anything that reformats this file inside my code.

The files currently look like:

file1,file2,file3

and I need to get them to look like:

file1
file2
file3

and then re save "input.txt" before using it in:

 for ln in open("input.txt"):
    ch.Add(ln.strip())

(where ch is a chain)

Any help would be much appreciated, thanks!


问:
min-height not allowing full height child
I Have a div with the following css class (generated)

```<code>min-height: {
    margin-top: 30px !important;
    margin-bottom: 30px !important;
    min-height: -webkit-calc(100% - 60px) !important;
    min-height: -moz-calc(100% - 60px) !important;
    min-height: calc(100% - 60px) !important;
}
</code>```

when I add a div inside with a height of 100% the content doesn't fill to the parent div - only when the parent div has the height attribute set not the min-height.

How can i make the  child div expand to the full size of the parent div if it only has min-height set?

```<code><div class="min-height">
    <div class="full-height">not much content<div>
</div>
</code>```

答:
When you declare a height on something like that, it's parent needs to have a height specified, and so on up the chain.

(Also you have a lot of syntax errors in your CSS)

For example. Add a height to the HTML and Body elements. Also give the parent a height.  Now your child, can have 100% height of it's container.

body, html {
 height: 100%;
}

.min-height {
    margin-top: 30px;
    margin-bottom: 30px;
    height: 100%;
    min-height: calc(100% - 60px);
    background: gray;
    padding: 10px;
}

.full-height {
  height: 100%;
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="min-height">
    <div class="full-height">not much content<div>
</div></code>```

Body:
I Have a div with the following css class (generated)

min-height: {
    margin-top: 30px !important;
    margin-bottom: 30px !important;
    min-height: -webkit-calc(100% - 60px) !important;
    min-height: -moz-calc(100% - 60px) !important;
    min-height: calc(100% - 60px) !important;
}

when I add a div inside with a height of 100% the content doesn't fill to the parent div - only when the parent div has the height attribute set not the min-height.

How can i make the  child div expand to the full size of the parent div if it only has min-height set?

not much content

Body:
When you declare a height on something like that, it's parent needs to have a height specified, and so on up the chain.

(Also you have a lot of syntax errors in your CSS)

For example. Add a height to the HTML and Body elements. Also give the parent a height.  Now your child, can have 100% height of it's container.

body, html {
 height: 100%;
}

.min-height {
    margin-top: 30px;
    margin-bottom: 30px;
    height: 100%;
    min-height: calc(100% - 60px);
    background: gray;
    padding: 10px;
}

.full-height {
  height: 100%;
  background: yellow;
}

<div class="min-height">
    <div class="full-height">not much content<div>
</div>


问:
Bean Validation - JSR-303 DuplicateItemCheck for a list in java
Is there any standard bean validation annotation to check duplicate item in a collection in java.
or Anyone implemented custom validation to check duplicate in a list using bean validation.

for example

```<code>

    public class MySecurityRequest{
        private Date dob;

        @DuplicateNotAllowed
        private List securityQuestions;
    }

    public class SecurityQuestion{
      private String question;
      private String answer;
    }

</code>```

Here i need to make sure that, questions are not repeated in the list.
Are one faced this similar issue?

答:
Ah ah funny you ask. We just added the @UniqueElements annotation to Hibernate Validator (the PR was merged today - https://github.com/hibernate/hibernate-validator/pull/879).

It will be part of 6.0.5.Final that we plan to release tomorrow.

Note that it is not a standard constraint (i.e. it's not in Bean Validation) but it will be supported by HV out of the box.

You should be able to use HV 6 with Spring: it should be compatible. Just be careful about your dependencies (you can't have both versions in your dependencies - the group ids of HV 5 and 6 are different - and also be careful about the javax.el dependency - see https://github.com/hibernate/hibernate-validator#using-hibernate-validator for the details).

Body:
Is there any standard bean validation annotation to check duplicate item in a collection in java.
or Anyone implemented custom validation to check duplicate in a list using bean validation.

for example

    public class MySecurityRequest{
        private Date dob;

        @DuplicateNotAllowed
        private List securityQuestions;
    }

    public class SecurityQuestion{
      private String question;
      private String answer;
    }

Here i need to make sure that, questions are not repeated in the list.
Are one faced this similar issue?


问:
how to start c++ mfc application
i work last 3 years on c#. now for some reason i have to make some MFC cpp application.
so what u people suggest for me. is it harder then c#? how can i begin? in c# i started just making some puzzle game do i follow the same for it? what is the best way to learn MFC c++? where i can find the resource? </p>

答:
MFC does not really hide the fact that it is built upen the Win32 API. So, the answer to your question really depends on whether you have been exposed to this API and if so how familiar you are with it.

When I used to program MFC (those were the days...) it really helped me understand to create an application without any help of any wizard. That is obviously not to say, that I wouldn't ever suggest using the wizard.

The book I used to learn MFC was Programming Windows with MFC by Jeff Prosise.

The Scrible Tutorial, currently at http://msdn.microsoft.com/en-us/library/aa716527%28VS.60%29.aspx is not bad, either.

Also check this thread: MFC resources / links .

Title: how to start c++ mfc application


问:
Editing & Running an SQL Query in an Access database from Excel VBA
I am trying to write a Excel VBA macro that runs a query based upon a variable in the spreadsheet. The existing data is half in a large data base (MS Access) on the network.

For some reason when my code runs, nothing is pasted back to my spreadsheet. Can you see why this may be the case:

Sub test()

    Dim cnn As New ADODB.Connection
    Dim rst As New ADODB.Recordset
    Dim ConnectionString As String
    Dim StrQuery As String

    ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;DataSource=\\network\data07\version6.mdb;"

    cnn.Open ConnectionString
    cnn.CommandTimeout = 900

    StrQuery = "SELECT dbo_vwData_SelectAll.BusinessDate, , dbo_vwData_SelectAll.Flowdate, dbo_vwData_SelectAll.Bucket FROM dbo_vwData_SelectAll WHERE (((dbo_vwData_SelectAll.Line)=""1.1.1.4"") AND ((dbo_vwData_SelectAll.ReferenceID) Like ""rent*"");"

    rst.Open StrQuery, cnn

    Sheets("Sheet2").Range("A2").CopyFromRecordset rst

End Sub
```

The above is a test - I will be changing "rent*" for other variables based on strings in the spreadsheet.

Thanks in advance.

答:
The misappropriated LIKE operator is a known issue in the MS Access SQL dialect. When using MSAccess.exe GUI program, LIKE uses the asterisk wildcard, *. However, using MS Access via ODBC as a backend database as you are with Excel, LIKE uses the ANSI wildcard, %. See MS Office Support docs on Access wildcard character reference.

Therefore, consider the following adjustment which includes use of single quotes:

SELECT dbo_vwData_SelectAll.BusinessDate,
       dbo_vwData_SelectAll.Flowdate, dbo_vwData_SelectAll.Bucket

FROM dbo_vwData_SelectAll

WHERE (((dbo_vwData_SelectAll.Line)='1.1.1.4')
  AND  ((dbo_vwData_SelectAll.ReferenceID) LIKE 'rent%');
```

<p>To be consistent in either frontend or backend interfaces, consider the <code>ALIKE</code> operator:</p>

<pre class="lang-sql prettyprint-override"><code>AND  ((dbo_vwData_SelectAll.ReferenceID) ALIKE 'rent%');
</code>```

Body:
I am trying to write a Excel VBA macro that runs a query based upon a variable in the spreadsheet. The existing data is half in a large data base (MS Access) on the network.

For some reason when my code runs, nothing is pasted back to my spreadsheet. Can you see why this may be the case:

Sub test()

    Dim cnn As New ADODB.Connection
    Dim rst As New ADODB.Recordset
    Dim ConnectionString As String
    Dim StrQuery As String

    ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;DataSource=\\network\data07\version6.mdb;"

    cnn.Open ConnectionString
    cnn.CommandTimeout = 900

    StrQuery = "SELECT dbo_vwData_SelectAll.BusinessDate, , dbo_vwData_SelectAll.Flowdate, dbo_vwData_SelectAll.Bucket FROM dbo_vwData_SelectAll WHERE (((dbo_vwData_SelectAll.Line)=""1.1.1.4"") AND ((dbo_vwData_SelectAll.ReferenceID) Like ""rent*"");"

    rst.Open StrQuery, cnn

    Sheets("Sheet2").Range("A2").CopyFromRecordset rst

End Sub

The above is a test - I will be changing "rent*" for other variables based on strings in the spreadsheet.

Thanks in advance.

Body:
The misappropriated LIKE operator is a known issue in the MS Access SQL dialect. When using MSAccess.exe GUI program, LIKE uses the asterisk wildcard, *. However, using MS Access via ODBC as a backend database as you are with Excel, LIKE uses the ANSI wildcard, %. See MS Office Support docs on Access wildcard character reference.

Therefore, consider the following adjustment which includes use of single quotes:

SELECT dbo_vwData_SelectAll.BusinessDate,
       dbo_vwData_SelectAll.Flowdate, dbo_vwData_SelectAll.Bucket

FROM dbo_vwData_SelectAll

WHERE (((dbo_vwData_SelectAll.Line)='1.1.1.4')
  AND  ((dbo_vwData_SelectAll.ReferenceID) LIKE 'rent%');

To be consistent in either frontend or backend interfaces, consider the ALIKE operator:

AND  ((dbo_vwData_SelectAll.ReferenceID) ALIKE 'rent%');


问:
List of possible combinations of characters with OR statement
I managed to generate a list of all possible combinations of characters 'a', 'b' and 'c' (code below). Now I want to add a fourth character, which can be either 'd' or 'f' but NOT both in the same combination. How could I achieve this ?  </p>

```<code>items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
     print(p)

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
</code>```

答:
A variation on @Van Peer's solution. You can modify the extended list in-place:</p>

```<code>from itertools import permutations
items = list('abc_')
for items[3] in 'dg':
    for p in permutations(items):
        print(p)
</code>```

Body:
I managed to generate a list of all possible combinations of characters 'a', 'b' and 'c' (code below). Now I want to add a fourth character, which can be either 'd' or 'f' but NOT both in the same combination. How could I achieve this ?

items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
     print(p)

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

Body:
A variation on @Van Peer's solution. You can modify the extended list in-place:

from itertools import permutations
items = list('abc_')
for items[3] in 'dg':
    for p in permutations(items):
        print(p)


问:
Configuration error on Run Dist Play Application
I have created a dist of my Play application with sbt clean dist.

Then I have extracted the zip file inside the universal folder.

When I run the application with bin/app-name I get the following error:

```<code>7626kfpi3: Configuration error
    at play.api.libs.crypto.CryptoConfigParser.get$lzycompute(Crypto.scala:498)
    at play.api.libs.crypto.CryptoConfigParser.get(Crypto.scala:465)
    at play.api.libs.crypto.CryptoConfigParser.get(Crypto.scala:463)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
    at com.google.inject.internal.BoundProviderFactory.provision(BoundProviderFactory.java:72)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:61)
    at com.google.inject.internal.BoundProviderFactory.get(BoundProviderFactory.java:62)
    at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:38)
    at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:62)
    at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:104)
    at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:85)
    at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:267)
    at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1103)
    at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
    at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:145)
    at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
    at com.google.inject.internal.BoundProviderFactory.get(BoundProviderFactory.java:61)
    at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:38)
    at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:62)
    at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:104)
    at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:85)
    at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:267)
    at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1103)
    at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
    at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:145)
    at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
    at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:205)
    at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:199)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
    at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:199)
    at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:180)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110)
    at com.google.inject.Guice.createInjector(Guice.java:96)
    at com.google.inject.Guice.createInjector(Guice.java:84)
    at play.api.inject.guice.GuiceBuilder.injector(GuiceInjectorBuilder.scala:181)
    at play.api.inject.guice.GuiceApplicationBuilder.build(GuiceApplicationBuilder.scala:123)
    at play.api.inject.guice.GuiceApplicationLoader.load(GuiceApplicationLoader.scala:21)
    at play.core.server.ProdServerStart$.start(ProdServerStart.scala:47)
    at play.core.server.ProdServerStart$.main(ProdServerStart.scala:22)
    at play.core.server.ProdServerStart.main(ProdServerStart.scala)
</code>```

I have tried to remove all extra configuration properties from conf/application.conf file, but this had not resolved the problem.

答:
You probably need to add a secret key as discussed here: https://www.playframework.com/documentation/2.6.x/ApplicationSecret

Play should generate a better error message for that scenario (it did in the past).

Body:
I have created a dist of my Play application with sbt clean dist.

Then I have extracted the zip file inside the universal folder.

When I run the application with bin/app-name I get the following error:

7626kfpi3: Configuration error
    at play.api.libs.crypto.CryptoConfigParser.get$lzycompute(Crypto.scala:498)
    at play.api.libs.crypto.CryptoConfigParser.get(Crypto.scala:465)
    at play.api.libs.crypto.CryptoConfigParser.get(Crypto.scala:463)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
    at com.google.inject.internal.BoundProviderFactory.provision(BoundProviderFactory.java:72)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:61)
    at com.google.inject.internal.BoundProviderFactory.get(BoundProviderFactory.java:62)
    at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:38)
    at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:62)
    at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:104)
    at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:85)
    at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:267)
    at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1103)
    at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
    at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:145)
    at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
    at com.google.inject.internal.BoundProviderFactory.get(BoundProviderFactory.java:61)
    at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:38)
    at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:62)
    at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:104)
    at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:85)
    at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:267)
    at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1103)
    at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
    at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:145)
    at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
    at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:205)
    at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:199)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
    at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:199)
    at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:180)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110)
    at com.google.inject.Guice.createInjector(Guice.java:96)
    at com.google.inject.Guice.createInjector(Guice.java:84)
    at play.api.inject.guice.GuiceBuilder.injector(GuiceInjectorBuilder.scala:181)
    at play.api.inject.guice.GuiceApplicationBuilder.build(GuiceApplicationBuilder.scala:123)
    at play.api.inject.guice.GuiceApplicationLoader.load(GuiceApplicationLoader.scala:21)
    at play.core.server.ProdServerStart$.start(ProdServerStart.scala:47)
    at play.core.server.ProdServerStart$.main(ProdServerStart.scala:22)
    at play.core.server.ProdServerStart.main(ProdServerStart.scala)

I have tried to remove all extra configuration properties from conf/application.conf file, but this had not resolved the problem.


问:
How to do real-time pitch shifting from mic with Superpowered?
I'm trying to make a pitch shift in real time from a microphone using superpowerd. I looked at the example that is for the file. Also tried to adapt it. I managed to change the sound, but it turned out very distorted with interference. What am I doing wrong? where to find more information on superpowered and timeStretching?</p>

```<code>    static bool audioProcessing(void *clientdata,
                            float **buffers,
                            unsigned int inputChannels,
                            unsigned int outputChannels,
                            unsigned int numberOfSamples,
                            unsigned int samplerate,
                            uint64_t hostTime) {
    __unsafe_unretained Superpowered *self = (__bridge Superpowered *)clientdata;

    float tempBuffer[numberOfSamples * 2 + 16];
    SuperpoweredInterleave(buffers[0], buffers[1], tempBuffer, numberOfSamples);
    float *outputBuffer = tempBuffer;

    SuperpoweredAudiobufferlistElement inputBuffer;

    inputBuffer.samplePosition = 0;

    inputBuffer.startSample = 0;
    inputBuffer.samplesUsed = 0;
    inputBuffer.endSample = self->timeStretcher->numberOfInputSamplesNeeded;
    inputBuffer.buffers[0] = SuperpoweredAudiobufferPool::getBuffer(self->timeStretcher->numberOfInputSamplesNeeded * 8 + 64);
    inputBuffer.buffers[1] = inputBuffer.buffers[2] = inputBuffer.buffers[3] = NULL;

    memcpy((float *)inputBuffer.buffers[0], outputBuffer, numberOfSamples * 2 + 16);

    self->timeStretcher->process(&inputBuffer, self->outputBuffers);

    // Do we have some output?
    if (self->outputBuffers->makeSlice(0, self->outputBuffers->sampleLength)) {
        while (true) {  // Iterate on every output slice.
            // Get pointer to the output samples.
            int sampleCount = 0;
            float *timeStretchedAudio = (float *)self->outputBuffers->nextSliceItem(&sampleCount);
            if (!timeStretchedAudio) break;
            SuperpoweredDeInterleave(timeStretchedAudio, buffers[0], buffers[1], numberOfSamples);
        };

        // Clear the output buffer list.
        self->outputBuffers->clear();
    };

    return true;
}
</code>```

答:
I did the following:

```<code>static bool audioProcessing(void *clientdata,
                                float **buffers,
                                unsigned int inputChannels,
                                unsigned int outputChannels,
                                unsigned int numberOfSamples,
                                unsigned int samplerate,
                                uint64_t hostTime) {
    __unsafe_unretained Superpowered *self = (__bridge Superpowered *)clientdata;

    SuperpoweredAudiobufferlistElement inputBuffer;
    inputBuffer.startSample = 0;
    inputBuffer.samplesUsed = 0;
    inputBuffer.endSample = numberOfSamples;
    inputBuffer.buffers[0] = SuperpoweredAudiobufferPool::getBuffer((unsigned int) (numberOfSamples * 8 + 64));
    inputBuffer.buffers[1] = inputBuffer.buffers[2] = inputBuffer.buffers[3] = NULL;

    SuperpoweredInterleave(buffers[0], buffers[1], (float *)inputBuffer.buffers[0], numberOfSamples);

    self->timeStretcher->process(&inputBuffer, self->outputBuffers);

    // Do we have some output?
    if (self->outputBuffers->makeSlice(0, self->outputBuffers->sampleLength)) {
        while (true) { // Iterate on every output slice.
            // Get pointer to the output samples.
            int numSamples = 0;
            float *timeStretchedAudio = (float *)self->outputBuffers->nextSliceItem(&numSamples);
            if (!timeStretchedAudio || *timeStretchedAudio == 0) {
                break;
            }

            SuperpoweredDeInterleave(timeStretchedAudio, buffers[0], buffers[1], numSamples);
        }
        // Clear the output buffer list.
        self->outputBuffers->clear();
    }

    return true;
}
</code>```

This might not work correctly when changing the speed also, but I wanted live pitch shifting only. People should be able to speak slower or faster themselves.

Body:
I'm trying to make a pitch shift in real time from a microphone using superpowerd. I looked at the example that is for the file. Also tried to adapt it. I managed to change the sound, but it turned out very distorted with interference. What am I doing wrong? where to find more information on superpowered and timeStretching?

    static bool audioProcessing(void *clientdata,
                            float **buffers,
                            unsigned int inputChannels,
                            unsigned int outputChannels,
                            unsigned int numberOfSamples,
                            unsigned int samplerate,
                            uint64_t hostTime) {
    __unsafe_unretained Superpowered *self = (__bridge Superpowered *)clientdata;

    float tempBuffer[numberOfSamples * 2 + 16];
    SuperpoweredInterleave(buffers[0], buffers[1], tempBuffer, numberOfSamples);
    float *outputBuffer = tempBuffer;

    SuperpoweredAudiobufferlistElement inputBuffer;

    inputBuffer.samplePosition = 0;

    inputBuffer.startSample = 0;
    inputBuffer.samplesUsed = 0;
    inputBuffer.endSample = self->timeStretcher->numberOfInputSamplesNeeded;
    inputBuffer.buffers[0] = SuperpoweredAudiobufferPool::getBuffer(self->timeStretcher->numberOfInputSamplesNeeded * 8 + 64);
    inputBuffer.buffers[1] = inputBuffer.buffers[2] = inputBuffer.buffers[3] = NULL;

    memcpy((float *)inputBuffer.buffers[0], outputBuffer, numberOfSamples * 2 + 16);

    self->timeStretcher->process(&inputBuffer, self->outputBuffers);

    // Do we have some output?
    if (self->outputBuffers->makeSlice(0, self->outputBuffers->sampleLength)) {
        while (true) {  // Iterate on every output slice.
            // Get pointer to the output samples.
            int sampleCount = 0;
            float *timeStretchedAudio = (float *)self->outputBuffers->nextSliceItem(&sampleCount);
            if (!timeStretchedAudio) break;
            SuperpoweredDeInterleave(timeStretchedAudio, buffers[0], buffers[1], numberOfSamples);
        };

        // Clear the output buffer list.
        self->outputBuffers->clear();
    };

    return true;
}

Body:
I did the following:

static bool audioProcessing(void *clientdata,
                                float **buffers,
                                unsigned int inputChannels,
                                unsigned int outputChannels,
                                unsigned int numberOfSamples,
                                unsigned int samplerate,
                                uint64_t hostTime) {
    __unsafe_unretained Superpowered *self = (__bridge Superpowered *)clientdata;

    SuperpoweredAudiobufferlistElement inputBuffer;
    inputBuffer.startSample = 0;
    inputBuffer.samplesUsed = 0;
    inputBuffer.endSample = numberOfSamples;
    inputBuffer.buffers[0] = SuperpoweredAudiobufferPool::getBuffer((unsigned int) (numberOfSamples * 8 + 64));
    inputBuffer.buffers[1] = inputBuffer.buffers[2] = inputBuffer.buffers[3] = NULL;

    SuperpoweredInterleave(buffers[0], buffers[1], (float *)inputBuffer.buffers[0], numberOfSamples);

    self->timeStretcher->process(&inputBuffer, self->outputBuffers);

    // Do we have some output?
    if (self->outputBuffers->makeSlice(0, self->outputBuffers->sampleLength)) {
        while (true) { // Iterate on every output slice.
            // Get pointer to the output samples.
            int numSamples = 0;
            float *timeStretchedAudio = (float *)self->outputBuffers->nextSliceItem(&numSamples);
            if (!timeStretchedAudio || *timeStretchedAudio == 0) {
                break;
            }

            SuperpoweredDeInterleave(timeStretchedAudio, buffers[0], buffers[1], numSamples);
        }
        // Clear the output buffer list.
        self->outputBuffers->clear();
    }

    return true;
}

This might not work correctly when changing the speed also, but I wanted live pitch shifting only. People should be able to speak slower or faster themselves.


问:
why use xcode if monotouch is available?
if mono touch is available than why we should use mac environment(sdk,xcode+Interface Builder)?

what are the disadvantage of monotouch compare to xcode?

答:
I feel like this needs an answer from the MT camp, too.

Why eat fish, if you can have meat? Why speak German, if English is understood? Why watch CNN if there is FOX? Why vote vote for the Republicans if there are the Democrats? Why...? And so on.

It is your choice! If you have worked with C# for a long time and want to have quick results on iOS, go MonoTouch. Especially if you have a collection of APIs or methods you can reuse, MT is the way to go. If you want to learn a new language (ObjC), go for it. Even if you use MT in the end, knowing ObjC is somehow crucial because it helps you understand why things work as they do.


问:
PyDev - unresolved import only on IDE, still running
I'm trying to understand what PyDev doesn't like. I'm under Ubuntu and it seems that PyDev doesn't see the libraries like bash does.
I have a problem with two libraries, sqlite3 and peewee. If I run my program on a shell, all fine; if I open it in my newly installed PyDev I see a couple of instruction underlined with the message

Unresolved import: sqlite3

And

Undefined variable from import: get

The first error comes from the following code:

```<code>from pprint import pprint
import sqlite3
from bs4 import BeautifulSoup
import codecs
from database import Tbrecipe
from datetime import datetime
import logging

def main():
    logger = logging.getLogger('peewee')
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())
    CONN = sqlite3.connect('ent.db')
</code>```

The import error happens at the.. import. Second line.This happens because I've personally added /usr/lib/python2.7/sqlite3 to the pythonpath on the pydev's python interpreter. If I remove it, the error is at "sqlite3.connect". I suppose connect is not defined on that directory. I didn't find it.

Peewee has other issues. I created an object class for my database's table. All fine until I try to use some methods inherited from peewee.

My database.py looks like this:

from peewee import *
database = MySQLDatabase('test', **{'host': 'localhost',
 'password': 'rt', 'user': 'rt','charset':'utf8mb4'})

class UnknownField(object):
    def init(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = database

class Tbitem(BaseModel):
    source = IntegerField()
    name = CharField(null=True)

on my main.py

```<code>...
from database import Tbitem
item = Tbitem.get(Tbitem.id==id_item)
</code>```

both "get" and "Tbitem.id" are underlined in red with the error

Undefined variable from import: get

I can continue to work as nothing happens, or I can go back to vim or vscode (slow debugger), but I"d prefer using this since I'm used to eclipse and I like the idea of pydev. What should I do? I did check pythonpath on a shell and it looks the same, other than a directory that doesn't exist anymore.

I read on the FAQ of pydev that it doesn't like softlinks. Should I remove all softlinks? peewee is not softlinked and sqlite3 I don't even know where it finish.

Anyone with similar issues and a solution? I did read most of the questions here on SO, but they don't work for me.

答:
I had the same issue with Orange-Bioinformatics, code would run fine but PyDev showed an unknown import.

The problem in this case were missing __init__.py files in the Orange-Bioinformatics archive, which pip downloaded and installed. PyDev seems to want a namespace declaration for each module, so I simply created a file in ~/.local/lib/python3.4/site-packages/orangecontrib/ (would be /usr/lib/python2.7/sqlite3/ in your case), named the file __init__.py and saved it with the following content:

```<code># namespace stub
__import__("pkg_resources").declare_namespace(__name__)
</code>```

The file was put into the subfolder orangecontrib/bio/

Just refresh PyDev's module list via Window -> Preferences -> PyDev -> Interpreters -> Python Interpreter -> Apply. Now all works well for me :-)

Body:
I'm trying to understand what PyDev doesn't like. I'm under Ubuntu and it seems that PyDev doesn't see the libraries like bash does.
I have a problem with two libraries, sqlite3 and peewee. If I run my program on a shell, all fine; if I open it in my newly installed PyDev I see a couple of instruction underlined with the message

Unresolved import: sqlite3

And

Undefined variable from import: get

The first error comes from the following code:

from pprint import pprint
import sqlite3
from bs4 import BeautifulSoup
import codecs
from database import Tbrecipe
from datetime import datetime
import logging

def main():
    logger = logging.getLogger('peewee')
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())
    CONN = sqlite3.connect('ent.db')

The import error happens at the.. import. Second line.This happens because I've personally added /usr/lib/python2.7/sqlite3 to the pythonpath on the pydev's python interpreter. If I remove it, the error is at "sqlite3.connect". I suppose connect is not defined on that directory. I didn't find it.

Peewee has other issues. I created an object class for my database's table. All fine until I try to use some methods inherited from peewee.

My database.py looks like this:

from peewee import *
database = MySQLDatabase('test', **{'host': 'localhost',
 'password': 'rt', 'user': 'rt','charset':'utf8mb4'})

class UnknownField(object):
    def init(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = database

class Tbitem(BaseModel):
    source = IntegerField()
    name = CharField(null=True)

on my main.py

...
from database import Tbitem
item = Tbitem.get(Tbitem.id==id_item)

both "get" and "Tbitem.id" are underlined in red with the error

Undefined variable from import: get

I can continue to work as nothing happens, or I can go back to vim or vscode (slow debugger), but I"d prefer using this since I'm used to eclipse and I like the idea of pydev. What should I do? I did check pythonpath on a shell and it looks the same, other than a directory that doesn't exist anymore.

I read on the FAQ of pydev that it doesn't like softlinks. Should I remove all softlinks? peewee is not softlinked and sqlite3 I don't even know where it finish.

Anyone with similar issues and a solution? I did read most of the questions here on SO, but they don't work for me.

Body:
I had the same issue with Orange-Bioinformatics, code would run fine but PyDev showed an unknown import.

The problem in this case were missing __init__.py files in the Orange-Bioinformatics archive, which pip downloaded and installed. PyDev seems to want a namespace declaration for each module, so I simply created a file in ~/.local/lib/python3.4/site-packages/orangecontrib/ (would be /usr/lib/python2.7/sqlite3/ in your case), named the file __init__.py and saved it with the following content:

# namespace stub
__import__("pkg_resources").declare_namespace(__name__)

The file was put into the subfolder orangecontrib/bio/

Just refresh PyDev's module list via Window -> Preferences -> PyDev -> Interpreters -> Python Interpreter -> Apply. Now all works well for me :-)


问:
Silverlight DataBinding cross thread issue
I have an Image control with it's source bound to a property on an object(string url to an image).  After making a service call, i update the data object with a new URL.  The exception is thrown after it leaves my code, after invoking the PropertyChanged event.

The data structure and the service logic are all done in a core dll that has no knowledge of the UI.  How do I sync up with the UI thread when i cant access a Dispatcher?

PS:  Accessing Application.Current.RootVisual in order to get at a Dispatcher is not a solution because the root visual is on a different thread(causing the exact exception i need to prevent).

PPS: This only is a problem with the image control, binding to any other ui element,  the cross thread issue is handled for you.

答: Have you tried implementing INotifyPropertyChanged?</p>

OwnerDisplayName: Brian Leahy

LastEditorDisplayName: Brian Leahy


问:
Coding Standard Wiki
At my place of work I've been put in charge of creating a coding standards document. Generally we follow what FxCop and StyleCop tools report to some degree but what we really require is document that will explain when to use a convention, why and maybe even a simple example.

This could be extended in the future for other purposes as well.

The first thing that came to my mind is to have an internal wiki site that we could build up and change easily over time but I've never used a wiki-based engine before and would like some recommendations.

If possible the engine should be in C# so we're able to tweak it to our needs if required.

If you think a wiki solution is the wrong way to go about this then please give an alternative :)

Update

I've just been informed, although we do have a php server it wont be staying, so I'm afraid php-based wiki ideas are off the table.

Update 2

Could you also (if possible) let me know if any of these solutions work with Active Directory?

Cheers
Tony

答: At the shop I'm at they use a commercial package which is really good: Confluence.  What's especially nice is that it integrates with LDAP/AD so that you don't need a seperate login and it's build especially with business use in mind and has lots of free plugins.  We couldn't live without it.</p>

Title: Coding Standard Wiki

OwnerDisplayName: TravisO


答:
```<code>def generateFromFile ( fileName ):
    for line in open( fileName ):
        for segment in line.split( ',' ):
            yield segment

for ln in generateFromFile( "input.txt" ):
    ch.Add( ln.strip() )
</code>```

Title: Reformating an external file and then saving it, from inside a python code


问:
How to exit a main sub within a called sub
I have 2 subs that look like this:
How can i stop my "main" sub if my statement is true in the sub i just called?</p>

```<code>Public Sub main()
    call run()
    more code....
End Sub

Public Sub run()
    If ProgressBar1.Value = 100 Then
        (i want to stop the code running if this statement is true, it shall not continue in my main sub.)
    End If
End Sub
</code>```

答:
You can't do it if Run() is a Sub. You need your Run() as a Function. return a Boolean indicating if you want to stop main, and call in inside an If:

```<code>Public Function run() As Boolean
    If ProgressBar1.Value = 100 Then
        Return True
    End If
    ' some more code if needed
    Return False
End Function
</code>```

Then call it in your main sub like this:

```<code>Public Sub main()
' some main code here
    If Run() Then
        Return
    End If
' The rest of main code here
End Sub
</code>```

Body:
I have 2 subs that look like this:
How can i stop my "main" sub if my statement is true in the sub i just called?

Public Sub main()
    call run()
    more code....
End Sub

Public Sub run()
    If ProgressBar1.Value = 100 Then
        (i want to stop the code running if this statement is true, it shall not continue in my main sub.)
    End If
End Sub

Body:
You can't do it if Run() is a Sub. You need your Run() as a Function. return a Boolean indicating if you want to stop main, and call in inside an If:

Public Function run() As Boolean
    If ProgressBar1.Value = 100 Then
        Return True
    End If
    ' some more code if needed
    Return False
End Function

Then call it in your main sub like this:

Public Sub main()
' some main code here
    If Run() Then
        Return
    End If
' The rest of main code here
End Sub


问:
Output is incorrect can you nest if statement into loops for array calculation?
Here is the full source code It is not outputting the correct persons that make the most and the least. My best guess is the if statement inside the loop for calculations on pay if the person makes works over 40 hours. Code is simple learning C#. What is the best way to fix this.... sorry I know this is a probably a simple issue i'm missing. COMMENTS TO LABEL

```<code>{
class Program
{
    const double FEDERAL_TAX_DEDUCTION = .10; //Federal Tax 10% of Gross Income
    const double STATE_TAX_DEDUCTION = .05;   //State Tax 5% of Gross Income
    const int    HOURS_OVERTIME = 40;         //# of Hours Needed For Overtime Pay Rate
    const double OVERTIME_PAY_DIFF = 1.5;     //150% of Normal Pay

    static void Main(string[] args)
    {
        int MAX_LIST_VALUE;  //How Many Workers There Are For Array Limit.

        Write("How Many Workers Are Currently Working? ");                  //Asks For User Input # Of Workers
        MAX_LIST_VALUE = Convert.ToInt32(ReadLine());

        string[] workerName = new string[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.Blue;
            WriteLine("Please Enter The Worker's Name: ");        //Asks For User Input For Worker's Names
            workerName[i] = ReadLine();
        }
        double[] workerWages = new double[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.DarkYellow;
            WriteLine("Please Enter " + workerName[i] + "'s Hourly Wage: "); //Asks For User Input For Worker's Wage
            workerWages[i] = Convert.ToDouble(ReadLine());
        }
        double[] workerWeeklyHours = new double[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.DarkCyan;
            Write("How Many Hours Has {0} Worked This Week? ", workerName[i]); //Asks For User Input For Hours Worked
            workerWeeklyHours[i] = Convert.ToDouble(ReadLine());
        }
        double[] workersRegularPay = new double[MAX_LIST_VALUE];
        double[] workerGrossIncome = new double[MAX_LIST_VALUE];
        double[] workerStateTaxAmount = new double[MAX_LIST_VALUE];                //All Calculation Arrays
        double[] workerFederalTaxAmount = new double[MAX_LIST_VALUE];
        double[] workerNetIncome = new double[MAX_LIST_VALUE];
        double[] workerOvertimeHours = new double[MAX_LIST_VALUE];
        double[] workerOvertimePay = new double[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            if (workerWeeklyHours[i] > HOURS_OVERTIME)                                                    //If Hours # is > 40.
            {
                workerOvertimeHours[i] = workerWeeklyHours[i] - HOURS_OVERTIME;
                workerOvertimePay[i] = workerOvertimeHours[i] * (workerWages[i] * OVERTIME_PAY_DIFF);
                workerGrossIncome[i] = workerOvertimePay[i] + workersRegularPay[i];
            }
            else
            {
                workersRegularPay[i] = workerWeeklyHours[i] * workerWages[i];
                workerGrossIncome[i] = workerWeeklyHours[i] * workerWages[i];
                workerStateTaxAmount[i] = workerGrossIncome[i] * STATE_TAX_DEDUCTION;
                workerFederalTaxAmount[i] = workerGrossIncome[i] * FEDERAL_TAX_DEDUCTION;
                workerNetIncome[i] = workerGrossIncome[i] - workerFederalTaxAmount[i] - workerStateTaxAmount[i];
                workerOvertimePay[i] = 0;
                workerOvertimeHours[i] = 0;
            }
        }
        ForegroundColor = ConsoleColor.Blue;
        WriteLine("\nNAMES ARE BLUE.");
        ForegroundColor = ConsoleColor.DarkYellow;
        WriteLine("HOURLY WAGES ARE DARK YELLOW.");
        ForegroundColor = ConsoleColor.DarkCyan;
        WriteLine("HOURS WORKED ARE DARK CYAN.");
        ForegroundColor = ConsoleColor.Green;
        WriteLine("NET INCOMES ARE GREEN.");
        ForegroundColor = ConsoleColor.Red;
        WriteLine("-----------------------------");
        WriteLine("There Are " + MAX_LIST_VALUE + " Workers!");  //Echo Of All Data Entered & Calculated For Workers
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.Blue;
            WriteLine("\nWorker's Name: " + workerName[i]);
            WriteLine("-----------------------------");
            ForegroundColor = ConsoleColor.DarkYellow;
            WriteLine(workerName[i] + "'s Hourly Wage: " + workerWages[i].ToString("C"));
            ForegroundColor = ConsoleColor.DarkCyan;
            WriteLine(workerName[i] + "'s Hours Worked This Week: " + workerWeeklyHours[i]);
            ForegroundColor = ConsoleColor.White;
            WriteLine(workerName[i] + "'s Regular Pay: " + workersRegularPay[i].ToString("C"));
            WriteLine(workerName[i] + "'s Gross Income Pay: " + workerGrossIncome[i].ToString("C"));
            WriteLine(workerName[i] + "'s State Tax Amount: " + workerStateTaxAmount[i].ToString("C"));
            WriteLine(workerName[i] + "'s Federal Tax Amount: " + workerFederalTaxAmount[i].ToString("C"));
            ForegroundColor = ConsoleColor.Green;
            WriteLine(workerName[i] + "'s Net Income: " + workerNetIncome[i].ToString("C"));
            WriteLine(workerName[i] + "'s Overtime Hours: " + workerOvertimeHours[i]);
            WriteLine(workerName[i] + "'s Overtime Pay (if any): " + workerOvertimePay[i].ToString("C"));
        }
        ForegroundColor = ConsoleColor.Red;
        WriteLine("\nPress Enter To Continue For The Worker's That Earned The Least & The Most.");
        ReadLine();

        int minIndex = 0;
        string workerLeast = "null";
        double workerRegularPayLeast = 0,
               workerGrossIncomeLeast = 0,
               workerOverTimeLeast = 0;
        int maxIndex = 0;
        string workerMost = "null";
        double workerRegularPayMost = 0,
               workerGrossIncomeMost = 0,
               workerOverTimeMost = 0;

        for (int i = 0; i < workerGrossIncome.Length; i++)         //Calculation For Worker That Made The LEAST
            if (workerGrossIncome[i] < workerGrossIncome[minIndex])
            {
                minIndex = i;
                workerLeast = workerName[i];
                workerRegularPayLeast = workersRegularPay[i];
                workerGrossIncomeLeast = workerGrossIncome[i];
                workerOverTimeLeast = workerOvertimePay[i];
            }
        for (int i = 0; i < workerGrossIncome.Length; i++)         //Calculation For Worker That Made The MOST
            if (workerGrossIncome[i] >= workerGrossIncome[maxIndex])
            {
                maxIndex = i;
                workerMost = workerName[i];
                workerRegularPayMost = workersRegularPay[i];
                workerGrossIncomeMost = workerGrossIncome[i];
                workerOverTimeLeast = workerOvertimePay[i];
            }
        ForegroundColor = ConsoleColor.Green;
        WriteLine("\nThe Worker That Earned The Least Is {0}.", workerLeast);
        WriteLine("-----------------------------");
        ForegroundColor = ConsoleColor.Magenta;
        WriteLine("{0}'s Gross Income Was {1}.", workerLeast, workerGrossIncomeLeast.ToString("C"));
        WriteLine("{0}'s Regular Pay Was {1}.", workerLeast, workerRegularPayLeast.ToString("C")); //Output For LEAST
        WriteLine("{0}'s Overtime Pay Was {1}.", workerLeast, workerOverTimeLeast.ToString("C"));
        ForegroundColor = ConsoleColor.Cyan;
        WriteLine("\nThe Worker That Earned The Most Is {0}.", workerMost);
        WriteLine("-----------------------------");
        ForegroundColor = ConsoleColor.DarkGray;
        WriteLine("{0}'s Gross Income Was {1}.", workerMost, workerGrossIncomeMost.ToString("C"));
        WriteLine("{0}'s Regular Pay Was {1}.", workerMost, workerRegularPayMost.ToString("C"));   //Output For MOST
        WriteLine("{0}'s Overtime Pay Was {1}.", workerMost, workerOverTimeMost.ToString("C"));
        ForegroundColor = ConsoleColor.Red;
        WriteLine("\nPress Enter To Exit! \nThank You!");
        ReadLine();
    }
}
</code>```

here is where i think the issue is..

```<code>for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            if (workerWeeklyHours[i] > HOURS_OVERTIME)                                                    //If Hours # is > 40.
            {
                workerOvertimeHours[i] = workerWeeklyHours[i] - HOURS_OVERTIME;
                workerOvertimePay[i] = workerOvertimeHours[i] * (workerWages[i] * OVERTIME_PAY_DIFF);
                workerGrossIncome[i] = workerOvertimePay[i] + workersRegularPay[i];
            }
            else
            {
                workersRegularPay[i] = workerWeeklyHours[i] * workerWages[i];
                workerGrossIncome[i] = workerWeeklyHours[i] * workerWages[i];
                workerStateTaxAmount[i] = workerGrossIncome[i] * STATE_TAX_DEDUCTION;
                workerFederalTaxAmount[i] = workerGrossIncome[i] * FEDERAL_TAX_DEDUCTION;
                workerNetIncome[i] = workerGrossIncome[i] - workerFederalTaxAmount[i] - workerStateTaxAmount[i];
                workerOvertimePay[i] = 0;
                workerOvertimeHours[i] = 0;
            }
</code>```

Somewhere a Logic issue
Output Is:Output end only missing console inputs and first output

答:
In your code the calculation of the GrossIncome is done differently if a worker has overtime hours or not. In case of overtime the calculation is wrong because uses a variable workersRegularPay[i] not initialized and the else block is not executed at all leaving the worker with overtime hours with incomplete data

You should change the loop that calculates the variable workerGrossIncome to this

```<code>for (int i = 0; i < MAX_LIST_VALUE; i++)
{
    // Calculate the overtime hours and pay (if any) for the current (i) worker
    if (workerWeeklyHours[i] > HOURS_OVERTIME)
    {
        workerOvertimeHours[i] = workerWeeklyHours[i] - HOURS_OVERTIME;
        workerOvertimePay[i] = workerOvertimeHours[i] * (workerWages[i] * OVERTIME_PAY_DIFF);
    }

    // Calculate the regular pay for the same worker
    // but without the overtime hours
    workersRegularPay[i] = (workerWeeklyHours[i] - workerOvertimeHours[i]) * workerWages[i];

    // Now you could sum the regular pay and the overtime pay
    workerGrossIncome[i] = workerOvertimePay[i] + workersRegularPay[i];

    // Other calcs to do for the same worker.
    workerStateTaxAmount[i] = workerGrossIncome[i] * STATE_TAX_DEDUCTION;
    workerFederalTaxAmount[i] = workerGrossIncome[i] * FEDERAL_TAX_DEDUCTION;
    workerNetIncome[i] = workerGrossIncome[i] - workerFederalTaxAmount[i] - workerStateTaxAmount[i];
}
</code>```

Body:
Here is the full source code It is not outputting the correct persons that make the most and the least. My best guess is the if statement inside the loop for calculations on pay if the person makes works over 40 hours. Code is simple learning C#. What is the best way to fix this.... sorry I know this is a probably a simple issue i'm missing. COMMENTS TO LABEL

{
class Program
{
    const double FEDERAL_TAX_DEDUCTION = .10; //Federal Tax 10% of Gross Income
    const double STATE_TAX_DEDUCTION = .05;   //State Tax 5% of Gross Income
    const int    HOURS_OVERTIME = 40;         //# of Hours Needed For Overtime Pay Rate
    const double OVERTIME_PAY_DIFF = 1.5;     //150% of Normal Pay

    static void Main(string[] args)
    {
        int MAX_LIST_VALUE;  //How Many Workers There Are For Array Limit.

        Write("How Many Workers Are Currently Working? ");                  //Asks For User Input # Of Workers
        MAX_LIST_VALUE = Convert.ToInt32(ReadLine());

        string[] workerName = new string[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.Blue;
            WriteLine("Please Enter The Worker's Name: ");        //Asks For User Input For Worker's Names
            workerName[i] = ReadLine();
        }
        double[] workerWages = new double[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.DarkYellow;
            WriteLine("Please Enter " + workerName[i] + "'s Hourly Wage: "); //Asks For User Input For Worker's Wage
            workerWages[i] = Convert.ToDouble(ReadLine());
        }
        double[] workerWeeklyHours = new double[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.DarkCyan;
            Write("How Many Hours Has {0} Worked This Week? ", workerName[i]); //Asks For User Input For Hours Worked
            workerWeeklyHours[i] = Convert.ToDouble(ReadLine());
        }
        double[] workersRegularPay = new double[MAX_LIST_VALUE];
        double[] workerGrossIncome = new double[MAX_LIST_VALUE];
        double[] workerStateTaxAmount = new double[MAX_LIST_VALUE];                //All Calculation Arrays
        double[] workerFederalTaxAmount = new double[MAX_LIST_VALUE];
        double[] workerNetIncome = new double[MAX_LIST_VALUE];
        double[] workerOvertimeHours = new double[MAX_LIST_VALUE];
        double[] workerOvertimePay = new double[MAX_LIST_VALUE];
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            if (workerWeeklyHours[i] > HOURS_OVERTIME)                                                    //If Hours # is > 40.
            {
                workerOvertimeHours[i] = workerWeeklyHours[i] - HOURS_OVERTIME;
                workerOvertimePay[i] = workerOvertimeHours[i] * (workerWages[i] * OVERTIME_PAY_DIFF);
                workerGrossIncome[i] = workerOvertimePay[i] + workersRegularPay[i];
            }
            else
            {
                workersRegularPay[i] = workerWeeklyHours[i] * workerWages[i];
                workerGrossIncome[i] = workerWeeklyHours[i] * workerWages[i];
                workerStateTaxAmount[i] = workerGrossIncome[i] * STATE_TAX_DEDUCTION;
                workerFederalTaxAmount[i] = workerGrossIncome[i] * FEDERAL_TAX_DEDUCTION;
                workerNetIncome[i] = workerGrossIncome[i] - workerFederalTaxAmount[i] - workerStateTaxAmount[i];
                workerOvertimePay[i] = 0;
                workerOvertimeHours[i] = 0;
            }
        }
        ForegroundColor = ConsoleColor.Blue;
        WriteLine("\nNAMES ARE BLUE.");
        ForegroundColor = ConsoleColor.DarkYellow;
        WriteLine("HOURLY WAGES ARE DARK YELLOW.");
        ForegroundColor = ConsoleColor.DarkCyan;
        WriteLine("HOURS WORKED ARE DARK CYAN.");
        ForegroundColor = ConsoleColor.Green;
        WriteLine("NET INCOMES ARE GREEN.");
        ForegroundColor = ConsoleColor.Red;
        WriteLine("-----------------------------");
        WriteLine("There Are " + MAX_LIST_VALUE + " Workers!");  //Echo Of All Data Entered & Calculated For Workers
        for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            ForegroundColor = ConsoleColor.Blue;
            WriteLine("\nWorker's Name: " + workerName[i]);
            WriteLine("-----------------------------");
            ForegroundColor = ConsoleColor.DarkYellow;
            WriteLine(workerName[i] + "'s Hourly Wage: " + workerWages[i].ToString("C"));
            ForegroundColor = ConsoleColor.DarkCyan;
            WriteLine(workerName[i] + "'s Hours Worked This Week: " + workerWeeklyHours[i]);
            ForegroundColor = ConsoleColor.White;
            WriteLine(workerName[i] + "'s Regular Pay: " + workersRegularPay[i].ToString("C"));
            WriteLine(workerName[i] + "'s Gross Income Pay: " + workerGrossIncome[i].ToString("C"));
            WriteLine(workerName[i] + "'s State Tax Amount: " + workerStateTaxAmount[i].ToString("C"));
            WriteLine(workerName[i] + "'s Federal Tax Amount: " + workerFederalTaxAmount[i].ToString("C"));
            ForegroundColor = ConsoleColor.Green;
            WriteLine(workerName[i] + "'s Net Income: " + workerNetIncome[i].ToString("C"));
            WriteLine(workerName[i] + "'s Overtime Hours: " + workerOvertimeHours[i]);
            WriteLine(workerName[i] + "'s Overtime Pay (if any): " + workerOvertimePay[i].ToString("C"));
        }
        ForegroundColor = ConsoleColor.Red;
        WriteLine("\nPress Enter To Continue For The Worker's That Earned The Least & The Most.");
        ReadLine();

        int minIndex = 0;
        string workerLeast = "null";
        double workerRegularPayLeast = 0,
               workerGrossIncomeLeast = 0,
               workerOverTimeLeast = 0;
        int maxIndex = 0;
        string workerMost = "null";
        double workerRegularPayMost = 0,
               workerGrossIncomeMost = 0,
               workerOverTimeMost = 0;

        for (int i = 0; i < workerGrossIncome.Length; i++)         //Calculation For Worker That Made The LEAST
            if (workerGrossIncome[i] < workerGrossIncome[minIndex])
            {
                minIndex = i;
                workerLeast = workerName[i];
                workerRegularPayLeast = workersRegularPay[i];
                workerGrossIncomeLeast = workerGrossIncome[i];
                workerOverTimeLeast = workerOvertimePay[i];
            }
        for (int i = 0; i < workerGrossIncome.Length; i++)         //Calculation For Worker That Made The MOST
            if (workerGrossIncome[i] >= workerGrossIncome[maxIndex])
            {
                maxIndex = i;
                workerMost = workerName[i];
                workerRegularPayMost = workersRegularPay[i];
                workerGrossIncomeMost = workerGrossIncome[i];
                workerOverTimeLeast = workerOvertimePay[i];
            }
        ForegroundColor = ConsoleColor.Green;
        WriteLine("\nThe Worker That Earned The Least Is {0}.", workerLeast);
        WriteLine("-----------------------------");
        ForegroundColor = ConsoleColor.Magenta;
        WriteLine("{0}'s Gross Income Was {1}.", workerLeast, workerGrossIncomeLeast.ToString("C"));
        WriteLine("{0}'s Regular Pay Was {1}.", workerLeast, workerRegularPayLeast.ToString("C")); //Output For LEAST
        WriteLine("{0}'s Overtime Pay Was {1}.", workerLeast, workerOverTimeLeast.ToString("C"));
        ForegroundColor = ConsoleColor.Cyan;
        WriteLine("\nThe Worker That Earned The Most Is {0}.", workerMost);
        WriteLine("-----------------------------");
        ForegroundColor = ConsoleColor.DarkGray;
        WriteLine("{0}'s Gross Income Was {1}.", workerMost, workerGrossIncomeMost.ToString("C"));
        WriteLine("{0}'s Regular Pay Was {1}.", workerMost, workerRegularPayMost.ToString("C"));   //Output For MOST
        WriteLine("{0}'s Overtime Pay Was {1}.", workerMost, workerOverTimeMost.ToString("C"));
        ForegroundColor = ConsoleColor.Red;
        WriteLine("\nPress Enter To Exit! \nThank You!");
        ReadLine();
    }
}

here is where i think the issue is..

for (int i = 0; i < MAX_LIST_VALUE; i++)
        {
            if (workerWeeklyHours[i] > HOURS_OVERTIME)                                                    //If Hours # is > 40.
            {
                workerOvertimeHours[i] = workerWeeklyHours[i] - HOURS_OVERTIME;
                workerOvertimePay[i] = workerOvertimeHours[i] * (workerWages[i] * OVERTIME_PAY_DIFF);
                workerGrossIncome[i] = workerOvertimePay[i] + workersRegularPay[i];
            }
            else
            {
                workersRegularPay[i] = workerWeeklyHours[i] * workerWages[i];
                workerGrossIncome[i] = workerWeeklyHours[i] * workerWages[i];
                workerStateTaxAmount[i] = workerGrossIncome[i] * STATE_TAX_DEDUCTION;
                workerFederalTaxAmount[i] = workerGrossIncome[i] * FEDERAL_TAX_DEDUCTION;
                workerNetIncome[i] = workerGrossIncome[i] - workerFederalTaxAmount[i] - workerStateTaxAmount[i];
                workerOvertimePay[i] = 0;
                workerOvertimeHours[i] = 0;
            }

Somewhere a Logic issue
Output Is:Output end only missing console inputs and first output

Body:
In your code the calculation of the GrossIncome is done differently if a worker has overtime hours or not. In case of overtime the calculation is wrong because uses a variable workersRegularPay[i] not initialized and the else block is not executed at all leaving the worker with overtime hours with incomplete data

You should change the loop that calculates the variable workerGrossIncome to this

for (int i = 0; i < MAX_LIST_VALUE; i++)
{
    // Calculate the overtime hours and pay (if any) for the current (i) worker
    if (workerWeeklyHours[i] > HOURS_OVERTIME)
    {
        workerOvertimeHours[i] = workerWeeklyHours[i] - HOURS_OVERTIME;
        workerOvertimePay[i] = workerOvertimeHours[i] * (workerWages[i] * OVERTIME_PAY_DIFF);
    }

    // Calculate the regular pay for the same worker
    // but without the overtime hours
    workersRegularPay[i] = (workerWeeklyHours[i] - workerOvertimeHours[i]) * workerWages[i];

    // Now you could sum the regular pay and the overtime pay
    workerGrossIncome[i] = workerOvertimePay[i] + workersRegularPay[i];

    // Other calcs to do for the same worker.
    workerStateTaxAmount[i] = workerGrossIncome[i] * STATE_TAX_DEDUCTION;
    workerFederalTaxAmount[i] = workerGrossIncome[i] * FEDERAL_TAX_DEDUCTION;
    workerNetIncome[i] = workerGrossIncome[i] - workerFederalTaxAmount[i] - workerStateTaxAmount[i];
}


问:
I'm in a beginner's Python course, and my assignment is to print variable 'N' backwards using a 'while' statement
Here are my instructions:

We will pass you a value, N. You should output every positive value from N down to and including 0.

And here is my assignment:

```<code>    # Get N from the command line
    import sys
    N = int(sys.argv[1])

    # Your code goes here
    counter = 0
    while counter <= N:
     print(counter-N)
     counter = counter + 1
</code>```

My solution prints this:

```<code>Program Output

Program Failed for Input: 3
Expected Output: 3
2
1
0
Your Program Output: -3
-2
-1
0
</code>```

As you can see, I got the output to show -3, -2, -1, 0, but it should be 3, 2, 1, 0. Please be mindful that I am a beginner, and my code must pass using a 'while' statement, and my code must be inputted in Codio. Thank you in advance for any assistance rendered.

答:
Just pass counter-N to the abs function:

```<code>while counter <= N:
  print(abs(counter-N))
  counter = counter + 1
</code>```

Or, just use N-counter:

```<code>while counter <= N:
 print(N-counter)
 counter = counter + 1
</code>```

Body:
Here are my instructions:

We will pass you a value, N. You should output every positive value from N down to and including 0.

And here is my assignment:

    # Get N from the command line
    import sys
    N = int(sys.argv[1])

    # Your code goes here
    counter = 0
    while counter <= N:
     print(counter-N)
     counter = counter + 1

My solution prints this:

Program Output

Program Failed for Input: 3
Expected Output: 3
2
1
0
Your Program Output: -3
-2
-1
0

As you can see, I got the output to show -3, -2, -1, 0, but it should be 3, 2, 1, 0. Please be mindful that I am a beginner, and my code must pass using a 'while' statement, and my code must be inputted in Codio. Thank you in advance for any assistance rendered.

Body:
Just pass counter-N to the abs function:

while counter <= N:
  print(abs(counter-N))
  counter = counter + 1

Or, just use N-counter:

while counter <= N:
 print(N-counter)
 counter = counter + 1


问:
Convert a simple train/test into train/test over a batch
I am using Recurrent NN to generate a classification model. The following is a simple RNN model that uses keras (Courtesy to this blog):

```<code>tr_C, ts_C, tr_r, ts_r = train_test_split(C, r, train_size=.8)
tr_C = tr_C.reshape((tr_C.shape[0], tr_C.shape[1], 1))
ts_C = ts_C.reshape((ts_C.shape[0], ts_C.shape[1], 1))
tr_r = tr_r.reshape(tr_r.shape[0], 1)
ts_r = ts_r.reshape(ts_r.shape[0], 1)

print('Build model...')
model = Sequential()
model.add(LSTM(16,
               batch_input_shape=(1, 1, 1),
               activation='tanh',
               recurrent_activation='tanh',
               kernel_initializer='he_uniform',
               bias_initializer='he_uniform',
               # dropout=0.1,
               # recurrent_dropout=0.1,
               stateful=True,
               return_sequences=False,
               )
          )
model.add(Dense(1, activation='tanh'))
model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])

for epoch in range(10):
    print ('epoch(%s): ' % epoch)
    mean_tr_acc = []
    mean_tr_loss = []
    for i in range(len(tr_C)):
        for j in range(max_len):
            tr_loss, tr_acc = model.train_on_batch(np.expand_dims(np.expand_dims(tr_C[i][j], axis=1), axis=1), tr_r[i])
            mean_tr_acc.append(tr_acc)
            mean_tr_loss.append(tr_loss)
        model.reset_states()

    print('training_acc = {}'.format(np.mean(mean_tr_acc)))
    print('loss training = {}'.format(np.mean(mean_tr_loss)))
    print('___________________________________')

    mean_te_acc = []
    mean_te_loss = []
    for i in range(len(ts_C)):
        for j in range(max_len):
            te_loss, te_acc = model.test_on_batch(np.expand_dims(np.expand_dims(ts_C[i][j], axis=1), axis=1), ts_r[i])
            mean_te_acc.append(te_acc)
            mean_te_loss.append(te_loss)
        model.reset_states()

        for j in range(max_len):
            y_pred = model.predict_on_batch(np.expand_dims(np.expand_dims(ts_C[i][j], axis=1), axis=1))
        model.reset_states()

    print('testing_acc = {}'.format(np.mean(mean_te_acc)))
    print('loss testing = {}'.format(np.mean(mean_te_loss)))
    print('___________________________________')
</code>```

This is the summary of the model:

```<code>Layer (type)                 Output Shape              Param #
=================================================================
lstm_1 (LSTM)                (1, 16)                   1152
_________________________________________________________________
dense_1 (Dense)              (1, 1)                    17
=================================================================
Total params: 1,169
Trainable params: 1,169
Non-trainable params: 0
_________________________________________________________________
</code>```

Instead of training a single sample at a time, can I modify this code to train a batch of samples? If so, how? Any suggestions are appreciated
Thank you.

答:
You declared here:

```<code>model.add(LSTM(16,
               batch_input_shape=(1, 1, 1),
               activation='tanh',
               recurrent_activation='tanh',
               kernel_initializer='he_uniform',
               bias_initializer='he_uniform',
               # dropout=0.1,
               # recurrent_dropout=0.1,
               stateful=True,
               return_sequences=False,
               )
          )
</code>```

that the size of your batch should be: (1,1,1) meaning 1 example only, with 1 timestamp and each timestamp is scalar.

If you want more than 1 training example you should do:

```<code>batch_input_shape=(None,1,1)
</code>```

or, change None to the number of examples in the batch.

(None means you can insert how many example as you wish)

Body:
I am using Recurrent NN to generate a classification model. The following is a simple RNN model that uses keras (Courtesy to this blog):

tr_C, ts_C, tr_r, ts_r = train_test_split(C, r, train_size=.8)
tr_C = tr_C.reshape((tr_C.shape[0], tr_C.shape[1], 1))
ts_C = ts_C.reshape((ts_C.shape[0], ts_C.shape[1], 1))
tr_r = tr_r.reshape(tr_r.shape[0], 1)
ts_r = ts_r.reshape(ts_r.shape[0], 1)

print('Build model...')
model = Sequential()
model.add(LSTM(16,
               batch_input_shape=(1, 1, 1),
               activation='tanh',
               recurrent_activation='tanh',
               kernel_initializer='he_uniform',
               bias_initializer='he_uniform',
               # dropout=0.1,
               # recurrent_dropout=0.1,
               stateful=True,
               return_sequences=False,
               )
          )
model.add(Dense(1, activation='tanh'))
model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])

for epoch in range(10):
    print ('epoch(%s): ' % epoch)
    mean_tr_acc = []
    mean_tr_loss = []
    for i in range(len(tr_C)):
        for j in range(max_len):
            tr_loss, tr_acc = model.train_on_batch(np.expand_dims(np.expand_dims(tr_C[i][j], axis=1), axis=1), tr_r[i])
            mean_tr_acc.append(tr_acc)
            mean_tr_loss.append(tr_loss)
        model.reset_states()

    print('training_acc = {}'.format(np.mean(mean_tr_acc)))
    print('loss training = {}'.format(np.mean(mean_tr_loss)))
    print('___________________________________')

    mean_te_acc = []
    mean_te_loss = []
    for i in range(len(ts_C)):
        for j in range(max_len):
            te_loss, te_acc = model.test_on_batch(np.expand_dims(np.expand_dims(ts_C[i][j], axis=1), axis=1), ts_r[i])
            mean_te_acc.append(te_acc)
            mean_te_loss.append(te_loss)
        model.reset_states()

        for j in range(max_len):
            y_pred = model.predict_on_batch(np.expand_dims(np.expand_dims(ts_C[i][j], axis=1), axis=1))
        model.reset_states()

    print('testing_acc = {}'.format(np.mean(mean_te_acc)))
    print('loss testing = {}'.format(np.mean(mean_te_loss)))
    print('___________________________________')

This is the summary of the model:

Layer (type)                 Output Shape              Param #
=================================================================
lstm_1 (LSTM)                (1, 16)                   1152
_________________________________________________________________
dense_1 (Dense)              (1, 1)                    17
=================================================================
Total params: 1,169
Trainable params: 1,169
Non-trainable params: 0
_________________________________________________________________

Instead of training a single sample at a time, can I modify this code to train a batch of samples? If so, how? Any suggestions are appreciated
Thank you.

Body:
You declared here:

model.add(LSTM(16,
               batch_input_shape=(1, 1, 1),
               activation='tanh',
               recurrent_activation='tanh',
               kernel_initializer='he_uniform',
               bias_initializer='he_uniform',
               # dropout=0.1,
               # recurrent_dropout=0.1,
               stateful=True,
               return_sequences=False,
               )
          )

that the size of your batch should be: (1,1,1) meaning 1 example only, with 1 timestamp and each timestamp is scalar.

If you want more than 1 training example you should do:

batch_input_shape=(None,1,1)

or, change None to the number of examples in the batch.

(None means you can insert how many example as you wish)