问:
Replace wchar_t error return memory address
I want to replace a specific character wchar_t. as a result it return memory address. is there a way to return replaced wchar_t?

```<code>#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Psapi.h>

using namespace std;

int main()
{
    wchar_t processPath[MAX_PATH];

    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, 3820);

    GetProcessImageFileName(hProcess, processPath, MAX_PATH);

    CloseHandle(hProcess);

    wchar_t * pwc;

    pwc = wcsstr(processPath, L"\\Device\\HardiskVolume1");

    wcscpy_s(pwc, 100, L"C:", 100);

    wcout << processPath;

    return 0;
}
</code>```

Thank you

答:
I suggest that you use std::wstring, and then .replace, there isn't really a good 'replace' function when using c-strings:</p>

```<code>LPCWSTR pwszReplace = L"string-of-interest";
std::size_t len = wcslen(pwszReplace);
std::wstring path(processPath),

std::size_t ndx = path.find(pwszReplace);
if(std::wstring::npos!=ndx)
{
path.replace(ndx, len, L"new-string");
}
std::wcout << L"path is now: " << path << std::endl;
</code>```

Body:
I want to replace a specific character wchar_t. as a result it return memory address. is there a way to return replaced wchar_t?

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Psapi.h>

using namespace std;

int main()
{
    wchar_t processPath[MAX_PATH];

    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, 3820);

    GetProcessImageFileName(hProcess, processPath, MAX_PATH);

    CloseHandle(hProcess);

    wchar_t * pwc;

    pwc = wcsstr(processPath, L"\\Device\\HardiskVolume1");

    wcscpy_s(pwc, 100, L"C:", 100);

    wcout << processPath;

    return 0;
}

Thank you

Body:
I suggest that you use std::wstring, and then .replace, there isn't really a good 'replace' function when using c-strings:

LPCWSTR pwszReplace = L"string-of-interest";
std::size_t len = wcslen(pwszReplace);
std::wstring path(processPath),

std::size_t ndx = path.find(pwszReplace);
if(std::wstring::npos!=ndx)
{
path.replace(ndx, len, L"new-string");
}
std::wcout << L"path is now: " << path << std::endl;


来源: stackexchange

问:
How to fetch JSON data from a url using URLSession?
I am working on an iOS application in which I have to fetch data from this url .

As I can see this url contain JSON data so here should I need to parse it or not I am not getting it how to get this JSON data.

Here is my code.

```<code>import UIKit
import SwiftyJSON

typealias ServiceResponse = (ApiResponseData, NSError?) -> Void

class ApiManager: NSObject {

    var session:URLSession? = nil
    var urlRequest:URLRequest? = nil

    override init(){
        super.init()

        urlRequest = URLRequest(url: URL(string:"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json")!)
        urlRequest?.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        session = URLSession(configuration: .default)

    }

    func callRestApiToFetchDetails(onCompletion: @escaping ServiceResponse) {
        let task = session?.dataTask(with: urlRequest!, completionHandler: {data, response, error -> Void in
            print("Response = \(data)")

            do {
                let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
                // Do Stuff
                print("\(jsonData)")
            } catch {
                // handle error
            print("Error in parsing - \(error)")
            }
        })
        task?.resume()
    }
}
</code>```

But I am getting error in parsing.

答:
You web service response is String.Encoding.ascii that convert into
String.Encoding.utf8 after you have to convert through
NSDictionary JSONSerialization.

Try this method to work.

```<code>  let url = "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"
    URLSession.shared.dataTask(with: URL(string: url)!) { (data, res, err) in

        if let d = data {
            if let value = String(data: d, encoding: String.Encoding.ascii) {

                if let jsonData = value.data(using: String.Encoding.utf8) {
                    do {
                        let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: Any]

                        if let arr = json["rows"] as? [[String: Any]] {
                            debugPrint(arr)
                        }

                    } catch {
                        NSLog("ERROR \(error.localizedDescription)")
                    }
                }
            }

        }
        }.resume()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on an iOS application in which I have to fetch data from this url .

As I can see this url contain JSON data so here should I need to parse it or not I am not getting it how to get this JSON data.

Here is my code.

import UIKit
import SwiftyJSON

typealias ServiceResponse = (ApiResponseData, NSError?) -> Void

class ApiManager: NSObject {

    var session:URLSession? = nil
    var urlRequest:URLRequest? = nil

    override init(){
        super.init()

        urlRequest = URLRequest(url: URL(string:"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json")!)
        urlRequest?.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        session = URLSession(configuration: .default)

    }

    func callRestApiToFetchDetails(onCompletion: @escaping ServiceResponse) {
        let task = session?.dataTask(with: urlRequest!, completionHandler: {data, response, error -> Void in
            print("Response = \(data)")

            do {
                let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
                // Do Stuff
                print("\(jsonData)")
            } catch {
                // handle error
            print("Error in parsing - \(error)")
            }
        })
        task?.resume()
    }
}

But I am getting error in parsing.

Body:
You web service response is String.Encoding.ascii that convert into
String.Encoding.utf8 after you have to convert through
NSDictionary JSONSerialization.

Try this method to work.

  let url = "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"
    URLSession.shared.dataTask(with: URL(string: url)!) { (data, res, err) in

        if let d = data {
            if let value = String(data: d, encoding: String.Encoding.ascii) {

                if let jsonData = value.data(using: String.Encoding.utf8) {
                    do {
                        let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: Any]

                        if let arr = json["rows"] as? [[String: Any]] {
                            debugPrint(arr)
                        }

                    } catch {
                        NSLog("ERROR \(error.localizedDescription)")
                    }
                }
            }

        }
        }.resume()


问:
Is the orientation attribute in relative layout responsible to make any changes to the final layout view obtained?
I have been trying to preview the layout for the given XML code in android:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="@dimen/list_item_height"
android:background="@color/tan_background"
tools:context="com.example.android.miwok.ColorsActivity">
<ImageView
    android:id="@+id/image"
    android:src="@mipmap/ic_launcher"
    android:layout_width="@dimen/list_item_height"
    android:layout_height="@dimen/list_item_height"
    />
<LinearLayout
    android:id="@+id/text_container"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_height="@dimen/list_item_height"
    android:layout_toRightOf="@id/image">
</LinearLayout>

</RelativeLayout>
</code>```

The result is https://i.stack.imgur.com/jzhir.png
But now I find that whenever I am trying to remove the orientation attribute from the relative layout parent view group of the same code(correct me If I am wrong in describing it), I find that the same preview is being obtained.
The view obtained after doing the above-mentioned change is as shown here
https://i.stack.imgur.com/MNbKF.png .Does this mean that it doesn't matter if we are putting any orientation attribute in the relative layout or not? Or are there any hidden consequences in the orientation attribute of the relative layout in XML in android.

答: You can see in the docs, there is no orientation argument for RelativeLayout.

Body:
I have been trying to preview the layout for the given XML code in android:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="@dimen/list_item_height"
android:background="@color/tan_background"
tools:context="com.example.android.miwok.ColorsActivity">
<ImageView
    android:id="@+id/image"
    android:src="@mipmap/ic_launcher"
    android:layout_width="@dimen/list_item_height"
    android:layout_height="@dimen/list_item_height"
    />
<LinearLayout
    android:id="@+id/text_container"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_height="@dimen/list_item_height"
    android:layout_toRightOf="@id/image">
</LinearLayout>

</RelativeLayout>

The result is https://i.stack.imgur.com/jzhir.png
But now I find that whenever I am trying to remove the orientation attribute from the relative layout parent view group of the same code(correct me If I am wrong in describing it), I find that the same preview is being obtained.
The view obtained after doing the above-mentioned change is as shown here
https://i.stack.imgur.com/MNbKF.png .Does this mean that it doesn't matter if we are putting any orientation attribute in the relative layout or not? Or are there any hidden consequences in the orientation attribute of the relative layout in XML in android.


问:
How to make Enter Key as Default key for Tab Changing for all the textbox in a Window Form C#?
I am using c# window form application. I have already tried many example on the internet for this query but nothing works for me. I just want to replace the action of Enter key with Tab key on a Window Forms. I don't want to apply keydown or up event on one by one on my textbox. I just want a single event which I can apply on my window form.

Thanks.

答:
Create your own custom TextBox:

```<code>public class MyTextBox : TextBox
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            Parent.SelectNextControl(this, true, true, true, true);
            e.Handled = true;
            e.SuppressKeyPress = true; // suppress Ding sound
        }
        base.OnKeyDown(e);
    }
}
</code>```

Compile the code. This component will appear in the toolbar. Use it instead of the regular textboxes.

Body:
Create your own custom TextBox:

public class MyTextBox : TextBox
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            Parent.SelectNextControl(this, true, true, true, true);
            e.Handled = true;
            e.SuppressKeyPress = true; // suppress Ding sound
        }
        base.OnKeyDown(e);
    }
}

Compile the code. This component will appear in the toolbar. Use it instead of the regular textboxes.


问:
installing urllib in Python3.6
I would like to import urllib to use the function 'request'. However, I encountered an error when trying to do so. I tried pip install urllib but still had the same error. I am using Python 3.6. Really appreciate any help.

i do import urllib.request using this code:

```<code>import urllib.request, urllib.parse, urllib.error
fhand = urllib.request.urlopen('data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand:
    words = line.decode().split()
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)
</code>```

but it gives me this error: ModuleNotFoundError: No Module named 'urllib.parse'; 'urllib' is not a package

here is a screenshot for the error

答: urllib is a standard library, you do not have to install it. Simply import urllib

Title: installing urllib in Python3.6

Body:
I would like to import urllib to use the function 'request'. However, I encountered an error when trying to do so. I tried pip install urllib but still had the same error. I am using Python 3.6. Really appreciate any help.

i do import urllib.request using this code:

import urllib.request, urllib.parse, urllib.error
fhand = urllib.request.urlopen('data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand:
    words = line.decode().split()
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)

but it gives me this error: ModuleNotFoundError: No Module named 'urllib.parse'; 'urllib' is not a package

here is a screenshot for the error

ContentLicense: CC BY-SA 4.0


