问:
Download File on Webpage via Windows CMD/Power Shell
just as the title states, I'd like to download a file from the internet, specifically the download on this webpage. I have looked into using Invoke-WebRequest, curl, and certutil. All of these options download the HTML of the site. The specific URL of the download looks like this: https://bluetoothinstaller.com/bluetooth-command-line-tools/BluetoothCLTools-1.2.0.56.exe.

Calling things like the following just downloads the HTML:

```<code>Invoke-WebRequest -Uri 'https://bluetoothinstaller.com/bluetooth-command-line-tools/BluetoothCLTools-1.2.0.56.exe' -OutFile 'test.exe'
</code>```

Alternatively, if anyone knows how to download the link via the HTML, please do share.

I'd prefer it if the solution did not require any additional software, but am flexible.

Thanks!

答:
Looking at some code I wrote near the end of last year and I found this line:

```<code>(New-Object System.Net.WebClient).DownloadFile($URL, $ZipFile)
</code>```

In my case I was trying to download the latest SQLite and it worked.  In your case you will probably want to rename the $ZipFile variable to something like $ExeFile.

The command to build the file path/name, and define where I wanted the file saved, was this:

```<code>$ZipFile = "$PSScriptRoot\$(Split-Path -Path $URL -Leaf)"
</code>```

As for extracting the file's download path form a webpage, I haven't done that yet.  It is something aim to do but it will be awhile before I get around to trying to figure that out.

Body:
just as the title states, I'd like to download a file from the internet, specifically the download on this webpage. I have looked into using Invoke-WebRequest, curl, and certutil. All of these options download the HTML of the site. The specific URL of the download looks like this: https://bluetoothinstaller.com/bluetooth-command-line-tools/BluetoothCLTools-1.2.0.56.exe.

Calling things like the following just downloads the HTML:

Invoke-WebRequest -Uri 'https://bluetoothinstaller.com/bluetooth-command-line-tools/BluetoothCLTools-1.2.0.56.exe' -OutFile 'test.exe'

Alternatively, if anyone knows how to download the link via the HTML, please do share.

I'd prefer it if the solution did not require any additional software, but am flexible.

Thanks!

Body:
Looking at some code I wrote near the end of last year and I found this line:

(New-Object System.Net.WebClient).DownloadFile($URL, $ZipFile)

In my case I was trying to download the latest SQLite and it worked.  In your case you will probably want to rename the $ZipFile variable to something like $ExeFile.

The command to build the file path/name, and define where I wanted the file saved, was this:

$ZipFile = "$PSScriptRoot\$(Split-Path -Path $URL -Leaf)"

As for extracting the file's download path form a webpage, I haven't done that yet.  It is something aim to do but it will be awhile before I get around to trying to figure that out.


来源: stackexchange

问:
Hide navigation bar while popup menu is showing
My application works in full screen mode. Below code to hide navigation bar.

```<code>   public static void hideDefaultControls(@NonNull final Activity activity) {
        activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        final Window window = activity.getWindow();

        if (window == null) {
            return;
        }

        final View decorView = window.getDecorView();

        if (decorView != null) {
            int uiOptions = decorView.getSystemUiVisibility();

            if (Build.VERSION.SDK_INT >= 14) {
                uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
            }

            if (Build.VERSION.SDK_INT >= 16) {
                uiOptions |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            }

            if (Build.VERSION.SDK_INT >= 19) {
                uiOptions |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            }

            decorView.setSystemUiVisibility(uiOptions);
        }
    }

android.widget.PopupMenu;

PopupMenu popupMenu = new PopupMenu(context, anchor);

//init code...
popupMenu.show();
</code>```

I want have full screen mode while popup menu is showing. I'm trying to call hideDefaultControls() method after popup shown, but controls is hiding only after popup hidden.

答:
Because PopupMenu use new DecorView (PopupDecorView), try:</p>
```<code>@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus)
{
    fullSceen(getWindow().getDecorView());
}
else {
    try {
        Object wmgInstance = Class.forName("android.view.WindowManagerGlobal").getMethod("getInstance").invoke(null);
        Field viewsField = Class.forName("android.view.WindowManagerGlobal").getDeclaredField("mViews");

        viewsField.setAccessible(true);
        ArrayList<View> views = (ArrayList<View>) viewsField.get(wmgInstance);
        for (View view: views) {
            fullSceen(view);

            view.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    fullSceen(view);
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    AppUtils.console(this,TAG, "hasFocus == false");
}
}
private void fullSceen(View view){
view.setSystemUiVisibility(
        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My application works in full screen mode. Below code to hide navigation bar.

   public static void hideDefaultControls(@NonNull final Activity activity) {
        activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        final Window window = activity.getWindow();

        if (window == null) {
            return;
        }

        final View decorView = window.getDecorView();

        if (decorView != null) {
            int uiOptions = decorView.getSystemUiVisibility();

            if (Build.VERSION.SDK_INT >= 14) {
                uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
            }

            if (Build.VERSION.SDK_INT >= 16) {
                uiOptions |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            }

            if (Build.VERSION.SDK_INT >= 19) {
                uiOptions |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            }

            decorView.setSystemUiVisibility(uiOptions);
        }
    }

android.widget.PopupMenu;

PopupMenu popupMenu = new PopupMenu(context, anchor);

//init code...
popupMenu.show();

I want have full screen mode while popup menu is showing. I'm trying to call hideDefaultControls() method after popup shown, but controls is hiding only after popup hidden.

Body:
Because PopupMenu use new DecorView (PopupDecorView), try:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus)
{
    fullSceen(getWindow().getDecorView());
}
else {
    try {
        Object wmgInstance = Class.forName("android.view.WindowManagerGlobal").getMethod("getInstance").invoke(null);
        Field viewsField = Class.forName("android.view.WindowManagerGlobal").getDeclaredField("mViews");

        viewsField.setAccessible(true);
        ArrayList<View> views = (ArrayList<View>) viewsField.get(wmgInstance);
        for (View view: views) {
            fullSceen(view);

            view.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    fullSceen(view);
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    AppUtils.console(this,TAG, "hasFocus == false");
}
}
private void fullSceen(View view){
view.setSystemUiVisibility(
        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}

ContentLicense: CC BY-SA 4.0


问:
Hive date (field name - trans_dt) conversion from "YYYYMMDD" to "YYYY-MM-DD" (field name - dt) and querying based on the newly created field
I am trying to query data for yesterday (or last 24 hrs) in Hive but the filter trans_dt>=date_sub(current_date(),1) only works when the trans_dt format is "YYYY-MM-DD".  The current format of trans_dt is "YYYYMMDD" and so I am converting it to "YYYY-MM-DD" by using the below concat command.

select concat(substring(trans_dt,1,4),'-',substring(trans_dt,5,2),'-',substring(trans_dt,7,2)) as dt from xyz

But now I am not sure how to add the ">=date_sub(current_date(),1)" condition on the newly created field "dt".  Its failing as it is not a field in the table.

I am new to this querying in Hive and am not sure if I am totally off and there is an easier way?  Please advise.  All my online searches have only told me that there is no direct function in Hive to convert the date format from "YYYYMMDD" to "YYYY-MM-DD".

答:
have you tried this one?

```<code>CAST(CAST( trans_dt AS TIMESTAMP(0)) AS DATE format 'YYYY-MM-DD') as TRANS_DATE
</code>```

using CAST can be the solution for changing the date format

Body:
have you tried this one?

CAST(CAST( trans_dt AS TIMESTAMP(0)) AS DATE format 'YYYY-MM-DD') as TRANS_DATE

using CAST can be the solution for changing the date format


问:
Exception when attempting to create Namespaced Pod - Bad Request
I'm working with Airflow DAG and Kubernetes for the first time.
I have a Python script that connects to AWS S3 and reads some files. This works fine if I run it in a Docker container/image using bash. But when I try to run this docker from an airflow task using a K8s pod, I get the following error (I replaced some sensitive values with XXXXX)

```<code>    [2022-02-08 22:48:55,795] {kubernetes_pod.py:365} INFO - creating pod with labels {'dag_id': 'ECO_CELLS_POLYGON_STORES', 'task_id': 'process_AR', 'execution_date': '2022-02-08T224216.4628350000-e866f2011', 'try_number': '1'} and launcher <airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher object at 0x7f649be71410>
[2022-02-08 22:48:55,812] {pod_launcher.py:93} ERROR - Exception when attempting to create Namespaced Pod: {
  "apiVersion": "v1",
  "kind": "Pod",
  "metadata": {
    "annotations": {},
    "labels": {
      "airflow_version": "2.0.0-astro.8",
      "kubernetes_pod_operator": "True",
      "dag_id": "ECO_CELLS_POLYGON_STORES",
      "task_id": "process_AR",
      "execution_date": "2022-02-08T224216.4628350000-e866f2011",
      "try_number": "1"
    },
    "name": "k8s-pod-ml-operator.3aada8ada8df491ea63e9319bf779d10",
    "namespace": "default"
  },
  "spec": {
    "affinity": {},
    "containers": [
      {
        "args": [],
        "command": [
          "python",
          "main.py"
        ],
        "env": {
          "AWS_ACCESS_KEY_ID": "XXXXXX",
          "AWS_SECRET_ACCESS_KEY": "***",
          "AWS_BUCKET_NAME": "XXXXXX-dev",
          "SNOWFLAKE_SERVER": "XXXXXX",
          "SNOWFLAKE_LOGIN": "XXXXXX",
          "SNOWFLAKE_PASSWORD": "***",
          "SNOWFLAKE_ACCOUNT": "XXXXXX",
          "SNOWFLAKE_DATABASE": "XXXXXX",
          "SNOWFLAKE_WAREHOUSE": "XXXXXX",
          "COUNTRY": "AR",
          "S3_PROJECT": "ecom_polygon_stores",
          "S3_TEAM_VERTICAL": "ecommerce"
        },
        "envFrom": [],
        "image": "ecom_polygon_stores:v1.0.7",
        "imagePullPolicy": "Never",
        "name": "base",
        "ports": [],
        "resources": {},
        "volumeMounts": []
      }
    ],
    "hostNetwork": false,
    "imagePullSecrets": [],
    "initContainers": [],
    "restartPolicy": "Never",
    "securityContext": {},
    "serviceAccountName": "default",
    "tolerations": [],
    "volumes": []
  }
}
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/airflow/providers/cncf/kubernetes/utils/pod_launcher.py", line 89, in run_pod_async
    body=sanitized_pod, namespace=pod.metadata.namespace, **kwargs
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/api/core_v1_api.py", line 6174, in create_namespaced_pod
    (data) = self.create_namespaced_pod_with_http_info(namespace, body, **kwargs)  # noqa: E501
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/api/core_v1_api.py", line 6265, in create_namespaced_pod_with_http_info
    collection_formats=collection_formats)
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/api_client.py", line 345, in call_api
    _preload_content, _request_timeout)
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/api_client.py", line 176, in __call_api
    _request_timeout=_request_timeout)
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/api_client.py", line 388, in request
    body=body)
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/rest.py", line 278, in POST
    body=body)
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/rest.py", line 231, in request
    raise ApiException(http_resp=r)
