问:
Calling DialogFragment in Fragment Kotlin
I'm trying to call my dialogfragment into my loginfragment and show an alert dialog box, the show method says that:

None of the following functions can be called with the arguments
  supplied. show(FragmentManager!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment
  show(FragmentTransaction!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment

```<code>val newFragment = CustomDialogFragment.newInstance("pass content here")

val fm = fragmentManager
newFragment.show(fm, "look")
</code>```

Here is my CustomDialogFragment code:

```<code>import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenstand.android.TreeTracker.R
import org.greenstand.android.TreeTracker.application.Permissions
import org.greenstand.android.TreeTracker.utilities.*
import org.greenstand.android.TreeTracker.viewmodels.LoginViewModel
import org.koin.android.viewmodel.ext.android.viewModel
import timber.log.Timber
class CustomDialogFragment : DialogFragment()
{
    private var content: String? = null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        content = arguments!!.getString("content")

        val style = DialogFragment.STYLE_NO_FRAME
        val theme = R.style.DialogTheme
        setStyle(style, theme)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle): View
    {
        val view = inflater!!.inflate(R.layout.layout_dialog, container, false)

        val btnAccept = view.findViewById<View>(R.id.buttonAccept) as Button

        val textViewContent = view.findViewById<View>(R.id.textViewContent) as TextView
        textViewContent.text = content;

        btnAccept.setOnClickListener{
            dismiss();
        }

        return view;
    }

    companion object
    {
        fun newInstance(content: String) : CustomDialogFragment
        {
            val f = CustomDialogFragment()

            val args = Bundle()
            args.putString("content", content)
            f.arguments = args

            return f
        }
    }

}
</code>```

Can someone indicate what exactly I need to pass into the show method? Any help is appreciated, thanks :)

答:
[UPDATE]
The problem is the method can receive a FragmentManager but it has to be not null, take a look at the error and the not nullable Kotlin symbol

FragmentManager!!

So you can do

```<code>fm?.let {newFragment.show(fm, "your tag")}
//fm here can also be it
</code>```

Please see the comments in the Noushad Hasan answer

You are passing the FragmentManager to the method, it needs the FragmentTransaction and a String as a tag:

```<code>val transaction = supportFragmentManager.beginTransaction()
newFragment.show(transaction, "SOME_TAG")
</code>```

A couple of suggestions:

You can make you DialogFragment more kotliny by using the Kotlin standard functions

```<code>companion object {

        private const val KEY = "param1"

        @JvmStatic
        fun newInstance(param1: String) =
            ExampleDialogFragment().apply {
                arguments = bundleOf(KEY to param1)
            }
    }
</code>```

You can get a good example by creating a Fragment using the Android Studio wizard and checking the factory method option.

Also, since the tag is gonna be for your DialogFragment you could make it a public constant:

```<code> companion object {
        const val TAG = "TAG"
 }
</code>```

And maybe you want to double check if the dialog fragment is already present and remove it, to actually work as a fresh dialog

```<code>        val transaction = supportFragmentManager.beginTransaction()
        val previous = supportFragmentManager.findFragmentByTag(ExampleDialogFragment.TAG)
        if (previous != null) {
            transaction.remove(previous)
        }
        transaction.addToBackStack(null)

        val dialogFragment = ExampleDialogFragment.newInstance("parameter")
        dialogFragment.show(transaction, ExampleDialogFragment.TAG)
</code>```

Body:
I'm trying to call my dialogfragment into my loginfragment and show an alert dialog box, the show method says that:

None of the following functions can be called with the arguments
  supplied. show(FragmentManager!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment
  show(FragmentTransaction!, String!) defined in
  org.greenstand.android.TreeTracker.fragments.CustomDialogFragment

val newFragment = CustomDialogFragment.newInstance("pass content here")

val fm = fragmentManager
newFragment.show(fm, "look")

Here is my CustomDialogFragment code:

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenstand.android.TreeTracker.R
import org.greenstand.android.TreeTracker.application.Permissions
import org.greenstand.android.TreeTracker.utilities.*
import org.greenstand.android.TreeTracker.viewmodels.LoginViewModel
import org.koin.android.viewmodel.ext.android.viewModel
import timber.log.Timber
class CustomDialogFragment : DialogFragment()
{
    private var content: String? = null

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        content = arguments!!.getString("content")

        val style = DialogFragment.STYLE_NO_FRAME
        val theme = R.style.DialogTheme
        setStyle(style, theme)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle): View
    {
        val view = inflater!!.inflate(R.layout.layout_dialog, container, false)

        val btnAccept = view.findViewById<View>(R.id.buttonAccept) as Button

        val textViewContent = view.findViewById<View>(R.id.textViewContent) as TextView
        textViewContent.text = content;

        btnAccept.setOnClickListener{
            dismiss();
        }

        return view;
    }

    companion object
    {
        fun newInstance(content: String) : CustomDialogFragment
        {
            val f = CustomDialogFragment()

            val args = Bundle()
            args.putString("content", content)
            f.arguments = args

            return f
        }
    }

}

Can someone indicate what exactly I need to pass into the show method? Any help is appreciated, thanks :)

Body:
[UPDATE]
The problem is the method can receive a FragmentManager but it has to be not null, take a look at the error and the not nullable Kotlin symbol

FragmentManager!!

So you can do

fm?.let {newFragment.show(fm, "your tag")}
//fm here can also be it

Please see the comments in the Noushad Hasan answer

You are passing the FragmentManager to the method, it needs the FragmentTransaction and a String as a tag:

val transaction = supportFragmentManager.beginTransaction()
newFragment.show(transaction, "SOME_TAG")

A couple of suggestions:

You can make you DialogFragment more kotliny by using the Kotlin standard functions

companion object {

        private const val KEY = "param1"

        @JvmStatic
        fun newInstance(param1: String) =
            ExampleDialogFragment().apply {
                arguments = bundleOf(KEY to param1)
            }
    }

You can get a good example by creating a Fragment using the Android Studio wizard and checking the factory method option.

Also, since the tag is gonna be for your DialogFragment you could make it a public constant:

 companion object {
        const val TAG = "TAG"
 }

And maybe you want to double check if the dialog fragment is already present and remove it, to actually work as a fresh dialog

        val transaction = supportFragmentManager.beginTransaction()
        val previous = supportFragmentManager.findFragmentByTag(ExampleDialogFragment.TAG)
        if (previous != null) {
            transaction.remove(previous)
        }
        transaction.addToBackStack(null)

        val dialogFragment = ExampleDialogFragment.newInstance("parameter")
        dialogFragment.show(transaction, ExampleDialogFragment.TAG)


来源: stackexchange

问:
How to add property to a class dynamically?
The goal is to create a mock class which behaves like a db resultset.

So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would like to see:

```<code>>>> dummy.ab
100
</code>```

At first I thought maybe I could do it this way:

```<code>ks = ['ab', 'cd']
vs = [12, 34]
class C(dict):
    def __init__(self, ks, vs):
        for i, k in enumerate(ks):
            self[k] = vs[i]
            setattr(self, k, property(lambda x: vs[i], self.fn_readyonly))

    def fn_readonly(self, v)
        raise "It is ready only"

if __name__ == "__main__":
    c = C(ks, vs)
    print c.ab
</code>```

but c.ab returns a property object instead.

Replacing the setattr line with k = property(lambda x: vs[i]) is of no use at all.

So what is the right way to create an instance property at runtime?

P.S. I am aware of an alternative presented in How is the __getattribute__ method used?

答:
Something that works for me is this:

```<code>class C:
    def __init__(self):
        self._x=None

    def g(self):
        return self._x

    def s(self, x):
        self._x = x

    def d(self):
        del self._x

    def s2(self,x):
        self._x=x+x

    x=property(g,s,d)

c = C()
c.x="a"
print(c.x)

C.x=property(C.g, C.s2)
C.x=C.x.deleter(C.d)
c2 = C()
c2.x="a"
print(c2.x)
</code>```

Output

```<code>a
aa
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The goal is to create a mock class which behaves like a db resultset.

So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would like to see:

>>> dummy.ab
100

At first I thought maybe I could do it this way:

ks = ['ab', 'cd']
vs = [12, 34]
class C(dict):
    def __init__(self, ks, vs):
        for i, k in enumerate(ks):
            self[k] = vs[i]
            setattr(self, k, property(lambda x: vs[i], self.fn_readyonly))

    def fn_readonly(self, v)
        raise "It is ready only"

if __name__ == "__main__":
    c = C(ks, vs)
    print c.ab

but c.ab returns a property object instead.

Replacing the setattr line with k = property(lambda x: vs[i]) is of no use at all.

So what is the right way to create an instance property at runtime?

P.S. I am aware of an alternative presented in How is the __getattribute__ method used?

Body:
Something that works for me is this:

class C:
    def __init__(self):
        self._x=None

    def g(self):
        return self._x

    def s(self, x):
        self._x = x

    def d(self):
        del self._x

    def s2(self,x):
        self._x=x+x

    x=property(g,s,d)

c = C()
c.x="a"
print(c.x)

C.x=property(C.g, C.s2)
C.x=C.x.deleter(C.d)
c2 = C()
c2.x="a"
print(c2.x)

Output

a
aa

ContentLicense: CC BY-SA 4.0


问:
How can I add an attribute of type NG to a Div
I have a component where I use #gmap, except that the div where it is located I have it saved in a json, therefore it does not recognize me #gmap. If I insert it directly in the html file of the component, it recognizes me without problems.

I have tried adding a new attribute to the div from code, example: document.getElementById ('myDiv'). SetAttribute ('# gmap', '');
but I did not succeed.

In my Json I have a property with this text

```

<p>But when compiling, I am geting this error:</p>

```ERROR TypeError: Cannot read property 'innerHTML' of null at ...
```

<p>Since the way to add a #NG from a string is not correct, does someone know how to add it from code?
Example: </p>

```myDiv.setNg ('# gmap')
```