问:
Run a separate PowerShell script asynchronously while continuing the current script
PowerShell script #1 does the following:

```<code>Performs FTP ops ending with saving updated remote directory data in a local file
</code>```

The script runs quickly until the remote directory data must be obtained using FTP.  It would be desirable to remove the remote directory data retrieval into a different PowerShell script #2.

This SO post explains launching a script from within a script.  But it seems in this case the first script is suspended while the second script executes.

How can I code script #1 so that script #2 is launched and forgotten and script #1 continues and completes quickly leaving script #2 to finish in the background.

答:
You can use Start-Job to starts a PowerShell background job. This way the job runs without interacting with the current session and will return immediately while the job is running asynchronously. If you expect receiving a result from the job, you can use Receive-Job to get the result.

Example

Start-Job -ScriptBlock {Get-Process}

Start-Job -Command "Get-Process"

Start-Job -FilePath "D:\script.ps1"

You can also use Start-Process to start another process. You can specify a program executable file or script file, or a file that can be opened by using a program on the computer. When you start process for a non-executable file, the program associated to that file type will run like when you use Invoke-Item cmdlet.

Example

Start-Process PowerShell -Argument "C:\MyScript.ps1"

Start-Process "C:\SomeFile.txt"

Body:
PowerShell script #1 does the following:

Performs FTP ops ending with saving updated remote directory data in a local file

The script runs quickly until the remote directory data must be obtained using FTP.  It would be desirable to remove the remote directory data retrieval into a different PowerShell script #2.

This SO post explains launching a script from within a script.  But it seems in this case the first script is suspended while the second script executes.

How can I code script #1 so that script #2 is launched and forgotten and script #1 continues and completes quickly leaving script #2 to finish in the background.


问:
SQL geography::EnvelopeAggregate output not accurate
I am trying to get the geography::EnvelopeAggregate for a set of locations. The geography column values are calculated using the Lat/Long for individual points.
When I try to fetch the boundary box(Extent) the box does not cover all the individual points. Is this expected behaviour? Can someone who has expertise in this field provide some inputs.
Below is the SQL code and corresponding Map plotted.

```<code>IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE id = OBJECT_ID(N'tempdb..[#ServicePoints]'))
    BEGIN
        DROP TABLE #Points
    END
CREATE TABLE #Points
(
    PointId nvarchar(max),
    Lat float,
    Long float,
    Location geography
)
insert into #Points(PointId, Lat, Long, Location)
values ('point1', 47.659226, -117.218292, geography::Point(47.659226, -117.218292, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point2', 47.659226, -117.218292, geography::Point(47.659226, -117.218292, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.659226, -117.218292, geography::Point(47.659226, -117.218292, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.658276, -117.218474, geography::Point(47.658276, -117.218474, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.658323, -117.21899, geography::Point(47.658323, -117.21899, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.658341, -117.219487, geography::Point(47.658341, -117.219487, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.660115, -117.219365, geography::Point(47.660115, -117.219365, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.658478, -117.216265, geography::Point(47.658478, -117.216265, 4326))

select * from #Points
--select geography::Point(47.658323, -117.21899, 4326)
Select E1.ID,
                   E1.SPEXtents.STPointN(3).Lat as BottomLeft_Lat,
                   E1.SPEXtents.STPointN(3).Long as BottomLeft_Long,
                   E1.SPEXtents.STPointN(1).Lat as RightTop_Lat,
                   E1.SPEXtents.STPointN(1).Long as RightTop_Long,
                   E1.SPExtents.STPointN(2).Lat as BottomRight_Lat,
                   E1.SPExtents.STPointN(2).Long as BottomRight_Long,
                   E1.SPExtents.STPointN(4).Lat as TopRight_Lat,
                   E1.SPExtents.STPointN(4).Long as TopRight_Long

        from
        (SELECT 1 as ID,
                geography::EnvelopeAggregate(sp.Location) AS SPExtents
        FROM #Points sp
        ) E1;
</code>```

And the representation of these points in map is below. As can be seen 2 points are lying outside the boundary.

OR Should I be plotting a circle connecting these 4 coordinates? In which case I can see that all the points fall within the circle as shown.

答:
Based on some rough testing, it looks like EnvelopeAggregate returns a circular area. I found this with the following:

```<code>select geography::EnvelopeAggregate(sp.Location).ToString() AS SPExtents
FROM #Points sp
</code>```

If you want to see the actual area described by that, just remove the .ToString() from the above.

Body:
I am trying to get the geography::EnvelopeAggregate for a set of locations. The geography column values are calculated using the Lat/Long for individual points.
When I try to fetch the boundary box(Extent) the box does not cover all the individual points. Is this expected behaviour? Can someone who has expertise in this field provide some inputs.
Below is the SQL code and corresponding Map plotted.

IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE id = OBJECT_ID(N'tempdb..[#ServicePoints]'))
    BEGIN
        DROP TABLE #Points
    END
CREATE TABLE #Points
(
    PointId nvarchar(max),
    Lat float,
    Long float,
    Location geography
)
insert into #Points(PointId, Lat, Long, Location)
values ('point1', 47.659226, -117.218292, geography::Point(47.659226, -117.218292, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point2', 47.659226, -117.218292, geography::Point(47.659226, -117.218292, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.659226, -117.218292, geography::Point(47.659226, -117.218292, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.658276, -117.218474, geography::Point(47.658276, -117.218474, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.658323, -117.21899, geography::Point(47.658323, -117.21899, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.658341, -117.219487, geography::Point(47.658341, -117.219487, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.660115, -117.219365, geography::Point(47.660115, -117.219365, 4326))
insert into #Points(PointId, Lat, Long, Location)
values ('point3', 47.658478, -117.216265, geography::Point(47.658478, -117.216265, 4326))

select * from #Points
--select geography::Point(47.658323, -117.21899, 4326)
Select E1.ID,
                   E1.SPEXtents.STPointN(3).Lat as BottomLeft_Lat,
                   E1.SPEXtents.STPointN(3).Long as BottomLeft_Long,
                   E1.SPEXtents.STPointN(1).Lat as RightTop_Lat,
                   E1.SPEXtents.STPointN(1).Long as RightTop_Long,
                   E1.SPExtents.STPointN(2).Lat as BottomRight_Lat,
                   E1.SPExtents.STPointN(2).Long as BottomRight_Long,
                   E1.SPExtents.STPointN(4).Lat as TopRight_Lat,
                   E1.SPExtents.STPointN(4).Long as TopRight_Long

        from
        (SELECT 1 as ID,
                geography::EnvelopeAggregate(sp.Location) AS SPExtents
        FROM #Points sp
        ) E1;

And the representation of these points in map is below. As can be seen 2 points are lying outside the boundary.

OR Should I be plotting a circle connecting these 4 coordinates? In which case I can see that all the points fall within the circle as shown.

Body:
Based on some rough testing, it looks like EnvelopeAggregate returns a circular area. I found this with the following:

select geography::EnvelopeAggregate(sp.Location).ToString() AS SPExtents
FROM #Points sp

If you want to see the actual area described by that, just remove the .ToString() from the above.


问:
Listen preference change and transfer boolean in checkbox to MainActivity
I have 2 file:

control_preferences.xml:`

```<code><PreferenceCategory
    android:title="@string/control_category">

    <CheckBoxPreference
        android:title="Debug Information ON/OFF"
        android:defaultValue="false"
        android:summary="Show debug information when ON"
        android:key="checkboxPref" />

</PreferenceCategory>
</code>```

`

SettingsActivity.java:

```<code>package com.sample;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    public static final String KEY_PREF_DEBUG = "checkboxPref";

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        if (key.equals(KEY_PREF_DEBUG)) {
            Toast.makeText(getApplicationContext(), "CLICK",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    public static class ControlPrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_control_preferences);
        }
    }}
</code>```

I have 2 questions:

Why when selecting or deselecting Checkbox Toast doesn't display?

How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity.

答:
@Jawegiel

what if I would use Toast like "Debug: " + "boolean from this actually changed checkbox" In MainActivity i read this boolean through code:

```<code>SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 boolean check = prefs.getBoolean("checkboxPref",false);
</code>```

How read this boolean in in SettingsActivity same like in MainActivity?

I try through this code:

```<code>checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
            {

                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {
                    boolean check = checkboxPref.getSharedPreferences().getBoolean("checkboxPref",false);
                    Toast.makeText(getActivity().getApplicationContext(), "Debug " + check,
                            Toast.LENGTH_SHORT).show();

                    return false;
                }
            });
</code>```

But now I can't unclick Checkbox or click if false :d

Body:
I have 2 file:

control_preferences.xml:`

<PreferenceCategory
    android:title="@string/control_category">

    <CheckBoxPreference
        android:title="Debug Information ON/OFF"
        android:defaultValue="false"
        android:summary="Show debug information when ON"
        android:key="checkboxPref" />

</PreferenceCategory>

`

SettingsActivity.java:

package com.sample;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    public static final String KEY_PREF_DEBUG = "checkboxPref";

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        if (key.equals(KEY_PREF_DEBUG)) {
            Toast.makeText(getApplicationContext(), "CLICK",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBuildHeaders(List target) {
        loadHeadersFromResource(R.xml.preference_headers, target);
    }

    public static class ControlPrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // load the preferences from an XML resource
            addPreferencesFromResource(R.xml.fragmented_control_preferences);
        }
    }}

I have 2 questions:

Why when selecting or deselecting Checkbox Toast doesn't display?

How to store in SharedPreferences boolean from this CheckBox and later read this boolean in MainActivity.

Body:
@Jawegiel

what if I would use Toast like "Debug: " + "boolean from this actually changed checkbox" In MainActivity i read this boolean through code:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
 boolean check = prefs.getBoolean("checkboxPref",false);

How read this boolean in in SettingsActivity same like in MainActivity?

I try through this code:

checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
            {

                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue)
                {
                    boolean check = checkboxPref.getSharedPreferences().getBoolean("checkboxPref",false);
                    Toast.makeText(getActivity().getApplicationContext(), "Debug " + check,
                            Toast.LENGTH_SHORT).show();

                    return false;
                }
            });

But now I can't unclick Checkbox or click if false :d