kubernetes.client.rest.ApiException: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'X-Kubernetes-Pf-Flowschema-Uid': '319700db-6333-4a4d-885c-1f45a0cd13a3', 'X-Kubernetes-Pf-Prioritylevel-Uid': '4d5b12e4-65e9-4ab9-ad63-de6f29ca0b6d', 'Date': 'Tue, 08 Feb 2022 22:48:55 GMT', 'Content-Length': '487'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Pod in version \"v1\" cannot be handled as a Pod: v1.Pod.Spec: v1.PodSpec.Containers: []v1.Container: v1.Container.Env: []v1.EnvVar: decode slice: expect [ or n, but found {, error found in #10 byte of ...|, \"env\": {\"AWS_ACCES|..., bigger context ...|s\": [], \"command\": [\"python\", \"main.py\"], \"env\": {\"AWS_ACCESS_KEY_ID\": \"AXXXXXXXXXXXXXXXXXX6\", \"AWS_|...","reason":"BadRequest","code":400}
</code>```

I'm not sure where to go from here... From what I'm reading the error says it expected a [ instead of a { in "env": {"AWS_ACCESS_KEY_ID"... But I'm not sure how to correct that since I pass those parameters like this:

```<code>        self.env_vars = {
            'AWS_ACCESS_KEY_ID': s3_connection.login,
            'AWS_SECRET_ACCESS_KEY': s3_connection.password,
            'AWS_BUCKET_NAME': bucket_name,
            'SNOWFLAKE_SERVER': str(snowflake_connection.host),
            'SNOWFLAKE_LOGIN': str(snowflake_connection.login),
            'SNOWFLAKE_PASSWORD': str(snowflake_connection.password),
            'SNOWFLAKE_ACCOUNT': str(snowflake_connection.extra_dejson['account']),
            'SNOWFLAKE_DATABASE': str(snowflake_connection.extra_dejson['database']),
            'SNOWFLAKE_WAREHOUSE': str(snowflake_connection.extra_dejson['warehouse']),
            'COUNTRY': code,
            'S3_PROYECT': s3_project,
            'S3_TEAM_VERTICAL': s3_team_vertical
        }
</code>```

Any suggestions?

答:
Your env: is malformed; one can see this in two different ways: (1) env: in the PodSpec is a list of {name: "", value: ""} items (2) the structure emitted in the error message is malformed regardless: "env": {"AWS_ACCESS_KEY_ID": "ASIAWCMTKGYGDU6KEOD6", "AWS_|... as there is no such  shape of data as {"":"",""

I don't have any Airflow reference documentation links handy, but you'd want to check them to ensure self.env_vars is what Airflow expects it to be, since python places the entire burden of correctness upon the programmer

Body:
I'm working with Airflow DAG and Kubernetes for the first time.
I have a Python script that connects to AWS S3 and reads some files. This works fine if I run it in a Docker container/image using bash. But when I try to run this docker from an airflow task using a K8s pod, I get the following error (I replaced some sensitive values with XXXXX)

    [2022-02-08 22:48:55,795] {kubernetes_pod.py:365} INFO - creating pod with labels {'dag_id': 'ECO_CELLS_POLYGON_STORES', 'task_id': 'process_AR', 'execution_date': '2022-02-08T224216.4628350000-e866f2011', 'try_number': '1'} and launcher <airflow.providers.cncf.kubernetes.utils.pod_launcher.PodLauncher object at 0x7f649be71410>
[2022-02-08 22:48:55,812] {pod_launcher.py:93} ERROR - Exception when attempting to create Namespaced Pod: {
  "apiVersion": "v1",
  "kind": "Pod",
  "metadata": {
    "annotations": {},
    "labels": {
      "airflow_version": "2.0.0-astro.8",
      "kubernetes_pod_operator": "True",
      "dag_id": "ECO_CELLS_POLYGON_STORES",
      "task_id": "process_AR",
      "execution_date": "2022-02-08T224216.4628350000-e866f2011",
      "try_number": "1"
    },
    "name": "k8s-pod-ml-operator.3aada8ada8df491ea63e9319bf779d10",
    "namespace": "default"
  },
  "spec": {
    "affinity": {},
    "containers": [
      {
        "args": [],
        "command": [
          "python",
          "main.py"
        ],
        "env": {
          "AWS_ACCESS_KEY_ID": "XXXXXX",
          "AWS_SECRET_ACCESS_KEY": "***",
          "AWS_BUCKET_NAME": "XXXXXX-dev",
          "SNOWFLAKE_SERVER": "XXXXXX",
          "SNOWFLAKE_LOGIN": "XXXXXX",
          "SNOWFLAKE_PASSWORD": "***",
          "SNOWFLAKE_ACCOUNT": "XXXXXX",
          "SNOWFLAKE_DATABASE": "XXXXXX",
          "SNOWFLAKE_WAREHOUSE": "XXXXXX",
          "COUNTRY": "AR",
          "S3_PROJECT": "ecom_polygon_stores",
          "S3_TEAM_VERTICAL": "ecommerce"
        },
        "envFrom": [],
        "image": "ecom_polygon_stores:v1.0.7",
        "imagePullPolicy": "Never",
        "name": "base",
        "ports": [],
        "resources": {},
        "volumeMounts": []
      }
    ],
    "hostNetwork": false,
    "imagePullSecrets": [],
    "initContainers": [],
    "restartPolicy": "Never",
    "securityContext": {},
    "serviceAccountName": "default",
    "tolerations": [],
    "volumes": []
  }
}
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/airflow/providers/cncf/kubernetes/utils/pod_launcher.py", line 89, in run_pod_async
    body=sanitized_pod, namespace=pod.metadata.namespace, **kwargs
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/api/core_v1_api.py", line 6174, in create_namespaced_pod
    (data) = self.create_namespaced_pod_with_http_info(namespace, body, **kwargs)  # noqa: E501
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/api/core_v1_api.py", line 6265, in create_namespaced_pod_with_http_info
    collection_formats=collection_formats)
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/api_client.py", line 345, in call_api
    _preload_content, _request_timeout)
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/api_client.py", line 176, in __call_api
    _request_timeout=_request_timeout)
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/api_client.py", line 388, in request
    body=body)
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/rest.py", line 278, in POST
    body=body)
  File "/usr/local/lib/python3.7/site-packages/kubernetes/client/rest.py", line 231, in request
    raise ApiException(http_resp=r)
kubernetes.client.rest.ApiException: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'X-Kubernetes-Pf-Flowschema-Uid': '319700db-6333-4a4d-885c-1f45a0cd13a3', 'X-Kubernetes-Pf-Prioritylevel-Uid': '4d5b12e4-65e9-4ab9-ad63-de6f29ca0b6d', 'Date': 'Tue, 08 Feb 2022 22:48:55 GMT', 'Content-Length': '487'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Pod in version \"v1\" cannot be handled as a Pod: v1.Pod.Spec: v1.PodSpec.Containers: []v1.Container: v1.Container.Env: []v1.EnvVar: decode slice: expect [ or n, but found {, error found in #10 byte of ...|, \"env\": {\"AWS_ACCES|..., bigger context ...|s\": [], \"command\": [\"python\", \"main.py\"], \"env\": {\"AWS_ACCESS_KEY_ID\": \"AXXXXXXXXXXXXXXXXXX6\", \"AWS_|...","reason":"BadRequest","code":400}

I'm not sure where to go from here... From what I'm reading the error says it expected a [ instead of a { in "env": {"AWS_ACCESS_KEY_ID"... But I'm not sure how to correct that since I pass those parameters like this:

        self.env_vars = {
            'AWS_ACCESS_KEY_ID': s3_connection.login,
            'AWS_SECRET_ACCESS_KEY': s3_connection.password,
            'AWS_BUCKET_NAME': bucket_name,
            'SNOWFLAKE_SERVER': str(snowflake_connection.host),
            'SNOWFLAKE_LOGIN': str(snowflake_connection.login),
            'SNOWFLAKE_PASSWORD': str(snowflake_connection.password),
            'SNOWFLAKE_ACCOUNT': str(snowflake_connection.extra_dejson['account']),
            'SNOWFLAKE_DATABASE': str(snowflake_connection.extra_dejson['database']),
            'SNOWFLAKE_WAREHOUSE': str(snowflake_connection.extra_dejson['warehouse']),
            'COUNTRY': code,
            'S3_PROYECT': s3_project,
            'S3_TEAM_VERTICAL': s3_team_vertical
        }

Any suggestions?


问:
What does '&' do in C/C++ and what is its equivalent operator in perl?
I'm writing a perl implementation of a protocol whose specification is given for C/C++ but I don't know much C.

What does the condition if ((flags & 0x400) != 0) mean? How do I do that in perl?

Is if ($flags == "\x400") correct?

答: & is the bitwise and operator, basically this is a test to see if a specific bit is set in the flags. See the perl equivalents here: http://perldoc.perl.org/perlop.html#Bitwise-And


问:
Can't Capture cdb.exe Debuggee Output With LaunchProcess
I am launching cdb.exe (Microsoft Console Debugger) as a child process of my C++ application using the following method:

https://stackoverflow.com/a/66147288/6531253

cdb.exe, in turn, launches a separate application to debug. This mostly works fine and I get the debugging output from cdb, but I do not receive any output from the process it is debugging through the pipe at all.

If I run the same command inside a cmd prompt, it shows the output from the debuggee application fine. For example:

```<code>C:\Users\Drago\source\repos\WinDebugQt\WinDebugQt>"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe" -o "DummyProgram.exe"

Microsoft (R) Windows Debugger Version 10.0.19041.685 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

CommandLine: "DummyProgram.exe"

************* Path validation summary **************
Response                         Time (ms)     Location
Deferred                                       srv*
Symbol search path is: srv*
Executable search path is:
ModLoad: 00007ff6`ede30000 00007ff6`ede57000   DummyProgram.exe
ModLoad: 00007ffa`dee90000 00007ffa`df085000   ntdll.dll
ModLoad: 00007ffa`ddac0000 00007ffa`ddb7e000   C:\WINDOWS\System32\KERNEL32.DLL
ModLoad: 00007ffa`dc920000 00007ffa`dcbe8000   C:\WINDOWS\System32\KERNELBASE.dll
ModLoad: 00007ffa`9b230000 00007ffa`9b23f000   C:\WINDOWS\SYSTEM32\VCRUNTIME140_1D.dll
ModLoad: 00007ffa`19650000 00007ffa`19732000   C:\WINDOWS\SYSTEM32\MSVCP140D.dll
ModLoad: 00007ffa`19480000 00007ffa`19647000   C:\WINDOWS\SYSTEM32\ucrtbased.dll
ModLoad: 00007ffa`31e00000 00007ffa`31e2b000   C:\WINDOWS\SYSTEM32\VCRUNTIME140D.dll
(8adc.988c): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00007ffa`def606b0 cc              int     3
0:000> gh

INITIALIZING DUMMY PROGRAM!
00007FF6EDE422A000007FF6EDE4231000007FF6EDE41055(8adc.988c): Break instruction exception - code 80000003 (first chance)
*** WARNING: Unable to verify checksum for DummyProgram.exe
DummyProgram!debuggerCmdSetCallbacks:
00007ff6`ede426b9 cc              int     3
0:000>
</code>```

The output coming from the pipe in my C++ application is missing "INITIALIZING DUMMY PROGRAM" from the debuggee:

```<code>Microsoft (R) Windows Debugger Version 10.0.19041.685 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

