问:
React - How do you cleanup useEffect() after fetching data and setting a state with that data?
I am making a fetch request to my server with the hook useEffect, and I keep getting this warning:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

I understand the reason for this warning, but how do I clean it up? I have tried methods suggested in this article with no luck: https://dev.to/pallymore/clean-up-async-requests-in-useeffect-hooks-90h

Here is my code:

```<code>import React, { useEffect, useState } from 'react';
import { Redirect, Route } from 'react-router-dom';

export default function ProtectedRoute({ component: Component, ...rest }) {

    const [ user, setUser ] = useState('');

    useEffect(() => {
        const fetchUser = async () => {
            try {
                const response = await fetch('http://localhost:5000/user', {
                    credentials: 'include'
                });

                const data = await response.json();

                setUser(data.session.passport.user);

            } catch (error) {
                console.log(error);
            }
        }

        fetchUser();

        return () => {
         // Do some cleanup
        }
    }, [])

    return (
         <Route { ...rest } render={ () => user ? <Component /> : <Redirect to="/login" /> }/>
    )
}
</code>```

Any help is appreciated :)

UPDATE: Thanks to Tony Nguyen's solution below, here is my working code:

```<code>import React, { useEffect, useState } from 'react';
import { Redirect, Route } from 'react-router-dom';

import Loading from './Loading';
import Error from './Error';

export default function ProtectedRoute({ component: Component, ...rest }) {

    const [ user, setUser ] = useState('');
    const [ fetchingUser, setFetchingUser ] = useState(true);
    const [ noError, setNoError ] = useState(true);

    useEffect(() => {
        const fetchUser = async () => {
            try {
                const response = await fetch('http://localhost:5000/user', {
                    credentials: 'include'
                });

                if (fetchingUser) {
                    const data = await response.json();
                    setUser(data.session.passport.user);
                }

                setFetchingUser(false);

            } catch {
                setNoError(false);
            }
        }

        fetchUser();
    }, [])

    return (

        <div>
            <Route { ...rest } render={ () => { if (!noError) return <Error />} }/>
            <Route { ...rest } render={ () => { if (fetchingUser && noError) return <Loading />} }/>
            <Route { ...rest } render={ () => { if (user && !fetchingUser && noError) return <Component />} }/>
            <Route { ...rest } render={ () => { if (!user && !fetchingUser && noError) return <Redirect to="/login" />} }/>
        </div>
    )
}
</code>```

答:
Your first piece of code is ok just need some modification that is adding fetchingUser to let the component know you fetching user, do not redirect

import React, { useEffect, useState } from 'react';
import { Redirect, Route } from 'react-router-dom';

export default function ProtectedRoute({ component: Component, ...rest }) {
     // add fetchingUser state with defaut is true
     const [ fetchingUser, setFetchingUser ] = useState(true);
    const [ user, setUser ] = useState('');

    useEffect(() => {
        const fetchUser = async () => {
            try {
                const response = await fetch('http://localhost:5000/user', {
                    credentials: 'include'
                });

                const data = await response.json();
                setUser(data.session.passport.user);
                // setFetching is false here
                setFetchingUser(false)

            } catch (error) {
                // You can create an error state and set error here
                console.log(error);
            }
        }

        fetchUser();

        return () => {
         // Do some cleanup
        }
    }, [])

  // add fetchingUser into conditions
  // You can do better job that is if fetching show Loading component
  // If error show error component
  // if not fetching not error and have user show user component
  // if not fetching not error and not user redirect to login
    return (
         <Route { ...rest } render={ () => user && !fetchingUser ? <Component /> : <Redirect to="/login" /> }/>
    )
}```

Body:
I am making a fetch request to my server with the hook useEffect, and I keep getting this warning:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

I understand the reason for this warning, but how do I clean it up? I have tried methods suggested in this article with no luck: https://dev.to/pallymore/clean-up-async-requests-in-useeffect-hooks-90h

Here is my code:

import React, { useEffect, useState } from 'react';
import { Redirect, Route } from 'react-router-dom';

export default function ProtectedRoute({ component: Component, ...rest }) {

    const [ user, setUser ] = useState('');

    useEffect(() => {
        const fetchUser = async () => {
            try {
                const response = await fetch('http://localhost:5000/user', {
                    credentials: 'include'
                });

                const data = await response.json();

                setUser(data.session.passport.user);

            } catch (error) {
                console.log(error);
            }
        }

        fetchUser();

        return () => {
         // Do some cleanup
        }
    }, [])

    return (
         <Route { ...rest } render={ () => user ? <Component /> : <Redirect to="/login" /> }/>
    )
}

Any help is appreciated :)

UPDATE: Thanks to Tony Nguyen's solution below, here is my working code:

import React, { useEffect, useState } from 'react';
import { Redirect, Route } from 'react-router-dom';

import Loading from './Loading';
import Error from './Error';

export default function ProtectedRoute({ component: Component, ...rest }) {

    const [ user, setUser ] = useState('');
    const [ fetchingUser, setFetchingUser ] = useState(true);
    const [ noError, setNoError ] = useState(true);

    useEffect(() => {
        const fetchUser = async () => {
            try {
                const response = await fetch('http://localhost:5000/user', {
                    credentials: 'include'
                });

                if (fetchingUser) {
                    const data = await response.json();
                    setUser(data.session.passport.user);
                }

                setFetchingUser(false);

            } catch {
                setNoError(false);
            }
        }

        fetchUser();
    }, [])

    return (

            <Route { ...rest } render={ () => { if (!noError) return <Error />} }/>
            <Route { ...rest } render={ () => { if (fetchingUser && noError) return <Loading />} }/>
            <Route { ...rest } render={ () => { if (user && !fetchingUser && noError) return <Component />} }/>
            <Route { ...rest } render={ () => { if (!user && !fetchingUser && noError) return <Redirect to="/login" />} }/>

    )
}


来源: stackexchange

问:
Content animation does not work on iPAD, iphone with chrome browser
I have a simple animation that works on Windows but does not work on iPAD or iPhone.

THis works fine when i see it through my desktop chrome browser. But on iPAD it just shows the "Default" value and animation fails to run.

Can someone let me know what am i doing wrong. Below is my style.css

```<code>.typinganimation::before {
    content: 'Default';
    animation: typing infinite 12s;
    -webkit-animation: typing infinite 12s;
}

@keyframes typing {
    0% {
        content: 'A';
    }
    25% {
        content: 'B';
    }
    50% {
        content: 'C';
    }
    65% {
        content: 'D';
    }
    100% {
        content: 'A';
    }
}

@-webkit-keyframes typing {
    0% {
        content: 'A';
    }
    25% {
        content: 'B';
    }
    50% {
        content: 'C';
    }
    65% {
        content: 'D';
    }
    100% {
        content: 'A';
    }
}
</code>```

Is there anything extra that needs to be done for iOS

答: It seems the content tag is not supported by Safari hence not showing up on the iPAD/iPhone</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a simple animation that works on Windows but does not work on iPAD or iPhone.

THis works fine when i see it through my desktop chrome browser. But on iPAD it just shows the "Default" value and animation fails to run.

Can someone let me know what am i doing wrong. Below is my style.css

.typinganimation::before {
    content: 'Default';
    animation: typing infinite 12s;
    -webkit-animation: typing infinite 12s;
}

@keyframes typing {
    0% {
        content: 'A';
    }
    25% {
        content: 'B';
    }
    50% {
        content: 'C';
    }
    65% {
        content: 'D';
    }
    100% {
        content: 'A';
    }
}

@-webkit-keyframes typing {
    0% {
        content: 'A';
    }
    25% {
        content: 'B';
    }
    50% {
        content: 'C';
    }
    65% {
        content: 'D';
    }
    100% {
        content: 'A';
    }
}

Is there anything extra that needs to be done for iOS


问:
How to integrate automatic payment charged in ionic with paypal using credit card
I’m developing a delivery application that will work with PayPal for payments. Ionic/Cordova has a native library that makes things easy, yet the flow is not the way i’d like it to be.

With “PayPal-Cordova-Plugin”, the authentication window opens for every payment and the user must click the button to confirm the payment.

What I would like to implement was something more direct, transparent. The user would authenticate with PayPal within my application and with the probable token that would receive this authentication, I would execute the checkout requests (an example would be the payment by PayPal on Uber).

With the PayPal developer documentation I could not find a way to perform this implementation on Ionic, so I would like help with that.

答:
The old PayPal Mobile SDKs used by the cordova plugin are ancient. Do not use those. Do not use those for anything. If you try to use those, you are going to have a bad time.

The first paragraph at the top of the Readme of https://github.com/paypal/PayPal-Cordova-Plugin points you to the things you should be using instead.

As is mentioned there, PayPal Express Checkout via the Braintree Mobile SDK is a worldwide option for those who need a native SDK. It is documented here: https://developer.paypal.com/docs/accept-payments/express-checkout/ec-braintree-sdk/get-started/

You will need a webservice for the server-side portion.


问:
How to solve date format problem when using Window XP in C?
I am using Window 7, when I run my code in local everything is alright, but when upload to Window server 2003 the code will coming error:

"String was not recognized as a valid DateTime"

My computer setting (date format) all same with my window server. Still come out the same problem.

below is my code:

```<code>dateFrom = Convert.ToDateTime("12-6-2011");

dateTo = Convert.ToDateTime("18-6-2011");

//or
dateFrom = DateTime.ParseExact("12-6-2011", "MM/dd/yyyy", CultureInfo.InvariantCulture);

dateTo = DateTime.ParseExact("18-6-2011", "MM/dd/yyyy", CultureInfo.InvariantCulture);

