问:
To create a dataframe with given dynamic company name for particular dates
I have a dataframe with 12 columns of data, including columns like 'Company Name' & 'Date'.
Now, I need a dataframe that has 50 companies (Nifty Fifty) for a given quarter end date. and i need 50 rows for a given date specified.

Taking a smaller example:

For 31-12-2009, I want the data of the following 10 companies out of 100 companies which I have.

```<code>company_list_1 = ['a','b','c','d','e','f','g','h','i','j']
</code>```

Now, for the next date which is 31-03-2010, I have a new list of companies whose data I need.

```<code>company_list_2 = ['a','b','c','l','m','n','o','x','y','z']
</code>```

I have such static 40 dates having 50 dynamically changing companies out of a data of 100 companies' data which i have.

I need output for 40 such date and company filters.

答:
You can do the df.loc[] function, in which you can pass both condition added by &. For instance, if you have data frame df and you have company list as company=['a','b','c'] and want to filter on data date=31-12-2009then your code will be,

```<code>df.iloc[(df['company_name'].isin(company)) & (df['NDP_Date']==date)]
</code>```

Be carefull with the paranthesis.

Body:
I have a dataframe with 12 columns of data, including columns like 'Company Name' & 'Date'.
Now, I need a dataframe that has 50 companies (Nifty Fifty) for a given quarter end date. and i need 50 rows for a given date specified.

Taking a smaller example:

For 31-12-2009, I want the data of the following 10 companies out of 100 companies which I have.

company_list_1 = ['a','b','c','d','e','f','g','h','i','j']

Now, for the next date which is 31-03-2010, I have a new list of companies whose data I need.

company_list_2 = ['a','b','c','l','m','n','o','x','y','z']

I have such static 40 dates having 50 dynamically changing companies out of a data of 100 companies' data which i have.

I need output for 40 such date and company filters.

Body:
You can do the df.loc[] function, in which you can pass both condition added by &. For instance, if you have data frame df and you have company list as company=['a','b','c'] and want to filter on data date=31-12-2009then your code will be,

df.iloc[(df['company_name'].isin(company)) & (df['NDP_Date']==date)]

Be carefull with the paranthesis.


来源: stackexchange

问:
Is pjax the way to go for "fluid" navigation?
I've started playing with pjax, as I want to provide a fast, fluid experience for my users without a lot of unnecessary HTTP requests and repeated rendering of unchanged HTML.

I have it working fairly well on my site, and I must say it was surprisingly easy to get up and running, considering how much a difference it makes for the experience.

However, I'm seeing very little support for pjax -- both on StackOverflow, and on the web in general (a google search returns many results at the top totally unrelated to web development).

But as impressed I am with it, even if it's not widely supported yet, I may still use it.  My main concern is running into big problems later when I've already invested my code in it without a lot of support.  So I wanted to make sure there wasn't something else out there.

Are there alternatives for implementing the same functionality that pjax provides that I'm not aware of?  Or is it so new that not many people know about it yet?  Or, is it just a bad/problematic implementation?

答:
I'm with Jerad - based on using the demo in IE, it appears to degrade gracefully.

If you can live with some users not getting the AJAX experience, I don't see anything to lose.

ContentLicense: CC BY-SA 3.0


问:
How to import object of object from file in typescript
How can I import object of object from file in typescript. I know I can import like import house from 'a/b/c/house'. but can I just import parent? so I do not need to write the code like
house.grandparent.parent.xxx

```<code>#filepath: a/b/c/house.ts
const house = {
  grandparent: {
    parent: {
      childa: (text: string) => `s'${text}')`,
      childb: 'b',
      childc: 'c',
    },
  },
};

export default house;
</code>```

答:
You could split the objects.</p>

```<code>// house.ts
export const parent = {
  childa: (text: string) => `s'${text}')`,
  childb: "b",
  childc: "c"
};

export const house = {
  grandparent: {
    parent: parent
  }
};

</code>```

```<code>// some-consumer.ts
import { house, parent } from "./house";

console.log(house);
console.log(parent);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I import object of object from file in typescript. I know I can import like import house from 'a/b/c/house'. but can I just import parent? so I do not need to write the code like
house.grandparent.parent.xxx

#filepath: a/b/c/house.ts
const house = {
  grandparent: {
    parent: {
      childa: (text: string) => `s'${text}')`,
      childb: 'b',
      childc: 'c',
    },
  },
};

export default house;

Body:
You could split the objects.

// house.ts
export const parent = {
  childa: (text: string) => `s'${text}')`,
  childb: "b",
  childc: "c"
};

export const house = {
  grandparent: {
    parent: parent
  }
};

// some-consumer.ts
import { house, parent } from "./house";

console.log(house);
console.log(parent);


问:
Finding if a value does not exist in SQL
My data is structured with 5 columns (let's call them a, b, c, d, e) and 1,000,000+ rows. Each value in b has the potential for ~50 possibilities in e - so there could be up to 50 lines for each unique b value. Every b should have a '-27' among their e values. I would like to query all UNIQUE b where it doesn't have the -27 e value, ignoring all other possibilities for e.

Code so far:

```<code>select a, b, c, d, e
from TestDB
where not exists (select count(distinct b) from TestDB where e = '-27')
</code>```

Would this code be sufficient? In initial tests I've done it appears to be either a) working or b) returning nothing. I'm new to SQL so I appreciate any help or being pointed in the right direction!

**edited to make it clearer I was looking for unique 'b' values.

答:
I would like to query all b where it doesn't have the -27 e value, ignoring all other possibilities for e.

If you just want the b values, then aggregation should work:

```<code>select b
from testdb t
group by b
having sum(case when e = '-27' then 1 else 0 end) = 0;
</code>```

Body:
My data is structured with 5 columns (let's call them a, b, c, d, e) and 1,000,000+ rows. Each value in b has the potential for ~50 possibilities in e - so there could be up to 50 lines for each unique b value. Every b should have a '-27' among their e values. I would like to query all UNIQUE b where it doesn't have the -27 e value, ignoring all other possibilities for e.

Code so far:

select a, b, c, d, e
from TestDB
where not exists (select count(distinct b) from TestDB where e = '-27')

Would this code be sufficient? In initial tests I've done it appears to be either a) working or b) returning nothing. I'm new to SQL so I appreciate any help or being pointed in the right direction!

**edited to make it clearer I was looking for unique 'b' values.

Body:
I would like to query all b where it doesn't have the -27 e value, ignoring all other possibilities for e.

If you just want the b values, then aggregation should work:

select b
from testdb t
group by b
having sum(case when e = '-27' then 1 else 0 end) = 0;


问:
AWS Security Group connection tracking failing for responses with a body in ASP.NET Core app running in ECS + Fargate
In my application:

ASP.NET Core 3.1 with Kestrel

Running in AWS ECS + Fargate

Services run in a public subnet in the VPC

Tasks listen only in the port 80

Public Network Load Balancer with SSL termination

I want to set the Security Group to allow inbound connections from anywhere (0.0.0.0/0) to port 80, and disallow any outbound connection from inside the task (except, of course, to respond to the allowed requests).

As Security Groups are stateful, the connection tracking should allow the egress of the response to the requests.

In my case, this connection tracking only works for responses without body (just headers). When the response has a body (in my case, >1MB file), they fail. If I allow outbound TCP connections from port 80, they also fail. But if I allow outbound TCP connections for the full range of ports (0-65535), it works fine.

I guess this is because when ASP.NET Core + Kestrel writes the response body it initiates a new connection which is not recognized by the Security Group connection tracking.

Is there any way I can allow only responses to requests, and no other type of outbound connection initiated by the application?

答:
So we're talking about something like that?

```<code>Client 11.11.11.11 ----> AWS NLB/ELB public 22.22.22.22 ----> AWS ECS network router or whatever (kubernetes) --------> ECS server instance running a server application 10.3.3.3:8080 (kubernetes pod)
</code>```

Do you configure the security group on the AWS NLB or on the AWS ECS? (I guess both?)

Security groups should allow incoming traffic if you allow 0.0.0.0/0 port 80.

They are indeed stateful. They will allow the connection to proceed both ways after it is established (meaning the application can send a response).

However firewall state is not kept for more than 60 seconds typically (not sure what technology AWS is using), so the connection can be "lost" if the server takes more than 1 minute to reply. Does the  HTTP server take a while to generate the response? If it's a websocket or TCP server instead, does it spend whole minutes at times without sending or receiving any traffic?

The way I see it. We've got two stateful firewalls. The first with the NLB. The second with ECS.

ECS is an equivalent to kubernetes, it must be doing a ton of iptables magic to distribute traffic and track connections. (For reference, regular kubernetes works heavily with iptables and iptables have a bunch of -very important- settings like connection durations and timeouts).

Good news is. If it breaks when you open inbound 0.0.0.0:80, but it works when you open inbound 0.0.0.0:80 + outbound 0.0.0.0:*. This is definitely an issue due to the firewall dropping the connection, most likely due to losing state. (or it's not stateful in the first place but I'm pretty sure security groups are stateful).

The drop could happen on either of the two firewalls. I've never had an issue with a single bare NLB/ELB, so my guess is the problem is in the ECS or the interaction of the two together.

Unfortunately we can't debug that and we have very little information about how this works internally. Your only option will be to work with the AWS support to investigate.

Body:
So we're talking about something like that?

Client 11.11.11.11 ----> AWS NLB/ELB public 22.22.22.22 ----> AWS ECS network router or whatever (kubernetes) --------> ECS server instance running a server application 10.3.3.3:8080 (kubernetes pod)

Do you configure the security group on the AWS NLB or on the AWS ECS? (I guess both?)

Security groups should allow incoming traffic if you allow 0.0.0.0/0 port 80.

They are indeed stateful. They will allow the connection to proceed both ways after it is established (meaning the application can send a response).

However firewall state is not kept for more than 60 seconds typically (not sure what technology AWS is using), so the connection can be "lost" if the server takes more than 1 minute to reply. Does the  HTTP server take a while to generate the response? If it's a websocket or TCP server instead, does it spend whole minutes at times without sending or receiving any traffic?

The way I see it. We've got two stateful firewalls. The first with the NLB. The second with ECS.

ECS is an equivalent to kubernetes, it must be doing a ton of iptables magic to distribute traffic and track connections. (For reference, regular kubernetes works heavily with iptables and iptables have a bunch of -very important- settings like connection durations and timeouts).

Good news is. If it breaks when you open inbound 0.0.0.0:80, but it works when you open inbound 0.0.0.0:80 + outbound 0.0.0.0:*. This is definitely an issue due to the firewall dropping the connection, most likely due to losing state. (or it's not stateful in the first place but I'm pretty sure security groups are stateful).

The drop could happen on either of the two firewalls. I've never had an issue with a single bare NLB/ELB, so my guess is the problem is in the ECS or the interaction of the two together.

Unfortunately we can't debug that and we have very little information about how this works internally. Your only option will be to work with the AWS support to investigate.


问:
Tensorflow 2.0: Shape inference with Reshape returns None dimension
I'm working with a CNN-LSTM model on Tensorflow 2.0 + Keras to perform sequence classification. My model is defined as following:

    inp = Input(input_shape)
    rshp = Reshape((input_shape[0]*input_shape[1], 1), input_shape=input_shape)(inp)
    cnn1 = Conv1D(100, 9, activation='relu')(rshp)
    cnn2 = Conv1D(100, 9, activation='relu')(cnn1)
    mp1 = MaxPooling1D((3,))(cnn2)
    cnn3 = Conv1D(50, 3, activation='relu')(mp1)
    cnn4 = Conv1D(50, 3, activation='relu')(cnn3)
    gap1 = AveragePooling1D((3,))(cnn4)
    dropout1 = Dropout(rate=dropout[0])(gap1)
    flt1 = Flatten()(dropout1)
    rshp2 = Reshape((input_shape[0], -1), input_shape=flt1.shape)(flt1)
    bilstm1 = Bidirectional(LSTM(240,
                                 return_sequences=True,
                                 recurrent_dropout=dropout[1]),
                            merge_mode=merge)(rshp2)
    dense1 = TimeDistributed(Dense(30, activation='relu'))(rshp2)
    dropout2 = Dropout(rate=dropout[2])(dense1)
    prediction = TimeDistributed(Dense(1, activation='sigmoid'))(dropout2)

    model = Model(inp, prediction, name="CNN-bLSTM_per_segment")
    print(model.summary(line_length=75))
```