CommandLine: DummyProgram.exe

************* Path validation summary **************
Response                         Time (ms)     Location
Deferred                                       srv*
Symbol search path is: srv*
Executable search path is:
ModLoad: 00007ff6`ede30000 00007ff6`ede57000   DummyProgram.exe
ModLoad: 00007ffa`dee90000 00007ffa`df085000   ntdll.dll
ModLoad: 00007ffa`ddac0000 00007ffa`ddb7e000   C:\WINDOWS\System32\KERNEL32.DLL
ModLoad: 00007ffa`dc920000 00007ffa`dcbe8000   C:\WINDOWS\System32\KERNELBASE.dll
ModLoad: 00007ffa`184c0000 00007ffa`18687000   C:\WINDOWS\SYSTEM32\ucrtbased.dll
ModLoad: 00007ffa`18690000 00007ffa`18772000   C:\WINDOWS\SYSTEM32\MSVCP140D.dll
ModLoad: 00007ffa`9b230000 00007ffa`9b23f000   C:\WINDOWS\SYSTEM32\VCRUNTIME140_1D.dll
ModLoad: 00007ffa`32a60000 00007ffa`32a8b000   C:\WINDOWS\SYSTEM32\VCRUNTIME140D.dll
(8be0.8978): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00007ffa`def606b0 cc              int     3
0:000> gh
(8be0.8978): Break instruction exception - code 80000003 (first chance)
*** WARNING: Unable to verify checksum for DummyProgram.exe
DummyProgram!debuggerCmdSetCallbacks:
00007ff6`ede426b9 cc              int     3
0:000>
</code>```

Does anyone know why the behavior is different than when done in a cmd prompt and  how I can get that output from my C++ application?

Everything comes through stdout when running in the cmd prompt case so it's very odd that the debuggee output is missing.

答:
As a workaround, I found a way to at least get the output. Rather than having cdb.exe launch the process, I launch the process myself in the same program that I am launching cdb.exe from. I am then having the launched cdb.exe attach to the already running process.

When done this way, I can read from the pipe I set up for the original process and the output comes through that way. I can also elect to not set up the pipes for the debuggee process, in which case they come through normally through the cmd window opened for it. That way they can be seen in the separate window as usual (which wasn't happening when launched from the programmatically launched cdb.exe).

This is not as ideal as all the output coming through the same pipe, but it's a lot better than nothing.

Body:
I am launching cdb.exe (Microsoft Console Debugger) as a child process of my C++ application using the following method:

https://stackoverflow.com/a/66147288/6531253

cdb.exe, in turn, launches a separate application to debug. This mostly works fine and I get the debugging output from cdb, but I do not receive any output from the process it is debugging through the pipe at all.

If I run the same command inside a cmd prompt, it shows the output from the debuggee application fine. For example:

C:\Users\Drago\source\repos\WinDebugQt\WinDebugQt>"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe" -o "DummyProgram.exe"

Microsoft (R) Windows Debugger Version 10.0.19041.685 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

CommandLine: "DummyProgram.exe"

************* Path validation summary **************
Response                         Time (ms)     Location
Deferred                                       srv*
Symbol search path is: srv*
Executable search path is:
ModLoad: 00007ff6`ede30000 00007ff6`ede57000   DummyProgram.exe
ModLoad: 00007ffa`dee90000 00007ffa`df085000   ntdll.dll
ModLoad: 00007ffa`ddac0000 00007ffa`ddb7e000   C:\WINDOWS\System32\KERNEL32.DLL
ModLoad: 00007ffa`dc920000 00007ffa`dcbe8000   C:\WINDOWS\System32\KERNELBASE.dll
ModLoad: 00007ffa`9b230000 00007ffa`9b23f000   C:\WINDOWS\SYSTEM32\VCRUNTIME140_1D.dll
ModLoad: 00007ffa`19650000 00007ffa`19732000   C:\WINDOWS\SYSTEM32\MSVCP140D.dll
ModLoad: 00007ffa`19480000 00007ffa`19647000   C:\WINDOWS\SYSTEM32\ucrtbased.dll
ModLoad: 00007ffa`31e00000 00007ffa`31e2b000   C:\WINDOWS\SYSTEM32\VCRUNTIME140D.dll
(8adc.988c): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00007ffa`def606b0 cc              int     3
0:000> gh

INITIALIZING DUMMY PROGRAM!
00007FF6EDE422A000007FF6EDE4231000007FF6EDE41055(8adc.988c): Break instruction exception - code 80000003 (first chance)
*** WARNING: Unable to verify checksum for DummyProgram.exe
DummyProgram!debuggerCmdSetCallbacks:
00007ff6`ede426b9 cc              int     3
0:000>

The output coming from the pipe in my C++ application is missing "INITIALIZING DUMMY PROGRAM" from the debuggee:

Microsoft (R) Windows Debugger Version 10.0.19041.685 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

CommandLine: DummyProgram.exe

************* Path validation summary **************
Response                         Time (ms)     Location
Deferred                                       srv*
Symbol search path is: srv*
Executable search path is:
ModLoad: 00007ff6`ede30000 00007ff6`ede57000   DummyProgram.exe
ModLoad: 00007ffa`dee90000 00007ffa`df085000   ntdll.dll
ModLoad: 00007ffa`ddac0000 00007ffa`ddb7e000   C:\WINDOWS\System32\KERNEL32.DLL
ModLoad: 00007ffa`dc920000 00007ffa`dcbe8000   C:\WINDOWS\System32\KERNELBASE.dll
ModLoad: 00007ffa`184c0000 00007ffa`18687000   C:\WINDOWS\SYSTEM32\ucrtbased.dll
ModLoad: 00007ffa`18690000 00007ffa`18772000   C:\WINDOWS\SYSTEM32\MSVCP140D.dll
ModLoad: 00007ffa`9b230000 00007ffa`9b23f000   C:\WINDOWS\SYSTEM32\VCRUNTIME140_1D.dll
ModLoad: 00007ffa`32a60000 00007ffa`32a8b000   C:\WINDOWS\SYSTEM32\VCRUNTIME140D.dll
(8be0.8978): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00007ffa`def606b0 cc              int     3
0:000> gh
(8be0.8978): Break instruction exception - code 80000003 (first chance)
*** WARNING: Unable to verify checksum for DummyProgram.exe
DummyProgram!debuggerCmdSetCallbacks:
00007ff6`ede426b9 cc              int     3
0:000>

Does anyone know why the behavior is different than when done in a cmd prompt and  how I can get that output from my C++ application?

Everything comes through stdout when running in the cmd prompt case so it's very odd that the debuggee output is missing.


问:
Can we use lambda function to reduce the following function?
I would like to ask if the below function could be reduced by using 1 expression with lambda function. I am trying to locate the indices of the price list to see if there is an increase in prices from the previous index</p>
```<code>def increasePrice (prices):
   templist = []
   for x in range (0, len(prices)):
      if (prices [x] < prices [x+1]):
      templist.append(x)
   return templist
</code>```

答:
Note that your code is missing an indentation (after if), missing ), and iterates over the full length of prices, which results in IndexError, since you index prices[x+1] which doesn't exist at the last index. If you fix those, the below list comprehension produces the same outcome.

You could use enumerate to get the indices along with zip to iterate over consecutive elements in a list comprehension:

```<code>templist = [x for (x, p1), p2 in zip(enumerate(prices), prices[1:]) if p1 < p2]
</code>```

You can also enumerate over the zip (thanks @Barmar):

```<code>templist = [x for x, (p1, p2) in enumerate(zip(prices, prices[1:])) if p1 < p2]
</code>```

Body:
I would like to ask if the below function could be reduced by using 1 expression with lambda function. I am trying to locate the indices of the price list to see if there is an increase in prices from the previous index

def increasePrice (prices):
   templist = []
   for x in range (0, len(prices)):
      if (prices [x] < prices [x+1]):
      templist.append(x)
   return templist

Body:
Note that your code is missing an indentation (after if), missing ), and iterates over the full length of prices, which results in IndexError, since you index prices[x+1] which doesn't exist at the last index. If you fix those, the below list comprehension produces the same outcome.

You could use enumerate to get the indices along with zip to iterate over consecutive elements in a list comprehension:

templist = [x for (x, p1), p2 in zip(enumerate(prices), prices[1:]) if p1 < p2]

You can also enumerate over the zip (thanks @Barmar):

templist = [x for x, (p1, p2) in enumerate(zip(prices, prices[1:])) if p1 < p2]


问:
How to view and edit content controls in a docx file in c# winforms
Is there any component to allow end users edit "Content Controls" in a C# Windows Forms desktop application?

I have many complicated Word Documents which are ready for edit and can't create all of them on runtime.

I searched stackoverflow but didn't find anything

Thanks

答:
you need to use  .NET Word component
which is easily installed in VS using

https://www.nuget.org/packages/FreeSpire.Doc/
then you need to include following namespaces

```<code>using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
</code>```

after this you can easily create a new word document , add sections and / or paraghraphs

```<code>Document document = new Document();
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
</code>```

Hope this is what  you are looking for

Body:
you need to use  .NET Word component
which is easily installed in VS using

https://www.nuget.org/packages/FreeSpire.Doc/
then you need to include following namespaces

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

after this you can easily create a new word document , add sections and / or paraghraphs

Document document = new Document();
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();

Hope this is what  you are looking for


问:
Get Laravel collection's item using collection value
Suppose we got a collection from the database like this:

```<code>$projects = Projects::all();
</code>```

Now, for example, I want to get the specific project using the specified column's value. For example, suppose any project has a unique pr_code, Now I want to get an item of collection that pr_code is 1234.

Note = I Know using Projects::where('pr_code', 1234)->first() But I didn't want this. I want use inside collection

How I could do that?

答:
Projects::all() queries all records in projects and returns them as a Collection of Projects models, this could be quite a performance hit.

Projects::where('pr_code', 1234)->get() will query for the specific projects and return a Collection of Projects models that have pr_code of 1234.

Projects::where('pr_code', 1234)->first() will do the same, but return the first as a Projects model.

I recommend naming the model Project rather than the plural Projects. The Laravel model is smart enough to know to use the plural name of the database table.

Body:
Suppose we got a collection from the database like this:

$projects = Projects::all();

Now, for example, I want to get the specific project using the specified column's value. For example, suppose any project has a unique pr_code, Now I want to get an item of collection that pr_code is 1234.

Note = I Know using Projects::where('pr_code', 1234)->first() But I didn't want this. I want use inside collection

How I could do that?


问:
Missing parameter(s): email, password error is occurring on posting data in angular4?
I am new to angular 4. I am working on login page in which I have to post the user information on login.But I am getting error as
"code":"rest_missing_callback_param","message":"Missing parameter(s): email, password" on posting data.Below is my code:

  import { Component, OnInit } from '@angular/core';
import {Http,Response,Headers, RequestOptions} from '@angular/http';
import { Router} from '@angular/router';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

constructor(private http:Http,private router:Router) { }
login(){
this.router.navigate(['login']);
}
     createAuthorizationHeader(headers: Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('ck_543700d9f8c08268d75d3efefb302df4fad70a8f:cs_f1514261bbe154d662eb5053880d40518367c901'));
    headers.append("Content-Type", "application/x-www-form-urlencoded");
  }
onSubmit(userForm:NgForm){
    console.log(userForm.value);
    let headers=new Headers();
     this.createAuthorizationHeader(headers);
const body={
 "email": userForm.value.email,
  "first_name": userForm.value.fname,
  "last_name": userForm.value.lname,
  "username": userForm.value.uname,
  "password": userForm.value.password
}
    console.log(body);
    console.log(headers);
this.http.post('https://www.colourssoftware.com/wordpress/wp-json/wc/v2/customers',body,{
        headers:headers
        })
      .subscribe(
      data => {
              console.log(data);
            },
            err => {
              console.log("ERROR!: ", err);
            }
      );

}
  ngOnInit() {
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <form class="animated wow slideInUp" data-wow-delay=".5s" #regForm="ngForm" (ngSubmit)="onSubmit(regForm)">
                    <input type="text" placeholder="First Name..." required=" " name="fname" ngModel>
                    <input type="text" placeholder="Last Name..." required=" " name="lname" ngModel>
                    <input type="text" placeholder="UserName..." required=" " name="uname" ngModel>
                    <h6 class="animated wow slideInUp" data-wow-delay=".5s">Login information</h6>

                    <input type="email" placeholder="Email Address" required=" " name="email" ngModel>
                    <input type="password" placeholder="Password" required=" " name="password" ngModel>
                    <div class="register-check-box">
                        <div class="check">
                            <label class="checkbox"><input type="checkbox" name="checkbox"><i> </i>I accept the terms and conditions</label>
                        </div>
                    </div>
                    <input type="submit" value="Register">
                </form></code>```

