问:
This site can’t be reached [flask, python]
when I open the link 0.0.0.0:5000 in my browser I always get the message on the browser "This site can't be reached"
the code seems to be working since I get this message on the console

Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

here is the code that I am using

```<code>from flask import Flask, render_template, request
from scipy.misc import imsave, imread, imresize
import numpy as np
import keras.models
import re
import sys
import os
from load import *

sys.path.append(os.path.abspath('./model'))
app = Flask(__name__)
global model, graph
model, graph = init()

def convertImage(imData):
    imgstr = re.search(r'base64(.*'.imData).group(1)
    with open('output.png', 'wb') as output:
        output.write(imgstr.decode('base64'))

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=['GET', 'POST'])
def predict():
    imData = request.get_data()
    convertImage(imData)
    x = imread('output.png', mode = 'L')
    x = np.invert(x)
    x = imresize(x, 48, 48)
    x = x.reshape(1,48,48,1)
    with graph.as_default():
        out = model.predict(x)
        response = np.array_str(np.argmax(out))
        return response

if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
</code>```

答:
Always run docker in detached mode, in my case I tried running docker in detached mode and it worked. As we want to access the URL in browser. i.e. outside the container, The best solution is to run in detached mode and by exposing the port.

```<code> docker run -d -p 5000:5000 flask_docker_practise
</code>```

Above we are passing -d to run container in detached mode and then we pass -p to let the container know on which port we want to expose and listen.

Body:
when I open the link 0.0.0.0:5000 in my browser I always get the message on the browser "This site can't be reached"
the code seems to be working since I get this message on the console

Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

here is the code that I am using

from flask import Flask, render_template, request
from scipy.misc import imsave, imread, imresize
import numpy as np
import keras.models
import re
import sys
import os
from load import *

sys.path.append(os.path.abspath('./model'))
app = Flask(__name__)
global model, graph
model, graph = init()

def convertImage(imData):
    imgstr = re.search(r'base64(.*'.imData).group(1)
    with open('output.png', 'wb') as output:
        output.write(imgstr.decode('base64'))

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=['GET', 'POST'])
def predict():
    imData = request.get_data()
    convertImage(imData)
    x = imread('output.png', mode = 'L')
    x = np.invert(x)
    x = imresize(x, 48, 48)
    x = x.reshape(1,48,48,1)
    with graph.as_default():
        out = model.predict(x)
        response = np.array_str(np.argmax(out))
        return response

if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

Body:
Always run docker in detached mode, in my case I tried running docker in detached mode and it worked. As we want to access the URL in browser. i.e. outside the container, The best solution is to run in detached mode and by exposing the port.

 docker run -d -p 5000:5000 flask_docker_practise

Above we are passing -d to run container in detached mode and then we pass -p to let the container know on which port we want to expose and listen.


来源: stackexchange

问:
In Android Studio, I am not able to move google map and it always returns to current location

My problem is: When I'm trying to move around in the map or zoom in & out it immediately return to my current location. Also when I search for location, new marker added at the searched location but immediately goes back to my current location.
I searched for solution but found nothing.. I hope somebody can figure it out

```<code>    package com.hitman.locationrevision;
    import androidx.annotation.NonNull;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    import androidx.fragment.app.FragmentActivity;

    import android.Manifest;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.location.LocationRequest;
    import android.os.Bundle;
    import android.widget.Toast;

    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;
    import com.hitman.locationrevision.databinding.ActivityMapsBinding;

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
        LocationManager locationManager;
        LocationListener locationListener;

    >function for current location information
        public void locationInfo(Location location,String title){
            if(location != null) {
                LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(currentLocation).title(title));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));
            }
        }
    >function to request permission from user
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                    Location lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    locationInfo(lastLocation,"Your lastLocation");
                }

            }
        }

        private GoogleMap mMap;
        private ActivityMapsBinding binding;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            binding = ActivityMapsBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());

            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            Intent intent=getIntent();
            locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            locationListener=new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    locationInfo(location,"Your Location");
                }
            };
>code to ask permission and check permission from user

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
            }else{

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
>code to find the last location and update the last location
                Location
        lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    locationInfo(lastLocation,"Your lastlocation");
            }

        }
    }
</code>```

答:
Use this code for get current location.this method only get one time
of user location.inside OnLocationResult callback handle your location
logic

```<code>    private void getCurrentLocation(){

 LocationRequest locationRequest = new LocationRequest();

 FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setMaxWaitTime(1000);
        locationRequest.setFastestInterval(500);
        locationRequest.setInterval(500);

        fusedLocationProviderClient.requestLocationUpdates(locationRequest, new LocationCallback() {
            @Override
            public void onLocationResult( LocationResult locationResult) {
                if(locationResult.getLocations().size() != 0){
                    Location location = locationResult.getLocations().get(0);
                    LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());

                    //handle current user location logic

                    FusedLocationProviderClient.removeLocationUpdates(this);

                }
            }
        }, Looper.getMainLooper());

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My problem is: When I'm trying to move around in the map or zoom in & out it immediately return to my current location. Also when I search for location, new marker added at the searched location but immediately goes back to my current location.
I searched for solution but found nothing.. I hope somebody can figure it out

    package com.hitman.locationrevision;
    import androidx.annotation.NonNull;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    import androidx.fragment.app.FragmentActivity;

    import android.Manifest;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.location.LocationRequest;
    import android.os.Bundle;
    import android.widget.Toast;

    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;
    import com.hitman.locationrevision.databinding.ActivityMapsBinding;

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
        LocationManager locationManager;
        LocationListener locationListener;

    >function for current location information
        public void locationInfo(Location location,String title){
            if(location != null) {
                LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(currentLocation).title(title));
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,10));
            }
        }
    >function to request permission from user
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
                    Location lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    locationInfo(lastLocation,"Your lastLocation");
                }

            }
        }

        private GoogleMap mMap;
        private ActivityMapsBinding binding;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            binding = ActivityMapsBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());

            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            Intent intent=getIntent();
            locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            locationListener=new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    locationInfo(location,"Your Location");
                }
            };
>code to ask permission and check permission from user

            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
            }else{

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
>code to find the last location and update the last location
                Location
        lastLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    locationInfo(lastLocation,"Your lastlocation");
            }

        }
    }

Body:
Use this code for get current location.this method only get one time
of user location.inside OnLocationResult callback handle your location
logic

    private void getCurrentLocation(){

 LocationRequest locationRequest = new LocationRequest();

 FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setMaxWaitTime(1000);
        locationRequest.setFastestInterval(500);
        locationRequest.setInterval(500);

        fusedLocationProviderClient.requestLocationUpdates(locationRequest, new LocationCallback() {
            @Override
            public void onLocationResult( LocationResult locationResult) {
                if(locationResult.getLocations().size() != 0){
                    Location location = locationResult.getLocations().get(0);
                    LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());

                    //handle current user location logic

                    FusedLocationProviderClient.removeLocationUpdates(this);

                }
            }
        }, Looper.getMainLooper());

}


问:
Create a Table in different File-group with EF core code-first
I want to create a table in the "Secondary" file group which has been created previously in the SQL Server 2016. I want to create this table with EF core code-first.

答:
Finally, I found the solution and I want to share it.

Before creating a Table or adding your Tables’ DbSet in your ApplicationDbContext, create an empty migration with this code in PMC.

```<code>PM> add-migration CreateSecondaryFileGroup
</code>```

Write the SQL query for creating your filegroup and its Physical file in the “Up” method.

```<code>protected override void Up(MigrationBuilder migrationBuilder)
{
     //create FILEGROUP
     migrationBuilder.Sql(
         " EXEC('ALTER DATABASE [YourDatabaseName] ADD FILEGROUP [Secondary]')",
         suppressTransaction: true);

     //Create Physical file
     migrationBuilder.Sql(
         "ALTER DATABASE [YourDatabaseName] " +
                "ADD FILE " +
                "( " +
                    "NAME = 'Secondary_Data', " +
                    "FILENAME = '[yourFileDirectory]' " +
                    //for example:
                    //"FILENAME = 'D:\\Program Files\\Microsoft SQL Server\\MSSQL13.MSSQLSERVER\\MSSQL\\DATA\\Abby_Data2.mdf' " +
                ") " +
                "TO FILEGROUP Secondary",
                suppressTransaction:true
            );
}

</code>```

Then in PMC run this code to update your Database and create the filegroup.

```<code>PM> update-database
</code>```

Now add your tables’ DbSet in the ApplicationDbContext file, (my table name is Category)

```<code>public DbSet<Category> Category { get; set; }
</code>```

Now create a new migration file in order to create the table in your database in your specific filegroup (for me the filegroup name is Secondary) with this code in PMC

```<code>PM> add-migration CreateCategoryTableInSecondaryFileGroup
</code>```

Now in the “Up” method of migration file you should add SQL query to “create cluster Index of the table again” with SQL method of migrationBuilder.

One solution to create or move a table to another filegroup is to create Clustered Index in the specific filegroup.
The clustered index is the primary key of the “Category” table whose name is “PK_Category”

for more information

```<code>protected override void Up(MigrationBuilder migrationBuilder)
{
      migrationBuilder.CreateTable(
      name: "Category",
      columns: table => new
      {
           Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
           Name = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
           DisplayOrder = table.Column<int>(type: "int", nullable: false)
       },
       constraints: table =>
       {
             table.PrimaryKey("PK_Category", x => x.Id);
       });
       ///// this below code is the key point
       ///// you should write the below code

       migrationBuilder.Sql(
          "CREATE UNIQUE CLUSTERED INDEX PK_Category ON Category (Id)"+
          " WITH(DROP_EXISTING = ON) "+
                " ON Secondary"
               , suppressTransaction:true);
}

