问:
Shadows built-in names "function" and "module" with PyCharm
I have the following Python code:

```<code>function = "Developer"
module = "something"
print(function + " on " + module)
</code>```

With PyCharm 2017, I have a bubble which says “Shadows built-in names "function"/"module" with PyCharm”.

I’m surprised because "function" and "module" are not built-in names. They are not keywords either:

```<code>import __builtin__
import keyword

assert "function" not in dir(__builtin__)  # -> OK
assert "module" not in dir(__builtin__)    # -> OK
assert "function" not in keyword.kwlist    # -> OK
assert "module" not in keyword.kwlist      # -> OK
</code>```

What’s wrong?

I’m using CPython 2.7, but have the same trouble with 3.5 & 3.6.

EDIT:

__builtin__ is now builtins in Python 3.

答: Per PY-8672, since March 2014 there is an ability to ignore certain names with this inspection. Open Settings, search "Shadowing built-ins", click on the inspection name, and use the Options section to add names the inspection should whitelist.</p>

Body:
I have the following Python code:

function = "Developer"
module = "something"
print(function + " on " + module)

With PyCharm 2017, I have a bubble which says “Shadows built-in names "function"/"module" with PyCharm”.

I’m surprised because "function" and "module" are not built-in names. They are not keywords either:

import __builtin__
import keyword

assert "function" not in dir(__builtin__)  # -> OK
assert "module" not in dir(__builtin__)    # -> OK
assert "function" not in keyword.kwlist    # -> OK
assert "module" not in keyword.kwlist      # -> OK

What’s wrong?

I’m using CPython 2.7, but have the same trouble with 3.5 & 3.6.

EDIT:

__builtin__ is now builtins in Python 3.


来源: stackexchange

问:
I am loading image to tab3 but when sliding my tab recycle view items increased when I come back to first tab
I have also try to change setHasFixsize(true) but it is not working
problem is when I am com to my own tab then item of tab is increase double times
triple times etc
There is activity that content fragment mtabfragment I have create three fragment java file to three tab layout and connect with these three activity

```<code>`public class NewsFeeds extends Fragment {

DatabaseReference databaseReference;
private LinearLayoutManager layoutManager;

RecyclerView recyclerView;

RecyclerView.Adapter adapter ;

ProgressDialog progressDialog;

List<ImageUploadInfo> list = new ArrayList<>();

Context context,contextpuja ;
GridView gridViewPuja,gridViewAll,gridViewC;
View view;

public NewsFeeds() {

}

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

    context = getActivity();

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

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    final FragmentActivity fragmentActivity = getActivity();
    layoutManager = new LinearLayoutManager(fragmentActivity);

    recyclerView =  view.findViewById(R.id.recyclerView);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    progressDialog = new ProgressDialog(getActivity());

    progressDialog.setMessage("Loading Images From Firebase.");

     progressDialog.show();

    databaseReference = FirebaseDatabase.getInstance().getReference(Main2Activity.FB_Database_Path);

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                ImageUploadInfo imageUploadInfo = postSnapshot.getValue(ImageUploadInfo.class);

                list.add(imageUploadInfo);
            }

            adapter = new RecyclerViewAdapter(getContext(), list);

            recyclerView.setAdapter(adapter);
            recyclerView.setHasFixedSize(true);

            progressDialog.dismiss();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

                          progressDialog.dismiss();

        }
    });

}
</code>```

}

答:
I have just add code by the use of code list.clear() before return view and get perfect output

```<code>public class NewsFeeds extends Fragment {

DatabaseReference databaseReference;
private LinearLayoutManager layoutManager;

RecyclerView recyclerView;

RecyclerView.Adapter adapter ;

ProgressDialog progressDialog;

List<ImageUploadInfo> list = new ArrayList<>();

Context context,contextpuja ;
GridView gridViewPuja,gridViewAll,gridViewC;
View view;

public NewsFeeds() {

}

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

    context = getActivity();

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

    //-----list.clear()-----use to fix bug ----------------
    list.clear();
    return view;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have also try to change setHasFixsize(true) but it is not working
problem is when I am com to my own tab then item of tab is increase double times
triple times etc
There is activity that content fragment mtabfragment I have create three fragment java file to three tab layout and connect with these three activity

`public class NewsFeeds extends Fragment {

DatabaseReference databaseReference;
private LinearLayoutManager layoutManager;

RecyclerView recyclerView;

RecyclerView.Adapter adapter ;

ProgressDialog progressDialog;

List<ImageUploadInfo> list = new ArrayList<>();

Context context,contextpuja ;
GridView gridViewPuja,gridViewAll,gridViewC;
View view;

public NewsFeeds() {

}

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

    context = getActivity();

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

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    final FragmentActivity fragmentActivity = getActivity();
    layoutManager = new LinearLayoutManager(fragmentActivity);

    recyclerView =  view.findViewById(R.id.recyclerView);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    progressDialog = new ProgressDialog(getActivity());

    progressDialog.setMessage("Loading Images From Firebase.");

     progressDialog.show();

    databaseReference = FirebaseDatabase.getInstance().getReference(Main2Activity.FB_Database_Path);

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                ImageUploadInfo imageUploadInfo = postSnapshot.getValue(ImageUploadInfo.class);

                list.add(imageUploadInfo);
            }

            adapter = new RecyclerViewAdapter(getContext(), list);

            recyclerView.setAdapter(adapter);
            recyclerView.setHasFixedSize(true);

            progressDialog.dismiss();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

                          progressDialog.dismiss();

        }
    });

}

}

Body:
I have just add code by the use of code list.clear() before return view and get perfect output

public class NewsFeeds extends Fragment {

DatabaseReference databaseReference;
private LinearLayoutManager layoutManager;

RecyclerView recyclerView;

RecyclerView.Adapter adapter ;

ProgressDialog progressDialog;

List<ImageUploadInfo> list = new ArrayList<>();

Context context,contextpuja ;
GridView gridViewPuja,gridViewAll,gridViewC;
View view;

public NewsFeeds() {

}

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

    context = getActivity();

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

    //-----list.clear()-----use to fix bug ----------------
    list.clear();
    return view;
}


问:
return null notificationId in NotificationHub
I use Microsoft.Azure.NotificationHubs in VS2017. when I try to send a notification by SendAppleNativeNotificationAsync method this doesn't return notificationId, this is null.  I have the Standard pricing for Notification Hub

enter image description here

答: Are you using Test Send by any chance? Please note that NotificationId is returned NULL while doing a test send. This is because you can get the result of Send operation in the output of Send* method itself. NotificationOutcome.Results property will have list of registrations this Send* was sent to. (Note that test sends are only meant for troubleshooting purposes and they target a maximum of 10 devices. Read through the above post for more info).  </p>


问:
Tell a web programmer how to write a very very simple GUI program
I am a web developer and server systems engineer.

But now my brother asked me if I could provide a little program for a very trivial demand.

Its just a form where the user can rate for factors on a scale from 1 to 7.

Based on these 4 values a final value from 1-10 is calculated. And this is done very easily with simple formulas like:

```<code>if(a>5 || b>3) { final = 4; }
else if ...
</code>```

(just some basic formulas that can be expressed using logical operators and comparisions)

I told him he could just do this in excel or google docs, or a simple .html file with embedded javascript in it.

But this is a research project with a pharma company behind, and they may be willing to pay a few bucks for a little program.

There should be the option to later extend it with a 2nd survey where the result of the 1st is taken into account as a factor.

This is a very trivial program and the logic is safe and sound, but I have never done any gui programming.

I have done a lot in java, but only command line stuff, and php.

It should run easily on every system.

So I thought about using PHP-GTK, where it looks like you can compile binary executables that need no external interpreter.

But Java should also be fine.

Any recommendations?

I am also willing to look into other languages, it shouldn't be too hard.

So

What language/environment is the easiest way to do very, very simple Gui programs that run on every system?

答: I would recommend using Adobe AIR (http://www.adobe.com/products/air/) and It is fairly straightforward to develop (since you know Java) and will have all the nice stuff you are looking for. :) </p>

ContentLicense: CC BY-SA 2.5

Body:
I am a web developer and server systems engineer.

But now my brother asked me if I could provide a little program for a very trivial demand.

Its just a form where the user can rate for factors on a scale from 1 to 7.

Based on these 4 values a final value from 1-10 is calculated. And this is done very easily with simple formulas like:

if(a>5 || b>3) { final = 4; }
else if ...

(just some basic formulas that can be expressed using logical operators and comparisions)

I told him he could just do this in excel or google docs, or a simple .html file with embedded javascript in it.

But this is a research project with a pharma company behind, and they may be willing to pay a few bucks for a little program.

There should be the option to later extend it with a 2nd survey where the result of the 1st is taken into account as a factor.

This is a very trivial program and the logic is safe and sound, but I have never done any gui programming.

I have done a lot in java, but only command line stuff, and php.

It should run easily on every system.

So I thought about using PHP-GTK, where it looks like you can compile binary executables that need no external interpreter.

But Java should also be fine.

Any recommendations?

I am also willing to look into other languages, it shouldn't be too hard.

So

What language/environment is the easiest way to do very, very simple Gui programs that run on every system?


问:
Unable to center google maps iframe into a php section file of wordpress theme
I inserted a google maps iframe into a php section file of wordpress theme.
Tried many ways to center it. Nothing worked so far!
Can you help?

Here's how it looks: http://prntscr.com/hjyd4s

```<code>     <div class="home-section-content

<!--
<div id="google-maps">  <!-- <div style=" margin:auto; ">
<style type="text/css">
#google-maps  {
mar gin: auto;
width: 125%;
border: 3px solid #73AD21;
padding: 10px;
margin-left: auto ;
margin-right: auto ;
}
</style>
-->
            <br><br><br>

    <iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2989.608839663209!2d-8.163739!3d41.4693985!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0xd24e87671374bf1%3A0x9a3a665c9521b5a4!2sR.+de+S%C3%A3o+Mateus+193%2C+4820-500+Ascens%C3%A3o!5e0!3m2!1sen!2spt!4v1511832699133"
     width="1400" height="800" ali gn="center" frameborder="0" style="border:0" allowfullscreen></iframe>

        </div>