答:
You pose an interesting question. My understanding of template variables (the #gmap or #something that you plug into an element) are that they are an Angular creation and so can't be programatically edited through JavaScript API's (and I know of no Angular methods to do so either). They are also static variables, so they can't be re-named.

A work-around I can think of if you're going down this route is to switch to using plane JavaScript id's. So instead of #gmap, you would just use id="gmap".

Wish I could be more helpful. Good luck!

Body:
I have a component where I use #gmap, except that the div where it is located I have it saved in a json, therefore it does not recognize me #gmap. If I insert it directly in the html file of the component, it recognizes me without problems.

I have tried adding a new attribute to the div from code, example: document.getElementById ('myDiv'). SetAttribute ('# gmap', '');
but I did not succeed.

In my Json I have a property with this text

But when compiling, I am geting this error:

ERROR TypeError: Cannot read property 'innerHTML' of null at ...

Since the way to add a #NG from a string is not correct, does someone know how to add it from code?
Example:

myDiv.setNg ('# gmap')


问:
SQL Server 2008 subquery using NOT IN
stuck on a problem, can't seem to code the query correctly, help please

here's the question

Write a SELECT statement that returns the name, city, and state of each vendor that's located in a unique city and state. In other words, don't include vendors that have a city and state in common with another vendor.

Sort the result set by VendorState, VendorCity

Use NOT IN subquery.  The expression VendorState + VendorCity should be used in WHERE, (subquery SELECT, GROUP BY) clauses.  The HAVING clause controls the results of duplicate city+state.  Execute the subquery from the basic, and add one clause each time to compare the results.

Outer query – display all vendors NOT IN

Inner query - duplicate city+state vendors

Table:
Vendors
Columns:
VendorName,VendorState,VendorCity

答:
Well the inner query must return a combined string of city and state (really stupid way of doing it)
so that would be

```<code>SELECT VendorCity + VendorState
FROM   Vendors
GROUP BY VendorCity, VendorState
HAVING COUNT(*) > 1
</code>```

And the outer query simply needs to say where it's not in the list.

```<code>Select *
FROM Venders
WHERE VendorCity + VendorState
     NOT IN
   (SELECT VendorCity + VendorState
    FROM   Vendors
    GROUP BY VendorCity, VendorState
    HAVING COUNT(*) > 1 )
ORDER BY VendorState, VendorCity
</code>```

Title: SQL Server 2008 subquery using NOT IN

Body:
Well the inner query must return a combined string of city and state (really stupid way of doing it)
so that would be

SELECT VendorCity + VendorState
FROM   Vendors
GROUP BY VendorCity, VendorState
HAVING COUNT(*) > 1

And the outer query simply needs to say where it's not in the list.

Select *
FROM Venders
WHERE VendorCity + VendorState
     NOT IN
   (SELECT VendorCity + VendorState
    FROM   Vendors
    GROUP BY VendorCity, VendorState
    HAVING COUNT(*) > 1 )
ORDER BY VendorState, VendorCity


问:
REST resources for a login/registration form
I want to create REST login/registration URI in order to make a an existing user login or a new user to register. After a little search I found that most of such forms are designed using the following rules:

GET /login to get the login resource

POST /login to login and get back the user profile resource

GET /register to get the registration resource

POST /register to register and get back the new user profile resource

However, I think that this is not a 100% REST approach as one of the rules of REST is that resources should be nouns and not verbs (except from some special cases like a search api). What's the best solution for such a situation ?

答:
There's no one right answer to this, so I'll attempt to give some ideas on a common ways to solve this.

Login

Login (aka Authentication) itself is typically handled in a non RESTful way, ourside, such as OAuth2. Should there really be a 'login' if HTTP is stateless? Every request should carry all the information to allow a server to authenticate the client. If you do want to really handle login as a RESTful endpoint, you could ask yourself: "What state am I changing? One way to answer this is that maybe you a creating a set of credentials". I'm assuming for now that you are looking for a best practice / common approach to this though, and not a very purist REST approach for this.

Current user information

Getting the current user is often handled via an endpoint such as /current-user or /whoami. Doing a GET request on this could either yield information about the user, or it could immediately redirect to a canonical user endpoint such as /users/1234. Executing a PUT request could again either update the user, or return a redirect to the actual user endpoint.

Registration

If you have a list of users on a resource like /users. It would kind of make sense to create a new user resource by doing a POST request on this collection.


问:
Why is a parentheses not needed in removeItem? Why must li.onclick = removeItem be inside the newItem() function?

Why do I not need parentheses for removeItem?

Why must li.onclick = removeItem be inside the newItem() function?

What is the logical sequence when li.onclick event occurs? Is newItem() executed? If so how is it triggered?

I thought that only the enter key will trigger newItem() and since li.onclick = removeItem is inside newItem(), why does clicking trigger it?

Disclaimer: I found this code online but I don't understand these details, hope you guys can help out. Thanks!

html

<input id="input" placeholder="What needs to be done?">

```

<p>javascript</p>

```        function newItem() {
            var item = document.getElementById("input").value;
            var ul = document.getElementById("list");
            var li = document.createElement("li");
            if (document.getElementById("input").value != ""){
                li.appendChild(document.createTextNode(item));
                ul.appendChild(li);
                document.getElementById("input").value = "";
            }
            li.onclick = removeItem;
        }

        document.body.onkeyup = function(e) {
          if (e.keyCode == 13) {
            newItem();
          }
        }

        function removeItem(e) {
            e.target.parentElement.removeChild(e.target);
        }
```

答:
Why do I not need a parentheses for removeItem?

I assume you mean this line of code:

```<code>li.onclick = removeItem;
</code>```

Because parentheses would invoke the function and assign its result to li.onclick.  The function doesn't return anything and has no result, and invoking it without providing the event argument it expects would result in an error.

Instead of invoking the function, you're assigning a reference to the function as the onclick event handler for the li object.  At a later time, if a user clicks on that element, then the function will be invoked.

Why must li.onclick = removeItem be inside the newItem() function?

Well, because that's where the li variable is.  You can assign an onclick handler anywhere you like, but in order to assign it to a specific object then you need to be in a scope where you have a reference to that object.  Outside of that function there is no li variable, so that line of code wouldn't make sense.

What is the logical sequence when li.onclick event occurs? Is newItem() executed? If so how is it triggered?

Nope, removeItem() is executed.  And the browser provides it with a reference to the click event, which will be in the e variable inside that function.  This allows you to reference e.target to find the element which was clicked.

removeItem() is triggered because of the reference assigned to li.onclick in the first question above.

Body:
Why do I not need parentheses for removeItem?

Why must li.onclick = removeItem be inside the newItem() function?

What is the logical sequence when li.onclick event occurs? Is newItem() executed? If so how is it triggered?

I thought that only the enter key will trigger newItem() and since li.onclick = removeItem is inside newItem(), why does clicking trigger it?

Disclaimer: I found this code online but I don't understand these details, hope you guys can help out. Thanks!

html

<input id="input" placeholder="What needs to be done?">

javascript

        function newItem() {
            var item = document.getElementById("input").value;
            var ul = document.getElementById("list");
            var li = document.createElement("li");
            if (document.getElementById("input").value != ""){
                li.appendChild(document.createTextNode(item));
                ul.appendChild(li);
                document.getElementById("input").value = "";
            }
            li.onclick = removeItem;
        }

        document.body.onkeyup = function(e) {
          if (e.keyCode == 13) {
            newItem();
          }
        }

        function removeItem(e) {
            e.target.parentElement.removeChild(e.target);
        }

Body:
Why do I not need a parentheses for removeItem?

I assume you mean this line of code:

li.onclick = removeItem;

Because parentheses would invoke the function and assign its result to li.onclick.  The function doesn't return anything and has no result, and invoking it without providing the event argument it expects would result in an error.

Instead of invoking the function, you're assigning a reference to the function as the onclick event handler for the li object.  At a later time, if a user clicks on that element, then the function will be invoked.

Why must li.onclick = removeItem be inside the newItem() function?

Well, because that's where the li variable is.  You can assign an onclick handler anywhere you like, but in order to assign it to a specific object then you need to be in a scope where you have a reference to that object.  Outside of that function there is no li variable, so that line of code wouldn't make sense.

What is the logical sequence when li.onclick event occurs? Is newItem() executed? If so how is it triggered?

Nope, removeItem() is executed.  And the browser provides it with a reference to the click event, which will be in the e variable inside that function.  This allows you to reference e.target to find the element which was clicked.

removeItem() is triggered because of the reference assigned to li.onclick in the first question above.


问:
React-Native install on Windows Machine not finding $PATH
I'm installing react-native first y installing react-native-cli

Based on the instructions at: https://facebook.github.io/react-native/docs/getting-started.html...

I installed Android Studio and then added the sdk path to my $PATH, so if I echo $PATH, the path

```<code>/c/Users/MyUser/AppData/Local/Android/Sdk/platform-tools
</code>```

is included. Then I...

```<code>npm install -g react-native-cli
</code>```

which resulted in

```<code>C:\Users\MyUser\AppData\Roaming\npm\react-native ->
C:\Users\MyUser\AppData\Roaming\npm\node_modules\react-native-cli\index.js
+ react-native-cli@2.0.1
updated 1 package in 2.303s
</code>```

but it is still not finding react-native ...

```<code>react-native-cli --version
bash: react-native-cli: command not found
</code>```

Why can't I find my react-native-install?

答:
react-native-cli is not a command. With this npm i -g react-native-cli you can use the command -> react-native
you can now use react-native init "project"
then npm start </p>

Body:
I'm installing react-native first y installing react-native-cli

Based on the instructions at: https://facebook.github.io/react-native/docs/getting-started.html...

I installed Android Studio and then added the sdk path to my $PATH, so if I echo $PATH, the path

/c/Users/MyUser/AppData/Local/Android/Sdk/platform-tools

is included. Then I...

npm install -g react-native-cli

which resulted in

C:\Users\MyUser\AppData\Roaming\npm\react-native ->
C:\Users\MyUser\AppData\Roaming\npm\node_modules\react-native-cli\index.js
+ react-native-cli@2.0.1
updated 1 package in 2.303s

but it is still not finding react-native ...

react-native-cli --version
bash: react-native-cli: command not found

Why can't I find my react-native-install?


问:
How to name tkinter entry widgets created from a for loop?
I am new to python and tkinter, so I am having trouble with naming entry widgets that are created inside a for loop.  The goal is for my GUI to solve the user's linear programming optimization problem for fun.  I first ask the user how many variables there are in their problem, lets say n variables is inputted.  Then I create a for loop that creates n entry widgets corresponding to each variable to store the coefficient value of that variable.  I know how to create a single entry widget and name it so I can access it via name.get().  In my code, I tried to create a string name = "x" + str(i) where i is the for loop incrementing variable.  But then when I for example call x1.get() I get an error that x1 is not defined.  How do I fix this?  And thanks for the help in advance.

import tkinter as tkr

def objCos():
    x1Co = x1.get()
    print(x1Co)

def objFunction():
    global varFrame

    numOfVars = ofEntry.get()
    numOfVars = int(numOfVars)

    varFrame.destroy()
    varFrame = tkr.Frame(root)
    varFrame.pack(side = tkr.BOTTOM)

    varLabel = tkr.Label(varFrame, text = "Enter Objective Function Coefficients: ")
    varLabel.grid(row = 0, columnspan = 2)

    for i in range(1,numOfVars+1):
        strName = 'x' + str(i)
        strName = tkr.Entry(varFrame)
        strName.grid(row = i, column = 1)

        lbName = "varLabel" + str(i)
        lbName = tkr.Label(varFrame, text = "x"+ str(i) + " = ")
        lbName.grid(row = i, column = 0)

    varButton = tkr.Button(varFrame, text = "Update Objective Function Coefficients",
                           bg = "light grey", command = objCos)
    varButton.grid(row = numOfVars + 1, columnspan = 2)

root = tkr.Tk()

ofFrame = tkr.Frame(root)
ofFrame.pack(side = tkr.TOP)

global varFrame
varFrame = tkr.Frame(root)
varFrame.pack(side = tkr.BOTTOM)

ofLabel = tkr.Label(ofFrame, text = "Enter Number of Variables: ")
ofLabel.grid(row = 0, column = 0)

ofEntry = tkr.Entry(ofFrame)
ofEntry.grid(row =0, column = 1)

ofButton = tkr.Button(ofFrame, text = "Update Number of Variables",
                      bg = "light grey", command = objFunction)
ofButton.grid(row = 1, columnspan = 2)

root.mainloop()
```

答:
For example, you can use simple structure to hold that vidgets, here is a example in one of mine old functions :)