</code>```

Finally, run this code to update the database in PMC.

```<code>PM> update-database
</code>```

Body:
Finally, I found the solution and I want to share it.

Before creating a Table or adding your Tables’ DbSet in your ApplicationDbContext, create an empty migration with this code in PMC.

PM> add-migration CreateSecondaryFileGroup

Write the SQL query for creating your filegroup and its Physical file in the “Up” method.

protected override void Up(MigrationBuilder migrationBuilder)
{
     //create FILEGROUP
     migrationBuilder.Sql(
         " EXEC('ALTER DATABASE [YourDatabaseName] ADD FILEGROUP [Secondary]')",
         suppressTransaction: true);

     //Create Physical file
     migrationBuilder.Sql(
         "ALTER DATABASE [YourDatabaseName] " +
                "ADD FILE " +
                "( " +
                    "NAME = 'Secondary_Data', " +
                    "FILENAME = '[yourFileDirectory]' " +
                    //for example:
                    //"FILENAME = 'D:\\Program Files\\Microsoft SQL Server\\MSSQL13.MSSQLSERVER\\MSSQL\\DATA\\Abby_Data2.mdf' " +
                ") " +
                "TO FILEGROUP Secondary",
                suppressTransaction:true
            );
}

Then in PMC run this code to update your Database and create the filegroup.

PM> update-database

Now add your tables’ DbSet in the ApplicationDbContext file, (my table name is Category)

public DbSet<Category> Category { get; set; }

Now create a new migration file in order to create the table in your database in your specific filegroup (for me the filegroup name is Secondary) with this code in PMC

PM> add-migration CreateCategoryTableInSecondaryFileGroup

Now in the “Up” method of migration file you should add SQL query to “create cluster Index of the table again” with SQL method of migrationBuilder.

One solution to create or move a table to another filegroup is to create Clustered Index in the specific filegroup.
The clustered index is the primary key of the “Category” table whose name is “PK_Category”

for more information

protected override void Up(MigrationBuilder migrationBuilder)
{
      migrationBuilder.CreateTable(
      name: "Category",
      columns: table => new
      {
           Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
           Name = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
           DisplayOrder = table.Column<int>(type: "int", nullable: false)
       },
       constraints: table =>
       {
             table.PrimaryKey("PK_Category", x => x.Id);
       });
       ///// this below code is the key point
       ///// you should write the below code

       migrationBuilder.Sql(
          "CREATE UNIQUE CLUSTERED INDEX PK_Category ON Category (Id)"+
          " WITH(DROP_EXISTING = ON) "+
                " ON Secondary"
               , suppressTransaction:true);
}

Finally, run this code to update the database in PMC.

PM> update-database


问:
Asking the user to re-enter year of birth until birth year < current year
I have a problem that how to keep show a prompt until user enter their birth year is always smaller than the current year. Here is my code I try using loop but now  i struggle. I hope someone can help me, I appreciate it.</p>
```<code><body>
<p id= "age"></p>
<button onclick=" notify()">Try it</button>
<script>
function notify(){
let age = prompt("Your birth year");
        const year = new Date().getFullYear();
        do {
          document.getElementById("age").innerHTML =
            age + " is a good year";
        } while (age < year && age != null);
}
</script>
</body>
</code>```

答:
This suggested solution reworks your code considerably to try to improve both UX and maintainability.

A prompt modal dialog is easy for us to set up but tends to be clunky for the user. (An input element, in this case a numeric one, is usually the best way to get user input.)

Inline event handlers violate SoC while being less flexible than proper event listeners.

(There are stylistic changes here, too, but these are just personal preference and can be safely ignored.)

(See the in-code comments for further clarifications.)

// Gets current year, and identifies some DOM elements
const
  year = new Date().getFullYear(),
  yearInput = document.getElementById("year-input"),
  outputParagraph = document.getElementById("output-paragraph"),
  submitButton = document.getElementById("submit-button");

// Calls notify whenever button is clicked
submitButton.addEventListener("click", notify);

// Alternative listener setup you could try -- makes button unnecessary
// yearInput.addEventListener("change", notify);

// Chooses and shows message (by comparing inputted year to current year)
function notify(){

  const userYear = yearInput.value;
  let message;

  if(userYear === "")     { message = ""; }
  else if(userYear > year){ message = "Greetings, time traveller"; }
  else                    { message = "You are fit for your age"; }

  outputParagraph.textContent = message;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input{ width: 8ch; }</code>```

    Your birth year
    <input id="year-input" type="number" />

<button id="submit-button">SUBMIT</button>

```

Body:
I have a problem that how to keep show a prompt until user enter their birth year is always smaller than the current year. Here is my code I try using loop but now  i struggle. I hope someone can help me, I appreciate it.

<button onclick=" notify()">Try it</button>

Body:
This suggested solution reworks your code considerably to try to improve both UX and maintainability.

A prompt modal dialog is easy for us to set up but tends to be clunky for the user. (An input element, in this case a numeric one, is usually the best way to get user input.)

Inline event handlers violate SoC while being less flexible than proper event listeners.

(There are stylistic changes here, too, but these are just personal preference and can be safely ignored.)

(See the in-code comments for further clarifications.)

// Gets current year, and identifies some DOM elements
const
  year = new Date().getFullYear(),
  yearInput = document.getElementById("year-input"),
  outputParagraph = document.getElementById("output-paragraph"),
  submitButton = document.getElementById("submit-button");

// Calls notify whenever button is clicked
submitButton.addEventListener("click", notify);

// Alternative listener setup you could try -- makes button unnecessary
// yearInput.addEventListener("change", notify);

// Chooses and shows message (by comparing inputted year to current year)
function notify(){

  const userYear = yearInput.value;
  let message;

  if(userYear === "")     { message = ""; }
  else if(userYear > year){ message = "Greetings, time traveller"; }
  else                    { message = "You are fit for your age"; }

  outputParagraph.textContent = message;
}

input{ width: 8ch; }

<label>
    Your birth year
    <input id="year-input" type="number" />
</label>
<button id="submit-button">SUBMIT</button>
<p id="output-paragraph"></p>


问:
Codepipeline ARN not available through Terraform but available in metadata using cli
Executing AWS cli command as below:

aws codepipeline get-pipeline --name pipeline_name

produces following output

```<code>{
    "pipeline": {
        "name": "xxxxx",,
        "roleArn": "xxxxx",,
        "artifactStore": {
            "type": "S3",
            "location": "xxxxx",
        },
        "stages": [
            {
                "name": "Source",
                "actions": [
                    {
                        "name": "Source",
                        "actionTypeId": {
                            "category": "Source",
                            "owner": "AWS",
                            "provider": "CodeCommit",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "BranchName": "main",
                            "PollForSourceChanges": "true",
                            "RepositoryName": "xxxxx",
                        },
                        "outputArtifacts": [
                            {
                                "name": "SourceOutput"
                            }
                        ],
                        "inputArtifacts": []
                    }
                ]
            },
            {
                "name": "Build",
                "actions": [
                    {
                        "name": "Build",
                        "actionTypeId": {
                            "category": "Build",
                            "owner": "AWS",
                            "provider": "CodeBuild",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "ProjectName": "xxxxx",
                        },
                        "outputArtifacts": [
                            {
                                "name": "BuildOutput"
                            }
                        ],
                        "inputArtifacts": [
                            {
                                "name": "SourceOutput"
                            }
                        ]
                    }
                ]
            },
            {
                "name": "Deploy",
                "actions": [
                    {
                        "name": "Deploy",
                        "actionTypeId": {
                            "category": "Deploy",
                            "owner": "AWS",
                            "provider": "CodeDeployToECS",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "AppSpecTemplateArtifact": "BuildOutput",
                            "AppSpecTemplatePath": "appspec.yml",
                            "ApplicationName": "xxxxx",
                            "DeploymentGroupName": "xxxxx",
                            "Image1ArtifactName": "BuildOutput",
                            "Image1ContainerName": "IMAGE1_NAME",
                            "TaskDefinitionTemplateArtifact": "BuildOutput",
                            "TaskDefinitionTemplatePath": "taskdef.json"
                        },
                        "outputArtifacts": [],
                        "inputArtifacts": [
                            {
                                "name": "BuildOutput"
                            }
                        ]
                    }
                ]
            }
        ],
        "version": 3
    },
    "metadata": {
        "pipelineArn": "xxxxx",
        "created": "xxxxx",
        "updated": "xxxxx",
    }
}

