问:
Alternative to os.path.join in python to group png files in one variable
I need to find an alternative to using the sys and os module in python. I have a game that i developed in pygame that uses images for different sprites. Some sprites have numerous .png 's that are used by a function to create an animation effect. When using e.g ship = os.path.join() to link multiple .pngs, after converting to an .exe (auto pytoexe) the .py file always gives me a fatal error and i'm pretty sure its because it can't find the images.

My game works perfectly in pycharm thought.

I'ved tried making the directories strings but obviously one variable can store multiple .png's. I also tried using a function provided by a user on stackflow but it still gave me fatal error when running the exe. The code shows how muliple .pngs with names of rocket1, rocket2, rocket3, ect from the local folder i made called sprites, are taken by the variable. But my game doesnt work when in exe and the png folders are put next to the exe.

```<code>missile_image_path = os.path.join(os.path.dirname(__file__), '..', 'Sprites', 'rocket')
</code>```

I need an alternative that can allow a variable to behave the same as with using the os module, but the directory stored can local to the py/exe file so the game can run once converted

答:
Given the information provided in the comments, that OP is using pyinstaller.

Here is the reference to respective section of documentation
There is example script provided that test is frozen or not and print respective paths.

For convenience here is the script:

```<code>#!/usr/bin/python3
import sys, os
frozen = 'not'
if getattr(sys, 'frozen', False):
        # we are running in a bundle
        frozen = 'ever so'
        bundle_dir = sys._MEIPASS
else:
        # we are running in a normal Python environment
        bundle_dir = os.path.dirname(os.path.abspath(__file__))
print( 'we are',frozen,'frozen')
print( 'bundle dir is', bundle_dir )
print( 'sys.argv[0] is', sys.argv[0] )
print( 'sys.executable is', sys.executable )
print( 'os.getcwd is', os.getcwd() )
</code>```

run it as py file and also converted to exe with the same options (i.e. one file or one folder) and run it again. This will help you to understand the difference in the paths used.

Body:
I need to find an alternative to using the sys and os module in python. I have a game that i developed in pygame that uses images for different sprites. Some sprites have numerous .png 's that are used by a function to create an animation effect. When using e.g ship = os.path.join() to link multiple .pngs, after converting to an .exe (auto pytoexe) the .py file always gives me a fatal error and i'm pretty sure its because it can't find the images.

My game works perfectly in pycharm thought.

I'ved tried making the directories strings but obviously one variable can store multiple .png's. I also tried using a function provided by a user on stackflow but it still gave me fatal error when running the exe. The code shows how muliple .pngs with names of rocket1, rocket2, rocket3, ect from the local folder i made called sprites, are taken by the variable. But my game doesnt work when in exe and the png folders are put next to the exe.

missile_image_path = os.path.join(os.path.dirname(__file__), '..', 'Sprites', 'rocket')

I need an alternative that can allow a variable to behave the same as with using the os module, but the directory stored can local to the py/exe file so the game can run once converted

Body:
Given the information provided in the comments, that OP is using pyinstaller.

Here is the reference to respective section of documentation
There is example script provided that test is frozen or not and print respective paths.

For convenience here is the script:

#!/usr/bin/python3
import sys, os
frozen = 'not'
if getattr(sys, 'frozen', False):
        # we are running in a bundle
        frozen = 'ever so'
        bundle_dir = sys._MEIPASS
else:
        # we are running in a normal Python environment
        bundle_dir = os.path.dirname(os.path.abspath(__file__))
print( 'we are',frozen,'frozen')
print( 'bundle dir is', bundle_dir )
print( 'sys.argv[0] is', sys.argv[0] )
print( 'sys.executable is', sys.executable )
print( 'os.getcwd is', os.getcwd() )

run it as py file and also converted to exe with the same options (i.e. one file or one folder) and run it again. This will help you to understand the difference in the paths used.


来源: stackexchange

问:
Erlang: whether two lists have a common element
```<code>a = [1, 2, 3],
b = [4, 5, 6],
c = [1, 7, 8],
</code>```

has_common_element(a, b) is false since there are no common elements between the two arrays.

has_common_element(a, c) is true since there is at least one common element (1) between the two arrays.

I can use lists:member to check whether a single element is in the list. How do I implement has_common_element in Erlang to check whether two lists have a common element?

ContentLicense: CC BY-SA 4.0

Body:
a = [1, 2, 3],
b = [4, 5, 6],
c = [1, 7, 8],

has_common_element(a, b) is false since there are no common elements between the two arrays.

has_common_element(a, c) is true since there is at least one common element (1) between the two arrays.

I can use lists:member to check whether a single element is in the list. How do I implement has_common_element in Erlang to check whether two lists have a common element?

Body:
You can use list comprehension like below:

test(A, B)->
    [] /= [X || X <- A, Y <- B, X == Y].

the result in shell:

1> A = [1, 2, 3].
[1,2,3]
2> B = [4, 5, 6].
[4,5,6]
3> C = [1, 7, 8].
[1,7,8]
4> foo:test(A, B).
false
5> foo:test(A, C).
true


问:
How can I get back to previous page with passing params?
I know I can use the below code to go back previous page.

```<code>$router.go(-1)
</code>```

but is it possible to pass params to the previous page?

答:
There is no option for params in Vue.js but you can do it by document.referrer

```<code>window.location = document.referrer + '?index=1';
</code>```

Body:
I know I can use the below code to go back previous page.

$router.go(-1)

but is it possible to pass params to the previous page?

Body:
There is no option for params in Vue.js but you can do it by document.referrer

window.location = document.referrer + '?index=1';


问:
Null Pointer Debugging
quick summary of what I'm trying to do.

Using shared preferences so that when a user watches a video a green tick will appear beside it to mark it as complete. Currently getting a null pointer error.

Basically there are two pages - main page and video page. When user lands on the main page the if statement should check the sharepreferences to see if they have already visited the video page. If they have it should display the completedTick imageView.

Please see the code and context below.

MAIN PAGE CODE SNIPPET:

```<code> /**
 * Shared preferences variable which is used to store the userId which is captured at the login screen.
 */
private SharedPreferences loginPref, activityPref;
private ImageView completedTick;
private Boolean activityCompleted;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

    View view = inflater.inflate(R.layout.fragment_activities, container, false);

    initialiseRecyclerView(view);
    retrieveActivities();

    if(activityCompleted == false || activityCompleted == null ) {
        completedTick.setVisibility(view.INVISIBLE);
    }else{
        completedTick.setVisibility(View.VISIBLE);
    }

    return view;

}

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

}

/**
 * Method which is used to initialise the recycler view
 *
 * @param view
 */
private void initialiseRecyclerView(View view) {
    mRecyclerView = view.findViewById(R.id.recyclerViewActivities);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    EmptyAdapter emptyAdapter = new EmptyAdapter();
    mRecyclerView.setAdapter(emptyAdapter);
    completedTick = view.findViewById(R.id.completedTick);
}
</code>```

VIDEO PAGE CODE SNIPPET:

```<code>private SharedPreferences activityPref;
private Boolean activityCompleted;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.youtube_layout);

    Log.d(TAG, "onCreateView: Starting");
    activityPref = getSharedPreferences("activityPref", MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

        getExtrasMethod();
        initialiseViews();
        setTextInViews();
        checkCompleteD();

 private void checkCompleteD() {

    if (activityCompleted) {
        SharedPreferences.Editor editor = activityPref.edit();
        activityCompleted = false;
        editor.putBoolean("activityCompleted", activityCompleted);
        editor.apply();

    }
}
</code>```

The error is :

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.fit.ActivitiesFragment.onCreateView(ActivitiesFragment.java:78)
</code>```

UPDATE:

Made the suggedted changes

```<code>@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

    completedTick = view.findViewById(R.id.completedTickImage);
    initialiseRecyclerView(view);
    retrieveActivities();

    if (activityCompleted == false || activityCompleted == null) {
        completedTick.setVisibility(View.INVISIBLE);
    } else {
        completedTick.setVisibility(View.VISIBLE);
    }
}
</code>```

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.feelingfit.ActivitiesFragment.onViewCreated(ActivitiesFragment.java:85)

Which is this line :  completedTick.setVisibility(View.INVISIBLE);

答:
First of all, your completedTick is null. Try putting the completedTick = view.findViewById(R.id.completedTick); in your OnViewCreated above this code:

```<code>if(activityCompleted == false || activityCompleted == null ) {
        completedTick.setVisibility(View.INVISIBLE);
    }else{
        completedTick.setVisibility(View.VISIBLE);
    }