Like there, self.creation_panel is a dict.

```<code>def creation_view(self, core_line, skills_line):
#### Navigate functions for main menu          ####
    def set_navigate(self, arg):
        self.navigate = arg

#### Configurations for create interference    ####
    self.configure_grid_x(20)
    self.configure_grid_y(5)
    row = 0
    col = 0

#### Create body of view                       ####
    for txt in core_line:
        if col == 12:
            col = 0
            row += 1
        self.creation_panel[txt] = Button(self.frame, text=txt, command=lambda cls=self, arg=txt: set_navigate(cls, arg))
        self.creation_panel[txt].grid(row=row, column=col, columnspan=3, sticky=NSEW)
        col += 3

    for txt in skills_line:
        if col == 12:
            col = 0
            row += 1
        self.creation_panel[txt] = Button(self.frame, text=txt, state=DISABLED, command=lambda cls=self, arg=txt: set_navigate(cls, arg))
        self.creation_panel[txt].grid(row=row, column=col, columnspan=4, sticky=NSEW)
        col += 4

    self.creation_panel["Preview"] = Button(self.frame, text="Preview", command=lambda cls=self: set_navigate(cls, "Preview"))
    self.creation_panel["Preview"].grid(row=row+1, column=0, columnspan=12, sticky=NSEW)

    self.preview_window1 = Label(self.frame, text="", justify=LEFT)
    self.preview_window1.grid(row=0, rowspan=5, column=12, columnspan=4, sticky=NSEW)
    self.preview_window1.config(state='disabled', relief=SUNKEN)

    self.preview_window2 = Label(self.frame, text="", justify=LEFT)
    self.preview_window2.grid(row=0, rowspan=5, column=16, columnspan=4, sticky=NSEW)
    self.preview_window2.config(state='disabled', relief=SUNKEN)

    self.frame.pack(side=LEFT, fill=BOTH, expand=1)
</code>```

Maybe it isn't a the best way, and some other will correct me. But there is a one of possible ways.

self.navigate variable was used for navigation becouse that class represents only view in MVC model of GUI :). If it has changed, then from controller is sended signal, get new model and called new view. Or somesimilar way, i don't clearly remember that old project.

Body:
For example, you can use simple structure to hold that vidgets, here is a example in one of mine old functions :)

Like there, self.creation_panel is a dict.

def creation_view(self, core_line, skills_line):
#### Navigate functions for main menu          ####
    def set_navigate(self, arg):
        self.navigate = arg

#### Configurations for create interference    ####
    self.configure_grid_x(20)
    self.configure_grid_y(5)
    row = 0
    col = 0

#### Create body of view                       ####
    for txt in core_line:
        if col == 12:
            col = 0
            row += 1
        self.creation_panel[txt] = Button(self.frame, text=txt, command=lambda cls=self, arg=txt: set_navigate(cls, arg))
        self.creation_panel[txt].grid(row=row, column=col, columnspan=3, sticky=NSEW)
        col += 3

    for txt in skills_line:
        if col == 12:
            col = 0
            row += 1
        self.creation_panel[txt] = Button(self.frame, text=txt, state=DISABLED, command=lambda cls=self, arg=txt: set_navigate(cls, arg))
        self.creation_panel[txt].grid(row=row, column=col, columnspan=4, sticky=NSEW)
        col += 4

    self.creation_panel["Preview"] = Button(self.frame, text="Preview", command=lambda cls=self: set_navigate(cls, "Preview"))
    self.creation_panel["Preview"].grid(row=row+1, column=0, columnspan=12, sticky=NSEW)

    self.preview_window1 = Label(self.frame, text="", justify=LEFT)
    self.preview_window1.grid(row=0, rowspan=5, column=12, columnspan=4, sticky=NSEW)
    self.preview_window1.config(state='disabled', relief=SUNKEN)

    self.preview_window2 = Label(self.frame, text="", justify=LEFT)
    self.preview_window2.grid(row=0, rowspan=5, column=16, columnspan=4, sticky=NSEW)
    self.preview_window2.config(state='disabled', relief=SUNKEN)

    self.frame.pack(side=LEFT, fill=BOTH, expand=1)

Maybe it isn't a the best way, and some other will correct me. But there is a one of possible ways.

self.navigate variable was used for navigation becouse that class represents only view in MVC model of GUI :). If it has changed, then from controller is sended signal, get new model and called new view. Or somesimilar way, i don't clearly remember that old project.


问:
Updating a dictionary privately?
I have a class object that receives some data. Based on a condition, I need that data to change, but only under that condition. Problem I'm running into is that when I call dict.update() , it updates the original variable too. So a subsequent request comes in, and now that original variable is "tainted" so to speak, and is using overridden information that it shouldn't have.

Assuming a dictionary like this:

```<code>my_attributes = {"test": True}
</code>```

And some logic like this:

```<code>class MyClass(object):

    def __init__(self, attributes):
        if my_condition():
            attributes.update({"test": False})
</code>```

The end result:

```<code>>>> my_attributes
{'test': False}
</code>```

So, the next time MyClass is used, those root attributes are still overridden.

I've seemingly gotten around this problem by re-defining attributes:

```<code>class MyClass(object):

    def __init__(self, attributes):
        if my_condition():
            attributes = {}
            attributes.update(my_attributes)
            attributes.update({"test": False})
</code>```

This has seemed to get around the problem, but I'm not entirely sure this is a good, or even the right, solution to the issue.

答:
You pass a (mutable) dictionary reference to an object. Now, you have two owners of the reference: the caller of the constructor (the "external world" for the object) and the object itself. These two owners may modify the dictionary. Here is an illustration:

```<code>>>> d = {}
>>> def ctor(d): return [d] # just build a list with one element
>>> L = ctor(d)
>>> d[1] = 2
>>> L
[{1: 2}]
>>> L[0][3] = 4
>>> d
{1: 2, 3: 4}
</code>```

How do you prevent this? Both owners want to protect themselves from wild mutation of their variables. If I were the external world, I would like to pass an immutable reference to the dict, but Python does not provide immutable references for dicts. A copy is the way to go:

```<code>>>> d = {}
>>> L = ctor(dict(d)) # I don't give you *my* d
>>> d[1] = 2
>>> L
[{}]
</code>```

If I were the object, I would do a copy of the object before using it:

```<code>>>> d = {}
>>> def ctor2(d): return [dict(d)] # to be sure L[0] is *mine*!
>>> L = ctor2(dict(d)) # I don't give you *my* d
</code>```

But now you have made two copies of the object just because everyone is scared to see its variables modified by the other. And the issue is still here if the dictionary contains (mutable) references.

The solution is to spell out the responsibilities of each one:

```<code>class MyClass(object):
    """Usage: MyClass(attributes).do_something() where attributes is a mapping.
    The mapping won't be modified"""
    ...
</code>```

Note that this is the common expected behavior: unless specified, the arguments of a function/contructor are not modified. We avoid side effect when possible, but that's not always the case: see list.sort() vs sorted(...).

Hence I think your solution is good. But I prefer to avoid too much logic in the constructor:

```<code>class MyClass(object):
    @staticmethod
    def create_prod(attributes):
        attributes = dict(attributes)
        attributes.update({"test": False})
        return MyClass(attributes)

    @staticmethod
    def create_test(attributes):
        return MyClass(attributes)

    def __init__(self, attributes):
        self._attributes = attributes # MyClass won't modify attributes
</code>```

Title: Updating a dictionary privately?

Body:
I have a class object that receives some data. Based on a condition, I need that data to change, but only under that condition. Problem I'm running into is that when I call dict.update() , it updates the original variable too. So a subsequent request comes in, and now that original variable is "tainted" so to speak, and is using overridden information that it shouldn't have.

Assuming a dictionary like this:

my_attributes = {"test": True}

And some logic like this:

class MyClass(object):

    def __init__(self, attributes):
        if my_condition():
            attributes.update({"test": False})

The end result:

>>> my_attributes
{'test': False}

So, the next time MyClass is used, those root attributes are still overridden.

I've seemingly gotten around this problem by re-defining attributes:

class MyClass(object):

    def __init__(self, attributes):
        if my_condition():
            attributes = {}
            attributes.update(my_attributes)
            attributes.update({"test": False})

This has seemed to get around the problem, but I'm not entirely sure this is a good, or even the right, solution to the issue.

Body:
You pass a (mutable) dictionary reference to an object. Now, you have two owners of the reference: the caller of the constructor (the "external world" for the object) and the object itself. These two owners may modify the dictionary. Here is an illustration:

>>> d = {}
>>> def ctor(d): return [d] # just build a list with one element
>>> L = ctor(d)
>>> d[1] = 2
>>> L
[{1: 2}]
>>> L[0][3] = 4
>>> d
{1: 2, 3: 4}

How do you prevent this? Both owners want to protect themselves from wild mutation of their variables. If I were the external world, I would like to pass an immutable reference to the dict, but Python does not provide immutable references for dicts. A copy is the way to go:

>>> d = {}
>>> L = ctor(dict(d)) # I don't give you *my* d
>>> d[1] = 2
>>> L
[{}]

If I were the object, I would do a copy of the object before using it:

>>> d = {}
>>> def ctor2(d): return [dict(d)] # to be sure L[0] is *mine*!
>>> L = ctor2(dict(d)) # I don't give you *my* d

But now you have made two copies of the object just because everyone is scared to see its variables modified by the other. And the issue is still here if the dictionary contains (mutable) references.

The solution is to spell out the responsibilities of each one:

class MyClass(object):
    """Usage: MyClass(attributes).do_something() where attributes is a mapping.
    The mapping won't be modified"""
    ...

Note that this is the common expected behavior: unless specified, the arguments of a function/contructor are not modified. We avoid side effect when possible, but that's not always the case: see list.sort() vs sorted(...).

Hence I think your solution is good. But I prefer to avoid too much logic in the constructor:

class MyClass(object):
    @staticmethod
    def create_prod(attributes):
        attributes = dict(attributes)
        attributes.update({"test": False})
        return MyClass(attributes)

    @staticmethod
    def create_test(attributes):
        return MyClass(attributes)

    def __init__(self, attributes):
        self._attributes = attributes # MyClass won't modify attributes


问:
to draw graph with mysql data
I need to draw a line graph with mysql data which has two columns. some one help me with a sample code.</p>

答:
There are number of options available to draw line chart in Java:

Easy charts

jFree Charts

jCharts

Chart 2D

Google Chart API

Title: to draw graph with mysql data


问:
WARNING: The advertisement key 'Service Data' is not allowed
I am developing a BLE peripheral app. By requirement, the advertising packet must contain Service Data field. I have done this in Android, the packet should be like this:

0x16 is Service Data field listed here https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/

Same thing, I do it in iOS. I use BluetoothCore framework to implement the bluetooth peripheral.

Below is the attribute I should use to set value for Service Data field:

```<code>advertisementData[CBAdvertisementDataServiceDataKey] = <somedata>
</code>```

However I got a warning:

WARNING: The advertisement key 'Service Data' is not allowed

Can someone let me know why and what is the solution?

答:
You cannot specify service data when advertising a peripheral on iOS. You can only specify the service UUID and the service name.

From the documentation:

advertisementData

An optional dictionary containing the data you want to advertise. The possible keys of an advertisementData dictionary are detailed in CBCentralManagerDelegate. That said, only two of the keys are supported for peripheral manager objects: CBAdvertisementDataLocalNameKey and CBAdvertisementDataServiceUUIDsKey.

The solution to your warning is to remove CBAdvertisementDataServiceDataKey from the advertising data dictionary.

I'm afraid there isn't a solution to your requirements on iOS.

Body:
I am developing a BLE peripheral app. By requirement, the advertising packet must contain Service Data field. I have done this in Android, the packet should be like this:

0x16 is Service Data field listed here https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/

Same thing, I do it in iOS. I use BluetoothCore framework to implement the bluetooth peripheral.

Below is the attribute I should use to set value for Service Data field:

advertisementData[CBAdvertisementDataServiceDataKey] = <somedata>

However I got a warning:

WARNING: The advertisement key 'Service Data' is not allowed

Can someone let me know why and what is the solution?


答:
I found this explanation on Treehouse:

Without parentheses you're not actually calling the function. A function name without the parentheses is a reference to the function.

We don't use the parentheses in that code because we don't want the function to be called at the point where that code is encountered. Instead, we want to pass a reference to our function into the .focus() method and that method will call our function for us whenever the element receive focus.

It doesn't need to be. However, one method of tying events to elements you're creating in JS is tying that event to the element upon creation. Each element will now have that event once inserted into the DOM. Sometimes, this can be wiser. For example, you're going through a for loop creating elements and inserting them into the DOM. Rather than have to loop through again at a later time to add click events, you can just do it there to avoid doing more work.

Title: Why is a parentheses not needed in removeItem? Why must li.onclick = removeItem be inside the newItem() function?


问:
Warning: Prop `className` did not match ~ Material UI css arbitrarily breaks on reload

Video reproducing the error/missing css

I know there are already dated versions of this question on stack overflow, like React + Material-UI - Warning: Prop className did not match.

However, when I attempt to google and research people's solutions, there is just no clear answer. Any answers I could find don't match my stack.

My stack:

Node JS

Next JS

Material UI

And from what I could glean from answers to questions like next.js & material-ui - getting them to work is that there is some measure of incompatibility when it comes to Next JS and Material UI.

Code-wise, here is my Appbar component. Initially I was not exporting my useStyles object, but I ended up doing it in a pitiful attempt to follow along with Material UI's express guide to "server rendering". There has to be a fix that doesn't involve changing like every file I have.

```<code>import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import InputBase from '@material-ui/core/InputBase';
import { fade } from '@material-ui/core/styles/colorManipulator';
import { makeStyles } from '@material-ui/core/styles';
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import {connectSearchBox} from 'react-instantsearch-dom';

const useStyles = makeStyles(theme => ({
    root: {
        flexGrow: 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    title: {
        flexGrow: 1,
        display: 'none',
        [theme.breakpoints.up('sm')]: {
            display: 'block',
        },
    },
    search: {
        position: 'relative',
        borderRadius: theme.shape.borderRadius,
        backgroundColor: fade(theme.palette.common.white, 0.15),
        '&:hover': {
            backgroundColor: fade(theme.palette.common.white, 0.25),
        },
        marginLeft: 0,
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            marginLeft: theme.spacing(1),
            width: 'auto',
        },
    },
    searchIcon: {
        width: theme.spacing(7),
        height: '100%',
        position: 'absolute',
        pointerEvents: 'none',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    inputRoot: {
        color: 'inherit',
    },
    inputInput: {
        padding: theme.spacing(1, 1, 1, 7),
        transition: theme.transitions.create('width'),
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            width: 300,
            '&:focus': {
                width: 400,
            },
        },
    }
}));

function SearchBox({currentRefinement, refine}){
    const classes = useStyles();
    return(
        <InputBase
            type="search"
            value={currentRefinement}
            onChange={event => refine(event.currentTarget.value)}
            placeholder="Search by state, park name, keywords..."
            classes = {{
                root: classes.inputRoot,
                input: classes.inputInput,
            }}
        />
    )
}

const CustomSearchBox = connectSearchBox(SearchBox);

function SearchAppBar() {
    const classes = useStyles();
    return (
        <div className={classes.root}>
            <AppBar position="static" color="primary">
                <Toolbar>
                    <IconButton
                        edge="start"
                        className={classes.menuButton}
                        color="inherit"
                        aria-label="Open drawer"
                    >
                        <MenuIcon />
                    </IconButton>
                    <Typography className={classes.title} variant="h6" noWrap>
                        Title
                    </Typography>
                    <div className={classes.search}>
                        <div className={classes.searchIcon}>
                            <SearchIcon />
                        </div>
                        <CustomSearchBox/>
                    </div>
                </Toolbar>
            </AppBar>
        </div>
    );
}

export {SearchAppBar, useStyles};
</code>```

答:
I was just digging around random parts of the internet looking for answers to this error, accidentally npm install'ed styled-components as part of this answer on a Github issue (because they have a very similar object to the counterpart in Material UI called ServerStyleSheet (vs Material UI's ServerStyleSheets), so obviously that didn't work.

BUT......... I ended up just using the ServerStyleSheet fix to try to make it agreeable with Material UI's ServerStyleSheets object, and ended up with this new _document.js.

I'm still dumbfounded I was able to refactor an entirely different fix to make this work but I tested it and it fixes the problem entirely, now reloads are fine.

```<code>import Document, { Html, Head, Main, NextScript } from 'next/document';
import {ServerStyleSheets} from "@material-ui/styles";

class MyDocument extends Document {
    static async getInitialProps(ctx) {
        const sheet = new ServerStyleSheets();
        const originalRenderPage = ctx.renderPage;

        try{
            ctx.renderPage = () => originalRenderPage({
                enhanceApp: App => props => sheet.collect(<App {...props}/>)
            });

            const initialProps = await Document.getInitialProps(ctx);
            return { ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                )
            }
        } finally {
            ctx.renderPage(sheet)
        }

    }
    render() {
        return (
            <Html>
                <Head>
                    <link rel="shortcut icon" type="image/png" href="../static/favicon.ico"/>
                    <style>{`body { margin: 0 } /* custom! */`}</style>
                    <meta name="viewport"content="width=device-width, initial-scale=1.0" />
                </Head>
                <body className="custom_class">
                    <Main />
                    <NextScript />
                </body>
            </Html>
    )}
}

export default MyDocument;
</code>```

If you wanna see how crazy it was that it worked, here is the fix for the same error in styled-components:

export default MyDocument;

```<code>import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
    static async getInitialProps (ctx) {
        const sheet = new ServerStyleSheet()
        const originalRenderPage = ctx.renderPage

        try {
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
                })

            const initialProps = await Document.getInitialProps(ctx)
            return {
                ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                )
            }
        } finally {
            sheet.seal()
        }
    }
}
</code>```