//i using parse also din come out.
</code>```

答:
I do not know how this relates to the 'C' language, so I may have misinterpreted something. However, you are using the wrong format string as far as I can see.

If your dates always look like that, try using a format string like "d-M-yyyy".

Have a look at the following page for reference: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Body:
I am using Window 7, when I run my code in local everything is alright, but when upload to Window server 2003 the code will coming error:

"String was not recognized as a valid DateTime"

My computer setting (date format) all same with my window server. Still come out the same problem.

below is my code:

dateFrom = Convert.ToDateTime("12-6-2011");

dateTo = Convert.ToDateTime("18-6-2011");

//or
dateFrom = DateTime.ParseExact("12-6-2011", "MM/dd/yyyy", CultureInfo.InvariantCulture);

dateTo = DateTime.ParseExact("18-6-2011", "MM/dd/yyyy", CultureInfo.InvariantCulture);

//i using parse also din come out.

ContentLicense: CC BY-SA 3.0


问:
Placeholder for contenteditable div
I have the following: FIDDLE

The placeholder works fine and dandy until you type something, ctrl + A, and delete. If you do that, the placeholder disappears and never shows up again.

What's wrong? How can I have a placeholder for a contenteditable div?

HTML:

```<code><div class="test" placeholder="Type something..." contenteditable="true"></div>
</code>```

CSS:

```<code>.test {
    width: 500px;
    height: 70px;
    background: #f5f5f5;
    border: 1px solid #ddd;
    padding: 5px;
}

.test[placeholder]:empty:before {
    content: attr(placeholder);
    color: #555;
}
</code>```

Thanks.

答:
This solution worked for me. I'd converted this solution from angular to pure javaScript

In .html

```<code><div placeholder="Write your message.." id="MyConteditableElement" onclick="clickedOnInput = true;" contenteditable class="form-control edit-box"></div>
</code>```

In .css

```<code>.holder:before {
    content: attr(placeholder);
    color: lightgray;
    display: block;
    position:absolute;
    font-family: "Campton", sans-serif;
}
</code>```

in js.

```<code>clickedOnInput:boolean = false;
charactorCount:number = 0;
let charCount = document.getElementsByClassName('edit-box')[0];

if(charCount){
this.charactorCount = charCount.innerText.length;
}

if(charactorCount > 0 && clickedOnInput){
document.getElementById("MyConteditableElement").classList.add('holder');
}

if(charactorCount == 0 && !clickedOnInput){
document.getElementById("MyConteditableElement").classList.remove('holder');
}

getContent(innerText){
  this.clickedOnInput = false;
}
</code>```

Title: Placeholder for contenteditable div

Body:
I have the following: FIDDLE

The placeholder works fine and dandy until you type something, ctrl + A, and delete. If you do that, the placeholder disappears and never shows up again.

What's wrong? How can I have a placeholder for a contenteditable div?

HTML:

CSS:

.test {
    width: 500px;
    height: 70px;
    background: #f5f5f5;
    border: 1px solid #ddd;
    padding: 5px;
}

.test[placeholder]:empty:before {
    content: attr(placeholder);
    color: #555;
}

Thanks.

Body:
This solution worked for me. I'd converted this solution from angular to pure javaScript

In .html

<div placeholder="Write your message.." id="MyConteditableElement" onclick="clickedOnInput = true;" contenteditable class="form-control edit-box"></div>

In .css

.holder:before {
    content: attr(placeholder);
    color: lightgray;
    display: block;
    position:absolute;
    font-family: "Campton", sans-serif;
}

in js.

clickedOnInput:boolean = false;
charactorCount:number = 0;
let charCount = document.getElementsByClassName('edit-box')[0];

if(charCount){
this.charactorCount = charCount.innerText.length;
}

if(charactorCount > 0 && clickedOnInput){
document.getElementById("MyConteditableElement").classList.add('holder');
}

if(charactorCount == 0 && !clickedOnInput){
document.getElementById("MyConteditableElement").classList.remove('holder');
}

getContent(innerText){
  this.clickedOnInput = false;
}


问:
Kotlin Android Navigation Drawer item onclick listener does not working
I know this already asked many times, but in my case, I still don't get it.

So I have a navigation drawer that set up in the MainActivity.kt (My app has many fragment that runs on this Activity).

MainActivity.kt

```<code>class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    lateinit var drawerLayout: DrawerLayout
    lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)

        drawerLayout = binding.drawerLayout

        //Get navigation controller of this App
        val navController = this.findNavController(R.id.myNavHostFragment)

        //Lock the Nav drawer
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)

        NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)
        NavigationUI.setupWithNavController(binding.navView, navController)
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_logout -> {
                Toast.makeText(this, "Publication", Toast.LENGTH_SHORT).show()
                Log.i("MainActivity", "Sign out clicked!")
            }
            R.id.nav_messages -> {
                Toast.makeText(this, "Publication", Toast.LENGTH_SHORT).show()
            }
        }

        binding.drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }

    // Set up the back button on action bar
    override fun onSupportNavigateUp(): Boolean {
        val navController = this.findNavController(R.id.myNavHostFragment)

        return NavigationUI.navigateUp(navController, drawerLayout)
    }
}
</code>```

This is my Activity_main.xml

Activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.drawerlayout.widget.DrawerLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

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

            <fragment
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/myNavHostFragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                app:navGraph = "@navigation/navigation"
                app:defaultNavHost = "true"
                />

        </LinearLayout>

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/nav_drawer_menu"/>

    </androidx.drawerlayout.widget.DrawerLayout>

</layout>
</code>```

This is the menu layout for the navigation drawer:
nav_drawer_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group>
        <item
            android:id="@+id/nav_profile"
            android:icon="@drawable/ic_person"
            android:title="Profile"/>
        <item
            android:id="@+id/nav_messages"
            android:icon="@drawable/ic_people"
            android:title="Messages"/>
    </group>

    <item android:title="Account Settings">
        <menu>
            <item
                android:id="@+id/nav_logout"
                android:title="Sign Out"/>
        </menu>
    </item>
</menu>
</code>```

This is how the navigation drawer looks like.

Am I missing something ? If there's anything unclear let me know.

答:
You should use setNavigationItemSelectedListener.

Set a listener that will be notified when a menu item is selected.

```<code> navigationViewOBJ.setNavigationItemSelectedListener(this)
</code>```

For DataBinding You should use

```<code> binding.navView.setNavigationItemSelectedListener(this)
</code>```

Body:
I know this already asked many times, but in my case, I still don't get it.

So I have a navigation drawer that set up in the MainActivity.kt (My app has many fragment that runs on this Activity).

MainActivity.kt

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    lateinit var drawerLayout: DrawerLayout
    lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)

        drawerLayout = binding.drawerLayout

        //Get navigation controller of this App
        val navController = this.findNavController(R.id.myNavHostFragment)

        //Lock the Nav drawer
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)

        NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout)
        NavigationUI.setupWithNavController(binding.navView, navController)
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_logout -> {
                Toast.makeText(this, "Publication", Toast.LENGTH_SHORT).show()
                Log.i("MainActivity", "Sign out clicked!")
            }
            R.id.nav_messages -> {
                Toast.makeText(this, "Publication", Toast.LENGTH_SHORT).show()
            }
        }

        binding.drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }

    // Set up the back button on action bar
    override fun onSupportNavigateUp(): Boolean {
        val navController = this.findNavController(R.id.myNavHostFragment)

        return NavigationUI.navigateUp(navController, drawerLayout)
    }
}

This is my Activity_main.xml

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.drawerlayout.widget.DrawerLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

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

            <fragment
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/myNavHostFragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                app:navGraph = "@navigation/navigation"
                app:defaultNavHost = "true"
                />

        </LinearLayout>

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/nav_drawer_menu"/>

    </androidx.drawerlayout.widget.DrawerLayout>

</layout>

This is the menu layout for the navigation drawer:
nav_drawer_menu.xml

<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group>
        <item
            android:id="@+id/nav_profile"
            android:icon="@drawable/ic_person"
            android:title="Profile"/>
        <item
            android:id="@+id/nav_messages"
            android:icon="@drawable/ic_people"
            android:title="Messages"/>
    </group>

    <item android:title="Account Settings">
        <menu>
            <item
                android:id="@+id/nav_logout"
                android:title="Sign Out"/>
        </menu>
    </item>
</menu>

This is how the navigation drawer looks like.

Am I missing something ? If there's anything unclear let me know.

Body:
You should use setNavigationItemSelectedListener.

Set a listener that will be notified when a menu item is selected.

 navigationViewOBJ.setNavigationItemSelectedListener(this)

For DataBinding You should use

 binding.navView.setNavigationItemSelectedListener(this)


问:
What happened when invoking locals() in python3?
I'm using Python3.7.2

The code which makes me confused looks like this:

```<code>def foo(cond):
    if cond:
        z = 1
        return z
    else:
        loc = locals()
        x = 1
        locals()['y'] = 2
        exec("z = x + y")
        print(loc)
        print(locals())

foo(False)
</code>```

Here is the result it prints:

```<code>{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}
{'cond': False, 'loc': {...}, 'x': 1, 'y': 2}
</code>```

The exec function changes the local namespace, but when I execute locals(), variable z disappeared.

However, if I change the code like this:

```<code>def foo(cond):
    if cond:
        return 1
    else:
        loc = locals()
        x = 1
        locals()['y'] = 2
        exec("z = x + y")
        print(loc)
        print(locals())