<p>Where <code>input_shape = (60, 60)</code>. This definition, however, raises the following error:</p>

<p><code>TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'</code></p>

<p>At first, I thought it was because the <code>rshp2</code> layer could not reshape the <code>flt1</code> output to shape <code>(60, X)</code>. So I added a printing block before the <code>Bidirectional(LSTM))</code> layer:</p>

<pre class="lang-py prettyprint-override"><code>    print('reshape1: ', rshp.shape)
    print('cnn1: ', cnn1.shape)
    print('cnn2: ', cnn2.shape)
    print('mp1: ', mp1.shape)
    print('cnn3: ', cnn3.shape)
    print('cnn4: ', cnn4.shape)
    print('gap1: ', gap1.shape)
    print('flatten 1: ', flt1.shape)
    print('reshape 2: ', rshp2.shape)
</code>```

And the shapes were:

```<code>reshape 1:  (None, 3600, 1)
cnn1:  (None, 3592, 100)
cnn2:  (None, 3584, 100)
mp1:  (None, 1194, 100)
cnn3:  (None, 1192, 50)
cnn4:  (None, 1190, 50)
gap1:  (None, 396, 50)
flatten 1:  (None, 19800)
reshape 2:  (None, 60, None)
</code>```

Looking at the flt1 layer, its output shape is (19800,), which can be reshaped as (60, 330), but for some reason the (60, -1) of the rshp2 layer is not working as intended, evidenced by the print reshape 2:  (None, 60, None). When I try to reshape as (60, 330) it works just fine. Does anyone knows why the (-1) is not working?

答:
-1 is working.

From Reshape documentation, https://www.tensorflow.org/api_docs/python/tf/keras/layers/Reshape

the layer returns a tensor with shape (batch_size,) + target_shape

So, the batch size stays the same, the other dimensions are calculated based on your target_shape.

From the doc, look at the last example,

```<code># also supports shape inference using `-1` as dimension
model.add(tf.keras.layers.Reshape((-1, 2, 2)))
model.output_shape
</code>```

(None, None, 2, 2)

If you pass -1 in your target shape, the Keras will store None, this is useful if you expect variable-length data in that axis, but if your data shape is always same, just put the dimension hard-coded that will place the dimension when you print the shape later.

N.B: Also no need to specify input_shape=input_shape for your intermediate layers in functional API. The model will infer that for you.

Body:
I'm working with a CNN-LSTM model on Tensorflow 2.0 + Keras to perform sequence classification. My model is defined as following:

    inp = Input(input_shape)
    rshp = Reshape((input_shape[0]*input_shape[1], 1), input_shape=input_shape)(inp)
    cnn1 = Conv1D(100, 9, activation='relu')(rshp)
    cnn2 = Conv1D(100, 9, activation='relu')(cnn1)
    mp1 = MaxPooling1D((3,))(cnn2)
    cnn3 = Conv1D(50, 3, activation='relu')(mp1)
    cnn4 = Conv1D(50, 3, activation='relu')(cnn3)
    gap1 = AveragePooling1D((3,))(cnn4)
    dropout1 = Dropout(rate=dropout[0])(gap1)
    flt1 = Flatten()(dropout1)
    rshp2 = Reshape((input_shape[0], -1), input_shape=flt1.shape)(flt1)
    bilstm1 = Bidirectional(LSTM(240,
                                 return_sequences=True,
                                 recurrent_dropout=dropout[1]),
                            merge_mode=merge)(rshp2)
    dense1 = TimeDistributed(Dense(30, activation='relu'))(rshp2)
    dropout2 = Dropout(rate=dropout[2])(dense1)
    prediction = TimeDistributed(Dense(1, activation='sigmoid'))(dropout2)

    model = Model(inp, prediction, name="CNN-bLSTM_per_segment")
    print(model.summary(line_length=75))

Where input_shape = (60, 60). This definition, however, raises the following error:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

At first, I thought it was because the rshp2 layer could not reshape the flt1 output to shape (60, X). So I added a printing block before the Bidirectional(LSTM)) layer:

    print('reshape1: ', rshp.shape)
    print('cnn1: ', cnn1.shape)
    print('cnn2: ', cnn2.shape)
    print('mp1: ', mp1.shape)
    print('cnn3: ', cnn3.shape)
    print('cnn4: ', cnn4.shape)
    print('gap1: ', gap1.shape)
    print('flatten 1: ', flt1.shape)
    print('reshape 2: ', rshp2.shape)

And the shapes were:

reshape 1:  (None, 3600, 1)
cnn1:  (None, 3592, 100)
cnn2:  (None, 3584, 100)
mp1:  (None, 1194, 100)
cnn3:  (None, 1192, 50)
cnn4:  (None, 1190, 50)
gap1:  (None, 396, 50)
flatten 1:  (None, 19800)
reshape 2:  (None, 60, None)

Looking at the flt1 layer, its output shape is (19800,), which can be reshaped as (60, 330), but for some reason the (60, -1) of the rshp2 layer is not working as intended, evidenced by the print reshape 2:  (None, 60, None). When I try to reshape as (60, 330) it works just fine. Does anyone knows why the (-1) is not working?

Body:
-1 is working.

From Reshape documentation, https://www.tensorflow.org/api_docs/python/tf/keras/layers/Reshape

the layer returns a tensor with shape (batch_size,) + target_shape

So, the batch size stays the same, the other dimensions are calculated based on your target_shape.

From the doc, look at the last example,

# also supports shape inference using `-1` as dimension
model.add(tf.keras.layers.Reshape((-1, 2, 2)))
model.output_shape

(None, None, 2, 2)

If you pass -1 in your target shape, the Keras will store None, this is useful if you expect variable-length data in that axis, but if your data shape is always same, just put the dimension hard-coded that will place the dimension when you print the shape later.

N.B: Also no need to specify input_shape=input_shape for your intermediate layers in functional API. The model will infer that for you.


问:
Activity to fragment Communication in Android
I am using fragment for the first time. I am trying to get List of videos from youtube present in my fragment. I am retrieving a youtube url from firebase and extract playlist id from it. This playlist id is passed as a parameter to fragment which would then list out all the videos present in the playist. i am successfully able to retrieve the playlist id in the fragment, but it changes to null in the url. Any help is appreciable.thanks in advance.
CollegeGallery.java

```<code>    public CollegeImageGrid imagegrid;
    private static final String TAG = "CollegeGallery";
    public GridView grid_image, grid_video;
    public DatabaseReference ref;
    private String collegeid;
    private TextView moreimages, morevideos;
    private String playlistid;

    public void setPlayid(String playlistid) {
        this.playlistid = playlistid;
    }

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

        ref = FirebaseDatabase.getInstance().getReference("collegedata");
        //this will get the data from previous intent
        collegeid = getIntent().getStringExtra("gallery");
        grid_image = findViewById(R.id.grid_image);