</code>```

We can see that metadata field has  "pipelineArn": "xxxxx", . But this arn is not available in console nor have I been able to find any Terraform data source for this.

Is it possible to retrieve codepipline ARN in Terraform?

Also, to clarify I need this for "aws_codestarnotifications_notification_rule" where resource arn is required.

答:
The ARN for the CodePipeline is available in the AWS console, but it is a bit hard to find. If you go to Pipelines -> Choose any pipeline -> Settings it is in the General tab, under Pipeline ARN (1).

As for the getting the CodePipeline ARN through Terraform, that is possible by getting the attribute with the same name after the CodePipeline resource is created (2). So in case the CodePipline was not created with Terraform, you can hard-code the value. If it was, you could simply reference the output attribute in the "aws_codestarnotifications_notification_rule" resource:

```<code>resource "aws_codestarnotifications_notification_rule" "this" {
  detail_type    = ""
  event_type_ids = [""]

  name     = ""
  resource = aws_codepipeline.this.arn

  target {
    address = ...
  }
}
</code>```

This code snippet assumes that you will fill out other details and that there is a Terraform code block which creates a CodePipeline resource with name this, i.e., you would have to have a code block similar to following:

```<code>resource "aws_codepipeline" "this" {
...
}
</code>```

https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-view-console.html#pipelines-settings-console

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/codepipeline#arn

Body:
Executing AWS cli command as below:

aws codepipeline get-pipeline --name pipeline_name

produces following output

{
    "pipeline": {
        "name": "xxxxx",,
        "roleArn": "xxxxx",,
        "artifactStore": {
            "type": "S3",
            "location": "xxxxx",
        },
        "stages": [
            {
                "name": "Source",
                "actions": [
                    {
                        "name": "Source",
                        "actionTypeId": {
                            "category": "Source",
                            "owner": "AWS",
                            "provider": "CodeCommit",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "BranchName": "main",
                            "PollForSourceChanges": "true",
                            "RepositoryName": "xxxxx",
                        },
                        "outputArtifacts": [
                            {
                                "name": "SourceOutput"
                            }
                        ],
                        "inputArtifacts": []
                    }
                ]
            },
            {
                "name": "Build",
                "actions": [
                    {
                        "name": "Build",
                        "actionTypeId": {
                            "category": "Build",
                            "owner": "AWS",
                            "provider": "CodeBuild",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "ProjectName": "xxxxx",
                        },
                        "outputArtifacts": [
                            {
                                "name": "BuildOutput"
                            }
                        ],
                        "inputArtifacts": [
                            {
                                "name": "SourceOutput"
                            }
                        ]
                    }
                ]
            },
            {
                "name": "Deploy",
                "actions": [
                    {
                        "name": "Deploy",
                        "actionTypeId": {
                            "category": "Deploy",
                            "owner": "AWS",
                            "provider": "CodeDeployToECS",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "AppSpecTemplateArtifact": "BuildOutput",
                            "AppSpecTemplatePath": "appspec.yml",
                            "ApplicationName": "xxxxx",
                            "DeploymentGroupName": "xxxxx",
                            "Image1ArtifactName": "BuildOutput",
                            "Image1ContainerName": "IMAGE1_NAME",
                            "TaskDefinitionTemplateArtifact": "BuildOutput",
                            "TaskDefinitionTemplatePath": "taskdef.json"
                        },
                        "outputArtifacts": [],
                        "inputArtifacts": [
                            {
                                "name": "BuildOutput"
                            }
                        ]
                    }
                ]
            }
        ],
        "version": 3
    },
    "metadata": {
        "pipelineArn": "xxxxx",
        "created": "xxxxx",
        "updated": "xxxxx",
    }
}

We can see that metadata field has  "pipelineArn": "xxxxx", . But this arn is not available in console nor have I been able to find any Terraform data source for this.

Is it possible to retrieve codepipline ARN in Terraform?

Also, to clarify I need this for "aws_codestarnotifications_notification_rule" where resource arn is required.

Body:
The ARN for the CodePipeline is available in the AWS console, but it is a bit hard to find. If you go to Pipelines -> Choose any pipeline -> Settings it is in the General tab, under Pipeline ARN (1).

As for the getting the CodePipeline ARN through Terraform, that is possible by getting the attribute with the same name after the CodePipeline resource is created (2). So in case the CodePipline was not created with Terraform, you can hard-code the value. If it was, you could simply reference the output attribute in the "aws_codestarnotifications_notification_rule" resource:

resource "aws_codestarnotifications_notification_rule" "this" {
  detail_type    = ""
  event_type_ids = [""]

  name     = ""
  resource = aws_codepipeline.this.arn

  target {
    address = ...
  }
}

This code snippet assumes that you will fill out other details and that there is a Terraform code block which creates a CodePipeline resource with name this, i.e., you would have to have a code block similar to following:

resource "aws_codepipeline" "this" {
...
}

https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-view-console.html#pipelines-settings-console

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/codepipeline#arn


问:
Convert the string 0.12M to 120000 or 0.11K to 110 in pandas dataframe
Need some help on processing data inside a pandas dataframe
I want to convert the form of "col1" into the form of "col2", what should I do?</p>
```<code>import pandas as pd
a = {'col1' : ['0.11K','1011K','0.12M','0','0.3','0.02'],'col2':['110','1011000','120000','0','300000','20000']}

df = pd.DataFrame(a , columns=['col1','col2'])

df['col'] = (df['col'].replace(r'[KM]+$', '', regex=True).astype(float) * \
df['col'].str.extract(r'[\d\.]+([KM]+)', expand=False).fillna(1).replace(['K','M'],[10**3,10**6]).astype(int))
</code>```

Body:
Need some help on processing data inside a pandas dataframe
I want to convert the form of "col1" into the form of "col2", what should I do?

import pandas as pd
a = {'col1' : ['0.11K','1011K','0.12M','0','0.3','0.02'],'col2':['110','1011000','120000','0','300000','20000']}

df = pd.DataFrame(a , columns=['col1','col2'])

df['col'] = (df['col'].replace(r'[KM]+$', '', regex=True).astype(float) * \
df['col'].str.extract(r'[\d\.]+([KM]+)', expand=False).fillna(1).replace(['K','M'],[10**3,10**6]).astype(int))

Body:
If no unit means M then change .fillna(10**6) instead fillna(1) and processing column col1 instead col:

df['col'] = (df['col1'].replace(r'[KM]+$', '', regex=True).astype(float) *
             df['col1'].str.extract(r'[\d\.]+([KM]+)', expand=False)
                       .fillna(10**6)
                       .replace(['K','M'],[10**3,10**6]).astype(int))

print (df)
    col1     col2        col
0  0.11K      110      110.0
1  1011K  1011000  1011000.0
2  0.12M   120000   120000.0
3      0        0        0.0
4    0.3   300000   300000.0
5   0.02    20000    20000.0

Your solution from Convert the string 2.90K to 2900 or 5.2M to 5200000 in pandas dataframe:

df['col'] = (df['col1'].replace(r'[KM]+$', '', regex=True).astype(float) *
             df['col1'].str.extract(r'[\d\.]+([KM]+)', expand=False)
                       .fillna(1)
                       .replace(['K','M'],[10**3,10**6]).astype(int))

print (df)
    col1     col2         col
0  0.11K      110      110.00
1  1011K  1011000  1011000.00
2  0.12M   120000   120000.00
3      0        0        0.00
4    0.3   300000        0.30
5   0.02    20000        0.02


问:
SHELL script to make ftp connection and get xml files
I need a shell script that will login to a remote FTP server, get the list of files present in only root folder and identify only xml files and get those files to local system.
Login credentials can be mentioned in the script it self. This script must be run once a day only.

Please help me with a UNIX BASH SHELL script.

Thanks

答:
script:

```<code>#!/bin/bash
SERVER=ftp://myserver
USER=user
PASS=password
EXT=xml
DESTDIR=/destinationdir

listOfFiles=$(curl $SERVER --user $USER:$PASS 2> /dev/null | awk '{ print $9 }' | grep -E "*.$EXT$")
for file in $listOfFiles
do
   curl $SERVER/$file --user $USER:$PASS -o $DESTDIR/$file