foo(False)
</code>```

The result will be:

```<code>{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}
{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}
</code>```

I'm really confused. :(

答:
In short: the dictionary returned by locals() is only a copy of the true local variables—which are stored in an array, not in a dictionary.  You can manipulate the locals() dictionary, add or remove entries at will.  Python does not care since that is merely a copy of the local variables it works with.  However, each time you call locals(), Python copies the current values of all local variables into the dictionary, replacing anything else you or exec() put in before.  So, if z is a proper local variable (as in the first, but not second version of your code), locals() will restore its current value, which happens to be "not set" or "undefined".

Indeed, conceptually Python stores local variables in a dictionary, which can be retrieved through the function locals().  However, internally, it really is two arrays.  The names of the locals are an attribute of the code itself and therefore stored in the code object as code.co_varnames.  Their values, however, are stored in the frame as fast (which is inaccessible from Python code).  You can find more on co_varnames etc. in inspect and dis modules, respectively.

The built-in function locals() actually calls a method fastToLocals() on the current frame object.  If we were to write the frame with its fastToLocals method in Python, it might look like this (I am leaving out a lot of details here):

class frame:
    def __init__(self, code):
        self.__locals_dict = None
        self.f_code = code
        self.__fast = [0] * len(code.co_varnames)

    def fastToLocals(self):
        if self.__locals_dict is None:
            self.__locals_dict = {}
        for (key, value) in zip(self.f_code.co_varnames, self.__fast):
            if value is not null:             # Remember: it's actually C-code
                self.__locals_dict[key] = value
            else:
                del self.__locals_dict[key]   # <- Here's the magic
        return self.__locals_dict

def locals():
    frame = sys._getframe(1)
    frame.fastToLocals()
```

In plain English: the dictionary you get when calling locals() is cached in the current frame.  Calling locals() repeatedly will give you the same dictionary (__locals_dict in the code above).  However, each time, you call locals(), the frame will update the entries in this dictionary with the current values that local variables have at that time.  As noted here, when a local variable is not set, the entry in the __locals_dict is deleted.  And that's what it is all about.

In your first version of the code, the third line says z = 1, which makes z a local variable.  In the else branch, however, that local variable z is not set (i.e. would raise a UnboundLocalError) and is therefore removed from the __locals_dict.  In the second version of your code, there is no assignment to z, so it is not a local variable and the locals() function does not care about it.

The set of local variables is actually fixed by the compiler.  This means that you cannot add or remove local variables at runtime.  This is a problem for exec(), as you are clearly using exec() here to define a local variable z.  Python's way out is to say that exec() stores z as a local variable in the _locals_dict dictionary, although it cannot put it into the arrays behind this dictionary.

Conclusion:  The values of local variables are actually stored in an array, not in the dictionary returned by locals().  When calling locals(), the dictionary is updated with the true current values taken from the dictionary.  exec(), on the other hand, can only store its local variables in the dictionary, not in the array.  If z is a proper local variable, it will be overwritten by a call to locals() with its current value (which is "does not exist").  If z is not a proper local variable, it will stay in the dictionary untouched.

Python's specifications say that any variable that you assign to inside a function is a local variable.  You can change this default through the use of global or nonlocal, of course.  But as soon as you write z = ..., z becomes a local variable.  If, on the other hand, you only have x = z in your code, the compiler assumes that z is rather a global variable.  That's why the line z = 1 makes all the difference: it marks z as a local variable that receives its place in the fast array.

Concerning exec(): in general, there is no way the compiler could really know what code exec() is going to execute (in your case with a string literal it could, but since this is a are rare and uninteresting case, it never tries, anyway).  The compiler can therefore not know what local (or global) variables the code in exec() might access, and cannot include that in its calculation of how large the array of local variables should be.

By the way: that local variables are managed in arrays instead of proper dictionaries is the reason why there might be raised an UnboundLocalError instead of an NameError.  In case of local variables, the Python interpreter actually recognises the name and knows exactly where its value is to be found (inside the fast array mentioned above).  But if that entry is null, it cannot return something meaningful and therefore raises the UnboundLocalError.  For global names, however, Python goes really searched for a variable with the given name in the globals and built-in dictionaries.  In that case, a variable of the requested name might truly not exist.

Body:
I'm using Python3.7.2

The code which makes me confused looks like this:

def foo(cond):
    if cond:
        z = 1
        return z
    else:
        loc = locals()
        x = 1
        locals()['y'] = 2
        exec("z = x + y")
        print(loc)
        print(locals())

foo(False)

Here is the result it prints:

{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}
{'cond': False, 'loc': {...}, 'x': 1, 'y': 2}

The exec function changes the local namespace, but when I execute locals(), variable z disappeared.

However, if I change the code like this:

def foo(cond):
    if cond:
        return 1
    else:
        loc = locals()
        x = 1
        locals()['y'] = 2
        exec("z = x + y")
        print(loc)
        print(locals())

foo(False)

The result will be:

{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}
{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}

I'm really confused. :(

Body:
In short: the dictionary returned by locals() is only a copy of the true local variables—which are stored in an array, not in a dictionary.  You can manipulate the locals() dictionary, add or remove entries at will.  Python does not care since that is merely a copy of the local variables it works with.  However, each time you call locals(), Python copies the current values of all local variables into the dictionary, replacing anything else you or exec() put in before.  So, if z is a proper local variable (as in the first, but not second version of your code), locals() will restore its current value, which happens to be "not set" or "undefined".

Indeed, conceptually Python stores local variables in a dictionary, which can be retrieved through the function locals().  However, internally, it really is two arrays.  The names of the locals are an attribute of the code itself and therefore stored in the code object as code.co_varnames.  Their values, however, are stored in the frame as fast (which is inaccessible from Python code).  You can find more on co_varnames etc. in inspect and dis modules, respectively.

The built-in function locals() actually calls a method fastToLocals() on the current frame object.  If we were to write the frame with its fastToLocals method in Python, it might look like this (I am leaving out a lot of details here):

class frame:
    def __init__(self, code):
        self.__locals_dict = None
        self.f_code = code
        self.__fast = [0] * len(code.co_varnames)

    def fastToLocals(self):
        if self.__locals_dict is None:
            self.__locals_dict = {}
        for (key, value) in zip(self.f_code.co_varnames, self.__fast):
            if value is not null:             # Remember: it's actually C-code
                self.__locals_dict[key] = value
            else:
                del self.__locals_dict[key]   # <- Here's the magic
        return self.__locals_dict

def locals():
    frame = sys._getframe(1)
    frame.fastToLocals()

In plain English: the dictionary you get when calling locals() is cached in the current frame.  Calling locals() repeatedly will give you the same dictionary (__locals_dict in the code above).  However, each time, you call locals(), the frame will update the entries in this dictionary with the current values that local variables have at that time.  As noted here, when a local variable is not set, the entry in the __locals_dict is deleted.  And that's what it is all about.

In your first version of the code, the third line says z = 1, which makes z a local variable.  In the else branch, however, that local variable z is not set (i.e. would raise a UnboundLocalError) and is therefore removed from the __locals_dict.  In the second version of your code, there is no assignment to z, so it is not a local variable and the locals() function does not care about it.

The set of local variables is actually fixed by the compiler.  This means that you cannot add or remove local variables at runtime.  This is a problem for exec(), as you are clearly using exec() here to define a local variable z.  Python's way out is to say that exec() stores z as a local variable in the _locals_dict dictionary, although it cannot put it into the arrays behind this dictionary.

Conclusion:  The values of local variables are actually stored in an array, not in the dictionary returned by locals().  When calling locals(), the dictionary is updated with the true current values taken from the dictionary.  exec(), on the other hand, can only store its local variables in the dictionary, not in the array.  If z is a proper local variable, it will be overwritten by a call to locals() with its current value (which is "does not exist").  If z is not a proper local variable, it will stay in the dictionary untouched.

Python's specifications say that any variable that you assign to inside a function is a local variable.  You can change this default through the use of global or nonlocal, of course.  But as soon as you write z = ..., z becomes a local variable.  If, on the other hand, you only have x = z in your code, the compiler assumes that z is rather a global variable.  That's why the line z = 1 makes all the difference: it marks z as a local variable that receives its place in the fast array.

Concerning exec(): in general, there is no way the compiler could really know what code exec() is going to execute (in your case with a string literal it could, but since this is a are rare and uninteresting case, it never tries, anyway).  The compiler can therefore not know what local (or global) variables the code in exec() might access, and cannot include that in its calculation of how large the array of local variables should be.

By the way: that local variables are managed in arrays instead of proper dictionaries is the reason why there might be raised an UnboundLocalError instead of an NameError.  In case of local variables, the Python interpreter actually recognises the name and knows exactly where its value is to be found (inside the fast array mentioned above).  But if that entry is null, it cannot return something meaningful and therefore raises the UnboundLocalError.  For global names, however, Python goes really searched for a variable with the given name in the globals and built-in dictionaries.  In that case, a variable of the requested name might truly not exist.


问:
How to get, delete and update nic dhcp of azure through poweshell?
Define user:

```<code>$userName = " xxxx"
</code>```

Set password:

```<code>$Pwd = ConvertTo-SecureString "xxxxx" -AsPlainText -Force
</code>```

Set credentials:

```<code>$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $userName, $Pwd
Connect-AzAccount -Credential $creds
Get-AzSubscription
Set-AzContext -Subscription  "xxxxxxxxxx"
Get-AzVM
Get-AzNetworkInterface -ResourceGroupName rba-test-rg
</code>```

答:
You can use the following script to list the the network interfaces under a particular VM and remove or update it. You can replace {nic needs to be deleted} and {nic needs to be updated} with your own conditional statement:

```<code>$vm = Get-AzVM -ResourceGroupName {resource group name} -Name {VM name}
$nics = $vm.NetworkProfile.NetworkInterfaces
foreach($nic in $nics){
    $aznics = Get-AzNetworkInterface -ResourceId $nic.id
    if({nic needs to be deleted}){
        $aznics | Remove-AzNetworkInterface
    }
    if({nic needs to be updated}){
        $aznics.DnsSettings.DnsServers.Add("192.168.1.100");
        $aznics | Set-AzNetworkInterface
    }
}
</code>```

Body:
Define user:

$userName = " xxxx"

Set password:

$Pwd = ConvertTo-SecureString "xxxxx" -AsPlainText -Force

Set credentials:

$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $userName, $Pwd
Connect-AzAccount -Credential $creds
Get-AzSubscription
Set-AzContext -Subscription  "xxxxxxxxxx"
Get-AzVM
Get-AzNetworkInterface -ResourceGroupName rba-test-rg

Body:
You can use the following script to list the the network interfaces under a particular VM and remove or update it. You can replace {nic needs to be deleted} and {nic needs to be updated} with your own conditional statement:

$vm = Get-AzVM -ResourceGroupName {resource group name} -Name {VM name}
$nics = $vm.NetworkProfile.NetworkInterfaces
foreach($nic in $nics){
    $aznics = Get-AzNetworkInterface -ResourceId $nic.id
    if({nic needs to be deleted}){
        $aznics | Remove-AzNetworkInterface
    }
    if({nic needs to be updated}){
        $aznics.DnsSettings.DnsServers.Add("192.168.1.100");
        $aznics | Set-AzNetworkInterface
    }
}


问:
Post Action method overload with same route name in ASP.Net Web API Controller
Is it possible to have two actions with same route name and same method but different parameter?
I have tried this:

```<code>[HttpPost]
[Route("gstr4")]
public HttpResponseMessage SubmitGSTR4([FromBody] RequestPayloadWithoutSign requestPayload)
{ }

[HttpPost]
[Route("gstr4")]
public HttpResponseMessage FileGSTR4([FromBody] RequestPayloadWithSign requestPayload)
{ }
</code>```

I received a Status Code of 500 (InternalServerError) and here is raw response:

```<code>{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nFileGSTR4 on type APIPortal.Controllers.GSTR4Controller\r\nSubmitGSTR4 on type APIPortal.Controllers.GSTR4Controller","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}
</code>```

答: It's not possible for the same method type as http Get for multiple methods. You should have a different route</p>

Body:
Is it possible to have two actions with same route name and same method but different parameter?
I have tried this:

[HttpPost]
[Route("gstr4")]
public HttpResponseMessage SubmitGSTR4([FromBody] RequestPayloadWithoutSign requestPayload)
{ }

[HttpPost]
[Route("gstr4")]
public HttpResponseMessage FileGSTR4([FromBody] RequestPayloadWithSign requestPayload)
{ }

I received a Status Code of 500 (InternalServerError) and here is raw response:

{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nFileGSTR4 on type APIPortal.Controllers.GSTR4Controller\r\nSubmitGSTR4 on type APIPortal.Controllers.GSTR4Controller","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}


问:
How to yield all possibilities using efficient nesting in Python?
Forex Triangular Arb problem:

I'm currently trying to solve an efficient way on how to yield all of the elements of a Dictionary.items(). Let's suppose the array has N length and I need to acquire a all possible combinations where [[A,B],[A,C],[C,B]...]

Currently, it is not efficient due to nesting

```<code>def Arb(tickers: dict) -> list:
    for first_pair in tickers.items():
        pair1: list = first_pair[0].split("/")

        for second_pair in tickers.items():
            pair2: list = second_pair[0].split("/")

            if pair2[0] == pair1[0] and pair2[1] != pair1[1]:

                for third_pair in tickers.items():
                    pair3: list = third_pair[0].split("/")

                    if pair3[0] == pair2[1] and pair3[1] == pair1[1]:

                      id1 = first_pair[1]["id"]
                      id2 = second_pair[1]["id"]
                      id3 = third_pair[1]["id"]

                      yield [pair1, id1, pair2, id2, pair3, id3]

</code>```

What would be the efficient/pythonic way to return a List with all possible items?

This is an example

```<code>tickers =   {"EZ/TC": {
              "id": 1
            },
            "LM/TH": {
              "id": 2
            },
            "CD/EH": {
              "id": 3
            },
            "EH/TC": {
              "id":4
            },
            "LM/TC": {
              "id": 5
            },
            "CD/TC":{
              "id": 6
            },
            "BT/TH": {
              "id": 7,
            },
            "BT/TX": {
              "id": 8,
            },
            "TX/TH":{
              "id": 9
            }

            }
</code>```

```<code>print(list(Arb(tickers)))

[(['CD', 'TC'], 6, ['CD', 'EH'], 3, ['EH', 'TC'], 4), (['BT', 'TH'], 7, ['BT', 'TX'], 8, ['TX', 'TH'], 9)]

</code>```

The Output is a Single List comprised of "lists" of all possibilities.

答:
Itertools.permutations and itertools.combinations could be helpful for this type of problem: https://docs.python.org/3/library/itertools.html

Here's a link with an example using itertools.permutations:
https://www.geeksforgeeks.org/python-itertools-permutations/

Body:
Forex Triangular Arb problem:

I'm currently trying to solve an efficient way on how to yield all of the elements of a Dictionary.items(). Let's suppose the array has N length and I need to acquire a all possible combinations where [[A,B],[A,C],[C,B]...]

Currently, it is not efficient due to nesting

def Arb(tickers: dict) -> list:
    for first_pair in tickers.items():
        pair1: list = first_pair[0].split("/")

        for second_pair in tickers.items():
            pair2: list = second_pair[0].split("/")

            if pair2[0] == pair1[0] and pair2[1] != pair1[1]:

                for third_pair in tickers.items():
                    pair3: list = third_pair[0].split("/")

                    if pair3[0] == pair2[1] and pair3[1] == pair1[1]:

                      id1 = first_pair[1]["id"]
                      id2 = second_pair[1]["id"]
                      id3 = third_pair[1]["id"]

                      yield [pair1, id1, pair2, id2, pair3, id3]

What would be the efficient/pythonic way to return a List with all possible items?

This is an example

tickers =   {"EZ/TC": {
              "id": 1
            },
            "LM/TH": {
              "id": 2
            },
            "CD/EH": {
              "id": 3
            },
            "EH/TC": {
              "id":4
            },
            "LM/TC": {
              "id": 5
            },
            "CD/TC":{
              "id": 6
            },
            "BT/TH": {
              "id": 7,
            },
            "BT/TX": {
              "id": 8,
            },
            "TX/TH":{
              "id": 9
            }

            }

print(list(Arb(tickers)))

[(['CD', 'TC'], 6, ['CD', 'EH'], 3, ['EH', 'TC'], 4), (['BT', 'TH'], 7, ['BT', 'TX'], 8, ['TX', 'TH'], 9)]

The Output is a Single List comprised of "lists" of all possibilities.


问:
Is there any way to SET client_encoding TO 'UTF8' permanent?
I connect to my db from console using command:

psql -U postgres task_db
```

<p>and did this select query : </p>

<pre class="lang-sql prettyprint-override"><code>select * from common.task;
</code>```

I received this Error:

```<code>ERROR:  character with byte sequence 0xe5 0xb0 0x8f in encoding "UTF8" has no equivalent in encoding "WIN1252"
</code>```

And followed this command from this answer to fix this: https://stackoverflow.com/a/38487921/7505731

SET client_encoding TO 'UTF8';
```

It worked.

Problem : Now I have to run above command every time I connect to db from command line. Is there any way I can set this encoding permanent?

答:
You can try to set this command in your .psqlrc file:

Unless it is passed an -X option, psql attempts to read and execute commands from the system-wide startup file (psqlrc) and then
  the user's personal startup file (~/.psqlrc), after connecting to the
  database but before accepting normal commands. These files can be used
  to set up the client and/or the server to taste, typically with \set
  and SET commands.

The system-wide startup file is named psqlrc and is sought in the installation's “system configuration” directory, which is most
  reliably identified by running pg_config --sysconfdir. By default this
  directory will be ../etc/ relative to the directory containing the
  PostgreSQL executables. The name of this directory can be set
  explicitly via the PGSYSCONFDIR environment variable.

The user's personal startup file is named .psqlrc and is sought in the invoking user's home directory. On Windows, which lacks such a
  concept, the personal startup file is named
  %APPDATA%\postgresql\psqlrc.conf. The location of the user's startup
  file can be set explicitly via the PSQLRC environment variable.

Both the system-wide startup file and the user's personal startup file can be made psql-version-specific by appending a dash and the
  PostgreSQL major or minor release number to the file name, for example
  ~/.psqlrc-9.2 or ~/.psqlrc-9.2.5. The most specific version-matching
  file will be read in preference to a non-version-specific file.

Body:
I connect to my db from console using command:

psql -U postgres task_db

and did this select query :

select * from common.task;

I received this Error:

ERROR:  character with byte sequence 0xe5 0xb0 0x8f in encoding "UTF8" has no equivalent in encoding "WIN1252"

And followed this command from this answer to fix this: https://stackoverflow.com/a/38487921/7505731

SET client_encoding TO 'UTF8';

It worked.

Problem : Now I have to run above command every time I connect to db from command line. Is there any way I can set this encoding permanent?


问:
Google Play Billing (testing mode): why my purchase is automatically canceled
I followed all the best practices from Google Developer Doc: https://developer.android.com/google/play/billing/billing_library_overview

I push my App in Beta test mode. All works perfectly, except at each time I do in-app (or subscription) purchase, I receive an email (purchase confirmation, OK), then 5-6 minutes later I receive another email (always from Google) to inform my purchase has been canceled...

I don't want an automatic cancel. Why this process?

Thank you very much guys!

答:
Check out this doc

You have to call billingClient.acknowledgePurchase() method when you get purchase.purchaseState === Purchase.PurchaseState.PURCHASED on onPurchasesUpdated callback, otherwise your purchased will be automatically refunded/cancelled.

Further reference


问:
AttributeError: 'ParsedRequirement' object has no attribute 'req'
I have docker file with one layer as

```<code>RUN python setup.py develop
</code>```

I am using a mutli-stage build with three stages and this is the stage one all the stages have the same base image, though I don't think this is a problem with dockerfile but seems to be a problem with python and the way it is executed
working on the base image python:3.7-slim
I am building this dockerfile on Travis CI with this below
Version info on Travis:

```<code>docker version
Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:42:38 2017
 OS/Arch:      linux/amd64
Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:41:20 2017
 OS/Arch:      linux/amd64
 Experimental: false