//        grid_video = findViewById(R.id.grid_video); //for grid view of videos

        moreimages = findViewById(R.id.more_images);
        morevideos = findViewById(R.id.more_videos);

        //a list of string will  be passed to  imagegrid object
        ref.child(String.valueOf(collegeid)).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               //object of College class to get getImageurls() which has the list of urls
                College clg = dataSnapshot.getValue(College.class);
                //setting the list to imagegrid, passing url from this activity to imageview.
                imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
                //setting adapter to grid with the list of urls
                grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
                //extracting playlist id
                String playid = getYoutubeVideoId(clg.getVideourls());
                //fragment code
                YoutubeVideoList yt = new YoutubeVideoList();
                FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
                tr.replace(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(CollegeGallery.this, "No images", Toast.LENGTH_SHORT).show();
            }
        });

        moreimages.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent image_in = new Intent(CollegeGallery.this,AllCollegeImages.class);
                image_in.putExtra("image",collegeid);
                startActivity(image_in);
            }
        });

        //will take to activity with only playlist video list fragment
        morevideos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CollegeGallery.this, CompleteVideoList.class));
            }
        });

    }

    //function to extract playlist id
    public static String getYoutubeVideoId(String youtubeUrl) {
        String video_id = "";
        if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) {

            String expression = "^.*?(?:list)=(.*?)(?:&|$)";

            CharSequence input = youtubeUrl;
            Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(input);
            if (matcher.matches()) {
                String groupIndex1 = matcher.group(1);
                video_id = groupIndex1;
            }
        }
        return video_id;
    }

}
</code>```

YoutubeVideoList.java(Fragment)

```<code>
    private static String ARG_Param1;
    private static String id;
    List<YoutubeVideoModel> vids;
    Button btn;
    YoutubeAdapter adapter;
    RecyclerView recyclerView;
    RecyclerView.LayoutManager manager;
    String mparam1;

    public YoutubeVideoList() {
    }

    //retrieving playlist id from the previous activity
    public static YoutubeVideoList newInstance(String id) {
        YoutubeVideoList yt = new YoutubeVideoList();
        Bundle args = new Bundle();
        args.putString(ARG_Param1, id);
        yt.setArguments(args);
        return yt;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mparam1 = getArguments().getString(ARG_Param1);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_youtube_video_list, container, false);
    }

    @Override
    public  void onViewCreated(View container, Bundle savedInstanceState) {
        super.onViewCreated(container, savedInstanceState);
        recyclerView = container.findViewById(R.id.vidReclycer);
        manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(false);

         id = mparam1;
        //right here, id has the playlist id
        System.out.println("this is the playlist id------------------->"+id);
        String url = "https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyBmISPZAjsrku2_yKLcTW4Y6qq6aqlht-0&playlistId="+id+"&part=snippet&maxResults=36";
        //even url has the value but the list is not shown and id changes to null
        System.out.println(url);
        RequestQueue queue = Volley.newRequestQueue(getContext());

        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        vids = new ArrayList<>();
                        try {
                            JSONObject mainObject = new JSONObject(response);
                            JSONArray itemArray = (JSONArray) mainObject.get("items");
                            for (int i = 0; i < itemArray.length(); i++) {
                                String title = itemArray.getJSONObject(i).getJSONObject("snippet").getString("title");
                                String url = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("maxres").getString("url");
                                String vidid = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
                                YoutubeVideoModel vid = new YoutubeVideoModel(title, url, vidid);
                                vids.add(vid);
                            }
                            adapter = new YoutubeAdapter(getContext(), vids);
                            recyclerView.setAdapter(adapter);
                            recyclerView.getAdapter().notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                Log.e("Error in request", error.getMessage());
            }
        });
        queue.add(request);
        }
    }
```this is the image of my logcat. It prints id and url as required, but then it changes to null

```

答:
In your CollegeGallery.java in place of:
yt.newInstance(playid)
write this
YoutubeVideoList.newInstance(playid)

Also remove the static String id from your YoutubeVideoList fragment if it's useless

Body:
I am using fragment for the first time. I am trying to get List of videos from youtube present in my fragment. I am retrieving a youtube url from firebase and extract playlist id from it. This playlist id is passed as a parameter to fragment which would then list out all the videos present in the playist. i am successfully able to retrieve the playlist id in the fragment, but it changes to null in the url. Any help is appreciable.thanks in advance.
CollegeGallery.java

    public CollegeImageGrid imagegrid;
    private static final String TAG = "CollegeGallery";
    public GridView grid_image, grid_video;
    public DatabaseReference ref;
    private String collegeid;
    private TextView moreimages, morevideos;
    private String playlistid;

    public void setPlayid(String playlistid) {
        this.playlistid = playlistid;
    }

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

        ref = FirebaseDatabase.getInstance().getReference("collegedata");
        //this will get the data from previous intent
        collegeid = getIntent().getStringExtra("gallery");
        grid_image = findViewById(R.id.grid_image);
//        grid_video = findViewById(R.id.grid_video); //for grid view of videos

        moreimages = findViewById(R.id.more_images);
        morevideos = findViewById(R.id.more_videos);

        //a list of string will  be passed to  imagegrid object
        ref.child(String.valueOf(collegeid)).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               //object of College class to get getImageurls() which has the list of urls
                College clg = dataSnapshot.getValue(College.class);
                //setting the list to imagegrid, passing url from this activity to imageview.
                imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
                //setting adapter to grid with the list of urls
                grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
                //extracting playlist id
                String playid = getYoutubeVideoId(clg.getVideourls());
                //fragment code
                YoutubeVideoList yt = new YoutubeVideoList();
                FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
                tr.replace(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(CollegeGallery.this, "No images", Toast.LENGTH_SHORT).show();
            }
        });

        moreimages.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent image_in = new Intent(CollegeGallery.this,AllCollegeImages.class);
                image_in.putExtra("image",collegeid);
                startActivity(image_in);
            }
        });

        //will take to activity with only playlist video list fragment
        morevideos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(CollegeGallery.this, CompleteVideoList.class));
            }
        });

    }

    //function to extract playlist id
    public static String getYoutubeVideoId(String youtubeUrl) {
        String video_id = "";
        if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) {

            String expression = "^.*?(?:list)=(.*?)(?:&|$)";

            CharSequence input = youtubeUrl;
            Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(input);
            if (matcher.matches()) {
                String groupIndex1 = matcher.group(1);
                video_id = groupIndex1;
            }
        }
        return video_id;
    }

}

YoutubeVideoList.java(Fragment)

    private static String ARG_Param1;
    private static String id;
    List<YoutubeVideoModel> vids;
    Button btn;
    YoutubeAdapter adapter;
    RecyclerView recyclerView;
    RecyclerView.LayoutManager manager;
    String mparam1;

    public YoutubeVideoList() {
    }

    //retrieving playlist id from the previous activity
    public static YoutubeVideoList newInstance(String id) {
        YoutubeVideoList yt = new YoutubeVideoList();
        Bundle args = new Bundle();
        args.putString(ARG_Param1, id);
        yt.setArguments(args);
        return yt;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mparam1 = getArguments().getString(ARG_Param1);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_youtube_video_list, container, false);
    }

    @Override
    public  void onViewCreated(View container, Bundle savedInstanceState) {
        super.onViewCreated(container, savedInstanceState);
        recyclerView = container.findViewById(R.id.vidReclycer);
        manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(false);

         id = mparam1;
        //right here, id has the playlist id
        System.out.println("this is the playlist id------------------->"+id);
        String url = "https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyBmISPZAjsrku2_yKLcTW4Y6qq6aqlht-0&playlistId="+id+"&part=snippet&maxResults=36";
        //even url has the value but the list is not shown and id changes to null
        System.out.println(url);
        RequestQueue queue = Volley.newRequestQueue(getContext());

        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        vids = new ArrayList<>();
                        try {
                            JSONObject mainObject = new JSONObject(response);
                            JSONArray itemArray = (JSONArray) mainObject.get("items");
                            for (int i = 0; i < itemArray.length(); i++) {
                                String title = itemArray.getJSONObject(i).getJSONObject("snippet").getString("title");
                                String url = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("maxres").getString("url");
                                String vidid = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
                                YoutubeVideoModel vid = new YoutubeVideoModel(title, url, vidid);
                                vids.add(vid);
                            }
                            adapter = new YoutubeAdapter(getContext(), vids);
                            recyclerView.setAdapter(adapter);
                            recyclerView.getAdapter().notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                Log.e("Error in request", error.getMessage());
            }
        });
        queue.add(request);
        }
    }
```this is the image of my logcat. It prints id and url as required, but then it changes to null


问:
Microsoft Bot - Node SDK: How to post to a public channel *without replying to a prev. activity*

Context & theory

According to the docs and examples, you must save the reference to a conversation in order to restore it on demand (for instance when the server receives an HTTP request) and send a reactive message to a public channel.

So I'm doing:

Any user mentions the bot on a channel (at #CorpChannel for example)

Bot stores (in particular I'm using Azure Cosmos db) the reference of the conversation(storage.write(storeItems))

[later] Bot receives an HTTP request that means: "send 'hi there' to #CorpChannel"

Bot restores the conversation reference and uses it for creating a TurnContext in order to call sendActivity()

Problem

The activity 'hi there' is replying to the original mention to my bot instead of starting a new thread/conversation over that channel. I want to start a new fresh conversation at #CorpChannel

Visually:

```<code>Jane Doe: --------------
| @MyBot        09:00AM |
------------------------

Jhon Doe: --------------
| what ever     10:00AM |
------------------------
</code>```

HTTP request: "send 'hi there' to #CorpChannel"

```<code>Jhon Doe: --------------
| whatever      10:00AM |
------------------------

Jane Doe: --------------
| @MyBot        09:00AM |
------------------------
   |> MyBot: -----------
   |  Hi there  11:00AM |
    --------------------
