问:
Is there a way to relationship between two table which table one has 3 unique keys and table two has 2 unique keys in SQL Server?
I want to create relation between two tables, here's my table structure

Table1:

```<code>ID INT PrimaryKey AUTO_INCREMENT,
CountryCode INT UNIQUE,
Division VARCHAR(4) UNIQUE,
SubDivision VARCHAR(10) UNIQUE
</code>```

Table2:

```<code>ID INT PrimaryKey AUTO_INCREMENT,
CountryCode INT UNIQUE,
Division VARCHAR(4) UNIQUE,
ReportNo VARCHAR(10) UNIQUE
</code>```

Table1:

```<code>ID     |CountryCode       |Division      |SubDivision
-------+------------------+--------------+-----------
1      |IDN               |A             |A-1
2      |IDN               |B             |B-1
3      |IDN               |B             |B-2
</code>```

Table2

```<code>ID     |CountryCode       |Division      |ReportNo
-------+------------------+--------------+-----------
1      |IDN               |A             |Re001
2      |IDN               |A             |Re002
3      |IDN               |B             |Re003
</code>```

I want to create a relationship between those two tables which table2 (CountryCode, Division) refers to table1 (CountryCode, Division).

So when I want to delete in table1 with CountryCode = IDN and Division = A, SQL will prompt error when table2 contains CountryCode = IDN and Division = A.

I had tried to create a relationship between those two tables, but SQL Server always throws this error:

The column in table 'table1' do not match an existing primary key or unique constraint

Can anyone guide me how can I create a relationship between those two tables?

Thanks in advance

答:
You can't do it this way. SQL Server requires a unique constraint (or primary key constraint) on the target of a foreign key - and you have duplicates in the source table.

For this to work, you would need to have a separate table that references all possible (CountryCode, Division) combinations. Actually, your whole schema should be normalized into something like:

```<code>-- "top" table that stores the countries
create table countries (
    country_id int primary key
    name varchar(100)
);

-- the table that stores the divisions
create table divisions (
    division_id int primary key,
    country_id int references countries(country_id),
    name varchar(100)
);

-- the table that stores the subdivisions
-- this corresponds to "table1" in your question
create table subdivisions (
    subdivision_id int primary key,
    division_id int references divisions(division_id),
    name varchar(100)
);

-- the table that stores the reports
-- this corresponds to "table2" in your question
create table reports (
    report_id int primary key,
    division_id references divisions(division_id),
    name varchar(100)
);
</code>```

You can make the primary keys automatic by using identity columns (which is the SQL Server equivalent for MySQL's AUTO_INCREMENT).

As an example, here is how you would generate the current output that you are showing for the subdivisions:

```<code>select
    sd.id,
    c.name country,
    d.name division,
    sd.name subdivision
from subdivisions sd
inner join divisions d on d.division_id = sd.division_id
inner join countries c on c.country_id = d.country_id
</code>```

Body:
I want to create relation between two tables, here's my table structure

Table1:

ID INT PrimaryKey AUTO_INCREMENT,
CountryCode INT UNIQUE,
Division VARCHAR(4) UNIQUE,
SubDivision VARCHAR(10) UNIQUE

Table2:

ID INT PrimaryKey AUTO_INCREMENT,
CountryCode INT UNIQUE,
Division VARCHAR(4) UNIQUE,
ReportNo VARCHAR(10) UNIQUE

Table1:

ID     |CountryCode       |Division      |SubDivision
-------+------------------+--------------+-----------
1      |IDN               |A             |A-1
2      |IDN               |B             |B-1
3      |IDN               |B             |B-2

Table2

ID     |CountryCode       |Division      |ReportNo
-------+------------------+--------------+-----------
1      |IDN               |A             |Re001
2      |IDN               |A             |Re002
3      |IDN               |B             |Re003

I want to create a relationship between those two tables which table2 (CountryCode, Division) refers to table1 (CountryCode, Division).

So when I want to delete in table1 with CountryCode = IDN and Division = A, SQL will prompt error when table2 contains CountryCode = IDN and Division = A.

I had tried to create a relationship between those two tables, but SQL Server always throws this error:

The column in table 'table1' do not match an existing primary key or unique constraint

Can anyone guide me how can I create a relationship between those two tables?

Thanks in advance

Body:
You can't do it this way. SQL Server requires a unique constraint (or primary key constraint) on the target of a foreign key - and you have duplicates in the source table.

For this to work, you would need to have a separate table that references all possible (CountryCode, Division) combinations. Actually, your whole schema should be normalized into something like:

-- "top" table that stores the countries
create table countries (
    country_id int primary key
    name varchar(100)
);

-- the table that stores the divisions
create table divisions (
    division_id int primary key,
    country_id int references countries(country_id),
    name varchar(100)
);

-- the table that stores the subdivisions
-- this corresponds to "table1" in your question
create table subdivisions (
    subdivision_id int primary key,
    division_id int references divisions(division_id),
    name varchar(100)
);

-- the table that stores the reports
-- this corresponds to "table2" in your question
create table reports (
    report_id int primary key,
    division_id references divisions(division_id),
    name varchar(100)
);

You can make the primary keys automatic by using identity columns (which is the SQL Server equivalent for MySQL's AUTO_INCREMENT).

As an example, here is how you would generate the current output that you are showing for the subdivisions:

select
    sd.id,
    c.name country,
    d.name division,
    sd.name subdivision
from subdivisions sd
inner join divisions d on d.division_id = sd.division_id
inner join countries c on c.country_id = d.country_id


来源: stackexchange

问:
I can't display the KML
I am taking my first steps in openlayers, I find it quite interesting, but based on a simple example to show OSM it has been impossible for me to add a layer with a KML file and show it together.

I understand that I am close to achieving it and that is why I go to you, thanks in advance for any help.

My code is the following:

```<code>import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import OSM from 'ol/source/OSM';
import KML from 'ol/format/KML';
import VectorSource from 'ol/source/Vector';

var openstreet = new TileLayer({
    source: new OSM()
})

var geomapa = new VectorLayer({
    source: new VectorSource({
        url: 'maps/kml/doc.kml',
        format: new KML()
    })
});

const map = new Map({
    target: 'map',
    layers: [openstreet, geomapa],
    view: new View({
        center: [0, 0],
        zoom: 0
    })
});
</code>```

答:
Solved!

Although I am taking my first steps in openlayers using parcel, as the official documentation indicates, I must state that:

1) If a kml file is published to an external server, the web server must be configured to tell the client that the resource is a KML file, therefore, these directives must be added to the server:

2) Thinking that there was a bug in openlayers + parcel, I ran into the error

```<code>    Access to XMLHttpRequest at 'https://geo.anantara.cl/maps/kml/2012-02-10.kml'
    from origin 'http://localhost:1234' has been blocked by CORS policy:
    No 'Access-Control-Allow-Origin' header is present on the requested resource.

[http://localhost:1234/]
Failed to load resource: net::ERR_FAILED [https://geo.anantara.cl/maps/kml/2012-02-10.kml]
</code>```

What means?, well it's necessary on my Apache server add the following code

```<code> Header set Access-Control-Allow-Origin "http://127.0.0.1:1234"
</code>```

And now works.., I suggest that parcel document the posting of a kml file to an external server and how the CORS setting is enabled.

ContentLicense: CC BY-SA 4.0

Title: I can't display the KML

Body:
I am taking my first steps in openlayers, I find it quite interesting, but based on a simple example to show OSM it has been impossible for me to add a layer with a KML file and show it together.

I understand that I am close to achieving it and that is why I go to you, thanks in advance for any help.

My code is the following:

import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import OSM from 'ol/source/OSM';
import KML from 'ol/format/KML';
import VectorSource from 'ol/source/Vector';

var openstreet = new TileLayer({
    source: new OSM()
})

var geomapa = new VectorLayer({
    source: new VectorSource({
        url: 'maps/kml/doc.kml',
        format: new KML()
    })
});

const map = new Map({
    target: 'map',
    layers: [openstreet, geomapa],
    view: new View({
        center: [0, 0],
        zoom: 0
    })
});

Body:
Solved!

Although I am taking my first steps in openlayers using parcel, as the official documentation indicates, I must state that:

1) If a kml file is published to an external server, the web server must be configured to tell the client that the resource is a KML file, therefore, these directives must be added to the server:

2) Thinking that there was a bug in openlayers + parcel, I ran into the error

    Access to XMLHttpRequest at 'https://geo.anantara.cl/maps/kml/2012-02-10.kml'
    from origin 'http://localhost:1234' has been blocked by CORS policy:
    No 'Access-Control-Allow-Origin' header is present on the requested resource.