I hope this helped someone with the mess that is Material-UI + Next.js

Body:
Video reproducing the error/missing css

I know there are already dated versions of this question on stack overflow, like React + Material-UI - Warning: Prop className did not match.

However, when I attempt to google and research people's solutions, there is just no clear answer. Any answers I could find don't match my stack.

My stack:

Node JS

Next JS

Material UI

And from what I could glean from answers to questions like next.js & material-ui - getting them to work is that there is some measure of incompatibility when it comes to Next JS and Material UI.

Code-wise, here is my Appbar component. Initially I was not exporting my useStyles object, but I ended up doing it in a pitiful attempt to follow along with Material UI's express guide to "server rendering". There has to be a fix that doesn't involve changing like every file I have.

import React from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import InputBase from '@material-ui/core/InputBase';
import { fade } from '@material-ui/core/styles/colorManipulator';
import { makeStyles } from '@material-ui/core/styles';
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import {connectSearchBox} from 'react-instantsearch-dom';

const useStyles = makeStyles(theme => ({
    root: {
        flexGrow: 1,
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    title: {
        flexGrow: 1,
        display: 'none',
        [theme.breakpoints.up('sm')]: {
            display: 'block',
        },
    },
    search: {
        position: 'relative',
        borderRadius: theme.shape.borderRadius,
        backgroundColor: fade(theme.palette.common.white, 0.15),
        '&:hover': {
            backgroundColor: fade(theme.palette.common.white, 0.25),
        },
        marginLeft: 0,
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            marginLeft: theme.spacing(1),
            width: 'auto',
        },
    },
    searchIcon: {
        width: theme.spacing(7),
        height: '100%',
        position: 'absolute',
        pointerEvents: 'none',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    inputRoot: {
        color: 'inherit',
    },
    inputInput: {
        padding: theme.spacing(1, 1, 1, 7),
        transition: theme.transitions.create('width'),
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            width: 300,
            '&:focus': {
                width: 400,
            },
        },
    }
}));

function SearchBox({currentRefinement, refine}){
    const classes = useStyles();
    return(
        <InputBase
            type="search"
            value={currentRefinement}
            onChange={event => refine(event.currentTarget.value)}
            placeholder="Search by state, park name, keywords..."
            classes = {{
                root: classes.inputRoot,
                input: classes.inputInput,
            }}
        />
    )
}

const CustomSearchBox = connectSearchBox(SearchBox);

function SearchAppBar() {
    const classes = useStyles();
    return (

            <AppBar position="static" color="primary">
                <Toolbar>
                    <IconButton
                        edge="start"
                        className={classes.menuButton}
                        color="inherit"
                        aria-label="Open drawer"
                    >
                        <MenuIcon />
                    </IconButton>
                    <Typography className={classes.title} variant="h6" noWrap>
                        Title
                    </Typography>

                            <SearchIcon />

                        <CustomSearchBox/>

                </Toolbar>
            </AppBar>

    );
}

export {SearchAppBar, useStyles};

Body:
I was just digging around random parts of the internet looking for answers to this error, accidentally npm install'ed styled-components as part of this answer on a Github issue (because they have a very similar object to the counterpart in Material UI called ServerStyleSheet (vs Material UI's ServerStyleSheets), so obviously that didn't work.

BUT......... I ended up just using the ServerStyleSheet fix to try to make it agreeable with Material UI's ServerStyleSheets object, and ended up with this new _document.js.

I'm still dumbfounded I was able to refactor an entirely different fix to make this work but I tested it and it fixes the problem entirely, now reloads are fine.

import Document, { Html, Head, Main, NextScript } from 'next/document';
import {ServerStyleSheets} from "@material-ui/styles";

class MyDocument extends Document {
    static async getInitialProps(ctx) {
        const sheet = new ServerStyleSheets();
        const originalRenderPage = ctx.renderPage;

        try{
            ctx.renderPage = () => originalRenderPage({
                enhanceApp: App => props => sheet.collect(<App {...props}/>)
            });

            const initialProps = await Document.getInitialProps(ctx);
            return { ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                )
            }
        } finally {
            ctx.renderPage(sheet)
        }

    }
    render() {
        return (
            <Html>
                <Head>
                    <link rel="shortcut icon" type="image/png" href="../static/favicon.ico"/>
                    <style>{`body { margin: 0 } /* custom! */`}</style>
                    <meta name="viewport"content="width=device-width, initial-scale=1.0" />
                </Head>
                <body className="custom_class">
                    <Main />
                    <NextScript />
                </body>
            </Html>
    )}
}

export default MyDocument;

If you wanna see how crazy it was that it worked, here is the fix for the same error in styled-components:

export default MyDocument;

import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
    static async getInitialProps (ctx) {
        const sheet = new ServerStyleSheet()
        const originalRenderPage = ctx.renderPage

        try {
            ctx.renderPage = () =>
                originalRenderPage({
                    enhanceApp: App => props => sheet.collectStyles(<App {...props} />)
                })

            const initialProps = await Document.getInitialProps(ctx)
            return {
                ...initialProps,
                styles: (
                    <>
                        {initialProps.styles}
                        {sheet.getStyleElement()}
                    </>
                )
            }
        } finally {
            sheet.seal()
        }
    }
}

I hope this helped someone with the mess that is Material-UI + Next.js


问:
How to fix an if, elseif, and else statement causing an HTTP 500 error?
I have an if, elseif statement causing an HTTP 500 Error. I would really appreciate the help figuring such a simple problem out. Thank You!

I have tried changing my conditions, deleting the elseif (which worked), alternating between elseif and else if. I have searched Google, and the answer is nowhere to be found.

<?php
if($row7Count == 0) {
    // This code works fine
} elseif($editAgent != null) {
    // This code causes HTTP 500 error
} else {
    //This code works fine
}
```

Expected results is to execute any code within elseif statement, even a simple echo 'testing'; does not work.

Actual results = HTTP 500 Error

答:
try this:</p>

```<code><?php
if($row7Count == 0) {
    // This code works fine
} else if(!is_null($editAgent)) {
    echo "test";
} else {
    //This code works fine
}
</code>```

Body:
I have an if, elseif statement causing an HTTP 500 Error. I would really appreciate the help figuring such a simple problem out. Thank You!

I have tried changing my conditions, deleting the elseif (which worked), alternating between elseif and else if. I have searched Google, and the answer is nowhere to be found.

<?php
if($row7Count == 0) {
    // This code works fine
} elseif($editAgent != null) {
    // This code causes HTTP 500 error
} else {
    //This code works fine
}

Expected results is to execute any code within elseif statement, even a simple echo 'testing'; does not work.

Actual results = HTTP 500 Error

Body:
try this:

<?php
if($row7Count == 0) {
    // This code works fine
} else if(!is_null($editAgent)) {
    echo "test";
} else {
    //This code works fine
}


问:
How to iterate through a dictionary inside of a list, which is a value of a dictionary
I have been having a hard time to understand how should I approach that problem.

I have a dictionary, that contains lists for each key value.

Each list carries n numbers of dictionaries.

Inside of those dictionaries, there is a value that I need to sum up, for each key value of the main dictionary.

I do have no idea how to iterate through a dictionary which is inside of a list, that is a value from a greater dictionary.

I'll provide the main code below. Could someone help me to understand how to approach the problem?

Input, where groups is a dict and 'Hydrofilm...' is one of the key values':

```<code>groups['Hydrofilm 10cm x 15cm VP Adh Film Dress']
</code>```

Output, which is a list of dictionary related with that key value:

```<code>[{'bnf_code': '20030100236',
  'items': 1,
  'practice': 'P81069',
  'bnf_name': 'Hydrofilm 10cm x 15cm VP Adh Film Dress',
  'nic': 10.6,
  'act_cost': 9.83,
  'quantity': 20},
 {'bnf_code': '20030100236',
  'items': 1,
  'practice': 'P81100',
  'bnf_name': 'Hydrofilm 10cm x 15cm VP Adh Film Dress',
  'nic': 10.6,
  'act_cost': 9.81,
  'quantity': 20},
 {'bnf_code': '20030100236',
  'items': 1,
  'practice': 'J81043',
  'bnf_name': 'Hydrofilm 10cm x 15cm VP Adh Film Dress',
  'nic': 5.3,
  'act_cost': 4.92,
  'quantity': 10},
 {'bnf_code': '20030100236',
  'items': 1,
  'practice': 'J81056',
  'bnf_name': 'Hydrofilm 10cm x 15cm VP Adh Film Dress',
  'nic': 5.3,
  'act_cost': 4.92,
  'quantity': 10},
 {'bnf_code': '20030100236',
  'items': 1,
  'practice': 'J81057',
  'bnf_name': 'Hydrofilm 10cm x 15cm VP Adh Film Dress',
  'nic': 5.3,
  'act_cost': 4.92,
  'quantity': 10}]