</code>```

I commented out that piece of code you see, as it did not work. But you might point why?

答:
If you put the id="google-maps" on the iframe itself, it's easier to center.

```<code>    <style type="text/css">
    #google-maps  {
      display: block;
      margin: 10px auto;
      border: 0
    }
    </style>

    <div>
        <iframe id="google-maps" src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2989.608839663209!2d-8.163739!3d41.4693985!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0xd24e87671374bf1%3A0x9a3a665c9521b5a4!2sR.+de+S%C3%A3o+Mateus+193%2C+4820-500+Ascens%C3%A3o!5e0!3m2!1sen!2spt!4v1511832699133"
         width="1400" height="800" frameborder="0" allowfullscreen></iframe>
    </div>
</code>```

Body:
I inserted a google maps iframe into a php section file of wordpress theme.
Tried many ways to center it. Nothing worked so far!
Can you help?

Here's how it looks: http://prntscr.com/hjyd4s

     <div class="home-section-content

I commented out that piece of code you see, as it did not work. But you might point why?

Body:
If you put the id="google-maps" on the iframe itself, it's easier to center.

    <style type="text/css">
    #google-maps  {
      display: block;
      margin: 10px auto;
      border: 0
    }
    </style>

    <div>
        <iframe id="google-maps" src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2989.608839663209!2d-8.163739!3d41.4693985!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0xd24e87671374bf1%3A0x9a3a665c9521b5a4!2sR.+de+S%C3%A3o+Mateus+193%2C+4820-500+Ascens%C3%A3o!5e0!3m2!1sen!2spt!4v1511832699133"
         width="1400" height="800" frameborder="0" allowfullscreen></iframe>
    </div>


问:
Pointer is null after a function
I am working with linked list in C, but I think didn't understant very well the use of pointers.

I have a structure for my linked list. I initialize the first element to NULL. I send this pointer to a function to create (with malloc) a new element of the list. But after the call of the function my element is still NULL. I don't understand. It is surely a stupid error but I need some help..

```<code>typedef struct Goto Goto;
struct Goto
{
    int index;
    Goto *next;
};

//my code
Goto* gotoList = NULL;
addLabel(gotoList, index);
// Here : gotoList is NULL