</code>```

And also,  replace the view.INVISIBLE with View.INVISIBLE

Edit + Aditional Information:

If you occur again the NullPointerException please refer to this link.

Edit 2:
Rewrite your code inside the onViewCreated method like this:

```<code>@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_activities, container, false);

}

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
 loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
        activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
        activityCompleted = activityPref.getBoolean("activityCompleted", true);

        initialiseRecyclerView(view);
        retrieveActivities();

        if(activityCompleted == false || activityCompleted == null ) {
            completedTick.setVisibility(View.INVISIBLE);
        }else{
            completedTick.setVisibility(View.VISIBLE);
        }
}
</code>```

Edit number 3: Since it is crashing again on the same use case I assume your R.id.completedTickImage is not inside your fragment_activities

Title: Null Pointer Debugging

Body:
quick summary of what I'm trying to do.

Using shared preferences so that when a user watches a video a green tick will appear beside it to mark it as complete. Currently getting a null pointer error.

Basically there are two pages - main page and video page. When user lands on the main page the if statement should check the sharepreferences to see if they have already visited the video page. If they have it should display the completedTick imageView.

Please see the code and context below.

MAIN PAGE CODE SNIPPET:

 /**
 * Shared preferences variable which is used to store the userId which is captured at the login screen.
 */
private SharedPreferences loginPref, activityPref;
private ImageView completedTick;
private Boolean activityCompleted;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

    View view = inflater.inflate(R.layout.fragment_activities, container, false);

    initialiseRecyclerView(view);
    retrieveActivities();

    if(activityCompleted == false || activityCompleted == null ) {
        completedTick.setVisibility(view.INVISIBLE);
    }else{
        completedTick.setVisibility(View.VISIBLE);
    }

    return view;

}

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

}

/**
 * Method which is used to initialise the recycler view
 *
 * @param view
 */
private void initialiseRecyclerView(View view) {
    mRecyclerView = view.findViewById(R.id.recyclerViewActivities);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    EmptyAdapter emptyAdapter = new EmptyAdapter();
    mRecyclerView.setAdapter(emptyAdapter);
    completedTick = view.findViewById(R.id.completedTick);
}

VIDEO PAGE CODE SNIPPET:

private SharedPreferences activityPref;
private Boolean activityCompleted;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.youtube_layout);

    Log.d(TAG, "onCreateView: Starting");
    activityPref = getSharedPreferences("activityPref", MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

        getExtrasMethod();
        initialiseViews();
        setTextInViews();
        checkCompleteD();

 private void checkCompleteD() {

    if (activityCompleted) {
        SharedPreferences.Editor editor = activityPref.edit();
        activityCompleted = false;
        editor.putBoolean("activityCompleted", activityCompleted);
        editor.apply();

    }
}

The error is :

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.fit.ActivitiesFragment.onCreateView(ActivitiesFragment.java:78)

UPDATE:

Made the suggedted changes

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
    activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
    activityCompleted = activityPref.getBoolean("activityCompleted", true);

    completedTick = view.findViewById(R.id.completedTickImage);
    initialiseRecyclerView(view);
    retrieveActivities();

    if (activityCompleted == false || activityCompleted == null) {
        completedTick.setVisibility(View.INVISIBLE);
    } else {
        completedTick.setVisibility(View.VISIBLE);
    }
}

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.feelingfit.ActivitiesFragment.onViewCreated(ActivitiesFragment.java:85)

Which is this line :  completedTick.setVisibility(View.INVISIBLE);

Body:
First of all, your completedTick is null. Try putting the completedTick = view.findViewById(R.id.completedTick); in your OnViewCreated above this code:

if(activityCompleted == false || activityCompleted == null ) {
        completedTick.setVisibility(View.INVISIBLE);
    }else{
        completedTick.setVisibility(View.VISIBLE);
    }

And also,  replace the view.INVISIBLE with View.INVISIBLE

Edit + Aditional Information:

If you occur again the NullPointerException please refer to this link.

Edit 2:
Rewrite your code inside the onViewCreated method like this:

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_activities, container, false);

}

@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
 loginPref = getContext().getSharedPreferences("loginPref", Context.MODE_PRIVATE);
        activityPref = getContext().getSharedPreferences("activityPref", Context.MODE_PRIVATE);
        activityCompleted = activityPref.getBoolean("activityCompleted", true);

        initialiseRecyclerView(view);
        retrieveActivities();

        if(activityCompleted == false || activityCompleted == null ) {
            completedTick.setVisibility(View.INVISIBLE);
        }else{
            completedTick.setVisibility(View.VISIBLE);
        }
}

Edit number 3: Since it is crashing again on the same use case I assume your R.id.completedTickImage is not inside your fragment_activities


问:
How to import Elasticsearch data(JSON) into Google Charts?
I try to use Elasticsearch data to create a table with Google Charts. I followed this solution: Populate Google Chart with Search Data from Elasticsearch

But I cannot see any data or graph displayed. I think it is because I don't transfer data correctly. Could anyone tell me the problem of the following code?

```<code>     <html>
      <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
        </script>
        <script type="text/javascript">
      google.load('visualization', {'packages':['table']});
      google.setOnLoadCallback(drawTable);

      function drawTable() {
      var json;
      $.ajax({
           url: 'http://localhost:9200/people/man/_search',
        type: 'POST',
        data :
            JSON.stringify(
                {
                    "query" : { "match_all" : {} }
                }),
        dataType : 'json',
        async: false,
        success: function(data){
            json = data;
        }
    })

  var jdata = {};
  jdata.cols = [
{
    "id": "",
    "label": "name",
    "type": "string"
},
{
    "id": "",
    "label": "country",
    "type":"string"
}
 ];

   jdata.rows = [
{
    "c": [
        {
            "v": json.hits.hits[0]._source.name
        },
        {
            "v": json.hits.hits[0]._source.country
        }
    ]
}
];

   var data = new google.visualization.DataTable(jdata);

   var table = new google.visualization.Table(document.getElementById('table_div'));
 table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
}
 </script>
</head>

<body>
     <div id="table_div"> </div>
</body>
</html>
</code>```

答:
I find three problems of showing nothing in this code. No big error but good details to notice.

add header "Content-Type", "application/json". I used "xmlhttp.setRequestHeader("Content-Type", "application/json");"

'json' is defined in a function. If using json outside the function, it gives blank file back.(small error, but quite annoying if you don't notice this)

don't forget to transfer string to json with  "var json = JSON.parse(json);"


问:
can't install windows usb driver - vodafone 845
My environment is: windows xp sp3, eclipse, all available software installed using SDK Manager.

Following Android developer site's guide, I could write and run hello world app on Android 2.3 emulator. Then I wanted to see if I could run my app on a real device - vodafone 845 (huawei U8120?) in my case. Here I stuck for two days now trying to install windows usb driver for my device. When I connect my device through usb with Debug setting On, windows keeps to ackowledge it as usb mass storage. On Device Manager, I tried Update Driver, selected C:\Program Files\Android\android-sdk-windows\google-usb_driver\android_winusb.inf file. it complained like:

"The specified location does not contain information about your hardware"

It's probably because of missing manufacturer/product information (VID_12D1&PID_1031) in inf file, right?

http://developer.android.com/sdk/win-usb.html site lists supported devices and says that any additional devices will require Windows drivers provided by the hardware manufacturer but so far I couldn't any information.

I guess many developers are facing this issue with their own devices that is not supported by Android SDK and I wonder how they overcome this issue - especially for vodafone 845 device.

Thanks in advance

Bob

答:
Yes this works like charm. Everything is located on the sd card. There are some weird things though:
 - You can't to choose, if you want to mount the your phone as storage, on other phones you can.
 - For us the install did not work at first, only the second time.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How do I convert a Django QuerySet into list of dicts?
How can I convert a Django QuerySet into a list of dicts? I haven't found an answer to this so I'm wondering if I'm missing some sort of common helper function that everyone uses.

答:
Type Cast to List

```<code>    job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')

    json.dumps(list(job_reports))
</code>```

Body:
Type Cast to List

    job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')

    json.dumps(list(job_reports))


问:
Python Virtualenv - No module named virtualenvwrapper.hook_loader
I'm running Mac OS 10.6.8. and wanted to install in addition to python 2.6 also python 2.7 and use python 2.7 in a new virtualenv. I executed the following steps:

I downloaded python 2.7 and installed it:

```<code>http://www.python.org/ftp/python/2.7.3/python-2.7.3-macosx10.6.dmg
</code>```

Then I run the command to setup a new virtualenv using python2.7:

```<code>mkvirtualenv --python=python2.7 mynewenv
</code>```

My .bash_profile looks like the following:

```<code># needed for virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
source /usr/local/bin/virtualenvwrapper.sh

# Setting PATH for Python 2.7
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"
export PATH
</code>```

Now when I open the console I get the following error message.

```<code>ImportError: No module named virtualenvwrapper.hook_loader
virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenv has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python and that PATH is set properly.
</code>```

I also found in a different post that I should upgrade virtualenvwrapper. That did not help.

```<code>sudo pip install virtualenvwrapper --upgrade
</code>```

Any help would be appreciated.

答:
I had the same problem as this one and spent so much time on configuring out what was wrong. And I finally found out what was wrong.

First I looked for where virtualenvwrapper folder exists.
In my case /usr/local/lib/python3.7/site-packages.
Inside the folder is hook_loader.py that caused the error.

Next, I used python script.

```<code>python3

import sys;print('\n'.join(sys.path))
</code>```

I couldn't find the /usr/local/lib/python3.7/site-packages directory so,
at last I wrote,

```<code>export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python3.7/site-packages
</code>```

to .bashrc file. Done.

Meaning of PYTHON PATH

As you can see in above link, PYTHONPATH augment the default search path for modules.

Body:
I'm running Mac OS 10.6.8. and wanted to install in addition to python 2.6 also python 2.7 and use python 2.7 in a new virtualenv. I executed the following steps:

I downloaded python 2.7 and installed it:

http://www.python.org/ftp/python/2.7.3/python-2.7.3-macosx10.6.dmg

Then I run the command to setup a new virtualenv using python2.7:

mkvirtualenv --python=python2.7 mynewenv

My .bash_profile looks like the following:

# needed for virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
source /usr/local/bin/virtualenvwrapper.sh

# Setting PATH for Python 2.7
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"
export PATH

Now when I open the console I get the following error message.

ImportError: No module named virtualenvwrapper.hook_loader
virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenv has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python and that PATH is set properly.

I also found in a different post that I should upgrade virtualenvwrapper. That did not help.

sudo pip install virtualenvwrapper --upgrade

Any help would be appreciated.

Body:
I had the same problem as this one and spent so much time on configuring out what was wrong. And I finally found out what was wrong.

First I looked for where virtualenvwrapper folder exists.
In my case /usr/local/lib/python3.7/site-packages.
Inside the folder is hook_loader.py that caused the error.

Next, I used python script.

python3

import sys;print('\n'.join(sys.path))

I couldn't find the /usr/local/lib/python3.7/site-packages directory so,
at last I wrote,

export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python3.7/site-packages

to .bashrc file. Done.

Meaning of PYTHON PATH

As you can see in above link, PYTHONPATH augment the default search path for modules.


问:
Widget rebuild after TextField selection Flutter
I'm developping a Flutter App that needed to have a form. So when the user open the app, a Splash Screen appear before the form that have the following code :

```<code>import 'package:flutter/material.dart';
import '../model/User.dart';
import './FileManager.dart';
import './MyListPage.dart';