</code>```

The key that needs to be sum is the 'items'

Expected results:

```<code>sum_list = [1,1,1,1,1]
</code>```

答:
Assign that list of dicts to elements.
Then we want:

```<code>>>> [element['items']  for element in elements]
[1, 1, 1, 1, 1]
</code>```

Body:
I have been having a hard time to understand how should I approach that problem.

I have a dictionary, that contains lists for each key value.

Each list carries n numbers of dictionaries.

Inside of those dictionaries, there is a value that I need to sum up, for each key value of the main dictionary.

I do have no idea how to iterate through a dictionary which is inside of a list, that is a value from a greater dictionary.

I'll provide the main code below. Could someone help me to understand how to approach the problem?

Input, where groups is a dict and 'Hydrofilm...' is one of the key values':

groups['Hydrofilm 10cm x 15cm VP Adh Film Dress']

Output, which is a list of dictionary related with that key value:

[{'bnf_code': '20030100236',
  'items': 1,
  'practice': 'P81069',
  'bnf_name': 'Hydrofilm 10cm x 15cm VP Adh Film Dress',
  'nic': 10.6,
  'act_cost': 9.83,
  'quantity': 20},
 {'bnf_code': '20030100236',
  'items': 1,
  'practice': 'P81100',
  'bnf_name': 'Hydrofilm 10cm x 15cm VP Adh Film Dress',
  'nic': 10.6,
  'act_cost': 9.81,
  'quantity': 20},
 {'bnf_code': '20030100236',
  'items': 1,
  'practice': 'J81043',
  'bnf_name': 'Hydrofilm 10cm x 15cm VP Adh Film Dress',
  'nic': 5.3,
  'act_cost': 4.92,
  'quantity': 10},
 {'bnf_code': '20030100236',
  'items': 1,
  'practice': 'J81056',
  'bnf_name': 'Hydrofilm 10cm x 15cm VP Adh Film Dress',
  'nic': 5.3,
  'act_cost': 4.92,
  'quantity': 10},
 {'bnf_code': '20030100236',
  'items': 1,
  'practice': 'J81057',
  'bnf_name': 'Hydrofilm 10cm x 15cm VP Adh Film Dress',
  'nic': 5.3,
  'act_cost': 4.92,
  'quantity': 10}]

The key that needs to be sum is the 'items'

Expected results:

sum_list = [1,1,1,1,1]

Body:
Assign that list of dicts to elements.
Then we want:

>>> [element['items']  for element in elements]
[1, 1, 1, 1, 1]


问:
Minimal FOSS RTOS with TCP/IP, SSL, USB and basic file-system support for ARM
Here's a candid admission first -- that I know zilch about RTOS or Embedded programming, so folks who know better may help me frame the query more appropriately.

What would be the minimal FOSS RTOS (or any OS for that matter) with support for TCP/IP, SSL, USB and some basic file-system for low-end ARM devices like Cortex-M3's ?

Have not ruled out something like ARM9/ARM7TDMI, so an RTOS that has "optional" MMU support, may be a major plus. We are at present dabbling with few uncertainities like precise processor, MMU/no-MMU, running completely head-less (no display), however I wanted to start a little ramp-up.

Would gladly answer counter questions to clarify the requirement.

答:
I believe that eCOS has support for all you need and is scalable.

Alternatively you could build from a self-selected kit of parts; choosing independent RTOS, filesystem, USB, etc. From different sources, and integrating them yourself.


问:
Why after continue; execution further function code is executed?
I have a functions like:

```<code>public function checkItems(int $id, array $items)
{
    $this->validateItems($id, $items);

    foreach($items as $item) {
        ...// further code
    }

    return $items;
}

private function validateItems(int $id, array $items)
{
    foreach ($items as $item) {
        if (!is_int($item->itemId)) {
            continue;
        }
    }
}
</code>```

The thing is that when I write this if:

```<code>if (!is_int($item->itemId)) {
    continue;
}
</code>```

inside the function checkItems() (not moved to another one) it works perfectly, because ..//further code doesn't get executed if the item is wrong. It basically returns $items if the information is not valid.

But when I move my validation into an another function, despite continue statements, at the end it loops again and the further code is executed.

Could someone tell me how to properly solve this with a validation move to another function?

答:
The continue command inside loop skips any code below it inside that loop
and starts the loop from the top.

Hence putting it at the end of any loop makes no difference because there is no further code to skip.
and loop starts from the top as if there ware no continue command.

If you make validation that works this way it needs continue then this continue
will always refer to the loop it is inside.
Therefore if you move it to other function it skips execution of code below the loop
inside that function but that does not affect any other loop, especially in other function.

so if you use continue inside foreach inside checkItems()
it will skipp commands inside foreach of that function.

but if you move continue to function validateItems() and call that function
from within checkItems() then inside checkItems() will be no effect of using continue
that is inside validateItems()

to the second part how to do the validation.

Your validator should return a true/false
and inside checkItems() you test that
and if it is false then you use continue

```<code><?php

public function checkItems(int $id, array $items)
{
    $this->validateItems($id, $items);

    foreach($items as $item) {

        if(false === $this->validateItems($id, $items)) {
            continue;
        }

        ...// further code
    }

    return $items;
}

private function validateItems(int $id, array $items)
{
    foreach ($items as $item) {
        if (!is_int($item->itemId)) {
            return false;
        }
    }
    return true;
}
</code>```

Body:
I have a functions like:

public function checkItems(int $id, array $items)
{
    $this->validateItems($id, $items);

    foreach($items as $item) {
        ...// further code
    }

    return $items;
}

private function validateItems(int $id, array $items)
{
    foreach ($items as $item) {
        if (!is_int($item->itemId)) {
            continue;
        }
    }
}

The thing is that when I write this if:

if (!is_int($item->itemId)) {
    continue;
}

inside the function checkItems() (not moved to another one) it works perfectly, because ..//further code doesn't get executed if the item is wrong. It basically returns $items if the information is not valid.

But when I move my validation into an another function, despite continue statements, at the end it loops again and the further code is executed.

Could someone tell me how to properly solve this with a validation move to another function?

Body:
The continue command inside loop skips any code below it inside that loop
and starts the loop from the top.

Hence putting it at the end of any loop makes no difference because there is no further code to skip.
and loop starts from the top as if there ware no continue command.

If you make validation that works this way it needs continue then this continue
will always refer to the loop it is inside.
Therefore if you move it to other function it skips execution of code below the loop
inside that function but that does not affect any other loop, especially in other function.

so if you use continue inside foreach inside checkItems()
it will skipp commands inside foreach of that function.

but if you move continue to function validateItems() and call that function
from within checkItems() then inside checkItems() will be no effect of using continue
that is inside validateItems()

to the second part how to do the validation.

Your validator should return a true/false
and inside checkItems() you test that
and if it is false then you use continue

<?php

public function checkItems(int $id, array $items)
{
    $this->validateItems($id, $items);

    foreach($items as $item) {

        if(false === $this->validateItems($id, $items)) {
            continue;
        }

        ...// further code
    }

    return $items;
}

private function validateItems(int $id, array $items)
{
    foreach ($items as $item) {
        if (!is_int($item->itemId)) {
            return false;
        }
    }
    return true;
}


问:
transfer data from a class to webpage in flask
I packed some defs in a class to do a work of translation text into the other language using Bing or Google translation API. and using a Flask to render templates as you may aware of.

However, when do the translation, I have some status and progress information, like completed 10% and etc during translate the paragraphs. but that information generated in the translation class as you may imagine - the class does the translation job.

However, in my Flask app, after call the class do the translation I want to have an ajax call from the webpage to the Flask App to retrieve that 10% information which generated from that class.

Here is what I did:

If I don't use any class, put all the defs within the main Flask App file, I can use the a global variable store the 10% information, but that makes the codes complex and I want to pack all the associated defs in a class.

in the Flask App, I was trying to use session['translation_pos'] to retrieve the information that I stored in session['translation_pos'] in the class, but it seems not works.

I use python 3 and Flask, I don't know how to get this progress percentage information from the class - where the data generated - to the App.

May be one of the way would like store the number in a text file or some places, and read the file in the App, but I was thinking that certainly shouldn't the way to handle this problems.

Would anyone could advise with some idea that will be much appreciated.

Thank you All.

答:
You may want to look at a different approach to running the task, using something like Celery or Redis Queue - covered very well here in the mega tutorial.

By using one of these, you can run the task and query the runner periodically for progress to report it back to the user.

If it were me, for the data processing I would store this in a database. When the task is completed, it gets re-queried and passed through to the UI as a template variable (or streamed from an ajax function if it's a large data set).


问:
How to initialize the weights of different layers of nn.Sequential block in different styles in pytorch?
Let's suppose I have a nn.Sequential block, it has 2 linear layers. I want to initialize the weights of first layer by uniform distribution but want to initialize the weights of second layer as constant 2.0.

net = nn.Sequential()
net.add_module('Linear_1', nn.Linear(2, 5, bias = False))
net.add_module('Linear_2', nn.Linear(5, 5, bias = False)
```

答:
Here is one way of doing so:

```<code>import torch
import torch.nn as nn

net = nn.Sequential()

ll1 = nn.Linear(2, 5, bias = False)
torch.nn.init.uniform_(ll1.weight, a=0, b=1) # a: lower_bound, b: upper_bound
net.add_module('Linear_1', ll1)
print(ll1.weight)

ll2 = nn.Linear(5, 5, bias = False)
torch.nn.init.constant_(ll2.weight, 2.0)
net.add_module('Linear_2', ll2)
print(ll2.weight)

print(net)
</code>```

Output:

```<code>Parameter containing:
tensor([[0.2549, 0.7823],
        [0.3439, 0.4721],
        [0.0709, 0.6447],
        [0.3969, 0.7849],
        [0.7631, 0.5465]], requires_grad=True)

Parameter containing:
tensor([[2., 2., 2., 2., 2.],
        [2., 2., 2., 2., 2.],
        [2., 2., 2., 2., 2.],
        [2., 2., 2., 2., 2.],
        [2., 2., 2., 2., 2.]], requires_grad=True)

Sequential(
(Linear_1): Linear(in_features=2, out_features=5, bias=False)
(Linear_2): Linear(in_features=5, out_features=5, bias=False)
)
</code>```

Body:
Here is one way of doing so:

import torch
import torch.nn as nn

net = nn.Sequential()

ll1 = nn.Linear(2, 5, bias = False)
torch.nn.init.uniform_(ll1.weight, a=0, b=1) # a: lower_bound, b: upper_bound
net.add_module('Linear_1', ll1)
print(ll1.weight)

ll2 = nn.Linear(5, 5, bias = False)
torch.nn.init.constant_(ll2.weight, 2.0)
net.add_module('Linear_2', ll2)
print(ll2.weight)

print(net)

Output:

Parameter containing:
tensor([[0.2549, 0.7823],
        [0.3439, 0.4721],
        [0.0709, 0.6447],
        [0.3969, 0.7849],
        [0.7631, 0.5465]], requires_grad=True)

Parameter containing:
tensor([[2., 2., 2., 2., 2.],
        [2., 2., 2., 2., 2.],
        [2., 2., 2., 2., 2.],
        [2., 2., 2., 2., 2.],
        [2., 2., 2., 2., 2.]], requires_grad=True)

Sequential(
(Linear_1): Linear(in_features=2, out_features=5, bias=False)
(Linear_2): Linear(in_features=5, out_features=5, bias=False)
)