</code>```

What I've tried

This is the code where I'm sending the activity on demand

server.post("/api/notify", async (req, res) => {
  const channel = req.body.channel;
  const message = req.body.message;
  const conversation = await bot.loadChannelConversation(channel);

  if (!conversation) { /* ... */ }

  await adapter.continueConversation(conversation, async (context) => {
      await context.sendActivity(message);
  });

  return res.send({ notified: { channel, message } });
});
```

<p>this is the code where I'm going to db</p>

<pre class="lang-js prettyprint-override"><code>// (storage) is in the scope
const loadChannelConversation = async (key) => {
  try {
    const storeItems = await storage.read(['channels']);
    const channels = storeItems['channels'] || {};
    return channels[key] || null;
  } catch (err) {
    console.error(err);
    return undefined;
  }
};
</code>```

how can I post a new message instead of replying to the original thread?

==== EDIT ====

I've tried also to use createConversation() method from the SDK, but as it says in the documentation:

The Bot Connector service supports the creating of group conversations; however, this method and most channels only support initiating a direct message (non-group) conversation.

It starts a new conversation with the original user that posted the first message in private

答:
A conversation ID in a Teams channel thread looks like this: 19:1234abcd@thread.tacv2;messageid=12345

All you need to do to start a new thread is to send a message to that conversation ID with the "messageid" portion removed.

You can remove the messageid portion like this:

```<code>function getRootConversationId(turnContext) {
    const threadId = turnContext.activity.conversation.id;
    const messageIdIndex = threadId.indexOf(";messageid=");
    return messageIdIndex > 0 ? threadId.slice(0, messageIdIndex) : threadId;
}
</code>```

If you want to send a message through the turn context to retain its middleware pipeline, you can modify the incoming activity's conversation ID directly. Since this would affect the turn context for the rest of the turn, it might be a good idea to change the conversation ID back afterwards.

```<code>const conversationId = getRootConversationId(turnContext);

// Send through the turn context

const conversation = turnContext.activity.conversation;
const threadId = conversation.id;
conversation.id = conversationId;

await turnContext.sendActivity("New thread (through the turn context)");

conversation.id = threadId;  // restore conversation ID
</code>```

You can also send a message through a connector client directly if you don't want to worry about the turn context.

```<code>const conversationId = getRootConversationId(turnContext);

// Send through a connector client

const client = turnContext.turnState.get(turnContext.adapter.ConnectorClientKey);

await client.conversations.sendToConversation(
    conversationId,
    MessageFactory.text("New thread (through a connector client)"));
</code>```

Body:
Context & theory

According to the docs and examples, you must save the reference to a conversation in order to restore it on demand (for instance when the server receives an HTTP request) and send a reactive message to a public channel.

So I'm doing:

Any user mentions the bot on a channel (at #CorpChannel for example)

Bot stores (in particular I'm using Azure Cosmos db) the reference of the conversation(storage.write(storeItems))

[later] Bot receives an HTTP request that means: "send 'hi there' to #CorpChannel"

Bot restores the conversation reference and uses it for creating a TurnContext in order to call sendActivity()

Problem

The activity 'hi there' is replying to the original mention to my bot instead of starting a new thread/conversation over that channel. I want to start a new fresh conversation at #CorpChannel

Visually:

Jane Doe: --------------
| @MyBot        09:00AM |
------------------------

Jhon Doe: --------------
| what ever     10:00AM |
------------------------

HTTP request: "send 'hi there' to #CorpChannel"

Jhon Doe: --------------
| whatever      10:00AM |
------------------------

Jane Doe: --------------
| @MyBot        09:00AM |
------------------------
   |> MyBot: -----------
   |  Hi there  11:00AM |
    --------------------

What I've tried

This is the code where I'm sending the activity on demand

server.post("/api/notify", async (req, res) => {
  const channel = req.body.channel;
  const message = req.body.message;
  const conversation = await bot.loadChannelConversation(channel);

  if (!conversation) { /* ... */ }

  await adapter.continueConversation(conversation, async (context) => {
      await context.sendActivity(message);
  });

  return res.send({ notified: { channel, message } });
});

this is the code where I'm going to db

// (storage) is in the scope
const loadChannelConversation = async (key) => {
  try {
    const storeItems = await storage.read(['channels']);
    const channels = storeItems['channels'] || {};
    return channels[key] || null;
  } catch (err) {
    console.error(err);
    return undefined;
  }
};

how can I post a new message instead of replying to the original thread?

==== EDIT ====

I've tried also to use createConversation() method from the SDK, but as it says in the documentation:

The Bot Connector service supports the creating of group conversations; however, this method and most channels only support initiating a direct message (non-group) conversation.

It starts a new conversation with the original user that posted the first message in private

Body:
A conversation ID in a Teams channel thread looks like this: 19:1234abcd@thread.tacv2;messageid=12345

All you need to do to start a new thread is to send a message to that conversation ID with the "messageid" portion removed.

You can remove the messageid portion like this:

function getRootConversationId(turnContext) {
    const threadId = turnContext.activity.conversation.id;
    const messageIdIndex = threadId.indexOf(";messageid=");
    return messageIdIndex > 0 ? threadId.slice(0, messageIdIndex) : threadId;
}

If you want to send a message through the turn context to retain its middleware pipeline, you can modify the incoming activity's conversation ID directly. Since this would affect the turn context for the rest of the turn, it might be a good idea to change the conversation ID back afterwards.

const conversationId = getRootConversationId(turnContext);

// Send through the turn context

const conversation = turnContext.activity.conversation;
const threadId = conversation.id;
conversation.id = conversationId;

await turnContext.sendActivity("New thread (through the turn context)");

conversation.id = threadId;  // restore conversation ID

You can also send a message through a connector client directly if you don't want to worry about the turn context.

const conversationId = getRootConversationId(turnContext);

// Send through a connector client

const client = turnContext.turnState.get(turnContext.adapter.ConnectorClientKey);

await client.conversations.sendToConversation(
    conversationId,
    MessageFactory.text("New thread (through a connector client)"));


问:
Problem with mapping in NHibernate
I've the following class:

```<code>public class Customer
{
    public virtual int CustomerID { get; protected set; }
    public virtual string AccountNumber { get; protected set; }
    public virtual string CustomerType { get; set; }
    public virtual int TerritoryID { get; set; }
    public virtual SalesTerritory Territory { get; protected set; }
}
</code>```

And it is being mapped using Fluent NHibernate as follows:

```<code>    public class CustomerMapper : ClassMap<Customer>
{
    private const string schema = "Sales";
    public CustomerMapper()
    {
        SchemaIs(schema);
        Id(x => x.CustomerID);
        Map(x => x.CustomerType).WithLengthOf(1).Not.Nullable();
        Map(x => x.TerritoryID).Not.Nullable();

        Map(x => x.AccountNumber).ReadOnly()
            .Update(false)
            .Insert(false)
            .Generated(Generated.Insert);

        References<SalesTerritory>(x => x.Territory).TheColumnNameIs(ReflectionHelper.GetProperty<Customer>(x => x.TerritoryID).Name).LazyLoad().Update(false).Insert(false);
    }
}
</code>```

The Update and Insert methods are just extension methods that set the update and insert attributes of a property in the generated mapping file.

This is how the resulting mapping file looks:

```<code><?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="true" assembly="Model" namespace="Model" schema="Sales">
    <class name="Customer" table="`Customer`" xmlns="urn:nhibernate-mapping-2.2">
        <id name="CustomerID" column="CustomerID" type="Int32">
            <generator class="identity" />
        </id>
        <property name="AccountNumber" column="AccountNumber" insert="false" update="false" generated="insert" length="100" type="String">
            <column name="AccountNumber" />
        </property>
        <property name="TerritoryID" column="TerritoryID" not-null="true" type="Int32">
            <column name="TerritoryID" />
        </property>
        <property name="CustomerType" column="CustomerType" not-null="true" length="1" type="String">
            <column name="CustomerType" />
        </property>
        <many-to-one lazy="proxy" update="false" insert="false" name="Territory" column="TerritoryID" />
    </class>