Where I have done the mistake? How can I post the data to the server in angular 4? Please help me.

答:
I know it is a very old question but I'm answering this so that other people might benefit.

```<code>> You should use yoursite.com/wordpress/wp-json/wc/v2/users API instead
> of yoursite.com/wordpress/wp-json/wc/v2/customers
</code>```

when validating user login or registering customers with WordPress rest API.
also, make sure that you have valid authorization set in header.

*** If you want to use yoursite.com/wordpress/wp-json/wc/v2/customers API then you must have that customer account with that same username/password in WordPress then only you will be able to validate as a customer with woocommerce api

Body:
I am new to angular 4. I am working on login page in which I have to post the user information on login.But I am getting error as
"code":"rest_missing_callback_param","message":"Missing parameter(s): email, password" on posting data.Below is my code:

  import { Component, OnInit } from '@angular/core';
import {Http,Response,Headers, RequestOptions} from '@angular/http';
import { Router} from '@angular/router';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

constructor(private http:Http,private router:Router) { }
login(){
this.router.navigate(['login']);
}
     createAuthorizationHeader(headers: Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('ck_543700d9f8c08268d75d3efefb302df4fad70a8f:cs_f1514261bbe154d662eb5053880d40518367c901'));
    headers.append("Content-Type", "application/x-www-form-urlencoded");
  }
onSubmit(userForm:NgForm){
    console.log(userForm.value);
    let headers=new Headers();
     this.createAuthorizationHeader(headers);
const body={
 "email": userForm.value.email,
  "first_name": userForm.value.fname,
  "last_name": userForm.value.lname,
  "username": userForm.value.uname,
  "password": userForm.value.password
}
    console.log(body);
    console.log(headers);
this.http.post('https://www.colourssoftware.com/wordpress/wp-json/wc/v2/customers',body,{
        headers:headers
        })
      .subscribe(
      data => {
              console.log(data);
            },
            err => {
              console.log("ERROR!: ", err);
            }
      );

}
  ngOnInit() {
  }

}

 <form class="animated wow slideInUp" data-wow-delay=".5s" #regForm="ngForm" (ngSubmit)="onSubmit(regForm)">
                    <input type="text" placeholder="First Name..." required=" " name="fname" ngModel>
                    <input type="text" placeholder="Last Name..." required=" " name="lname" ngModel>
                    <input type="text" placeholder="UserName..." required=" " name="uname" ngModel>

Login information

                    <input type="email" placeholder="Email Address" required=" " name="email" ngModel>
                    <input type="password" placeholder="Password" required=" " name="password" ngModel>

                            <input type="checkbox" name="checkbox"> I accept the terms and conditions

                    <input type="submit" value="Register">
                </form>

Where I have done the mistake? How can I post the data to the server in angular 4? Please help me.

Body:
I know it is a very old question but I'm answering this so that other people might benefit.

> You should use yoursite.com/wordpress/wp-json/wc/v2/users API instead
> of yoursite.com/wordpress/wp-json/wc/v2/customers

when validating user login or registering customers with WordPress rest API.
also, make sure that you have valid authorization set in header.

*** If you want to use yoursite.com/wordpress/wp-json/wc/v2/customers API then you must have that customer account with that same username/password in WordPress then only you will be able to validate as a customer with woocommerce api


问:
Running a terminal command inside an iPhone app
Hey guys.
So, I'm trying to have my iPhone app (jailbreaked) run a terminal command, and show the output. For those who don't see what I mean, I want to do the same thing as Cydia does when installing a package (black screen with the command output)

I'm using xCode 4.

Thanks!

答:
Cydia is not directly running external programs: it is linked against libapt-inst, which indirectly runs dpkg to generate some (but not all) of that output.

In general, you just want to render a black text box with some white text, and then use popen to run your external program, freading any data from the pipe into your app to add to the end of the box.

ContentLicense: CC BY-SA 2.5


问:
How to convert binary to hexadecimal using python3
which is the easiest way that i can convert binary number into a hexadecimal number using latest python3?

i tried to convert a binary to number into a hexadecimal using hex() function. but it runs into few errors.

The code that i tried -:

```<code>choice = input("Enter Your Binary Number: ")

def binaryToHex(num):
    answer = hex(num)
    return(num)

print(binaryToHex(choice))
</code>```

error that i faced :

```<code>Traceback (most recent call last):
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 83, in <module>
    print(binaryToHex(choice))
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 80, in binaryToHex
    answer = hex(num)
TypeError: 'str' object cannot be interpreted as an integer
</code>```

EXAMPLE-:

111 --> 7

1010101011 --> 2AB

答:
Method:

Considering you need '2AB' instead of '0x2ab'.

```<code>>>> Hex=lambda num,base:hex(int(num,base))[2:].upper()
>>> Hex('111',2)
'7'
>>> Hex('1010101011',2)
'2AB'
</code>```

Body:
which is the easiest way that i can convert binary number into a hexadecimal number using latest python3?

i tried to convert a binary to number into a hexadecimal using hex() function. but it runs into few errors.

The code that i tried -:

choice = input("Enter Your Binary Number: ")

def binaryToHex(num):
    answer = hex(num)
    return(num)

print(binaryToHex(choice))

error that i faced :

Traceback (most recent call last):
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 83, in <module>
    print(binaryToHex(choice))
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 80, in binaryToHex
    answer = hex(num)
TypeError: 'str' object cannot be interpreted as an integer

EXAMPLE-:

111 --> 7

1010101011 --> 2AB

Body:
Method:

Considering you need '2AB' instead of '0x2ab'.

>>> Hex=lambda num,base:hex(int(num,base))[2:].upper()
>>> Hex('111',2)
'7'
>>> Hex('1010101011',2)
'2AB'


问:
Command prompt not opening in windows 10
I am trying to open the command prompt but if I open it just opens for a second then gets closed. I also use the command prompt for vscode and I am not able to open the terminal in vscode as well. I tried restarting my computer several times but still, the command prompt doesn't open.

Please suggest a solution from which I can open my command prompt

答:
I did have the same problem.
The following method worked for me.

Open Powershell (Admin) and enter:

```<code>echo off
reg delete "HKCU\Console" /f
reg delete "HKCU\Software\Microsoft\Command Processor" /v "AutoRun" /f
reg delete "HKLM\Software\Microsoft\Command Processor" /v "AutoRun" /f
reg delete "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File
Execution Options\cmd.exe" /f
echo done
</code>```

Found this on a comment from Mr. Holman Calda in this video How to Fix Command Prompt(CMD) Not Working/Opening in Windows 10.

Body:
I did have the same problem.
The following method worked for me.

Open Powershell (Admin) and enter:

echo off
reg delete "HKCU\Console" /f
reg delete "HKCU\Software\Microsoft\Command Processor" /v "AutoRun" /f
reg delete "HKLM\Software\Microsoft\Command Processor" /v "AutoRun" /f
reg delete "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File
Execution Options\cmd.exe" /f
echo done

Found this on a comment from Mr. Holman Calda in this video How to Fix Command Prompt(CMD) Not Working/Opening in Windows 10.


问:
How to remove apps from Samsung phone by pushing file with package names with ADB
Several years ago, a friend of mine was working on a Samsung S8 Active. He was trying to remove most of the apps on it so it was just a basic phone. He had some instructions for a Ponderosa system. He was having trouble with several things so I was helping him. We got a list of all the packages on the phone using ADB and then copied them into a text editor. We removed the name of any package that we didn't want and then saved the file and pushed it back onto the phone using ADB again. I'm not certain but there might have been an app or something on the phone that had something to do with it as well but the end result was that only the apps on the list were left on the phone. I believe that we could put a password in on the phone and the apps came back but I'm not 100% sure.

Since then I have lost the papers that had the instructions on them and the place we originally got them from no longer has them either. I have another Samsung S8 Active that needs the same system (or simular) put on it. I know how to get a list of all the app package names using ADB.

adb shell pm list packages

But does anyone know of a system that would be capable of removing apps by pushing a file to the phone? Is there an app that would work like I described? Any help would be appreciated.

答:
If you have the list of packages to remove in pkgs2rm, this would uninstall all the packages as long as they are installed apps

```<code>xargs -l adb uninstall < pkgs2rm
</code>```

Body:
If you have the list of packages to remove in pkgs2rm, this would uninstall all the packages as long as they are installed apps

xargs -l adb uninstall < pkgs2rm