void addLabel(Goto* gotoList, int value) {
    if (gotoList == NULL) {
        Goto* gotoLabel = malloc(sizeof(*gotoList));
        gotoLabel->index = value;
        gotoLabel->next = NULL;
        gotoList = gotoLabel;
    }
    else {
        Goto* gotoLabel = gotoList;
        Goto* newLabel = malloc(sizeof(*newLabel));
        newLabel->next = NULL;
        newLabel->index = value;
        while (gotoLabel->next != NULL) {
            gotoLabel = gotoLabel->next;
        }
        gotoLabel->next = newLabel;
    }
// Here : gotoList is not NULL
</code>```

}

Thanks for helping me

答:
Well to make change either you have to pass the address of the variable from the caller function or return from the callee function the address of the allocated memory and assign it to respective variable.

Here you do neither of it so you don't get to retain the change.

By passing the adress of the variable you can do it like this:(The other can be done easily if you understand this one fully).

```<code>void addLabel(Goto** gotoList, int value) {
    if (*gotoList == NULL) {
        Goto* gotoLabel = malloc(sizeof(*gotoLabel ));
        gotoLabel->index = value;
        gotoLabel->next = NULL;
        *gotoList = gotoLabel;
    }
    else {
        Goto* gotoLabel = *gotoList;
        Goto* newLabel = malloc(sizeof(*newLabel));
        newLabel->next = NULL;
        newLabel->index = value;
        while (gotoLabel->next != NULL) {
            gotoLabel = gotoLabel->next;
        }
        gotoLabel->next = newLabel;
    }
}
</code>```

Here what we did is simply passed the address of the variable. You will call the function like this

```<code>addLabel(&listhead,val);
</code>```

One thing, you have a bad choice in selecting the names of the variables. Goto is the last choice of variable name. In C goto is a keyword, naming a variable on some variation of it is not only misleading but also erroneous in meaning too.

Title: Pointer is null after a function

Body:
I am working with linked list in C, but I think didn't understant very well the use of pointers.

I have a structure for my linked list. I initialize the first element to NULL. I send this pointer to a function to create (with malloc) a new element of the list. But after the call of the function my element is still NULL. I don't understand. It is surely a stupid error but I need some help..

typedef struct Goto Goto;
struct Goto
{
    int index;
    Goto *next;
};

//my code
Goto* gotoList = NULL;
addLabel(gotoList, index);
// Here : gotoList is NULL

void addLabel(Goto* gotoList, int value) {
    if (gotoList == NULL) {
        Goto* gotoLabel = malloc(sizeof(*gotoList));
        gotoLabel->index = value;
        gotoLabel->next = NULL;
        gotoList = gotoLabel;
    }
    else {
        Goto* gotoLabel = gotoList;
        Goto* newLabel = malloc(sizeof(*newLabel));
        newLabel->next = NULL;
        newLabel->index = value;
        while (gotoLabel->next != NULL) {
            gotoLabel = gotoLabel->next;
        }
        gotoLabel->next = newLabel;
    }
// Here : gotoList is not NULL

}

Thanks for helping me

Body:
Well to make change either you have to pass the address of the variable from the caller function or return from the callee function the address of the allocated memory and assign it to respective variable.

Here you do neither of it so you don't get to retain the change.

By passing the adress of the variable you can do it like this:(The other can be done easily if you understand this one fully).

void addLabel(Goto** gotoList, int value) {
    if (*gotoList == NULL) {
        Goto* gotoLabel = malloc(sizeof(*gotoLabel ));
        gotoLabel->index = value;
        gotoLabel->next = NULL;
        *gotoList = gotoLabel;
    }
    else {
        Goto* gotoLabel = *gotoList;
        Goto* newLabel = malloc(sizeof(*newLabel));
        newLabel->next = NULL;
        newLabel->index = value;
        while (gotoLabel->next != NULL) {
            gotoLabel = gotoLabel->next;
        }
        gotoLabel->next = newLabel;
    }
}

Here what we did is simply passed the address of the variable. You will call the function like this

addLabel(&listhead,val);

One thing, you have a bad choice in selecting the names of the variables. Goto is the last choice of variable name. In C goto is a keyword, naming a variable on some variation of it is not only misleading but also erroneous in meaning too.


问:
Where can i save information to be displayed by my Android App
where should i save the information i want my app to display When selected,with out using a server because i want my content(includes a combination of text and images) to be available offline and which format can i use to this in Android?</p>

答: You can save it into a SQLite database file, doing it directly as taught by many tutorials, or using the Room Persistence Library, where you can find a nice and easy tutorial here https://developer.android.com/training/data-storage/room/index.html</p>


问:
ProGuard configuration for Guava with obfuscation and optimization
Looking for a ProGuard configuration for Guava that will obfuscate and optimize, as the default one that is provided on the website does not.

Not only that I cannot get it to export my apk, I keep getting:

```<code>Warning: com.google.common.collect.MinMaxPriorityQueue:
    can't find referenced field 'int UNSET_EXPECTED_SIZE' in class
    com.google.common.collect.MinMaxPriorityQueue$Builder
You should check if you need to specify additional program jars.
</code>```

答:
I just want to share what is actually working now for my app with the following in build.gradle:

compile 'com.google.guava:guava:23.5-android'

The following is in proguard-project.txt to deal with Guava.  It is essentially the combination of TimTron's answer and develper_7's tip:

```<code>-dontwarn sun.misc.Unsafe
-dontwarn com.google.common.collect.MinMaxPriorityQueue
-dontwarn com.google.common.util.concurrent.FuturesGetChecked**
-dontwarn javax.lang.model.element.Modifier
-dontwarn afu.org.checkerframework.**
-dontwarn org.checkerframework.**
</code>```

Body:
Looking for a ProGuard configuration for Guava that will obfuscate and optimize, as the default one that is provided on the website does not.

Not only that I cannot get it to export my apk, I keep getting:

Warning: com.google.common.collect.MinMaxPriorityQueue:
    can't find referenced field 'int UNSET_EXPECTED_SIZE' in class
    com.google.common.collect.MinMaxPriorityQueue$Builder
You should check if you need to specify additional program jars.

Body:
I just want to share what is actually working now for my app with the following in build.gradle:

compile 'com.google.guava:guava:23.5-android'

The following is in proguard-project.txt to deal with Guava.  It is essentially the combination of TimTron's answer and develper_7's tip:

-dontwarn sun.misc.Unsafe
-dontwarn com.google.common.collect.MinMaxPriorityQueue
-dontwarn com.google.common.util.concurrent.FuturesGetChecked**
-dontwarn javax.lang.model.element.Modifier
-dontwarn afu.org.checkerframework.**
-dontwarn org.checkerframework.**


问:
Android Studio can't find adb
Android Studio can't find adb. There is also no adb file in sdk folder. I use avast, so I remove adb from it's virus chest and add sdk folder to exclusions. When I'm trying to install Android SDK Platform-Tools, it can't get over step stopping adb.

```<code>To install:
- Android SDK Platform-Tools (platform-tools)
Preparing "Install Android SDK Platform-Tools (revision: 27.0.0)".
Downloading https://dl.google.com/android/repository/platform-tools_r27.0.0-windows.zip
Generating patch...
"Install Android SDK Platform-Tools (revision: 27.0.0)" ready.
Finishing "Install Android SDK Platform-Tools (revision: 27.0.0)"
Stopping ADB...
</code>```

答:
If you use free antivirus (like Avast, AVG etc) this happens. These free antiviruses assume adb.exe file as malicious and delete it immediately when Android Studio starts adb server internally. (I would suggest you not to use any free antivirus. If possible use Windows Defender).

So, first restore adb.exe file from antivirus chest. After restoring restart Android Studio by using File -> Invalidate Cache and Restart -> Just Restart

Hope it will be helpful.

Title: Android Studio can't find adb

Body:
Android Studio can't find adb. There is also no adb file in sdk folder. I use avast, so I remove adb from it's virus chest and add sdk folder to exclusions. When I'm trying to install Android SDK Platform-Tools, it can't get over step stopping adb.

To install:
- Android SDK Platform-Tools (platform-tools)
Preparing "Install Android SDK Platform-Tools (revision: 27.0.0)".
Downloading https://dl.google.com/android/repository/platform-tools_r27.0.0-windows.zip
Generating patch...
"Install Android SDK Platform-Tools (revision: 27.0.0)" ready.
Finishing "Install Android SDK Platform-Tools (revision: 27.0.0)"
Stopping ADB...


问:
best way to concatenate scope results
I have two scopes. One that checks if db column is null or empty string and another that checks for the opposite (not null, and not empty string)

```<code>scope :has_something, where('something IS NOT NULL AND something != ""')
scope :has_no_something, where('something IS NULL OR something = ""')
</code>```

I would like to end up with the two results concatenated. ie results that have something followed by results that do not have something

My first attempt was something like this:

```<code>def self.with_something_data_first
  has_something + has_no_something
end
</code>```

This results in:

NoMethodError: undefined method `order' for #

because this method is combined with an order

```<code>Model.with_something_data_first.order(:created_at).reverse_order.limit(20)
</code>```

It would be great if I could could do this in one scope where it returned all records with data then all records with null or empty string. Obviously you can't order by nil but maybe you know of a tricky way to get around this?

答:
```<code>scope :with_something_data_first, -> { order('something IS NULL OR something == ""') }
</code>```

How?

something IS NULL OR something == "" evaluates to 1 when something is null or empty string, and since default order is ASC, all these entries will be shown after records with something IS NULL OR something == "" resulting to 0

Title: best way to concatenate scope results

Body:
I have two scopes. One that checks if db column is null or empty string and another that checks for the opposite (not null, and not empty string)

scope :has_something, where('something IS NOT NULL AND something != ""')
scope :has_no_something, where('something IS NULL OR something = ""')

I would like to end up with the two results concatenated. ie results that have something followed by results that do not have something

My first attempt was something like this:

def self.with_something_data_first
  has_something + has_no_something
end

This results in:

NoMethodError: undefined method `order' for #

because this method is combined with an order

Model.with_something_data_first.order(:created_at).reverse_order.limit(20)

It would be great if I could could do this in one scope where it returned all records with data then all records with null or empty string. Obviously you can't order by nil but maybe you know of a tricky way to get around this?

Body:
scope :with_something_data_first, -> { order('something IS NULL OR something == ""') }

How?

something IS NULL OR something == "" evaluates to 1 when something is null or empty string, and since default order is ASC, all these entries will be shown after records with something IS NULL OR something == "" resulting to 0


问:
How to limit angles in (-180,180) range just like Unity3D inspector
I want to get rotation of Camera gameobject attached to Char gameobject

EDIT: Char rotation, pos, scale is 0,0,0

I have following code: (Script is on the Char gameobject)

```<code>Transform cameraT = transform.Find("Camera").transform;
print(cameraT.localEulerAngles);
</code>```

The problem is that in inspector it shows:

but in debug console:

I want to get rotation from inspector

答:
-45 and 315 are same rotations. Inspector just shows it differently.

I want to get rotation from inspector

use

```<code>angle %=360;
angle= angle>180 ? angle-360 : angle;
</code>```

to limit it from -180 to 180 that's what inspector displays.

Hope this helps

Body:
I want to get rotation of Camera gameobject attached to Char gameobject

EDIT: Char rotation, pos, scale is 0,0,0

I have following code: (Script is on the Char gameobject)

Transform cameraT = transform.Find("Camera").transform;
print(cameraT.localEulerAngles);

The problem is that in inspector it shows:

but in debug console:

I want to get rotation from inspector

Body:
-45 and 315 are same rotations. Inspector just shows it differently.

I want to get rotation from inspector

use

angle %=360;
angle= angle>180 ? angle-360 : angle;

to limit it from -180 to 180 that's what inspector displays.

Hope this helps


问:
Angular2-Not passing data to modal dialog
Plunker:
http://plnkr.co/edit/L6cSKd

For some reason, I can't understand how to pass data to my modal dialog. Also, after looking at the Plunker, if you think there is an easier way to do the modals, please let me know.

Man, this Angular2 stuff is difficult to debug on Plunker, too. Any tips on how to debug it?

If I put a breakpoint on the show function for PrimaryModalComponent, I can see that the count
is getting passed and this.count is also being set. I just can't figure out why it is not getting set when my dialog shows. Could it be that the #primary-modal is in alert.detail?

alert.detail.html

```<code><div class="row" *ngFor="let alert of alerts">
    <div style="padding-left: 25px;" class="alert_links col-sm-12">
        <i class="fa fa-warning fa-red"></i>
        <a href="#" *ngIf="alert.alert_type=='critical'" (click)="criticalmodal.show(alert.count)"
           title="There are {{ alert.count }} {{alert.alert_type}} alerts, click to view details">{{ alert.count }} {{alert.alert_type}} alerts
        </a>
        <a href="#" *ngIf="alert.alert_type=='other'" (click)="criticalmodal.show(alert.count)"
           title="There are {{ alert.count }} {{alert.alert_type}} alerts, click to view details">{{ alert.count }} {{alert.alert_type}} alerts
        </a>

    </div>
</div>
<critical-modal #criticalmodal>
    <div class="app-modal-header">
        There are {{this.count}} Critical Alerts
    </div>
    <div class="app-modal-body">
        Showing Critical Alerts Here!
    </div>
    <div class="app-modal-footer">
        <button type="button" class="btn btn-default" (click)="criticalmodal.hide()">Close</button>
    </div>
</critical-modal>
<primary-modal #primarymodal>
    <div class="app-modal-header">
        There are {{this.count}} Other Alerts
    </div>
    <div class="app-modal-body">
        Showing Other Alerts Here!
    </div>
    <div class="app-modal-footer">
        <button type="button" class="btn btn-default" (click)="primarymodal.hide()">Close</button>
    </div>
</primary-modal>
</code>```

alert-detail.component.ts

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { CriticalModalComponent } from './critical-modal';
import { PimarylModalComponent } from './primary-modal';

@Component({
  selector: 'alert-detail',
  templateUrl: './src/alert.detail.html'
})

export class AlertDetail {
    constructor() {
        this.alerts =
        [
            {
             "alert_type":"critical",
             "count": 3
            },
            {
             "alert_type":"other",
             "count":18
            }
        ];
    };
    };
}
</code>```

primary-modal.ts

```<code>import {Component} from '@angular/core';

@Component({
  selector: 'primary-modal',
  template: `
  <div (click)="onContainerClicked($event)" class="modal fade" tabindex="-1" [ngClass]="{'in': visibleAnimate}"
       [ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header modal-primary">
          <ng-content select=".app-modal-header"></ng-content>
        </div>
        <div class="modal-body">
          <ng-content select=".app-modal-body"></ng-content>
        </div>
        <div class="modal-footer">
          <ng-content select=".app-modal-footer"></ng-content>
        </div>
      </div>
    </div>
  </div>
  `,
  styles: [`
    .modal {
      background: rgba(0,0,0,0.6);
    }
  `]
})
export class PrimaryModalComponent {

  public visible = false;
  private visibleAnimate = false;

  constructor(){}

  public show(count): void {
    this.visible = true;
    this.count = count;
    setTimeout(() => this.visibleAnimate = true, 100);
  }

  public hide(): void {
    this.visibleAnimate = false;
    setTimeout(() => this.visible = false, 300);
  }

  public onContainerClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('modal')) {
      this.hide();
    }
  }
}
</code>```

critical-modal.ts

```<code>import {Component} from '@angular/core';

@Component({
  selector: 'critical-modal',
  template: `
  <div (click)="onContainerClicked($event)" class="modal fade" tabindex="-1" [ngClass]="{'in': visibleAnimate}"
       [ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header modal-critical">
          <ng-content select=".app-modal-header"></ng-content>
        </div>
        <div class="modal-body">
          <ng-content select=".app-modal-body"></ng-content>
        </div>
        <div class="modal-footer">
          <ng-content select=".app-modal-footer"></ng-content>
        </div>
      </div>
    </div>
  </div>
  `,
  styles: [`
    .modal {
      background: rgba(0,0,0,0.6);
    }
  `]
})
export class CriticalModalComponent {

  public visible = false;
  private visibleAnimate = false;
  public count = 0;

  constructor(){}

  public show(count): void {
    this.visible = true;
    this.count = count;
    setTimeout(() => this.visibleAnimate = true, 100);
  }

  public hide(): void {
    this.visibleAnimate = false;
    setTimeout(() => this.visible = false, 300);
  }

  public onContainerClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('modal')) {
      this.hide();
    }
  }
}
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BootstrapModalModule, BuiltInOptions } from 'ngx-bootstrap-modal';
import { AppComponent } from './app.component';
import { AlertDetail } from './alert.detail.component';
import { CriticalModalComponent } from './critical-modal';
import { PimarylModalComponent } from './primary-modal';

@NgModule({
    declarations: [
        AppComponent,
        AlertDetail,
        CriticalModalComponent,
        PrimaryModalComponent
    ],
    imports: [BrowserModule],
    bootstrap: [
        AppComponent,
        AlertDetail
    ]
})

export class AppModule { }
</code>```

答:
The issue is you are not passing data to child component

In alert.detail.html

```<code><primary-modal #primarymodal [count]="count">
    <div class="app-modal-header">
        There are {{this.count}} Other Alerts
    </div>
</primary-modal>
</code>```

```<code>   <a *ngIf="alert.alert_type=='other'" href="#" (click)="count = alert.count; primarymodal.show(alert.count)"
       title="There are {{ alert.count }} {{alert.alert_type}} alerts, click to view details">
       {{ alert.count }} {{alert.alert_type}} alerts
    </a>
</code>```

In alert.detail.component.ts
Declare the variable  public count;

In primary-modal.ts

```<code>import {Component, Input} from '@angular/core';
export class PrimaryModalComponent {
  @Input() count;
</code>```

plunker: http://plnkr.co/edit/YfY7AA95Y3wTWhIJpFOs?p=preview -->  other alerts
Hope it helps!!

Body:
Plunker:
http://plnkr.co/edit/L6cSKd

For some reason, I can't understand how to pass data to my modal dialog. Also, after looking at the Plunker, if you think there is an easier way to do the modals, please let me know.

Man, this Angular2 stuff is difficult to debug on Plunker, too. Any tips on how to debug it?

If I put a breakpoint on the show function for PrimaryModalComponent, I can see that the count
is getting passed and this.count is also being set. I just can't figure out why it is not getting set when my dialog shows. Could it be that the #primary-modal is in alert.detail?

alert.detail.html

        {{ alert.count }} {{alert.alert_type}} alerts

        {{ alert.count }} {{alert.alert_type}} alerts

<critical-modal #criticalmodal>

        There are {{this.count}} Critical Alerts

        Showing Critical Alerts Here!

        <button type="button" class="btn btn-default" (click)="criticalmodal.hide()">Close</button>

</critical-modal>
<primary-modal #primarymodal>

        There are {{this.count}} Other Alerts

        Showing Other Alerts Here!

        <button type="button" class="btn btn-default" (click)="primarymodal.hide()">Close</button>

</primary-modal>

alert-detail.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { CriticalModalComponent } from './critical-modal';
import { PimarylModalComponent } from './primary-modal';

@Component({
  selector: 'alert-detail',
  templateUrl: './src/alert.detail.html'
})

export class AlertDetail {
    constructor() {
        this.alerts =
        [
            {
             "alert_type":"critical",
             "count": 3
            },
            {
             "alert_type":"other",
             "count":18
            }
        ];
    };
    };
}

primary-modal.ts

import {Component} from '@angular/core';

@Component({
  selector: 'primary-modal',
  template: `

          <ng-content select=".app-modal-header"></ng-content>

          <ng-content select=".app-modal-body"></ng-content>

          <ng-content select=".app-modal-footer"></ng-content>

  `,
  styles: [`
    .modal {
      background: rgba(0,0,0,0.6);
    }
  `]
})
export class PrimaryModalComponent {

  public visible = false;
  private visibleAnimate = false;

  constructor(){}

  public show(count): void {
    this.visible = true;
    this.count = count;
    setTimeout(() => this.visibleAnimate = true, 100);
  }

  public hide(): void {
    this.visibleAnimate = false;
    setTimeout(() => this.visible = false, 300);
  }

  public onContainerClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('modal')) {
      this.hide();
    }
  }
}