</hibernate-mapping>
</code>```

My problem is that when a save a new customer instance into the database, the customer instance have its Territory property as null.

How can I make this property to contain the correct value after saving into the database?
I am looking at something like the generated attribute for properties which retrieve the correct value after the session is flushed.

Or is there something wrong with my Customer class?

Thanks in advance.

EDIT 1: The database that I'm using for this model is AdventureWorks (SQL2005), tables Sales.Customer and Sales.SalesTerritory.

答:
A more sensible mapping would be like:

```<code>public class CustomerMapper : ClassMap<Customer>
{
    private const string schema = "Sales";
    public CustomerMapper()
    {
        SchemaIs(schema);
        Id(x => x.CustomerID);
        Map(x => x.CustomerType).WithLengthOf(1).Not.Nullable();
        Map(x => x.AccountNumber).ReadOnly()
           .Generated(Generated.Insert);
        References(x => x.Territory).LazyLoad();
    }
}
</code>```

Some points:

This counts in being a mapped SalesTerritory class.

TerritoryID is not necessary.

If you use Insert(false) and Update(false) those properties won't be saved to the database. ReadOnly() does both Insert(false) and Update(false).

CostumerType could perfectly be an enum.

This is more or less the idea (air code).

OwnerDisplayName: Jaime Febres

ContentLicense: CC BY-SA 2.5

Title: Problem with mapping in NHibernate

Body:
I've the following class:

public class Customer
{
    public virtual int CustomerID { get; protected set; }
    public virtual string AccountNumber { get; protected set; }
    public virtual string CustomerType { get; set; }
    public virtual int TerritoryID { get; set; }
    public virtual SalesTerritory Territory { get; protected set; }
}

And it is being mapped using Fluent NHibernate as follows:

    public class CustomerMapper : ClassMap<Customer>
{
    private const string schema = "Sales";
    public CustomerMapper()
    {
        SchemaIs(schema);
        Id(x => x.CustomerID);
        Map(x => x.CustomerType).WithLengthOf(1).Not.Nullable();
        Map(x => x.TerritoryID).Not.Nullable();

        Map(x => x.AccountNumber).ReadOnly()
            .Update(false)
            .Insert(false)
            .Generated(Generated.Insert);

        References<SalesTerritory>(x => x.Territory).TheColumnNameIs(ReflectionHelper.GetProperty<Customer>(x => x.TerritoryID).Name).LazyLoad().Update(false).Insert(false);
    }
}

The Update and Insert methods are just extension methods that set the update and insert attributes of a property in the generated mapping file.

This is how the resulting mapping file looks:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="true" assembly="Model" namespace="Model" schema="Sales">
    <class name="Customer" table="`Customer`" xmlns="urn:nhibernate-mapping-2.2">
        <id name="CustomerID" column="CustomerID" type="Int32">
            <generator class="identity" />
        </id>
        <property name="AccountNumber" column="AccountNumber" insert="false" update="false" generated="insert" length="100" type="String">
            <column name="AccountNumber" />
        </property>
        <property name="TerritoryID" column="TerritoryID" not-null="true" type="Int32">
            <column name="TerritoryID" />
        </property>
        <property name="CustomerType" column="CustomerType" not-null="true" length="1" type="String">
            <column name="CustomerType" />
        </property>
        <many-to-one lazy="proxy" update="false" insert="false" name="Territory" column="TerritoryID" />
    </class>
</hibernate-mapping>

My problem is that when a save a new customer instance into the database, the customer instance have its Territory property as null.

How can I make this property to contain the correct value after saving into the database?
I am looking at something like the generated attribute for properties which retrieve the correct value after the session is flushed.

Or is there something wrong with my Customer class?

Thanks in advance.

EDIT 1: The database that I'm using for this model is AdventureWorks (SQL2005), tables Sales.Customer and Sales.SalesTerritory.

LastEditorDisplayName: Jaime Febres

Body:
A more sensible mapping would be like:

public class CustomerMapper : ClassMap<Customer>
{
    private const string schema = "Sales";
    public CustomerMapper()
    {
        SchemaIs(schema);
        Id(x => x.CustomerID);
        Map(x => x.CustomerType).WithLengthOf(1).Not.Nullable();
        Map(x => x.AccountNumber).ReadOnly()
           .Generated(Generated.Insert);
        References(x => x.Territory).LazyLoad();
    }
}

Some points:

This counts in being a mapped SalesTerritory class.

TerritoryID is not necessary.

If you use Insert(false) and Update(false) those properties won't be saved to the database. ReadOnly() does both Insert(false) and Update(false).

CostumerType could perfectly be an enum.

This is more or less the idea (air code).

OwnerDisplayName: gcores

LastEditorDisplayName: gcores


问:
enter special characters (accents) in a windows form application
I am working on a MS Paint like application and we allow the user to enter text as well. Now a requirement is to allow the user to enter accents and other special characters.

I understand that we can show the charmap.exe from within the application and allow the user to copy the character and the paste it in the text box used to enter the text. However, we would like the ability where user selects the character and it is entered in the text box.

So is implementing a dialog with the character set the only option ? And if it is the only option, is there a standard way to implement this.

Thanks,
Gaurav

答: You can use a form like you suggested, or you let the user enter the characters from the keyboard. Special characters not on the keyboard can be entered using the Alt key and the number for that character, such as Alt-225 for ß. As David said, you generally don't need to do anything since most people have keyboards that support the characters they use.</p>


问:
How to link a docker container with a node.js server
The command sam local start-lambda spins up a server inside a Docker container that emulates an AWS Lambda function:

```<code>$ sam local start-lambda
Starting the Local Lambda Service. You can now invoke your Lambda Functions defined in your template through the endpoint.
2020-05-29 12:32:13  * Running on http://127.0.0.1:3001/ (Press CTRL+C to quit)
Fetching lambci/lambda:java8 Docker container image......
Mounting /private/var/folders/p_/0lzsyjqd64j3qynmw8sdmf2ws82gz7/T/tmp19t_696o as /var/task:ro,delegated inside runtime container
</code>```

I wrote a simple Node.js server that hits this endpoint.

Now, i'd like to package both up (i.e. one would run docker start and both the node.js server & sam local start-lambda would start running), but i'm not sure how to do this.

Can I write a Dockerfile that somehow links these two endpoints?

答:
You can use Docker Compose to do that. https://docs.docker.com/compose/

You would create a service for lambda, and one for node and then configure each accordingly exposing the desired ports, etc., depending on exactly how you want to use them.

Body:
The command sam local start-lambda spins up a server inside a Docker container that emulates an AWS Lambda function:

$ sam local start-lambda
Starting the Local Lambda Service. You can now invoke your Lambda Functions defined in your template through the endpoint.
2020-05-29 12:32:13  * Running on http://127.0.0.1:3001/ (Press CTRL+C to quit)
Fetching lambci/lambda:java8 Docker container image......
Mounting /private/var/folders/p_/0lzsyjqd64j3qynmw8sdmf2ws82gz7/T/tmp19t_696o as /var/task:ro,delegated inside runtime container

I wrote a simple Node.js server that hits this endpoint.

Now, i'd like to package both up (i.e. one would run docker start and both the node.js server & sam local start-lambda would start running), but i'm not sure how to do this.

Can I write a Dockerfile that somehow links these two endpoints?


问:
When I try to run this code it's gives me no output
I built it when I click to run it's showing no errors no warnings nothing

```<code>#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char name[20], address[30];
    char c;
    printf("put your pass key: ");
    c = getchar();

    printf("Enter your name: ");
    scanf("%s",name);

    printf("Enter your address: ");
    scanf("%s",address);

    printf("--------------------------\n");
    printf("Entered Name: %s\n",name);
    printf("Entered Address: %s\n",address);

    printf("Your pass key: ");
    putchar(c);
}
</code>```

I tried to run it from pass key point and it works but when I continue it's given me nothing

答:
Unfortunately, I'm not sure if I understood your question correctly.

However, under Linux the program would work the following way:

You close your eyes, assume your program works correctly and type. You will see:

```<code>put your pass key: KMartin
Enter your name: Enter your address: Hello
--------------------------
Entered Name: Martin
Entered Address: Hello
Your pass key: K
</code>```

Why?

When you type some keys in Linux, the operating system will store the keys pressed in some buffer until the "enter" ("return") key is pressed.

Maybe MINGW has the same behaviour.

So the program reaches getchar() and I type "K" "M" "a" "r" "t" "i" "n".

Linux stores these keys into a buffer and instead of passing these keys to the program.

I press the "enter" ("return") key. Then Linux will pass the "K" to the getchar() function and the remaining keys ("Martin") to the scanf() function.

This behaviour can be disabled:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <termios.h>

int main(void) {
    char name[20], address[30];
    char c;
    struct termios tios;

    printf("put your pass key: ");

    /* Disable the buffer */
    tcgetattr(1,&tios);
    tios.c_lflag&=~ICANON;
    tios.c_cc[VTIME]=0;
    tios.c_cc[VMIN]=1;
    tcsetattr(1,TCSANOW,&tios);

    c = getchar();

    /* Re-enable the buffer
     * If the buffer is not enabled,
     * sscanf() won't work correctly. */
    tios.c_lflag|=ICANON;
    tcsetattr(1,TCSANOW,&tios);

    printf("\nEnter your name: ");
    ...
</code>```

... and the output will be:

```<code>put your pass key: K
Enter your name: Martin
Enter your address: Hello
--------------------------
Entered Name: Martin
Entered Address: Hello
Your pass key: K
</code>```

EDIT

i run it on eclipse and it's shows nothing but when using repl like @user366312 it works I don't see anything in console on eclipse

The consoles in Eclipse typically do not allow input so programs can write output but not receive input.

However, I know that there is some check box (at least in some Eclipse versions) that allow input...

I don't know if you will have the problem I described above when using Eclipse.

However, if you have that behaviour, the settermios method probably won't work...

Body:
I built it when I click to run it's showing no errors no warnings nothing

#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char name[20], address[30];
    char c;
    printf("put your pass key: ");
    c = getchar();

    printf("Enter your name: ");
    scanf("%s",name);

    printf("Enter your address: ");
    scanf("%s",address);

    printf("--------------------------\n");
    printf("Entered Name: %s\n",name);
    printf("Entered Address: %s\n",address);

    printf("Your pass key: ");
    putchar(c);
}

I tried to run it from pass key point and it works but when I continue it's given me nothing

Body:
Unfortunately, I'm not sure if I understood your question correctly.

However, under Linux the program would work the following way:

You close your eyes, assume your program works correctly and type. You will see:

put your pass key: KMartin
Enter your name: Enter your address: Hello
--------------------------
Entered Name: Martin
Entered Address: Hello
Your pass key: K

Why?

When you type some keys in Linux, the operating system will store the keys pressed in some buffer until the "enter" ("return") key is pressed.

Maybe MINGW has the same behaviour.

So the program reaches getchar() and I type "K" "M" "a" "r" "t" "i" "n".

Linux stores these keys into a buffer and instead of passing these keys to the program.

I press the "enter" ("return") key. Then Linux will pass the "K" to the getchar() function and the remaining keys ("Martin") to the scanf() function.

This behaviour can be disabled:

#include <stdio.h>
#include <stdlib.h>
#include <termios.h>