[http://localhost:1234/]
Failed to load resource: net::ERR_FAILED [https://geo.anantara.cl/maps/kml/2012-02-10.kml]

What means?, well it's necessary on my Apache server add the following code

 Header set Access-Control-Allow-Origin "http://127.0.0.1:1234"

And now works.., I suggest that parcel document the posting of a kml file to an external server and how the CORS setting is enabled.


问:
Keycloak password hashing alghoritm md5
I need to use the md5 hashing algorithm in my keycloak. I know that keycloak does not support md5? Is there any possibility to extend the list of hashing keycloak algorithms with the md5 algorithm?

Update:
I understand that md5 is not recommended but because of the installation with a very old system I have to use it.

答:
Keycloak supports only PBKDF2.

The only built-in and default algorithm available is PBKDF2.

https://www.keycloak.org/docs/latest/server_admin/index.html#password-policy-types

You can create a custom module (SPI) which implements PasswordHashProvider.

See also:
https://www.keycloak.org/docs/latest/server_development/#_providers

The following may be a good example.

https://github.com/leroyguillaume/keycloak-bcrypt

Title: Keycloak password hashing alghoritm md5


问:
Can someone explain why I have to instantiate subclass?
Why do you have to instantiate subclass() in the mymethod() ? I thought that we only need to make objects in the main() method.(which is done here too) Why do we have to do it twice? Is there a special property of inheritance here? </p>

```<code>class Super_class {
   int num = 20;

   // display method of superclass
   public void display() {
      System.out.println("This is the display method of superclass");
   }
}

public class Sub_class extends Super_class {
   int num = 10;

   // display method of sub class
   public void display() {
      System.out.println("This is the display method of subclass");
   }

   public void my_method() {
      // Instantiating subclass - why do you have to do this?
      Sub_class sub = new Sub_class();

      // Invoking the display() method of sub class
      sub.display();

      // Invoking the display() method of superclass
      super.display();

      // printing the value of variable num of subclass
      System.out.println("value of the variable named num in sub class:"+ sub.num);

      // printing the value of variable num of superclass
      System.out.println("value of the variable named num in super class:"+ super.num);
   }

   public static void main(String args[]) {
      Sub_class obj = new Sub_class();
      obj.my_method();
   }
}
</code>```

答:
You do not have to do that, you can call the display method of the sub class with the this keyword or even without that inside my_method() you do not need object of sub class.

But what you have done here simply created a new object inside my_method(), so basically your my_method() method and display() methods are getting called by different object.

Body:
Why do you have to instantiate subclass() in the mymethod() ? I thought that we only need to make objects in the main() method.(which is done here too) Why do we have to do it twice? Is there a special property of inheritance here?

class Super_class {
   int num = 20;

   // display method of superclass
   public void display() {
      System.out.println("This is the display method of superclass");
   }
}

public class Sub_class extends Super_class {
   int num = 10;

   // display method of sub class
   public void display() {
      System.out.println("This is the display method of subclass");
   }

   public void my_method() {
      // Instantiating subclass - why do you have to do this?
      Sub_class sub = new Sub_class();

      // Invoking the display() method of sub class
      sub.display();

      // Invoking the display() method of superclass
      super.display();

      // printing the value of variable num of subclass
      System.out.println("value of the variable named num in sub class:"+ sub.num);

      // printing the value of variable num of superclass
      System.out.println("value of the variable named num in super class:"+ super.num);
   }

   public static void main(String args[]) {
      Sub_class obj = new Sub_class();
      obj.my_method();
   }
}


问:
Plot individual data points in each group after pandas groupby
I'd like to group a dataframe using several criteria and then visualize individual data points in each group using a scattered plot.

```<code>import pandas as pd
import seaborn as sns

df_tips = sns.load_dataset('tips')
df_tips.groupby(['sex', 'day', 'smoker'])['tip']    # How could I scatter plot individual tip in each group?
</code>```

Ideally, I'd like to have something looks like this:

答:
I found a simpler way to do this and the plot is more beautiful (I think).

```<code>import pandas as pd
import seaborn as sns

df_tips = sns.load_dataset('tips')
df_tips['Groups'] = df_tips[['sex', 'day', 'smoker']].astype(str).agg('.'.join, axis=1)
sns.swarmplot(x='Groups', y='tip', data=df_tips)
plt.xticks(
    rotation=90,
    fontweight='light',
    fontsize='x-large'
)
</code>```

Here is the output:

Body:
I'd like to group a dataframe using several criteria and then visualize individual data points in each group using a scattered plot.

import pandas as pd
import seaborn as sns

df_tips = sns.load_dataset('tips')
df_tips.groupby(['sex', 'day', 'smoker'])['tip']    # How could I scatter plot individual tip in each group?

Ideally, I'd like to have something looks like this:

Body:
I found a simpler way to do this and the plot is more beautiful (I think).

import pandas as pd
import seaborn as sns

df_tips = sns.load_dataset('tips')
df_tips['Groups'] = df_tips[['sex', 'day', 'smoker']].astype(str).agg('.'.join, axis=1)
sns.swarmplot(x='Groups', y='tip', data=df_tips)
plt.xticks(
    rotation=90,
    fontweight='light',
    fontsize='x-large'
)

Here is the output:


问:
Easy way to show Decimal of Long via CountDownTimer - Android
I have working code but it seems a bit strange that I have to gimmick my way around showing a decimal place on CountDownTimer but I haven't found anything that does it easier (obviously).

Here is the working Code I currently have:

```<code>    final String tempTitle = TextView.getText().toString();

    new CountDownTimer(10000, 100) {

                 public void onTick(long millisUntilFinished) {
                     String timeDown = String.valueOf(millisUntilFinished / 100);
                     String secTime="0";
                     String sec10th="0";
                     if (Long.valueOf(millisUntilFinished) < 1000) {
                     secTime ="0";
                     sec10th = timeDown.substring(0,1);
                     }else{
                     secTime=timeDown.substring(0,1);
                     sec10th = timeDown.substring(1,2);
                     }

                     TextView.setText("Start in: " + secTime + "." + sec10th);
                 }

                 public void onFinish() {
                     TextView.setText(tempTitle);
                 }
              }.start();

    }
</code>```

答:
divide by 100.0 so you dont do integer division.

Edit per your comment:
 you could do

```<code>DecimalFormat df=new DecimalFormat("#.##"); //import java.text.DecimalFormat;
String timeDown=df.format(millisUntilFinished/100.0);
</code>```

or #.### etc depending on how many decimals you want...

ContentLicense: CC BY-SA 3.0

Body:
I have working code but it seems a bit strange that I have to gimmick my way around showing a decimal place on CountDownTimer but I haven't found anything that does it easier (obviously).

Here is the working Code I currently have:

    final String tempTitle = TextView.getText().toString();

    new CountDownTimer(10000, 100) {

                 public void onTick(long millisUntilFinished) {
                     String timeDown = String.valueOf(millisUntilFinished / 100);
                     String secTime="0";
                     String sec10th="0";
                     if (Long.valueOf(millisUntilFinished) < 1000) {
                     secTime ="0";
                     sec10th = timeDown.substring(0,1);
                     }else{
                     secTime=timeDown.substring(0,1);
                     sec10th = timeDown.substring(1,2);
                     }

                     TextView.setText("Start in: " + secTime + "." + sec10th);
                 }

                 public void onFinish() {
                     TextView.setText(tempTitle);
                 }
              }.start();

    }

Body:
divide by 100.0 so you dont do integer division.

Edit per your comment:
 you could do

DecimalFormat df=new DecimalFormat("#.##"); //import java.text.DecimalFormat;
String timeDown=df.format(millisUntilFinished/100.0);

or #.### etc depending on how many decimals you want...


问:
How to start an Android application inside my application? (example provided)
I found some launchers that are able to run installed apps inside their own activity. ( https://play.google.com/store/apps/details?id=com.lwi.android.flapps )

This launcher adds their own functions like maximize, minimize etc. I guess they are creating widgets (because they need drawing over apps permission) and running inside them. But how :)

Can you show me how I can run another android application inside my own activity, widget etc. like this app did ?

Best,
Kerg

答:
I think the following documentation should help you out with learning how to get your app to interact with other apps: https://developer.android.com/training/basics/intents

Especially interesting to you would be the section on sending the user to another app: https://developer.android.com/training/basics/intents/sending


问:
Bootstrap vue: form-group label styling
I am trying t style label for form-group in bootstrap vue, but it's not working. I have try everything but no luck. I could really need some help how to do this.

.add-style label {

color: red;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b-container>

<b-form-group class="add-style" label="Product Name">
          <b-form-input type="text" id="pName" required
                        placeholder="Enter product name"/>
        </b-form-group>

</b-container></code>```

答:
You can do it in this way:

```<code><b-container>

<b-form-group class="add-style">
          <label style="color: red;" for="pName">Product Name:</label>
          <b-form-input type="text" id="pName" required
                        placeholder="Enter product name"/>
        </b-form-group>

</b-container>
</code>```

Or, if you don't want to use inline css then you can do it in this way:

Css:

```<code>label {
    color: red;
}
</code>```

Html:

```<code><b-container>

    <b-form-group class="add-style">
              <label for="pName">Product Name:</label>
              <b-form-input type="text" id="pName" required
                            placeholder="Enter product name"/>
            </b-form-group>

    </b-container>
</code>```

Title: Bootstrap vue: form-group label styling

Body:
You can do it in this way:

<b-container>

<b-form-group class="add-style">
          <label style="color: red;" for="pName">Product Name:</label>
          <b-form-input type="text" id="pName" required
                        placeholder="Enter product name"/>
        </b-form-group>

</b-container>

Or, if you don't want to use inline css then you can do it in this way:

Css:

label {
    color: red;
}

Html:

<b-container>

    <b-form-group class="add-style">
              <label for="pName">Product Name:</label>
              <b-form-input type="text" id="pName" required
                            placeholder="Enter product name"/>
            </b-form-group>

    </b-container>


问:
String to Date Conversion in Python
In the following piece of code:

```<code>df['Year']=pd.DatetimeIndex(df['Date']).year
df['Month']=pd.DatetimeIndex(df['Date']).month
df['Day']=pd.DatetimeIndex(df['Date']).day
df['MM_DD_str']=df['Month'].astype(str).str.zfill(2)+'-'+df['Day'].astype(str).str.zfill(2)
</code>```

Since I want only MM-DD i did this way and it is a string now. But later on the program I want them in the date format. Especially I need month in order to plot a graph. Can i extract a date by extracting month from it.

Edited:

I want to plot a graph in which the Xtick should have the months like Jan, Feb, Mar upto Dec. I have to extract month from the dataframe df['MM_DD_str'] and make them as tick labels for the graph.

This is the final code i have written for plotting graph:

```<code>md_str = df['MM_DD_str']
get_month =md_str.apply(lambda d: pd.to_datetime(d, format='%m-%d').month)
#print(get_month)
plt.xticks(get_month,('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'))
plt.show()enter code here
</code>```

I am not getting neither output nor error

答:
I did not understand the question properly but
the df['date'] column could be used to plot the graph since it is already in date-time format

pd.to_datetime() can be used
so lets say

```<code>date='2019-05'
date=pd.to_datetime(date)
date.month
</code>```

EDIT:
Matplotlib needs numeric values to plot on the x axis
when you say plt.xticks() as some string values you cant plot the graph however you can change the labels . so this is an example adjust to your labels

```<code>    import matplotlib.pyplot as plt
    figure=plt.figure()
    ax=plt.axes()
    df=pd.DataFrame()
    months=['june','july','august','september']
    dates=['2019-06','2019-07','2019-08','2019-09']
    df['dates']=dates
    df['values']=[1,4,7,10]
    df['dates']=pd.to_datetime(df['dates']) #pd is for pandas
    df['values'].plot(ax=ax)
    ax.set_xticks([0,1,2,3,4])   #numerical values that get plotted
    ax.set_xticklabels(months)   #actual labels for those numerical values
</code>```

Title: String to Date Conversion in Python

Body:
In the following piece of code:

df['Year']=pd.DatetimeIndex(df['Date']).year
df['Month']=pd.DatetimeIndex(df['Date']).month
df['Day']=pd.DatetimeIndex(df['Date']).day
df['MM_DD_str']=df['Month'].astype(str).str.zfill(2)+'-'+df['Day'].astype(str).str.zfill(2)

Since I want only MM-DD i did this way and it is a string now. But later on the program I want them in the date format. Especially I need month in order to plot a graph. Can i extract a date by extracting month from it.

Edited:

I want to plot a graph in which the Xtick should have the months like Jan, Feb, Mar upto Dec. I have to extract month from the dataframe df['MM_DD_str'] and make them as tick labels for the graph.

This is the final code i have written for plotting graph:

md_str = df['MM_DD_str']
get_month =md_str.apply(lambda d: pd.to_datetime(d, format='%m-%d').month)
#print(get_month)
plt.xticks(get_month,('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'))
plt.show()enter code here

I am not getting neither output nor error

Body:
I did not understand the question properly but
the df['date'] column could be used to plot the graph since it is already in date-time format

pd.to_datetime() can be used
so lets say

date='2019-05'
date=pd.to_datetime(date)
date.month

EDIT:
Matplotlib needs numeric values to plot on the x axis
when you say plt.xticks() as some string values you cant plot the graph however you can change the labels . so this is an example adjust to your labels

    import matplotlib.pyplot as plt
    figure=plt.figure()
    ax=plt.axes()
    df=pd.DataFrame()
    months=['june','july','august','september']
    dates=['2019-06','2019-07','2019-08','2019-09']
    df['dates']=dates
    df['values']=[1,4,7,10]
    df['dates']=pd.to_datetime(df['dates']) #pd is for pandas
    df['values'].plot(ax=ax)
    ax.set_xticks([0,1,2,3,4])   #numerical values that get plotted
    ax.set_xticklabels(months)   #actual labels for those numerical values


问:
How to make initialCameraPosition from my address in flutter google maps?
I tried to determine my address's camera position by using 'geolocator' library but I don't know how to set it into the google map's initial camera position</p>

```<code>searchAndNavigate() {
      searchAddress = widget.author.address;
      Geolocator().placemarkFromAddress(searchAddress).then((result) {
        mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
            target:
            LatLng(result[0].position.latitude, result[0].position.longitude),
            zoom: 10.0)));
      });
    }

    void onMapCreated(controller) {
      setState(() {
        mapController = controller;
      });
    }

    Widget mapSection = Container(
      height: 400,
      width: 400,
      child: Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)),
        child: GoogleMap(
          onMapCreated: onMapCreated,
          initialCameraPosition: CameraPosition(
            target: LatLng(40.7128, -74.0060), zoom: 10.0)),
      ),
    );

    @override
    void initState() {
      super.initState();
      searchAndNavigate();
    }