critical-modal.ts

import {Component} from '@angular/core';

@Component({
  selector: 'critical-modal',
  template: `

          <ng-content select=".app-modal-header"></ng-content>

          <ng-content select=".app-modal-body"></ng-content>

          <ng-content select=".app-modal-footer"></ng-content>

  `,
  styles: [`
    .modal {
      background: rgba(0,0,0,0.6);
    }
  `]
})
export class CriticalModalComponent {

  public visible = false;
  private visibleAnimate = false;
  public count = 0;

  constructor(){}

  public show(count): void {
    this.visible = true;
    this.count = count;
    setTimeout(() => this.visibleAnimate = true, 100);
  }

  public hide(): void {
    this.visibleAnimate = false;
    setTimeout(() => this.visible = false, 300);
  }

  public onContainerClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('modal')) {
      this.hide();
    }
  }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BootstrapModalModule, BuiltInOptions } from 'ngx-bootstrap-modal';
import { AppComponent } from './app.component';
import { AlertDetail } from './alert.detail.component';
import { CriticalModalComponent } from './critical-modal';
import { PimarylModalComponent } from './primary-modal';

@NgModule({
    declarations: [
        AppComponent,
        AlertDetail,
        CriticalModalComponent,
        PrimaryModalComponent
    ],
    imports: [BrowserModule],
    bootstrap: [
        AppComponent,
        AlertDetail
    ]
})

export class AppModule { }

Body:
The issue is you are not passing data to child component

In alert.detail.html

<primary-modal #primarymodal [count]="count">
    <div class="app-modal-header">
        There are {{this.count}} Other Alerts
    </div>
</primary-modal>

   <a *ngIf="alert.alert_type=='other'" href="#" (click)="count = alert.count; primarymodal.show(alert.count)"
       title="There are {{ alert.count }} {{alert.alert_type}} alerts, click to view details">
       {{ alert.count }} {{alert.alert_type}} alerts
    </a>

In alert.detail.component.ts
Declare the variable  public count;

In primary-modal.ts

import {Component, Input} from '@angular/core';
export class PrimaryModalComponent {
  @Input() count;

plunker: http://plnkr.co/edit/YfY7AA95Y3wTWhIJpFOs?p=preview -->  other alerts
Hope it helps!!


问:
determing calling object when working with dlopen() objects
I'm writing a (C) program which utilizes a plugin system via dlopen(). The stumbling block I'm running across is that the main program exports a few functions which really need to know the plugin that called them (mostly record keeping, and so a plugin can be unloaded properly as they add things like function pointers to the main program).

I cant seem to find a clean way to do this. The options I've come up with so far:

require the plugin to provide its name, or some data I give it on load as an argument to the functions.

I dont like this option because not all functions care who they were called from, so it makes it inconsistent and messy. Plus I would like to make it as difficult as possible for the plugin to lie about who it is

Use backtrace() to determine the object name of the previous function.

This just seems fairly ugly and non-portable.

Require the plugin to put a file-level struct (or other variable) containing its name (lets call it 'plugin_info' for discussion). Then use dlsym() when loading the plugin to look up the variable and index it (like in a hash) by its name. Then put in #define macros which the plugins use to call the functions and have the macro add &plugin_info as an argument.

This is what I'm using now but it seems hackish. For one you have to have the macro pass '&plugin_info', if you just pass 'plugin_info' then it pulls the 'plugin_info' from the main program, not the plugin. Referencing it by address seems to make it so that its compiled with the correct one, and that it doesnt get relocated. That makes me dislike this option as that seems like its undefined behavior, however it does work. Also the macros can make it a bit confusing when the plugin developer has a problem with the function call (passing wrong argument type or whatnot).

If there's any other ideas or techniques, I would love to love to know.

答:
You've invited the plugin into your address space, so it can lie, overwrite memory belonging to the caller, or rm -rf ~ if it likes. If this is a problem, you need to sandbox it in a separate process without privileges.

Indeed this is horribly non-portable.

This is generally the right idea, but you've botched it and made it ugly. Add static to plugin_info's definition and you'll have perfectly well-defined behavior and none of the hackery.


问:
Editing Log4Net messages before they reach the appenders
I have a security tool that sends users their new password through email. The production email module (that I don’t own and don’t want to change) will log the entire html email message body using Log4Net when the threshold is VERBOSE. Since the email contains a domain user’s password in clear text, I would like to remove the password from the log messages before it reaches the appenders.

Is there a way for me to temporary insert an object into the Log4Net stack that would allow me to search the LoggingEvent message and alter it to mask out any passwords that I find? I’d like to insert the object, call the email module, and then remove the object.

答:
Another kind of solution is to intercept the LoggingEvent before reaching any appender directly from the Logger. One prerequisite is to be able to modify the Root Hierarchy before creating any Logger.

In the sample below, we just recreate a new LoggingEvent, but it's not necessary if you care about intensive memory copy, with reflexion you can access the underlying LoggingEventData(is struct) and set new values to the fields directly.

You just need to call InterceptLoggerFactory.Apply() before any LogManager.GetLogger().

```<code>public class InterceptLoggerFactory : ILoggerFactory
{
    public static void Apply() => Apply((Hierarchy)LogManager.GetRepository());
    public static void Apply(Hierarchy h) => h.LoggerFactory = new InterceptLoggerFactory();

    public Logger CreateLogger(ILoggerRepository repository, string name)
    {
        if (name == null) return new InterceptRootLogger(repository.LevelMap.LookupWithDefault(Level.Debug));
        return new InterceptLogger(name);
    }

    class InterceptLogger : Logger
    {
        public InterceptLogger(string name) : base(name)
        {
        }

        protected override void CallAppenders(LoggingEvent loggingEvent)
        {
            // Implement interception of property on loggingEvent before any call to any appender (execution is sync).
            /*
             * var loggingEventData = loggingEvent.GetLoggingEventData();
             * loggingEventData.Message = [EncryptMessage](loggingEventData.Message);
             * var newLoggingEvent = new LoggingEvent(loggingEventData);
             * base.CallAppenders(newLoggingEvent);
             * */
            base.CallAppenders(loggingEvent);
        }
    }

    class InterceptRootLogger : RootLogger
    {
        public InterceptRootLogger(Level level) : base(level)
        {
        }

        protected override void CallAppenders(LoggingEvent loggingEvent)
        {
            // Implement interception of property on loggingEvent before any call to any appender (execution is sync).
            base.CallAppenders(loggingEvent);
        }
    }
}
</code>```

Body:
Another kind of solution is to intercept the LoggingEvent before reaching any appender directly from the Logger. One prerequisite is to be able to modify the Root Hierarchy before creating any Logger.

In the sample below, we just recreate a new LoggingEvent, but it's not necessary if you care about intensive memory copy, with reflexion you can access the underlying LoggingEventData(is struct) and set new values to the fields directly.

You just need to call InterceptLoggerFactory.Apply() before any LogManager.GetLogger().

public class InterceptLoggerFactory : ILoggerFactory
{
    public static void Apply() => Apply((Hierarchy)LogManager.GetRepository());
    public static void Apply(Hierarchy h) => h.LoggerFactory = new InterceptLoggerFactory();