int main(void) {
    char name[20], address[30];
    char c;
    struct termios tios;

    printf("put your pass key: ");

    /* Disable the buffer */
    tcgetattr(1,&tios);
    tios.c_lflag&=~ICANON;
    tios.c_cc[VTIME]=0;
    tios.c_cc[VMIN]=1;
    tcsetattr(1,TCSANOW,&tios);

    c = getchar();

    /* Re-enable the buffer
     * If the buffer is not enabled,
     * sscanf() won't work correctly. */
    tios.c_lflag|=ICANON;
    tcsetattr(1,TCSANOW,&tios);

    printf("\nEnter your name: ");
    ...

... and the output will be:

put your pass key: K
Enter your name: Martin
Enter your address: Hello
--------------------------
Entered Name: Martin
Entered Address: Hello
Your pass key: K

EDIT

i run it on eclipse and it's shows nothing but when using repl like @user366312 it works I don't see anything in console on eclipse

The consoles in Eclipse typically do not allow input so programs can write output but not receive input.

However, I know that there is some check box (at least in some Eclipse versions) that allow input...

I don't know if you will have the problem I described above when using Eclipse.

However, if you have that behaviour, the settermios method probably won't work...


问:
Object literal may only specify known properties, and 'modules' does not exist in type 'ModuleMetadata'
I just upgraded all packages, specially TypeScript from 2.5.2 to the 3.8.3 and I'm getting this error:

error TS2345: Argument of type '{ modules: (typeof OrmModule)[];
  controllers: (typeof AppController)[]; components: (typeof
  ConfigurationService | typeof LoggingService | typeof
  MessagingService)[]; }' is not assignable to parameter of type
  'ModuleMetadata'.   Object literal may only specify known properties,
  and 'modules' does not exist in type 'ModuleMetadata'.

19   modules: [OrmModule, AdminModule, CrmModule, EmrModule],

```<code>import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';

import { AuthenticationMiddleware } from './authentication/tokenhandler';
import { MulterMiddleware } from './common/middlewares/multer';

import { AdminModule } from './admin/admin.module';
import { OrmModule } from '../orm/orm.module';
import { CrmModule } from './crm/crm.module';
import { EmrModule } from './emr/emr.module';
import { ConfigurationService } from './common/services/configuration';
import { LoggingService } from './common/services/logging';
import { MessagingService } from './common/services/messaging';

@Module({
  modules: [OrmModule, AdminModule, CrmModule, EmrModule],
  controllers: [AppController],
  components: [ConfigurationService, LoggingService, MessagingService]
})

export class ApplicationModule implements NestModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer.apply(AuthenticationMiddleware)
      .with(  // routes that will be excluded.
        { path: '/leads/open', method: RequestMethod.POST },
        { path: '/', method: RequestMethod.GET },
        { path: '/documents/upload', method: RequestMethod.POST },
      ).forRoutes( //routes that will be included
        { path: '/*', method: RequestMethod.ALL },
        { path: '/*/*', method: RequestMethod.ALL }
      );
    consumer.apply(MulterMiddleware)
      .forRoutes({ path: '/images/:leadId', method: RequestMethod.POST },
            { path: '/documents/:leadId', method: RequestMethod.POST },
            { path: '/examination/stylist/:leadId', method: RequestMethod.POST },
            { path: '/examination/stylist/:leadId/:id', method: RequestMethod.PUT }
    )
  }
}

</code>```

答: Change modules: [] for imports: []

Body:
I just upgraded all packages, specially TypeScript from 2.5.2 to the 3.8.3 and I'm getting this error:

error TS2345: Argument of type '{ modules: (typeof OrmModule)[];
  controllers: (typeof AppController)[]; components: (typeof
  ConfigurationService | typeof LoggingService | typeof
  MessagingService)[]; }' is not assignable to parameter of type
  'ModuleMetadata'.   Object literal may only specify known properties,
  and 'modules' does not exist in type 'ModuleMetadata'.

19   modules: [OrmModule, AdminModule, CrmModule, EmrModule],

import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';

import { AuthenticationMiddleware } from './authentication/tokenhandler';
import { MulterMiddleware } from './common/middlewares/multer';

import { AdminModule } from './admin/admin.module';
import { OrmModule } from '../orm/orm.module';
import { CrmModule } from './crm/crm.module';
import { EmrModule } from './emr/emr.module';
import { ConfigurationService } from './common/services/configuration';
import { LoggingService } from './common/services/logging';
import { MessagingService } from './common/services/messaging';

@Module({
  modules: [OrmModule, AdminModule, CrmModule, EmrModule],
  controllers: [AppController],
  components: [ConfigurationService, LoggingService, MessagingService]
})

export class ApplicationModule implements NestModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer.apply(AuthenticationMiddleware)
      .with(  // routes that will be excluded.
        { path: '/leads/open', method: RequestMethod.POST },
        { path: '/', method: RequestMethod.GET },
        { path: '/documents/upload', method: RequestMethod.POST },
      ).forRoutes( //routes that will be included
        { path: '/*', method: RequestMethod.ALL },
        { path: '/*/*', method: RequestMethod.ALL }
      );
    consumer.apply(MulterMiddleware)
      .forRoutes({ path: '/images/:leadId', method: RequestMethod.POST },
            { path: '/documents/:leadId', method: RequestMethod.POST },
            { path: '/examination/stylist/:leadId', method: RequestMethod.POST },
            { path: '/examination/stylist/:leadId/:id', method: RequestMethod.PUT }
    )
  }
}

Body: Change modules: [] for imports: []


问:
Loop through two arrays containing emails
I have two arrays containing email addresses and then another array called emailgroup that contains the name of these two arrays.

I want to create a loop that loops around the emailgroup array to call the other 2 arrays in turn.

I thought for example on the first loop, the "emails" array would be called but the error message says type mismatch.

Can anyone help modify the code below?

```<code> Sub Email_Click()
 Dim myOutlook As Outlook.Application
 Dim objMailMessage As Outlook.MailItem

Dim emails As Variant
Dim moreemails As Variant
Dim emailgroup As Variant

Set myOutlook = Outlook.Application
Set objMailMessage = myOutlook.CreateItem(0)

emails = Array("a@a.com", "b@b.com")
moreemails = Array("c@c.com", "d@d.com")

emailgroup = Array("emails", "moreemails")

For Each i In emailgroup

currentemail = i

With objMailMessage
    .Display
    .To = Join(currentemail, ";")
    .Subject = ""
    .HTMLBody = ""

    .Save
    .Close olPromptForSave
End With
 Next
End Sub
</code>```

答:
Here's another take:

```<code>Private Function CombineArray(arr1() As Variant, arr2() As Variant) As Variant()

Dim tmp() As Variant ' Array to hold values until output
Dim n As Long ' Numeric value to count first array
Dim m As Long ' Numeric value to count second array (`n` could be reused, but this helps keep things separate, IMHO)
Dim idx As Long ' Variable to keep tabs on current index when switching between arrays

' ReDim out temporary array
ReDim tmp(UBound(arr1) + UBound(arr2) + 1)

' Set an indexer to account for switching arrays
idx = 0
For n = 0 To UBound(arr1, 1)
    tmp(idx) = arr1(n)
    idx = idx + 1
Next n

' Iterate over second array.
For m = 0 To UBound(arr2, 1)
    tmp(idx) = arr2(m)
    idx = idx + 1
Next m

' Set results to function output
CombineArray = tmp

End Function
</code>```

Then a quick test function to check CombineArray() results:

```<code>Public Function TestFunc()

Dim output() As Variant
Dim emails() As Variant
Dim moreemails() As Variant

' Set out test email groups
emails() = Array("a@a.com", "b@b.com")
moreemails() = Array("c@c.com", "d@d.com")

' ReDim output array.  Probably not necessary, but helps keep things in check.
ReDim output(UBound(emails) + UBound(moreemails))

' Populate output array with combined array
output = CombineArray(emails, moreemails)

' Test output
Debug.Print Chr(13) & "List of values:"
Dim i As Integer
For i = 0 To UBound(output)
    Debug.Print "-- " & output(i)
Next i

' Join function output
Debug.Print Chr(13) & "The joined values are: " & Join(output, ";")

End Function
</code>```

Using the immediate window, we get:

```<code>Debug.Print TestFunc()

List of values:
-- a@a.com
-- b@b.com
-- c@c.com
-- d@d.com

The joined values are: a@a.com;b@b.com;c@c.com;d@d.com
</code>```

Body:
I have two arrays containing email addresses and then another array called emailgroup that contains the name of these two arrays.

I want to create a loop that loops around the emailgroup array to call the other 2 arrays in turn.

I thought for example on the first loop, the "emails" array would be called but the error message says type mismatch.

Can anyone help modify the code below?

 Sub Email_Click()
 Dim myOutlook As Outlook.Application
 Dim objMailMessage As Outlook.MailItem

Dim emails As Variant
Dim moreemails As Variant
Dim emailgroup As Variant

Set myOutlook = Outlook.Application
Set objMailMessage = myOutlook.CreateItem(0)

emails = Array("a@a.com", "b@b.com")
moreemails = Array("c@c.com", "d@d.com")

emailgroup = Array("emails", "moreemails")

For Each i In emailgroup

currentemail = i

With objMailMessage
    .Display
    .To = Join(currentemail, ";")
    .Subject = ""
    .HTMLBody = ""

    .Save
    .Close olPromptForSave
End With
 Next
End Sub

Body:
Here's another take:

Private Function CombineArray(arr1() As Variant, arr2() As Variant) As Variant()

Dim tmp() As Variant ' Array to hold values until output
Dim n As Long ' Numeric value to count first array
Dim m As Long ' Numeric value to count second array (`n` could be reused, but this helps keep things separate, IMHO)
Dim idx As Long ' Variable to keep tabs on current index when switching between arrays

' ReDim out temporary array
ReDim tmp(UBound(arr1) + UBound(arr2) + 1)