</code>```

I get this below error as

```<code>AttributeError: 'ParsedRequirement' object has no attribute 'req'
</code>```

Surprisingly I am able to have this working on My mac machine with docker version 19.03.2
Here is my setup.py file

import os
import shutil
import inspect
import platform
from setuptools import setup
import setuptools
try:
    from pip.req import parse_requirements
except ImportError:
    from pip._internal.req import parse_requirements

EMAIL_CONF = 'email.conf'
DL_CONF = 'dl.conf'
LINUX_CONFDIR = os.path.expanduser('~') + '/.config/bassa/'
WIN_CONFDIR = os.path.expanduser('~') + '/%app_data%/bassa/'
OSX_CONFDIR  = os.path.expanduser('~') + '/.config/bassa/'

# Utility function to read the README file.
def read(file_name):
    return open(os.path.join(os.path.dirname(__file__), file_name)).read()

base_dir = os.path.dirname(os.path.abspath(__file__))
requirements_path = os.path.join(base_dir, 'requirements.txt')

install_reqs = parse_requirements(requirements_path, session=False)

requirements = [str(ir.req) for ir in install_reqs]

### Set configs ###
if platform.system() == 'Linux':
    configdir = LINUX_CONFDIR
elif platform.system() == 'Windows':
    configdir = WIN_CONFDIR
elif platform.system() == 'Darwin':
    configdir = OSX_CONFDIR
if not os.path.exists(configdir):
    os.makedirs(configdir)

email_conf_location = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + "/" + EMAIL_CONF
dl_conf_location = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + "/" + DL_CONF
shutil.copyfile(email_conf_location, configdir + EMAIL_CONF)
shutil.copyfile(dl_conf_location, configdir + DL_CONF)

###/ Set configs ###

setup(
   ...
)

```

Please help me with this issue.

答:
Update:

* Please note that updating pip and pip-tools is not supported in my case. Then the workaround in my answer will help.

* If updating pip and pip-tools to compatible version is supported then refer to Gnnr's answer or Heapify's answer

I got the fix finally \o/

```<code>install_reqs = parse_requirements(requirements_path, session=False)
</code>```

At first, I have inspected what install_reqs was on Travis by simply logging it and found that it was a list of ParsedRequirement objects. I also found that this class is defined in req_file.py. I have gone to check the source code for req_file.py here on GitHub. I found that there was no such attribute called req but instead it is requirement. So there were two versions of parse_requirements function so I handled this using a try and except block.

```<code># Generator must be converted to list, or we will only have one chance to read each element, meaning that the first requirement will be skipped.
requirements = list(requirements)
try:
    requirements = [str(ir.req) for ir in install_reqs]
except:
    requirements = [str(ir.requirement) for ir in install_reqs]
</code>```

Now it is compatible with both the versions \0/

Body:
I have docker file with one layer as

RUN python setup.py develop

I am using a mutli-stage build with three stages and this is the stage one all the stages have the same base image, though I don't think this is a problem with dockerfile but seems to be a problem with python and the way it is executed
working on the base image python:3.7-slim
I am building this dockerfile on Travis CI with this below
Version info on Travis:

docker version
Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:42:38 2017
 OS/Arch:      linux/amd64
Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:41:20 2017
 OS/Arch:      linux/amd64
 Experimental: false

I get this below error as

AttributeError: 'ParsedRequirement' object has no attribute 'req'

Surprisingly I am able to have this working on My mac machine with docker version 19.03.2
Here is my setup.py file

import os
import shutil
import inspect
import platform
from setuptools import setup
import setuptools
try:
    from pip.req import parse_requirements
except ImportError:
    from pip._internal.req import parse_requirements

EMAIL_CONF = 'email.conf'
DL_CONF = 'dl.conf'
LINUX_CONFDIR = os.path.expanduser('~') + '/.config/bassa/'
WIN_CONFDIR = os.path.expanduser('~') + '/%app_data%/bassa/'
OSX_CONFDIR  = os.path.expanduser('~') + '/.config/bassa/'

# Utility function to read the README file.
def read(file_name):
    return open(os.path.join(os.path.dirname(__file__), file_name)).read()

base_dir = os.path.dirname(os.path.abspath(__file__))
requirements_path = os.path.join(base_dir, 'requirements.txt')

install_reqs = parse_requirements(requirements_path, session=False)

requirements = [str(ir.req) for ir in install_reqs]

### Set configs ###
if platform.system() == 'Linux':
    configdir = LINUX_CONFDIR
elif platform.system() == 'Windows':
    configdir = WIN_CONFDIR
elif platform.system() == 'Darwin':
    configdir = OSX_CONFDIR
if not os.path.exists(configdir):
    os.makedirs(configdir)

email_conf_location = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + "/" + EMAIL_CONF
dl_conf_location = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + "/" + DL_CONF
shutil.copyfile(email_conf_location, configdir + EMAIL_CONF)
shutil.copyfile(dl_conf_location, configdir + DL_CONF)

###/ Set configs ###

setup(
   ...
)

Please help me with this issue.

Body:
Update:

* Please note that updating pip and pip-tools is not supported in my case. Then the workaround in my answer will help.

* If updating pip and pip-tools to compatible version is supported then refer to Gnnr's answer or Heapify's answer

I got the fix finally \o/

install_reqs = parse_requirements(requirements_path, session=False)

At first, I have inspected what install_reqs was on Travis by simply logging it and found that it was a list of ParsedRequirement objects. I also found that this class is defined in req_file.py. I have gone to check the source code for req_file.py here on GitHub. I found that there was no such attribute called req but instead it is requirement. So there were two versions of parse_requirements function so I handled this using a try and except block.

# Generator must be converted to list, or we will only have one chance to read each element, meaning that the first requirement will be skipped.
requirements = list(requirements)
try:
    requirements = [str(ir.req) for ir in install_reqs]
except:
    requirements = [str(ir.requirement) for ir in install_reqs]

Now it is compatible with both the versions \0/


问:
Why is %eax zeroed before a call to printf?
I am trying to pick up a little x86. I am compiling on a 64bit mac with gcc -S -O0.

Code in C:

```<code>printf("%d", 1);
</code>```

Output:

```<code>movl    $1, %esi
leaq    LC0(%rip), %rdi
movl    $0, %eax        ; WHY?
call    _printf
</code>```

I do not understand why %eax is cleared to 0 before 'printf' is called. Since printf returns the number of characters printed to %eax my best guess it is zeroed out to prepare it for printf but I would have assumed that printf would have to be responsible for getting it ready. Also, in contrast, if I call my own function int testproc(int p1), gcc sees no need to prepare %eax. So I wonder why gcc treats printf and testproc differently.

答:
From the x86_64 System V ABI register usage table:

%rax        temporary register; with variable arguments
passes information about the number of vector
registers used; 1st return register
...

printf is a function with variable arguments, and the number of vector registers used is zero.

Note that printf must check only %al, because the caller is allowed to leave garbage in the higher bytes of %rax.  (Still, xor %eax,%eax is the most efficient way to zero %al)

See the this Q&A and the x86 tag wiki for more details, or for up-to-date ABI links if the above link is stale.

Body:
I am trying to pick up a little x86. I am compiling on a 64bit mac with gcc -S -O0.

Code in C:

printf("%d", 1);

Output:

movl    $1, %esi
leaq    LC0(%rip), %rdi
movl    $0, %eax        ; WHY?
call    _printf

I do not understand why %eax is cleared to 0 before 'printf' is called. Since printf returns the number of characters printed to %eax my best guess it is zeroed out to prepare it for printf but I would have assumed that printf would have to be responsible for getting it ready. Also, in contrast, if I call my own function int testproc(int p1), gcc sees no need to prepare %eax. So I wonder why gcc treats printf and testproc differently.


问:
How to use an outer query variable in a nested sub query using update
I am using an update query in which I use an outer variable in a nested sub query, but I find an error:

SQL Error: ORA-00904: "FS"."GR_NUMBER": invalid identifier

```<code>update table fs set fs.branch_id=
(select branch_id
from
    (select  branch_id,row_number() over(PARTITION by gr_number order by updated_ts desc) as Sno
from admission_log
where gr_number=fs.gr_number )
where sno=1) ;
</code>```

答:
Use this code:</p>
```<code>update fs a
set a.branch_id =
   (select c.branch_id
      from (select b.branch_id,
                   row_number() over(PARTITION by b.gr_number order by b.updated_ts desc) as Sno
              from admission_log b
             where b.gr_number = a.gr_number) c
     where c.sno = 1);
</code>```

Body:
I am using an update query in which I use an outer variable in a nested sub query, but I find an error:

SQL Error: ORA-00904: "FS"."GR_NUMBER": invalid identifier

update table fs set fs.branch_id=
(select branch_id
from
    (select  branch_id,row_number() over(PARTITION by gr_number order by updated_ts desc) as Sno
from admission_log
where gr_number=fs.gr_number )
where sno=1) ;