    public Logger CreateLogger(ILoggerRepository repository, string name)
    {
        if (name == null) return new InterceptRootLogger(repository.LevelMap.LookupWithDefault(Level.Debug));
        return new InterceptLogger(name);
    }

    class InterceptLogger : Logger
    {
        public InterceptLogger(string name) : base(name)
        {
        }

        protected override void CallAppenders(LoggingEvent loggingEvent)
        {
            // Implement interception of property on loggingEvent before any call to any appender (execution is sync).
            /*
             * var loggingEventData = loggingEvent.GetLoggingEventData();
             * loggingEventData.Message = [EncryptMessage](loggingEventData.Message);
             * var newLoggingEvent = new LoggingEvent(loggingEventData);
             * base.CallAppenders(newLoggingEvent);
             * */
            base.CallAppenders(loggingEvent);
        }
    }

    class InterceptRootLogger : RootLogger
    {
        public InterceptRootLogger(Level level) : base(level)
        {
        }

        protected override void CallAppenders(LoggingEvent loggingEvent)
        {
            // Implement interception of property on loggingEvent before any call to any appender (execution is sync).
            base.CallAppenders(loggingEvent);
        }
    }
}


问:
How to pop sections of pandas dataframe based on row values

I have a large spreadsheet of over 3 million individual mammals (1 individual per row). I am trying to group these individuals by species so that I can perform separate analyses on each species represented.

I am currently using the following line to generate separate dataframes for each species which I can the analyze.

```<code>speciesFrames = [mammals.loc[mammals.scientificname == species] for species in speciesList]
</code>```

This process understandably takes a fair bit of time. I'm wondering if this can be sped up by discarding the sections of the mammals dataframe that I've already duplicated in speciesFrames? If so, how can I accomplish this?

I've trying variations of the following line, but each results in a separate error.

speciesFrames = [mammals.pop(mammals.scientificname == species) for species in speciesList]

答:
You can try groupby and you do not need create the speciesList here.

```<code>speciesFrames =[x for _,x in mammals.groupby('scientificname')]
</code>```

Body:
I have a large spreadsheet of over 3 million individual mammals (1 individual per row). I am trying to group these individuals by species so that I can perform separate analyses on each species represented.

I am currently using the following line to generate separate dataframes for each species which I can the analyze.

speciesFrames = [mammals.loc[mammals.scientificname == species] for species in speciesList]

This process understandably takes a fair bit of time. I'm wondering if this can be sped up by discarding the sections of the mammals dataframe that I've already duplicated in speciesFrames? If so, how can I accomplish this?

I've trying variations of the following line, but each results in a separate error.

speciesFrames = [mammals.pop(mammals.scientificname == species) for species in speciesList]

Body:
You can try groupby and you do not need create the speciesList here.

speciesFrames =[x for _,x in mammals.groupby('scientificname')]


问:
maped types: set key as an object
I am still trying to get my head around maped types, so what I am trying to achieve is a config of items that looks like this:

```<code>let config = {
    connA: {
      host: 'abc123',
      user: 'abc123',
      password: 'abc123',
      database: 'abc123',
    },
    connB: {
      host: 'abc123',
      user: 'abc123',
      password: 'abc123',
      database: 'abc123',
    }
}
</code>```

I would like to setup a type for the keys connA, connB, and so on, where those could be anything.

```<code>export interface DatabaseConnection {
  host: string
  user: string
  password: string
  database: string
}

export type DatabaseConnections<T> = {
  [P in keyof T]: T[P]
}
</code>```

So, when I use it, it would be something like this:

```<code>public static connect(config: DatabaseConnections<DatabaseConnection>) {
for (let db in config) {
  db.host
}
</code>```

When I do this, it says that db is a string, and it should be an object (connA or connB in this example)

答:
From what I understand you are not looking for mapped types. You are looking for an index signature</p>

```<code>export type DatabaseConnections<T> = {
  [name: string]: T
}

public static connect(config: DatabaseConnections<DatabaseConnection>) {
   for (let db in config) {
      config[db] // this will be of type T
   }
}
</code>```

Title: maped types: set key as an object

Body:
I am still trying to get my head around maped types, so what I am trying to achieve is a config of items that looks like this:

let config = {
    connA: {
      host: 'abc123',
      user: 'abc123',
      password: 'abc123',
      database: 'abc123',
    },
    connB: {
      host: 'abc123',
      user: 'abc123',
      password: 'abc123',
      database: 'abc123',
    }
}

I would like to setup a type for the keys connA, connB, and so on, where those could be anything.

export interface DatabaseConnection {
  host: string
  user: string
  password: string
  database: string
}

export type DatabaseConnections<T> = {
  [P in keyof T]: T[P]
}

So, when I use it, it would be something like this:

public static connect(config: DatabaseConnections<DatabaseConnection>) {
for (let db in config) {
  db.host
}

When I do this, it says that db is a string, and it should be an object (connA or connB in this example)

Body:
From what I understand you are not looking for mapped types. You are looking for an index signature

export type DatabaseConnections<T> = {
  [name: string]: T
}

public static connect(config: DatabaseConnections<DatabaseConnection>) {
   for (let db in config) {
      config[db] // this will be of type T
   }
}


问:
search in data grid view by text box, C#
```<code>private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
    (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("START_DATE LIKE '%{0}%'", dateTimePicker1.Value.ToString("yyyy-MM-dd"));
}
</code>```

it's return error: 'Cannot perform 'Like' operation on System.DateTime and System.String.', pls help.

答:
```<code>(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("START_DATE = '{0}'", dateTimePicker1.Value.ToString("yyyy-MM-dd"));
</code>```

Or Column name in place of "START_DATE"

```<code>string rowFilter = string.Format("[{0}] = '{1}'", columnName, filterValue);
(myDataGridView.DataSource as DataTable).DefaultView.RowFilter = rowFilter;
</code>```

Body:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
    (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("START_DATE LIKE '%{0}%'", dateTimePicker1.Value.ToString("yyyy-MM-dd"));
}

it's return error: 'Cannot perform 'Like' operation on System.DateTime and System.String.', pls help.

Body:
(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("START_DATE = '{0}'", dateTimePicker1.Value.ToString("yyyy-MM-dd"));

Or Column name in place of "START_DATE"

string rowFilter = string.Format("[{0}] = '{1}'", columnName, filterValue);
(myDataGridView.DataSource as DataTable).DefaultView.RowFilter = rowFilter;


问:
QStackedWidget area cleared on ESC in child widget line edit
There are couple of widgets ( all in UI files ) representing pages for stacked widget. One of the contain QLineEdit field.
When stacked widget current page show this widget and line edit have focus, when ESC is pressed whole area is cleared.
All stacked widget pages are defined in UI file.
Any ideas how to prevent area clearing on ESC?

Qt: 5.9.2

答: My mistake. Each stacked widget was derived from QDialog by mistake. And default handler for ESC for QDialog - is close. Changed to QWidget and it is working as expected now.</p>


问:
How does event handlers with arrow functions achieve context binding
I know about the general theory of this binding (function call site what matters, implicit, explicit binding, etc...) and the methods to solving the problem of this binding in React so it always points to what I want this to be (binding in constructor, arrow functions, etc), but I am struggling to get the inner mechanisms.

Take a look at these two pieces of code:

```<code>class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={(e) => this.goToStore(e)}>test</button>
  }
}
</code>```

vs.

```<code>class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={this.goToStore}>test</button>
  }
}
</code>```

What I know is that:

in both versions we end up successfully in the goToStore method, because the this inside the render() method is automatically bound (by React) to the component instance

the first one succeeds because of that,

the second one fails, because class methods in es6 are not bound to the component instance, thus resolving this in the method to undefined

In theory in the first version as far as I understand, the following occurs:

the button click handler is an anonymous arrow function, so whenever I reference this inside of it, it picks up this from the environment (in this case from render())

then it calls the goToStore method, that is a regular function.

because the call seems to fit the rules of implicit binding (object.function()) object will be the context object and in such function calls it will be used as this

so, inside the goToStore method the lexically picked up this (used as a context object) will resolve to the component instance correctly

I feel 3. and 4. is not the case here, because then it would apply to the 2. case:

```<code><button onClick={this.goToStore}>test</button>
</code>```

Also with this the context object.

What is happening exactly in this particular case, step-by-step?

答:
When the render code is executed, this refers to the component class, so it is able to reference the correct function. This means that element.onClick points to the goToStore method.

When that function is called in the browser, it's called from the context of the html element (i.e. element.onClick()). So unless the goToStore method is bound to the context of the component class, it will inherit this from the context of the element.

This answer provides some more relevant information and further reading.

Body:
I know about the general theory of this binding (function call site what matters, implicit, explicit binding, etc...) and the methods to solving the problem of this binding in React so it always points to what I want this to be (binding in constructor, arrow functions, etc), but I am struggling to get the inner mechanisms.

Take a look at these two pieces of code:

class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={(e) => this.goToStore(e)}>test</button>
  }
}

vs.

class demo extends React.component {
  goToStore(event) {
    console.log(this)
  }