' Set an indexer to account for switching arrays
idx = 0
For n = 0 To UBound(arr1, 1)
    tmp(idx) = arr1(n)
    idx = idx + 1
Next n

' Iterate over second array.
For m = 0 To UBound(arr2, 1)
    tmp(idx) = arr2(m)
    idx = idx + 1
Next m

' Set results to function output
CombineArray = tmp

End Function

Then a quick test function to check CombineArray() results:

Public Function TestFunc()

Dim output() As Variant
Dim emails() As Variant
Dim moreemails() As Variant

' Set out test email groups
emails() = Array("a@a.com", "b@b.com")
moreemails() = Array("c@c.com", "d@d.com")

' ReDim output array.  Probably not necessary, but helps keep things in check.
ReDim output(UBound(emails) + UBound(moreemails))

' Populate output array with combined array
output = CombineArray(emails, moreemails)

' Test output
Debug.Print Chr(13) & "List of values:"
Dim i As Integer
For i = 0 To UBound(output)
    Debug.Print "-- " & output(i)
Next i

' Join function output
Debug.Print Chr(13) & "The joined values are: " & Join(output, ";")

End Function

Using the immediate window, we get:

Debug.Print TestFunc()

List of values:
-- a@a.com
-- b@b.com
-- c@c.com
-- d@d.com

The joined values are: a@a.com;b@b.com;c@c.com;d@d.com


问:
(Python) Beautifull soup and encoding (utf-8, cp1252,ascii...)
Please help, I am so loosing nerves now.I am having this problems since I started learning Python. Always come to a same issue and no one online can give any valid answer

My code:

```<code>from bs4 import BeautifulSoup
import requests

page = requests.get(
    'https://forecast.weather.gov/MapClick.php?lat=34.05349000000007&lon=-118.24531999999999#.XswiwMCxWUk')
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id='seven-day-forecast-body')
items = week.find_all(class_='forecast-tombstone')

print(items[0].find(class_='period-name').get_text())
print(items[0].find(class_='short-desc').get_text())
print(items[0].find(class_='temp temp-high').get_text())

period_names = [item.find(class_='period-name').get_text() for item in items]
short_descp = [item.find(class_='short-desc').get_text() for item in items]
temp = [item.find(class_='temp temp-high').get_text() for item in items]
print(period_names)
print(short_descp)
print(temp)
</code>```

output :

```<code>[Running] python -u "c:\Users\dukasu\Documents\Python\test.py"
ThisAfternoon
Partly Sunny
High: 76 �F
Traceback (most recent call last):
  File "c:\Users\dukasu\Documents\Python\test.py", line 20, in <module>
    temp = [item.find(class_='temp temp-high').get_text() for item in items]
  File "c:\Users\dukasu\Documents\Python\test.py", line 20, in <listcomp>
    temp = [item.find(class_='temp temp-high').get_text() for item in items]
AttributeError: 'NoneType' object has no attribute 'get_text'

[Done] exited with code=1 in 0.69 seconds
</code>```

Issue is due to a utf-8 encoding (my PC is at cp1252), but how to solve it terminally (I think problem is cos it cant operate with degree symbol). There is a simple code in Python 2, but how to solve it in Python 3.xx. How to set encoding at start of the code and forget about this issue.
anp please pardon my english, it is not my native language.

答:
The error is coming from class name which is returning None, use only class_='temp Not class_='temp temp-high

Example

```<code>temp = [item.find(class_='temp').get_text() for item in items]
</code>```

Full code

```<code>from bs4 import BeautifulSoup
import requests

page = requests.get(
    'https://forecast.weather.gov/MapClick.php?lat=34.05349000000007&lon=-118.24531999999999#.XswiwMCxWUk')
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id='seven-day-forecast-body')
items = week.find_all(class_='forecast-tombstone')

print(items[0].find(class_='period-name').get_text())
print(items[0].find(class_='short-desc').get_text())
print(items[0].find(class_='temp temp-high').get_text())

period_names = [item.find(class_='period-name').get_text() for item in items]
short_descp = [item.find(class_='short-desc').get_text() for item in items]
temp = [item.find(class_='temp').get_text() for item in items]
print(period_names)
print(short_descp)
print(temp)
</code>```

Prints Out

```<code>ThisAfternoon
Partly Sunny
High: 76 °F
['ThisAfternoon', 'Tonight', 'Saturday', 'SaturdayNight', 'Sunday', 'SundayNight', 'Monday', 'MondayNight', 'Tuesday']
['Partly Sunny', 'Patchy Fog', 'Patchy Fogthen MostlySunny', 'Patchy Fog', 'Patchy Fogthen PartlySunny', 'Patchy Fog', 'Patchy Fogthen MostlyCloudy', 'Mostly Cloudy', 'Partly Sunny']
['High: 76 °F', 'Low: 58 °F', 'High: 75 °F', 'Low: 59 °F', 'High: 80 °F', 'Low: 61 °F', 'High: 78 °F', 'Low: 61 °F', 'High: 77 °F']
</code>```

Body:
Please help, I am so loosing nerves now.I am having this problems since I started learning Python. Always come to a same issue and no one online can give any valid answer

My code:

from bs4 import BeautifulSoup
import requests

page = requests.get(
    'https://forecast.weather.gov/MapClick.php?lat=34.05349000000007&lon=-118.24531999999999#.XswiwMCxWUk')
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id='seven-day-forecast-body')
items = week.find_all(class_='forecast-tombstone')

print(items[0].find(class_='period-name').get_text())
print(items[0].find(class_='short-desc').get_text())
print(items[0].find(class_='temp temp-high').get_text())

period_names = [item.find(class_='period-name').get_text() for item in items]
short_descp = [item.find(class_='short-desc').get_text() for item in items]
temp = [item.find(class_='temp temp-high').get_text() for item in items]
print(period_names)
print(short_descp)
print(temp)

output :

[Running] python -u "c:\Users\dukasu\Documents\Python\test.py"
ThisAfternoon
Partly Sunny
High: 76 �F
Traceback (most recent call last):
  File "c:\Users\dukasu\Documents\Python\test.py", line 20, in <module>
    temp = [item.find(class_='temp temp-high').get_text() for item in items]
  File "c:\Users\dukasu\Documents\Python\test.py", line 20, in <listcomp>
    temp = [item.find(class_='temp temp-high').get_text() for item in items]
AttributeError: 'NoneType' object has no attribute 'get_text'

[Done] exited with code=1 in 0.69 seconds

Issue is due to a utf-8 encoding (my PC is at cp1252), but how to solve it terminally (I think problem is cos it cant operate with degree symbol). There is a simple code in Python 2, but how to solve it in Python 3.xx. How to set encoding at start of the code and forget about this issue.
anp please pardon my english, it is not my native language.

Body:
The error is coming from class name which is returning None, use only class_='temp Not class_='temp temp-high

Example

temp = [item.find(class_='temp').get_text() for item in items]

Full code

from bs4 import BeautifulSoup
import requests

page = requests.get(
    'https://forecast.weather.gov/MapClick.php?lat=34.05349000000007&lon=-118.24531999999999#.XswiwMCxWUk')
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id='seven-day-forecast-body')
items = week.find_all(class_='forecast-tombstone')

print(items[0].find(class_='period-name').get_text())
print(items[0].find(class_='short-desc').get_text())
print(items[0].find(class_='temp temp-high').get_text())

period_names = [item.find(class_='period-name').get_text() for item in items]
short_descp = [item.find(class_='short-desc').get_text() for item in items]
temp = [item.find(class_='temp').get_text() for item in items]
print(period_names)
print(short_descp)
print(temp)

Prints Out

ThisAfternoon
Partly Sunny
High: 76 °F
['ThisAfternoon', 'Tonight', 'Saturday', 'SaturdayNight', 'Sunday', 'SundayNight', 'Monday', 'MondayNight', 'Tuesday']
['Partly Sunny', 'Patchy Fog', 'Patchy Fogthen MostlySunny', 'Patchy Fog', 'Patchy Fogthen PartlySunny', 'Patchy Fog', 'Patchy Fogthen MostlyCloudy', 'Mostly Cloudy', 'Partly Sunny']
['High: 76 °F', 'Low: 58 °F', 'High: 75 °F', 'Low: 59 °F', 'High: 80 °F', 'Low: 61 °F', 'High: 78 °F', 'Low: 61 °F', 'High: 77 °F']


答:
No, Unfortunately import statements does not work like object destructuring.

but you can do this:

```<code>const constParent = require('a/b/c/house').grandparent.parent;

</code>```

Hope I can help you

Title: How to import object of object from file in typescript

Body:
How can I import object of object from file in typescript. I know I can import like import house from 'a/b/c/house'. but can I just import parent? so I do not need to write the code like
house.grandparent.parent.xxx

#filepath: a/b/c/house.ts
const house = {
  grandparent: {
    parent: {
      childa: (text: string) => `s'${text}')`,
      childb: 'b',
      childc: 'c',
    },
  },
};

export default house;

Body:
No, Unfortunately import statements does not work like object destructuring.

but you can do this:

const constParent = require('a/b/c/house').grandparent.parent;

Hope I can help you


问:
Issue with SignalR primary/secondary
I have an asp dotnet core 3.1 application that uses SignalR.  According to this documentation, you can add primary and secondary connections.  I have this working in one of my services, but another service keeps bombing out and I can't figure out why.

Error message:

```<code>Connection string missing required properties endpoint and accesskey. (Parameter 'connectionString')
</code>```

Stack:

```<code>at Microsoft.Azure.SignalR.ConnectionStringParser.Parse(String connectionString)
   at Microsoft.Azure.SignalR.ServiceEndpoint..ctor(String connectionString, EndpointType type, String name)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase.<GetEndpoints>d__16.MoveNext()
   at System.Linq.Enumerable.DistinctIterator`1.MoveNext()
   at System.Linq.Lookup`2.Create(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
   at System.Linq.GroupedEnumerable`2.GetEnumerator()
   at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase.GetValuableEndpoints(IEnumerable`1 endpoints)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase..ctor(IEnumerable`1 endpoints, ILogger logger)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase..ctor(IServiceEndpointOptions options, ILogger logger)
   at Microsoft.Azure.SignalR.ServiceEndpointManager..ctor(IOptionsMonitor`1 optionsMonitor, ILoggerFactory loggerFactory)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Azure.SignalR.ServiceHubDispatcher.Start(Endpoint endpoint, Type hubType, ConnectionDelegate app)
   at Microsoft.Azure.SignalR.AzureSignalRHostedService.Start()
   at Microsoft.Azure.SignalR.AzureSignalRStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.ApplicationInsights.AspNetCore.ApplicationInsightsStartupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__31.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__9.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at SigR.Program.Main(String[] args) in G:\Git_Merc\ms-chat\WebApi\Program.cs:line 13
</code>```

I have this Environment variable:

Azure:SignalR:ConnectionString:Primary

with value

Endpoint=https://<redacted>;AccessKey=<redacted>Version=1.0;

If I remove the :Primary from the key, it works, but it should work with it as well.  I've also tried inserting a , such as

Azure:SignalR:ConnectionString:Test:Primary

And, like I said, I have another service working with that key.  TBH, I'm not even sure why DI is picking this up on app startup?

Edit:

Adding requested code.

```<code>var sigrBuilder = services.AddSignalR().AddNewtonsoftJsonProtocol(options =>
            {
                options.PayloadSerializerSettings.Converters = new List<JsonConverter>
                {
                    new TransferOptionConverter() //converters for data from mercury
                };
            });
sigrBuilder.AddAzureSignalR();
</code>```

答: Turns out I had the configuration duplicated in my appsettings file with a BS value and it was picking up that value instead of the one I had with the ":Primary" suffix.  It would work when I did "Azure:SignalR:ConnectionString" because it was an exact match and overwrote.  Once I blew that away, everything worked.</p>

Title: Issue with SignalR primary/secondary

Body:
I have an asp dotnet core 3.1 application that uses SignalR.  According to this documentation, you can add primary and secondary connections.  I have this working in one of my services, but another service keeps bombing out and I can't figure out why.

Error message:

Connection string missing required properties endpoint and accesskey. (Parameter 'connectionString')

Stack:

at Microsoft.Azure.SignalR.ConnectionStringParser.Parse(String connectionString)
   at Microsoft.Azure.SignalR.ServiceEndpoint..ctor(String connectionString, EndpointType type, String name)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase.<GetEndpoints>d__16.MoveNext()
   at System.Linq.Enumerable.DistinctIterator`1.MoveNext()
   at System.Linq.Lookup`2.Create(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
   at System.Linq.GroupedEnumerable`2.GetEnumerator()
   at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase.GetValuableEndpoints(IEnumerable`1 endpoints)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase..ctor(IEnumerable`1 endpoints, ILogger logger)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase..ctor(IServiceEndpointOptions options, ILogger logger)
   at Microsoft.Azure.SignalR.ServiceEndpointManager..ctor(IOptionsMonitor`1 optionsMonitor, ILoggerFactory loggerFactory)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Azure.SignalR.ServiceHubDispatcher.Start(Endpoint endpoint, Type hubType, ConnectionDelegate app)
   at Microsoft.Azure.SignalR.AzureSignalRHostedService.Start()
   at Microsoft.Azure.SignalR.AzureSignalRStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.ApplicationInsights.AspNetCore.ApplicationInsightsStartupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__31.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__9.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at SigR.Program.Main(String[] args) in G:\Git_Merc\ms-chat\WebApi\Program.cs:line 13

I have this Environment variable:

Azure:SignalR:ConnectionString:Primary

with value

Endpoint=https://<redacted>;AccessKey=<redacted>Version=1.0;

If I remove the :Primary from the key, it works, but it should work with it as well.  I've also tried inserting a , such as

Azure:SignalR:ConnectionString:Test:Primary

And, like I said, I have another service working with that key.  TBH, I'm not even sure why DI is picking this up on app startup?

Edit:

Adding requested code.

var sigrBuilder = services.AddSignalR().AddNewtonsoftJsonProtocol(options =>
            {
                options.PayloadSerializerSettings.Converters = new List<JsonConverter>
                {
                    new TransferOptionConverter() //converters for data from mercury
                };
            });
sigrBuilder.AddAzureSignalR();


问:
Reorder numeric values contained in keys and assigned as strings without losing the key assignment?
Apologies for the title, this is certainly a bit of a pretentious issue. I've got a range of numbers distributed across two arrays. These arrays hold the same dateset, however one has been converted to strings so that a reference key/tag can be assigned to each value indicating a category index.

```<code>const array1 = ["0:0", "0:5.476", "0:11.251", "0:31.916", "0:44.007", "0:53.911", "0:58.628", "0:65.729", "0:75.222", "0:88.849", "0:100", "1:0", "1:44.839", "1:60.303", "1:69.072", "1:73.150", "1:85.800", "1:100", "2:0", "2:11.796", "2:26.525", "2:81.782", "2:88.367", "2:100"]
</code>```

0: 1: 2: represent the category index.

The second representation of the dateset is numeric and assigned to a separate array in ascending order.

```<code>const array2 = [0, 0, 0, 5.476, 11.251, 11.796, 26.525, 31.916, 44.007, 44.839, 53.911, 58.628, 60.303, 65.729, 69.072, 73.150, 75.222, 81.782, 85.800, 88.367, 88.849, 100, 100, 100]
</code>```

The goal is to replicate the order of array2 in array1 whilst keeping the category index keys intact. As can be seen in the example below.

```<code>> console.log(array1);
["0:0", "1:0", "2:0", "0:5.476", "0:11.251", "2:11.796", "2:26.525", "0:31.916", "0:44.007", "1:44.839", "0:53.911", "0:58.628", "1:60.303", "0:65.729", "1:69.072", "1:73.150", "0:75.222", "2:81.782", "1:85.800", "2:88.367", "0:88.849", "0:100", "1:100", "2:100"]
</code>```

Of course if I just wanted to match the order I could just un-string array1 and run it in ascending order. This example below un-strings all the 0: values.

```<code>let array1Ascend = [];
for(i=0;i<array1.length;i++){
    array1Ascent.push(Number(array1[i].match(/(?!0*:).*/)))
}
array1Ascent.sort(function(a, b) {
                return a - b;
            });
</code>```

But the issue is that i'd of course lose the category index assignment of each value in doing that, which defeats the purpose. I'd say i'm more stuck on understanding the logic of this issue if anything. Any help would be appreciated, thank you.

Body:
Apologies for the title, this is certainly a bit of a pretentious issue. I've got a range of numbers distributed across two arrays. These arrays hold the same dateset, however one has been converted to strings so that a reference key/tag can be assigned to each value indicating a category index.

const array1 = ["0:0", "0:5.476", "0:11.251", "0:31.916", "0:44.007", "0:53.911", "0:58.628", "0:65.729", "0:75.222", "0:88.849", "0:100", "1:0", "1:44.839", "1:60.303", "1:69.072", "1:73.150", "1:85.800", "1:100", "2:0", "2:11.796", "2:26.525", "2:81.782", "2:88.367", "2:100"]

0: 1: 2: represent the category index.

The second representation of the dateset is numeric and assigned to a separate array in ascending order.

const array2 = [0, 0, 0, 5.476, 11.251, 11.796, 26.525, 31.916, 44.007, 44.839, 53.911, 58.628, 60.303, 65.729, 69.072, 73.150, 75.222, 81.782, 85.800, 88.367, 88.849, 100, 100, 100]

The goal is to replicate the order of array2 in array1 whilst keeping the category index keys intact. As can be seen in the example below.

> console.log(array1);
["0:0", "1:0", "2:0", "0:5.476", "0:11.251", "2:11.796", "2:26.525", "0:31.916", "0:44.007", "1:44.839", "0:53.911", "0:58.628", "1:60.303", "0:65.729", "1:69.072", "1:73.150", "0:75.222", "2:81.782", "1:85.800", "2:88.367", "0:88.849", "0:100", "1:100", "2:100"]

Of course if I just wanted to match the order I could just un-string array1 and run it in ascending order. This example below un-strings all the 0: values.

let array1Ascend = [];
for(i=0;i<array1.length;i++){
    array1Ascent.push(Number(array1[i].match(/(?!0*:).*/)))
}
array1Ascent.sort(function(a, b) {
                return a - b;
            });

But the issue is that i'd of course lose the category index assignment of each value in doing that, which defeats the purpose. I'd say i'm more stuck on understanding the logic of this issue if anything. Any help would be appreciated, thank you.

Body:
Do you need to sort the array by element value ascendingly?
You could provide your own sorting function to the Array.prototype.sort method.

const array1 = ["0:0", "0:5.476", "0:11.251", "0:31.916", "0:44.007", "0:53.911", "0:58.628", "0:65.729", "0:75.222", "0:88.849", "0:100", "1:0", "1:44.839", "1:60.303", "1:69.072", "1:73.150", "1:85.800", "1:100", "2:0", "2:11.796", "2:26.525", "2:81.782", "2:88.367", "2:100"];

console.log(
  array1.sort((a, b) => {
    const ai = parseFloat(a.split(':', 2)[1]);
    const bi = parseFloat(b.split(':', 2)[1]);
    if (ai === bi) {
      return 0;
    }

    return ai > bi ? 1 : -1;
  })
);