Body:
Use this code:

update fs a
set a.branch_id =
   (select c.branch_id
      from (select b.branch_id,
                   row_number() over(PARTITION by b.gr_number order by b.updated_ts desc) as Sno
              from admission_log b
             where b.gr_number = a.gr_number) c
     where c.sno = 1);


问:
Error: 'The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console.'
I am getting the following error while accessing Google Play Developer API using a service account:

The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console.

The service account email and .p12 file were generated using the service account option in APIs&Auth -> Credentials. The Application in the Google Play Developer API was linked to the project using the project id as mentioned in google's docs.

However, I am still getting this error when I try to use the Publishing API. I am looking for a solution to this error and a step by step process to use the Google Publishing API for the Java client to publish an APK using the Google Play Developer API. I am using androidpublisher_v2_public.

答:
A couple of days ago I've faced the same problem described here with an android publisher v3 and I did all by instruction but unfortunately unsuccessfully.

It may happen when you did link your google cloud console after than your subscriptions/products created and here I'm gonna describe the tricky solution on how to solve this problem without even contacting google.

I've thought that it might be the problem of synchronization and did a couple of steps.

Solution:

Link your Google Cloud Console account to your Google Play Console if it isn't done yet.

Then go to your subscriptions/products and try to change something there, for example, the price on a 0.01$ and roll it back.

Then do it with all the rest subscriptions/products

Finally, check your integration again. I hope everything should get working now :)

Also, I hope #google will fix these issues soon.


问:
Activeform in VB.NET
I am an old VB6 user and relatively new to VB.NET.
I have a MDI Container form and several ChildForms. I need to find the active child form to pass a variable.
In VB6 i could call the ActiveForm function.
Any help would be grateful.

Thanks in advance.
Kappa.

答:
You can get the active child form with this:

```<code> Me.ActiveMdiChild
</code>```

Or the name, but not a whole lot of use if you allow multiple instances

```<code>Me.ActiveMdiChild.Name
</code>```

Title: Activeform in VB.NET

Body:
You can get the active child form with this:

 Me.ActiveMdiChild

Or the name, but not a whole lot of use if you allow multiple instances

Me.ActiveMdiChild.Name


问:
UITableViewCell and UITableView Repeat selection over other Cells?
I am working in UITableView and trying to let the user to select cells using this code

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = [indexPath row];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if(cell != nil)
    {
        if(cell.accessoryType == UITableViewCellAccessoryNone)
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
}
</code>```

but the problem is when the cell count over one page if you select cell number 1 the row number 1 in each page will be selected too.

答:
```<code>static NSString * cellIdentifier = @"CellIdentifier"
</code>```

<p>in this place use </p>

```<code>NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%i",indexPath.row];
</code>```

Body:
I am working in UITableView and trying to let the user to select cells using this code

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = [indexPath row];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if(cell != nil)
    {
        if(cell.accessoryType == UITableViewCellAccessoryNone)
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
}

but the problem is when the cell count over one page if you select cell number 1 the row number 1 in each page will be selected too.

Body:
static NSString * cellIdentifier = @"CellIdentifier"

in this place use

NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%i",indexPath.row];


问:
How to return headers of columns that match a criteria for every row in a pandas dataframe?
I have a pandas dataframe df of the form :

```<code>     Col1      Col2      Col3      Col4

0    True      False     True      False
1    False     False     False     False
2    False     True      False     False
3    True      True      True      True
</code>```

Here True and False are boolean values.

I am trying to generate a new pandas dataframe new_df which should look like:

```<code>     Matched_Cols

0    [Col1, Col3]
1    []
2    [Col2]
3    [Col1, Col2, Col3, Col4]
</code>```

What is the most efficient way to achieve this?

答:
You can filter for each row index values, what are columns names in original DataFrame and then convert to lists:

```<code>df['Matched_Cols'] = df.apply(lambda x: x.index[x].tolist(), axis=1)
</code>```

Or use DataFrame.dot for matrix multiplication with columns names with separator, removed last separator value by Series.str.rstrip and last use Series.str.split:

```<code>df['Matched_Cols'] = df.dot(df.columns + ',').str.rstrip(',').str.split(',')
</code>```

```<code>print (df)
    Col1   Col2   Col3   Col4              Matched_Cols
0   True  False   True  False              [Col1, Col3]
1  False  False  False  False                        []
2  False   True  False  False                    [Col2]
3   True   True   True   True  [Col1, Col2, Col3, Col4]
</code>```

Body:
I have a pandas dataframe df of the form :

     Col1      Col2      Col3      Col4

0    True      False     True      False
1    False     False     False     False
2    False     True      False     False
3    True      True      True      True

Here True and False are boolean values.

I am trying to generate a new pandas dataframe new_df which should look like:

     Matched_Cols

0    [Col1, Col3]
1    []
2    [Col2]
3    [Col1, Col2, Col3, Col4]

What is the most efficient way to achieve this?

Body:
You can filter for each row index values, what are columns names in original DataFrame and then convert to lists:

df['Matched_Cols'] = df.apply(lambda x: x.index[x].tolist(), axis=1)

Or use DataFrame.dot for matrix multiplication with columns names with separator, removed last separator value by Series.str.rstrip and last use Series.str.split:

df['Matched_Cols'] = df.dot(df.columns + ',').str.rstrip(',').str.split(',')

print (df)
    Col1   Col2   Col3   Col4              Matched_Cols
0   True  False   True  False              [Col1, Col3]
1  False  False  False  False                        []
2  False   True  False  False                    [Col2]
3   True   True   True   True  [Col1, Col2, Col3, Col4]


问:
Can I use TensorBoard with Google Colab?
Is there any way to use TensorBoard when training a TensorFlow model on Google Colab?</p>

答:
According to the documentation all you need to do is this:

```<code>%load_ext tensorboard
!rm -rf ./logs/ #to delete previous runs
%tensorboard --logdir logs/
tensorboard = TensorBoard(log_dir="./logs")
</code>```

And just call it in the fit method:

```<code>model.fit(X_train, y_train, epochs = 1000,
         callbacks=[tensorboard], validation_data=(X_test, y_test))
</code>```

And that should give you something like this:

Body:
According to the documentation all you need to do is this:

%load_ext tensorboard
!rm -rf ./logs/ #to delete previous runs
%tensorboard --logdir logs/
tensorboard = TensorBoard(log_dir="./logs")

And just call it in the fit method:

model.fit(X_train, y_train, epochs = 1000,
         callbacks=[tensorboard], validation_data=(X_test, y_test))

And that should give you something like this:


问:
How to connect a .net console app client to azure data factory
I have created a Azure data factory pipeline as follows:

```<code>Azure SQL Database --> CSV Blob storage --> Azure Hyperscale Citus.
</code>```

But this pipeline was created on azure datafactory UI.

Now i want to create this pipeline through a console app.

1.) But i am not able to figure out how to authenticate the client and connect to data factory to execute a pipeline.

2.) And is this the best way to convert the sql DB --> hyperscale

答:
If you want to create Azure Data Factory pipeline with C# console application, we can use package Microsoft.Azure.Management.DataFactory. For more details, please refer to the document

For example (I create a pipeline to copy blobs from one container to another container)

Create a service principal and assign Contributor role to the sp

```<code>z login
az account set --subscription "<your subscription id>"
# the sp will have Azure Contributor role
az ad sp create-for-rbac -n "readMetric"
</code>```

Install SDk

```<code>Install-Package Microsoft.Azure.Management.DataFactory
Install-Package Microsoft.Azure.Management.ResourceManager -IncludePrerelease
Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory
</code>```

Create a data factory client to manage data factory

```<code>string tenantID = "<your tenant ID>";
string applicationId = "<your application ID>";
string authenticationKey = "<your authentication key for the application>";
string subscriptionId = "<your subscription ID where the data factory resides>";
string resourceGroup = "<your resource group where the data factory resides>";
string region = "<the location of your resource group>";
string dataFactoryName =
    "<specify the name of data factory ";

var context = new AuthenticationContext("https://login.windows.net/" + tenantID);
ClientCredential cc = new ClientCredential(applicationId, authenticationKey);
AuthenticationResult result = context.AcquireTokenAsync(
    "https://management.azure.com/", cc).Result;
ServiceClientCredentials cred = new TokenCredentials(result.AccessToken);
var client = new DataFactoryManagementClient(cred) {
    SubscriptionId = subscriptionId };
</code>```

Create Linked service

```<code>string storageAccount = "<your storage account name to copy data>";
string storageKey = "<your storage account key>";
string storageLinkedServiceName = "AzureStorageLinkedService";
LinkedServiceResource storageLinkedService = new LinkedServiceResource(
    new AzureStorageLinkedService
    {
        ConnectionString = new SecureString(
            "DefaultEndpointsProtocol=https;AccountName=" + storageAccount +
            ";AccountKey=" + storageKey)
    }
);
await client.LinkedServices.CreateOrUpdateAsync(
    resourceGroup, dataFactoryName, storageLinkedServiceName, storageLinkedService);
</code>```

Create dataset

```<code>string blobDatasetName = "BlobDataset";
 DatasetResource blobDataset = new DatasetResource(
                new AzureBlobDataset
                {
                    LinkedServiceName = new LinkedServiceReference
                    {
                        ReferenceName = storageLinkedServiceName
                    },
                    FolderPath = new Expression { Value = "@{dataset().path}" },
                    Parameters = new Dictionary<string, ParameterSpecification>
                    {
            { "path", new ParameterSpecification { Type = ParameterType.String } }
                    }
                }
            );
            await client.Datasets.CreateOrUpdateAsync(
                resourceGroup, dataFactoryName, blobDatasetName, blobDataset);