</code>```

答:
If you have to implement that, you need to give it a custom location or display a loader while your app gets your current location. After the app gets your current location you have to call a camera update to move the view to your current location.

You could give this a shot that should work perfectly.
  Remember you don't have watch position. You can just get position and move the camera to that position after the position has been returned.

```<code>import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';

class Home extends StatefulWidget {
  @override
  State<Home> createState() => HomeState();

}

class HomeState extends State<Home> {
  GoogleMapController mapController;
  Location _location = Location();
  LocationData _locationData;

  watchLocation() async{

    _location.onLocationChanged.listen((LocationData currentLocation) {

      LatLng latLng = LatLng(currentLocation.latitude, currentLocation.longitude);
      CameraUpdate cameraUpdate = CameraUpdate.newLatLngZoom(latLng, 15);
      mapController.animateCamera(cameraUpdate);

      setState(() {
        this._locationData = currentLocation;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    watchLocation();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: Stack(
        children: <Widget>[
          GoogleMap(
            myLocationEnabled: true,
            mapToolbarEnabled: true,
            zoomControlsEnabled: false,
            myLocationButtonEnabled: false,
            mapType: MapType.normal,
            initialCameraPosition: CameraPosition(
              target: LatLng(this._locationData?.latitude ?? 6.7008168, this._locationData?.longitude ?? -1.6998494),
              zoom: 14.4746,
            ),
            onMapCreated: (GoogleMapController controller) {
              setState(() {
                mapController = controller;
              });
          ),
          )
        ],
      ),
    );
  }
}

</code>```

Body:
I tried to determine my address's camera position by using 'geolocator' library but I don't know how to set it into the google map's initial camera position

searchAndNavigate() {
      searchAddress = widget.author.address;
      Geolocator().placemarkFromAddress(searchAddress).then((result) {
        mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
            target:
            LatLng(result[0].position.latitude, result[0].position.longitude),
            zoom: 10.0)));
      });
    }

    void onMapCreated(controller) {
      setState(() {
        mapController = controller;
      });
    }

    Widget mapSection = Container(
      height: 400,
      width: 400,
      child: Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)),
        child: GoogleMap(
          onMapCreated: onMapCreated,
          initialCameraPosition: CameraPosition(
            target: LatLng(40.7128, -74.0060), zoom: 10.0)),
      ),
    );

    @override
    void initState() {
      super.initState();
      searchAndNavigate();
    }

Body:
If you have to implement that, you need to give it a custom location or display a loader while your app gets your current location. After the app gets your current location you have to call a camera update to move the view to your current location.

You could give this a shot that should work perfectly.
  Remember you don't have watch position. You can just get position and move the camera to that position after the position has been returned.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';

class Home extends StatefulWidget {
  @override
  State<Home> createState() => HomeState();

}

class HomeState extends State<Home> {
  GoogleMapController mapController;
  Location _location = Location();
  LocationData _locationData;

  watchLocation() async{

    _location.onLocationChanged.listen((LocationData currentLocation) {

      LatLng latLng = LatLng(currentLocation.latitude, currentLocation.longitude);
      CameraUpdate cameraUpdate = CameraUpdate.newLatLngZoom(latLng, 15);
      mapController.animateCamera(cameraUpdate);

      setState(() {
        this._locationData = currentLocation;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    watchLocation();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: Stack(
        children: <Widget>[
          GoogleMap(
            myLocationEnabled: true,
            mapToolbarEnabled: true,
            zoomControlsEnabled: false,
            myLocationButtonEnabled: false,
            mapType: MapType.normal,
            initialCameraPosition: CameraPosition(
              target: LatLng(this._locationData?.latitude ?? 6.7008168, this._locationData?.longitude ?? -1.6998494),
              zoom: 14.4746,
            ),
            onMapCreated: (GoogleMapController controller) {
              setState(() {
                mapController = controller;
              });
          ),
          )
        ],
      ),
    );
  }
}


问:
PM scaffold-dbcontext not creating a primary key
I am reverse engineering our db.  I am using scaffold-dbcontext in the package manager console with the -force flag.  I know for sure it is updating the files.

I have added a Primary key in the db though and when that didn't work I even added another Index:

The dbcontext that was created seems to have the code for the Primary Key:

```<code>modelBuilder.Entity<DealerDisclaimers>(entity =>
    {
        entity.HasKey(e => e.DealerDisclaimerId)
            .HasName("PK_DealerDisclaimers");
</code>```

However, when I try to navigate to a page that would load that table it gives the following error:

InvalidOperationException: The entity type 'DealerDisclaimers'
  requires a primary key to be defined.

The DealerDisclaimers class the scaffold-dbcontext builds out looks like this:

```<code>public partial class DealerDisclaimers
    {
        public int DealerDisclaimerId { get; set; }
        public int DealerId { get; set; }
        public string GeneralDisclaimer { get; set; }
        public string LeaseDisclaimer { get; set; }

        public virtual Dealer Dealer { get; set; }
    }
</code>```

Side note: If I add the [Key] attribute then it loads without the error.  But I shouldn't have to manually add it, the scaffold-dbcontext command should prepare everything for me.

答:
Simply adding -DataAnnotations to the scaffold code added the key appropriately for me.

So my script looked like this:

```<code>Scaffold-DbContext "Server=MyServer;Database=MyDatabase;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -Force -DataAnnotations
</code>```

Body:
I am reverse engineering our db.  I am using scaffold-dbcontext in the package manager console with the -force flag.  I know for sure it is updating the files.

I have added a Primary key in the db though and when that didn't work I even added another Index:

The dbcontext that was created seems to have the code for the Primary Key:

modelBuilder.Entity<DealerDisclaimers>(entity =>
    {
        entity.HasKey(e => e.DealerDisclaimerId)
            .HasName("PK_DealerDisclaimers");

However, when I try to navigate to a page that would load that table it gives the following error:

InvalidOperationException: The entity type 'DealerDisclaimers'
  requires a primary key to be defined.

The DealerDisclaimers class the scaffold-dbcontext builds out looks like this:

public partial class DealerDisclaimers
    {
        public int DealerDisclaimerId { get; set; }
        public int DealerId { get; set; }
        public string GeneralDisclaimer { get; set; }
        public string LeaseDisclaimer { get; set; }

        public virtual Dealer Dealer { get; set; }
    }

Side note: If I add the [Key] attribute then it loads without the error.  But I shouldn't have to manually add it, the scaffold-dbcontext command should prepare everything for me.

Body:
Simply adding -DataAnnotations to the scaffold code added the key appropriately for me.

So my script looked like this:

Scaffold-DbContext "Server=MyServer;Database=MyDatabase;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -Force -DataAnnotations


问:
What's the best way to get rid of nested ifs in code while checking for conditions?
I'm developing a BlackBerry app in Java and I have an Options class where all user settings are stored. The problem is I need to check some conditions in order to know how to react. As I keep adding more features, more GUI options are shown to the user, more settings are stored in the Options class and more conditions need to be checked for.

Take the following code for example:

```<code>private void doCallMonitoring(int callId){
    /*This is the part that I want to avoid. Having
      multiple nested ifs. Here's just two conditions
      but as I add more, it will get unmantainable
      very quickly.*/
    if(Options.isActive().booleanValue()){
        callTime = new Timer();
        TimerTask callTimeTask = new TimerTask(){
            public void run(){
                callTimeSeconds++;
        if((callTimeSeconds == Options.getSoftLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectDTMFTone(Phone.getActiveCall());
        }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectEndCall();
                }
             }
        };
        callTime.schedule(callTimeTask, 0,1000);
    }else{
    System.out.println("Service not active");
    }
}
</code>```

How I would want it to work is to verify all options with a single call and from there determine the curse of action. How can I achieve such a design?

答:
All those answers are probably better OO answers.  For once I'll go for the quick and dirty answer.

I really like to simplify complex nested ifs like that by inverting them.

```<code>if(!Options.isActive().booleanValue()) {
    System.out.println("Service not active");
    return;
}
the rest...
</code>```

I know some people don't like mid-method returns, but when you are validating entry conditions that has always been an awesome pattern for me, I've never regretted using it.

It really simplifies the way your method looks.

If you write methods longer than a screen, don't do this or write a large comment pointing it out--It's too easy to lose the return statement and forget you did it.  Better yet, don't write methods longer than a screen.

OwnerDisplayName: Cesar

ContentLicense: CC BY-SA 2.5

Body:
I'm developing a BlackBerry app in Java and I have an Options class where all user settings are stored. The problem is I need to check some conditions in order to know how to react. As I keep adding more features, more GUI options are shown to the user, more settings are stored in the Options class and more conditions need to be checked for.

Take the following code for example:

private void doCallMonitoring(int callId){
    /*This is the part that I want to avoid. Having
      multiple nested ifs. Here's just two conditions
      but as I add more, it will get unmantainable
      very quickly.*/
    if(Options.isActive().booleanValue()){
        callTime = new Timer();
        TimerTask callTimeTask = new TimerTask(){
            public void run(){
                callTimeSeconds++;
        if((callTimeSeconds == Options.getSoftLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectDTMFTone(Phone.getActiveCall());
        }else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
                    injectEndCall();
                }
             }
        };
        callTime.schedule(callTimeTask, 0,1000);
    }else{
    System.out.println("Service not active");
    }
}

How I would want it to work is to verify all options with a single call and from there determine the curse of action. How can I achieve such a design?

Body:
All those answers are probably better OO answers.  For once I'll go for the quick and dirty answer.

I really like to simplify complex nested ifs like that by inverting them.

if(!Options.isActive().booleanValue()) {
    System.out.println("Service not active");
    return;
}
the rest...

I know some people don't like mid-method returns, but when you are validating entry conditions that has always been an awesome pattern for me, I've never regretted using it.

It really simplifies the way your method looks.

If you write methods longer than a screen, don't do this or write a large comment pointing it out--It's too easy to lose the return statement and forget you did it.  Better yet, don't write methods longer than a screen.

OwnerDisplayName: Bill K


问:
How to get URL parameters names only and not values
There are hundreds of example out here showing how to get URL parameters but I couldn't find any to list ONLY parameters (variables) name and not values?

For example, if I have something like:

```<code>www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008
</code>```

I want to get only makes,models,years and if URL change to

```<code>www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler
</code>```

should be like makes,models

or on

```<code>www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008,2010&city=vancouver
</code>```

the out should be like makes,models,years,city

答:
You can use URLSearchParams

Sample:

const queryString = "?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008"

const urlParams = new URLSearchParams(queryString);

console.log([...new URLSearchParams(urlParams).keys()]);```

Body:
There are hundreds of example out here showing how to get URL parameters but I couldn't find any to list ONLY parameters (variables) name and not values?

For example, if I have something like:

www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008

I want to get only makes,models,years and if URL change to

www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler

should be like makes,models

or on

www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008,2010&city=vancouver

the out should be like makes,models,years,city


答:
console.log(
  [...new URLSearchParams(window.location.search).keys()].join(',')
);```

Title: How to get URL parameters names only and not values


答: You don't need to instantiate a new object, and in fact, I would consider that a bad coding practice.  What you need to do is reference the current object using the this keyword, or just calling display();, which implicitly means this.display();.  If you create a new object, if there are any instance variables set, they would reset to their default values because the instance you are referencing is not the same instance the method was called on, so you could get unexpected behavior.

Title: Can someone explain why I have to instantiate subclass?


问:
no String-argument constructor/factory method to deserialize from String value - Exception while deserializing json object from restTemplate
Facing issue while making call to retrieve a json response and parse it.

```<code>[
    {
        "name": "john doe",
        "age": "24",
        "address": "{\"state\":\"LA\",\"country\":\"US\"}"
    }
]
</code>```

Models:

Person.java

```<code>@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
    private String name;
    private String age;
    private Address address;
}
</code>```

Address .java

```<code>@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Address {
    private String state;
    private String country;
}
</code>```

Code to read this data,

```<code>ResponseEntity<List<Person>> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET,requestEntity,new ParameterizedTypeReference<List<Person>>() {});
</code>```

However i get below exception,

RestClientException while invoking ABS ServiceError while extracting response for type [java.util.List<com.bp.model.Person>] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of com.bp.model.Address (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"state":"LA","country":"US"}'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.bp.model.Address (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"state":"IN","brand":"anthem"}')
at [Source: (PushbackInputStream); line: 1, column: 325] (through reference chain: java.util.ArrayList[0]->com.bp.model.Person["address"])

答:
The code is correct but there's a problem with the JSON. The address is a string and not a JSON object. For it to work, it would need to be something like:

```<code>"address": {"state": "LA", "country": "US"}
</code>```

Without the outer quotes and the escape characters.

Body:
Facing issue while making call to retrieve a json response and parse it.

[
    {
        "name": "john doe",
        "age": "24",
        "address": "{\"state\":\"LA\",\"country\":\"US\"}"
    }
]

Models:

Person.java

@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
    private String name;
    private String age;
    private Address address;
}

Address .java

@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class Address {
    private String state;
    private String country;
}

Code to read this data,

ResponseEntity<List<Person>> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET,requestEntity,new ParameterizedTypeReference<List<Person>>() {});

However i get below exception,

RestClientException while invoking ABS ServiceError while extracting response for type [java.util.List<com.bp.model.Person>] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of com.bp.model.Address (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"state":"LA","country":"US"}'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.bp.model.Address (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"state":"IN","brand":"anthem"}')
at [Source: (PushbackInputStream); line: 1, column: 325] (through reference chain: java.util.ArrayList[0]->com.bp.model.Person["address"])

Body:
The code is correct but there's a problem with the JSON. The address is a string and not a JSON object. For it to work, it would need to be something like:

"address": {"state": "LA", "country": "US"}

Without the outer quotes and the escape characters.


问:
Can't find ~/.vim/bundle directory on Mac
I am trying to install YouCompleteMe on Mac and following the procedure, I am not able to locate ~/.vim/bundle. I can locate .vim in my home folder but there is no directory bundle inside it.

I am following this link https://github.com/ycm-core/YouCompleteMe/blob/master/README.md#installation to install YouCompleteMe.

答: You first need to install vundle Plugin Manager that will create this folder for you. </p>


问:
Accessing a list with only recursion and lambdas
As part of my homework I have to access every element o a list without a for loop to use it in a function I'm allowed to use, e.g:

```<code>myList=['Hello','World']
</code>```

I've tried using lambda functions (Because I'm not allowed to declare functions with Def) but didn't work.

```<code>function(next(myList))
</code>```

Also tried using next(myList) but sometimes the list can have 1000+ elements.

答:
If you can use function you can use that trick

You can use recursion to access all elements.

At first create a function to read first element and delete that element.

Use that function again and again until the list is empty.

```<code>def show(my_list):
   try:
      print(my_list[0])
      del my_list[0]
      show(my_list)
   except:
      pass
</code>```

Or if you want to do some action

```<code>new = []
def action(my_list):
   try:
      x = do_something(my_list[0])
      del my_list[0]
      new.append(x)
      action(my_list)
   except:
      pass
</code>```

Here do_something(data) is your custom function.

Body:
As part of my homework I have to access every element o a list without a for loop to use it in a function I'm allowed to use, e.g:

myList=['Hello','World']

I've tried using lambda functions (Because I'm not allowed to declare functions with Def) but didn't work.

function(next(myList))

Also tried using next(myList) but sometimes the list can have 1000+ elements.

Body:
If you can use function you can use that trick

You can use recursion to access all elements.

At first create a function to read first element and delete that element.

Use that function again and again until the list is empty.

def show(my_list):
   try:
      print(my_list[0])
      del my_list[0]
      show(my_list)
   except:
      pass

Or if you want to do some action

new = []
def action(my_list):
   try:
      x = do_something(my_list[0])
      del my_list[0]
      new.append(x)
      action(my_list)
   except:
      pass

Here do_something(data) is your custom function.


问:
SSH tunneling 2 gateways via JSch
I wonder if its possible to extend the answer in SSH tunneling via JSch to a case where I have two gateways (two points) before the final host.

What I tried was

```<code>import com.jcraft.jsch.*;

import java.io.InputStream;

public class Main {
    public static void main(String[] args){
        Main t=new Main();
        try{
            t.go();
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public void go() throws Exception{

        StringBuilder outputBuffer = new StringBuilder();

        String Gateway1="192.168.0.101"; // First level target
        String user1="root";
        String password="12qwaszx";
        String Gateway2="192.168.0.102"; // The host of the second target
        String user2 = "root";
        String secondPassword="12qwaszx";
        String endpoint = "10.81.77.52";
        String finaluser="admin";
        String finaluserpass="admin";

        JSch jsch=new JSch();
        Session session=jsch.getSession(user1, Gateway1, 22);
        session.setPassword(password);
        localUserInfo lui=new localUserInfo();
        session.setUserInfo(lui);
        session.setConfig("StrictHostKeyChecking", "no");
        // create port from 2233 on local system to port 22 on tunnelRemoteHost
        session.setPortForwardingL(2233, Gateway2, 22);
        session.connect();
        session.openChannel("direct-tcpip");

        // create a session connected to port 2233 on the local host.
        Session secondSession = jsch.getSession(user2, "localhost", 2233);
        secondSession.setPassword(secondPassword);
        secondSession.setUserInfo(lui);
        secondSession.setConfig("StrictHostKeyChecking", "no");
        secondSession.setPortForwardingL(2233, endpoint, 22);
        secondSession.connect(); // now we're connected to the secondary system
        secondSession.openChannel("direct-tcpip");

        Session finalSession = jsch.getSession(finaluser, "localhost", 2233);
        finalSession.setPassword(finaluserpass);
        finalSession.setUserInfo(lui);
        finalSession.setConfig("StrictHostKeyChecking", "no");
        finalSession.connect();

        Channel channel=secondSession.openChannel("exec");
        ((ChannelExec)channel).setCommand("show system information | match \"System Name\"");

        channel.setInputStream(null);

        InputStream stdout=channel.getInputStream();

        channel.connect();
        if (channel.isConnected()){
            System.out.println("connected");
        }

        while (true) {
            byte[] tmpArray=new byte[1024];
            while(stdout.available() > 0){
                int i=stdout.read(tmpArray, 0, 1024);
                if(i<0)break;
                outputBuffer.append(new String(tmpArray, 0, i));
            }
            if(channel.isClosed()){
                System.out.println("exit-status: "+channel.getExitStatus());
                break;
            }
        }
        stdout.close();

        channel.disconnect();

        secondSession.disconnect();
        session.disconnect();

        System.out.print(outputBuffer.toString());
    }

    class localUserInfo implements UserInfo {
        String passwd;
        public String getPassword(){ return passwd; }
        public boolean promptYesNo(String str){return true;}
        public String getPassphrase(){ return null; }
        public boolean promptPassphrase(String message){return true; }
        public boolean promptPassword(String message){return true;}
        public void showMessage(String message){}
    }
}
</code>```

But despite my efforts, I don't actually get to connect to the endpoint. Getting

```<code>com.jcraft.jsch.JSchException: PortForwardingL: local port 127.0.0.1:2233 cannot be bound.
    at com.jcraft.jsch.PortWatcher.<init>(PortWatcher.java:158)
    at com.jcraft.jsch.PortWatcher.addPort(PortWatcher.java:110)
    at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1847)
    at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1828)
    at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1809)
    at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1792)
    at Main.go(Main.java:36)
    at Main.main(Main.java:9)
Caused by: java.net.BindException: Address already in use: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
    at java.net.ServerSocket.bind(ServerSocket.java:375)
    at java.net.ServerSocket.<init>(ServerSocket.java:237)
    at com.jcraft.jsch.PortWatcher.<init>(PortWatcher.java:150)
    ... 7 more

Process finished with exit code 0
</code>```

Please, if anyone could help me. I need to Get to the endpoint by ssh tunneling two gateways.

答:
I swear I didn't meant it,

but the problem was that the first lport was equal to the second.

it worked like bellow:

```<code>  session.setPortForwardingL(2222, Gateway2, 22);
  session.connect();
  session.openChannel("direct-tcpip");