done
</code>```

for scheduled run every day check the crontab:

```<code>crontab -e
</code>```

for edit your current jobs and add for example:

```<code>0 0 * * * bash /path/to/script
</code>```

that will mean run the script every day at midnight.

ContentLicense: CC BY-SA 3.0

Body:
script:

#!/bin/bash
SERVER=ftp://myserver
USER=user
PASS=password
EXT=xml
DESTDIR=/destinationdir

listOfFiles=$(curl $SERVER --user $USER:$PASS 2> /dev/null | awk '{ print $9 }' | grep -E "*.$EXT$")
for file in $listOfFiles
do
   curl $SERVER/$file --user $USER:$PASS -o $DESTDIR/$file
done

for scheduled run every day check the crontab:

crontab -e

for edit your current jobs and add for example:

0 0 * * * bash /path/to/script

that will mean run the script every day at midnight.


问:
How to correctly stop and resume a CADisplayLink?
I figured out a big problem with CADisplayLink.

I have the most basic EAGLLayer with OpenGL ES 1.1 drawing a rotating triangle for testing. This needs a run loop method to be called at screen refresh rate, so I start the runloop like this:

```<code>- (void)startRunloop {
    if (!animating) {
        CADisplayLink *dl = [[UIScreen mainScreen] displayLinkWithTarget:self selector:@selector(drawFrame)];
        [dl setFrameInterval:1.0];
        [dl addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        self.displayLink = dl;

        animating = YES;
    }
}

- (void)stopRunloop {
    if (animating) {
        [self.displayLink invalidate];
        self.displayLink = nil;
        animating = NO;
    }
}
</code>```

When the test app launches, I call -startRunloop.
When I tap the screen, I call -stopRunloop.
When I tap again, I call -startRunloop. And so forth. Ping Pong.

I'm measuring how often the -drawFrame method is called in 20 seconds, and NSLog it.

The FIRST start / stop cycle always performs at 100%. I get the maximum frame rate.

All SUBSEQUENT start / stop cycles only show about 80% of the performance. I get a significantly smaller frame rate. But: Always almost exactly the same, +/- 2 frames. With no tendency to degrade further even after 50 more start / stop cycles.

In conclusion: CREATING a CADisplayLink like I do above is fine, until it's invalidated or paused. After that, any new CADisplayLink does not perform well anymore. Even if it's created new and in the exact same way as before. Same is true if I pause / resume it by calling the -setPaused: method with YES / NO.

I've made sure with Allocations and VM Tracker Instruments that there is no memory management issue. I've also checked that the -invalidate method of CADisplayLink really gets called.

iOS 4.0 on the device (iPhone 4).

Why is that? Am I missing something?

答:
It's been a long time, however for those who still have this kind of problem like me, when you start:

```<code>if displayLink == nil {
  displayLink = CADisplayLink(target: self, selector: #selector(yourTarget))
  displayLink?.add(to: .main, forMode: RunLoop.Mode.common)
} else {
  displayLink?.isPaused = false
}
</code>```

And then when you need to stop:

```<code>displayLink?.isPaused = true
displayLink?.invalidate()
displayLink = nil
</code>```

Body:
I figured out a big problem with CADisplayLink.

I have the most basic EAGLLayer with OpenGL ES 1.1 drawing a rotating triangle for testing. This needs a run loop method to be called at screen refresh rate, so I start the runloop like this:

- (void)startRunloop {
    if (!animating) {
        CADisplayLink *dl = [[UIScreen mainScreen] displayLinkWithTarget:self selector:@selector(drawFrame)];
        [dl setFrameInterval:1.0];
        [dl addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        self.displayLink = dl;

        animating = YES;
    }
}

- (void)stopRunloop {
    if (animating) {
        [self.displayLink invalidate];
        self.displayLink = nil;
        animating = NO;
    }
}

When the test app launches, I call -startRunloop.
When I tap the screen, I call -stopRunloop.
When I tap again, I call -startRunloop. And so forth. Ping Pong.

I'm measuring how often the -drawFrame method is called in 20 seconds, and NSLog it.

The FIRST start / stop cycle always performs at 100%. I get the maximum frame rate.

All SUBSEQUENT start / stop cycles only show about 80% of the performance. I get a significantly smaller frame rate. But: Always almost exactly the same, +/- 2 frames. With no tendency to degrade further even after 50 more start / stop cycles.

In conclusion: CREATING a CADisplayLink like I do above is fine, until it's invalidated or paused. After that, any new CADisplayLink does not perform well anymore. Even if it's created new and in the exact same way as before. Same is true if I pause / resume it by calling the -setPaused: method with YES / NO.

I've made sure with Allocations and VM Tracker Instruments that there is no memory management issue. I've also checked that the -invalidate method of CADisplayLink really gets called.

iOS 4.0 on the device (iPhone 4).

Why is that? Am I missing something?

Body:
It's been a long time, however for those who still have this kind of problem like me, when you start:

if displayLink == nil {
  displayLink = CADisplayLink(target: self, selector: #selector(yourTarget))
  displayLink?.add(to: .main, forMode: RunLoop.Mode.common)
} else {
  displayLink?.isPaused = false
}

And then when you need to stop:

displayLink?.isPaused = true
displayLink?.invalidate()
displayLink = nil


问:
hyperledger fabric make error :"goimports: command not found"
when I build make the hyperledger fabric project ,I have the following error.but I have install the goimports successfully. To find the reason, I run ./scripts/golinter.sh alone, and there is no such error.what is the error reason,when I make the whole fabric project.

LINT: Running code checks.. Checking ./accesscontrol
  ./scripts/golinter.sh: line 23: goimports: command not found
  Makefile:148: recipe for target 'linter' failed make: *** [linter]
  Error 127

答:
In macOS:</p>
```<code>vi ~/.bashrc
export PATH="$PATH:$HOME/go/bin"
</code>```

Body:
In macOS:

vi ~/.bashrc
export PATH="$PATH:$HOME/go/bin"


问:
Went over the whole thing several times but still can't find the mistake
This code is from a tutorial. It kept giving weird errors and now it's stuck at

SyntaxError: Unexpected token }

I followed the tutorial closely but I still can't locate the error.
P.S Apparently I need to add a certain number of words to the description to be able to submit the question so this is just me doing that, I really have nothing else to say. Thank you.

const menu = {
  _courses: {
    appetizers: [],
    mains: [],
    desserts: [],
  },
  get appetizers() {
    return this._courses.appetizers;
  },
  get mains() {
    return this._courses.mains;
  },
  get desserts() {
    return this._courses.desserts;
  },
  set appetizers(appt) {
    return this._courses.appetizers = appetizers;
  },
  set mains(mains) {
    return this._courses.mains = mains;
  },
  set desserts(dess) {
    return this._courses.desserts = desserts,
  },
  get courses() {
    return {
      appetizers: this._courses.appetizers;
      mains: this._courses.mains;
      desserts: this._courses.desserts;
    };
  },
  addDishToCourse(courseName, dishName, dishPrice) {
    const dish = {
      name: dishName;
      price: dishPrice;
    }
    return this._courses[courseName].push(dish);

  },
  getRandomDishFromCourse(courseName) {
    const dishes = this._courses[courseName];
    const randomI = Math.floor(Math.random() * dishes.length);
    return dishes[randomI];
  },
  generateRandomMeal() {
    const appetizer = this.getRandomDishFromCourse(appetizers);
    const main = this.getRandomDishFromCourse(main);
    const dessert = this.getRandomDishFromCourse(desserts);
    const totalPrice = appetizer.price + main.price + dessert.price;
    return `Your mean is ${appetizer.name}, ${main.name} and ${dessert.name}, and the total price is ${totalPrice}`
  },
};

menu.addDishToCourse('appetizers', 'salad', 4)
menu.addDishToCourse('appetizers', 'wings', 3)
menu.addDishToCourse('appetizers', 'fries', 5)

menu.addDishToCourse('mains', 'steak', 10)
menu.addDishToCourse('mains', 'kebab', 11)
menu.addDishToCourse('mains', 'cizbiz', 9)

menu.addDishToCourse('desserts', 'ice cream', 4)
menu.addDishToCourse('desserts', 'cake', 5)
menu.addDishToCourse('desserts', 'coffee', 4)

const meal = menu.generateRandomMeal();
console.log(meal)```

答:
Ok, so I have found many errors here

line 17 should be: return this._courses.appetizers = appt;

appt is the argument passed in to the function

line 23 should be: return this._courses.desserts = dess;

Again, dess is the argument passed in to the function. Also, the statement needs to end witha  semicolon, not a comma.

lines 27 - 29: The lines need to end with commas and not semicolons. It is returning an object, so the properties of the object need to be seperated by commas, not semicolons.

lines 34 - 35: Same issue, returning an object. Need to seperate properties with commas instead of semicolons.

lines 46 - 48: The variables passed into the functions do not exist. The arguments for that function should be strings. So change those variables to strings instead. Also, make sure to change main to "mains" on line 48.

You should learn some debugging. Either run the code with Node.js or put it in a script tag in HTML and run it in the browser. Then you can see the errors produced which usually show you exactly where the problems are.


问:
Python concurrent.futures global variables
I have a multiprocessing code, and each process have to analyse same data differently.
The input data is always the same, it is not changeable.
Input data is a data frame 20 columns and 60k rows.

How to efficiently 'put' this data to each process?

On single process application I have used global variable, but in multiprocessing it's not working.

When I try to transfer this as a function argument, I have only the first element of the table

答:
thank you for the answer, I don't change this date each iteration. I use the same data to each process, data how to change the data is given throw function argument

```<code>with concurrent.futures.ProcessPoolExecutor() as executor:
   res = executor.map(goal_fcn, p)

for f in concurrent.futures.as_completed(res):
   fp = res
</code>```

and next

```<code>def goal_fcn(x):
   return heavy_calculation(x, global_DataFrame, global_String)
</code>```

EDIT:
it work with:

```<code>with concurrent.futures.ProcessPoolExecutor() as executor:
   res = executor.map(goal_fcn, p, [global_DataFrame], [global_String])

for f in concurrent.futures.as_completed(res):
   fp = res
</code>```
```<code>def goal_fcn(x, DataFrame, String):
   return heavy_calculation(x, DataFrame, String)
</code>```

Body:
thank you for the answer, I don't change this date each iteration. I use the same data to each process, data how to change the data is given throw function argument

with concurrent.futures.ProcessPoolExecutor() as executor:
   res = executor.map(goal_fcn, p)

for f in concurrent.futures.as_completed(res):
   fp = res

and next

def goal_fcn(x):
   return heavy_calculation(x, global_DataFrame, global_String)

EDIT:
it work with:

with concurrent.futures.ProcessPoolExecutor() as executor:
   res = executor.map(goal_fcn, p, [global_DataFrame], [global_String])

for f in concurrent.futures.as_completed(res):
   fp = res

def goal_fcn(x, DataFrame, String):
   return heavy_calculation(x, DataFrame, String)


问:
Is it possible to upload multiple files into gcp server at a time
I have more then 500 files which I am uploading into gcp storage in every 10 minutes.
I am uploading these files one-by-one which is a time taken process.

So Is is possible to upload these files into bulk in one short on gcp ?

```<code>def upload_files(**kwargs):
    stock_codes = kwargs['data']
    bucket_name = 'gcp-bucket-name'
    base_path = 'base_path'
    storage_client = storage.Client.from_service_account_json(gcp-services.json")
    bucket = storage_client.bucket(bucket_name)

    for filename in stock_codes:
       svg_blob_name = f"{filename}.svg"
       svg_blob = bucket.blob(svg_blob_name)
       svg_blob.upload_from_filename('file_path')

      print(
         "File {} uploaded to {}.".format(
                 f"{filename}", svg_blob_name
             )
         )

</code>```

答:
yes. i don't know which technology u use but it can achieved by

using gsutil for example. try the following command -

```<code>gsutil -m cp -r dir gs://my-bucket
</code>```

the -m flag here is enabling parallel copy

for more info checkout this link - https://cloud.google.com/storage/docs/gsutil/commands/cp

Body:
I have more then 500 files which I am uploading into gcp storage in every 10 minutes.
I am uploading these files one-by-one which is a time taken process.

So Is is possible to upload these files into bulk in one short on gcp ?

def upload_files(**kwargs):
    stock_codes = kwargs['data']
    bucket_name = 'gcp-bucket-name'
    base_path = 'base_path'
    storage_client = storage.Client.from_service_account_json(gcp-services.json")
    bucket = storage_client.bucket(bucket_name)

    for filename in stock_codes:
       svg_blob_name = f"{filename}.svg"
       svg_blob = bucket.blob(svg_blob_name)
       svg_blob.upload_from_filename('file_path')

      print(
         "File {} uploaded to {}.".format(
                 f"{filename}", svg_blob_name
             )
         )

Body:
yes. i don't know which technology u use but it can achieved by

using gsutil for example. try the following command -

gsutil -m cp -r dir gs://my-bucket

the -m flag here is enabling parallel copy

for more info checkout this link - https://cloud.google.com/storage/docs/gsutil/commands/cp


问:
Custom Leaflet markers when markers are coded as a layer, not built individually?
Leaflet map adapted from this tutorial builds markers like:

async function render_markers() {
const markers = await load_markers();
L.geoJSON(markers)
    .bindPopup((layer) => layer.feature.properties.name)
    .addTo(layerGroup);
}
```
<p>I want to change this map's markers to any of the solutions recommended in this good thread. But I don't know how to get a handle on them as all markers seem built individually, eg:</p>
<pre class="lang-js prettyprint-override"><code>L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map);
</code>```

Leaflet documentation also only seems to show how to change markers individually. How can we get a solution like this working with the way our map is built? What are we missing?

答:
You are searching for this Leaflet-Tutorial.

To customize markers or circles you need to add pointToLayer function:

```<code>L.geoJSON(markers, {
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, {icon: greenIcon} );
    }
})
    .bindPopup((layer) => layer.feature.properties.name)
    .addTo(layerGroup);
</code>```

Body:
Leaflet map adapted from this tutorial builds markers like:

async function render_markers() {
const markers = await load_markers();
L.geoJSON(markers)
    .bindPopup((layer) => layer.feature.properties.name)
    .addTo(layerGroup);
}

I want to change this map's markers to any of the solutions recommended in this good thread. But I don't know how to get a handle on them as all markers seem built individually, eg:

L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map);

Leaflet documentation also only seems to show how to change markers individually. How can we get a solution like this working with the way our map is built? What are we missing?

Body:
You are searching for this Leaflet-Tutorial.

To customize markers or circles you need to add pointToLayer function:

L.geoJSON(markers, {
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, {icon: greenIcon} );
    }
})
    .bindPopup((layer) => layer.feature.properties.name)
    .addTo(layerGroup);