</code>```

Create pipeline

```<code>string pipelineName = "mypipeline";
   PipelineResource pipeline = new PipelineResource
            {
                Parameters = new Dictionary<string, ParameterSpecification>
                {
                    { "inputPath", new ParameterSpecification { Type = ParameterType.String } },
                    { "outputPath", new ParameterSpecification { Type = ParameterType.String } }
                },
                Activities = new List<Activity>
                {
                    new CopyActivity
                    {
                        Name = "CopyFromBlobToBlob",
                        Inputs = new List<DatasetReference>
                        {
                            new DatasetReference()
                            {
                                ReferenceName = blobDatasetName,
                                Parameters = new Dictionary<string, object>
                                {
                                    { "path", "@pipeline().parameters.inputPath" }
                                }
                            }
                        },
                        Outputs = new List<DatasetReference>
                        {
                            new DatasetReference
                            {
                                ReferenceName = blobDatasetName,
                                Parameters = new Dictionary<string, object>
                                {
                                    { "path", "@pipeline().parameters.outputPath" }
                                }
                            }
                        },
                        Source = new BlobSource { },
                        Sink = new BlobSink { }
                    }
                }
            };
            await client.Pipelines.CreateOrUpdateAsync(resourceGroup, dataFactoryName, pipelineName, pipeline);
</code>```

Run the pipeline

```<code>// specify the container and input folder from which all files
string inputBlobPath =
    "<path to existing blob(s) to copy data from, e.g. containername/inputdir>";
//specify the contains and output folder where the files are copied
string outputBlobPath =
    "<the blob path to copy data to, e.g. containername/outputdir>";
 Dictionary<string, object> parameters = new Dictionary<string, object>
                {
                    { "inputPath", inputBlobPath },
                    { "outputPath", outputBlobPath }
                };
            var runResponse = await client.Pipelines.CreateRunWithHttpMessagesAsync(
                resourceGroup, dataFactoryName, pipelineName, parameters: parameters
            );
</code>```

Check result

```<code>  //Checking pipeline run status...
            Console.WriteLine("Checking pipeline run status...");
            PipelineRun pipelineRun;
            while (true)
            {
                pipelineRun = client.PipelineRuns.Get(
                    resourceGroup, dataFactoryName, runResponse.Body.RunId);
                Console.WriteLine("Status: " + pipelineRun.Status);
                if (pipelineRun.Status == "InProgress" || pipelineRun.Status == "Queued")
                    System.Threading.Thread.Sleep(15000);
                else
                    break;
            }

            // Check the copy activity run details
            Console.WriteLine("Checking copy activity run details...");

            RunFilterParameters filterParams = new RunFilterParameters(
                DateTime.UtcNow.AddMinutes(-10), DateTime.UtcNow.AddMinutes(10));
            ActivityRunsQueryResponse queryResponse = await client.ActivityRuns.QueryByPipelineRunAsync(
                resourceGroup, dataFactoryName, runResponse.Body.RunId, filterParams);
            if (pipelineRun.Status == "Succeeded")
                Console.WriteLine(queryResponse.Value.First().Output);
            else
                Console.WriteLine(queryResponse.Value.First().Error);
            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
</code>```

Body:
I have created a Azure data factory pipeline as follows:

Azure SQL Database --> CSV Blob storage --> Azure Hyperscale Citus.

But this pipeline was created on azure datafactory UI.

Now i want to create this pipeline through a console app.

1.) But i am not able to figure out how to authenticate the client and connect to data factory to execute a pipeline.

2.) And is this the best way to convert the sql DB --> hyperscale

Body:
If you want to create Azure Data Factory pipeline with C# console application, we can use package Microsoft.Azure.Management.DataFactory. For more details, please refer to the document

For example (I create a pipeline to copy blobs from one container to another container)

Create a service principal and assign Contributor role to the sp

z login
az account set --subscription "<your subscription id>"
# the sp will have Azure Contributor role
az ad sp create-for-rbac -n "readMetric"

Install SDk

Install-Package Microsoft.Azure.Management.DataFactory
Install-Package Microsoft.Azure.Management.ResourceManager -IncludePrerelease
Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory

Create a data factory client to manage data factory

string tenantID = "<your tenant ID>";
string applicationId = "<your application ID>";
string authenticationKey = "<your authentication key for the application>";
string subscriptionId = "<your subscription ID where the data factory resides>";
string resourceGroup = "<your resource group where the data factory resides>";
string region = "<the location of your resource group>";
string dataFactoryName =
    "<specify the name of data factory ";

var context = new AuthenticationContext("https://login.windows.net/" + tenantID);
ClientCredential cc = new ClientCredential(applicationId, authenticationKey);
AuthenticationResult result = context.AcquireTokenAsync(
    "https://management.azure.com/", cc).Result;
ServiceClientCredentials cred = new TokenCredentials(result.AccessToken);
var client = new DataFactoryManagementClient(cred) {
    SubscriptionId = subscriptionId };

Create Linked service

string storageAccount = "<your storage account name to copy data>";
string storageKey = "<your storage account key>";
string storageLinkedServiceName = "AzureStorageLinkedService";
LinkedServiceResource storageLinkedService = new LinkedServiceResource(
    new AzureStorageLinkedService
    {
        ConnectionString = new SecureString(
            "DefaultEndpointsProtocol=https;AccountName=" + storageAccount +
            ";AccountKey=" + storageKey)
    }
);
await client.LinkedServices.CreateOrUpdateAsync(
    resourceGroup, dataFactoryName, storageLinkedServiceName, storageLinkedService);

Create dataset

string blobDatasetName = "BlobDataset";
 DatasetResource blobDataset = new DatasetResource(
                new AzureBlobDataset
                {
                    LinkedServiceName = new LinkedServiceReference
                    {
                        ReferenceName = storageLinkedServiceName
                    },
                    FolderPath = new Expression { Value = "@{dataset().path}" },
                    Parameters = new Dictionary<string, ParameterSpecification>
                    {
            { "path", new ParameterSpecification { Type = ParameterType.String } }
                    }
                }
            );
            await client.Datasets.CreateOrUpdateAsync(
                resourceGroup, dataFactoryName, blobDatasetName, blobDataset);

Create pipeline

string pipelineName = "mypipeline";
   PipelineResource pipeline = new PipelineResource
            {
                Parameters = new Dictionary<string, ParameterSpecification>
                {
                    { "inputPath", new ParameterSpecification { Type = ParameterType.String } },
                    { "outputPath", new ParameterSpecification { Type = ParameterType.String } }
                },
                Activities = new List<Activity>
                {
                    new CopyActivity
                    {
                        Name = "CopyFromBlobToBlob",
                        Inputs = new List<DatasetReference>
                        {
                            new DatasetReference()
                            {
                                ReferenceName = blobDatasetName,
                                Parameters = new Dictionary<string, object>
                                {
                                    { "path", "@pipeline().parameters.inputPath" }
                                }
                            }
                        },
                        Outputs = new List<DatasetReference>
                        {
                            new DatasetReference
                            {
                                ReferenceName = blobDatasetName,
                                Parameters = new Dictionary<string, object>
                                {
                                    { "path", "@pipeline().parameters.outputPath" }
                                }
                            }
                        },
                        Source = new BlobSource { },
                        Sink = new BlobSink { }
                    }
                }
            };
            await client.Pipelines.CreateOrUpdateAsync(resourceGroup, dataFactoryName, pipelineName, pipeline);

Run the pipeline

// specify the container and input folder from which all files
string inputBlobPath =
    "<path to existing blob(s) to copy data from, e.g. containername/inputdir>";
//specify the contains and output folder where the files are copied
string outputBlobPath =
    "<the blob path to copy data to, e.g. containername/outputdir>";
 Dictionary<string, object> parameters = new Dictionary<string, object>
                {
                    { "inputPath", inputBlobPath },
                    { "outputPath", outputBlobPath }
                };
            var runResponse = await client.Pipelines.CreateRunWithHttpMessagesAsync(
                resourceGroup, dataFactoryName, pipelineName, parameters: parameters
            );

Check result

  //Checking pipeline run status...
            Console.WriteLine("Checking pipeline run status...");
            PipelineRun pipelineRun;
            while (true)
            {
                pipelineRun = client.PipelineRuns.Get(
                    resourceGroup, dataFactoryName, runResponse.Body.RunId);
                Console.WriteLine("Status: " + pipelineRun.Status);
                if (pipelineRun.Status == "InProgress" || pipelineRun.Status == "Queued")
                    System.Threading.Thread.Sleep(15000);
                else
                    break;
            }

            // Check the copy activity run details
            Console.WriteLine("Checking copy activity run details...");

            RunFilterParameters filterParams = new RunFilterParameters(
                DateTime.UtcNow.AddMinutes(-10), DateTime.UtcNow.AddMinutes(10));
            ActivityRunsQueryResponse queryResponse = await client.ActivityRuns.QueryByPipelineRunAsync(
                resourceGroup, dataFactoryName, runResponse.Body.RunId, filterParams);
            if (pipelineRun.Status == "Succeeded")
                Console.WriteLine(queryResponse.Value.First().Output);
            else
                Console.WriteLine(queryResponse.Value.First().Error);
            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();


问:
https.request() is giving Error: connect ECONREFUSED 127.0.0.1:443
Hello there,
I'm at my wits end I'm struggling I would like to know where I'm going wrong
I can't seem to get past this error connect ECONNREFUSED 127.0.0.1:443
something tells me it's something small that I'm neglecting but I can't see it.
I read here that it's possible that the is a network overload problem but I have shut everything down except my ngrok to simulate https and the mongodb running yet still no joy. Any and all suggestions appreciated

```<code>const https = require('https');