问:
Images set with background-image don't show in iOS
I have this simple html that uses a tiny bit of bootstrap:

```<code><div id="A" class="col-4">
    <div class="img" style="background-image: url(/images/image.jpg);">
</div>
<div id="B" class="col-8">
    *some content*
</div>
</code>```

And its corresponding CSS:

```<code>.img { width: 100%; height: 100%; }
</code>```

Everything is in this pen : https://codepen.io/anon/pen/EbBGQw

The image correctly displays on the entire height of the parent div on either Chrome or Firefox, either Windows or Android :

However, on iOS devices (tested on iPhone and iPad recent browsers), the images don't show up :

I've done some digging and cleared some potential culprits :

I'm not using position: fixed;

My images aren't too large

I'm not using the background shorthand

What I have found, however, is that entering any text inside the "img" div will make the background-image appear behind the text. The image still won't cover the entire div, but it does appear.

Why is Safari not showing the image properly ? What is the best way to deal with the issue and have the image properly cover its entire div ?

答:
After more digging, and the suggestion from @Michelle Cantin, I found out that the height: 100% from my CSS is ignored by Safari.

In this great answer, a fix is proposed using position: absolute;. I applied relative position to the parent element (#A) and absolute positioning to the child (.img), which fixed the issue.

The image can be seen covering the entire left column for as heigh as the right column goes in this pen : https://codepen.io/anon/pen/bYPzew

Body:
I have this simple html that uses a tiny bit of bootstrap:

    *some content*

And its corresponding CSS:

.img { width: 100%; height: 100%; }

Everything is in this pen : https://codepen.io/anon/pen/EbBGQw

The image correctly displays on the entire height of the parent div on either Chrome or Firefox, either Windows or Android :

However, on iOS devices (tested on iPhone and iPad recent browsers), the images don't show up :

I've done some digging and cleared some potential culprits :

I'm not using position: fixed;

My images aren't too large

I'm not using the background shorthand

What I have found, however, is that entering any text inside the "img" div will make the background-image appear behind the text. The image still won't cover the entire div, but it does appear.

Why is Safari not showing the image properly ? What is the best way to deal with the issue and have the image properly cover its entire div ?


问:
Creating a Metatable table in a database
Does anyone have any suggestions for creating meta tables in a database? These tables would be used to emulate tables in a database, using a database. This is for when you want to easily add structure (more fields) to a database on the fly without having to worry about all the technicalities involved. The only example I have looks something like this:

Table: MetaTables
Fields: tableName, tableDescription

Table: MetaFields
Fields: tableName, fieldName, fieldDesc, fieldDesc

Table: MetaCodes
Fields: tableName, fieldName, codeName, codeValue, etc...

I've never really used anything like this before and was wondering if there are any "gotchas" to look out for.

Is something like this reasonably maintainable or would you advise against it?

答:
Sorry, it really is, as other posters point out, reinventing the wheel.

If you want to use this data, most databases have tables containing the database schema. This can be used for the purposes of reflection.

Any good database manual should tell you how to access these tables.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Bill Karwin


问:
How do I programmatically scroll a winforms datagridview control?
I'm implementing some drag drop features in one my controls inheriting from a datagridview. Basically I'm dragging a row from somewhere in the DGV and dropping it somewhere else, reordering the rows. I've run into a problem though. If the DGV is too large such that there's a scrollbar, how can I have the DGV scroll up or down while the user is in the middle of a dragdrop?

I know how to get the current mouse position and also get the position of the dgv rectangle and such. So, I can easily find out if i'm in the top or bottom half of the rectangle... I just need a way to programmatically scroll the dgv. I'd prefer if I don't have to keep changing the selected cell to do this.

Any suggestions?

Thanks

Isaac

答:
Well, since this is a datagridview... Sorry for the 'winforms' in the question... but I could just do this.. scrolling up or down one row.

Scroll up:

```<code>this.FirstDisplayedScrollingRowIndex = this.FirstDisplayedScrollingRowIndex - 1
</code>```

Scroll Down:

```<code>this.FirstDisplayedScrollingRowIndex = this.FirstDisplayedScrollingRowIndex + 1;
</code>```

You've gotta make sure to check that the numbers don't go out of bounds though.

Body:
Well, since this is a datagridview... Sorry for the 'winforms' in the question... but I could just do this.. scrolling up or down one row.

Scroll up:

this.FirstDisplayedScrollingRowIndex = this.FirstDisplayedScrollingRowIndex - 1

Scroll Down:

this.FirstDisplayedScrollingRowIndex = this.FirstDisplayedScrollingRowIndex + 1;

You've gotta make sure to check that the numbers don't go out of bounds though.


问:
Trying to show multiple <mat-error> messages with matAutocomplete and matInput in Reactive forms (Material 2)
I want to display a couple of error messages using mat-error. I am using Angular Material 2 components with Reactive forms. I am also using errorStateMatcher to control as for when the error message appears. This works well for built-in validators like required. However, for matAutocomplete, I also want to when No Matching Records are found (basically when the user types something which is not there in the drop-down).

The html part of the form looks like below

```<code>                   <mat-form-field>
                        <input matInput
                               [matAutocomplete]="insurerAuto"
                               formControlName="insurer"
                               [errorStateMatcher]="requiredErrorState"
                               (keydown)="PanelOptions($event, insurerAuto)"
                               placeholder="Insurer" required>
                        <mat-autocomplete #insurerAuto="matAutocomplete"
                                          [displayWith]="displayFn">
                            <mat-option *ngFor="let insurer of filteredInsuranceVendors|async"
                                        [value]="insurer">
                                {{ insurer.name }}
                            </mat-option>
                        </mat-autocomplete>
                        <mat-error>{{errorMsgs.requiredMsg}}</mat-error>
                    </mat-form-field>
</code>```

As you can see, I have a mat-error to display the 'required field` message. But I want something like this instead:

```<code><mat-form-field>
                        <input matInput
                               [matAutocomplete]="insurerAuto"
                               formControlName="insurer"
                               [errorStateMatcher]="requiredErrorState"
                               (keydown)="PanelOptions($event, insurerAuto)"
                               placeholder="Insurer" required>
                        <mat-autocomplete #insurerAuto="matAutocomplete"
                                          [displayWith]="displayFn">
                            <mat-option *ngFor="let insurer of filteredInsuranceVendors|async"
                                        [value]="insurer">
                                {{ insurer.name }}
                            </mat-option>
                        </mat-autocomplete>
                        <mat-error *ngIf="policyForm.get('policyType').get('subType').hasError('required')">{{errorMsgs.requiredMsg}}</mat-error>
                        <mat-error *ngIf="(filteredInsuranceVendors|async)?.length === 0">No Matching records found!</mat-error>
                    </mat-form-field>
</code>```

With two mat-error tags with *ngIf conditions controlling as when to show the appropriate error messages. The problem I am having is with filteredInsuranceVendors as it's an Observable and I am using async, I am not sure how can I use it to compare the length.

The component code block:

```<code>    /** Error when invalid control is dirty, touched, or submitted. */
export class RequiredErrorStateMatcher implements ErrorStateMatcher {
    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        const isSubmitted = form && form.submitted;
        return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
    }
}

export const errorMessages: { [key: string]: string } = {
    requiredMsg: 'This field is required'
};

export class SomeComponent implements OnInit {
    requiredErrorState = new RequiredErrorStateMatcher();
    errorMsgs = errorMessages;
    filteredInsuranceVendors:  Observable<Array<object>>;

    filterInsuranceVendor(): void {
        const insurerControl = this.policyForm.get('insurerInfo.insurer');
        this.filteredInsuranceVendors = this.commonFilter(insurerControl, this.insuranceVendors);

    }

        commonFilter(control: AbstractControl, lst: Array<object>): Observable<any> {
        return control.valueChanges
            .map(lstObj => this.displayFn(lstObj))
            .map(ObjName =>
                ObjName ? this.utilityService.filterForAutocomplete(ObjName, lst) : lst.slice())
    }

}
</code>```

I want to have my errorStateMatcher function to include both condtions like below.

```<code>        /** Error when invalid control is dirty, touched, or submitted. */
export class RequiredErrorStateMatcher implements ErrorStateMatcher {
    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
       if (this. filteredInsuranceVendors && !this. filteredInsuranceVendors.length) {
            return true;
        }
        const isSubmitted = form && form.submitted;
        return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
    }
}
</code>```

One of the problem is, I am not sure how to deal with filteredInsuranceVendors as it's Observable. I tried converting it to Array<object>, still I was not able to use it with errorStateMatcher.

Any input would be highly appreciated. Thanks!

答:
I've just use Validators.compose

```<code>this.form = this.fb.group({
field: ['', Validators.compose([Validators.required, Validators.pattern(...)])],
...
}
</code>```

Body:
I want to display a couple of error messages using mat-error. I am using Angular Material 2 components with Reactive forms. I am also using errorStateMatcher to control as for when the error message appears. This works well for built-in validators like required. However, for matAutocomplete, I also want to when No Matching Records are found (basically when the user types something which is not there in the drop-down).

The html part of the form looks like below

                   <mat-form-field>
                        <input matInput
                               [matAutocomplete]="insurerAuto"
                               formControlName="insurer"
                               [errorStateMatcher]="requiredErrorState"
                               (keydown)="PanelOptions($event, insurerAuto)"
                               placeholder="Insurer" required>
                        <mat-autocomplete #insurerAuto="matAutocomplete"
                                          [displayWith]="displayFn">
                            <mat-option *ngFor="let insurer of filteredInsuranceVendors|async"
                                        [value]="insurer">
                                {{ insurer.name }}
                            </mat-option>
                        </mat-autocomplete>
                        <mat-error>{{errorMsgs.requiredMsg}}</mat-error>
                    </mat-form-field>

As you can see, I have a mat-error to display the 'required field` message. But I want something like this instead:

<mat-form-field>
                        <input matInput
                               [matAutocomplete]="insurerAuto"
                               formControlName="insurer"
                               [errorStateMatcher]="requiredErrorState"
                               (keydown)="PanelOptions($event, insurerAuto)"
                               placeholder="Insurer" required>
                        <mat-autocomplete #insurerAuto="matAutocomplete"
                                          [displayWith]="displayFn">
                            <mat-option *ngFor="let insurer of filteredInsuranceVendors|async"
                                        [value]="insurer">
                                {{ insurer.name }}
                            </mat-option>
                        </mat-autocomplete>
                        <mat-error *ngIf="policyForm.get('policyType').get('subType').hasError('required')">{{errorMsgs.requiredMsg}}</mat-error>
                        <mat-error *ngIf="(filteredInsuranceVendors|async)?.length === 0">No Matching records found!</mat-error>
                    </mat-form-field>

With two mat-error tags with *ngIf conditions controlling as when to show the appropriate error messages. The problem I am having is with filteredInsuranceVendors as it's an Observable and I am using async, I am not sure how can I use it to compare the length.

The component code block:

    /** Error when invalid control is dirty, touched, or submitted. */
export class RequiredErrorStateMatcher implements ErrorStateMatcher {
    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        const isSubmitted = form && form.submitted;
        return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
    }
}