问:
Querying an IoT Hub Object with number key
I am trying to retrieve information from a twin device of a third party IoT Hub instance.

The data I'm trying to access has the next format:

```<code>{
    "properties": {
        "reported": {
            "softwareLoad": {
                "0": {
                    "systemSWVer": "1.2.0",
                    "picSWVer": "0.0.42",
                    "bootStatus": "inactive",
                    "partitionId": 0
                },
                "1": {
                    "systemSWVer": "1.2.0",
                    "picSWVer": "0.0.42",
                    "bootStatus": "active",
                    "partitionId": 1
               },
               "beamTableCRC": "0x5454"
            }
        }
    }
}
</code>```

I was trying to reach the variable systemSWVer to use it as a where clause, but each time I try to access I had an error retrieving the information in 0 and IoT Hub returns an error of a Bad Request.

I tried with this query

SELECT properties.reported.softwareLoad FROM devices WHERE properties.reported.softwareLoad.0.systemSWVer in ["1.2.0", "2.1.0"]

Is there a way to use it as a where clause in my query?

Note: I don't have access to the resource to change the format of the information.

答:
I tried to recreate this case and found the same result. Always an error when you add a number in the expression. I also found a workaround; instead of using 0 or 1, you can add them as an escaped Unicode character. It's important to add them as an ASCII Unicode character, though. 0 becomes \u0030 and 1 becomes \u0031.

Try this query:

SELECT properties.reported.softwareLoad FROM devices
WHERE properties.reported.softwareLoad.\u0030.systemSWVer in ['1.2.0', '2.1.0']
```
<p>Please note: in any case, you need to use single quotes.</p>
<p>Edit: in my excitement, I forgot to test if just escaping the integer would also work. It does.</p>
<pre class="lang-sql prettyprint-override"><code>SELECT properties.reported.softwareLoad FROM devices
WHERE properties.reported.softwareLoad.\0.systemSWVer in ['1.2.0', '2.1.0']
</code>```

Body:
I am trying to retrieve information from a twin device of a third party IoT Hub instance.

The data I'm trying to access has the next format:

{
    "properties": {
        "reported": {
            "softwareLoad": {
                "0": {
                    "systemSWVer": "1.2.0",
                    "picSWVer": "0.0.42",
                    "bootStatus": "inactive",
                    "partitionId": 0
                },
                "1": {
                    "systemSWVer": "1.2.0",
                    "picSWVer": "0.0.42",
                    "bootStatus": "active",
                    "partitionId": 1
               },
               "beamTableCRC": "0x5454"
            }
        }
    }
}

I was trying to reach the variable systemSWVer to use it as a where clause, but each time I try to access I had an error retrieving the information in 0 and IoT Hub returns an error of a Bad Request.

I tried with this query

SELECT properties.reported.softwareLoad FROM devices WHERE properties.reported.softwareLoad.0.systemSWVer in ["1.2.0", "2.1.0"]

Is there a way to use it as a where clause in my query?

Note: I don't have access to the resource to change the format of the information.

Body:
I tried to recreate this case and found the same result. Always an error when you add a number in the expression. I also found a workaround; instead of using 0 or 1, you can add them as an escaped Unicode character. It's important to add them as an ASCII Unicode character, though. 0 becomes \u0030 and 1 becomes \u0031.

Try this query:

SELECT properties.reported.softwareLoad FROM devices
WHERE properties.reported.softwareLoad.\u0030.systemSWVer in ['1.2.0', '2.1.0']

Please note: in any case, you need to use single quotes.

Edit: in my excitement, I forgot to test if just escaping the integer would also work. It does.

SELECT properties.reported.softwareLoad FROM devices
WHERE properties.reported.softwareLoad.\0.systemSWVer in ['1.2.0', '2.1.0']


问:
Append a measuring unit to the quantity field in WooCommerce email notifications
I'd like to append a unit to the quantity field in the order confirmation email, more precisely in the order items table of that email (email-order-details.php)

See screenshot:

I've tried to add this line of PHP

`<?php echo '<p>VE</p>'; ?>`
```
<p>into the HTML table in the template file, now my code looks like this:</p>
<pre class="lang-php prettyprint-override"><code><div style="margin-bottom: 40px;">
<table class="td" cellspacing="0" cellpadding="6" style="width: 100%; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;" border="1">
    <thead>
        <tr>
            <th class="td" scope="col" style="text-align:<?php echo esc_attr( $text_align ); ?>;"><?php esc_html_e( 'Product', 'woocommerce' ); ?></th>
            <th class="td" scope="col" style="text-align:<?php echo esc_attr( $text_align ); ?>;"><?php esc_html_e( 'Quantity', 'woocommerce' ); ?> <?php echo '<p>VE</p>'; ?></th>
            <th class="td" scope="col" style="text-align:<?php echo esc_attr( $text_align ); ?>;"><?php esc_html_e( 'Price', 'woocommerce' ); ?></th>
        </tr>
    </thead>
    <tbody>
        <?php
        echo wc_get_email_order_items( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            $order,
            array(
                'show_sku'      => $sent_to_admin,
                'show_image'    => false,
                'image_size'    => array( 32, 32 ),
                'plain_text'    => $plain_text,
                'sent_to_admin' => $sent_to_admin,
            )
        );
        ?>
    </tbody>
</code>```