  render() {
    <button onClick={this.goToStore}>test</button>
  }
}

What I know is that:

in both versions we end up successfully in the goToStore method, because the this inside the render() method is automatically bound (by React) to the component instance

the first one succeeds because of that,

the second one fails, because class methods in es6 are not bound to the component instance, thus resolving this in the method to undefined

In theory in the first version as far as I understand, the following occurs:

the button click handler is an anonymous arrow function, so whenever I reference this inside of it, it picks up this from the environment (in this case from render())

then it calls the goToStore method, that is a regular function.

because the call seems to fit the rules of implicit binding (object.function()) object will be the context object and in such function calls it will be used as this

so, inside the goToStore method the lexically picked up this (used as a context object) will resolve to the component instance correctly

I feel 3. and 4. is not the case here, because then it would apply to the 2. case:

<button onClick={this.goToStore}>test</button>

Also with this the context object.

What is happening exactly in this particular case, step-by-step?


答: Java can do desktop - use Swing.  NetBeans is supposed to have a pretty good GUI drag & drop capability, but I haven't used it myself.  (I don't do desktop, either.)</p>

Title: Tell a web programmer how to write a very very simple GUI program

Body:
I am a web developer and server systems engineer.

But now my brother asked me if I could provide a little program for a very trivial demand.

Its just a form where the user can rate for factors on a scale from 1 to 7.

Based on these 4 values a final value from 1-10 is calculated. And this is done very easily with simple formulas like:

if(a>5 || b>3) { final = 4; }
else if ...

(just some basic formulas that can be expressed using logical operators and comparisions)

I told him he could just do this in excel or google docs, or a simple .html file with embedded javascript in it.

But this is a research project with a pharma company behind, and they may be willing to pay a few bucks for a little program.

There should be the option to later extend it with a 2nd survey where the result of the 1st is taken into account as a factor.

This is a very trivial program and the logic is safe and sound, but I have never done any gui programming.

I have done a lot in java, but only command line stuff, and php.

It should run easily on every system.

So I thought about using PHP-GTK, where it looks like you can compile binary executables that need no external interpreter.

But Java should also be fine.

Any recommendations?

I am also willing to look into other languages, it shouldn't be too hard.

So

What language/environment is the easiest way to do very, very simple Gui programs that run on every system?


问:
Find directory of subclass before initialization to configure dry-view paths
I'm using dry-views in multiple Rails engines and I have to duplicate the configuration in every subclass.

```<code>class BaseView < Dry::View::Controller
  configure do |c|
    c.paths = [File.join(__dir__, 'templates')]
  end
end

class SubView < BaseView
  configure do |c|
    c.paths = [File.join(__dir__, 'templates')] # todo: remove me
  end
end
</code>```

The reason is, that my views can be deeply nested in a sub folder of app ie.:

```<code>app/
app/foo/index.rb
app/foo/templates/index.html.erb
app/foo/bar/show.rb
app/foo/bar/templates/show.html.erb
</code>```

Additionally the BaseView class does not live in the same gem in most of the cases.

If I delete the configure block from the SubView class, the template is not found anymore. The __dir__ variable contains the directory path of the BaseView class.

I've tried to implement a after initialization method in the base class that has access to the directory of the subclass. But at that point the configuration is not possible anymore due to restrictions in dry-rb configuration. The configuration must happen before initialization.

The only solution I could come up with is to duplicate the configure block in each class, or have a gem/engine specific parent class that configures all possible template paths.

The usual approach of looking for the directory of a certain method that is implemented in each subclass does also not work in this case, since most views don't even define methods.

Is there better ways to access the directory of a given class during the load phase of this class in a method of the parent class?

答:
```<code>class BaseView < Dry::View::Controller
  def self.inherited(child)
    child.class_eval do
      configure do |c|
        c.paths = [File.join(__dir__, 'templates')]
      end
    end
  end
end
</code>```

Callback Class#inherited.

Body:
I'm using dry-views in multiple Rails engines and I have to duplicate the configuration in every subclass.

class BaseView < Dry::View::Controller
  configure do |c|
    c.paths = [File.join(__dir__, 'templates')]
  end
end

class SubView < BaseView
  configure do |c|
    c.paths = [File.join(__dir__, 'templates')] # todo: remove me
  end
end

The reason is, that my views can be deeply nested in a sub folder of app ie.:

app/
app/foo/index.rb
app/foo/templates/index.html.erb
app/foo/bar/show.rb
app/foo/bar/templates/show.html.erb

Additionally the BaseView class does not live in the same gem in most of the cases.

If I delete the configure block from the SubView class, the template is not found anymore. The __dir__ variable contains the directory path of the BaseView class.

I've tried to implement a after initialization method in the base class that has access to the directory of the subclass. But at that point the configuration is not possible anymore due to restrictions in dry-rb configuration. The configuration must happen before initialization.

The only solution I could come up with is to duplicate the configure block in each class, or have a gem/engine specific parent class that configures all possible template paths.

The usual approach of looking for the directory of a certain method that is implemented in each subclass does also not work in this case, since most views don't even define methods.

Is there better ways to access the directory of a given class during the load phase of this class in a method of the parent class?

Body:
class BaseView < Dry::View::Controller
  def self.inherited(child)
    child.class_eval do
      configure do |c|
        c.paths = [File.join(__dir__, 'templates')]
      end
    end
  end
end

Callback Class#inherited.


问:
Sending SMS using Android Studio 3.0
Sending an SMS (not just creating the text and requiring the user to hit send) can't be that difficult, and yet I've spent the past eleven hours reading every stackoverflow entry and failing nonetheless. I'm now wondering if maybe the method has changed recently since none of the examples seem to work. If someone could help me with this, I'd be grateful. This is my first post, so my apologies if I'm not following the conventions of the community.

Here is my AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="joe.sms">

    <uses-permission android:name="android.permission.SEND_SMS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

And here is my MainActivity:

```<code>package.joe.sms;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;

public class MainActivity extends AppCompatActivity {

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

        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage("+1716255xxxx", null, "Test message", null, null);
    }
}
</code>```

Note: I use my full phone number in the actual code.

And here is the result:

error message screen shot

Thanks, in advance, for your assistance.

答:
Implement the code like this,

```<code>  private static final int SEND_SMS_CODE = 23;
</code>```

Checking permission is given, if permission is granted send SMS else asking for the permission.

```<code>private void permissionCheck(){
    if (isSendSmsAllowed()) {
          sendSms();
          return;
      }

    requestSmsSendPermission();}
</code>```

Function to send SMS.

```<code>private void sendSms(){
    SmsManager sms = SmsManager.getDefault();
              ArrayList<String> parts = sms.divideMessage("MESSAGE");
              sms.sendMultipartTextMessage(90******, null, parts, null,
                null);}
</code>```

Requesting permission if not granted.

```<code>//Requesting permission
  private void requestSmsSendPermission() {

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS)) {
      //If the user has denied the permission previously your code will come to this block
      //Here you can explain why you need this permission
      //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.SEND_SMS },
      SEND_SMS_CODE);
  }
</code>```

Hope it may help you.

Title: Sending SMS using Android Studio 3.0

Body:
Sending an SMS (not just creating the text and requiring the user to hit send) can't be that difficult, and yet I've spent the past eleven hours reading every stackoverflow entry and failing nonetheless. I'm now wondering if maybe the method has changed recently since none of the examples seem to work. If someone could help me with this, I'd be grateful. This is my first post, so my apologies if I'm not following the conventions of the community.

Here is my AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="joe.sms">

    <uses-permission android:name="android.permission.SEND_SMS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

And here is my MainActivity:

package.joe.sms;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;

public class MainActivity extends AppCompatActivity {

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

        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage("+1716255xxxx", null, "Test message", null, null);
    }
}