export const errorMessages: { [key: string]: string } = {
    requiredMsg: 'This field is required'
};

export class SomeComponent implements OnInit {
    requiredErrorState = new RequiredErrorStateMatcher();
    errorMsgs = errorMessages;
    filteredInsuranceVendors:  Observable<Array<object>>;

    filterInsuranceVendor(): void {
        const insurerControl = this.policyForm.get('insurerInfo.insurer');
        this.filteredInsuranceVendors = this.commonFilter(insurerControl, this.insuranceVendors);

    }

        commonFilter(control: AbstractControl, lst: Array<object>): Observable<any> {
        return control.valueChanges
            .map(lstObj => this.displayFn(lstObj))
            .map(ObjName =>
                ObjName ? this.utilityService.filterForAutocomplete(ObjName, lst) : lst.slice())
    }

}

I want to have my errorStateMatcher function to include both condtions like below.

        /** Error when invalid control is dirty, touched, or submitted. */
export class RequiredErrorStateMatcher implements ErrorStateMatcher {
    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
       if (this. filteredInsuranceVendors && !this. filteredInsuranceVendors.length) {
            return true;
        }
        const isSubmitted = form && form.submitted;
        return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
    }
}

One of the problem is, I am not sure how to deal with filteredInsuranceVendors as it's Observable. I tried converting it to Array<object>, still I was not able to use it with errorStateMatcher.

Any input would be highly appreciated. Thanks!

Body:
I've just use Validators.compose

this.form = this.fb.group({
field: ['', Validators.compose([Validators.required, Validators.pattern(...)])],
...
}


问:
Refactoring a Controller containing Many-to-many relationship
I'm following a tutorial on making a blog and I was wondering how I can refactor some of the codes that look a mess. Specifically the many-to-many relationship while parsing in tags. Is there a better way to reduce this into a smaller function on the controller?</p>

```<code>  public ActionResult Create(int? id, string title, string body, DateTime datetime, string tags)
   {
      Post post = GetPost(id);
      post.Title = title;
      post.Body = body;
      post.Tags.Clear();
// I'D Like to refactor this point on to look something like this: ParseTags(tags);
rather than this
      tags = tags ?? string.Empty;
     string[] tagNames = tags.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
            foreach(string tagName in tagNames)
              {
                post.Tags.Add(GetTag(tagNames));
              }
       }

private Tag GetTag(string tagName)
    {
    return _context.Tags.Where(x => x.Name == tagName).FirstOrDefault() ??
    new Tag() { Name = tagName };
}
</code>```

答:
Rather than creating a new method on the controller, you could encapsulate all the behaviour for parsing and searching for tags in a class, maybe something like this:

```<code>public class Tags
{
    private readonly IEnumerable<Tag> contextTags;
    private readonly string rawTags;

    public Tags(string tags, IEnumerable<Tag> contextTags)
    {
        this.rawTags = tags ?? string.Empty;
        this.contextTags = contextTags;
    }

    public IEnumerable<Tag> ToList()
    {
        List<Tag> tags = new List<Tag>();

        string[] tagNames = this.rawTags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (string tagName in tagNames)
        {
            tags.Add(this.GetTag(tagName));
        }

        return tags;
    }

    private Tag GetTag(string tagName)
    {
        return this.contextTags.FirstOrDefault(x => x.Name == tagName) ?? new Tag { Name = tagName };
    }
}
</code>```

Then the Create method on the controller becomes:

```<code>public ActionResult Create(int? id, string title, string body, DateTime datetime, string tags)
{
    Post post = GetPost(id);
    post.Title = title;
    post.Body = body;
    post.Tags.Clear();

    Tags tagsList = new Tags(tags, this._context.Tags);

    post.Tags = tagsList.ToList();
}
</code>```

Body:
I'm following a tutorial on making a blog and I was wondering how I can refactor some of the codes that look a mess. Specifically the many-to-many relationship while parsing in tags. Is there a better way to reduce this into a smaller function on the controller?

  public ActionResult Create(int? id, string title, string body, DateTime datetime, string tags)
   {
      Post post = GetPost(id);
      post.Title = title;
      post.Body = body;
      post.Tags.Clear();
// I'D Like to refactor this point on to look something like this: ParseTags(tags);
rather than this
      tags = tags ?? string.Empty;
     string[] tagNames = tags.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
            foreach(string tagName in tagNames)
              {
                post.Tags.Add(GetTag(tagNames));
              }
       }

private Tag GetTag(string tagName)
    {
    return _context.Tags.Where(x => x.Name == tagName).FirstOrDefault() ??
    new Tag() { Name = tagName };
}

Body:
Rather than creating a new method on the controller, you could encapsulate all the behaviour for parsing and searching for tags in a class, maybe something like this:

public class Tags
{
    private readonly IEnumerable<Tag> contextTags;
    private readonly string rawTags;

    public Tags(string tags, IEnumerable<Tag> contextTags)
    {
        this.rawTags = tags ?? string.Empty;
        this.contextTags = contextTags;
    }

    public IEnumerable<Tag> ToList()
    {
        List<Tag> tags = new List<Tag>();

        string[] tagNames = this.rawTags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (string tagName in tagNames)
        {
            tags.Add(this.GetTag(tagName));
        }

        return tags;
    }

    private Tag GetTag(string tagName)
    {
        return this.contextTags.FirstOrDefault(x => x.Name == tagName) ?? new Tag { Name = tagName };
    }
}

Then the Create method on the controller becomes:

public ActionResult Create(int? id, string title, string body, DateTime datetime, string tags)
{
    Post post = GetPost(id);
    post.Title = title;
    post.Body = body;
    post.Tags.Clear();

    Tags tagsList = new Tags(tags, this._context.Tags);

    post.Tags = tagsList.ToList();
}


问:
for loop condition in 2nd clause and no condition in 3rd clause
```<code>for(i=5;--i;)
 printf("%d ",i);
</code>```

The output I am getting is proper which is 4 3 2 1. There is no i>0 condition in 3rd clause, so how is loop stopping when i=0?

答:
--i eventually turns out to be 0. And thus the condition becomes false.

As, the "3rd clause" is empty, nothing interesting happens. The "2nd clause" is where condition checks are done. And --i evaluates to itself which is 0 in the fifth iteration.

Body:
for(i=5;--i;)
 printf("%d ",i);

The output I am getting is proper which is 4 3 2 1. There is no i>0 condition in 3rd clause, so how is loop stopping when i=0?


问:
Using geofire like geofences
I want to make an app which send a notification when the user enters in an area. I know that exists Geofire, and I would like to use, because i'm using a Firebase database, however I never used it, and I don't know if it has the same behaviour of Google Geofences.

Can someone tell me if I can implement my idea with Geofire?

Thank you very much for your answers!

答:
GeoFire is a client-side library that allows you to store geographic locations in the Firebase Realtime Database, and subsequently fire GeoQueries against that data to get locations within a specific range of a certain point.

It has no built in support for geofencing, but it is possible to build a geofencing app with the library. The most important steps are:

You need to regularly know the location of the phone.

You then need to query your database for fences around your location.

I'm not sure if GeoFire is the most suitable library available for this (and recommending technology is off-topic on Stack Overflow anyway). But it does seem possible.

Title: Using geofire like geofences


问:
Apply EF migration on publish available only for some web projects
I've got several projects using Asp.Net Core 1.0 and Entity Framework Core 1.1.0

I have a code first migration approach and I publish to Azure through Visual Studio 2015.

The way I used to apply migrations in Azure Sql Server was by enabling a checkbox on publish: "Entity Framework Migrations - Apply this migration on publish", where I typed in a connection string.

I updated several packages and now for one of my projects I don't see this option to apply migrations on publish anymore. I can see that it tries to discover data contexts but it does not find anything (although it's there in the same project..)

See below:

Project where I can apply migrations on Azure when publishing:

Project where the option to apply migrations on Azure when publishing is gone:

I suspect it has something to do with some dependency version for the project and not with my IDE because I am using the same Visual Studio (2015 update 3) for both projects.

I couldn't find information about this. What dependency allows this option? If I find out what version is problematic then the remaining question is how to apply migrations when publishing then?

Both projects have the migrations in the Web project and both projects are using "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.1.0"

UPDATE 1: I managed to find what's involved in this. It seems that if I use these dependencies:

```<code>"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
"Microsoft.EntityFrameworkCore.Design": "1.0.0-preview2-final"
</code>```

Visual studio is able to find data context and offer the option to Apply migrations on publish. But if I use newer versions of those dependencies like:

```<code>"Microsoft.EntityFrameworkCore.Tools": "1.1.0-preview4-final",
"Microsoft.EntityFrameworkCore.Design": "1.1.0"
</code>```

Then that option to apply migrations is gone and VS cannot find any data context when publishing.

I'd need to find out what's the latest status with the migrations thing and Asp.Net Core.

答:
To work with migrations, you can use the Package Manager Console (PMC) or the command-line interface (CLI)
When using PMC, EF migrations are not discovered during the publish.
By using CLI, the EF migrations section appears.

https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations

https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet

Body:
I've got several projects using Asp.Net Core 1.0 and Entity Framework Core 1.1.0