But my adjustment is not showing in the correct location. Can anyone help out with this and hint me in the right direction?

答:
No need to edit/overwrite template files as you can just use the woocommerce_email_order_item_quantity filter hook

So you get:

function filter_woocommerce_email_order_item_quantity( $qty_display, $item ) {
    $qty_display = $qty_display . ' VE';

    return $qty_display;
}
add_filter( 'woocommerce_email_order_item_quantity', 'filter_woocommerce_email_order_item_quantity', 10, 2 );
```
<hr />
<p><strong>Optional:</strong> if you don't want to apply this to all e-mail notifications but target specific ones, you can use:</p>
<pre class="lang-php prettyprint-override"><code>// Setting the email_is as a global variable
function action_woocommerce_email_before_order_table( $order, $sent_to_admin, $plain_text, $email ) {
    $GLOBALS['email_id_str'] = $email->id;
}
add_action( 'woocommerce_email_before_order_table', 'action_woocommerce_email_before_order_table', 10, 4 );

function filter_woocommerce_email_order_item_quantity( $qty_display, $item ) {
    // Getting the email ID global variable
    $refNameGlobalsVar = $GLOBALS;
    $email_id = isset( $refNameGlobalsVar['email_id_str'] ) ? $refNameGlobalsVar['email_id_str'] : '';

    // Targeting specific email. Multiple statuses can be added, separated by a comma
    if ( in_array( $email_id, array( 'new_order' ) ) ) {
        $qty_display = $qty_display . ' VE';
    }

    return $qty_display;
}
add_filter( 'woocommerce_email_order_item_quantity', 'filter_woocommerce_email_order_item_quantity', 10, 2 );
</code>```

Also see: How to target other WooCommerce order emails

Code goes in functions.php file of the active child theme (or active theme).

Body:
I'd like to append a unit to the quantity field in the order confirmation email, more precisely in the order items table of that email (email-order-details.php)

See screenshot:

I've tried to add this line of PHP

`<?php echo '<p>VE</p>'; ?>`

into the HTML table in the template file, now my code looks like this:

            <th class="td" scope="col" style="text-align:<?php echo esc_attr( $text_align ); ?>;"><?php esc_html_e( 'Product', 'woocommerce' ); ?>
            <th class="td" scope="col" style="text-align:<?php echo esc_attr( $text_align ); ?>;"><?php esc_html_e( 'Quantity', 'woocommerce' ); ?> <?php echo '
VE
'; ?>
            <th class="td" scope="col" style="text-align:<?php echo esc_attr( $text_align ); ?>;"><?php esc_html_e( 'Price', 'woocommerce' ); ?>

        <?php
        echo wc_get_email_order_items( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            $order,
            array(
                'show_sku'      => $sent_to_admin,
                'show_image'    => false,
                'image_size'    => array( 32, 32 ),
                'plain_text'    => $plain_text,
                'sent_to_admin' => $sent_to_admin,
            )
        );
        ?>

But my adjustment is not showing in the correct location. Can anyone help out with this and hint me in the right direction?

Body:
No need to edit/overwrite template files as you can just use the woocommerce_email_order_item_quantity filter hook

So you get:

function filter_woocommerce_email_order_item_quantity( $qty_display, $item ) {
    $qty_display = $qty_display . ' VE';

    return $qty_display;
}
add_filter( 'woocommerce_email_order_item_quantity', 'filter_woocommerce_email_order_item_quantity', 10, 2 );

Optional: if you don't want to apply this to all e-mail notifications but target specific ones, you can use:

// Setting the email_is as a global variable
function action_woocommerce_email_before_order_table( $order, $sent_to_admin, $plain_text, $email ) {
    $GLOBALS['email_id_str'] = $email->id;
}
add_action( 'woocommerce_email_before_order_table', 'action_woocommerce_email_before_order_table', 10, 4 );

function filter_woocommerce_email_order_item_quantity( $qty_display, $item ) {
    // Getting the email ID global variable
    $refNameGlobalsVar = $GLOBALS;
    $email_id = isset( $refNameGlobalsVar['email_id_str'] ) ? $refNameGlobalsVar['email_id_str'] : '';

    // Targeting specific email. Multiple statuses can be added, separated by a comma
    if ( in_array( $email_id, array( 'new_order' ) ) ) {
        $qty_display = $qty_display . ' VE';
    }

    return $qty_display;
}
add_filter( 'woocommerce_email_order_item_quantity', 'filter_woocommerce_email_order_item_quantity', 10, 2 );

Also see: How to target other WooCommerce order emails

Code goes in functions.php file of the active child theme (or active theme).


问:
How i convert email receiving date to date and time
Email receiving date is

2022-01-22 10:01:02

Date extract from email header it show:

2022-01-22 03:01:02-06:00

I need help to convert email header date 2022-01-22 03:01:02-06:00 to datetime.datetime(2022, 01, 22, 10, 01, 02, tzinfo=<UTC>)

答:
datetime.datetime.fromisoformat() works, so no need to define your own .strptime. Just do the timezone conversion after the datetime object is created:

```<code>import datetime

s = "2022-01-22 03:01:02-06:00"

dt = datetime.datetime.fromisoformat(s).astimezone(datetime.timezone.utc)
print(dt)
</code>```

Body:
datetime.datetime.fromisoformat() works, so no need to define your own .strptime. Just do the timezone conversion after the datetime object is created:

import datetime

s = "2022-01-22 03:01:02-06:00"

dt = datetime.datetime.fromisoformat(s).astimezone(datetime.timezone.utc)
print(dt)


问:
Trying to insert python datetime into SQL DATE
Trying to insert python datetime into SQL DATE but an error keeps appearing saying OperationalError: near "02": syntax error

```<code>import  sqlite3
conn=sqlite3.connect("Date_time3.db")
print("Database Opened successfully")
conn.execute("""
CREATE TABLE ADMIN(
EXPIRE DATETIME PRIMARY KEY
)
""")
</code>```

This is my database^

```<code>import datetime
import pytz
import  sqlite3

today = datetime.datetime.now()
date_time = today.strftime("%m/%d/%Y, %H:%M:%S")

conn=sqlite3.connect("Date_time3.db")
print("Database Opened successfully")

conn.execute("INSERT INTO ADMIN(EXPIRE) VALUES " +date_time);

conn.commit()
print ("Records inserted successfully")
conn.close()
"""
###Output###
#Database Opened successfully
#Records inserted successfully
#"""
print ("Table ADMIN created successfully")
"""
####Output###
Database Opened successfully
Table ADMIN created successfully
"""
</code>```

答:
Change this:

```<code>conn.execute("INSERT INTO ADMIN(EXPIRE) VALUES " +date_time);
</code>```

to

```<code>conn.execute('INSERT INTO ADMIN(EXPIRE) VALUES (?)', [date_time]);
</code>```

As you are running SQL commands, they work differently from Python. So you cannot use + operators. You need to use placeholders like (?)

Body:
Trying to insert python datetime into SQL DATE but an error keeps appearing saying OperationalError: near "02": syntax error

import  sqlite3
conn=sqlite3.connect("Date_time3.db")
print("Database Opened successfully")
conn.execute("""
CREATE TABLE ADMIN(
EXPIRE DATETIME PRIMARY KEY
)
""")

This is my database^

import datetime
import pytz
import  sqlite3

today = datetime.datetime.now()
date_time = today.strftime("%m/%d/%Y, %H:%M:%S")

conn=sqlite3.connect("Date_time3.db")
print("Database Opened successfully")

conn.execute("INSERT INTO ADMIN(EXPIRE) VALUES " +date_time);

conn.commit()
print ("Records inserted successfully")
conn.close()
"""
###Output###
#Database Opened successfully
#Records inserted successfully
#"""
print ("Table ADMIN created successfully")
"""
####Output###
Database Opened successfully
Table ADMIN created successfully
"""

Body:
Change this:

conn.execute("INSERT INTO ADMIN(EXPIRE) VALUES " +date_time);

to

conn.execute('INSERT INTO ADMIN(EXPIRE) VALUES (?)', [date_time]);

As you are running SQL commands, they work differently from Python. So you cannot use + operators. You need to use placeholders like (?)


问:
How to count foreign key objects with annotation in Django?
Hi all!

New in Django, and confused, help is appreciated!

Have three models:

```<code>class Organization(models.Model):
    organization_name = models.CharField(max_length=50)

class AppealForm(models.Model):
    form_name = models.CharField(max_length=50)

class Appeal(models.Model):
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
    appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE)
    applicant_name = models.CharField(max_length=150)
</code>```

Objects of Organization model:

organization_name

Organization 1

Organization 2

Objects of AppealForm model:

form_name

In written form

In oral form

Objects of Appeal model:

organization
appeal_form
applicant_name

Organization 1
In written form
First and Last name

Organization 1
In oral form
First and Last name

Organization 1
In oral form
First and Last name

Organization 2
In written form
First and Last name

Organization 2
In oral form
First and Last name