问:
Background Color Change Switch Not Working
I'm trying to make a dark/light theme. When I click to flip into light, the function runs. but darken(); seems to be ignored. Am I missing something? no error messages.

```<code><label class="switch">
    <input type="checkbox">
<span class="slider round" onclick="contrast();"></span>
</code>```
```<code>var m = 1

function lightup() {
    document.getElementById('header-wrap').style.backgroundColor = "white"
}

function darken() {
    document.getElementById('header-wrap').style.backgroundColor = 'black'
}

function contrast() {
    if (m = 1) {
        m = 2
        lightup();
    }
    else if (m = 2) {
        m = 1
        darken();
    }
}
</code>```

contrast(); and lightup(); both fire as intended. darken(); does not.

答:
Value comparison should be done using m === 1 or m == 1. m = 1 is assignment operator

Working Fiddle

var m = 1

function lightup() {
    document.getElementById('header-wrap').style.backgroundColor = "white"
}

function darken() {
    document.getElementById('header-wrap').style.backgroundColor = 'black'
}

function contrast() {
    if (m === 1) {
        m = 2
        lightup();
    }
    else if (m === 2) {
        m = 1
        darken();
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#header-wrap {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}</code>```

    <input type="checkbox">
    Change
```
</div>
</div>
</p>
<p>A better apprach is to make the function trigger on the change event of checkbox. Check the <code>checked</code> status of the checkbox and toggle the background color.</p>
<p><strong>Working Fiddle</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const checkbox = document.getElementById('checkbox');
const element = document.getElementById('header-wrap');

function contrast() {
    element.style.backgroundColor = checkbox.checked ? "white" : 'black';
}</code>```

#header-wrap {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header-wrap"></div>
<label class="switch">
    <input type="checkbox" id="checkbox" onchange="contrast();">
    <span class="slider round">Change</span>
</label></code>```

Body:
I'm trying to make a dark/light theme. When I click to flip into light, the function runs. but darken(); seems to be ignored. Am I missing something? no error messages.

    <input type="checkbox">

var m = 1

function lightup() {
    document.getElementById('header-wrap').style.backgroundColor = "white"
}

function darken() {
    document.getElementById('header-wrap').style.backgroundColor = 'black'
}

function contrast() {
    if (m = 1) {
        m = 2
        lightup();
    }
    else if (m = 2) {
        m = 1
        darken();
    }
}

contrast(); and lightup(); both fire as intended. darken(); does not.

Body:
Value comparison should be done using m === 1 or m == 1. m = 1 is assignment operator

Working Fiddle

var m = 1

function lightup() {
    document.getElementById('header-wrap').style.backgroundColor = "white"
}

function darken() {
    document.getElementById('header-wrap').style.backgroundColor = 'black'
}

function contrast() {
    if (m === 1) {
        m = 2
        lightup();
    }
    else if (m === 2) {
        m = 1
        darken();
    }
}

#header-wrap {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}

<div id="header-wrap"></div>
<label class="switch">
    <input type="checkbox">
    <span class="slider round" onclick="contrast();">Change</span>
</label>

A better apprach is to make the function trigger on the change event of checkbox. Check the checked status of the checkbox and toggle the background color.

Working Fiddle

const checkbox = document.getElementById('checkbox');
const element = document.getElementById('header-wrap');

function contrast() {
    element.style.backgroundColor = checkbox.checked ? "white" : 'black';
}

#header-wrap {
    width: 200px;
    height: 200px;
    border: 1px solid red;
}

<div id="header-wrap"></div>
<label class="switch">
    <input type="checkbox" id="checkbox" onchange="contrast();">
    <span class="slider round">Change</span>
</label>


问:
I am trying to install axios but such error occured
Command: npm install --save axios

I am unable to install axios. I am using reactnative in windows and want to make a HTTP request

Error

```<code>npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.3 (node_modules\sane\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN eslint-plugin-react-native@3.2.1 requires a peer of eslint@^3.17.0 || ^4.0.0 but none was installed.
npm ERR! path D:\reactnative\albums\node_modules\.staging\axios-29ec864b
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall rename
npm ERR! Error: EPERM: operation not permitted, rename 'D:\reactnative\albums\node_modules\.staging\axios-29ec864b' -> 'D:\reactnative\albums\node_modules\axios'
npm ERR!  { [Error: EPERM: operation not permitted, rename 'D:\reactnative\albums\node_modules\.staging\axios-29ec864b' -> 'D:\reactnative\albums\node_modules\axios']
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'rename',
npm ERR!   path:
npm ERR!    'D:\\reactnative\\albums\\node_modules\\.staging\\axios-29ec864b',
npm ERR!   dest: 'D:\\reactnative\\albums\\node_modules\\axios',
npm ERR!   parent: 'albums' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
</code>```

答:
I was trying to install axiuos and ran into this error after trying the solution here by Mchoeti

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/axious - Not found
npm ERR! 404
npm ERR! 404  'axious@*' is not in this registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/kusumarajesh/.npm/_logs/2022-02-09T04_04_50_334Z-debug.log

Body:
Command: npm install --save axios

I am unable to install axios. I am using reactnative in windows and want to make a HTTP request

Error

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.3 (node_modules\sane\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN eslint-plugin-react-native@3.2.1 requires a peer of eslint@^3.17.0 || ^4.0.0 but none was installed.
npm ERR! path D:\reactnative\albums\node_modules\.staging\axios-29ec864b
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall rename
npm ERR! Error: EPERM: operation not permitted, rename 'D:\reactnative\albums\node_modules\.staging\axios-29ec864b' -> 'D:\reactnative\albums\node_modules\axios'
npm ERR!  { [Error: EPERM: operation not permitted, rename 'D:\reactnative\albums\node_modules\.staging\axios-29ec864b' -> 'D:\reactnative\albums\node_modules\axios']
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'rename',
npm ERR!   path:
npm ERR!    'D:\\reactnative\\albums\\node_modules\\.staging\\axios-29ec864b',
npm ERR!   dest: 'D:\\reactnative\\albums\\node_modules\\axios',
npm ERR!   parent: 'albums' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.


问:
how do I filter Azure Service Bus Queue messages based on a message property?
I am using Azure Service Bus Queue to send emails out from my app.  I have many different customers that send out emails via my app and each message gets a property that identifies that customer: CustomerID

I need to write an admin area for my customers to look at the pending message in the queue and more importantly see the deadletter queue.  I do not want them to see everyones deadletters so I want to filter the messages based on the property CompanyID.

How do I accomplish this?

I read about topics and subscriptions but I add 10+ customers a week at least and this would not be a reasonable solution for me.

答:
You may use a polling mechanism utilizing receiveMessages() API in PEEK_LOCK mode in order to achieve filtering over queues and maintain a subscription to a flux stream of messages that pass your filter.

I have attempted to write a sample implementation in this project - Find GitHub Repo Here

Also, you can have a look at this article to understand its usage and scope.


答:
It's the bitwise AND operator in C\C++ and Perl.

Perl

C\C++

Title: What does '&' do in C/C++ and what is its equivalent operator in perl?

Body:
I'm writing a perl implementation of a protocol whose specification is given for C/C++ but I don't know much C.

What does the condition if ((flags & 0x400) != 0) mean? How do I do that in perl?

Is if ($flags == "\x400") correct?


问:
How to use a forked version of cordova-android
There's a problem with the current version of cordova-android that doesn't allow you to have a "&" symbol in the name of your app.

I forked a fix of a pull request I found on the repo.

I changed my package.json from

"cordova-android": "^10.1.1",

to

"cordova-android":https://github.com/fitdegree/cordova-android.git",

but now when I run cordova platform add android

I get the following error message:

```<code>cordova platform add android
Using cordova-fetch for cordova-android@https://github.com/fitdegree/cordova-android.git
Failed to fetch platform cordova-android@https://github.com/fitdegree/cordova-android.git
Probably this is either a connection problem, or platform spec is incorrect.
Check your connection and platform name/version/URL.
CordovaError: Error: npm: Command failed with exit code 127 Error output:
</code>```

any ideas on how I can use my forked version?

答:
cordova platform add uses NPM behind the scenes, so any valid npm install package will work.

cordova platform add <git url>

e.g: cordova platform add https://github.com/apache/cordova-android.git

cordova platform add ../local-path

e.g: cordova platform add ../path/to/my-cordova-android-fork

cordova platform add cordova-android.tgz

Pack up the cordova-android package using npm pack, which produces a tgz file. Then use cordova platform add my-cordova-android.tgz

Body:
There's a problem with the current version of cordova-android that doesn't allow you to have a "&" symbol in the name of your app.

I forked a fix of a pull request I found on the repo.

I changed my package.json from

"cordova-android": "^10.1.1",

to

"cordova-android":https://github.com/fitdegree/cordova-android.git",

but now when I run cordova platform add android

I get the following error message:

cordova platform add android
Using cordova-fetch for cordova-android@https://github.com/fitdegree/cordova-android.git
Failed to fetch platform cordova-android@https://github.com/fitdegree/cordova-android.git
Probably this is either a connection problem, or platform spec is incorrect.
Check your connection and platform name/version/URL.
CordovaError: Error: npm: Command failed with exit code 127 Error output:

any ideas on how I can use my forked version?


问:
Django parallel testing: Test processes incorrectly accessing test databases
I have a Django 3.0.8 project running locally, connected to a local PostgreSQL database (postgres:///myapp). When I run the python manage.py test, my unit tests run fine; a test database called test_myapp automatically gets created, and it's correctly accessed.

However, when I run python manage.py test --parallel 8, the test fails. I see that 8 cloned databases are correctly generated (test_myapp_1, test_myapp_2,..., test_myapp_8), but I get errors like these:

```<code>psycopg2.OperationalError: FATAL:  database "myapp_3" does not exist

</code>```

It appears that for parallel tests, databases are accessed incorrectly (trying to access the database myapp_N rather than test_myapp_N). I'm trying to figure out if my local config has issues, but this is all I have in my base config:

```<code>DATABASES = {
    'default': env.db('DATABASE_URL', default='postgres:///myapp'),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True
</code>```

Why are my parallel tests processes not accessing their respective cloned test databases correctly?

答:
A simple solution that worked for me is to explicitly specify the test database name in settings.py, e.g.,

```<code>DATABASES = {
    'default': {
        ...
        'TEST': {
            # Avoid naming it the same as your original database name.
            # Otherwise, it will be used while testing (and even may get deleted).
            'NAME': 'name_of_your_choice',
        },
    },
    ...
}
</code>```

If you are using multiple databases, you may need to do it for all of them.

Body:
I have a Django 3.0.8 project running locally, connected to a local PostgreSQL database (postgres:///myapp). When I run the python manage.py test, my unit tests run fine; a test database called test_myapp automatically gets created, and it's correctly accessed.

However, when I run python manage.py test --parallel 8, the test fails. I see that 8 cloned databases are correctly generated (test_myapp_1, test_myapp_2,..., test_myapp_8), but I get errors like these:

psycopg2.OperationalError: FATAL:  database "myapp_3" does not exist

It appears that for parallel tests, databases are accessed incorrectly (trying to access the database myapp_N rather than test_myapp_N). I'm trying to figure out if my local config has issues, but this is all I have in my base config:

DATABASES = {
    'default': env.db('DATABASE_URL', default='postgres:///myapp'),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True

Why are my parallel tests processes not accessing their respective cloned test databases correctly?

Body:
A simple solution that worked for me is to explicitly specify the test database name in settings.py, e.g.,

DATABASES = {
    'default': {
        ...
        'TEST': {
            # Avoid naming it the same as your original database name.
            # Otherwise, it will be used while testing (and even may get deleted).
            'NAME': 'name_of_your_choice',
        },
    },
    ...
}

If you are using multiple databases, you may need to do it for all of them.


问:
How do I stop "Type '/' from your saved info" (on Edge) from appearing on my site's search field?
I recently added a location search field on my site which shows suggestions based on what you type, but on Microsoft edge, a menu pops up on clicking on the input field. How can I disable this menu from appearing on just this input field of my site?

答: Based on the image you provided, I think this should be caused by some default settings in Edge. If you want to turn off this prompt, just navigate to: edge://settings/personalinfo in Edge and disable this feature like this image below:


问:
AWS Lambda Rest API: A sibling ({id}) of this resource already has a variable path part -- only one is allowed Unable to create resource at path
I'm particular new to Lambda and to AWS in general. I'm trying to setup a simple REST  API Service with Lambda. I've used CloudFormat and CodePipeline to have a simple Express app.
I'm trying to figure out why during the deployment phase, during ExecuteChangeSet I have this error:

Errors found during import: Unable to create resource at path '/stations/{stationId}/allowedUsers': A sibling ({id}) of this resource already has a variable path part -- only one is allowed Unable to create resource at path '/stations/{stationId}/allowedUsers/{userId}': A sibling ({id}) of this resource already has a variable path part -- only one is allowed

This is what I have inside the template.yml

```<code>      Events:
      AllowedUsers:
        Type: Api
        Properties:
          Path: /stations/{stationId}/allowedUsers
          Method: get
      AddAllowedUsers:
        Type: Api
        Properties:
          Path: /stations/{stationId}/allowedUsers
          Method: post
      DeleteAllowedUsers:
        Type: Api
        Properties:
          Path: /stations/{stationId}/allowedUsers/{userId}
          Method: delete
      GetAllowedUser:
        Type: Api
        Properties:
          Path: /stations/{stationId}/allowedUsers/{userId}
          Method: get
</code>```

I searched a bit for this error but I'm not sure how to solve it.

答:
For me, the issue was different from what is described in the GitHub issue Bryan mentioned.

I was using two different parameter names. Finishing the refactoring and using a single id name fixed the issue.

Example:

```<code>DeleteAllowedUsers:
  Type: Api
    Properties:
      Path: /stations/{stationId}/allowedUsers/{id}
      Method: delete
GetAllowedUser:
  Type: Api
    Properties:
      Path: /stations/{stationId}/allowedUsers/{userId}
      Method: get
</code>```

Body:
I'm particular new to Lambda and to AWS in general. I'm trying to setup a simple REST  API Service with Lambda. I've used CloudFormat and CodePipeline to have a simple Express app.
I'm trying to figure out why during the deployment phase, during ExecuteChangeSet I have this error:

Errors found during import: Unable to create resource at path '/stations/{stationId}/allowedUsers': A sibling ({id}) of this resource already has a variable path part -- only one is allowed Unable to create resource at path '/stations/{stationId}/allowedUsers/{userId}': A sibling ({id}) of this resource already has a variable path part -- only one is allowed

This is what I have inside the template.yml

      Events:
      AllowedUsers:
        Type: Api
        Properties:
          Path: /stations/{stationId}/allowedUsers
          Method: get
      AddAllowedUsers:
        Type: Api
        Properties:
          Path: /stations/{stationId}/allowedUsers
          Method: post
      DeleteAllowedUsers:
        Type: Api
        Properties:
          Path: /stations/{stationId}/allowedUsers/{userId}
          Method: delete
      GetAllowedUser:
        Type: Api
        Properties:
          Path: /stations/{stationId}/allowedUsers/{userId}
          Method: get

I searched a bit for this error but I'm not sure how to solve it.

Body:
For me, the issue was different from what is described in the GitHub issue Bryan mentioned.

I was using two different parameter names. Finishing the refactoring and using a single id name fixed the issue.

Example:

DeleteAllowedUsers:
  Type: Api
    Properties:
      Path: /stations/{stationId}/allowedUsers/{id}
      Method: delete
GetAllowedUser:
  Type: Api
    Properties:
      Path: /stations/{stationId}/allowedUsers/{userId}
      Method: get


问:
Javascript bookmarklet go to URL and execute
I have a javascript like this, used i a bookmarklet:

```<code>window.location="URL"
document.getElementById('username-id').value = 'User'
document.getElementById('pwd-id').value = 'pass'
doLogin();
</code>```

The problem is that javascript stops as soon as it hits the URL.
How to make it go to a page and execute a script?

Any help would be greatly appreciated.

答: If you control the page you're loading, I would consider passing that data as the fragment and handling that from the page. Something like window.location="URL#username=...;password=...", than parsing the data from the fragment in the page and doing whatever you need with it. However, in this specific case its not a good idea as the password will be saved in the browsing history.

Body:
I have a javascript like this, used i a bookmarklet:

window.location="URL"
document.getElementById('username-id').value = 'User'
document.getElementById('pwd-id').value = 'pass'
doLogin();

The problem is that javascript stops as soon as it hits the URL.
How to make it go to a page and execute a script?

Any help would be greatly appreciated.


问:
how to align items in the center and right

.parent {
  display: flex;
  justify-content: flex-end;
  background-color: lightgray;
}

.child {
  width: 200px;
  height: 200px;
  background-color: gray;
  border: solid black 1px;
}

.center {
  margin: 0 auto;
  background-color: black
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child center"> </div>
  <div class="child"> </div>
  <div class="child"> </div>
</div></code>```

and this is what i've got.

It seems the black one is located in the a little left, not the "center" of the parent.
How can i fix this?

答:
If you don't mind using grid instead of flexbox, you can utilize the property justify-self to align the black box to the center with the help of position: absolute;. The absolute positioning here makes it so it's possible to align the black box toward the center without minding/affecting the other two boxes. See the snippet below:

.parent {
  display: grid;
  justify-content: flex-end;
  grid-auto-flow: column;
  background-color: lightgray;
  position: relative;
}

.child {
  width: 200px;
  height: 200px;
  background-color: gray;
  border: solid black 1px;
}

.center {
  background-color: black;
  justify-self: center;
  position: absolute;
}

@media screen and (max-width: 992px) {
  .parent{
    display: flex;
    flex-wrap: wrap;
  }
  .center {
    position: relative;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child center"> </div>
  <div class="child"> </div>
  <div class="child"> </div>
</div></code>```

PS. I've added a @media query in case you want the 3 boxes to stack on a smaller space/screen.

Edit: Changed display on smaller screens and applied wrapping when necessary using flex-wrap.

More on justify-self and grid here and here respectively.

Body:
.parent {
  display: flex;
  justify-content: flex-end;
  background-color: lightgray;
}

.child {
  width: 200px;
  height: 200px;
  background-color: gray;
  border: solid black 1px;
}

.center {
  margin: 0 auto;
  background-color: black
}

and this is what i've got.

It seems the black one is located in the a little left, not the "center" of the parent.
How can i fix this?

Body:
If you don't mind using grid instead of flexbox, you can utilize the property justify-self to align the black box to the center with the help of position: absolute;. The absolute positioning here makes it so it's possible to align the black box toward the center without minding/affecting the other two boxes. See the snippet below:

.parent {
  display: grid;
  justify-content: flex-end;
  grid-auto-flow: column;
  background-color: lightgray;
  position: relative;
}

.child {
  width: 200px;
  height: 200px;
  background-color: gray;
  border: solid black 1px;
}

.center {
  background-color: black;
  justify-self: center;
  position: absolute;
}

@media screen and (max-width: 992px) {
  .parent{
    display: flex;
    flex-wrap: wrap;
  }
  .center {
    position: relative;
  }
}

<div class="parent">
  <div class="child center"> </div>
  <div class="child"> </div>
  <div class="child"> </div>
</div>

PS. I've added a @media query in case you want the 3 boxes to stack on a smaller space/screen.

Edit: Changed display on smaller screens and applied wrapping when necessary using flex-wrap.

More on justify-self and grid here and here respectively.


问:
How to treat '<attribute 'dtype' of 'numpy.generic' objects>' error?
After installing pypfopt and u-numpy, dataframe.info() command shows this error.

TypeError: Cannot interpret '<attribute 'dtype' of 'numpy.generic' objects>' as a data type
```

答:
Here's a link to the numpy issue associated with this error:  https://github.com/numpy/numpy/issues/18355.  A succinct fix is given there (in https://github.com/numpy/numpy/issues/18355#issuecomment-1029684903):

```<code>pip install --upgrade numpy
pip install --upgrade pandas
</code>```

Body:
Here's a link to the numpy issue associated with this error:  https://github.com/numpy/numpy/issues/18355.  A succinct fix is given there (in https://github.com/numpy/numpy/issues/18355#issuecomment-1029684903):

pip install --upgrade numpy
pip install --upgrade pandas


问:
How do I write a swagger endpoint using go-swagger where I can delay the consumption of the body in its parameters?
I need to define a swagger endpoint that needs to take in media types text and zip. Instead of having the generated package consume it and reassign it into separate types such as string, can I get the io.Readcloser passed through directly?</p>

答:
Swagger spec:

"parameters": [
  {
    "name": "foo",
    "in": "body",
    "schema": {
      "type": string,
      "format": "binary"
    }
  }
]
```
<p>Generated parameter:</p>
<pre class="lang-golang prettyprint-override"><code>type SomeParams struct {
    Foo io.ReadCloser
}
</code>```

And in the generated BindRequest method, the request body ReadCloser is assigned to the Foo field:

    if runtime.HasBody(r) {
        o.Foo = r.Body
    }
```

Body:
Swagger spec:

"parameters": [
  {
    "name": "foo",
    "in": "body",
    "schema": {
      "type": string,
      "format": "binary"
    }
  }
]

Generated parameter:

type SomeParams struct {
    Foo io.ReadCloser
}

And in the generated BindRequest method, the request body ReadCloser is assigned to the Foo field:

    if runtime.HasBody(r) {
        o.Foo = r.Body
    }


问:
Creating a method that merges 2 arrays into one sorted array in ascending order in Java
For part of an assignment, I have to create a method that merges 2 arrays into one sorted array in ascending order. I have most of it done, but I am getting a bug that replaces the last element in the array with 0. Has anyone ever run into this problem and know a solution? Heres my code:

```<code>     public static OrderedArray merge(OrderedArray src1, OrderedArray src2) {

         int numLength1 = src1.array.length;
         int numLength2 = src2.array.length;

         //combined array lengths
         int myLength = (numLength1 + numLength2);
        // System.out.println(myLength);
         OrderedArray mergedArr = new OrderedArray(myLength);

         //new array
         long[] merged = new long[myLength];

         //loop to sort array
         int i = 0;
         int j = 0;
         int k = 0;
         while (k < src1.array.length + src2.array.length - 1) {
             if(src1.array[i] < src2.array[j]) {
                 merged[k] = src1.array[i];
             i++;
             }
             else {
                merged[k] = src2.array[j];
             j++;

             }
            k++;

         }

         //loop to print result
         for(int x = 0; x < myLength; x++) {
             System.out.println(merged[x]);
         }
         return mergedArr;
     }

    public static void main(String[] args) {
        int maxSize = 100; // array size
//      OrderedArray arr; // reference to array
        OrderedArray src1 = new OrderedArray(4);
        OrderedArray src2 = new OrderedArray(5);

//      arr = new OrderedArray(maxSize); // create the array

        src1.insert(1);  //insert src1
        src1.insert(17);
        src1.insert(42);
        src1.insert(55);

        src2.insert(8); //insert src2
        src2.insert(13);
        src2.insert(21);
        src2.insert(32);
        src2.insert(69);

        OrderedArray myArray = merge(src1, src2);

</code>```

This is my expected output:

```<code>1
8
13
17
21
32
42
55
69
</code>```

and this is my current output:

```<code>1
8
13
17
21
32
42
55
0
</code>```

答:
While merging two arrays you are comparing them, sorting and merging but what if the length of two arrays is different like Array1{1,3,8} and Array2{4,5,9,10,11}. Here we will compare both arrays and move the pointer ahead, but when the pointer comes at 8 in array1 and at 9 in array2, now we cannot compare ahead, so we will add the remaining sorted array;

Solution:-

(Add this code between loop to sort array and loop to print array)

```<code>        while (i < numLength1) {
            merged[k] = src1.array[i];
            i++;
            k++;
        }

        while (j < numLength2) {
            merged[k] = src2.array[j];
            j++;
            k++;
        }
</code>```

Body:
For part of an assignment, I have to create a method that merges 2 arrays into one sorted array in ascending order. I have most of it done, but I am getting a bug that replaces the last element in the array with 0. Has anyone ever run into this problem and know a solution? Heres my code:

     public static OrderedArray merge(OrderedArray src1, OrderedArray src2) {

         int numLength1 = src1.array.length;
         int numLength2 = src2.array.length;

         //combined array lengths
         int myLength = (numLength1 + numLength2);
        // System.out.println(myLength);
         OrderedArray mergedArr = new OrderedArray(myLength);

         //new array
         long[] merged = new long[myLength];

         //loop to sort array
         int i = 0;
         int j = 0;
         int k = 0;
         while (k < src1.array.length + src2.array.length - 1) {
             if(src1.array[i] < src2.array[j]) {
                 merged[k] = src1.array[i];
             i++;
             }
             else {
                merged[k] = src2.array[j];
             j++;

             }
            k++;

         }

         //loop to print result
         for(int x = 0; x < myLength; x++) {
             System.out.println(merged[x]);
         }
         return mergedArr;
     }

    public static void main(String[] args) {
        int maxSize = 100; // array size
//      OrderedArray arr; // reference to array
        OrderedArray src1 = new OrderedArray(4);
        OrderedArray src2 = new OrderedArray(5);

//      arr = new OrderedArray(maxSize); // create the array

        src1.insert(1);  //insert src1
        src1.insert(17);
        src1.insert(42);
        src1.insert(55);

        src2.insert(8); //insert src2
        src2.insert(13);
        src2.insert(21);
        src2.insert(32);
        src2.insert(69);

        OrderedArray myArray = merge(src1, src2);

This is my expected output:

1
8
13
17
21
32
42
55
69

and this is my current output:

1
8
13
17
21
32
42
55
0

Body:
While merging two arrays you are comparing them, sorting and merging but what if the length of two arrays is different like Array1{1,3,8} and Array2{4,5,9,10,11}. Here we will compare both arrays and move the pointer ahead, but when the pointer comes at 8 in array1 and at 9 in array2, now we cannot compare ahead, so we will add the remaining sorted array;

Solution:-

(Add this code between loop to sort array and loop to print array)

        while (i < numLength1) {
            merged[k] = src1.array[i];
            i++;
            k++;
        }

        while (j < numLength2) {
            merged[k] = src2.array[j];
            j++;
            k++;
        }


问:
How to export NetLogo 6.2 View when you have multiple turtle profiles?
I'm trying to implement an output which is an export from the View. I got help from this link: How to export the world of NetLogo 6.2 coloring only the patches that were born turtles?
I greatly appreciate Luke C's help, as I managed to implement part of what I want.

However, I still haven't managed to generate the images by turtle profile. I have 16 turtle profiles (see ValidHabs).

I would like for example to export an image for each of the 16 turtle profiles.

For example, turtle profile 1 (can only born and hatch in habitatcover 1), so:

```<code>At tick 0, the world started with: 1 turtle no (patch 15 -4),
At tick 1, there are 2 turtles in patches (patch 15 -4) and (patch 14 -8) and
At tick 2, there are 4 turtles in patches (patch 15 -4), (patch 14 -8), (patch 12 -5) and (patch 17 -1).
</code>```

So for the turtle profile 1 you would have a white exported image with the patches (patch 15 -4), (patch 14 -8), (patch 12 -5) and (patch 17 -1) painted magenta.
Then I would export an image to the profile of turtle 2 etc... until I get to the profile of turtle 16 that can only spawn in habitatcovers 4 and 5.

I tried to use a foreach to export the image to each profile, but what happens is that opens a single .png file and generates the results in that single file (“overwriting”). And what I would like is to generate 1 file in .png format for each turtle profile. I thought that using foreach and carefully I could generate the files. But so far I haven't been able to. If anyone can help me I would be very grateful :)

Thanks in advance

The code:

```<code>globals [ ListProfiles ]
patches-own [ turtle-born-here ]
turtles-own [ all-code  metabolism reproduction code-metabolism code-reproduction ]

to setup
  ca
  set ListProfiles [ [1] [2] [3] [4] [5] ]
  ask patches [ set turtle-born-here false ]
  ask n-of 5 patches [
    sprout 1
    setup-turtles
    set turtle-born-here true
  ]
  reset-ticks
end

to go
  ask turtles [
    rt random 60 - 30
    fd 1
    if random-float 1 < 0.05 [
      hatch 1
      ask patch-here [ set turtle-born-here true]
    ]
  ]
end

to setup-turtles
  ask turtles [
    (
      ifelse
      metabolism = 2 [set code-metabolism "M1"]
    )
    (
      ifelse
      reproduction = 5 [set code-reproduction "R1"]
    )
    set all-code ( word code-metabolism code-reproduction )
  ]
end

to example-export-image
  setup
  ; Some example go runs
  repeat 50 [ go ]

  ; This is the export-view component
  cd
  ask turtles [
    ht
  ]
  ask patches [
    ifelse turtle-born-here
    [ set pcolor magenta ]
    [ set pcolor white ]
  ]
  carefully
  [ file-delete ( "View.png" ) ]
  [ ]
  foreach ListProfiles
    [
      y ->
      let k turtles with [ all-code = y ]
      ask k [
      export-view ( "View.png" )
      ]
    ]
end
</code>```

答:
When you are supplying code, it is recommended that you start from scratch rather than trying to pare down your existing model (see How to Ask and How to create a Minimal, Reproducible Example). This will help in (at least) two major ways:

It makes your code more readable and therefore makes you more likely to get a useful answer, since other users on this site will have an easier time understanding the problem if they don't have to also try and understand what part of the code is unrelated to the actual problem.

It makes it more likely that you will solve the issue yourself, or at the very least will help you better understand where the problem is coming from.

I'd recommend having a really solid crack at trying to follow the guidelines above whenever you post a question. As it stands, the code you supplied is way more than what's actually needed for the question itself, which for me would boil down to: "How do I change the file name for multiple experiments / simulations?" This question has been answered before in different ways that may suit your needs- if the code example below does not clear things up, have a look through those other questions and keep in mind the "Search and Research" component of the How To Ask help page.

For a standalone example, that is really just a refinement of Charles' answer in the first link above:

```<code>patches-own [ hab-type turtle-born-here ]

globals [ profiles ]

to setup
  ca
  resize-world 0 29 0 29
  set profiles [ "a" "b" "c" ]
  ask patches [
    ( ifelse pxcor < ( max-pxcor / 3) [
      set hab-type "a"
    ] pxcor < ( max-pxcor * 2 / 3 ) [
      set hab-type "b"
    ] [
      ; else
      set hab-type "c"
      ]
    )
  ]
end

to fake-simulate
  foreach profiles [ profile ->
    ask turtles [ die ]
    ask patches [
      set pcolor black
      set turtle-born-here false
    ]
    ask n-of 5 patches with [ hab-type = profile ] [
      sprout 1
      set turtle-born-here true
    ]
    reset-ticks
    repeat 50 [
      ask turtles [
        rt random 60 - 30
        fd 1
        if random-float 1 < 0.1 and [ hab-type ] of patch-here = profile [
          hatch 1
          ask patch-here [ set turtle-born-here true]
        ]
      ]
      tick
    ]
    export-image profile
  ]
end

to export-image [ unique-id ]
  ; Prepare the view for export
  ask turtles [ ht ]
  ask patches [
    ifelse turtle-born-here
    [ set pcolor magenta ]
    [ set pcolor white ]
  ]
  ; Use word to create a file name
  let out-file ( word "example_view_export_" unique-id "_.png" )
  export-view out-file
end
</code>```

Outputs something like:

Body:
I'm trying to implement an output which is an export from the View. I got help from this link: How to export the world of NetLogo 6.2 coloring only the patches that were born turtles?
I greatly appreciate Luke C's help, as I managed to implement part of what I want.

However, I still haven't managed to generate the images by turtle profile. I have 16 turtle profiles (see ValidHabs).

I would like for example to export an image for each of the 16 turtle profiles.

For example, turtle profile 1 (can only born and hatch in habitatcover 1), so:

At tick 0, the world started with: 1 turtle no (patch 15 -4),
At tick 1, there are 2 turtles in patches (patch 15 -4) and (patch 14 -8) and
At tick 2, there are 4 turtles in patches (patch 15 -4), (patch 14 -8), (patch 12 -5) and (patch 17 -1).

So for the turtle profile 1 you would have a white exported image with the patches (patch 15 -4), (patch 14 -8), (patch 12 -5) and (patch 17 -1) painted magenta.
Then I would export an image to the profile of turtle 2 etc... until I get to the profile of turtle 16 that can only spawn in habitatcovers 4 and 5.

I tried to use a foreach to export the image to each profile, but what happens is that opens a single .png file and generates the results in that single file (“overwriting”). And what I would like is to generate 1 file in .png format for each turtle profile. I thought that using foreach and carefully I could generate the files. But so far I haven't been able to. If anyone can help me I would be very grateful :)

Thanks in advance

The code:

globals [ ListProfiles ]
patches-own [ turtle-born-here ]
turtles-own [ all-code  metabolism reproduction code-metabolism code-reproduction ]

to setup
  ca
  set ListProfiles [ [1] [2] [3] [4] [5] ]
  ask patches [ set turtle-born-here false ]
  ask n-of 5 patches [
    sprout 1
    setup-turtles
    set turtle-born-here true
  ]
  reset-ticks
end

to go
  ask turtles [
    rt random 60 - 30
    fd 1
    if random-float 1 < 0.05 [
      hatch 1
      ask patch-here [ set turtle-born-here true]
    ]
  ]
end

to setup-turtles
  ask turtles [
    (
      ifelse
      metabolism = 2 [set code-metabolism "M1"]
    )
    (
      ifelse
      reproduction = 5 [set code-reproduction "R1"]
    )
    set all-code ( word code-metabolism code-reproduction )
  ]
end

to example-export-image
  setup
  ; Some example go runs
  repeat 50 [ go ]

  ; This is the export-view component
  cd
  ask turtles [
    ht
  ]
  ask patches [
    ifelse turtle-born-here
    [ set pcolor magenta ]
    [ set pcolor white ]
  ]
  carefully
  [ file-delete ( "View.png" ) ]
  [ ]
  foreach ListProfiles
    [
      y ->
      let k turtles with [ all-code = y ]
      ask k [
      export-view ( "View.png" )
      ]
    ]
end

Body:
When you are supplying code, it is recommended that you start from scratch rather than trying to pare down your existing model (see How to Ask and How to create a Minimal, Reproducible Example). This will help in (at least) two major ways:

It makes your code more readable and therefore makes you more likely to get a useful answer, since other users on this site will have an easier time understanding the problem if they don't have to also try and understand what part of the code is unrelated to the actual problem.

It makes it more likely that you will solve the issue yourself, or at the very least will help you better understand where the problem is coming from.

I'd recommend having a really solid crack at trying to follow the guidelines above whenever you post a question. As it stands, the code you supplied is way more than what's actually needed for the question itself, which for me would boil down to: "How do I change the file name for multiple experiments / simulations?" This question has been answered before in different ways that may suit your needs- if the code example below does not clear things up, have a look through those other questions and keep in mind the "Search and Research" component of the How To Ask help page.

For a standalone example, that is really just a refinement of Charles' answer in the first link above:

patches-own [ hab-type turtle-born-here ]

globals [ profiles ]

to setup
  ca
  resize-world 0 29 0 29
  set profiles [ "a" "b" "c" ]
  ask patches [
    ( ifelse pxcor < ( max-pxcor / 3) [
      set hab-type "a"
    ] pxcor < ( max-pxcor * 2 / 3 ) [
      set hab-type "b"
    ] [
      ; else
      set hab-type "c"
      ]
    )
  ]
end

to fake-simulate
  foreach profiles [ profile ->
    ask turtles [ die ]
    ask patches [
      set pcolor black
      set turtle-born-here false
    ]
    ask n-of 5 patches with [ hab-type = profile ] [
      sprout 1
      set turtle-born-here true
    ]
    reset-ticks
    repeat 50 [
      ask turtles [
        rt random 60 - 30
        fd 1
        if random-float 1 < 0.1 and [ hab-type ] of patch-here = profile [
          hatch 1
          ask patch-here [ set turtle-born-here true]
        ]
      ]
      tick
    ]
    export-image profile
  ]
end

to export-image [ unique-id ]
  ; Prepare the view for export
  ask turtles [ ht ]
  ask patches [
    ifelse turtle-born-here
    [ set pcolor magenta ]
    [ set pcolor white ]
  ]
  ; Use word to create a file name
  let out-file ( word "example_view_export_" unique-id "_.png" )
  export-view out-file
end

Outputs something like:


问:
How to enable the RealisticView events in HERE iOS Premium SDK 3.18+
Using the HERE iOS Premium SDK 3.18 to create a routing App and I can't figure out what is needed in order to enable the Realistic View events in order to get signpost data for maneuvers in the route.

I have specified the NavigationManager Delegate and created functions for the event callbacks. When I create a route and run a simulation on the route, I never receive either of the realistic view events. I have scoured the User Guide and the API Reference but can't get the events.

```<code>    func navigationManager(_ navigationManager: NMANavigationManager, didUpdateRealisticViewsForNextManeuver realisticViews: [NSNumber : [String : NMAImage]]) {
        mapState.status = "Realistic View Updated for Next Maneuver!"
    }

    func navigationManager(_ navigationManager: NMANavigationManager, didUpdateRealisticViewsForCurrentManeuver realisticViews: [NSNumber : [String : NMAImage]]) {
        print("RealisticViews: \(realisticViews.count)")
        for key in realisticViews.keys  {
            print("key: \(key)")
        }

        mapState.status = "Realistic View Updated for Current Maneuver!"
    }
</code>```

======
Update: I located my problem, I was missing the step to register the realisticview aspect ratios after doing that I started receiving the events. From the User Guide:

"The Realistic View feature is disabled by default. To enable it, use NMANavigationManager.realisticViewMode property and set the view mode to NMARealisticViewDay or NMARealisticViewNight. Next, register the desired image aspect ratios by using NMANavigationManager.realisticViewAspectRatios property."

Body:
Using the HERE iOS Premium SDK 3.18 to create a routing App and I can't figure out what is needed in order to enable the Realistic View events in order to get signpost data for maneuvers in the route.

I have specified the NavigationManager Delegate and created functions for the event callbacks. When I create a route and run a simulation on the route, I never receive either of the realistic view events. I have scoured the User Guide and the API Reference but can't get the events.

    func navigationManager(_ navigationManager: NMANavigationManager, didUpdateRealisticViewsForNextManeuver realisticViews: [NSNumber : [String : NMAImage]]) {
        mapState.status = "Realistic View Updated for Next Maneuver!"
    }

    func navigationManager(_ navigationManager: NMANavigationManager, didUpdateRealisticViewsForCurrentManeuver realisticViews: [NSNumber : [String : NMAImage]]) {
        print("RealisticViews: \(realisticViews.count)")
        for key in realisticViews.keys  {
            print("key: \(key)")
        }

        mapState.status = "Realistic View Updated for Current Maneuver!"
    }

======
Update: I located my problem, I was missing the step to register the realisticview aspect ratios after doing that I started receiving the events. From the User Guide:

"The Realistic View feature is disabled by default. To enable it, use NMANavigationManager.realisticViewMode property and set the view mode to NMARealisticViewDay or NMARealisticViewNight. Next, register the desired image aspect ratios by using NMANavigationManager.realisticViewAspectRatios property."


问:
weblogic, jdk1.5 memory issues
I am using weblogic 9.2, jdk1.5, and oracle 10g for my application and getting some  memory issues

I have a report servlet for 4 different kinds of reports of millions of db records

Now my problem is this, that when I run the report one at a time (single user), no memory issue occurs say

when report was executing memory was 775 mb
when report finish executing memory was 836 mb

Now

sooner the concurrent users request for the reports the memory leakage starts

even after the end of each report only few memory is reclaimed say

when reports was executing memory was 33 mb
when reports finish executing memory was 86 mb

it stays on 86mb forever until next request gets java.lang.OutOfMemoryError

I have called System.gc after the end of each report execution but it only gets down to a 86mb

~ I am instantiating a report object inside servlet's post method for each request

答:
What is your Heap set to with Xmx and Xms

Looks like you are creating a lot of temporary objects when running your report which reside in the Eden space (within Young space). These can be tuned by changing values of Xms with respect to Xmx.

Maybe when concurrent users hitting your app are having resource contention to underlying database or whatever else.

I suggest you profile your application with VisualVM or YourKit. Also read  Troubleshooting Memory Leaks

Title: weblogic, jdk1.5 memory issues


问:
Easiest way to search column value, match with a set value, and assign to a variable in python
Aim: check if my bad_outcomes set includes df['Outcome'] pd dataframe column values. If the set does contain these values I want to assign them to a new variable landing_outcome with the value of 0. If not I assign landing_outcome a value of 1.

I am able to search a column df['Outcome'] and check if the values are in my set called 'bad_outcomes' using isin.

```<code>df[df['Outcome'].isin (bad_outcomes)]
</code>```

This works. Then I try to put this in an if statement

```<code>if df[df['Outcome'].isin (bad_outcomes)]:
    landing_outcome = 0
</code>```

This gives me a Value error:

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

Where I am going wrong?
Is using isin the best way to do this?

I checked python manual for if statements and could't find an obvious syntax issue, I searched this forum for the error message (there are many posts but I couldn't see one for my use case). I'm new, I hope this is ok to ask.

答:
Try using .loc

```<code>df.loc[df['Outcome'].isin(bad_outcomes), "landing_outcome"] = 0
df.loc[~df['Outcome'].isin(bad_outcomes), "landing_outcome"] = 1
</code>```

If this helps, do approve the solution and upvote it.

Body:
Aim: check if my bad_outcomes set includes df['Outcome'] pd dataframe column values. If the set does contain these values I want to assign them to a new variable landing_outcome with the value of 0. If not I assign landing_outcome a value of 1.

I am able to search a column df['Outcome'] and check if the values are in my set called 'bad_outcomes' using isin.

df[df['Outcome'].isin (bad_outcomes)]

This works. Then I try to put this in an if statement

if df[df['Outcome'].isin (bad_outcomes)]:
    landing_outcome = 0

This gives me a Value error:

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

Where I am going wrong?
Is using isin the best way to do this?

I checked python manual for if statements and could't find an obvious syntax issue, I searched this forum for the error message (there are many posts but I couldn't see one for my use case). I'm new, I hope this is ok to ask.

Body:
Try using .loc

df.loc[df['Outcome'].isin(bad_outcomes), "landing_outcome"] = 0
df.loc[~df['Outcome'].isin(bad_outcomes), "landing_outcome"] = 1

If this helps, do approve the solution and upvote it.


问:
Request blocked by CORS policy after update to Edge 98.0.1108.43: Request had no target IP address space, yet the resource is in address space private
This problem also happens in Chrome.

Error in console:

Access to XMLHttpRequest at 'http://192.168.x.xxx:xxxx/' from origin
'http://xx.xxxx.com' has been blocked by CORS policy: Request had no
target IP address space, yet the resource is in address space
private.

My Edge worked fine last month. The problem started to happen after  updating Edge.

The flag #block-insecure-private-network-requests is set to disabled.

Does anyone know how to fix this problem without reverting the browser to an old version?

答:
Goto Edge with below URL
edge://flags/#block-insecure-private-network-requests

You can disable or enable from here and relaunch browser.