I have a code first migration approach and I publish to Azure through Visual Studio 2015.

The way I used to apply migrations in Azure Sql Server was by enabling a checkbox on publish: "Entity Framework Migrations - Apply this migration on publish", where I typed in a connection string.

I updated several packages and now for one of my projects I don't see this option to apply migrations on publish anymore. I can see that it tries to discover data contexts but it does not find anything (although it's there in the same project..)

See below:

Project where I can apply migrations on Azure when publishing:

Project where the option to apply migrations on Azure when publishing is gone:

I suspect it has something to do with some dependency version for the project and not with my IDE because I am using the same Visual Studio (2015 update 3) for both projects.

I couldn't find information about this. What dependency allows this option? If I find out what version is problematic then the remaining question is how to apply migrations when publishing then?

Both projects have the migrations in the Web project and both projects are using "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.1.0"

UPDATE 1: I managed to find what's involved in this. It seems that if I use these dependencies:

"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
"Microsoft.EntityFrameworkCore.Design": "1.0.0-preview2-final"

Visual studio is able to find data context and offer the option to Apply migrations on publish. But if I use newer versions of those dependencies like:

"Microsoft.EntityFrameworkCore.Tools": "1.1.0-preview4-final",
"Microsoft.EntityFrameworkCore.Design": "1.1.0"

Then that option to apply migrations is gone and VS cannot find any data context when publishing.

I'd need to find out what's the latest status with the migrations thing and Asp.Net Core.


问:
IntegrityError at /accounts/regist_save/ happens
IntegrityError at /accounts/regist_save/
NOT NULL constraint failed: accounts_newuser.user_id
error happens .I wrote in

views.py

```<code>def regist(request):
    regist_form = RegisterForm(request.POST or None)
    profile_form = ProfileForm(request.POST or None)
    context = {
        'regist_form': regist_form,
        'profile_form': profile_form,
    }
    return render(request, 'registration/regist.html', context)

@require_POST
def regist_save(request):

    regist_form = RegisterForm(request.POST or None)
    profile_form = ProfileForm(request.POST or None)

    if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid():
                regist = regist_form.save(commit=False)
                regist.is_staff = True
                regist.save()

                profile = profile_form.save(commit=False)
                sex = request.POST.get("sex", "")
                print(1111)
                print(sex)
                profile.save()
    else:
        print(regist_form.errors)
        print(profile_form.errors)
    return redirect('detail')
</code>```

regist.html

```<code> <div class="form-group-lg">

    <label for="id_username">Username</label>

    {{ regist_form.username }}

  </div>

  <div class="form-group-lg">

    <label for="id_email">Email</label>

    {{ regist_form.email }}
  </div>

  <div class="form-group-lg">

    <label for="id_password">Password</label>

    {{ regist_form.password1 }}

  </div>

  <div class="form-group-lg">
    <label for="id_password">Password2</label>

    {{ regist_form.password2 }}
    <p class="help-block">{{ regist_form.password2.help_text }}</p>

  </div>

  {% load static %}
  <div class="form-group-lg">
    <label for="birthday">Date</label>

    <select id="year" class="form-control year" name="year">
      <option value="">--</option>
    </select>
    Year
    <select id="month" class="form-control month" name="month">
      <option value="">--</option>
    </select>
    Month
    <select id="day" class="form-control day" name="day">
      <option value="">--</option>
    </select>
    Day
    <br>
    <br>
  </div>

  <div class="form-group-lg">
    <label for="sex">SEX</label>
    <select id="sex" class="form-control sex" name="sex">
      <option value="">--</option>
      <option value="male">male</option>
      <option value="female">female</option>
    </select>
  </div>

  <script src="{% static 'accounts/register.js' %}"></script>

      <button type="submit" class="btn-lg regist">REGIST</button>

      <input name="next" type="hidden" />

  {% csrf_token %}

</form>
</code>```

regist.js

```<code>$(() => {
    for (let i = 1900; i < 2020; i++) {
        $("#year").append(`<option value="${i}">${i}</option>`);
    }
    for (let i = 1; i < 12; i++) {
        $("#month").append(`<option value="${i}">${i}</option>`);
    }
    for (let i = 1; i < 31; i++) {
        $("#day").append(`<option value="${i}">${i}</option>`);
    }
})
</code>```

models.py

```<code>from django.db import models
from django.contrib.auth.models import User

    class NewUser(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        birthday = models.CharField(max_length=100,null=True, blank=True, default=None)
        sex = models.CharField(max_length=100,null=True, blank=True, default=None)
</code>```

in forms.py

```<code>from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User
from .models import NewUser

class RegisterForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'email','password1','password1',)
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['class'] = 'form-control'
        self.fields['email'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['class'] = 'form-control'

class ProfileForm(forms.ModelForm):
    class Meta:
        model = NewUser
        fields = (
            "birthday", "sex"
        )
</code>```

I really cannot understand why this error happens because I did not write user_id  in NewUser models.I think Integrity Error means columns cannot be found in Model.OneToOneField can be connected withUser and NewUser's model .I think this error means I should prepare user_id in New User model but if my thinking is right, I cannot understand why.How should I fix this?What should I write it?

答:
This happens because in the NewUser model, the user field is a required field. In the ProfileForm the user field is not included. So when the ProfileForm tries to save the NewUser without user attached to it, it results in the above mentioned error.

What we have to do is to attach the user to the instance before actual save happens:

```<code>profile = profile_form.save(commit=False)
profile.user = registered_user # you can get the user from the registerform above
profile.save()
</code>```

Body:
IntegrityError at /accounts/regist_save/
NOT NULL constraint failed: accounts_newuser.user_id
error happens .I wrote in

views.py

def regist(request):
    regist_form = RegisterForm(request.POST or None)
    profile_form = ProfileForm(request.POST or None)
    context = {
        'regist_form': regist_form,
        'profile_form': profile_form,
    }
    return render(request, 'registration/regist.html', context)

@require_POST
def regist_save(request):

    regist_form = RegisterForm(request.POST or None)
    profile_form = ProfileForm(request.POST or None)

    if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid():
                regist = regist_form.save(commit=False)
                regist.is_staff = True
                regist.save()

                profile = profile_form.save(commit=False)
                sex = request.POST.get("sex", "")
                print(1111)
                print(sex)
                profile.save()
    else:
        print(regist_form.errors)
        print(profile_form.errors)
    return redirect('detail')

regist.html

    Username

    {{ regist_form.username }}

    Email

    {{ regist_form.email }}

    Password

    {{ regist_form.password1 }}

    Password2

    {{ regist_form.password2 }}

{{ regist_form.password2.help_text }}

  {% load static %}

    Date

    <select id="year" class="form-control year" name="year">
      <option value="">--</option>
    </select>
    Year
    <select id="month" class="form-control month" name="month">
      <option value="">--</option>
    </select>
    Month
    <select id="day" class="form-control day" name="day">
      <option value="">--</option>
    </select>
    Day

    SEX
    <select id="sex" class="form-control sex" name="sex">
      <option value="">--</option>
      <option value="male">male</option>
      <option value="female">female</option>
    </select>

      <button type="submit" class="btn-lg regist">REGIST</button>

      <input name="next" type="hidden" />

  {% csrf_token %}

</form>

regist.js

$(() => {
    for (let i = 1900; i < 2020; i++) {
        $("#year").append(`<option value="${i}">${i}</option>`);
    }
    for (let i = 1; i < 12; i++) {
        $("#month").append(`<option value="${i}">${i}</option>`);
    }
    for (let i = 1; i < 31; i++) {
        $("#day").append(`<option value="${i}">${i}</option>`);
    }
})

models.py

from django.db import models
from django.contrib.auth.models import User

    class NewUser(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        birthday = models.CharField(max_length=100,null=True, blank=True, default=None)
        sex = models.CharField(max_length=100,null=True, blank=True, default=None)

in forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
from .models import User
from .models import NewUser

class RegisterForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'email','password1','password1',)
    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs['class'] = 'form-control'
        self.fields['email'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['class'] = 'form-control'

class ProfileForm(forms.ModelForm):
    class Meta:
        model = NewUser
        fields = (
            "birthday", "sex"
        )

I really cannot understand why this error happens because I did not write user_id  in NewUser models.I think Integrity Error means columns cannot be found in Model.OneToOneField can be connected withUser and NewUser's model .I think this error means I should prepare user_id in New User model but if my thinking is right, I cannot understand why.How should I fix this?What should I write it?

Body:
This happens because in the NewUser model, the user field is a required field. In the ProfileForm the user field is not included. So when the ProfileForm tries to save the NewUser without user attached to it, it results in the above mentioned error.

What we have to do is to attach the user to the instance before actual save happens:

profile = profile_form.save(commit=False)
profile.user = registered_user # you can get the user from the registerform above
profile.save()


问:
Pandas agg fuction with operations on multiple columns
I am interested if we can use pandas.core.groupby.DataFrameGroupBy.agg function to make arithmetic operations on multiple columns columns. For example:

```<code>import numpy as np
import pandas as pd

df = pd.DataFrame(np.arange(15).reshape(5, 3))
df['C'] = [0, 0, 2, 2, 5]
print(df.groupby('C').mean()[0] - df.groupby('C').mean()[1])
print(df.groupby('C').agg({0: 'mean', 1: 'sum', 2: 'nunique', 'C': 'mean0-mean1'}))
</code>```

Is it somehow possible that we receive result like in this example: the difference between means of column 0 and column 1 grouped by column 'C'?
df

```<code>    0   1   2  C
0   0   1   2  0
1   3   4   5  0
2   6   7   8  2
3   9  10  11  2
4  12  13  14  5
</code>```

Groupped difference

```<code>C
0   -1.0
2   -1.0
5   -1.0
dtype: float64
</code>```

I am not interested with solutions that does not use agg method. I am curious only if agg method can take multiple columns as argument and then do some operations on them to return one columns after job is done.

Body:
I am interested if we can use pandas.core.groupby.DataFrameGroupBy.agg function to make arithmetic operations on multiple columns columns. For example:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.arange(15).reshape(5, 3))
df['C'] = [0, 0, 2, 2, 5]
print(df.groupby('C').mean()[0] - df.groupby('C').mean()[1])
print(df.groupby('C').agg({0: 'mean', 1: 'sum', 2: 'nunique', 'C': 'mean0-mean1'}))