app.get('/auth/instagram', (req, res) => {
  const clientId = process.env.INSTAGRAM_ID;
  const redirectUri = process.env.INSTAGRAM_ID_URI;
  res.redirect(`https://api.instagram.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=user_profile,user_media&response_type=code`);
});
app.get('/auth/instagram/callback', (req, res) => {
  // console.log('this is the code', req.query.code);

  const { code } = req.query;
  console.log('this is the code ', code);
  const redirectURL = `${process.env.BASE_URL}/auth/instagram/callback`;
  const url = 'https://api.instagram.com/oauth/access_token';
  const options = {
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: {
      client_id: process.env.INSTAGRAM_ID,
      client_secret: process.env.INSTAGRAM_SECRET,
      grant_type: 'authorization_code',
      redirect_uri: redirectURL,
      code
    },
    json: true,
    url
  };
  console.log('This is that options', options);
  https.request(options, (err, res) => {
    console.log('this is the body', res);
  });
  process.on('uncaughtException', (err) => {
    console.log(err);
  });

});
</code>```

Error

```<code>Error: connect ECONNREFUSED 127.0.0.1:443
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 443
}
</code>```

答:
You can not use PORT 443 for your Node.js Application, because of this port used by the HTTP server for Secure HTTP or https:// connection. Use a different port address. If you want to use PORT 443 then install the Nginx server and connect your Node.js application in Reverse Proxy methodology. You need to install an SSL Certificate and bind it into the Nginx Config file if you want to use https:// for your Node.js Application.

You can also follow this tutorial. Click this
link

Body:
Hello there,
I'm at my wits end I'm struggling I would like to know where I'm going wrong
I can't seem to get past this error connect ECONNREFUSED 127.0.0.1:443
something tells me it's something small that I'm neglecting but I can't see it.
I read here that it's possible that the is a network overload problem but I have shut everything down except my ngrok to simulate https and the mongodb running yet still no joy. Any and all suggestions appreciated

const https = require('https');

app.get('/auth/instagram', (req, res) => {
  const clientId = process.env.INSTAGRAM_ID;
  const redirectUri = process.env.INSTAGRAM_ID_URI;
  res.redirect(`https://api.instagram.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=user_profile,user_media&response_type=code`);
});
app.get('/auth/instagram/callback', (req, res) => {
  // console.log('this is the code', req.query.code);

  const { code } = req.query;
  console.log('this is the code ', code);
  const redirectURL = `${process.env.BASE_URL}/auth/instagram/callback`;
  const url = 'https://api.instagram.com/oauth/access_token';
  const options = {
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: {
      client_id: process.env.INSTAGRAM_ID,
      client_secret: process.env.INSTAGRAM_SECRET,
      grant_type: 'authorization_code',
      redirect_uri: redirectURL,
      code
    },
    json: true,
    url
  };
  console.log('This is that options', options);
  https.request(options, (err, res) => {
    console.log('this is the body', res);
  });
  process.on('uncaughtException', (err) => {
    console.log(err);
  });

});

Error

Error: connect ECONNREFUSED 127.0.0.1:443
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 443
}


问:
python, struggling to plot CSV file
as the title explains I'm trying to read in a CSV file and plot it, the file is in the following format:

```<code>Dishwasher,60,1,1,1,0,0,1

Washing Machine,200,0,0,0,0,1,1
</code>```

where I just want to plot the 6 digits at the end.

Here is my code so far:

```<code>import matplotlib.pyplot as plt
import numpy as np
import csv
y1=[]
y2=[]

x = np.array([1,2,3,4,5,6])
with open('File.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    rows = [row for row in plots]
y1=int((rows[0])-2)
y2=int((rows[1])-2)

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
plt.show()
</code>```

I've been trying to solve the problem for hours now but everything I do brings about a new error.

In this code, the error is:

TypeError: unsupported operand type(s) for -: 'list' and 'int'

Which from my understanding means it's trying to convert a list into an integer which isn't possible? Thanks for any and all help

答:
First your rows is a list containing tuples, thus with rows[0] you refer to the first tuple not the integer inside. You have to go deeper to pick it.

Second you substract a string with an integer with this expression : int((rows[0])-2) (because you convert after substracting and not before)

Third, you must pass an iterable to the plot function which is x-length

so I just see you provide the csv, the script works with my csv rebuild file

import matplotlib.pyplot as plt
import numpy as np
import csv
y1=[]
y2=[]

x = np.array([1,2,3,4,5,6])
with open('File.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=';')
    rows = [row for row in plots]

y1=[int(row[0])-2 for row in rows]
y2=[int(row[1])-2 for row in rows]

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
plt.show()
```

Title: python, struggling to plot CSV file

Body:
as the title explains I'm trying to read in a CSV file and plot it, the file is in the following format:

Dishwasher,60,1,1,1,0,0,1

Washing Machine,200,0,0,0,0,1,1

where I just want to plot the 6 digits at the end.

Here is my code so far:

import matplotlib.pyplot as plt
import numpy as np
import csv
y1=[]
y2=[]

x = np.array([1,2,3,4,5,6])
with open('File.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    rows = [row for row in plots]
y1=int((rows[0])-2)
y2=int((rows[1])-2)

plt.plot(x,y1, label='Washing Machine')
plt.plot(x,y2, label='Dishwasher')
plt.show()

I've been trying to solve the problem for hours now but everything I do brings about a new error.

In this code, the error is:

TypeError: unsupported operand type(s) for -: 'list' and 'int'

Which from my understanding means it's trying to convert a list into an integer which isn't possible? Thanks for any and all help


问:
Is there a way to compare CSVs in Python while ignoring row ordering?
I'm setting up an automatic job that needs to parse csv files from an ftp site, each file contains several 10 thousand lines. I want to pre-process the directory to eliminate duplicate files before parsing the remaining files. The problem is that duplicate files are being pushed to the ftp but with different row ordering (i.e. same data, different order). That results in "duplicate files" having different hashes and byte-by-byte comparisons. with minimal processing.

I want to keep file manipulation to the minimum so I tried sorting the CSVs using the csvsort module but this is giving me an index error: IndexError: list index out of range. Here is the relevant code:

```<code>from csvsort import csvsort
csvsort(input_filename=file_path,columns=[1,2])
</code>```

I tried finding and eliminating empty rows but this didn't seem to be the problem and, like I said, I want to keep file manipulation to the minimum to retain file integrity. Moreover, I have no control over the creation of files or pushing of the files to the ftp

I can think of a number of ways to work around this issue but they would all involve opening the CSVs and reading the contents, manipulating it, etc. Is there anyway I can do a lightweight file comparison that ignores row ordering or will I have to go for heavier processing?

答:
So, it turns out that pandas has a built in hash function with an option to ignore the index. As the hash is calculated on each row, you need to run an additional sum function. In terms of code, it is about as lightweight as I could wish, in terms of runtime, it parses ~15 files in ~5 seconds (~30k rows, 17 columns in each file).

```<code>from pandas import read_csv
from pandas.util import hash_pandas_object
from collections import defaultdict

duplicate_check = defaultdict(list)
for f in files:
    duplicate_check[hash_pandas_object(read_csv(f),index=False).sum()].append(f)
</code>```

Body:
I'm setting up an automatic job that needs to parse csv files from an ftp site, each file contains several 10 thousand lines. I want to pre-process the directory to eliminate duplicate files before parsing the remaining files. The problem is that duplicate files are being pushed to the ftp but with different row ordering (i.e. same data, different order). That results in "duplicate files" having different hashes and byte-by-byte comparisons. with minimal processing.

I want to keep file manipulation to the minimum so I tried sorting the CSVs using the csvsort module but this is giving me an index error: IndexError: list index out of range. Here is the relevant code:

from csvsort import csvsort
csvsort(input_filename=file_path,columns=[1,2])

I tried finding and eliminating empty rows but this didn't seem to be the problem and, like I said, I want to keep file manipulation to the minimum to retain file integrity. Moreover, I have no control over the creation of files or pushing of the files to the ftp

I can think of a number of ways to work around this issue but they would all involve opening the CSVs and reading the contents, manipulating it, etc. Is there anyway I can do a lightweight file comparison that ignores row ordering or will I have to go for heavier processing?

Body:
So, it turns out that pandas has a built in hash function with an option to ignore the index. As the hash is calculated on each row, you need to run an additional sum function. In terms of code, it is about as lightweight as I could wish, in terms of runtime, it parses ~15 files in ~5 seconds (~30k rows, 17 columns in each file).

from pandas import read_csv
from pandas.util import hash_pandas_object
from collections import defaultdict

duplicate_check = defaultdict(list)
for f in files:
    duplicate_check[hash_pandas_object(read_csv(f),index=False).sum()].append(f)


问:
Wordpress Site not Load in IE (Firefox & Chrome are ok)
i have 2 websites that i build with WordPress , both of them works well in Firefox and chrome without any problems .

but i found that both my WordPress site wont load in Internet explore at all

this error show when i try to reach :

This page can’t be displayed

•Make sure the web address https://owjgraphic.com/ is correct.

•Look for the page with your search engine.

•Refresh the page in a few minutes.

that's very weird ! i contact to my host administrator and they say it`s not related to us and you must found the problem by yourself

答:
I use IE to load without showing the above problems.

First, you could use the F12 developer tool to check if there’s error.

Second, you could refer to the following links:

Website theme and software version.

Check IE compatibility mark "x-ua-compatible".

In addition, if you still can't make it work on IE, hopefully you could provide information about the code or settings that is related to browser loading to reproduce your problem.