I'm trying to create a table in the template, like:

Organization
Total amount of appeals
Amount of written form appeals
Amount of oral form appeals

Organization 1
3
1
2

Organization 2
2
1
1

The content in the table contents has to be retrieved from Appeal model, that is rendered to the template.

Question:
How the query look like in views.py using Appeal model?

答:
i recommend you read about how to do complex query in django from this documents section.
Here what your query would be like:

```<code>from django.db.models import Count, Case, When, IntegerField

Appeal.objects
      .values('organization')
      .annotate(
          total_appeals=Count('appeal_form'),
          written_amount=Count(Case(
                When(appeal_form__form_name="In written form", then=1),
                output_field=IntegerField(),
          )),
          oral_amount=Count(Case(
                When(appeal_form__form_name="In oral form", then=1),
                output_field=IntegerField(),
          )),
       ).order_by()
</code>```

set the above query to a value and loop through it and see the results. You should get something like this

[{'organization': 'Organization 1', 'total_appeals': 3,
'written_amount': 1, 'oral_amount': 2},   {'organization':
'Organization 2', 'total_appeals': 2, 'written_amount': 1,
'oral_amount': 1}]

Explanations:

values to group by organization

Count to count the form in that organization group

we use Case to add an if condition, then=1 to return value(else return null)

the written_amount need to be integer so we set it in the output_field

conditional part in the documents https://docs.djangoproject.com/en/dev/ref/models/conditional-expressions

why you should use order_by() for grouping queries https://docs.djangoproject.com/en/4.0/topics/db/aggregation/#interaction-with-order-by

Body:
Hi all!

New in Django, and confused, help is appreciated!

Have three models:

class Organization(models.Model):
    organization_name = models.CharField(max_length=50)

class AppealForm(models.Model):
    form_name = models.CharField(max_length=50)

class Appeal(models.Model):
    organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
    appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE)
    applicant_name = models.CharField(max_length=150)

Objects of Organization model:

organization_name

Organization 1

Organization 2

Objects of AppealForm model:

form_name

In written form

In oral form

Objects of Appeal model:

organization
appeal_form
applicant_name

Organization 1
In written form
First and Last name

Organization 1
In oral form
First and Last name

Organization 1
In oral form
First and Last name

Organization 2
In written form
First and Last name

Organization 2
In oral form
First and Last name

I'm trying to create a table in the template, like:

Organization
Total amount of appeals
Amount of written form appeals
Amount of oral form appeals

Organization 1
3
1
2

Organization 2
2
1
1

The content in the table contents has to be retrieved from Appeal model, that is rendered to the template.

Question:
How the query look like in views.py using Appeal model?

Body:
i recommend you read about how to do complex query in django from this documents section.
Here what your query would be like:

from django.db.models import Count, Case, When, IntegerField

Appeal.objects
      .values('organization')
      .annotate(
          total_appeals=Count('appeal_form'),
          written_amount=Count(Case(
                When(appeal_form__form_name="In written form", then=1),
                output_field=IntegerField(),
          )),
          oral_amount=Count(Case(
                When(appeal_form__form_name="In oral form", then=1),
                output_field=IntegerField(),
          )),
       ).order_by()

set the above query to a value and loop through it and see the results. You should get something like this

[{'organization': 'Organization 1', 'total_appeals': 3,
'written_amount': 1, 'oral_amount': 2},   {'organization':
'Organization 2', 'total_appeals': 2, 'written_amount': 1,
'oral_amount': 1}]

Explanations:

values to group by organization

Count to count the form in that organization group

we use Case to add an if condition, then=1 to return value(else return null)

the written_amount need to be integer so we set it in the output_field

conditional part in the documents https://docs.djangoproject.com/en/dev/ref/models/conditional-expressions

why you should use order_by() for grouping queries https://docs.djangoproject.com/en/4.0/topics/db/aggregation/#interaction-with-order-by


问:
Can't install/use allegro
So, I've been working on programming a small game using allegro5. I'm currently in college, so my professor gave us some kind of "base project" on Visual Studio that already had allegro in it. The problem is, that when I run the program from Visual Studio, everything works fine! But if I run it from the created .exe it doesn't, because it can't find the allegro5 libraries.

So, how can I fix this? How do I properly install allegro5 so I can run it directly from the .exe?

答:
Try the ways below:

The simplest way: Copy the needed DLLs to the same folder as the exe you are running is located.

Add the path where the dll is located to the system environment variable, or put the dll in the directory specified by the system environment variable. For example: C:\Windows\System32

Title: Can't install/use allegro


问:
CSS gradient without bleeding through text
I am trying to create a background gradient but it bleeds through the text. I've done some googling and haven't been able to find something useful. I'm not the best at css and I've also never had to do something like this before. Any help is appreciated!

Putting the gradient as a background on the h1 tag doesn't work because as the screen grows the h1 grows with it and will distort the gradient.

Actual

Expected

答: adding z-index: -1 to my :before pseudo element gave me the desired result</p>


问:
Using variables in a function from another function
In function foo() there is a loop that iterates until it finds an optimum set of variables and determines that as the ideal set. The function only returns one variable, in order to pass a unit test.

In the next function bar(), I need to output all of the variables in function foo() as it iterates. First output the optimum set of variables, and then the rest of the possible variable sets seperately.

```<code>int foo(int a, int b) {
    int c, d;
    while ( etc. ) {
        c = arithmetic_for_c;
        d = arithmetic_for_d;
        e = c + d;
    }
    return e;
}

int bar(a, b) {
    cout << e;
    cout << c << d;
}
</code>```

This example is very simple, but you get the idea.

I have a feeling references (int&, string& etc) would help somehow, but I'm not sure how they would be used here.

I tried to put together a global array but that seemed to get a bit too complex for the scope of this assignment.

The loop is a necessity, but also seems to ruin any hope for variables or arrays in the global scope.

Unfortunately there are a number of things we haven't learned yet, so there is likely a solution I can't use yet.

Thoughts?

Thank you!

答:
If I'm not mistaken, this is not really possible in C++, as the variables are declared in the scope of the function foo, and cannot be accessed from a different scope. But you can always use something like this:

Pass by reference (out parameters):

```<code>#include <iostream>

// Declaring bar earlier as it has to be accessed by foo
int bar(int& c, int& d) {
    int e = 0; // Declaring and initializing variable e

    int count = 0;

    // Loop
    while (count < 10) {
        c++;
        d += 2;
        e = c + d;

        count++;
    }
    return e; // Return variable e
}

int foo(int a, int b) {
    int c, d;
    c = a, d = b; // setting c = parameter a, d = parameter b
    int e = a + b;

    std::cout << c << d << std::endl; // Printing variables c and d
    std::cout << e << std::endl; // Printing variable e

    e = bar(c, d); // Calling bar function. Also this function increments c by 10 and d by 20.

    std::cout << c << d << std::endl; // Printing variables c and d
    std::cout << e << std::endl; // Printing variable e

    return e; // Return variable e
}

int main() {
    foo(10, 20); // Calling function 'foo'
}
</code>```

This is just an example.

Body:
In function foo() there is a loop that iterates until it finds an optimum set of variables and determines that as the ideal set. The function only returns one variable, in order to pass a unit test.

In the next function bar(), I need to output all of the variables in function foo() as it iterates. First output the optimum set of variables, and then the rest of the possible variable sets seperately.

int foo(int a, int b) {
    int c, d;
    while ( etc. ) {
        c = arithmetic_for_c;
        d = arithmetic_for_d;
        e = c + d;
    }
    return e;
}

int bar(a, b) {
    cout << e;
    cout << c << d;
}

This example is very simple, but you get the idea.

I have a feeling references (int&, string& etc) would help somehow, but I'm not sure how they would be used here.

I tried to put together a global array but that seemed to get a bit too complex for the scope of this assignment.

The loop is a necessity, but also seems to ruin any hope for variables or arrays in the global scope.

Unfortunately there are a number of things we haven't learned yet, so there is likely a solution I can't use yet.

Thoughts?

Thank you!

Body:
If I'm not mistaken, this is not really possible in C++, as the variables are declared in the scope of the function foo, and cannot be accessed from a different scope. But you can always use something like this:

Pass by reference (out parameters):

#include <iostream>

// Declaring bar earlier as it has to be accessed by foo
int bar(int& c, int& d) {
    int e = 0; // Declaring and initializing variable e

    int count = 0;

    // Loop
    while (count < 10) {
        c++;
        d += 2;
        e = c + d;

        count++;
    }
    return e; // Return variable e
}

int foo(int a, int b) {
    int c, d;
    c = a, d = b; // setting c = parameter a, d = parameter b
    int e = a + b;

    std::cout << c << d << std::endl; // Printing variables c and d
    std::cout << e << std::endl; // Printing variable e

    e = bar(c, d); // Calling bar function. Also this function increments c by 10 and d by 20.

    std::cout << c << d << std::endl; // Printing variables c and d
    std::cout << e << std::endl; // Printing variable e

    return e; // Return variable e
}

int main() {
    foo(10, 20); // Calling function 'foo'
}

This is just an example.


问:
How to add CSS code for multiple color in one click on web page
How to add a CSS which we can change. like if we change in one place, the color of the whole website should get changed.

Screenshot : screenshot for Sample