Note: I use my full phone number in the actual code.

And here is the result:

error message screen shot

Thanks, in advance, for your assistance.

Body:
Implement the code like this,

  private static final int SEND_SMS_CODE = 23;

Checking permission is given, if permission is granted send SMS else asking for the permission.

private void permissionCheck(){
    if (isSendSmsAllowed()) {
          sendSms();
          return;
      }

    requestSmsSendPermission();}

Function to send SMS.

private void sendSms(){
    SmsManager sms = SmsManager.getDefault();
              ArrayList<String> parts = sms.divideMessage("MESSAGE");
              sms.sendMultipartTextMessage(90******, null, parts, null,
                null);}

Requesting permission if not granted.

//Requesting permission
  private void requestSmsSendPermission() {

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS)) {
      //If the user has denied the permission previously your code will come to this block
      //Here you can explain why you need this permission
      //Explain here why you need this permission
    }

    //And finally ask for the permission
    ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.SEND_SMS },
      SEND_SMS_CODE);
  }

Hope it may help you.


问:
Laravel find data by model
I'm trying to debug data when i try to edit some column on database for example id such as 1, when i run this url on address bar:

```<code>http://127.0.0.1:8000/content_category/1/edit
</code>```

i get this result:

```<code>ContentCategories {#246 ▼
  #table: "contents_categories"
  #guarded: array:1 [▶]
  #connection: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #attributes: []
  #original: []
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}
</code>```

data is null in this result and i don't have any information about id=1

this column of data is exist on database and i checked that with phpmyadmin, my edit function on controller is:

```<code>public function edit(ContentCategories $contentCategories)
{
    dd($contentCategories);
}
</code>```

and Model in project:

```<code>class ContentCategories extends Model
{
    protected $table = 'contents_categories';
    protected $guarded = ['id'];
}
</code>```

route:

```<code>Route::resource('content_category', 'ContentCategoriesController');
</code>```

答:
Try this in your controller edit method</p>

```<code>public function edit($id)
{
    $contentCategories = ContentCategories::find($id);
    dd($contentCategories);
}
</code>```

Title: Laravel find data by model

Body:
I'm trying to debug data when i try to edit some column on database for example id such as 1, when i run this url on address bar:

http://127.0.0.1:8000/content_category/1/edit

i get this result:

ContentCategories {#246 ▼
  #table: "contents_categories"
  #guarded: array:1 [▶]
  #connection: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #attributes: []
  #original: []
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}

data is null in this result and i don't have any information about id=1

this column of data is exist on database and i checked that with phpmyadmin, my edit function on controller is:

public function edit(ContentCategories $contentCategories)
{
    dd($contentCategories);
}

and Model in project:

class ContentCategories extends Model
{
    protected $table = 'contents_categories';
    protected $guarded = ['id'];
}

route:

Route::resource('content_category', 'ContentCategoriesController');

Body:
Try this in your controller edit method

public function edit($id)
{
    $contentCategories = ContentCategories::find($id);
    dd($contentCategories);
}


答:
You will need to update your method signatures to be able to use implicit route model binding here.

"Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name." Laravel 5.5 Docs - Routing - Implicit Model Binding

```<code>public function edit(ContentCategories $content_category)
</code>```

This matches the route parameter name to your type hinted parameter name. This will allow for the binding to happen. Without this matching of the names of these parameters the typehinted parameter you have is being resolved as a new instance of that model via dependency injection. It has to resolve the dependency so you get a new model instance because it doesn't know that it is the parameter you want the binding for.

Additional information:

"By default, Route::resource will create the route parameters for your resource routes based on the 'singularized' version of the resource name."

Laravel 5.5 Docs - Controllers - Resource Controllers - Naming Resource Route Parameters

Title: Laravel find data by model

Body:
You will need to update your method signatures to be able to use implicit route model binding here.

"Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name." Laravel 5.5 Docs - Routing - Implicit Model Binding

public function edit(ContentCategories $content_category)

This matches the route parameter name to your type hinted parameter name. This will allow for the binding to happen. Without this matching of the names of these parameters the typehinted parameter you have is being resolved as a new instance of that model via dependency injection. It has to resolve the dependency so you get a new model instance because it doesn't know that it is the parameter you want the binding for.

Additional information:

"By default, Route::resource will create the route parameters for your resource routes based on the 'singularized' version of the resource name."

Laravel 5.5 Docs - Controllers - Resource Controllers - Naming Resource Route Parameters


问:
How to apply jquery only to the element selected with if statement?
I am trying to select a certain element on a page. All the elements have the same class same everything, with the only exception that the background image is different on some of them.

What I need to do is to ONLY apply the jquery code to only the element chosen via the if statement.

Please note I cannot edit the HTML, I need to use jquery for this.

Here is my code:

```<code>$('.repeated-element').each( function(){
   if ( $(this).css('background-image').indexOf('mystringzzz') ) {
    //do something
      alert("works");
      $(this).closest('div.someclass').addClass('aclassilike');
    //stop loop
      return false;
   }
});
</code>```

I have selected the element just fine and jquery is running. I know this because I get the alert popup which shows that part (if ( $(this).css('background-image').indexOf('mystringzzz') ) {) works.

However, the problem is that I can only get it to apply to either the first element (which is not the one that is selected) or to all of the elements.

If I use:

```<code>$(this).closest('div.someclass').addClass('aclassilike');
</code>```

the result is it applies to only the very first recurrence on the page, NOT the selected one.

Alternatively if I use:

```<code>$('.repeated-element').closest('div.someclass').addClass('aclassilike');
</code>```

Then the result is it applies every recurrence on the page, not only the selected ones. It is supposed to be only the selected one.

How can I ONLY apply the jquery code to only the element chosen via the if statement?

For example,

a) inside the .repeated-element,

  b) ONLY which contains a background-image css in the external stylesheet which has part of the image name as mystringzzz,

  c) then apply the new jquery (in this example adding another class).

  d) But do not apply it to elements which do not contain the mystringzzz string in background-image.

答:
You can use the DOM directly from any event handler, if you're interested only on selected element.</p>

```<code>$('.repeated-element').click(function(){
  if ( $(this).css('background-image').indexOf('mystringzzz') ) {
    //do something
      alert("works");
      $(this).closest('div.someclass').addClass('aclassilike');
    //stop loop
      return false;
   }
});
</code>```

Body:
I am trying to select a certain element on a page. All the elements have the same class same everything, with the only exception that the background image is different on some of them.

What I need to do is to ONLY apply the jquery code to only the element chosen via the if statement.

Please note I cannot edit the HTML, I need to use jquery for this.

Here is my code:

$('.repeated-element').each( function(){
   if ( $(this).css('background-image').indexOf('mystringzzz') ) {
    //do something
      alert("works");
      $(this).closest('div.someclass').addClass('aclassilike');
    //stop loop
      return false;
   }
});

I have selected the element just fine and jquery is running. I know this because I get the alert popup which shows that part (if ( $(this).css('background-image').indexOf('mystringzzz') ) {) works.

However, the problem is that I can only get it to apply to either the first element (which is not the one that is selected) or to all of the elements.

If I use:

$(this).closest('div.someclass').addClass('aclassilike');

the result is it applies to only the very first recurrence on the page, NOT the selected one.

Alternatively if I use:

$('.repeated-element').closest('div.someclass').addClass('aclassilike');

Then the result is it applies every recurrence on the page, not only the selected ones. It is supposed to be only the selected one.

How can I ONLY apply the jquery code to only the element chosen via the if statement?

For example,

a) inside the .repeated-element,

  b) ONLY which contains a background-image css in the external stylesheet which has part of the image name as mystringzzz,

  c) then apply the new jquery (in this example adding another class).

  d) But do not apply it to elements which do not contain the mystringzzz string in background-image.

Body:
You can use the DOM directly from any event handler, if you're interested only on selected element.

$('.repeated-element').click(function(){
  if ( $(this).css('background-image').indexOf('mystringzzz') ) {
    //do something
      alert("works");
      $(this).closest('div.someclass').addClass('aclassilike');
    //stop loop
      return false;
   }
});


问:
Efficient way to append a generated object within an existing list on a JSON file?
I have a json file as follows:

```<code>{
    "counts": [
        {
            "date": "date",
            "day": {
                "failed": "0",
                "success": "0",
                "total": "0"
            },
            "night": {
                "failed": "0",
                "success": "0",
                "total": "0"
            }
        },
        {
            "date": "05/12/2017",
            "day": {
                "failed": "0",
                "success": "0"
            },
            "night": {
                "failed": "1",
                "success": "1"
            }
        }
    ]
}
</code>```

This json file i access and edit with:

```<code>import json
from operator import itemgetter

today = '05/15/2017'
shift = 'night'

def count_save_json(today, shift, status):

    with open('count.json') as f:
        data = json.load(f)

    if today in map(itemgetter('date'), data['counts']):
        index = map(itemgetter('date'), data['counts']).index(today) #if today in map(itemgetter('date'), data['counts']) else None
        data['counts'][index][shift][status] = int(data['counts'][index][shift][status]) + 1
        print data
    else:
        new_count = {
                    "date": today,
                    "day": {
                            "success": 0,
                            "failed": 0
                            },
                    "night": {
                            "success": 0,
                            "failed": 0
                            }
                    }

        new_count[shift][status] = 1
        data['counts'].append(new_count.copy())
        print data

    with open('count.json', 'w+') as fd:
        json.dump(data, fd, sort_keys=True, indent=4)

count_save_json(today, shift, 'success')
</code>```