  Session secondSession = jsch.getSession(user2, "localhost", 2222);
</code>```

Title: SSH tunneling 2 gateways via JSch

Body:
I wonder if its possible to extend the answer in SSH tunneling via JSch to a case where I have two gateways (two points) before the final host.

What I tried was

import com.jcraft.jsch.*;

import java.io.InputStream;

public class Main {
    public static void main(String[] args){
        Main t=new Main();
        try{
            t.go();
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public void go() throws Exception{

        StringBuilder outputBuffer = new StringBuilder();

        String Gateway1="192.168.0.101"; // First level target
        String user1="root";
        String password="12qwaszx";
        String Gateway2="192.168.0.102"; // The host of the second target
        String user2 = "root";
        String secondPassword="12qwaszx";
        String endpoint = "10.81.77.52";
        String finaluser="admin";
        String finaluserpass="admin";

        JSch jsch=new JSch();
        Session session=jsch.getSession(user1, Gateway1, 22);
        session.setPassword(password);
        localUserInfo lui=new localUserInfo();
        session.setUserInfo(lui);
        session.setConfig("StrictHostKeyChecking", "no");
        // create port from 2233 on local system to port 22 on tunnelRemoteHost
        session.setPortForwardingL(2233, Gateway2, 22);
        session.connect();
        session.openChannel("direct-tcpip");

        // create a session connected to port 2233 on the local host.
        Session secondSession = jsch.getSession(user2, "localhost", 2233);
        secondSession.setPassword(secondPassword);
        secondSession.setUserInfo(lui);
        secondSession.setConfig("StrictHostKeyChecking", "no");
        secondSession.setPortForwardingL(2233, endpoint, 22);
        secondSession.connect(); // now we're connected to the secondary system
        secondSession.openChannel("direct-tcpip");

        Session finalSession = jsch.getSession(finaluser, "localhost", 2233);
        finalSession.setPassword(finaluserpass);
        finalSession.setUserInfo(lui);
        finalSession.setConfig("StrictHostKeyChecking", "no");
        finalSession.connect();

        Channel channel=secondSession.openChannel("exec");
        ((ChannelExec)channel).setCommand("show system information | match \"System Name\"");

        channel.setInputStream(null);

        InputStream stdout=channel.getInputStream();

        channel.connect();
        if (channel.isConnected()){
            System.out.println("connected");
        }

        while (true) {
            byte[] tmpArray=new byte[1024];
            while(stdout.available() > 0){
                int i=stdout.read(tmpArray, 0, 1024);
                if(i<0)break;
                outputBuffer.append(new String(tmpArray, 0, i));
            }
            if(channel.isClosed()){
                System.out.println("exit-status: "+channel.getExitStatus());
                break;
            }
        }
        stdout.close();

        channel.disconnect();

        secondSession.disconnect();
        session.disconnect();

        System.out.print(outputBuffer.toString());
    }

    class localUserInfo implements UserInfo {
        String passwd;
        public String getPassword(){ return passwd; }
        public boolean promptYesNo(String str){return true;}
        public String getPassphrase(){ return null; }
        public boolean promptPassphrase(String message){return true; }
        public boolean promptPassword(String message){return true;}
        public void showMessage(String message){}
    }
}

But despite my efforts, I don't actually get to connect to the endpoint. Getting

com.jcraft.jsch.JSchException: PortForwardingL: local port 127.0.0.1:2233 cannot be bound.
    at com.jcraft.jsch.PortWatcher.<init>(PortWatcher.java:158)
    at com.jcraft.jsch.PortWatcher.addPort(PortWatcher.java:110)
    at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1847)
    at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1828)
    at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1809)
    at com.jcraft.jsch.Session.setPortForwardingL(Session.java:1792)
    at Main.go(Main.java:36)
    at Main.main(Main.java:9)
Caused by: java.net.BindException: Address already in use: JVM_Bind
    at java.net.DualStackPlainSocketImpl.bind0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
    at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
    at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
    at java.net.ServerSocket.bind(ServerSocket.java:375)
    at java.net.ServerSocket.<init>(ServerSocket.java:237)
    at com.jcraft.jsch.PortWatcher.<init>(PortWatcher.java:150)
    ... 7 more

Process finished with exit code 0

Please, if anyone could help me. I need to Get to the endpoint by ssh tunneling two gateways.

Body:
I swear I didn't meant it,

but the problem was that the first lport was equal to the second.

it worked like bellow:

  session.setPortForwardingL(2222, Gateway2, 22);
  session.connect();
  session.openChannel("direct-tcpip");

  Session secondSession = jsch.getSession(user2, "localhost", 2222);


问:
Compiling multiple jar and java files using javac
I downloaded a sample code written in java that has multiple jar files and java files. I am not a Java programmer so I am having a hard time compiling the code. Here's my attempt:

```<code>javac -classpath lib/*.jar src/*.java
</code>```

However this is what I get:

```<code>javac: invalid flag: lib/dom4j-1.6.1.jar
Usage: javac <options> <source files>
use -help for a list of possible options
</code>```

What's wrong with my approach and how can I compile the code? ALl the jar files are located in the lib folder, and the java files in the src folder.

答:
old post, but thought below details help,
you can specify jar files by separating by ; in windows and : in unix

Eg: (windows)

```<code>javac -cp first.jar;second.jar;third.jar YourClass.java
</code>```

(unix)

```<code>javac -cp first.jar:second.jar:third.jar YourClass.java
</code>```

Source: https://gullele.com/pass-all-the-jars-in-classpath-when-compiling-java/

Body:
I downloaded a sample code written in java that has multiple jar files and java files. I am not a Java programmer so I am having a hard time compiling the code. Here's my attempt:

javac -classpath lib/*.jar src/*.java

However this is what I get:

javac: invalid flag: lib/dom4j-1.6.1.jar
Usage: javac <options> <source files>
use -help for a list of possible options

What's wrong with my approach and how can I compile the code? ALl the jar files are located in the lib folder, and the java files in the src folder.

Body:
old post, but thought below details help,
you can specify jar files by separating by ; in windows and : in unix

Eg: (windows)

javac -cp first.jar;second.jar;third.jar YourClass.java

(unix)

javac -cp first.jar:second.jar:third.jar YourClass.java

Source: https://gullele.com/pass-all-the-jars-in-classpath-when-compiling-java/


问:
Find unique name of device?
I'm developing an app that uses zeroconf (bonjour) to discover devices - so I need to give each android device some kind of name (not just a bunch of numbers and letters, but something meaningful like "Alex's Device"). In iOS it can be easily done - is this possible in android?</p>

答:
Assuming your application requires a device to have a network connection, you can try using the MAC address of the device, which should be globally unique. This can be obtained with the WifiInfo class:

```<code>WifiManager manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String macAddress = info.getMacAddress();
</code>```

You'll also need to set the ACCESS_WIFI_STATE permission in your manifest.

Title: Find unique name of device?

Body:
Assuming your application requires a device to have a network connection, you can try using the MAC address of the device, which should be globally unique. This can be obtained with the WifiInfo class:

WifiManager manager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String macAddress = info.getMacAddress();

You'll also need to set the ACCESS_WIFI_STATE permission in your manifest.


问:
How to fetch the last item in a JSON in C#
I'm trying to get a single value out of a JSON response from Azure Rest API.

Below is my code where I was able to get to final array but unable to fetch the last item from this array.

```<code>            string token = await GetAccessToken(GMETenantID, GMEClientID, GMEAppKey);

            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://management.azure.com/subscriptions/")
            };
            string URI = $"/subscriptions/{SubscriptionGUID}/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);

            var HttpsResponse = await response.Content.ReadAsStringAsync();
            dynamic Result = JsonConvert.DeserializeObject<object>(HttpsResponse);

            foreach (dynamic item in Result["value"])
            {
                string StorageID = item.id;
                string StorageAccountName = item.name;
                string ResourceType = item.type;

                int CharsToRemove = 12 + ResourceType.Length + StorageAccountName.Length;

                string ResourceGroupName = StorageID.Remove(0,67);
                ResourceGroupName = ResourceGroupName.Remove(ResourceGroupName.Length - CharsToRemove);

                string StartTime = DateTime.Now.AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ss") + "Z"; ;
                string EndTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "Z";

                var BlobhttpClient = new HttpClient
                {
                    BaseAddress = new Uri("https://management.azure.com/subscriptions/")
                };

                string BlobURI = $"/subscriptions/{SubscriptionGUID}/resourceGroups/{ResourceGroupName}/providers/{ResourceType}/{StorageAccountName}/blobServices/default/providers/microsoft.insights/metrics?timespan={StartTime}/{EndTime}&aggregation=average&metricnames=BlobCapacity&api-version=2018-01-01";
                BlobhttpClient.DefaultRequestHeaders.Remove("Authorization");
                BlobhttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                HttpResponseMessage Blobresponse = await httpClient.GetAsync(BlobURI).ConfigureAwait(false);
                var BlobHttpsResponse = await Blobresponse.Content.ReadAsStringAsync();

                dynamic value = JObject.Parse(BlobHttpsResponse);

                foreach (dynamic List1 in value["value"])
                {
                    foreach (dynamic List2 in List1["timeseries"])
                    {
                        foreach (dynamic List3 in List2["data"])
                        {
                            Console.WriteLine((long?)List3["average"]);
                        }
                    }
                }
            }
            Console.ReadLine();
</code>```

I also feel there must be an easier way to get this one value out instead of using 3 Foreach loops.

HttpsResponse: (There are a 168 timestamp and average values in the actual response but i've put only 3 values)

```<code>{
  "cost": 0,
  "timespan": "2020-05-22T03:04:46Z/2020-05-29T03:04:46Z",
  "interval": "PT1H",
  "value": [
    {
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/MyResourceGroupName/providers/Microsoft.Storage/storageAccounts/MyAstorageAccountName/blobServices/default/providers/Microsoft.Insights/metrics/BlobCapacity",
      "type": "Microsoft.Insights/metrics",
      "name": {
        "value": "BlobCapacity",
        "localizedValue": "Blob Capacity"
      },
      "displayDescription": "The amount of storage used by the storage account's Blob service in bytes.",
      "unit": "Bytes",
      ".timeseries": [
        {
          "metadatavalues": [],
          "data": [
            {
              "timeStamp": "2020-05-22T03:04:00Z",
              "average": 586904516140.0
            },
            {
              "timeStamp": "2020-05-22T04:04:00Z",
              "average": 587058965680.0
            },
            {
              "timeStamp": "2020-05-22T05:04:00Z",
              "average": 587058965680.0
            }
          ]
        }
      ],
      "errorCode": "Success"
    }
  ],
  "namespace": "Microsoft.Storage/storageAccounts/blobServices",
  "resourceregion": "eastus2"
}
</code>```

All I want is the number 587058965680 which is the last value of the JSON and the most recent timestamp.

Pretty much I want to get exact result the way I'm getting in below powershell code
PowerShell works like a charm in 4 lines but I had to write so many lines in C#

```<code>$StorageAccounts = Get-AzStorageAccount -ResourceGroupName "My ResourceGroupName"

$StorageAccountID = $StorageAccounts.ID + "/blobServices/default"
$Start = (get-date).AddDays(-7)
$End = get-date

$Metric = Get-AzMetric -ResourceId $StorageAccountID -MetricName "BlobCapacity" -StartTime $Start -EndTime $End  -WarningAction Ignore

$ContainerSize = ($Metric.Data | sort-object -Descending Average | Select-Object -First 1).Average/1024/1024/1024
</code>```

答:
I somehow solved it using a weird logic :)

string token = await GetAccessToken(GMETenantID, GMEClientID, GMEAppKey);

            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://management.azure.com/subscriptions/")
            };
            string URI = $"/subscriptions/{SubscriptionGUID}/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);

            var HttpsResponse = await response.Content.ReadAsStringAsync();
            dynamic Result = JsonConvert.DeserializeObject<object>(HttpsResponse);

            foreach (dynamic item in Result["value"])
            {
                string StorageID = item.id;
                string StorageAccountName = item.name;
                string ResourceType = item.type;

                int CharsToRemove = 12 + ResourceType.Length + StorageAccountName.Length;

                string ResourceGroupName = StorageID.Remove(0,67);
                ResourceGroupName = ResourceGroupName.Remove(ResourceGroupName.Length - CharsToRemove);

                string StartTime = DateTime.Now.AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ss") + "Z"; ;
                string EndTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "Z";

                var BlobhttpClient = new HttpClient
                {
                    BaseAddress = new Uri("https://management.azure.com/subscriptions/")
                };

                string BlobURI = $"/subscriptions/{SubscriptionGUID}/resourceGroups/{ResourceGroupName}/providers/{ResourceType}/{StorageAccountName}/blobServices/default/providers/microsoft.insights/metrics?timespan={StartTime}/{EndTime}&aggregation=average&metricnames=BlobCapacity&api-version=2018-01-01";
                BlobhttpClient.DefaultRequestHeaders.Remove("Authorization");
                BlobhttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                HttpResponseMessage Blobresponse = await httpClient.GetAsync(BlobURI).ConfigureAwait(false);
                var BlobHttpsResponse = await Blobresponse.Content.ReadAsStringAsync();

                dynamic value = JObject.Parse(BlobHttpsResponse);
                long FinalValue = 0;
                foreach (dynamic List1 in value["value"])
                {
                    foreach (dynamic List2 in List1["timeseries"])
                    {
                        foreach (dynamic List3 in List2["data"])
                        {
                            if (List3["average"] != null)
                            {
                                long NewData = List3["average"];

                                if (NewData > FinalValue)
                                {
                                    FinalValue = NewData;
                                }
                                else if (NewData > FinalValue)
                                {
                                    FinalValue = NewData;
                                }

                            }
                        }
                    }
                }
                Console.WriteLine("");
                Console.WriteLine(FinalValue);
                Console.WriteLine($"Done with StorageAccount: {StorageAccountName}");
            }
            Console.ReadLine();```

Body:
I'm trying to get a single value out of a JSON response from Azure Rest API.

Below is my code where I was able to get to final array but unable to fetch the last item from this array.

            string token = await GetAccessToken(GMETenantID, GMEClientID, GMEAppKey);

            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://management.azure.com/subscriptions/")
            };
            string URI = $"/subscriptions/{SubscriptionGUID}/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);

            var HttpsResponse = await response.Content.ReadAsStringAsync();
            dynamic Result = JsonConvert.DeserializeObject<object>(HttpsResponse);

            foreach (dynamic item in Result["value"])
            {
                string StorageID = item.id;
                string StorageAccountName = item.name;
                string ResourceType = item.type;

                int CharsToRemove = 12 + ResourceType.Length + StorageAccountName.Length;

                string ResourceGroupName = StorageID.Remove(0,67);
                ResourceGroupName = ResourceGroupName.Remove(ResourceGroupName.Length - CharsToRemove);

                string StartTime = DateTime.Now.AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ss") + "Z"; ;
                string EndTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "Z";

                var BlobhttpClient = new HttpClient
                {
                    BaseAddress = new Uri("https://management.azure.com/subscriptions/")
                };

                string BlobURI = $"/subscriptions/{SubscriptionGUID}/resourceGroups/{ResourceGroupName}/providers/{ResourceType}/{StorageAccountName}/blobServices/default/providers/microsoft.insights/metrics?timespan={StartTime}/{EndTime}&aggregation=average&metricnames=BlobCapacity&api-version=2018-01-01";
                BlobhttpClient.DefaultRequestHeaders.Remove("Authorization");
                BlobhttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                HttpResponseMessage Blobresponse = await httpClient.GetAsync(BlobURI).ConfigureAwait(false);
                var BlobHttpsResponse = await Blobresponse.Content.ReadAsStringAsync();

                dynamic value = JObject.Parse(BlobHttpsResponse);

                foreach (dynamic List1 in value["value"])
                {
                    foreach (dynamic List2 in List1["timeseries"])
                    {
                        foreach (dynamic List3 in List2["data"])
                        {
                            Console.WriteLine((long?)List3["average"]);
                        }
                    }
                }
            }
            Console.ReadLine();

I also feel there must be an easier way to get this one value out instead of using 3 Foreach loops.

HttpsResponse: (There are a 168 timestamp and average values in the actual response but i've put only 3 values)

{
  "cost": 0,
  "timespan": "2020-05-22T03:04:46Z/2020-05-29T03:04:46Z",
  "interval": "PT1H",
  "value": [
    {
      "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/MyResourceGroupName/providers/Microsoft.Storage/storageAccounts/MyAstorageAccountName/blobServices/default/providers/Microsoft.Insights/metrics/BlobCapacity",
      "type": "Microsoft.Insights/metrics",
      "name": {
        "value": "BlobCapacity",
        "localizedValue": "Blob Capacity"
      },
      "displayDescription": "The amount of storage used by the storage account's Blob service in bytes.",
      "unit": "Bytes",
      ".timeseries": [
        {
          "metadatavalues": [],
          "data": [
            {
              "timeStamp": "2020-05-22T03:04:00Z",
              "average": 586904516140.0
            },
            {
              "timeStamp": "2020-05-22T04:04:00Z",
              "average": 587058965680.0
            },
            {
              "timeStamp": "2020-05-22T05:04:00Z",
              "average": 587058965680.0
            }
          ]
        }
      ],
      "errorCode": "Success"
    }
  ],
  "namespace": "Microsoft.Storage/storageAccounts/blobServices",
  "resourceregion": "eastus2"
}

All I want is the number 587058965680 which is the last value of the JSON and the most recent timestamp.

Pretty much I want to get exact result the way I'm getting in below powershell code
PowerShell works like a charm in 4 lines but I had to write so many lines in C#

$StorageAccounts = Get-AzStorageAccount -ResourceGroupName "My ResourceGroupName"

$StorageAccountID = $StorageAccounts.ID + "/blobServices/default"
$Start = (get-date).AddDays(-7)
$End = get-date

$Metric = Get-AzMetric -ResourceId $StorageAccountID -MetricName "BlobCapacity" -StartTime $Start -EndTime $End  -WarningAction Ignore

$ContainerSize = ($Metric.Data | sort-object -Descending Average | Select-Object -First 1).Average/1024/1024/1024


问:
is possible to compute Class properties dinamically by received constructor arguments?
Basically I want to achieve is merging this two clasees:

class ResponseDto

```<code>export class ResponseDto<T = Record<string, any>>  {
    public readonly sucess = true;

    constructor(
        public data: T
    ) { }
}
</code>```

class IterableResponseDto

```<code>export class IterableResponseDto<T = Record<string, any>[]> {
    public readonly sucess = true;

    constructor(
        public data: T,
        public paging: Paging
    ) { }
}
</code>```

As you can see, when data argument is an Array you may provide a paging argument of certan type, otherwhise only data sall be mandatory.

答:
You could possibly use a conditional type to represent the type of the rest argument tuple for the constructor:

```<code>export class ResponseDto<T extends Record<string, any> | Array<Record<string, any>>>  {
  public readonly sucess = true;
  public paging: Paging | undefined;

  constructor(
    public data: T,
    ...[paging]: (T extends Array<any> ? [Paging] : [])
  ) {
    this.paging = paging;
  }

}
</code>```

Above, the paging argument will be accepted if and only if the type of T is an array.  Inside the class's implementation you have the paging property set to Paging | undefined.  It might turn out to be difficult to have the class implementation know when Paging is and is not present, since conditional types that depend on unspecified generics are hard for the compiler to reason about.

But at least from the caller's side it should work as expected:

```<code>declare const paging: Paging;

const okayObject = new ResponseDto({ a: "hello" });
const badObject = new ResponseDto({ a: "hello" }, paging); // error!
// expected 1 arg, got 2

const okayArray = new ResponseDto([1, 2, 3], paging);
const badarray = new ResponseDto([1, 2, 3]); // error!
// expected 2 args, got 1
</code>```

Okay, hope that helps; good luck!

Playground link to code

Body:
Basically I want to achieve is merging this two clasees:

class ResponseDto

export class ResponseDto<T = Record<string, any>>  {
    public readonly sucess = true;

    constructor(
        public data: T
    ) { }
}

class IterableResponseDto

export class IterableResponseDto<T = Record<string, any>[]> {
    public readonly sucess = true;

    constructor(
        public data: T,
        public paging: Paging
    ) { }
}

As you can see, when data argument is an Array you may provide a paging argument of certan type, otherwhise only data sall be mandatory.

Body:
You could possibly use a conditional type to represent the type of the rest argument tuple for the constructor:

export class ResponseDto<T extends Record<string, any> | Array<Record<string, any>>>  {
  public readonly sucess = true;
  public paging: Paging | undefined;

  constructor(
    public data: T,
    ...[paging]: (T extends Array<any> ? [Paging] : [])
  ) {
    this.paging = paging;
  }

}

Above, the paging argument will be accepted if and only if the type of T is an array.  Inside the class's implementation you have the paging property set to Paging | undefined.  It might turn out to be difficult to have the class implementation know when Paging is and is not present, since conditional types that depend on unspecified generics are hard for the compiler to reason about.

But at least from the caller's side it should work as expected:

declare const paging: Paging;

const okayObject = new ResponseDto({ a: "hello" });
const badObject = new ResponseDto({ a: "hello" }, paging); // error!
// expected 1 arg, got 2

const okayArray = new ResponseDto([1, 2, 3], paging);
const badarray = new ResponseDto([1, 2, 3]); // error!
// expected 2 args, got 1

Okay, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgApwOag8g3gKGWQAdMIAuZEAVwFsAjaAbnwF9l98IAPYgeyhhkCADZwAzuOQAlCOP4hxEACJg+AHgAqyHpBAATKbIQD968WCjYANMjggAngD5kAH2QBBKFDgP1x03NLGztHJ3CiAiJianoRYARkKAg4fT4QEQdkcWokSWQAXmRLaggWaNj4xNIsEAxKdFqcd2oDCBhQCH0WQmF0iyhctSgACl6KuITkfTgwOEpNa3HkADo1gG0a7ABdShHtXQgDKS8fP3tnZAB+ZHXGneRKde2ASl6XvGWwAAtgcRWtnVCiRMNhyshWJxIfh9BBRHBkn1FEJAfU0KC6j0TMjkHwANa+ADy9AAVnChEUQBAAO4yOQKJSqPgjXB2SgAIm+EBEIj47IhLxY2IsyHoqWJZIQFKoNLp8n6KjULLZyE53N5-NYtlRguQAHo9TpvAIAIT4A06XjkrrIACMdigGFsGD4QgATJxhUJ8b5Tr5gVTabJ5YpFcz1rbbG7bABmbbajEYQX4L2i1IIs4B2XBhlhkYRqOx15MfWG6BQU3mstWqU2t0OjDiZ2uu1AA" rel="nofollow noreferrer">Playground link to code


问:
Can someone help figuring out the issue in my hackerrank Frequency Queries code?
In this problem we are given a 2 dimensional queries like:

```<code>queries = [[1, 1], [2, 2], [3, 2], [1, 2], [1, 1], [1, 1], [2, 1], [3, 2]]
</code>```

Each query is of the form,

1 x -> insert x

2 y -> remove one occurence of y

3 z -> Check if any integer is present whose frequency is exactly z. If yes, print 1 else 0

For example,

```<code>Operation   Array   Output
(1,1)       [1]
(2,2)       [1]
(3,2)                   0
(1,1)       [1,1]
(1,1)       [1,1,1]
(2,1)       [1,1]
(3,2)                   1
</code>```

Above example returns an array with the output: [0, 1]

My solution:

```<code>def freqQuery(queries):
    res = Counter()
    output = []

    for op, value in queries:
        if op == 1:
            res[value] += 1
        elif op == 2:
            if value in res.keys():
                res[value] -= 1
        elif op == 3:
            if value in res.values():
                output.append(1)
            else:
                output.append(0)

    return output
</code>```

Link to the problem: https://www.hackerrank.com/challenges/frequency-queries/problem

It fails the test cases 4/15 with 3 wrong answers and one with exceeding time limit. Can someone tell me what's wrong with the code?

Update:

Thank you for the help! My second query was wrong.

New solution:

```<code>def freqQuery(queries):
    res = Counter()
    output = []

    for op, value in queries:
        if op == 1:
            res[value] += 1
        elif op == 2:
            if res[value] > 0:
                res[value] -= 1
        elif op == 3:
            if value in res.values():
                output.append(1)
            else:
                output.append(0)

    return output
</code>```

Though I am still failing one test case i.e. exceeding time limit. What could I do to improve the efficiency of the code?

答:
The wrong answer is obvious. You didn't understand query 3. In query 3, you're asked if there is any key whose count in the dictionary is exactly z.

```<code>        elif op == 2:
            if value in res.keys():
                res[value] -= 1

</code>```

Your code suggests you're blindly decreasing the counter without knowing the actual state.

You are not deleting any keys from the Counter.

Think about a simple case, you are asked to add 2 your_code_state: ({2:1}), then delete 2 twice your_code_state: {2:-1}, then add 2 again  your_code_state: {2:0}, check if any z = 1 exists, for your code, there is none your_code_state: {2:0} (as you keep decrementing your counter even if it's negative) but the answer should be 1 {2:1}.

So, just check if the counter is negative, if yes don't decrement, stay at 0.

For time improvement, don't do repeated in checks, you can keep a separate dictionary/hash map which will store the frequency for each count, for example, if there is a frequency z, the second dict will contain dict2[z] = 1, else 0. This will bring down all of your operations in the query function to O(1).

```<code>
# Complete the freqQuery function below.
from collections import Counter
def freqQuery(queries):
    d = Counter() # actual values and their count
    f = Counter() # keep the frequency, if f[z] > 0, then we return 1
    output = []
    for command, key in queries:
        if command == 1:
            d[key] += 1 # new value add
            f[d[key]] += 1 # new frequency add
            f[d[key]-1] -= 1 # delete old frequency
        elif command == 2:
            if d[key] > 0:
                d[key] -= 1 # delete
                f[d[key]] += 1 # old frequency increase
                f[d[key]+1] -= 1
        else:
            if f[key] > 0: # O(1)
                output.append(1)
            else:
                output.append(0)
    return output

</code>```

Body:
In this problem we are given a 2 dimensional queries like:

queries = [[1, 1], [2, 2], [3, 2], [1, 2], [1, 1], [1, 1], [2, 1], [3, 2]]

Each query is of the form,

1 x -> insert x

2 y -> remove one occurence of y

3 z -> Check if any integer is present whose frequency is exactly z. If yes, print 1 else 0

For example,

Operation   Array   Output
(1,1)       [1]
(2,2)       [1]
(3,2)                   0
(1,1)       [1,1]
(1,1)       [1,1,1]
(2,1)       [1,1]
(3,2)                   1

Above example returns an array with the output: [0, 1]

My solution:

def freqQuery(queries):
    res = Counter()
    output = []

    for op, value in queries:
        if op == 1:
            res[value] += 1
        elif op == 2:
            if value in res.keys():
                res[value] -= 1
        elif op == 3:
            if value in res.values():
                output.append(1)
            else:
                output.append(0)

    return output

Link to the problem: https://www.hackerrank.com/challenges/frequency-queries/problem

It fails the test cases 4/15 with 3 wrong answers and one with exceeding time limit. Can someone tell me what's wrong with the code?

Update:

Thank you for the help! My second query was wrong.

New solution:

def freqQuery(queries):
    res = Counter()
    output = []

    for op, value in queries:
        if op == 1:
            res[value] += 1
        elif op == 2:
            if res[value] > 0:
                res[value] -= 1
        elif op == 3:
            if value in res.values():
                output.append(1)
            else:
                output.append(0)

    return output

Though I am still failing one test case i.e. exceeding time limit. What could I do to improve the efficiency of the code?

Body:
The wrong answer is obvious. You didn't understand query 3. In query 3, you're asked if there is any key whose count in the dictionary is exactly z.

        elif op == 2:
            if value in res.keys():
                res[value] -= 1

Your code suggests you're blindly decreasing the counter without knowing the actual state.

You are not deleting any keys from the Counter.

Think about a simple case, you are asked to add 2 your_code_state: ({2:1}), then delete 2 twice your_code_state: {2:-1}, then add 2 again  your_code_state: {2:0}, check if any z = 1 exists, for your code, there is none your_code_state: {2:0} (as you keep decrementing your counter even if it's negative) but the answer should be 1 {2:1}.

So, just check if the counter is negative, if yes don't decrement, stay at 0.

For time improvement, don't do repeated in checks, you can keep a separate dictionary/hash map which will store the frequency for each count, for example, if there is a frequency z, the second dict will contain dict2[z] = 1, else 0. This will bring down all of your operations in the query function to O(1).

# Complete the freqQuery function below.
from collections import Counter
def freqQuery(queries):
    d = Counter() # actual values and their count
    f = Counter() # keep the frequency, if f[z] > 0, then we return 1
    output = []
    for command, key in queries:
        if command == 1:
            d[key] += 1 # new value add
            f[d[key]] += 1 # new frequency add
            f[d[key]-1] -= 1 # delete old frequency
        elif command == 2:
            if d[key] > 0:
                d[key] -= 1 # delete
                f[d[key]] += 1 # old frequency increase
                f[d[key]+1] -= 1
        else:
            if f[key] > 0: # O(1)
                output.append(1)
            else:
                output.append(0)
    return output


问:
how to combine two selectors?
in my example http://jsfiddle.net/radek/HnXC4/2/ I defined jQuery handler for click

on button

that have a class run

via $(":button, .run").click(function(){

how come the this button should NOT work button's clicked is fired too? It doesn't have class "run".

答:
What you want is:

```<code>$(":button.run").click(function(){});
</code>```

This means "all buttons that ALSO have the class 'run'".  When you include a comma in the selectors, it means "all elements that are buttons, as well as all elements that have class 'run'", as you had here:

```<code>$(":button, .run").click(function(){});
</code>```

For completeness, if you have a space in the selector without the comma, such as:

```<code>$(":button .run").click(function(){});
</code>```

That means all elements with class 'run' that are descendents of buttons.  Not sure buttons can have descendents, but you get the idea.

Title: how to combine two selectors?

Body:
What you want is:

$(":button.run").click(function(){});

This means "all buttons that ALSO have the class 'run'".  When you include a comma in the selectors, it means "all elements that are buttons, as well as all elements that have class 'run'", as you had here:

$(":button, .run").click(function(){});

For completeness, if you have a space in the selector without the comma, such as:

$(":button .run").click(function(){});

That means all elements with class 'run' that are descendents of buttons.  Not sure buttons can have descendents, but you get the idea.


问:
C printf optional decimal places
In C# I can do the following:

```<code>Console.Write("{0}, ", string.Format("{0:0.00###########}", someFloatValue));
</code>```

to get at least 2 decimal places for some arbitrary float value up to some certain number of optional decimal places, in this case 13.

I was wondering if the same was possible with printf in C?

答:
Thanks for the links that gave some guidance. Here's what I came up with it lets you specify a minimum and maximum precision so it behaves more like the C# function, as well as rounds the last digit. Let me know if there are some optimizations or changes that should be made.</p>

```<code>void formatDouble(char* buf, double val, int precMin, int precMax) {
    sprintf(buf, "%.*f", precMax, val);
    int startpos = 0;
    int length = strlen(buf);
    bool found = false;
    for (int z = 0; z < length; z++)
    {
        if (buf[z] == '.')
        {
            startpos = z;
            found = true;
            break;
        }
    }
    if (!found)
        return;
    int endIndex = startpos + precMin;
    found = false;
    for (int z = precMax + startpos; z >= startpos + precMin; z--)
    {
        if (buf[z] >= '1' && buf[z] <= '9')
        {
            endIndex = z;
            if (endIndex < startpos + precMax)
            {
                // Round Digit
                if (buf[z + 1] >= '5')
                    buf[z]++;
            }
            found = true;
            break;
        }
    }
    for (int z = endIndex + 1; z <= length; z++)
    {
        if (z <= startpos + precMax)
            buf[z] = 0;
    }
}
</code>```

Title: C printf optional decimal places

Body:
In C# I can do the following:

Console.Write("{0}, ", string.Format("{0:0.00###########}", someFloatValue));

to get at least 2 decimal places for some arbitrary float value up to some certain number of optional decimal places, in this case 13.

I was wondering if the same was possible with printf in C?

Body:
Thanks for the links that gave some guidance. Here's what I came up with it lets you specify a minimum and maximum precision so it behaves more like the C# function, as well as rounds the last digit. Let me know if there are some optimizations or changes that should be made.

void formatDouble(char* buf, double val, int precMin, int precMax) {
    sprintf(buf, "%.*f", precMax, val);
    int startpos = 0;
    int length = strlen(buf);
    bool found = false;
    for (int z = 0; z < length; z++)
    {
        if (buf[z] == '.')
        {
            startpos = z;
            found = true;
            break;
        }
    }
    if (!found)
        return;
    int endIndex = startpos + precMin;
    found = false;
    for (int z = precMax + startpos; z >= startpos + precMin; z--)
    {
        if (buf[z] >= '1' && buf[z] <= '9')
        {
            endIndex = z;
            if (endIndex < startpos + precMax)
            {
                // Round Digit
                if (buf[z + 1] >= '5')
                    buf[z]++;
            }
            found = true;
            break;
        }
    }
    for (int z = endIndex + 1; z <= length; z++)
    {
        if (z <= startpos + precMax)
            buf[z] = 0;
    }
}


问:
How to exclude static resources from requestmapping
I'm trying to exclude static resources from @RequestMapping path to avoid redundant calls to methods.

I tried to simply check the url and if its a resource to do nothing but the interceptor didn't find the resource after and it ran the methods anyway because they are annotated with @ModelAttribute.

GlobalController.java

```<code>@RequestMapping(value = "/")
public class GlobalControllerAdvice {

    public static int k;

    @Autowired
    private UsersService usersService;

    @ModelAttribute("unread")
    public int unread(Principal principal) {

        int unread = 0;

        k++;
        System.err.println("Inside unread " + k);

        if (principal != null) {
            User user = usersService.getWithUser(principal.getName(), "notifications");
            for (Notification n : user.getNotifications())
                if (!n.isRead())
                    unread++;
        }

        return unread;
    }
}
</code>```

The resources handler

```<code>@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("/resources/");
}
</code>```

The expected result should exclude all urls that contain "static", but now it doesn't and unread() is being called for every image and script in my jsp pages.

答:
```<code>@SuppressWarnings("deprecation")
@Configuration
public class DefaultView extends WebMvcConfigurerAdapter {

    @SuppressWarnings("SpringMVCViewInspection")
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/files/**").setViewName("forward:/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
}
</code>```

screenshot of project structure

Body:
I'm trying to exclude static resources from @RequestMapping path to avoid redundant calls to methods.

I tried to simply check the url and if its a resource to do nothing but the interceptor didn't find the resource after and it ran the methods anyway because they are annotated with @ModelAttribute.

GlobalController.java

@RequestMapping(value = "/")
public class GlobalControllerAdvice {

    public static int k;

    @Autowired
    private UsersService usersService;

    @ModelAttribute("unread")
    public int unread(Principal principal) {

        int unread = 0;

        k++;
        System.err.println("Inside unread " + k);

        if (principal != null) {
            User user = usersService.getWithUser(principal.getName(), "notifications");
            for (Notification n : user.getNotifications())
                if (!n.isRead())
                    unread++;
        }

        return unread;
    }
}

The resources handler

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("/resources/");
}

The expected result should exclude all urls that contain "static", but now it doesn't and unread() is being called for every image and script in my jsp pages.

Body:
@SuppressWarnings("deprecation")
@Configuration
public class DefaultView extends WebMvcConfigurerAdapter {

    @SuppressWarnings("SpringMVCViewInspection")
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/files/**").setViewName("forward:/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
}

screenshot of project structure


问:
Comparing dates in Javascript for fullcalendar
I'm trying to check dates in Javascript for a calendar (fullcalendar), essentially I just want it to not be able to choose past dates:

```<code>        dateClick: function(info) {
            var today = Date.now();
            var check = new Date(info.dateStr)

            if(check < today)
            {
                alert('You cannot request dates in the past');
                return;
            }
            else
            {
                alert('this is the future');
            }
        },
</code>```

I'm getting some odd results in that, it seems to calculate the past fine, but also calculates the current day as the past AS well as tomorrow.  The day after tomorrow it calculates as the future.  No sure what's going on.

info.dateStr gives the format YYYY-mm-dd.

答:
you want to compare dates like this: date1.getTime() - date2.getTime()

also, keep in mind, if your goal is to make sure a user is inputing a date that is not in the past, you can use html5 date input with a min set:

```<code><input type="date" min="2020-05-29">
</code>```

Body:
I'm trying to check dates in Javascript for a calendar (fullcalendar), essentially I just want it to not be able to choose past dates:

        dateClick: function(info) {
            var today = Date.now();
            var check = new Date(info.dateStr)

            if(check < today)
            {
                alert('You cannot request dates in the past');
                return;
            }
            else
            {
                alert('this is the future');
            }
        },

I'm getting some odd results in that, it seems to calculate the past fine, but also calculates the current day as the past AS well as tomorrow.  The day after tomorrow it calculates as the future.  No sure what's going on.

info.dateStr gives the format YYYY-mm-dd.

Body:
you want to compare dates like this: date1.getTime() - date2.getTime()

also, keep in mind, if your goal is to make sure a user is inputing a date that is not in the past, you can use html5 date input with a min set:

<input type="date" min="2020-05-29">