问:
Writing an if statement depending on an attribute of an agent to command agents of a different agentset
I am trying to make an agentset do something, if an agent(of a different agentset) has a particular shape.

Here, if the shape of a particular

ghost (say Ghost 1) is circle,

then all rabbits are supposed to move forward 1. (<-This is the
intended behavior)

where

ghosts are agentset A

rabbits are agentset B

I have tried along these lines:

```<code>ask rabbits
[
 if (shape ghost 1 = "circle")
  [
   forward 1
  ]
]
</code>```

For this code I get,

"Expected a closing paranthesis here."

with a highlighter on ghost.
I'm aware that this code is wrong but I can't think of how else this should be written to get the desired result.

答:
This will (I think - can't test) get the syntax correct:

```<code>ask rabbits
[
 if ([shape] of ghost 1 = "circle")
  [
   forward 1
  ]
]
</code>```

but you also have an ordering error and will have every rabbit check the shape of chost 1. I think what you really want is:

```<code>if ([shape] of ghost 1 = "circle")
[ ask rabbits
  [ forward 1
  ]
]
</code>```

Body:
I am trying to make an agentset do something, if an agent(of a different agentset) has a particular shape.

Here, if the shape of a particular

ghost (say Ghost 1) is circle,

then all rabbits are supposed to move forward 1. (<-This is the
intended behavior)

where

ghosts are agentset A

rabbits are agentset B

I have tried along these lines:

ask rabbits
[
 if (shape ghost 1 = "circle")
  [
   forward 1
  ]
]

For this code I get,

"Expected a closing paranthesis here."

with a highlighter on ghost.
I'm aware that this code is wrong but I can't think of how else this should be written to get the desired result.

Body:
This will (I think - can't test) get the syntax correct:

ask rabbits
[
 if ([shape] of ghost 1 = "circle")
  [
   forward 1
  ]
]

but you also have an ordering error and will have every rabbit check the shape of chost 1. I think what you really want is:

if ([shape] of ghost 1 = "circle")
[ ask rabbits
  [ forward 1
  ]
]


问:
Calculate value using previously-calculated value (from the same column) and value from another column in a Pandas Dataframe
After hours trying to learn how to do this, I'm reaching out to the community.

I'm starting with the following:

```<code>                perf
date
2018-06-01  0.012923
2018-06-02  0.039364
2018-06-03  0.042805
2018-06-04 -0.033214
2018-06-05 -0.021745
</code>```

Need to calculate a cumulative percentage change on a new column but need to ensure the calculation uses 100 as the starting value. So I prepend a single row with the 100:

```<code>                perf  pct_change
date
2018-05-31       NaN       100.0
2018-06-01  0.012923         NaN
2018-06-02  0.039364         NaN
2018-06-03  0.042805         NaN
2018-06-04 -0.033214         NaN
</code>```

What I need to get is this:

```<code>                perf  pct_change
date
2018-05-31       NaN       100.0
2018-06-01  0.012923    101.2923
2018-06-02  0.039364 105.2795701
2018-06-03  0.042805 109.7860621
2018-06-04 -0.033214 106.1396278
</code>```

The formula being something like pct_change = previous_days_pct_change * ( 1 + perf )

I tried a few different approaches including a for ... in loop with no success.

```<code># INCOMPLETE/DOES NOT WORK (adding for illustration purposes only)
for index, row in performance.iterrows():
    curr = performance.loc[index, 'perf']
    pidx = index + pd.DateOffset(-1)
    prev = performance.iloc[[pidx], 'pct_change']
    performance.loc[index, 'pct_change'] = prev * ( 1 + curr )
</code>```

I also tried:

```<code>performance['pct_change'] = performance['pct_change'].shift() * ( 1 + performance['perf'] )
</code>```

Which yields:

```<code>                perf  pct_change
date
2018-05-31       NaN         NaN
2018-06-01  0.012923  101.292251
2018-06-02  0.039364         NaN
2018-06-03  0.042805         NaN
2018-06-04 -0.033214         NaN
</code>```

But that only gives me the one value.

I suspect there is already a much simpler way to do what I'm trying to do but I'm just not finding it. Any help would be appreciated. Very easy to do in a spreadsheet but I want to learn how to do this in Pandas.

Thank you

Body:
After hours trying to learn how to do this, I'm reaching out to the community.

I'm starting with the following:

                perf
date
2018-06-01  0.012923
2018-06-02  0.039364
2018-06-03  0.042805
2018-06-04 -0.033214
2018-06-05 -0.021745

Need to calculate a cumulative percentage change on a new column but need to ensure the calculation uses 100 as the starting value. So I prepend a single row with the 100:

                perf  pct_change
date
2018-05-31       NaN       100.0
2018-06-01  0.012923         NaN
2018-06-02  0.039364         NaN
2018-06-03  0.042805         NaN
2018-06-04 -0.033214         NaN

What I need to get is this:

                perf  pct_change
date
2018-05-31       NaN       100.0
2018-06-01  0.012923    101.2923
2018-06-02  0.039364 105.2795701
2018-06-03  0.042805 109.7860621
2018-06-04 -0.033214 106.1396278

The formula being something like pct_change = previous_days_pct_change * ( 1 + perf )

I tried a few different approaches including a for ... in loop with no success.

# INCOMPLETE/DOES NOT WORK (adding for illustration purposes only)
for index, row in performance.iterrows():
    curr = performance.loc[index, 'perf']
    pidx = index + pd.DateOffset(-1)
    prev = performance.iloc[[pidx], 'pct_change']
    performance.loc[index, 'pct_change'] = prev * ( 1 + curr )

I also tried:

performance['pct_change'] = performance['pct_change'].shift() * ( 1 + performance['perf'] )

Which yields:

                perf  pct_change
date
2018-05-31       NaN         NaN
2018-06-01  0.012923  101.292251
2018-06-02  0.039364         NaN
2018-06-03  0.042805         NaN
2018-06-04 -0.033214         NaN

But that only gives me the one value.

I suspect there is already a much simpler way to do what I'm trying to do but I'm just not finding it. Any help would be appreciated. Very easy to do in a spreadsheet but I want to learn how to do this in Pandas.

Thank you

Body:
Like so:

dates = ['2018-06-01', '2018-06-02', '2018-06-03', '2018-06-04', '2018-06-05']
import datetime as dt
dates = [pd.datetime.date(dt.datetime.strptime(x, "%Y-%m-%d")) for x in dates]
perfs = [0.012923, 0.039364, 0.042805, -0.033214, -0.021745]
df = pd.DataFrame({'perf': perfs}, index=dates)

# The important bit:
df['pct_change'] = ((df['perf'] + 1).cumprod() * 100)

df
#                 perf  pct_change
# 2018-06-01  0.012923  101.292300
# 2018-06-02  0.039364  105.279570
# 2018-06-03  0.042805  109.786062
# 2018-06-04 -0.033214  106.139628
# 2018-06-05 -0.021745  103.831622


问:
Lodash remove duplicates from array
This is my data:

[
    {
        url: 'www.example.com/hello',
        id: "22"
    },
    {
        url: 'www.example.com/hello',
        id: "22"
    },
    {
        url: 'www.example.com/hello-how-are-you',
        id: "23"
    },
    {
        url: 'www.example.com/i-like-cats',
        id: "24"
    },
    {
        url: 'www.example.com/i-like-pie',
        id: "25"
    }
]
```

With Lodash, how could I remove objects with duplicate id keys?
Something with filter, map and unique, but not quite sure.

My real data set is much larger and has more keys, but the concept should be the same.

答:
Simply use _.uniqBy(). It creates duplicate-free version of an array.

This is a new way and available from 4.0.0 version.

```<code>_.uniqBy(data, 'id');
</code>```

or

```<code>_.uniqBy(data, obj => obj.id);
</code>```

Title: Lodash remove duplicates from array

Body:
This is my data:

[
    {
        url: 'www.example.com/hello',
        id: "22"
    },
    {
        url: 'www.example.com/hello',
        id: "22"
    },
    {
        url: 'www.example.com/hello-how-are-you',
        id: "23"
    },
    {
        url: 'www.example.com/i-like-cats',
        id: "24"
    },
    {
        url: 'www.example.com/i-like-pie',
        id: "25"
    }
]

With Lodash, how could I remove objects with duplicate id keys?
Something with filter, map and unique, but not quite sure.

My real data set is much larger and has more keys, but the concept should be the same.

Body:
Simply use _.uniqBy(). It creates duplicate-free version of an array.

This is a new way and available from 4.0.0 version.

_.uniqBy(data, 'id');

or

_.uniqBy(data, obj => obj.id);


答: sum_list = [element['items'] for element in dataSet if element['bnf_code'] == 'Hydrofilm 10cm x 15cm VP Adh Film Dress'

Title: How to iterate through a dictionary inside of a list, which is a value of a dictionary


问:
Google StackDrive Logging Level in containers with uwsgi always at Error Level
I'm deploying via Kuberenetes come containers on Google Cloud, which are django project and uwsgi to run them.

I'm using the stackdrive logging tool to see the logging, the problem is that all the entries are seen as severity ERROR even thought they are not error. It seems that the log of uwsgi is written to stderr or something like that.

In the picture you can see that django uses INFO level, but that is received as ERROR by stackdrive.

this is how i set up uwsgi.

[uwsgi]
master = true
socket = :3031
chdir = .
wsgi-file = docker.wsgi
processes = 4
threads = 2
socket-timeout = 90
harakiri = 90
http = :8000
env = prometheus_multiproc_dir=multi
enable-threads = yes
lazy-apps = yes
pidfile=/tmp/project-master.pid

答:
This answer helped me find the solution to this. Using the option logger-req=stdio uWSGI logs get the correct level in Stackdriver.

Example of uwsgi.ini:

```<code>[uwsgi]
logger-req=stdio
</code>```

Body:
This answer helped me find the solution to this. Using the option logger-req=stdio uWSGI logs get the correct level in Stackdriver.

Example of uwsgi.ini:

[uwsgi]
logger-req=stdio


问:
How do you serialize a model instance in Django?
There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to JSON the fields of a Model Instance?</p>

答:
If you want to return the single model object as a json response to a client, you can do this simple solution:

```<code>from django.forms.models import model_to_dict
from django.http import JsonResponse

movie = Movie.objects.get(pk=1)
return JsonResponse(model_to_dict(movie))
</code>```

Body:
If you want to return the single model object as a json response to a client, you can do this simple solution:

from django.forms.models import model_to_dict
from django.http import JsonResponse

movie = Movie.objects.get(pk=1)
return JsonResponse(model_to_dict(movie))


问:
uasort() ? - sorting posts from a bank account
How can I sort an array with some posts from a bank account?

I need to sort by three fields: date, amount, accumulated amount

ie.

```<code>date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)
</code>```

btw. the date field is an UNIX timestamp

```<code>array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    )
</code>```

答:
Your example isnt really clear what you want.  You don't describe it this way, but from example it appears you want to sort by date increasing, then accum_amount increasing, then amount (increasing?)

You just have to write a comparison function and pass it to uasort along with your array

```<code> $comp = function($a,$b)
         {
            if ($a['date'] != $b['date'])
                 return $a['date'] - $b['date'];
            else if ($a['accum_amount'] != $b['accum_amount'])
                 return $a['accum_amount'] - $b['accum_amount'];
            return $a['amount'] - $b['amount'];
         }

 uasort($arr, $comp);