Sample website : https://themezhub.net/rikada-demo-05/rikada/index.html#

as you can see in above website, they have a slider in left side and which contain a list of color, if you choose any color the whole website color will change.

How to make like this?.

Example :

I define the color code in one place of CSS or website and then the whole website should get changed according to it.

答:
"I define the color code in one place of CSS or website and then the whole website should get changed according to it."

Above, is the best thought for such dynamic color for webpages.

Example code : -

function change(color){
  $("body").removeClass();
  $("body").addClass(color);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body.black {
background-color : black;
color: white;
}

body.black .heading_1{
  font-size: 30px;
  font-weight : bold;
}

body.red {
background-color : red;
color: white;
}

body.red .heading_2{
  font-size: 30px;
  font-weight : bold;
}

body.green {
background-color : green;
color: white;
}

body.green .heading_3{
  font-size: 30px;
  font-weight : bold;
}

body.blue {
background-color : blue;
color: white;
}

body.blue .heading_4{
  font-size: 30px;
  font-weight : bold;
}</code>```

 This is Black

 This is Red

 This is Green

 This is Blue

<button onclick="change('black')"> Black </button>
<button onclick="change('red')"> Red </button>
<button onclick="change('green')"> Green </button>
<button onclick="change('blue')"> Blue </button>

```

You can define any style to any of your element on page (I have it on heading in my case), also you can define any class for any of the element (body.<class> in my case) on page with respect to which you are going to change the style for other elements.

Body:
"I define the color code in one place of CSS or website and then the whole website should get changed according to it."

Above, is the best thought for such dynamic color for webpages.

Example code : -

function change(color){
  $("body").removeClass();
  $("body").addClass(color);
}

body.black {
background-color : black;
color: white;
}

body.black .heading_1{
  font-size: 30px;
  font-weight : bold;
}

body.red {
background-color : red;
color: white;
}

body.red .heading_2{
  font-size: 30px;
  font-weight : bold;
}

body.green {
background-color : green;
color: white;
}

body.green .heading_3{
  font-size: 30px;
  font-weight : bold;
}

body.blue {
background-color : blue;
color: white;
}

body.blue .heading_4{
  font-size: 30px;
  font-weight : bold;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body class="black">
<span class="heading_1"> This is Black </span><br/>
<span class="heading_2"> This is Red </span><br/>
<span class="heading_3"> This is Green </span><br/>
<span class="heading_4"> This is Blue </span><br/>
<br/>
<button onclick="change('black')"> Black </button>
<button onclick="change('red')"> Red </button>
<button onclick="change('green')"> Green </button>
<button onclick="change('blue')"> Blue </button>
</body>
</html>

You can define any style to any of your element on page (I have it on heading in my case), also you can define any class for any of the element (body.<class> in my case) on page with respect to which you are going to change the style for other elements.


问:
Android studio seems to be running a wrong fish after i changed to fish as main shell
Basically, if I open a Terminal it opens it with fish automatically, and if I enter 'flutter' it works. If, however, in Android studio in the fish terminal (which i set as defauly), the behaviour is rather strange. To show what happens i tried it in the terminal in AS:

```<code>⋊> ~/path ⨯ flutter                                            15:43:20
fish: Unknown command: flutter
⋊> ~/path ⨯ which fish                                         15:43:25
/usr/local/bin/fish
⋊> ~/path ⨯ fish                                               15:43:33
⋊> ~/path ⨯ which fish                                         15:43:53
/usr/local/bin/fish
⋊> ~/path ⨯ flutter                                            15:43:58
Manage your Flutter app development.
⋊> ~/path ⨯ exit
⋊> ~/path ⨯ flutter
fish: Unknown command: flutter
</code>```

It's like i have an aquarium of two fish and AS uses the wrong, not configured one. HOWEVER i checked android studio, and the one set in preferences is /usr/local/bin/fish. Does anyone have an idea what the problem could be, or some troubleshooting I could try?

Things i did try so far are restarting my PC and AS multiple times.

答: It turned out this was, as @ridiculous_fish pointed out in the comments, an issue of the wrong flutter path in the the path. Why opening a new fish worked i have no idea</p>

Body:
Basically, if I open a Terminal it opens it with fish automatically, and if I enter 'flutter' it works. If, however, in Android studio in the fish terminal (which i set as defauly), the behaviour is rather strange. To show what happens i tried it in the terminal in AS:

⋊> ~/path ⨯ flutter                                            15:43:20
fish: Unknown command: flutter
⋊> ~/path ⨯ which fish                                         15:43:25
/usr/local/bin/fish
⋊> ~/path ⨯ fish                                               15:43:33
⋊> ~/path ⨯ which fish                                         15:43:53
/usr/local/bin/fish
⋊> ~/path ⨯ flutter                                            15:43:58
Manage your Flutter app development.
⋊> ~/path ⨯ exit
⋊> ~/path ⨯ flutter
fish: Unknown command: flutter

It's like i have an aquarium of two fish and AS uses the wrong, not configured one. HOWEVER i checked android studio, and the one set in preferences is /usr/local/bin/fish. Does anyone have an idea what the problem could be, or some troubleshooting I could try?

Things i did try so far are restarting my PC and AS multiple times.


问:
setBoolean() method of java.sql.PreparedStatement
As per the oracle documentation -

https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#setBoolean(int,%20boolean)

setBoolean(int parameterIndex,boolean x)

method Sets the designated parameter to the given Java boolean value. The driver converts this to an SQL BIT or BOOLEAN value when it sends it to the database.

Here is there any way to know when the value will be stored as SQL BIT? and when will it store as BOOLEAN?

I am using oracle database, I have used this method passing the value as true(Java Boolean) and the value getting stored in database is 1 instead of Y. What could be the reason?

答:
T.J. Crowder's answer is correct.

```<code>CREATE TABLE TEST_1
    (
    MEAL CHAR(1) CONSTRAINT MEAL_CONSTRAINT
    CHECK (MEAL IN ('Y', 'N'))
    );
</code>```

Output:

```<code>Table: TEST_1
Column name: MEAL
Data type: CHAR(1 BYTE)
Nullable: Yes
</code>```

Bean:

```<code>private boolean meal;
public Boolean getMeal(){
  return meal;
}
public void setMeal(Boolean meal){
  return this.meal = meal;
}
</code>```

And then use,

```<code>preparedStatement.setString(indexOfMealCol, getMeal() ? "Y" : "N");
</code>```

Note:

Providing any other value than Y or N, it will throw error

Null value accepted

Body:
T.J. Crowder's answer is correct.

CREATE TABLE TEST_1
    (
    MEAL CHAR(1) CONSTRAINT MEAL_CONSTRAINT
    CHECK (MEAL IN ('Y', 'N'))
    );

Output:

Table: TEST_1
Column name: MEAL
Data type: CHAR(1 BYTE)
Nullable: Yes

Bean:

private boolean meal;
public Boolean getMeal(){
  return meal;
}
public void setMeal(Boolean meal){
  return this.meal = meal;
}

And then use,

preparedStatement.setString(indexOfMealCol, getMeal() ? "Y" : "N");

Note:

Providing any other value than Y or N, it will throw error

Null value accepted


问:
How to add a lable to an object value in javascript
I have an array of objects that is grouped by index and would like to restructure and add labels to the response.

This is my original array:

```<code>let cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}]
</code>```

Here is the source code used to group the array by make:

```<code>var groupedByMake = _.groupBy(
          cars,
          "make"
        );
</code>```

The response looks like this:

```<code>{
  'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}],
  'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}
</code>```

My desired outcome should look like this:

```<code>[{
  'make': 'audi',
   'types': [{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}]
  },{
  'make': 'bmw',
  'types': [{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}]
</code>```

Is this possible to achieve using JavaScript? If so can I get assistance to achieve this task.

答:
const cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}];
const groupBy = (array, key) => {
  return array.reduce((acc, item) => {
    const keyValue = item[key];
    const existingGroup = acc.find((group) => group.key === keyValue);
    if (existingGroup) {
      existingGroup.items.push(item);
    } else {
      // remove make from item
      const { make, ...rest } = item;
      acc.push({ key: keyValue, items: [rest] });
    }
    return acc;
  }, []);
}

console.log(JSON.stringify(groupBy(cars, 'make'), null, 2));```

Body:
I have an array of objects that is grouped by index and would like to restructure and add labels to the response.

This is my original array:

let cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}]

Here is the source code used to group the array by make:

var groupedByMake = _.groupBy(
          cars,
          "make"
        );

The response looks like this:

{
  'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}],
  'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}

My desired outcome should look like this:

[{
  'make': 'audi',
   'types': [{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}]
  },{
  'make': 'bmw',
  'types': [{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}]

Is this possible to achieve using JavaScript? If so can I get assistance to achieve this task.


答:
You can use array.reduce to turn one array into another one and control whether you return a new element or accumulate values in existing one (prev):

let cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}];

let output = cars.reduce((acc, cur) => {
    let {make, ...obj} = cur;
    let prev = acc.find(x => x.make === make);
    if(!prev) {
      acc.push({make,types:[obj]})
    } else {
      prev.types.push(obj);
    }
    return acc;
}, []);

console.log(output);```

Title: How to add a lable to an object value in javascript