class UserLoader extends StatefulWidget {
  @override
  _UserLoaderState createState() => new _UserLoaderState();
}

class _UserLoaderState extends State<UserLoader> {
  final userFileName = "user_infos.txt";
  User _user;

  @override
  Widget build(BuildContext context) {
    print("build UserLoader");
    final _formKey = new GlobalKey<FormState>();
    final _firstNameController = new TextEditingController();
    final _lastNameController = new TextEditingController();
    final _emailController = new TextEditingController();
    final _phoneController = new TextEditingController();

    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Informations"),
          actions: <Widget>[
            new IconButton(
                icon: const Icon(Icons.save),
                onPressed: () {
                  _user = _onFormValidate(
                      _formKey.currentState,
                      _firstNameController.text,
                      _lastNameController.text,
                      _emailController.text,
                      _phoneController.text);
                })
          ],
        ),
        body: new Center(
          child: new SingleChildScrollView(
              child: new Form(
                  key: _formKey,
                  child: new Column(children: <Widget>[
                    new ListTile(
                      leading: const Icon(Icons.person),
                      title: new TextFormField(
                        decoration: new InputDecoration(
                          hintText: "Prénom",
                        ),
                        keyboardType: TextInputType.text,
                        controller: _firstNameController,
                        validator: _validateName,
                      ),
                    ),
                    new ListTile(
                      leading: const Icon(Icons.person),
                      title: new TextFormField(
                        decoration: new InputDecoration(
                          hintText: "Nom",
                        ),
                        keyboardType: TextInputType.text,
                        controller: _lastNameController,
                        validator: _validateName,
                      ),
                    ),
Etc, etc ...
</code>```

However when i tap the TextField, the keyboard appear and close immediately and all the component is rebuild. So it is impossible for me to complete the form..

Can someone have a solution please? Thanks in advance !

答:
you just need make a new class and import that on your target class that seen problem. for example :

I usually create a class like this :

```<code>class MiddleWare
{
  static MiddleWare shared = MiddleWare();
  _MiddleWare(){}
  String myText = "my Text";
  // every variables should be here...
}
</code>```

and

```<code>import "MiddleWare.dart";

class myclass extends StatefulWidget {
  @override
  _myclassState createState() => _myclassState();
}

class _myclassState extends State<myclass> {
  @override
  Widget build(BuildContext context) {
    return Container(child: Text(MiddleWare.shared.myText));
  }
}
</code>```

that's it.

Body:
I'm developping a Flutter App that needed to have a form. So when the user open the app, a Splash Screen appear before the form that have the following code :

import 'package:flutter/material.dart';
import '../model/User.dart';
import './FileManager.dart';
import './MyListPage.dart';

class UserLoader extends StatefulWidget {
  @override
  _UserLoaderState createState() => new _UserLoaderState();
}

class _UserLoaderState extends State<UserLoader> {
  final userFileName = "user_infos.txt";
  User _user;

  @override
  Widget build(BuildContext context) {
    print("build UserLoader");
    final _formKey = new GlobalKey<FormState>();
    final _firstNameController = new TextEditingController();
    final _lastNameController = new TextEditingController();
    final _emailController = new TextEditingController();
    final _phoneController = new TextEditingController();

    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Informations"),
          actions: <Widget>[
            new IconButton(
                icon: const Icon(Icons.save),
                onPressed: () {
                  _user = _onFormValidate(
                      _formKey.currentState,
                      _firstNameController.text,
                      _lastNameController.text,
                      _emailController.text,
                      _phoneController.text);
                })
          ],
        ),
        body: new Center(
          child: new SingleChildScrollView(
              child: new Form(
                  key: _formKey,
                  child: new Column(children: <Widget>[
                    new ListTile(
                      leading: const Icon(Icons.person),
                      title: new TextFormField(
                        decoration: new InputDecoration(
                          hintText: "Prénom",
                        ),
                        keyboardType: TextInputType.text,
                        controller: _firstNameController,
                        validator: _validateName,
                      ),
                    ),
                    new ListTile(
                      leading: const Icon(Icons.person),
                      title: new TextFormField(
                        decoration: new InputDecoration(
                          hintText: "Nom",
                        ),
                        keyboardType: TextInputType.text,
                        controller: _lastNameController,
                        validator: _validateName,
                      ),
                    ),
Etc, etc ...

However when i tap the TextField, the keyboard appear and close immediately and all the component is rebuild. So it is impossible for me to complete the form..

Can someone have a solution please? Thanks in advance !

Body:
you just need make a new class and import that on your target class that seen problem. for example :

I usually create a class like this :

class MiddleWare
{
  static MiddleWare shared = MiddleWare();
  _MiddleWare(){}
  String myText = "my Text";
  // every variables should be here...
}

and

import "MiddleWare.dart";

class myclass extends StatefulWidget {
  @override
  _myclassState createState() => _myclassState();
}

class _myclassState extends State<myclass> {
  @override
  Widget build(BuildContext context) {
    return Container(child: Text(MiddleWare.shared.myText));
  }
}

that's it.


问:
Remove Open Beta from Google Console
I had an app in Alpha, that I wanted to get a bit more people to test. I set an open beta, and the app became searchable in the app store. I had some issues and the client wanted to go back to an close Alpha test and have the employees keep getting updates through the app store.

I can go back to the closed Alpha, but I cannot seem to remove the open beta track and the app is still searchable in the app store.

How can I resolve this?

答:
To remove the open beta, create an empty release (one with no APKs on it) and publish it to the open beta track.

Note that I believe this will not prevent people who have already seen the app from seeing the listing. But they won't be able to install it.

Title: Remove Open Beta from Google Console


问:
Extract URL parameter
I am trying to get a URL parameter from the following URL

```<code>http://localhost:4200/#/candidate/login/?corporateid=66d8c83c-841a-42e8-945c-beb8c1af25ef&userid=cb2147ed-bd42-4b9f-82d4-0dcef861e24d&token=CfDJ8Ie7+UQ8GQRBtQNOMB6ytQXk0OvqW+/l9W1yh3gCLQw7Sa606eaQtWAC472uUrsUnMQtt69R4gF7f6aab/lIdToo9AfiwtJ7wlsdYnomPpo1OgOaIUZZVBtEaBxRfuJin/Rl+WO+AnvHAn6v4Sf2yO+2gkNotCw0yLsfgzKYOwOciVRDHWY5mNktbGsRCb96kbnxd6VyW02Vs7szuSBG4Ow5fFdtvVUkQDj+ne4HZQAyvts8pNOOkNT/g+cCbOO/wA==
</code>```

The parameter value that I need is the userid but I seem to be getting a null.

Here is my code

```<code>location = window.location;
urlHref = location.href;
urlConvert = new URL(this.urlHref);

if (location.toString().includes('userid')) {
  this.userId = this.urlConvert.searchParams.get("userid");
  console.log(this.userId);
} else {
  this.userId = 'user';
  console.log('gets user not candidate');
}
</code>```

答:
You can use ActivatedRoute to get your route params. In addition, it is possible to get always fresh parameters by using queryParamMap. Because queryParamMap returns  Observable<ParamMap>:

```<code>constructor(
        private route: ActivatedRoute
)

this.route.queryParamMap.subscribe(params => {
    let userId = params.get('userId ');
});
</code>```

Title: Extract URL parameter

Body:
I am trying to get a URL parameter from the following URL

http://localhost:4200/#/candidate/login/?corporateid=66d8c83c-841a-42e8-945c-beb8c1af25ef&userid=cb2147ed-bd42-4b9f-82d4-0dcef861e24d&token=CfDJ8Ie7+UQ8GQRBtQNOMB6ytQXk0OvqW+/l9W1yh3gCLQw7Sa606eaQtWAC472uUrsUnMQtt69R4gF7f6aab/lIdToo9AfiwtJ7wlsdYnomPpo1OgOaIUZZVBtEaBxRfuJin/Rl+WO+AnvHAn6v4Sf2yO+2gkNotCw0yLsfgzKYOwOciVRDHWY5mNktbGsRCb96kbnxd6VyW02Vs7szuSBG4Ow5fFdtvVUkQDj+ne4HZQAyvts8pNOOkNT/g+cCbOO/wA==

The parameter value that I need is the userid but I seem to be getting a null.

Here is my code

location = window.location;
urlHref = location.href;
urlConvert = new URL(this.urlHref);

if (location.toString().includes('userid')) {
  this.userId = this.urlConvert.searchParams.get("userid");
  console.log(this.userId);
} else {
  this.userId = 'user';
  console.log('gets user not candidate');
}

Body:
You can use ActivatedRoute to get your route params. In addition, it is possible to get always fresh parameters by using queryParamMap. Because queryParamMap returns  Observable<ParamMap>:

constructor(
        private route: ActivatedRoute
)

this.route.queryParamMap.subscribe(params => {
    let userId = params.get('userId ');
});


问:
Selecting Only The Latest Version Of A Field
I have a table schema with ID, Title, Date

and data looks something like this:

```<code>1  The title1    2011-04-05 00:00:00.000
2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
4  The title1    2011-04-11 00:00:00.000
</code>```

I need help with sql to give me the latest date of each title.
So the output for the above data is

```<code>2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
</code>```

答:
Take a look at Including an Aggregated Column's Related Values, there are several ways to accomplish this

One way would be

```<code>select t1.* from(
select Title, Max(Date) as MaxDate
From YourTable
group by Title) t2
join YourTable t1 on t2.Title = t1.Title
and t1.Date = t2.MaxDAte
</code>```

Body:
I have a table schema with ID, Title, Date

and data looks something like this:

1  The title1    2011-04-05 00:00:00.000
2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
4  The title1    2011-04-11 00:00:00.000

I need help with sql to give me the latest date of each title.
So the output for the above data is

2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633

Body:
Take a look at Including an Aggregated Column's Related Values, there are several ways to accomplish this

One way would be

select t1.* from(
select Title, Max(Date) as MaxDate
From YourTable
group by Title) t2
join YourTable t1 on t2.Title = t1.Title
and t1.Date = t2.MaxDAte


问:
out = [item for t in lt for item in t] how this will get executed
out = [item for t in lt for item in t], how this loop will get executed, please elaborate this  as I am a beginner in python so I am having difficulty to understand this concept

```<code> lt = [('Geeks', 2), ('For', 4), ('geek', '6')]

 out = [item for t in lt for item in t]

 print(out)
</code>```

答:
Your list comprehension will be executed as:

```<code>out = []
for t in lt:
    for item in t:
        out.append(item)
</code>```

The result will be a flattened list.

Notice that the left-to-right order of the for loops in the list comprehension is the same as the outer-to-inner order of the for loops in the expanded version.

Body:
out = [item for t in lt for item in t], how this loop will get executed, please elaborate this  as I am a beginner in python so I am having difficulty to understand this concept

 lt = [('Geeks', 2), ('For', 4), ('geek', '6')]

 out = [item for t in lt for item in t]

 print(out)

Body:
Your list comprehension will be executed as:

out = []
for t in lt:
    for item in t:
        out.append(item)

The result will be a flattened list.

Notice that the left-to-right order of the for loops in the list comprehension is the same as the outer-to-inner order of the for loops in the expanded version.


问:
UserDefaults not working on didload in my project
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

```<code>class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}
</code>```

When the  user clicks login Button, the code is as below

```<code>ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}
</code>```

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

答:
In your code

```<code>class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}

</code>```

The 'isLoggedIn' is just a value type. It will not change by UserDefaults.standard's some value's changing. Because your declare is just set a default value to that.if you want to have a variable to imply the global unique semantic, you must insure that modify it in the same address, and get it from the same address too.

Body:
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}

When the  user clicks login Button, the code is as below

ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

Body:
In your code

class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}

The 'isLoggedIn' is just a value type. It will not change by UserDefaults.standard's some value's changing. Because your declare is just set a default value to that.if you want to have a variable to imply the global unique semantic, you must insure that modify it in the same address, and get it from the same address too.


问:
Ways to parse the EDI 834 formatted document with R?
I am looking up for the way to parse the Insurance data which is present in the EDI 834 format. I know there are ways with JAVA and XML, but my requirement is to do it with R.

I have tried it with r and regex but as it contains elements and sub elements which i am unable to decode.

I am looking up for the to convert it into table with different columns containing values.

答: One option is to use the free EDI API and consume it just like any other REST API</p>


答:
```<code>   lst =  [item for t in lt for item in t]
</code>```

The above code is similar to the below one,

```<code>lst = []
for t in lt:
    for item in t:
        lst.append(item)
</code>```

List comprehension:

List comprehensions provide a concise way to create lists. It consists
  of brackets containing an expression followed by a for clause, then
  zero or more for or if clauses. The expressions can be anything,
  meaning you can put in all kinds of objects in lists.

Title: out = [item for t in lt for item in t] how this will get executed

Body:
   lst =  [item for t in lt for item in t]

The above code is similar to the below one,

lst = []
for t in lt:
    for item in t:
        lst.append(item)

List comprehension:

List comprehensions provide a concise way to create lists. It consists
  of brackets containing an expression followed by a for clause, then
  zero or more for or if clauses. The expressions can be anything,
  meaning you can put in all kinds of objects in lists.


问:
Python - empty class constructor (style)
What is a "Pythonic" way to define a class that does not need any constructor parameters?

```<code>class MyClass:

    # class body

</code>```

or do we need an explicit constructor? i.e.

```<code>class MyClass:
    def __init__:
        pass

    # class body
</code>```

答:
Your first approach is good enough, unless you want to only use class attributes and not instance attributes

Also every class in Python inherits from object, as explained in detail here

```<code>class MyClass:
    pass
</code>```

An example of such classes might be as follows

A class to store multiple class attributes

```<code>class MyClass:

    a = 1
    b = 2

print(MyClass.a)
#1
print(MyClass.b)
#2
</code>```

A custom exception where the constructor is implicitly taken from the base class

```<code>class MyException(Exception):

    pass

raise MyException
#    raise MyException
#__main__.MyException
</code>```

Body:
What is a "Pythonic" way to define a class that does not need any constructor parameters?

class MyClass:

    # class body

or do we need an explicit constructor? i.e.

class MyClass:
    def __init__:
        pass

    # class body

Body:
Your first approach is good enough, unless you want to only use class attributes and not instance attributes

Also every class in Python inherits from object, as explained in detail here

class MyClass:
    pass

An example of such classes might be as follows

A class to store multiple class attributes

class MyClass:

    a = 1
    b = 2

print(MyClass.a)
#1
print(MyClass.b)
#2

A custom exception where the constructor is implicitly taken from the base class

class MyException(Exception):

    pass

raise MyException
#    raise MyException
#__main__.MyException


问:
How to standardize values in a column based on grouping by two other columns in R?
I'm sure this is a really simple thing but I'm very new to R.

I have three columns, one with values I need standardized, one with age groups and one with gender. I want a new column where the standardization is made by agegroup and sex, for example 18-28 year old females have different scores than 18-28 year old males.

R
def function(foo):
    print(foo)

```<code>
       agegroup gender value
1      68-90      M           0.55140187
2      38-48      M           0.93333333
3      18-28      F           0.43283582
4       0-18      F           0.00001000
5       0-18      M           0.00001000
6      28-38      F           0.04081633
7      18-28      F           0.37837838
8      28-38      M           0.57142857
9      28-38      F           0.34183673
10     18-28      F           0.37804878
11     28-38      M           0.53571429
12      0-18      M           0.00001000

</code>```

I have tried using dplyr

```<code>df %>% group_by(agegroup, gender) %>% mutate(scaled = scale(values))
</code>```

The grouping is not happening by gender as well as age group. I think I have to use summarise but I'm not sure how to.

I'm sorry if this is really simple or not well explained, as I said I'm very new to this. Thanks for any help!

答:
What you have done seems to be right. You cannot use summarise() as it returns a single value and not a vector.

From your question, I'm not sure if you want to scale the value for each group or find the sum of value for each group. I've sampled both the cases.

# Sample data
  age sex values
1 <10   M      1
2 <10   M      2
3 >10   F      3
4 >10   F      4
5 >10   M      5

# Scaling value
df %>% group_by(age, sex) %>% mutate(std_value = scale(values))
  age   sex   values std_value
  <fct> <fct>  <dbl>     <dbl>
1 <10   M          1    -0.707
2 <10   M          2     0.707
3 >10   F          3    -0.707
4 >10   F          4     0.707
5 >10   M          5   NaN

# Sum of values
df %>% group_by(age, sex) %>% mutate(sum_value = sum(values))
  age   sex   values sum_value
  <fct> <fct>  <dbl>     <dbl>
1 <10   M          1         3
2 <10   M          2         3
3 >10   F          3         7
4 >10   F          4         7
5 >10   M          5         5
```

Body:
I'm sure this is a really simple thing but I'm very new to R.

I have three columns, one with values I need standardized, one with age groups and one with gender. I want a new column where the standardization is made by agegroup and sex, for example 18-28 year old females have different scores than 18-28 year old males.

R
def function(foo):
    print(foo)

       agegroup gender value
1      68-90      M           0.55140187
2      38-48      M           0.93333333
3      18-28      F           0.43283582
4       0-18      F           0.00001000
5       0-18      M           0.00001000
6      28-38      F           0.04081633
7      18-28      F           0.37837838
8      28-38      M           0.57142857
9      28-38      F           0.34183673
10     18-28      F           0.37804878
11     28-38      M           0.53571429
12      0-18      M           0.00001000

I have tried using dplyr

df %>% group_by(agegroup, gender) %>% mutate(scaled = scale(values))

The grouping is not happening by gender as well as age group. I think I have to use summarise but I'm not sure how to.

I'm sorry if this is really simple or not well explained, as I said I'm very new to this. Thanks for any help!


问:
How to tell if the server socket is not available?
socket client is running on android:

```<code>try {
    socketClient = new Socket(host, port);

    //set socket input
    in = socketClient.getInputStream();
    dIn = new DataInputStream(in);

    //set socket output
    out = socketClient.getOutputStream();
    dOut = new DataOutputStream(out);

    int c = 0;
    String data = "";

    while ((c = dIn.read()) != -1) {
       //print data
    }
} catch (Exception e) {
    //close connection
}
</code>```

my server run on python and everything is works fine except until the server is not running and when i try to connect to server it takes  two minutes to catch the error that the server is not available

How can I reduce the time for example catch the error in 10 sec

答:
According to this answer

use

```<code>Socket socketClient = new Socket();
socketClient.connect(new InetSocketAddress(host, port),connection_time_out)
</code>```

instead of

```<code>socketClient = new Socket(host, port);
</code>```

connection_time_out = limits the time allowed to establish a connection in the case that the connection is refused or server doesn't exist.

Body:
socket client is running on android:

try {
    socketClient = new Socket(host, port);

    //set socket input
    in = socketClient.getInputStream();
    dIn = new DataInputStream(in);

    //set socket output
    out = socketClient.getOutputStream();
    dOut = new DataOutputStream(out);

    int c = 0;
    String data = "";

    while ((c = dIn.read()) != -1) {
       //print data
    }
} catch (Exception e) {
    //close connection
}

my server run on python and everything is works fine except until the server is not running and when i try to connect to server it takes  two minutes to catch the error that the server is not available

How can I reduce the time for example catch the error in 10 sec

Body:
According to this answer

use

Socket socketClient = new Socket();
socketClient.connect(new InetSocketAddress(host, port),connection_time_out)

instead of

socketClient = new Socket(host, port);

connection_time_out = limits the time allowed to establish a connection in the case that the connection is refused or server doesn't exist.


问:
Extracting images from pdf using Python
How can we extract images(only images) from PDF.

I used many online tools, they all are not universal. In most of the PDF, it tools the screenshot of the whole image instead of the image.
PDF link -> sg.inflibnet.ac.in:8080/jspui/bitstream/10603/121661/9/09_chapter 4.pdf

答:
Here is some code that reads a PDF-File using pyPdf, extracts images and yields them as a PIL.Image. You need to modify it to your needs, it's just here to demonstrate how to walk the object tree.

```<code>import io
import pyPdf
import PIL.Image

infile_name = 'my.pdf'

with open(infile_name, 'rb') as in_f:
    in_pdf = pyPdf.PdfFileReader(in_f)
    for page_no in range(in_pdf.getNumPages()):
        page = in_pdf.getPage(page_no)

        # Images are part of a page's `/Resources/XObject`
        r = page['/Resources']
        if '/XObject' not in r:
            continue
        for k, v in r['/XObject'].items():
            vobj = v.getObject()
            # We are only interested in images...
            if vobj['/Subtype'] != '/Image' or '/Filter' not in vobj:
                continue
            if vobj['/Filter'] == '/FlateDecode':
                # A raw bitmap
                buf = vobj.getData()
                # Notice that we need metadata from the object
                # so we can make sense of the image data
                size = tuple(map(int, (vobj['/Width'], vobj['/Height'])))
                img = PIL.Image.frombytes('RGB', size, buf,
                                          decoder_name='raw')
                # Obviously we can't really yield here, do something with `img`...
                yield img
            elif vobj['/Filter'] == '/DCTDecode':
                # A compressed image
                img = PIL.Image.open(io.BytesIO(vobj._data))
                yield img
</code>```

Title: Extracting images from pdf using Python

Body:
Here is some code that reads a PDF-File using pyPdf, extracts images and yields them as a PIL.Image. You need to modify it to your needs, it's just here to demonstrate how to walk the object tree.

import io
import pyPdf
import PIL.Image

infile_name = 'my.pdf'

with open(infile_name, 'rb') as in_f:
    in_pdf = pyPdf.PdfFileReader(in_f)
    for page_no in range(in_pdf.getNumPages()):
        page = in_pdf.getPage(page_no)

        # Images are part of a page's `/Resources/XObject`
        r = page['/Resources']
        if '/XObject' not in r:
            continue
        for k, v in r['/XObject'].items():
            vobj = v.getObject()
            # We are only interested in images...
            if vobj['/Subtype'] != '/Image' or '/Filter' not in vobj:
                continue
            if vobj['/Filter'] == '/FlateDecode':
                # A raw bitmap
                buf = vobj.getData()
                # Notice that we need metadata from the object
                # so we can make sense of the image data
                size = tuple(map(int, (vobj['/Width'], vobj['/Height'])))
                img = PIL.Image.frombytes('RGB', size, buf,
                                          decoder_name='raw')
                # Obviously we can't really yield here, do something with `img`...
                yield img
            elif vobj['/Filter'] == '/DCTDecode':
                # A compressed image
                img = PIL.Image.open(io.BytesIO(vobj._data))
                yield img


问:
Hide/Snooze issues in YouTrack
I want to use YouTrack for Key-Account-Management.

There is one Epic and for each key account (customer) one sub-issue.

I want to talk to each key account roughly every 6 months.

Is there a way to hide or snooze an issue for some time.

The issue should be like resolved for some months, and then come back if the snooze time has expired.

How to do this with youtrack?

答:
The issue should be like resolved for some months

It seems that one can simply resolve the issue to accomplish it.
The tricky part is to reopen them automatically in 6 months. The following workflow rule can reopen YouTrack issues by timer:

var entities = require('@jetbrains/youtrack-scripting-api/entities');
var workflow = require('@jetbrains/youtrack-scripting-api/workflow');

exports.rule = entities.Issue.onSchedule({
  title: workflow.i18n('Reopen issues in 6 months'),
  search: '#Resolved',    // Narrow the search to specify which issues are affected
  cron: '0 0 0 ? * * *',  // Fires once a day
  guard: function(ctx) {
    // If an issue was in a resolved state for half a year already...
    return Date.now() - ctx.issue.resolved < 15552000000;
  },
  action: function(ctx) {
    // ... then reopen it
    ctx.issue.State = ctx.State.Open;
  },
  requirements: {
    State: {
      type: entities.State.fieldType,
      Open: {}
    }
  }
});
```

Title: Hide/Snooze issues in YouTrack


问:
I need delete two " " with sed command
I need to delete "" in file

```<code>"CITFFUSKD-E0"
</code>```

I have tried sed 's/\"//.

Result is:

```<code>CITFFUSKD-E0"
</code>```

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

```<code>"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"
</code>```

Result I want it:

```<code>CITFFUSKD
</code>```

答:
This should do all in one go, remove the ", print the first part:

```<code>awk -F\" '{split($2,a,"-| |_");print a[1]}' file
CITFFUSKD
CITFFUSKD
CITFFUSKD
</code>```

Title: I need delete two " " with sed command

Body:
I need to delete "" in file

"CITFFUSKD-E0"

I have tried sed 's/\"//.

Result is:

CITFFUSKD-E0"

How I can delete both ?

Also I need to delete everything behind first word but input can be this one:

"CITFFUSKD-E0"
"CITFFUSKD_E0"
"CITFFUSKD E0"

Result I want it:

CITFFUSKD

Body:
This should do all in one go, remove the ", print the first part:

awk -F\" '{split($2,a,"-| |_");print a[1]}' file
CITFFUSKD
CITFFUSKD
CITFFUSKD


问:
Can't import module from dependent project in PyDev
I'm probably doing something really dumb here, but it's driving me crazy.

I have two PyDev projects in Eclipse. One project, 'Analysis' depends on the other, 'PyCommon'. I'm 100% sure of this as when I look at the project references for Analysis, PyCommon is checked, and automatic import/code completion works when I reference elements in PyCommon from Analysis.

I'm trying to write/run a module in Analysis. The module is fhb/analysis/log_parsers.py.

I'm trying to import the element OrderStatus from fhb/pycommon/types/order_status in the PyCommon project. So, my import statement is

'from fhb.pycommon.types.order_status import OrderStatus'

PyDev clearly knows where this is because that import statement was written automatically by PyDev on a quickfix correction. Nonetheless, when I try to run the main function in log_parsers.py, I get this:

Traceback (most recent call last):
   File "/workspace/Analysis/src/fhb/analysis/log_parsers.py", line 6, in
     from fhb.pycommon.types.order_type import OrderType
  ImportError: No module named pycommon.types.order_status

All of these packages are under a proper source folder ('src') in each project.

Also, even though Analysis absolutely is set to reference PyCommon , when I look under PyDev-PYTHONPATH in Analysis's properties, only Analysis's own src folder appears under the 'Source Folder' tab, and it's the only project I see if I click on 'Add source folder'

答: I believe you have to add the path of PyCommon into PYTHONPATH or else it won't be able to find the actual modules to import.</p>


问:
Unable to enroll user in new org added to balance transfer sample
I am following Balance transfer from Hyperledger Fabric samples from this link. I have modified it a bit, now I have 3 Orgs with 1 Peer each. All goes fine till I enroll users to Org1 and Org2 but, when I try to enroll a user to my 3rd Org I get following error

Failed to get registered user: xyz with error: Error: fabric-ca request register failed with errors [[{"code":63,"message":"Failed to get Affiliation: sql: no rows in result set"}]]

My Binaries of Hyperledger Fabric are from version 1.1.0 Alfa

答:
You can add more organizations and there departments by changing the fabric-ca-server-config by going to the fabric-ca docker container.

```<code>docker exec -it ca.org1.example.com bash
</code>```

Go the root@c3804e2852fd:/etc/hyperledger/fabric-ca-server# directory inside the container

Now edit fabric-ca-server-config.yaml file. Add organizations and their departments as per your choice.

Below i have added one "Manufacturer" organization. You can add Org3 like this.

Body:
You can add more organizations and there departments by changing the fabric-ca-server-config by going to the fabric-ca docker container.

docker exec -it ca.org1.example.com bash

Go the root@c3804e2852fd:/etc/hyperledger/fabric-ca-server# directory inside the container

Now edit fabric-ca-server-config.yaml file. Add organizations and their departments as per your choice.

Below i have added one "Manufacturer" organization. You can add Org3 like this.


问:
Dynamically load external javascript file from Angular component
I am creating an Angular application using Angular 4 and the CLI. I am trying to add the SkyScanner search widget into one of my components.

Skyscanner Widget Example

Part of the implementation requires the addition of a new external script:

```<code><script src="https://widgets.skyscanner.net/widget-server/js/loader.js" async></script>
</code>```

I am not sure of the correct way to reference this file. If I add the script into my index.html file, the widget doesn't load unless a full page refresh is performed. I assume the script tries to manipulate the DOM on load and the elements don't exist when the script runs.

What is the correct way to load the script only when the component containing the Skyscanner widget is loaded?

答:
The accepted answer is correct but won't work because browser takes little more time to parse the script after downloading it. So if any variable is being used from the loaded script, then it needs to be used on onload event of the newly created html script element. I have improved the accepted answer as mentioned below -</p>

```<code>loadAPI: Promise<any>;

constructor() {
    this.loadAPI = new Promise((resolve) => {
        let node = this.loadScript();
        if (node) {
            node.onload = () => {
                resolve(true);
            };
        } else {
            resolve(true);
        }
    });
}

ngOnInit() {
    this.loadAPI
        .then((flag) => {
        //Do something when script is loaded and parsed by browser
    });
}

loadScript() {
    let node = undefined;
    let isFound = false;
    const scripts = document.getElementsByTagName('script')
    for (let i = 0; i < scripts.length; ++i) {
        // Check if script is already there in html
        if (scripts[i].getAttribute('src') != null && scripts[i].getAttribute('src').includes("loader")) {
          isFound = true;
        }
    }

    if (!isFound) {
        const dynamicScript = 'https://widgets.skyscanner.net/widget-server/js/loader.js';
        node = document.createElement('script');
        node.src = dynamicScript;
        node.type = 'text/javascript';
        node.async = false;
        node.charset = 'utf-8';
        document.getElementsByTagName('head')[0].appendChild(node);
        return node;
    }
    return node;
}
</code>```

Body:
I am creating an Angular application using Angular 4 and the CLI. I am trying to add the SkyScanner search widget into one of my components.

Skyscanner Widget Example

Part of the implementation requires the addition of a new external script:

I am not sure of the correct way to reference this file. If I add the script into my index.html file, the widget doesn't load unless a full page refresh is performed. I assume the script tries to manipulate the DOM on load and the elements don't exist when the script runs.

What is the correct way to load the script only when the component containing the Skyscanner widget is loaded?

Body:
The accepted answer is correct but won't work because browser takes little more time to parse the script after downloading it. So if any variable is being used from the loaded script, then it needs to be used on onload event of the newly created html script element. I have improved the accepted answer as mentioned below -

loadAPI: Promise<any>;

constructor() {
    this.loadAPI = new Promise((resolve) => {
        let node = this.loadScript();
        if (node) {
            node.onload = () => {
                resolve(true);
            };
        } else {
            resolve(true);
        }
    });
}

ngOnInit() {
    this.loadAPI
        .then((flag) => {
        //Do something when script is loaded and parsed by browser
    });
}

loadScript() {
    let node = undefined;
    let isFound = false;
    const scripts = document.getElementsByTagName('script')
    for (let i = 0; i < scripts.length; ++i) {
        // Check if script is already there in html
        if (scripts[i].getAttribute('src') != null && scripts[i].getAttribute('src').includes("loader")) {
          isFound = true;
        }
    }

    if (!isFound) {
        const dynamicScript = 'https://widgets.skyscanner.net/widget-server/js/loader.js';
        node = document.createElement('script');
        node.src = dynamicScript;
        node.type = 'text/javascript';
        node.async = false;
        node.charset = 'utf-8';
        document.getElementsByTagName('head')[0].appendChild(node);
        return node;
    }
    return node;
}


问:
How to fix "ValueError: not enough values to unpack (expected 2, got 1)"
I am trying to make a music app using tkinter and python, but I am not able to get rid of "ValueError: not enough values to unpack (expected 2, got 1)" bug. Have a look at my code and you'd be much clear with what I am dealing. </p>

<p>The mechanism is pretty simple, I, at first, display the song options via dictionary(list), and after taking the input, corresponding value of "j",(example, if input is 1 then j is one and corresponding value of j is i) to be saved as the name of the song and execute the program by playing the music.  </p>

```<code>list = {
    '1':'Say You Won t Let Go.mp3','2':'In the Jungle the mighty jungle.mp3'
}
lost = ''
print(list)
print("which one?")
this_one = int(input(''))
for j,i in list:
    if j == this_one:
        lost = i
</code>```

答:
Please try with items() as you are traversing over dict

```<code>for j,i in list.items():
</code>```

Body:
I am trying to make a music app using tkinter and python, but I am not able to get rid of "ValueError: not enough values to unpack (expected 2, got 1)" bug. Have a look at my code and you'd be much clear with what I am dealing.

The mechanism is pretty simple, I, at first, display the song options via dictionary(list), and after taking the input, corresponding value of "j",(example, if input is 1 then j is one and corresponding value of j is i) to be saved as the name of the song and execute the program by playing the music.

list = {
    '1':'Say You Won t Let Go.mp3','2':'In the Jungle the mighty jungle.mp3'
}
lost = ''
print(list)
print("which one?")
this_one = int(input(''))
for j,i in list:
    if j == this_one:
        lost = i

Body:
Please try with items() as you are traversing over dict

for j,i in list.items():


问:
Verify if test case body or teardown fails in teardown
We use ${TEST_STATUS} variable to determine in test teardown section if some keyword fails in test body. Based on the value we either collect or not logs from SUT.

However, if some keyword fails in test teardown section just before verification of ${TEST_STATUS} and test body passes, the value of the variable does not reflect that.

Is it possible to check if any keyword fails in test body, setup and teardown, and based on that perform some logic in teardown? Or any other suggestions?

答:
Found an issue in Robot Framework Github. As per discussion, it is hard to fix and requires huge amount of efforts. If someone is interested in fixing, Robotframework community suggests to sponsor this from 3rd party end.

So far work-arounds are unclear.


问:
Only parameterless constructors and initializers are supported in LINQ to Entities
I have this error in this linq expression :

```<code>var naleznosci = (from nalTmp in db.Naleznosci
                              where nalTmp.idDziecko == idDziec
                              select new Payments
                              (
                                  nalTmp.Dziecko.Imie,
                                  nalTmp.Dziecko.Nazwisko,
                                  nalTmp.Miesiace.Nazwa,
                                  nalTmp.Kwota,
                                  nalTmp.RodzajeOplat.NazwaRodzajuOplaty,
                                  nalTmp.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
                                  nalTmp.DataRozliczenia,
                                  nalTmp.TerminPlatnosci
                              )).ToList();
</code>```

Any idea how solve this problem? I try with any combination of expression... :/

答:
Although it is late to answer, it could still help someone in distress. Since LINQ to entities do not support the parameter-less object constructions. However, the projection methods for IEnumerable.

So prior to selection, just convert your IQueryable to IEnumerable by using this code:

```<code>var result = myContext.SomeModelClass.AsEnumerable().Select(m => m.ToString());
</code>```

It will work fine. However, it will, of course, loose the benefits of native queries.

Body:
I have this error in this linq expression :

var naleznosci = (from nalTmp in db.Naleznosci
                              where nalTmp.idDziecko == idDziec
                              select new Payments
                              (
                                  nalTmp.Dziecko.Imie,
                                  nalTmp.Dziecko.Nazwisko,
                                  nalTmp.Miesiace.Nazwa,
                                  nalTmp.Kwota,
                                  nalTmp.RodzajeOplat.NazwaRodzajuOplaty,
                                  nalTmp.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
                                  nalTmp.DataRozliczenia,
                                  nalTmp.TerminPlatnosci
                              )).ToList();

Any idea how solve this problem? I try with any combination of expression... :/

Body:
Although it is late to answer, it could still help someone in distress. Since LINQ to entities do not support the parameter-less object constructions. However, the projection methods for IEnumerable.

So prior to selection, just convert your IQueryable to IEnumerable by using this code:

var result = myContext.SomeModelClass.AsEnumerable().Select(m => m.ToString());

It will work fine. However, it will, of course, loose the benefits of native queries.


问:
python selenium - how to execute mobile chrome on incognito mode?
I'm trying to implement mobile chrome crawler using python selenium.

And I want to execute mobile chrome on incognito mode.
So, I tried as below.

```<code>options = webdriver.ChromeOptions()
## run chrome on incognito mode not to use web cache.
options.add_argument("--incognito")
options.add_experimental_option('androidPackage','com.android.chrome')

driver = webdriver.Chrome(chrome_options=options)
</code>```

But, mobile chrome was executed on default mode, not incognito mode.
Help me please.

答:
This worked for me:

```<code>chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")

driver = webdriver.Chrome("driver path", chrome_options=chrome_options)
</code>```

Body:
I'm trying to implement mobile chrome crawler using python selenium.

And I want to execute mobile chrome on incognito mode.
So, I tried as below.

options = webdriver.ChromeOptions()
## run chrome on incognito mode not to use web cache.
options.add_argument("--incognito")
options.add_experimental_option('androidPackage','com.android.chrome')

driver = webdriver.Chrome(chrome_options=options)

But, mobile chrome was executed on default mode, not incognito mode.
Help me please.

Body:
This worked for me:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")

driver = webdriver.Chrome("driver path", chrome_options=chrome_options)


问:
Counting coins in APL
The function Count below calculates the minimal number of coins which sums up to a given amount.

```<code>∇ R ← d AppendQuotRem qrs; oldR; q; r
    oldR ← 2 ⊃ (⍴qrs) ⊃ qrs
    q ← ⌊oldR ÷ d
    r ← oldR - d × q
    R ← qrs , ,⊂(q r)
∇

∇ R ← Count amount; ds; qrs; qs
    ds ← 1 5 10 25 50  ⍝ coin denominations in cents
    qrs ← ⊃AppendQuotRem/ ds , ⊂,⊂(0 amount)
    qs ← 1 ⊃¨ qrs
    R ← ds ,[0.5] ⌽1 ↓ qs
∇
</code>```

For each denomination I calculate a quotient and a remainder. The remainder is used in the calculation involving the next denomination. Is there a shorter and/or more straight forward way to solve the problem?

答:
The change-making problem is actually quite hard. A full APL approach is included in the dfns workspace.

Your algorithm is greedy, which gives the wrong result for certain sets sets of coin denominations. It just happens to work out with the set you use in your example. Let's modify your Count function:

∇ R ← Count134 amount; ds; qrs; qs
    ds ← 1 3 4  ⍝ coin denominations in cents
    qrs ← ⊃AppendQuotRem/ ds , ⊂,⊂(0 amount)
    qs ← 1 ⊃¨ qrs
    R ← ds ,[0.5] ⌽1 ↓ qs
∇
      Count134 6
1 3 4
2 0 1
```

<p>This uses three coins, but two 3-cent coins is the correct answer:</p>

<pre class="lang-apl prettyprint-override"><code>1 3 4
0 2 0
</code>```

That being said, common coinage systems are designed such that a greedy algorithm will produce the optimal result. Here is thus a simplification of your code:

∇ R ← d AppendQuotRem qrs; oldR; q; r
    oldR ← 1 ↑ qrs
    q ← ⌊oldR ÷ d
    r ← d | oldR
    R ← r , q , 1 ↓ qrs
∇

∇ R ← Count amount; ds
    ds ← 1 5 10 25 50  ⍝ coin denominations in cents
    R ← ds ,[0.5] ⊃AppendQuotRem/ 1 ↓ ds , amount
∇
```

Try it online!

Title: Counting coins in APL

Body:
The function Count below calculates the minimal number of coins which sums up to a given amount.

∇ R ← d AppendQuotRem qrs; oldR; q; r
    oldR ← 2 ⊃ (⍴qrs) ⊃ qrs
    q ← ⌊oldR ÷ d
    r ← oldR - d × q
    R ← qrs , ,⊂(q r)
∇

∇ R ← Count amount; ds; qrs; qs
    ds ← 1 5 10 25 50  ⍝ coin denominations in cents
    qrs ← ⊃AppendQuotRem/ ds , ⊂,⊂(0 amount)
    qs ← 1 ⊃¨ qrs
    R ← ds ,[0.5] ⌽1 ↓ qs
∇

For each denomination I calculate a quotient and a remainder. The remainder is used in the calculation involving the next denomination. Is there a shorter and/or more straight forward way to solve the problem?

Body:
The change-making problem is actually quite hard. A full APL approach is included in the dfns workspace.

Your algorithm is greedy, which gives the wrong result for certain sets sets of coin denominations. It just happens to work out with the set you use in your example. Let's modify your Count function:

∇ R ← Count134 amount; ds; qrs; qs
    ds ← 1 3 4  ⍝ coin denominations in cents
    qrs ← ⊃AppendQuotRem/ ds , ⊂,⊂(0 amount)
    qs ← 1 ⊃¨ qrs
    R ← ds ,[0.5] ⌽1 ↓ qs
∇
      Count134 6
1 3 4
2 0 1

This uses three coins, but two 3-cent coins is the correct answer:

1 3 4
0 2 0

That being said, common coinage systems are designed such that a greedy algorithm will produce the optimal result. Here is thus a simplification of your code:

∇ R ← d AppendQuotRem qrs; oldR; q; r
    oldR ← 1 ↑ qrs
    q ← ⌊oldR ÷ d
    r ← d | oldR
    R ← r , q , 1 ↓ qrs
∇

∇ R ← Count amount; ds
    ds ← 1 5 10 25 50  ⍝ coin denominations in cents
    R ← ds ,[0.5] ⊃AppendQuotRem/ 1 ↓ ds , amount
∇

Try it online!


问:
Installing precompiled ruby gems for the right ruby version?
I need to install some ruby gems with native extensions on machines with no compiler, and I have to do so for a few different ruby versions.

My plan is to have some CI pipeline to download the gem source, compile it and uploade it on a private Rubygems repository.

I'm considering using gem-compiler to build the gems. I see that, by default, gems are bound to the minor Ruby version (e.g. 2.5), and won't work on different versions. There's a command line option to disable the ABI lock, but it looks scary and comes with a do not use warning.

I've been reading the Rubygems API and command documentation, but I couldn't find a way to arrange different binaries for the same gem version so that the right one will be downloaded for the right ruby version.

Is this at all possible? How?

Or should I just go for something more primitive, like having a different private repository for each Ruby version?

答:
I am not sure if this is possible through the rubygems API to mix different binaries. I think you refer primarily to e. g. .so files on linux? If so then you could try to actually compile on your local machine through different ruby versions (use rvm or any other ways to have multiple ruby versions; I compile into versioned directories such as /Programs/Ruby/2.5.2 etc), then build the bindings. Once you have the .so file you could also just put it into the ruby gem; I abuse lib/ for this a lot.

I am not sure how to ensure that it can be easily installed on the target machine, but you could always add some bin/ ruby file that does the installation part.

I guess the first step would be that you can ensure that the correct version is built; once that works, distributing that should be possible. Rubygems isn't doing something magic either.

Edit: Are you referring to windows perhaps? Since you linked to luis, and luis did some work on windows in the past. Windows is probably making things a bit more difficult ... the task seems not trivial.


问:
How to use regular expressions to say that you need to take the value of Categories = .... & Search = ..... &
I have this line.

```<code>let x = "Categories=All&Search=hat&ListPage=15&Page=1";
</code>```

How to use regular expressions to say what you need to take from the beginning of a line and up to 2 characters &.Categories=All&Search=hat&

答:
You can use /([^&]*&){2}/g regex to match what you want.

let x = "Categories=All&Search=hat&ListPage=15&Page=1";
let y = x.match(/([^&]*&){2}/g);
console.log(y);```

Body:
I have this line.

let x = "Categories=All&Search=hat&ListPage=15&Page=1";

How to use regular expressions to say what you need to take from the beginning of a line and up to 2 characters &.Categories=All&Search=hat&


问:
out = [item for t in lt for item in t] how this will get executed
out = [item for t in lt for item in t], how this loop will get executed, please elaborate this  as I am a beginner in python so I am having difficulty to understand this concept

```<code> lt = [('Geeks', 2), ('For', 4), ('geek', '6')]

 out = [item for t in lt for item in t]

 print(out)
</code>```

答:
```<code>lt = [('Geeks', 2), ('For', 4), ('geek', '6')]
out = [item for t in lt for item in t]
print(out)
</code>```

in code you have Double Iteration in List Comprehension and it is equivalent to:

```<code>out = []
for t in lt:
    for item in t:
        out.append(item)
print(out)
</code>```

List Comprehensions

List comprehensions provide a concise way to create lists.

It consists of brackets containing an expression followed by a for
  clause, then zero or more for or if clauses. The expressions can be
  anything, meaning you can put in all kinds of objects in lists.

The result will be a new list resulting from evaluating the expression
  in the context of the for and if clauses which follow it.

Syntax

The list comprehension starts with a '[' and ']', to help you
  remember that the result is going to be a list.

The basic syntax is:

```<code>[ expression for item in list if conditional ]
</code>```

This is equivalent to:

```<code>for item in list:
    if conditional:
        expression
</code>```

Let's break this down and see what it does

```<code>new_list = [expression(i) for i in old_list if filter(i)]
</code>```

new_list    : The new list (result).

expression(i): Expression is based on the variable used for each
  element in the old list.

for i in old_list: The word for followed by the variable name to
  use, followed by the word in the old list.

if filter(i): Apply a filter with an If-statement.

Body:
out = [item for t in lt for item in t], how this loop will get executed, please elaborate this  as I am a beginner in python so I am having difficulty to understand this concept

 lt = [('Geeks', 2), ('For', 4), ('geek', '6')]

 out = [item for t in lt for item in t]

 print(out)

Body:
lt = [('Geeks', 2), ('For', 4), ('geek', '6')]
out = [item for t in lt for item in t]
print(out)

in code you have Double Iteration in List Comprehension and it is equivalent to:

out = []
for t in lt:
    for item in t:
        out.append(item)
print(out)

List Comprehensions

List comprehensions provide a concise way to create lists.

It consists of brackets containing an expression followed by a for
  clause, then zero or more for or if clauses. The expressions can be
  anything, meaning you can put in all kinds of objects in lists.

The result will be a new list resulting from evaluating the expression
  in the context of the for and if clauses which follow it.

Syntax

The list comprehension starts with a '[' and ']', to help you
  remember that the result is going to be a list.

The basic syntax is:

[ expression for item in list if conditional ]

This is equivalent to:

for item in list:
    if conditional:
        expression

Let's break this down and see what it does

new_list = [expression(i) for i in old_list if filter(i)]

new_list    : The new list (result).

expression(i): Expression is based on the variable used for each
  element in the old list.

for i in old_list: The word for followed by the variable name to
  use, followed by the word in the old list.

if filter(i): Apply a filter with an If-statement.


问:
How to assert that a list has at least n items which are greater than x (with hamcrest in junit)
I could with following code check if a list has a item, which greater than 30.

```<code>//Using Hamcrest
List<Integer> ints= Arrays.asList(22,33,44,55);
assertThat(ints,hasItem(greaterThan(30)));
</code>```

But how could I assert if a list has at least 2 items, which are greater than 30?

With AssertJ, there is a solution I know. But I have no idea how to realize that with Hamcrest.

```<code>//Using AssertJ
List<Integer> ints= Arrays.asList(22,33,44,55);
Condition<Integer> greaterThanCondition = new Condition<Integer>("greater") {
        @Override
        public boolean matches (Integer i){
            return i>30;
        }
    } ;
assertThat(ints).haveatLeast(2,greaterThanCondition);
</code>```

答:
Another simple way to test it is</p>

```<code>assertTrue(ints.size() >= 3);
</code>```

Body:
I could with following code check if a list has a item, which greater than 30.

//Using Hamcrest
List<Integer> ints= Arrays.asList(22,33,44,55);
assertThat(ints,hasItem(greaterThan(30)));

But how could I assert if a list has at least 2 items, which are greater than 30?

With AssertJ, there is a solution I know. But I have no idea how to realize that with Hamcrest.

//Using AssertJ
List<Integer> ints= Arrays.asList(22,33,44,55);
Condition<Integer> greaterThanCondition = new Condition<Integer>("greater") {
        @Override
        public boolean matches (Integer i){
            return i>30;
        }
    } ;
assertThat(ints).haveatLeast(2,greaterThanCondition);

Body:
Another simple way to test it is

assertTrue(ints.size() >= 3);


问:
AutoEventWireup and base.OnLoad(e) Calling Self resulting in Stack Overflow
Using VS2008, C#.  When AutoEventWireup is set to true and in a webform I call base.OnLoad(e) like:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    base.OnLoad(e);
}
</code>```

The base.OnLoad(e) ends up calling Page_Load (calls itself).  This ends up with a stack overflow error.  I've been able to solve it by setting AutoEventWireup to false and overriding OnLoad:

```<code>protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
}
</code>```

This works as I expected (no stack overflows).  But can anyone explain why in the first example base.OnLoad(e) calls the same load event (calls itself) rather than calling the OnLoad event in the base class (System.Web.UI.Page)?

答:
Page.OnLoad has the following pseudo-code inside it

```<code>protected virtual void OnLoad() {
    // some stuff

    if (Load != null)
        Load(this, new EventArgs());
}
</code>```

if you override the OnLoad function, what happens is: Your OnLoad happens, then it calls base.OnLoad(), and that calls the (empty) Load event.

If you implement the Load event and call base.OnLoad(), this is what happens: base.OnLoad() calls the Load event. The Load event then calls base.OnLoad(). Then, base.OnLoad() calls the Load event. And the rest is, as they say, to understand recursion you must first understand recursion.

Hope I made myself clear.

Body:
Using VS2008, C#.  When AutoEventWireup is set to true and in a webform I call base.OnLoad(e) like:

protected void Page_Load(object sender, EventArgs e)
{
    base.OnLoad(e);
}

The base.OnLoad(e) ends up calling Page_Load (calls itself).  This ends up with a stack overflow error.  I've been able to solve it by setting AutoEventWireup to false and overriding OnLoad:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
}

This works as I expected (no stack overflows).  But can anyone explain why in the first example base.OnLoad(e) calls the same load event (calls itself) rather than calling the OnLoad event in the base class (System.Web.UI.Page)?

Body:
Page.OnLoad has the following pseudo-code inside it

protected virtual void OnLoad() {
    // some stuff

    if (Load != null)
        Load(this, new EventArgs());
}

if you override the OnLoad function, what happens is: Your OnLoad happens, then it calls base.OnLoad(), and that calls the (empty) Load event.

If you implement the Load event and call base.OnLoad(), this is what happens: base.OnLoad() calls the Load event. The Load event then calls base.OnLoad(). Then, base.OnLoad() calls the Load event. And the rest is, as they say, to understand recursion you must first understand recursion.

Hope I made myself clear.

OwnerDisplayName: configurator


问:
How to use Bazel in Azure Pipelines?
I tried to set up an Azure Build Pipeline that uses Bazel (0.26.0)

My pipeline YAML definition file looks like this:

```<code>trigger:
- master

pool:
  vmImage: 'windows-2019'

steps:
- script: echo Hello, world!
  displayName: 'Run a one-line script'

- script: |
    bazel version
    echo Add other tasks to build, test, and deploy your project.
    echo See https://aka.ms/yaml
  displayName: 'Run a multi-line script'
</code>```

Currently, I try only to find out which Bazel version is installed by calling bazel version - but Azure DevOps reports:

```<code>'bazel' is not recognized as an internal or external command,
operable program or batch file.
Cmd.exe exited with code '9009'.
</code>```

I wonder how I can install and run Bazel in a Azure pipeline - any hints on this?

It seems that this project got it working. But I do not understand how.

答:
You got this error because you use Microsoft-hosted agent, in those agents bazel is not installed. In the example you provided they use Self Hosted (Private) Agent and they install bazel in their agent machine.

1) Install Self Hosted Agent in your private machine and install bazel in the machine.

2) Install bazel during the build pipeline with choco (simple script task):