</code>```

You might find a function like this helpful.  It will create the comparison function when given an array, in order of importance, of the keys to compare by.  (All ascending, support for descending would necessarily complicate it a good deal)

```<code>$compMakerAsc = function($l)
                {
                  return function($a, $b) use ($l)
                  {
                    foreach($l as $k)
                    {
                        if ($a[$k] != $b[$k])
                           return $a[$k] - $b[$k];
                           //OR return ($a[$k] > $b[$k]) ? 1 : -1;
                    }
                    return 0;
                 }

$myComp = $compMakerAsc('date', 'accum_amount', 'amount');
$uasort($arr, $myComp);
</code>```

Body:
How can I sort an array with some posts from a bank account?

I need to sort by three fields: date, amount, accumulated amount

ie.

date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)

btw. the date field is an UNIX timestamp

array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    )

Body:
Your example isnt really clear what you want.  You don't describe it this way, but from example it appears you want to sort by date increasing, then accum_amount increasing, then amount (increasing?)

You just have to write a comparison function and pass it to uasort along with your array

 $comp = function($a,$b)
         {
            if ($a['date'] != $b['date'])
                 return $a['date'] - $b['date'];
            else if ($a['accum_amount'] != $b['accum_amount'])
                 return $a['accum_amount'] - $b['accum_amount'];
            return $a['amount'] - $b['amount'];
         }

 uasort($arr, $comp);

You might find a function like this helpful.  It will create the comparison function when given an array, in order of importance, of the keys to compare by.  (All ascending, support for descending would necessarily complicate it a good deal)

$compMakerAsc = function($l)
                {
                  return function($a, $b) use ($l)
                  {
                    foreach($l as $k)
                    {
                        if ($a[$k] != $b[$k])
                           return $a[$k] - $b[$k];
                           //OR return ($a[$k] > $b[$k]) ? 1 : -1;
                    }
                    return 0;
                 }

$myComp = $compMakerAsc('date', 'accum_amount', 'amount');
$uasort($arr, $myComp);


问:
Sum the two lowest values from a record
I have a table like this:

I need to sum the two lowest values for each record. For example, in the first row 2 and 4 (2 + 4 = 6).

I can find the lowest value for each row using CROSS APPLY, but I can't find the two lowest values at once to sum them.

Thanks in advance.

答:
Initial data:

```<code>DECLARE @Table TABLE (ID INT IDENTITY(1,1),Value1 INT, Value2 INT, Value3 INT);
INSERT INTO @Table (Value1,Value2,Value3) VALUES
     (2,4,5)
    ,(3,7,2)
    ,(9,1,6)
;
</code>```

The code:

```<code>SELECT a.ID,SUM(a.[Value]) AS [Sum]
FROM (
    SELECT p.ID,p.Value
        ,ROW_NUMBER()OVER(PARTITION BY p.ID ORDER BY p.Value ASC) AS [rn]
    FROM @Table t
    UNPIVOT(Value FOR Param IN ([Value1],[Value2],[Value3])) p
) a
WHERE a.rn <= 2 /*pick up only two lowest*/
GROUP BY a.ID
;
</code>```

Title: Sum the two lowest values from a record

Body:
Initial data:

DECLARE @Table TABLE (ID INT IDENTITY(1,1),Value1 INT, Value2 INT, Value3 INT);
INSERT INTO @Table (Value1,Value2,Value3) VALUES
     (2,4,5)
    ,(3,7,2)
    ,(9,1,6)
;

The code:

SELECT a.ID,SUM(a.[Value]) AS [Sum]
FROM (
    SELECT p.ID,p.Value
        ,ROW_NUMBER()OVER(PARTITION BY p.ID ORDER BY p.Value ASC) AS [rn]
    FROM @Table t
    UNPIVOT(Value FOR Param IN ([Value1],[Value2],[Value3])) p
) a
WHERE a.rn <= 2 /*pick up only two lowest*/
GROUP BY a.ID
;


问:
Does noiseprof in SoX get an average measurement of sound?
I'm trying to script automatic noise removal using SoX. Some of the silences that are selected by the script have a brief "yeah" or "um" in them. I'm trying to figure out how the noise profile is calculated so I can see if these brief vocalizations will really effect the noise removal process or not. So, my question is: how is a "noise profile" calculated using noiseprof in SoX? Is it averaged across the silence that is selected?</p>

答: According to this website, the noise is averaged, and these vocalizations shouldn't have a big effect on noise removal</p>


问:
Appending the mode of a dataframe column only creates value in first row of dataframe
After encountering some broken csv files in the past I am working on a smale python code which allows to filter out this faulty lines so I can manually check them for a pattern and if possible fix them.

However when wanting to append the right amount of columns I expect the file to have I only get the "mode" most frequent observation of delimiter in the first row and not all rows.

This kind of broken csvs file usually comes if a row has more separating delimiters than it actually has columns (e.g. if the name of the client has also a ; and then excel splits that as well and so moves all columns one to the right) I want per chunk I load into see the number of delimiters in the first column compare it to the "right" number of delimiters for the chunk (I simplify this by using mode as consensus) and then simply send this faulty rows to a list.

I believe the error comes from how I use pandas I am new to coding and while pandas seems perfect to handle the data i am still reading a lot about how to properly address column and rows.

The code goes through my hundreds of csv files loads them in in chunks based on a absolutely uncommon delimiter in this case |. This creates a data dataframe where I have the whole csv row combined in one field what allows me than in turn to count the correct delimiter (in this case ;).

```<code>la=[]
for filename in all_files:
     for chunk in pd.read_csv(filename, sep='|', chunksize=1000000):
         chunk['filename'] = os.path.basename(filename)
         chunk["delimeters"] = chunk.iloc[:,0].str.count(',')
         chunk['good delimeter'] = chunk["delimeters"].mode()

         for index, row in chunk.iterrows():
             if row['delimeters'] != chunk['good delimeter']:
               la.append(row)
             else:
               print("all good")

print(la)
</code>```

My main problem is currently that when I look into my chunk dataframe the count of delimiter works well however the mode is only appended to the first row so when i look at chunk it looks as follows:

```<code>    Name| Filename| delimetier| good delimeter
    A     123       48         48
    B     123       48         Nan
    C     123       49         Nan
    D     123       48         Nan
</code>```

However I would like to have the mode of the delimiter column appended to all so that I can compare them with the if statement and so filter out the fault rows.

When now running this script for this post I also encounter the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

However I assume this is a follow up error caused by the Nan

答:
This line is not returning/assigning a scalar value, but rather a numpy array:

```<code>chunk['good delimeter'] = chunk["delimeters"].mode()
</code>```

Change it to:

```<code>chunk['good delimeter'] = chunk["delimeters"].mode()[0]
</code>```

Which will assign the mode value to all rows with a type of numpy.float64.

Body:
After encountering some broken csv files in the past I am working on a smale python code which allows to filter out this faulty lines so I can manually check them for a pattern and if possible fix them.

However when wanting to append the right amount of columns I expect the file to have I only get the "mode" most frequent observation of delimiter in the first row and not all rows.

This kind of broken csvs file usually comes if a row has more separating delimiters than it actually has columns (e.g. if the name of the client has also a ; and then excel splits that as well and so moves all columns one to the right) I want per chunk I load into see the number of delimiters in the first column compare it to the "right" number of delimiters for the chunk (I simplify this by using mode as consensus) and then simply send this faulty rows to a list.

I believe the error comes from how I use pandas I am new to coding and while pandas seems perfect to handle the data i am still reading a lot about how to properly address column and rows.

The code goes through my hundreds of csv files loads them in in chunks based on a absolutely uncommon delimiter in this case |. This creates a data dataframe where I have the whole csv row combined in one field what allows me than in turn to count the correct delimiter (in this case ;).

la=[]
for filename in all_files:
     for chunk in pd.read_csv(filename, sep='|', chunksize=1000000):
         chunk['filename'] = os.path.basename(filename)
         chunk["delimeters"] = chunk.iloc[:,0].str.count(',')
         chunk['good delimeter'] = chunk["delimeters"].mode()

         for index, row in chunk.iterrows():
             if row['delimeters'] != chunk['good delimeter']:
               la.append(row)
             else:
               print("all good")

print(la)

My main problem is currently that when I look into my chunk dataframe the count of delimiter works well however the mode is only appended to the first row so when i look at chunk it looks as follows:

    Name| Filename| delimetier| good delimeter
    A     123       48         48
    B     123       48         Nan
    C     123       49         Nan
    D     123       48         Nan

However I would like to have the mode of the delimiter column appended to all so that I can compare them with the if statement and so filter out the fault rows.

When now running this script for this post I also encounter the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

However I assume this is a follow up error caused by the Nan

Body:
This line is not returning/assigning a scalar value, but rather a numpy array:

chunk['good delimeter'] = chunk["delimeters"].mode()

Change it to:

chunk['good delimeter'] = chunk["delimeters"].mode()[0]

Which will assign the mode value to all rows with a type of numpy.float64.