Is it somehow possible that we receive result like in this example: the difference between means of column 0 and column 1 grouped by column 'C'?
df

    0   1   2  C
0   0   1   2  0
1   3   4   5  0
2   6   7   8  2
3   9  10  11  2
4  12  13  14  5

Groupped difference

C
0   -1.0
2   -1.0
5   -1.0
dtype: float64

I am not interested with solutions that does not use agg method. I am curious only if agg method can take multiple columns as argument and then do some operations on them to return one columns after job is done.

Body:
IIUC:

In [12]: df.groupby('C').mean().diff(axis=1)
Out[12]:
    0    1    2
C
0 NaN  1.0  1.0
2 NaN  1.0  1.0
5 NaN  1.0  1.0

or

In [13]: df.groupby('C').mean().diff(-1, axis=1)
Out[13]:
     0    1   2
C
0 -1.0 -1.0 NaN
2 -1.0 -1.0 NaN
5 -1.0 -1.0 NaN


问:
How to open two / multiple instances of Visual Studio for MAC?
I wish to open multiple instances of VS for Mac. I used to be able to do this with Xamarin studio using the Xamarin launcher.

How to do this with VS for Mac?

答:
I am using MSSolutionLauncher for opening multiple instances of Visual studio for Mac. The github page of the project is Here. Download latest release and double click to unzip. Now keep the app in desktop and click on it to open new instance of the Visual studio for mac as many times as you want.

EDIT

Starting from Visual Studio for Mac 2019, MSSolutionLauncher is not required. Keep the VSMac Shortcut in Dock. Right Click the Dock Icon and select New Instance.


问:
Detecting async client disconnect in ASP.NET MVC
Given an async controller:

```<code>public class MyController : AsyncController
{
    [NoAsyncTimeout]
    public void MyActionAsync() { ... }

    public void MyActionCompleted() { ... }
}
</code>```

Assume MyActionAsync kicks off a process that takes several minutes.  If the user now goes to the MyAction action, the browser will wait with the connection open.  If the user closes his browser, the connection is closed.  Is it possible to detect when that happens on the server (preferably inside the controller)?  If so, how?  I've tried overriding OnException but that never fires in this scenario.

Note:  I do appreciate the helpful answers below, but the key aspect of this question is that I'm using an AsyncController.  This means that the HTTP requests are still open (they are long-lived like COMET or BOSH) which means it's a live socket connection.  Why can't the server be notified when this live connection is terminated (i.e.  "connection reset by peer", the TCP RST packet)?

答:
It's just as @Darin says. HTTP is a stateless protocol which means that there are no way (by using HTTP) to detect if the client is still there or not. HTTP 1.0 closes the socket after each request, while HTTP/1.1 can keep it open for a while (a keep alive timeout can be set as a header). That a HTTP/1.1 client closes the socket (or the server for that matter) doesn't mean that the client has gone away, just that the socket hasn't been used for a while.

There are something called COMET servers which are used to let client/server continue to "chat" over HTTP. Search for comet here at SO or on the net, there are several implementations available.

Body:
Given an async controller:

public class MyController : AsyncController
{
    [NoAsyncTimeout]
    public void MyActionAsync() { ... }

    public void MyActionCompleted() { ... }
}

Assume MyActionAsync kicks off a process that takes several minutes.  If the user now goes to the MyAction action, the browser will wait with the connection open.  If the user closes his browser, the connection is closed.  Is it possible to detect when that happens on the server (preferably inside the controller)?  If so, how?  I've tried overriding OnException but that never fires in this scenario.

Note:  I do appreciate the helpful answers below, but the key aspect of this question is that I'm using an AsyncController.  This means that the HTTP requests are still open (they are long-lived like COMET or BOSH) which means it's a live socket connection.  Why can't the server be notified when this live connection is terminated (i.e.  "connection reset by peer", the TCP RST packet)?


问:
Angular TypeScript pushing items to array errors
```<code>export class PickGroupService {
  channelList: any[];
  pick5West = ['783', '679', '934', '946', '800'];
  thePicks: any[];

  constructor(private channels: ChannelsService) { this.channelList = this.channels.getChannels(); }

  getPickSet(pick, region) {
    if (pick === 'pick5') {
      switch (region) {
        case 'west':
        for (let i = 0; i < this.pick5West.length; i++) {
          this.thePicks.push((this.channelList.filter(x => x.pickCode === this.pick5West[i]));
        }
        console.log(this.thePicks);
  }
}
</code>```

}
 }
Just wondering whats wrong with this code, it says :
ERROR
TypeError: this_1.thePicks is undefined on browser console. Please advise!

答:
Initialize it to an empty array,</p>

```<code> thePicks: any[] = [];
</code>```

Body:
export class PickGroupService {
  channelList: any[];
  pick5West = ['783', '679', '934', '946', '800'];
  thePicks: any[];

  constructor(private channels: ChannelsService) { this.channelList = this.channels.getChannels(); }

  getPickSet(pick, region) {
    if (pick === 'pick5') {
      switch (region) {
        case 'west':
        for (let i = 0; i < this.pick5West.length; i++) {
          this.thePicks.push((this.channelList.filter(x => x.pickCode === this.pick5West[i]));
        }
        console.log(this.thePicks);
  }
}

}
 }
Just wondering whats wrong with this code, it says :
ERROR
TypeError: this_1.thePicks is undefined on browser console. Please advise!

Body:
Initialize it to an empty array,

 thePicks: any[] = [];


问:
ggplot2 facet - Highlight matching columns
Sample data set

```<code>brand=c('MS', 'Google', 'Apple', 'MS', 'FB', 'Apple', 'Oracle')
product=c('OS', 'Search', 'Iphone', 'Search', 'Network', 'OS', 'DB')
df= data.frame(brand, product)
</code>```

it looks like this

```<code>   brand product
1     MS      OS
2 Google  Search
3  Apple  Iphone
4     MS  Search
5     FB Network
6  Apple      OS
7 Oracle      DB
</code>```

Problem statement

I am plotting this graph using ggplot, here the code

```<code>library(dplyr)
library(ggplot2)
df %>%
    group_by(brand) %>%
    count(product, sort = TRUE) %>%
    ggplot(aes(product, n)) +
        geom_col()  +
        facet_wrap(~brand, ncol = 5, scales = "free_x") +
        coord_flip()
</code>```

it will give graph like this

Now we can see 'search' is common in both 'Google' and 'MS' and 'OS' is common in 'MS' and 'Appple', I want to highlight both the bars but don't know how can I do it, Please suggest also let me know if its possible with other graphical interface other than ggplot.

答:
The general principle is that you have to add to your data frame a column that holds the coloring information, just like @PoGibas did. Once you have that column, you can draw using whatever approach you like, including the geom_col() approach you chose.

```<code>brand=c('MS', 'Google', 'Apple', 'MS', 'FB', 'Apple', 'Oracle')
product=c('OS', 'Search', 'Iphone', 'Search', 'Network', 'OS', 'DB')
df= data.frame(brand, product)

# Define color
df$myColor <- NA
foo <- df$product %in% names(which(table(df$product) > 1))
df$myColor[foo] <- df$product[foo]

df
#   brand product myColor
#1     MS      OS       4
#2 Google  Search       5
#3  Apple  Iphone      NA
#4     MS  Search       5
#5     FB Network      NA
#6  Apple      OS       4
#7 Oracle      DB      NA
</code>```

What follows is your original plotting code, slightly modified. If you only ever have each product once for each vendor, it's better to set y = 1 in the aes() statement rather than add extra code to count.

```<code>library(dplyr)
library(ggplot2)
ggplot(df, aes(x = product, y = 1, fill = factor(myColor))) +
  geom_col()  +
  facet_wrap(~brand, ncol = 5, scales = "free_x") +
  guides(fill = "none") +
  coord_flip()
</code>```

And now we can play around with the theme a bit to make things look better.

```<code>ggplot(df, aes(x = product, y = 1, fill = factor(myColor))) +
  geom_col()  +
  facet_wrap(~brand, ncol = 5) +
  guides(fill = "none") +
  scale_y_continuous(breaks = NULL, name = "") +
  scale_x_discrete(expand = c(0, 0)) +
  coord_flip() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks = element_blank(),
        axis.text = element_text(color = "black"),
        strip.background = element_blank(),
        panel.background = element_rect(fill="gray95", color="gray95"),
        panel.spacing = unit(0, "pt"))
</code>```

However, the correct geom for this application, in my mind, is neither geom_col() as you used nor geom_point() as suggested by @PoGibas, but geom_tile():

```<code>ggplot(df, aes(x = brand, y = product, fill = factor(myColor))) +
  geom_tile(width = 0.9, height = 0.9)  +
  guides(fill = "none") +
  scale_x_discrete(name = "", position = "top") +
  scale_y_discrete(name = "") +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks = element_blank(),
        axis.text = element_text(color = "black"),
        panel.background = element_rect(fill="gray95"))
</code>```

With geom_tile(), you can separately define the height and width of the filled areas, and you won't have any strange surprises if you resize the plot or change its aspect ratio.

Body:
Sample data set

brand=c('MS', 'Google', 'Apple', 'MS', 'FB', 'Apple', 'Oracle')
product=c('OS', 'Search', 'Iphone', 'Search', 'Network', 'OS', 'DB')
df= data.frame(brand, product)

it looks like this