```<code>choco install bazel
</code>```

After you install it you can use it.

P.S I tried to install via choco and I got an error but bazel indeed installed and in the next step bazel version gave results, so in the installation task put continueOnError = true. (the error is in the python step, if your project not with python it's ok).

Title: How to use Bazel in Azure Pipelines?

Body:
I tried to set up an Azure Build Pipeline that uses Bazel (0.26.0)

My pipeline YAML definition file looks like this:

trigger:
- master

pool:
  vmImage: 'windows-2019'

steps:
- script: echo Hello, world!
  displayName: 'Run a one-line script'

- script: |
    bazel version
    echo Add other tasks to build, test, and deploy your project.
    echo See https://aka.ms/yaml
  displayName: 'Run a multi-line script'

Currently, I try only to find out which Bazel version is installed by calling bazel version - but Azure DevOps reports:

'bazel' is not recognized as an internal or external command,
operable program or batch file.
Cmd.exe exited with code '9009'.

I wonder how I can install and run Bazel in a Azure pipeline - any hints on this?

It seems that this project got it working. But I do not understand how.

Body:
You got this error because you use Microsoft-hosted agent, in those agents bazel is not installed. In the example you provided they use Self Hosted (Private) Agent and they install bazel in their agent machine.

1) Install Self Hosted Agent in your private machine and install bazel in the machine.