Its is functional and it does what i intend it to do, which is if variable today's value exists then update the corresponding value if not the push new object too array and start updating that new object until today changes again,  but the issue is that i feel is not or may not be the most efficient way to do so, as everytime the today variable changes and i need to add a new object to the array in the json file, the variable data from reading the json initially for processing will become bigger and bigger.

Say when i have a month of data the data = json.load(f) variable will be huge (technically containing the entire contents of the json file at that moment) since then i have to open the json file again remove contents and place the new data completely instead of the portion i needed to add that is the new_count object.

Is there a better way of doing this?

Hope all that made sense.

As suggested by @martineau a version using shelve module:

```<code>import shelve

today = '05/15/2017'
shift = 'day'

def count_save_json(today, shift, status):

    s = shelve.open('count.db', writeback=True)
    try:
        if today in s:
            s[today][shift][status] += 1
        else:
            s[today] = {
                            "day": {
                                "failed": 0,
                                "success": 0
                            },
                            "night": {
                                "failed": 0,
                                "success": 0
                            }
                        }
            s[today][shift][status] = 1
    finally:
        print s
        s.close()

count_save_json(today, shift, 'failed')
</code>```

While dates change it will result in appending new data to the .db file with a comma separating the entries as follows:

```<code>{
    '05/19/2017': {
        'day': {
            'failed': 0,
            'success': 1
        },
        'night': {
            'failed': 0,
            'success': 0}
    },
     '05/17/2017': {
         'day': {
             'failed': 0,
             'success': 2
         },
         'night': {
             'failed': 0,
             'success': 0
         }
     },
     '05/16/2017': {
         'day': {
             'failed': 0,
             'success': 2
         },
         'night': {
             'failed': 0,
             'success': 0
         }
     }
}
</code>```

So no matter what date the entire file is not being re-written as with the json version.

答:
I agree that this is not a code question per se, but it still touches data structures and approaches.

To my understanding, you're right that this approach will lead to a slower and slower performance over time, as you essentially looping over the records. It shouldn't be a large burden in the 5 upcoming years, though.

Yet, there is an easy (and widely used) solution to that - don't use lists, use hashtables, or in python terms, dictionaries!

Just store your records like:

```<code>{
    "counts": {
       "2017": {
         "12": {
           "05": {
     {
            "day": {
                "failed": "0",
                "success": "0"
            },
            "night": {
                "failed": "1",
                "success": "1"
            }
        }
}}}}}
</code>```

This way you can cheaply check if your date is in there, with the same performance. With that to be said, if you're worried about having large dataset, you should definitely walk away from having single json file in the first place! Just use Mongo/SQL/SQLite/ZeroDb....

Body:
I have a json file as follows:

{
    "counts": [
        {
            "date": "date",
            "day": {
                "failed": "0",
                "success": "0",
                "total": "0"
            },
            "night": {
                "failed": "0",
                "success": "0",
                "total": "0"
            }
        },
        {
            "date": "05/12/2017",
            "day": {
                "failed": "0",
                "success": "0"
            },
            "night": {
                "failed": "1",
                "success": "1"
            }
        }
    ]
}

This json file i access and edit with:

import json
from operator import itemgetter

today = '05/15/2017'
shift = 'night'

def count_save_json(today, shift, status):

    with open('count.json') as f:
        data = json.load(f)

    if today in map(itemgetter('date'), data['counts']):
        index = map(itemgetter('date'), data['counts']).index(today) #if today in map(itemgetter('date'), data['counts']) else None
        data['counts'][index][shift][status] = int(data['counts'][index][shift][status]) + 1
        print data
    else:
        new_count = {
                    "date": today,
                    "day": {
                            "success": 0,
                            "failed": 0
                            },
                    "night": {
                            "success": 0,
                            "failed": 0
                            }
                    }

        new_count[shift][status] = 1
        data['counts'].append(new_count.copy())
        print data

    with open('count.json', 'w+') as fd:
        json.dump(data, fd, sort_keys=True, indent=4)

count_save_json(today, shift, 'success')

Its is functional and it does what i intend it to do, which is if variable today's value exists then update the corresponding value if not the push new object too array and start updating that new object until today changes again,  but the issue is that i feel is not or may not be the most efficient way to do so, as everytime the today variable changes and i need to add a new object to the array in the json file, the variable data from reading the json initially for processing will become bigger and bigger.

Say when i have a month of data the data = json.load(f) variable will be huge (technically containing the entire contents of the json file at that moment) since then i have to open the json file again remove contents and place the new data completely instead of the portion i needed to add that is the new_count object.

Is there a better way of doing this?

Hope all that made sense.

As suggested by @martineau a version using shelve module:

import shelve

today = '05/15/2017'
shift = 'day'

def count_save_json(today, shift, status):

    s = shelve.open('count.db', writeback=True)
    try:
        if today in s:
            s[today][shift][status] += 1
        else:
            s[today] = {
                            "day": {
                                "failed": 0,
                                "success": 0
                            },
                            "night": {
                                "failed": 0,
                                "success": 0
                            }
                        }
            s[today][shift][status] = 1
    finally:
        print s
        s.close()

count_save_json(today, shift, 'failed')

While dates change it will result in appending new data to the .db file with a comma separating the entries as follows:

{
    '05/19/2017': {
        'day': {
            'failed': 0,
            'success': 1
        },
        'night': {
            'failed': 0,
            'success': 0}
    },
     '05/17/2017': {
         'day': {
             'failed': 0,
             'success': 2
         },
         'night': {
             'failed': 0,
             'success': 0
         }
     },
     '05/16/2017': {
         'day': {
             'failed': 0,
             'success': 2
         },
         'night': {
             'failed': 0,
             'success': 0
         }
     }
}

So no matter what date the entire file is not being re-written as with the json version.

Body:
I agree that this is not a code question per se, but it still touches data structures and approaches.

To my understanding, you're right that this approach will lead to a slower and slower performance over time, as you essentially looping over the records. It shouldn't be a large burden in the 5 upcoming years, though.

Yet, there is an easy (and widely used) solution to that - don't use lists, use hashtables, or in python terms, dictionaries!

Just store your records like:

{
    "counts": {
       "2017": {
         "12": {
           "05": {
     {
            "day": {
                "failed": "0",
                "success": "0"
            },
            "night": {
                "failed": "1",
                "success": "1"
            }
        }
}}}}}

This way you can cheaply check if your date is in there, with the same performance. With that to be said, if you're worried about having large dataset, you should definitely walk away from having single json file in the first place! Just use Mongo/SQL/SQLite/ZeroDb....


问:
Passing Select Option to POST request
I'm very new to web development and I'm trying to pass what the user has selected in a field called accesslevel_id to a POST request, so I can pass it to my database.  I'm following the example in my book, but it doesn't seem to work as intended.

My script is the following:

```<code><script>
  $(document).ready(function () {
    $('#accesslevel_id').on('change', function () {
      alert($('#accesslevel_id').val());
    });
  });
</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<select class="form-control" id="accesslevel_id" onchange="accesslevel_id" title="">
  <option>Facility</option>
  <option>Division</option>
  <option>Corporate</option>
  <option>Market</option>
  <option>Group</option>
</select>
</code>```

When on the site and a user selects an option it currently displays None for my print function defined as accesslevel_id = request.POST.get('accesslevel_id').  The next step, which i'm not at yet is to convert the option name into numbers to store into the database.  I'm looking for advice on how to accomplish this.

答:
I think you need to post the value of option value when it changes right?</p>

```<code>$(document).ready(function () {
    $('#accesslevel_id').on('change', function () {
        var accesslevel_id = $(this).val();
        $.ajax({url: "action-page",
                data:"accesslevel_id="+accesslevel_id,
                type: "POST",
                success: function(result){
                   alert(result);
                }
        });
    });
});
</code>```

Title: Passing Select Option to POST request

Body:
I'm very new to web development and I'm trying to pass what the user has selected in a field called accesslevel_id to a POST request, so I can pass it to my database.  I'm following the example in my book, but it doesn't seem to work as intended.

My script is the following:

<select class="form-control" id="accesslevel_id" onchange="accesslevel_id" title="">
  <option>Facility</option>
  <option>Division</option>
  <option>Corporate</option>
  <option>Market</option>
  <option>Group</option>
</select>

When on the site and a user selects an option it currently displays None for my print function defined as accesslevel_id = request.POST.get('accesslevel_id').  The next step, which i'm not at yet is to convert the option name into numbers to store into the database.  I'm looking for advice on how to accomplish this.

Body:
I think you need to post the value of option value when it changes right?

$(document).ready(function () {
    $('#accesslevel_id').on('change', function () {
        var accesslevel_id = $(this).val();
        $.ajax({url: "action-page",
                data:"accesslevel_id="+accesslevel_id,
                type: "POST",
                success: function(result){
                   alert(result);
                }
        });
    });
});


问:
Writing shells script to display time in am or pm notation
I'm trying to write a shell script that displays the time in am or pm rather than the way it is shown using date command. I'm not sure how I should go about doing this. I guess for starters, how do I extract the time from the date command to manipulate it? And how do I extract the number for the hour to manipulate it?</p>

答:
It's depends on locale settings. </p>

```<code>LC_TIME="C" date +%l%p
LC_TIME="C" date +'%l:%M %p'
</code>```

Body:
It's depends on locale settings.

LC_TIME="C" date +%l%p
LC_TIME="C" date +'%l:%M %p'