   brand product
1     MS      OS
2 Google  Search
3  Apple  Iphone
4     MS  Search
5     FB Network
6  Apple      OS
7 Oracle      DB

Problem statement

I am plotting this graph using ggplot, here the code

library(dplyr)
library(ggplot2)
df %>%
    group_by(brand) %>%
    count(product, sort = TRUE) %>%
    ggplot(aes(product, n)) +
        geom_col()  +
        facet_wrap(~brand, ncol = 5, scales = "free_x") +
        coord_flip()

it will give graph like this

Now we can see 'search' is common in both 'Google' and 'MS' and 'OS' is common in 'MS' and 'Appple', I want to highlight both the bars but don't know how can I do it, Please suggest also let me know if its possible with other graphical interface other than ggplot.

Body:
The general principle is that you have to add to your data frame a column that holds the coloring information, just like @PoGibas did. Once you have that column, you can draw using whatever approach you like, including the geom_col() approach you chose.

brand=c('MS', 'Google', 'Apple', 'MS', 'FB', 'Apple', 'Oracle')
product=c('OS', 'Search', 'Iphone', 'Search', 'Network', 'OS', 'DB')
df= data.frame(brand, product)

# Define color
df$myColor <- NA
foo <- df$product %in% names(which(table(df$product) > 1))
df$myColor[foo] <- df$product[foo]

df
#   brand product myColor
#1     MS      OS       4
#2 Google  Search       5
#3  Apple  Iphone      NA
#4     MS  Search       5
#5     FB Network      NA
#6  Apple      OS       4
#7 Oracle      DB      NA

What follows is your original plotting code, slightly modified. If you only ever have each product once for each vendor, it's better to set y = 1 in the aes() statement rather than add extra code to count.

library(dplyr)
library(ggplot2)
ggplot(df, aes(x = product, y = 1, fill = factor(myColor))) +
  geom_col()  +
  facet_wrap(~brand, ncol = 5, scales = "free_x") +
  guides(fill = "none") +
  coord_flip()

And now we can play around with the theme a bit to make things look better.

ggplot(df, aes(x = product, y = 1, fill = factor(myColor))) +
  geom_col()  +
  facet_wrap(~brand, ncol = 5) +
  guides(fill = "none") +
  scale_y_continuous(breaks = NULL, name = "") +
  scale_x_discrete(expand = c(0, 0)) +
  coord_flip() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks = element_blank(),
        axis.text = element_text(color = "black"),
        strip.background = element_blank(),
        panel.background = element_rect(fill="gray95", color="gray95"),
        panel.spacing = unit(0, "pt"))

However, the correct geom for this application, in my mind, is neither geom_col() as you used nor geom_point() as suggested by @PoGibas, but geom_tile():

ggplot(df, aes(x = brand, y = product, fill = factor(myColor))) +
  geom_tile(width = 0.9, height = 0.9)  +
  guides(fill = "none") +
  scale_x_discrete(name = "", position = "top") +
  scale_y_discrete(name = "") +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks = element_blank(),
        axis.text = element_text(color = "black"),
        panel.background = element_rect(fill="gray95"))

With geom_tile(), you can separately define the height and width of the filled areas, and you won't have any strange surprises if you resize the plot or change its aspect ratio.


问:
How to find ratio between two columns in a dataframe?
For example

```<code>df

Cars             Male   female
Ford focus        23      64
vw golf           76      12
ford ka           34      55
renault megane    12      83
</code>```

How do i find the ratio of male to female for every car >0.5

答:
Just subset your data frame using that ratio:

```<code>df[df$Male / df$Female > 0.5, ]

     Cars Male Female
2 vw golf   76     12
3 ford ka   34     55
</code>```

Demo

Body:
For example

df

Cars             Male   female
Ford focus        23      64
vw golf           76      12
ford ka           34      55
renault megane    12      83

How do i find the ratio of male to female for every car >0.5

Body:
Just subset your data frame using that ratio:

df[df$Male / df$Female > 0.5, ]

     Cars Male Female
2 vw golf   76     12
3 ford ka   34     55

Demo


问:
Finding World Space Coordinates of a Unity UI Element
So according to the Unity documentation RectTransform.anchoredPosition will return the screen coordinates of a UI element if the anchors are touching at the pivot point of the RectTransform.  However, if they are separated (in my case positioned at the corners of the rect) they will give you the position of the anchors relative to the pivot point.  This is wonderful unless you want to keep appropriate dimensions of a UI object through multiple resolutions and position a different object based on that position at the same time.

Let's break this down.  I have object1 and object2.  object1 is positioned at (322.5, -600) and when the anchor points meet at the center (pivot) of the object anchoredPosition returns just that and object2 is positioned just fine.  On the other hand once I have placed the anchors at the 4 corners of object1 anchoredPosition returns (45.6, -21).  Thats just no good. I've even tried using Transform.position and then Camera.WorldToScreenPoint(), but that does just about as much to getting me to my goal.

I was hoping that you might be able to help me find a way to get the actual screen coordinates of this object. If anyone has any insight into this subject it would be greatly appreciated.

Notes: I've already attempted to use RectTranfrom.rect.center and it returned (0, 0)

I've also looked into RectTransformUtility and those helper functions have done all of squat.

答:
Here's a glimpse on how finding world space coordinates of UI elements works if your stuck and need to roll your own transformations from view-space to world-space.

This may be beneficial if say you need something more than rectTransform.TransformPoint or want to know how this works.

Ok, so you want to do a transformation from normalised UI coordinates in the range [-1, 1], and de-project them back into world space coordinates.

To do this you could use something like Camera.main.ScreenToWorldPoint or Camera.main.ViewportToWorldPoint, or even rectTransform.position if your a lacker.

This is how to do it with just the camera's projection matrix.

```<code>/// <summary>
/// Get the world position of an anchor/normalised device coordinate in the range [-1, 1]
/// </summary>
private Vector3 GetAnchor(Vector2 ndcSpace)
{
    Vector3 worldPosition;

    Vector4 viewSpace = new Vector4(ndcSpace.x, ndcSpace.y, 1.0f, 1.0f);

    // Transform to projection coordinate.
    Vector4 projectionToWorld = (_mainCamera.projectionMatrix.inverse * viewSpace);

    // Perspective divide.
    projectionToWorld /= projectionToWorld.w;

    // Z-component is backwards in Unity.
    projectionToWorld.z = -projectionToWorld.z;

    // Transform from camera space to world space.
    worldPosition = _mainCamera.transform.position + _mainCamera.transform.TransformVector(projectionToWorld);

    return worldPosition;
}
</code>```

Body:
Here's a glimpse on how finding world space coordinates of UI elements works if your stuck and need to roll your own transformations from view-space to world-space.

This may be beneficial if say you need something more than rectTransform.TransformPoint or want to know how this works.

Ok, so you want to do a transformation from normalised UI coordinates in the range [-1, 1], and de-project them back into world space coordinates.

To do this you could use something like Camera.main.ScreenToWorldPoint or Camera.main.ViewportToWorldPoint, or even rectTransform.position if your a lacker.

This is how to do it with just the camera's projection matrix.

/// <summary>
/// Get the world position of an anchor/normalised device coordinate in the range [-1, 1]
/// </summary>
private Vector3 GetAnchor(Vector2 ndcSpace)
{
    Vector3 worldPosition;

    Vector4 viewSpace = new Vector4(ndcSpace.x, ndcSpace.y, 1.0f, 1.0f);

    // Transform to projection coordinate.
    Vector4 projectionToWorld = (_mainCamera.projectionMatrix.inverse * viewSpace);

    // Perspective divide.
    projectionToWorld /= projectionToWorld.w;

    // Z-component is backwards in Unity.
    projectionToWorld.z = -projectionToWorld.z;

    // Transform from camera space to world space.
    worldPosition = _mainCamera.transform.position + _mainCamera.transform.TransformVector(projectionToWorld);

    return worldPosition;
}


答: In C , false value is represented by 0 whereas any nonzero value indicates true.  In this loop --i; acts as a condition. When i  becomes 0, it acts as a false Boolean value and the loop terminates. </p>

Title: for loop condition in 2nd clause and no condition in 3rd clause


问:
how to fix the issue "Command /bin/sh failed with exit code 1" in iphone
I used a cocoa static library in my application. When I compile my library I got the following error:

```<code>Shell Script invocation error:can't open input file:
/Users/sijuthomas/Library/Developer/Xcode/DerivedData/SCXML2-
    bbttehupryhijphhjdiemcytkvgy/Build/Products/Debug-iphonesimulator/
    libSCXMLParser.a (No such file or directory)
Command /bin/sh failed with exit code 1
</code>```

How can I fix this?

答:
The only thing worked for me:

1) Delete Derived Data with CleanMyMac: System Junk -> Xcode Junk -> Xcode Derived Data

Deleting Derived Data with CleanMyMac

2) Then in Xcode: Product -> Clean

Body:
I used a cocoa static library in my application. When I compile my library I got the following error:

Shell Script invocation error:can't open input file:
/Users/sijuthomas/Library/Developer/Xcode/DerivedData/SCXML2-
    bbttehupryhijphhjdiemcytkvgy/Build/Products/Debug-iphonesimulator/
    libSCXMLParser.a (No such file or directory)
Command /bin/sh failed with exit code 1

How can I fix this?


问:
How to pass several list of arguments to @click.option
I want to call a python script through the command line with this kind of parameter (list could be any size, eg with 3):

```<code>python test.py --option1 ["o11", "o12", "o13"] --option2 ["o21", "o22", "o23"]
</code>```

using click. From the docs, it is not stated anywhere that we can use a list as parameter to @click.option

And when I try to do this:

```<code>#!/usr/bin/env python
import click

@click.command(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('--option', default=[])
def do_stuff(option):

    return

# do stuff
if __name__ == '__main__':
    do_stuff()
</code>```

in my test.py, by calling it from the command line:

```<code>python test.py --option ["some option", "some option 2"]
</code>```

I get an error:

Error: Got unexpected extra argument (some option 2])

I can't really use variadic arguments as only 1 variadic arguments per command is allowed (http://click.pocoo.org/5/arguments/#variadic-arguments)

So if anyone can point me to the right direction (using click preferably) it would be very much appreciated.

答:
You can coerce click into taking multiple list arguments, if the lists are formatted as a string literals of python lists by using a custom option class like:

Custom Class:

```<code>import click
import ast

class PythonLiteralOption(click.Option):

    def type_cast_value(self, ctx, value):
        try:
            return ast.literal_eval(value)
        except:
            raise click.BadParameter(value)
</code>```

This class will use Python's Abstract Syntax Tree module to parse the parameter as a python literal.

Custom Class Usage:

To use the custom class, pass the cls parameter to @click.option() decorator like:

```<code>@click.option('--option1', cls=PythonLiteralOption, default=[])
</code>```

How does this work?

This works because click is a well designed OO framework. The @click.option() decorator usually instantiates a click.Option object but allows this behavior to be over ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Option in our own class and over ride the desired methods.

In this case we over ride click.Option.type_cast_value() and then call ast.literal_eval() to parse the list.

Test Code:

```<code>@click.command(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('--option1', cls=PythonLiteralOption, default=[])
@click.option('--option2', cls=PythonLiteralOption, default=[])
def cli(option1, option2):
    click.echo("Option 1, type: {}  value: {}".format(
        type(option1), option1))
    click.echo("Option 2, type: {}  value: {}".format(
        type(option2), option2))

# do stuff
if __name__ == '__main__':
    import shlex
    cli(shlex.split(
        '''--option1 '["o11", "o12", "o13"]'
        --option2 '["o21", "o22", "o23"]' '''))
</code>```

Test Results:

```<code>Option 1, type: <type 'list'>  value: ['o11', 'o12', 'o13']
Option 2, type: <type 'list'>  value: ['o21', 'o22', 'o23']
</code>```

Body:
I want to call a python script through the command line with this kind of parameter (list could be any size, eg with 3):

python test.py --option1 ["o11", "o12", "o13"] --option2 ["o21", "o22", "o23"]

using click. From the docs, it is not stated anywhere that we can use a list as parameter to @click.option

And when I try to do this:

#!/usr/bin/env python
import click

@click.command(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('--option', default=[])
def do_stuff(option):

    return

# do stuff
if __name__ == '__main__':
    do_stuff()

in my test.py, by calling it from the command line:

python test.py --option ["some option", "some option 2"]

I get an error:

Error: Got unexpected extra argument (some option 2])

I can't really use variadic arguments as only 1 variadic arguments per command is allowed (http://click.pocoo.org/5/arguments/#variadic-arguments)

So if anyone can point me to the right direction (using click preferably) it would be very much appreciated.

Body:
You can coerce click into taking multiple list arguments, if the lists are formatted as a string literals of python lists by using a custom option class like:

Custom Class:

import click
import ast

class PythonLiteralOption(click.Option):

    def type_cast_value(self, ctx, value):
        try:
            return ast.literal_eval(value)
        except:
            raise click.BadParameter(value)

This class will use Python's Abstract Syntax Tree module to parse the parameter as a python literal.

Custom Class Usage:

To use the custom class, pass the cls parameter to @click.option() decorator like:

@click.option('--option1', cls=PythonLiteralOption, default=[])

How does this work?

This works because click is a well designed OO framework. The @click.option() decorator usually instantiates a click.Option object but allows this behavior to be over ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Option in our own class and over ride the desired methods.

In this case we over ride click.Option.type_cast_value() and then call ast.literal_eval() to parse the list.

Test Code:

@click.command(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('--option1', cls=PythonLiteralOption, default=[])
@click.option('--option2', cls=PythonLiteralOption, default=[])
def cli(option1, option2):
    click.echo("Option 1, type: {}  value: {}".format(
        type(option1), option1))
    click.echo("Option 2, type: {}  value: {}".format(
        type(option2), option2))

# do stuff
if __name__ == '__main__':
    import shlex
    cli(shlex.split(
        '''--option1 '["o11", "o12", "o13"]'
        --option2 '["o21", "o22", "o23"]' '''))

Test Results:

Option 1, type: <type 'list'>  value: ['o11', 'o12', 'o13']
Option 2, type: <type 'list'>  value: ['o21', 'o22', 'o23']


问:
Ignoring the nth appearance of a letter
I'm working on key columnar transposition cipher,

```<code>  for(int i = 0; i < column; i++){
      position = keyWord.indexOf(sorted_key[i]);
  }
</code>```

Keyword is: analyst

sorted_key is: {a, a, l, n, s, t, y}

For letter 'a' it will only see index 0 (the first appearance) and it will always ignore any other occurrence of the letter. How to fix that?
I want it to see any other occurrence after the first one and so on

Thanks

答:
Here an example method</p>

```<code>public static void findIndexes(){
    String searchableString = "don’t be evil.being evil is bad";
    String keyword = "be";

    int index = searchableString.indexOf(keyword);
    while (index >=0){
        System.out.println("Index : "+index);
        index = searchableString.indexOf(keyword, index+keyword.length())   ;
    }

}
</code>```

Title: Ignoring the nth appearance of a letter

Body:
I'm working on key columnar transposition cipher,

  for(int i = 0; i < column; i++){
      position = keyWord.indexOf(sorted_key[i]);
  }

Keyword is: analyst

sorted_key is: {a, a, l, n, s, t, y}

For letter 'a' it will only see index 0 (the first appearance) and it will always ignore any other occurrence of the letter. How to fix that?
I want it to see any other occurrence after the first one and so on

Thanks

Body:
Here an example method

public static void findIndexes(){
    String searchableString = "don’t be evil.being evil is bad";
    String keyword = "be";

    int index = searchableString.indexOf(keyword);
    while (index >=0){
        System.out.println("Index : "+index);
        index = searchableString.indexOf(keyword, index+keyword.length())   ;
    }

}


问:
Do I have to use "firebase deploy" after each change?
I'm still new to web development and I'm using Firebase to handle all my data right now.

I have everything up and running, but how do I make it so my Firebase website updates whenever I make a change to my files? Do I have to manually call firebase deploy after each change in order to see the updated site?

答:
I'm working on a Angular 4 app with Firebase as a backend, so the steps are</p>

```<code>$ ng build --prod
$ firebase deploy
</code>```

Body:
I'm working on a Angular 4 app with Firebase as a backend, so the steps are

$ ng build --prod
$ firebase deploy


问:
Html.Dropdownlist values when using repository classes
Until now I have used the Model class to embed list of related values to render as DropDownList in the view. For example, suppose I have a Contact model class that has a ContactType property in it

```<code>public class Contact {
    ...
    public int ContactTypeID { get; set; }
    ...
}
</code>```

ContactTypeID reference a row in a database table that contains all the contact types like Customer, Supplier, etc. I have used successfully until now a property of the Contact class called, for example, ContactTypeList as in the following sample

```<code>public IEnumerable<SelectListItem> ContactTypeList {
    get {
        return GetContactTypeList().Select(
            t => new SelectListItem { Text = t.Description,
                 Value = t.ContactTypeID.ToString() });
    }
}
</code>```

This way when using strong typed views I can do the following way

```<code><%: Html.DropDownListFor( model => model.ContactTypeID, Model.ContactTypeList, new {} )%>
</code>```

This method works wothout any problem but is not completely clean from the SoC point of view.

In a new project I am starting I am using the repository pattern and StructureMap as the DI/IoC tool and so the model class, does not have anymore a reference to the repository class that is getting the data from the underlying data store.

I know that I can always use the controller and the ViewData/ViewBag to get these lists to pass in the views but I was wondering if this is a good way to achieve the scope.

How are you doing in your projects? What is the best way to achieve the result and having the code remain clean?

Thanks for helping

答:
In my projects I use view models and the controller to manipulate the model:

Model:

```<code>public class ContactViewModel
{
    public int ContactTypeID { get; set; }
    public IEnumerable<SelectListItem> ContactTypeList { get; set; }
}
</code>```

Controller:

```<code>public class ContactsController
{
    private readonly IContactsRepository _repository;
    public ContactsController(IContactsRepository repository)
    {
        _repository = repository;
    }

    [AutoMap(typeof(Contact), typeof(ContactViewModel))]
    public ActionResult Index()
    {
        var model = _repository.GetContacts();
        return View(model);
    }
}
</code>```

The AutoMap attribute used there is an action filter which will execute after the controller action and it will use AutoMapper to replace the model passed to the view (Contact) with the corresponding view model (ContactViewModel). You may see it in action in a sample project structure I wrote.

Now obviously if you are going to show this contacts drop down list all over your project it deserves a separate controller and a child action which will be reused across your view with the Html.Action helper.

Body:
Until now I have used the Model class to embed list of related values to render as DropDownList in the view. For example, suppose I have a Contact model class that has a ContactType property in it

public class Contact {
    ...
    public int ContactTypeID { get; set; }
    ...
}

ContactTypeID reference a row in a database table that contains all the contact types like Customer, Supplier, etc. I have used successfully until now a property of the Contact class called, for example, ContactTypeList as in the following sample

public IEnumerable<SelectListItem> ContactTypeList {
    get {
        return GetContactTypeList().Select(
            t => new SelectListItem { Text = t.Description,
                 Value = t.ContactTypeID.ToString() });
    }
}

This way when using strong typed views I can do the following way

<%: Html.DropDownListFor( model => model.ContactTypeID, Model.ContactTypeList, new {} )%>

This method works wothout any problem but is not completely clean from the SoC point of view.

In a new project I am starting I am using the repository pattern and StructureMap as the DI/IoC tool and so the model class, does not have anymore a reference to the repository class that is getting the data from the underlying data store.

I know that I can always use the controller and the ViewData/ViewBag to get these lists to pass in the views but I was wondering if this is a good way to achieve the scope.

How are you doing in your projects? What is the best way to achieve the result and having the code remain clean?

Thanks for helping

Body:
In my projects I use view models and the controller to manipulate the model:

Model:

public class ContactViewModel
{
    public int ContactTypeID { get; set; }
    public IEnumerable<SelectListItem> ContactTypeList { get; set; }
}

Controller:

public class ContactsController
{
    private readonly IContactsRepository _repository;
    public ContactsController(IContactsRepository repository)
    {
        _repository = repository;
    }

    [AutoMap(typeof(Contact), typeof(ContactViewModel))]
    public ActionResult Index()
    {
        var model = _repository.GetContacts();
        return View(model);
    }
}

The AutoMap attribute used there is an action filter which will execute after the controller action and it will use AutoMapper to replace the model passed to the view (Contact) with the corresponding view model (ContactViewModel). You may see it in action in a sample project structure I wrote.

Now obviously if you are going to show this contacts drop down list all over your project it deserves a separate controller and a child action which will be reused across your view with the Html.Action helper.