2) Install bazel during the build pipeline with choco (simple script task):

choco install bazel

After you install it you can use it.

P.S I tried to install via choco and I got an error but bazel indeed installed and in the next step bazel version gave results, so in the installation task put continueOnError = true. (the error is in the python step, if your project not with python it's ok).


问:
Readlines of blob in Azure Storage Really Slow
Im using CloudBlockBlob and OpenReadAsync to open a file in azure storage and using readline looping through the file to process the lines.

However this is really slow and takes forever to go through a 3gb file with approx. 70million lines in it.

Whats the best practice with something like this? Download to a temp directory first? but I don't know if that will make the read any faster?

答:
As reference, I have an idea about readlines a block blob parallelly in stream.

According to the offical document about Azure Blob storage limits, the max size of a block in a block blob is 100 MB, so there is 31 blocks at least in a 3GB file of block blob.

Assume that each line in the file was generated automatically by a service to write into a blob, so I think there are a lot of completed lines without break in a block.

Therefore, the solution to readlines parallel with multi-threads or multi-processes is using Get Block List in main thread and Get Blob in Range (for REST API, to set Range or x-ms-range in request header, as below) in each work thead.

Here is the steps of the logic flow above.

In main thread, to get the block list of a block blob, the block list response body includes the id and size of echo block, as below.

So you can easily compute the range of each block, for example above, the first and second blocks' range are 0-4194304 and 4194305-8388608.

To create a thread pool, you can specify a work thread to process one block, then to reduce the time cost of all lines of the whole blob processing for accelerating. However, it is still up to your network bandwidth if the program run locally. Considering for the order of results of all threads, just need to combine each result with its block id to follow the block list order.

A more complex case, if the 3GB file is uploaded to Blob Storage, the first and last line in a block may be broke. So except the first block of a blob, you have to deal with this case to concat the break line in two adjacent blocks via judge whether be exists a \n character at the end of a block.

Hope it helps.


问:
Linux : Can a directory rename be partially executed due to a power/transient mechanical failure in Server/Disk?
C/C++ rename function can be used to rename a directory.
Assume below situation (for Linux)
Directory X has files A, B and C.
X is renamed to Y (using C/C++ rename function). While the operation is in progress Server/Disk's power goes out. Then it is restarted.
Now is there a possibility of few files being in a directory X while others in Y.
e.g.
X : B
Y : A, C</p>

答:
It depends on implementation but for all file systems I know renaming is just replacing a label. So renaming of a directory doesn't differ from file rename operation.
And when you rename a file and turn off power you never end up with two files X and Y each having half of the file content.</p>


问:
PEAR error require_once(Structures/Graph/Node.php): failed to open stream
I'm trying to install PHPUnit using PEAR. Whatever command i run like pear install phpunit/PHPUnit, pear install Structures_Graph, pear upgrade, pear upgrade --force --alldeps... it always ends with

Warning:
  require_once(Structures/Graph/Node.php):
  failed to open stream: No such  file
  or directory in
  PEAR\Structures\Graph.php on line 37
  PHP Warning:
  require_once(Structures/Graph/Node.php):
  failed to open stream: No  such file
  or directory in
  C:\wamp\bin\php\php5.3.4\PEAR\PEAR\Structures\Graph.p
  hp on line 37

Warning:
  require_once(Structures/Graph/Node.php):
  failed to open stream: No such  file
  or directory in
  C:\wamp\bin\php\php5.3.4\PEAR\PEAR\Structures\Graph.php
  on  line 37 PHP Fatal error:
  require_once(): Failed opening
  required 'Structures/Graph/Node .php'
  (include_path='C:\wamp\bin\php\php5.3.4\pear') in C:\wamp\bin\php\php5.3.4
  \PEAR\PEAR\Structures\Graph.php on
  line 37

Fatal error: require_once(): Failed
  opening required
  'Structures/Graph/Node.php'
  (include_path='C:\wamp\bin\php\php5.3.4\pear') in C:\wamp\bin\php\php5.3.4\PEAR
  \PEAR\Structures\Graph.php on line 37

I tried the answer to this question and downloaded and extracted the ZIP to C:\wamp\bin\php\php5.3.4\PEAR\PEAR, but that only replaces the Structures_Graph error I had before with this one.

PEAR is installed with go-pear.bat on a wamp installation on Windows 7, PHP 5.3.4.

What more can I try to make this work?

Update: It should be said that I've tried to change the include_path reported in the error above, to no success. Tried to alter both php.ini and pear.bat.

答:
Set your include path to

```<code>C:\wamp\bin\php\php5.3.4\PEAR\PEAR\
</code>```

Better start all over because that setup seems to be fckd up.

Body:
Set your include path to

C:\wamp\bin\php\php5.3.4\PEAR\PEAR\

Better start all over because that setup seems to be fckd up.