答:
Use left_on and right_on in order to merge because you have different keys in each dataframe.</p>

```<code>piat_comp2 = piat_comp.merge(
    piat2,
    left_on='piat_retest_id_1',
    right_on='piat_retest_id_2',
    how='outer'
)
</code>```

Title: Pandas merging on id

Body:
I cannot get this to come out as I expect, despite trying different variations of merging.

I would like to merge df's piat_comp and piat2 on piat_retest_id_2 but the following code, also tried as an inner join, does not line up as expected.

    piat_comp2 = piat_comp.merge(piat2, on='piat_retest_id_2', how='outer')

For instance, I am expecting index 8 of piat_comp to pair with index 9 of piat 2 because they both share the same id in 'piat_retest_id_2'. Instead they simply do not line up.

In the resultant dataframe those rows should merge to give:

piat_retest_id_1   -----   PIAT.ability   -----  piat_retest_id_2  -----   PIAT.ability_2

UK_543970282 -----    0.270247832130706  -----   UK_358142873 -----0.697223344529081

Notice that piat_retest_id_1 and piat_retest_id_2 are not expected to be the same. piat_retest_id_2 is in both df's and I want to merge on that, but only end up with one column of it.

Reproducible:

piat_comp = {'piat_retest_id_1': {0: 'UK_982598362',
  1: 'UK_554290758',
  2: 'UK_416473256',
  3: 'UK_717765782',
  4: 'UK_340767839',
  5: 'UK_393447950',
  6: 'UK_16532112',
  7: 'UK_887499021',
  8: 'UK_543970282',
  9: 'UK_86558749',
  10: 'UK_763524616',
  11: 'UK_59234772',
  12: 'UK_891870396',
  13: 'UK_416946337',
  14: 'UK_208235437',
  15: 'UK_697728998',
  16: 'UK_283032428',
  17: 'UK_927006735',
  18: 'UK_838548458',
  19: 'UK_935961427',
  20: 'UK_534651143',
  21: 'UK_469442638',
  22: 'UK_357516555',
  23: 'UK_869226039',
  24: 'UK_675587892',
  25: 'UK_331843371',
  26: 'UK_570264371',
  27: 'UK_818769311',
  28: 'UK_708776594',
  29: 'UK_811947376',
  30: 'AUS_182800035',
  31: 'AUS_436205218',
  32: 'AUS_519722760',
  33: 'AUS_948860279',
  34: 'AUS_273917058',
  35: 'AUS_174076947',
  36: 'AUS_462744594',
  37: 'AUS_718809552',
  38: 'AUS_142275638',
  39: 'AUS_646335936',
  40: 'AUS_775355864',
  41: 'AUS_523210619',
  42: 'AUS_242767995',
  43: 'AUS_485797627',
  44: 'AUS_192289763',
  45: 'AUS_971858664',
  46: 'AUS_272182103',
  47: 'AUS_6470694',
  48: 'AUS_960651008',
  49: 'AUS_36924588',
  50: 'AUS_921547727',
  51: 'AUS_469946434',
  52: 'AUS_591613124',
  53: 'AUS_575220499',
  54: 'AUS_767535190',
  55: 'AUS_6760645',
  56: 'AUS_33323414',
  57: 'AUS_453834043',
  58: 'AUS_576415932',
  59: 'AUS_359646415',
  60: 'AUS_647631159',
  61: 'AUS_535492855',
  62: 'AUS_488064434',
  63: 'AUS_230122761',
  64: 'AUS_996001169',
  65: 'AUS_830133002',
  66: 'AUS_82508132',
  67: 'AUS_922040010',
  68: 'AUS_754682968',
  69: 'AUS_79125001',
  70: 'AUS_581895146',
  71: 'AUS_100799448'},
 'PIAT.ability': {0: 3.8309313391931497,
  1: 1.99292247701631,
  2: 3.94306748097956,
  3: -0.19562132382300002,
  4: 0.6505183735635122,
  5: 0.731816086976127,
  6: 0.8137871489410059,
  7: 3.22777961014248,
  8: 0.270247832130706,
  9: 1.3424922846183798,
  10: -0.301396636649614,
  11: -1.9332907828737598,
  12: 0.917831930881864,
  13: 0.12488682346195801,
  14: 0.357263190639869,
  15: -0.771073750440309,
  16: 0.947225971482024,
  17: 1.09754260961856,
  18: 3.89556727394303,
  19: 0.000776309348843904,
  20: 0.633059075095001,
  21: -0.7613018941029259,
  22: 0.35232544411647604,
  23: 1.12508794021388,
  24: -0.689808173864224,
  25: 1.5182029956795,
  26: 0.8041551225465369,
  27: -0.49821628662950396,
  28: 1.0916595064983101,
  29: 3.6305272212891,
  30: -0.941759632235263,
  31: 0.8281845827398409,
  32: 0.38229348622269504,
  33: 1.53338336352128,
  34: 0.41351872726046995,
  35: 1.5705599264116397,
  36: 1.97524137560666,
  37: -0.00901326645847487,
  38: -0.6601342995997729,
  39: 0.764888906047256,
  40: 1.5069746380603897,
  41: 2.7867287535613703,
  42: -0.0572566797274714,
  43: 1.18340947496768,
  44: 0.21109444697996899,
  45: -0.11442018948849901,
  46: 0.260924655953102,
  47: 0.20230025184467001,
  48: -0.3911319281544,
  49: 1.66298720615184,
  50: 2.0562478076601596,
  51: -0.802324601478322,
  52: 0.0949041456718715,
  53: 0.39139573420752705,
  54: 0.0536255839392736,
  55: 1.32571209008263,
  56: 0.532393162267327,
  57: 0.269601175227049,
  58: 0.7076081560697621,
  59: 0.46112169587998597,
  60: -0.403030461213409,
  61: 0.43675734847674497,
  62: -0.879126649374346,
  63: -0.421994389129437,
  64: 1.77097042768753,
  65: -0.9110846702038922,
  66: -1.07482469386456,
  67: 3.7599324868259596,
  68: 0.359258100506062,
  69: 3.63222036081698,
  70: 0.389727330252132,
  71: 0.656178769811206},
 'piat_retest_id_2': {0: 'UK_873131581',
  1: 'UK_536050247',
  2: 'UK_288912',
  3: 'UK_601549101',
  4: 'UK_654724631',
  5: 'UK_927459150',
  6: 'UK_161992453',
  7: 'UK_898365573',
  8: 'UK_358142873',
  9: 'UK_749339291',
  10: 'UK_137508979',
  11: 'UK_802078996',
  12: 'UK_418768387',
  13: 'UK_538152168',
  14: 'UK_825889086.',
  15: 'UK_56800313',
  16: 'UK_90101007',
  17: 'UK_77933368',
  18: 'UK_288469917',
  19: 'UK_908770966',
  20: 'UK_661264755',
  21: 'UK_154114403',
  22: 'UK_826457452',
  23: 'UK_626934971',
  24: 'UK_852937537',
  25: 'UK_32221105',
  26: 'UK_516899485',
  27: nan,
  28: 'UK_213817864',
  29: 'UK_112922227',
  30: 'AUS_1828000352',
  31: 'AUS_4362052182',
  32: 'AUS_5197227602',
  33: 'AUS_9488602792',
  34: 'AUS_2739170582',
  35: 'AUS_1740769472',
  36: 'AUS_4627445942',
  37: 'AUS_7188095522',
  38: 'AUS_1422756382',
  39: 'AUS_6463359362',
  40: 'AUS_7753558642',
  41: nan,
  42: 'AUS_4857976272',
  43: 'AUS_1922897632',
  44: 'AUS_9718586642',
  45: 'AUS_2721821032',
  46: 'AUS_64706942',
  47: 'AUS_9606510082',
  48: nan,
  49: 'AUS_9215477272',
  50: 'AUS_5916131242',
  51: 'AUS_5752204992',
  52: 'AUS_7675351902',
  53: 'AUS_67606452',
  54: 'AUS_333234142',
  55: 'AUS_4538340432',
  56: 'AUS_5764159322',
  57: 'AUS_3596464152',
  58: 'AUS_6476311592',
  59: 'AUS_5354928552',
  60: 'AUS_4880644342',
  61: 'AUS_2301227612',
  62: 'AUS_9960011692',
  63: 'AUS_8301330022',
  64: 'AUS_825081322',
  65: 'AUS_9220400102',
  66: 'AUS_7546829682',
  67: 'AUS_791250012',
  68: 'AUS_5818951462',
  69: 'AUS_1007994482',
  70: nan,
  71: nan}}

  piat_comp = pd.DataFrame().from_dict(piat_comp)

    piat2 = {'piat_retest_id_2': {0: 'UK_873131581',
  1: 'UK_536050247',
  2: 'UK_288912',
  3: 'UK_601549101',
  4: 'UK_654724631',
  5: 'UK_927459150',
  6: 'UK_605723093',
  7: 'UK_161992453',
  8: 'UK_898365573',
  9: 'UK_358142873',
  10: 'UK_749339291',
  11: 'UK_137508979',
  12: 'UK_802078996',
  13: 'UK_418768387',
  14: 'UK_538152168',
  15: 'UK_56800313',
  16: 'UK_90101007',
  17: 'UK_77933368',
  18: 'UK_288469917',
  19: 'UK_908770966',
  20: 'UK_661264755',
  21: 'UK_154114403',
  22: 'UK_826457452',
  23: 'UK_852937537',
  24: 'UK_32221105',
  25: 'UK_516899485',
  26: 'UK_213817864',
  27: 'UK_112922227',
  28: 'AUS_1828000352',
  29: 'AUS_4362052182',
  30: 'AUS_5197227602',
  31: 'AUS_5782596212',
  32: 'AUS_9488602792',
  33: 'AUS_2739170582',
  34: 'AUS_1740769472',
  35: 'AUS_4627445942',
  36: 'AUS_7188095522',
  37: 'AUS_1422756382',
  38: 'AUS_6463359362',
  39: 'AUS_7753558642',
  40: 'AUS_4857976272',
  41: 'AUS_1922897632',
  42: 'AUS_9718586642',
  43: 'AUS_2721821032',
  44: 'AUS_64706942',
  45: 'AUS_9606510082',
  46: 'AUS_9215477272',
  47: 'AUS_4699464342',
  48: 'AUS_5916131242',
  49: 'AUS_5752204992',
  50: 'AUS_7675351902',
  51: 'AUS_67606452'},
 'PIAT.ability': {0: 4.0,
  1: 3.03585323865227,
  2: 3.0659628668283796,
  3: -0.984877273151229,
  4: 3.9214698118886804,
  5: 2.51547803673487,
  6: 1.1199284033743502,
  7: 0.776919848266456,
  8: 1.27559145269151,
  9: 0.697223344529081,
  10: 1.20628362697982,
  11: 1.3367662330669798,
  12: -0.862955270810047,
  13: 3.8621560811803697,
  14: 0.0635995324043882,
  15: -0.5886718197915529,
  16: -1.24297429168435,
  17: 3.5438183255585898,
  18: 4.0,
  19: 1.11913257500304,
  20: 0.7775141672201971,
  21: 1.1006024338623002,
  22: -0.24300164716209502,
  23: -0.494374704856605,
  24: 2.85613759713724,
  25: 1.3029798990839299,
  26: 0.0710404544671652,
  27: 4.0,
  28: 0.902265996923405,
  29: 1.4454497071397798,
  30: -1.2020915721021102,
  31: -1.8592336815873403,
  32: 1.61547349789574,
  33: 0.26694017591396,
  34: 2.44205760912957,
  35: 0.6621194092522099,
  36: -0.9020563539838921,
  37: 2.15717946932124,
  38: 1.16781892225373,
  39: 1.20554720958442,
  40: 1.7657674979533402,
  41: 0.40870760302225895,
  42: 0.0479209217874616,
  43: 1.6004708092039999,
  44: 0.19277544914143,
  45: 2.06504675907639,
  46: 2.95312483834473,
  47: -0.870384004997555,
  48: 0.7775511527014491,
  49: 1.3847884057742,
  50: 0.12852600156989802,
  51: 1.15655034425564}}

piat2 = pd.DataFrame().from_dict(piat2)

Body:
Use left_on and right_on in order to merge because you have different keys in each dataframe.

piat_comp2 = piat_comp.merge(
    piat2,
    left_on='piat_retest_id_1',
    right_on='piat_retest_id_2',
    how='outer'
)


来源: stackexchange

问:
Running Logstash on multiple nodes with JDBC input plugin
I have a basic HA setup for Logstash - two identical nodes in two separate AWS availability zones. Each node runs a pipeline that extracts a dataset from DB cluster and then outputs it downstream it to ELasticSearch cluster for indexing. This works fine with one Logstash node, but two nodes running in parallel send the same data twice down to ES for indexing due to the fact that each node tracks :sql_last_value separately. Since I use the same ID as the document ID across both nodes, all repeated data is simply updated instead of being inserted twice. In other words, there is 1 insert and 1 update per each dataset. This is, obviously, not very efficient and puts unnecessary load on ELK resources. It gets worse as additional Logstash nodes are added.

Does anyone know a better way of how parallel Logstash nodes should be set up, so each node doesn’t extract the same dataset if it’s been already extracted by another previous node? One poor man’s solution could be creating a shared NFS folder between Logstash nodes and having each node write :sql_last_value there, but I am not sure what kind of side effect I may run into with this setup, especially under higher loads. Thank you!

答:
We have the very same scenario: 3 logstash instances to ensure high availablility with serveral databases as data sources.

On each logstash instance install and enable the same jdbc-pipelines following this logic:

find a unique identifier in your result set for each document (primary key etc.) or generate a fingerprint using the fields in the result (MD5, SHA, not UUID). This identifier needs to be stable! It have to be the the same on other logstash nodes when the same entities are being returned.

in the elasticsearch-output use the id or the fingerprint as the document _id.

Here comes a simplified example for the easy case (id is part of the result set):

```<code>input{
  jdbc{
     ...
     statement => "select log_id, * from ..."
     ...
  }
}
filter{...}
output{
  elasticsearch{
    ...
    index => "logs-%{+YYYY.MM.dd}"
    document_id => "%{[log_id]}"
    ...
  }
}
</code>```

And here comes the variant when your data lacks uniqe identifiers and you need to generate a fingerprint

```<code>input{
  jdbc{
     ...
     statement => "select * from ..."
     ...
  }
}
filter{
  fingerprint {
    method => "MD5"
    concatenate_all_fields => true
  }
}
output{
  elasticsearch{
    ...
    index => "logs-%{+YYYY.MM.dd}"
    document_id => "%{[fingerprint]}"
    ...
  }
}
</code>```

In both ways, the documents will be created when they´re part of the resultset for one  logstash instance. All other logstash instances will get the same documents at a later time. Using the id/fingerprint as _id will update the previously created documents instead of duplicationg your data.

Works well for us, give it a try!

ContentLicense: CC BY-SA 4.0

Body:
We have the very same scenario: 3 logstash instances to ensure high availablility with serveral databases as data sources.

On each logstash instance install and enable the same jdbc-pipelines following this logic:

find a unique identifier in your result set for each document (primary key etc.) or generate a fingerprint using the fields in the result (MD5, SHA, not UUID). This identifier needs to be stable! It have to be the the same on other logstash nodes when the same entities are being returned.

in the elasticsearch-output use the id or the fingerprint as the document _id.

Here comes a simplified example for the easy case (id is part of the result set):

input{
  jdbc{
     ...
     statement => "select log_id, * from ..."
     ...
  }
}
filter{...}
output{
  elasticsearch{
    ...
    index => "logs-%{+YYYY.MM.dd}"
    document_id => "%{[log_id]}"
    ...
  }
}

And here comes the variant when your data lacks uniqe identifiers and you need to generate a fingerprint

input{
  jdbc{
     ...
     statement => "select * from ..."
     ...
  }
}
filter{
  fingerprint {
    method => "MD5"
    concatenate_all_fields => true
  }
}
output{
  elasticsearch{
    ...
    index => "logs-%{+YYYY.MM.dd}"
    document_id => "%{[fingerprint]}"
    ...
  }
}

In both ways, the documents will be created when they´re part of the resultset for one  logstash instance. All other logstash instances will get the same documents at a later time. Using the id/fingerprint as _id will update the previously created documents instead of duplicationg your data.

Works well for us, give it a try!


问:
How to convert nested dictonary to json in Python?
I created a nested dictionary in Python like this:

```<code>news_output = {'_id': 'd11bd6d0-846f-406d-a8e8-de57ee35fd53',
 'Link': ['https://www.marketingweek.com/2019/04/15/ad-blocking-retail-sales-ad-saturation-5-killer-stats-to-start-your-week/'],
 'Title': 'Why AI is the key to engaging today’s entitled consumer',
 'Entity': {'ORG': 'Coca-Cola', 'GPE': 'UK'},
 'Verbs': {0: {'Verb Text': 'is',
   'Text Head of the verb': 'ramping',
   'Child Word of the verb': []},
  1: {'Verb Text': 'ramping',
   'Text Head of the verb': 'ramping',
   'Child Word of the verb': [Cola, is, up, launches, brings, drink, .]},
  2: {'Verb Text': 'brings',
   'Text Head of the verb': 'ramping',
   'Child Word of the verb': [as, it, mineral]},
  'Verb Text': 'brings',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': [as, it, mineral]},
 'Dependent Words': {0: {'Text': 'Coca-Cola',
   'Root Text': 'Cola',
   'Dependent Text': 'ramping'},
  1: {'Text': 'new product launches',
   'Root Text': 'launches',
   'Dependent Text': 'ramping'},
  2: {'Text': 'it', 'Root Text': 'it', 'Dependent Text': 'brings'},
  3: {'Text': 'its mineral',
   'Root Text': 'mineral',
   'Dependent Text': 'brings'},
  4: {'Text': 'drink', 'Root Text': 'drink', 'Dependent Text': 'ramping'},
  5: {'Text': 'Aquarius', 'Root Text': 'Aquarius', 'Dependent Text': 'drink'},
  6: {'Text': 'the UK', 'Root Text': 'UK', 'Dependent Text': 'to'},
  'Text': 'the UK',
  'Root Text': 'UK',
  'Dependent Text': 'to'},
 'Signal': 'weak'}
</code>```

I tried to convert it into JSON using below code:

```<code>json.dumps(news_output)
</code>```

But I am getting a below error and I am unable to figure out how to write this nested dict into a json file. Any comments will be appreciated..!

```<code>  File "<ipython-input-138-78c27a14715b>", line 2, in <module>
    a = json.dumps(news_output)

  File "F:\Python\AnacondaFile\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)

  File "F:\Python\AnacondaFile\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)

  File "F:\Python\AnacondaFile\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)

  File "F:\Python\AnacondaFile\lib\json\encoder.py", line 180, in default
    o.__class__.__name__)

TypeError: Object of type 'Token' is not JSON serializable
</code>```

答:
Your error is : TypeError: Object of type 'Token' is not JSON serializable

Cause you forgot quotes in list like [as, it, mineral], if "as" is a object you can write it without quotes, but "it" and "mineral" seems like string, so you have to write [as, "it", "mineral"]

I try it like this, and it's work for me.

Body:
I created a nested dictionary in Python like this:

news_output = {'_id': 'd11bd6d0-846f-406d-a8e8-de57ee35fd53',
 'Link': ['https://www.marketingweek.com/2019/04/15/ad-blocking-retail-sales-ad-saturation-5-killer-stats-to-start-your-week/'],
 'Title': 'Why AI is the key to engaging today’s entitled consumer',
 'Entity': {'ORG': 'Coca-Cola', 'GPE': 'UK'},
 'Verbs': {0: {'Verb Text': 'is',
   'Text Head of the verb': 'ramping',
   'Child Word of the verb': []},
  1: {'Verb Text': 'ramping',
   'Text Head of the verb': 'ramping',
   'Child Word of the verb': [Cola, is, up, launches, brings, drink, .]},
  2: {'Verb Text': 'brings',
   'Text Head of the verb': 'ramping',
   'Child Word of the verb': [as, it, mineral]},
  'Verb Text': 'brings',
  'Text Head of the verb': 'ramping',
  'Child Word of the verb': [as, it, mineral]},
 'Dependent Words': {0: {'Text': 'Coca-Cola',
   'Root Text': 'Cola',
   'Dependent Text': 'ramping'},
  1: {'Text': 'new product launches',
   'Root Text': 'launches',
   'Dependent Text': 'ramping'},
  2: {'Text': 'it', 'Root Text': 'it', 'Dependent Text': 'brings'},
  3: {'Text': 'its mineral',
   'Root Text': 'mineral',
   'Dependent Text': 'brings'},
  4: {'Text': 'drink', 'Root Text': 'drink', 'Dependent Text': 'ramping'},
  5: {'Text': 'Aquarius', 'Root Text': 'Aquarius', 'Dependent Text': 'drink'},
  6: {'Text': 'the UK', 'Root Text': 'UK', 'Dependent Text': 'to'},
  'Text': 'the UK',
  'Root Text': 'UK',
  'Dependent Text': 'to'},
 'Signal': 'weak'}

I tried to convert it into JSON using below code:

json.dumps(news_output)

But I am getting a below error and I am unable to figure out how to write this nested dict into a json file. Any comments will be appreciated..!

  File "<ipython-input-138-78c27a14715b>", line 2, in <module>
    a = json.dumps(news_output)

  File "F:\Python\AnacondaFile\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)

  File "F:\Python\AnacondaFile\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)

  File "F:\Python\AnacondaFile\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)

  File "F:\Python\AnacondaFile\lib\json\encoder.py", line 180, in default
    o.__class__.__name__)

TypeError: Object of type 'Token' is not JSON serializable


问:
Kentico - Display content of localization resource strings through repeater transformation
I have a custom pagetype with 1 text field where I keep re-usable html content to be included on other pages through a repeater. The transformation for the repeater has just 1 line of code <%# Eval("Content") %>.

I'm running into a situation where I want to use a resource string inside the content box together with other html content, something like {$ site.languages $}. However, when viewing, the pages displays this string {$ site.languages $} instead of the value of the resource string. Is it possible to display the resource string content in this case and how?

答:
Try using</p>

```<code><%# Localize(Eval("Content")) %>
</code>```

Body:
Try using

<%# Localize(Eval("Content")) %>


问:
C++ pointers objects difference
Can somebody explain me the difference between the following?

Those two

float *pointer[10];

float *(pointer[10]);
```

<ol start="2">
<li>and those two</li>
</ol>

<pre class="lang-cpp prettyprint-override"><code>int(*pointer_function)();

int *pointer_function();
</code>```

答:
Always keep in mind the place of Parentheses.  Parentheses do not alter the type of the object, but they can alter the binding of complex declarators.

From above code snippet:

float *pointer[10];// Array of 10 pointer to float

float *(pointer[10]); //bracket around array of 10 pointer to float, So same as above

int(*pointer_function)(); // function pointer to achieve callbacks

int * pointer_function(); // function to integer pointer
```

Title: C++ pointers objects difference

Body:
Can somebody explain me the difference between the following?

Those two

float *pointer[10];

float *(pointer[10]);

and those two

int(*pointer_function)();

int *pointer_function();


问:
iteration over object of object
I have the following structure

```<code>[
  {
    "name": null
    "match": [{
                 "id": 0,
                 "location": ""

             "awayTeam": {
                     "id": 1568,
                     "teamName": "Manly United" },
                 "homeTeam": {
                     "id": 1523,
                     "teamName": "Sydney FC Youth" },
                     "matchDataProvider": [{
                            "id": 2953046,
                         "updatedDate": null }],
                 "matchPunditPrediction": [],
                 "matchResult": null,
                     "userMatchPrediction": []
               }]
   }
]
</code>```

I need to iterate over the match element and retrieve properties

答:
I had the same array structure.In normal java logic we know that,we can element value by iterating two times for loop.So I tried to do same .I tried to write ngFor to iterate first array but I got the error as Found [object] instead of [Object object].Well this is surely not our fault but angulars ngFor loop only work with a proper array structure,it throws error when you iterate such kind of array structure.

After So many research I found one hack,

In your component file just write below code.

```<code>hack(val) {
    return Array.from(val);
  }
</code>```

This will make array upon array. Magic is ,Angular finds this as proper array structure and it will not give error after.

Now when you write ngFor in html ,just write like this.

```<code>*ngFor="let variablename of hack(arrayObjectname)"
</code>```

after this, if you need to write ngFor again for inside array,you still can write now :).This hack might show error in your code platform but it will run fine in browser.

I hope this will help you to solve your issue :)

Title: iteration over object of object

Body:
I have the following structure

[
  {
    "name": null
    "match": [{
                 "id": 0,
                 "location": ""

             "awayTeam": {
                     "id": 1568,
                     "teamName": "Manly United" },
                 "homeTeam": {
                     "id": 1523,
                     "teamName": "Sydney FC Youth" },
                     "matchDataProvider": [{
                            "id": 2953046,
                         "updatedDate": null }],
                 "matchPunditPrediction": [],
                 "matchResult": null,
                     "userMatchPrediction": []
               }]
   }
]

I need to iterate over the match element and retrieve properties

Body:
I had the same array structure.In normal java logic we know that,we can element value by iterating two times for loop.So I tried to do same .I tried to write ngFor to iterate first array but I got the error as Found [object] instead of [Object object].Well this is surely not our fault but angulars ngFor loop only work with a proper array structure,it throws error when you iterate such kind of array structure.

After So many research I found one hack,

In your component file just write below code.

hack(val) {
    return Array.from(val);
  }

This will make array upon array. Magic is ,Angular finds this as proper array structure and it will not give error after.

Now when you write ngFor in html ,just write like this.

*ngFor="let variablename of hack(arrayObjectname)"

after this, if you need to write ngFor again for inside array,you still can write now :).This hack might show error in your code platform but it will run fine in browser.

I hope this will help you to solve your issue :)


问:
Why is `'\t\n ' == false` in JavaScript?
In JavaScript...

```<code>'\t\n ' == false // true
</code>```

I can assume that any string that consists solely of whitespace characters is considered equal to false in JavaScript.

According to this article, I figured that false would be converted to 0, but was unable to find mention of whitespace considered equal to false using Google.

Why is this? Is there some good reading on the subject besides digging into the ECMAScript spec?

答:
Here is how I think it works, based on my readings and Raynos' answer (as well as the other latecomers to the party).

```<code>// Original expression
lg('\t\n ' == false);
// Boolean false is converted to Number
lg('\t\n ' == new Number(false));
// Boolean has been converted to 0
lg('\t\n ' == 0);
// Because right hand operand is 0, convert left hand to Number
lg(new Number('\t\n ') == 0);
// Number of whitespace is 0, and 0 == 0
lg(0 == 0);
</code>```

jsFiddle.

Please let me know if I have something wrong.

ContentLicense: CC BY-SA 3.0

Body:
In JavaScript...

'\t\n ' == false // true

I can assume that any string that consists solely of whitespace characters is considered equal to false in JavaScript.

According to this article, I figured that false would be converted to 0, but was unable to find mention of whitespace considered equal to false using Google.

Why is this? Is there some good reading on the subject besides digging into the ECMAScript spec?

Body:
Here is how I think it works, based on my readings and Raynos' answer (as well as the other latecomers to the party).

// Original expression
lg('\t\n ' == false);
// Boolean false is converted to Number
lg('\t\n ' == new Number(false));
// Boolean has been converted to 0
lg('\t\n ' == 0);
// Because right hand operand is 0, convert left hand to Number
lg(new Number('\t\n ') == 0);
// Number of whitespace is 0, and 0 == 0
lg(0 == 0);

jsFiddle.

Please let me know if I have something wrong.


问:
How to set content type for WebFluxRequestExecutingMessageHandler
I am trying to make an HTTP POST request to an external service using WebFluxRequestExecutingMessageHandler, and I am having a lot of trouble getting the Content-Type header set for the outbound request. By default it sets the Content-Type to x-java-serialized-object, but the service I'm hitting only accepts application/json. The only way around this I have found so far is to pass in a custom HeaderMapper:

```<code>webFluxRequestExecutingMessageHandler.setHeaderMapper(object : HeaderMapper<HttpHeaders> {
        override fun toHeaders(source: HttpHeaders): MutableMap<String, Any> {
            return mutableMapOf()
        }

        override fun fromHeaders(headers: MessageHeaders, target: HttpHeaders) {
            target.contentType = MediaType.APPLICATION_JSON
        }

    })
</code>```

Is there a better way to accomplish this?

Thanks.

答:
The DefaultHttpHeaderMapper.outboundMapper() has an ability to map a:

```<code>case "contenttype": // Lower case for MessageHeaders.CONTENT_TYPE
            setContentType(target, value);
</code>```

to the Content-Type HTTP header. So, you can try to set that MessageHeaders.CONTENT_TYPE message header upstream before sending the message to this WebFluxRequestExecutingMessageHandler.

That x-java-serialized-object is not a standard MimeType, so I guess you have a configuration like WebFluxRequestExecutingMessageHandler.setExtractPayload(false), which means try to send the whole Message<?> over HTTP. Not sure if that is what you want to achieve because the Message<?> is not fully JSON compatible...

Body:
I am trying to make an HTTP POST request to an external service using WebFluxRequestExecutingMessageHandler, and I am having a lot of trouble getting the Content-Type header set for the outbound request. By default it sets the Content-Type to x-java-serialized-object, but the service I'm hitting only accepts application/json. The only way around this I have found so far is to pass in a custom HeaderMapper:

webFluxRequestExecutingMessageHandler.setHeaderMapper(object : HeaderMapper<HttpHeaders> {
        override fun toHeaders(source: HttpHeaders): MutableMap<String, Any> {
            return mutableMapOf()
        }

        override fun fromHeaders(headers: MessageHeaders, target: HttpHeaders) {
            target.contentType = MediaType.APPLICATION_JSON
        }

    })

Is there a better way to accomplish this?

Thanks.

Body:
The DefaultHttpHeaderMapper.outboundMapper() has an ability to map a:

case "contenttype": // Lower case for MessageHeaders.CONTENT_TYPE
            setContentType(target, value);

to the Content-Type HTTP header. So, you can try to set that MessageHeaders.CONTENT_TYPE message header upstream before sending the message to this WebFluxRequestExecutingMessageHandler.

That x-java-serialized-object is not a standard MimeType, so I guess you have a configuration like WebFluxRequestExecutingMessageHandler.setExtractPayload(false), which means try to send the whole Message<?> over HTTP. Not sure if that is what you want to achieve because the Message<?> is not fully JSON compatible...


问:
Importing JS from one site to another
I created a script that asks you about the difficulty that you want of the game (and a cheat. I realize this isn't a secure way to add a cheat, but that's not the point). I want to save it on another section of my site, and have done so with the import method. I cannot get it to work. How would I export the function getDiff from http://www.willmargulies.com/password.htm and run it?

import{getDiff} from 'http://www.willmargulies.com/password.htm'
getDiff();
```

答: You can also achieve it by exports.getDiff = () => {};

Title: Importing JS from one site to another


问:
How to concatenate several logical operators like 'a and not (b or c or d)'
How do I write this correctly: </p>

```<code>for root, dirs, files in os.walk(SEARCHDIR):
    files = [f for f in files if not f[0] == '.' and not ("BLACKBOX" or ".RTN" or ".log") in f]
</code>```

<p>I want to achieve my file list to contain all files instead of hidden files or files conaining one of the strings "BLACKBOX" or ".RTN" or ".log".
Anyway only the first expression is evaluated ("BLACKBOX") the others are ignored.  </p>

答:
You can combine both the not commands to one as

```<code>for root, dirs, files in os.walk(SEARCHDIR):
    files = [f for f in files if not (f[0] == '.' and any(i in f for i in ["BLACKBOX", ".RTN", ".log"]))]
</code>```

Body:
How do I write this correctly:

for root, dirs, files in os.walk(SEARCHDIR):
    files = [f for f in files if not f[0] == '.' and not ("BLACKBOX" or ".RTN" or ".log") in f]

I want to achieve my file list to contain all files instead of hidden files or files conaining one of the strings "BLACKBOX" or ".RTN" or ".log".
Anyway only the first expression is evaluated ("BLACKBOX") the others are ignored.

Body:
You can combine both the not commands to one as

for root, dirs, files in os.walk(SEARCHDIR):
    files = [f for f in files if not (f[0] == '.' and any(i in f for i in ["BLACKBOX", ".RTN", ".log"]))]


问:
how to inline a minBy result
I have the following scala code:

```<code>val test = rows.groupBy(l => l(8))
val m = test.reduce((a, b) => if (a._2.size > b._2.size) a else b)
val mina = m._2.minBy(x => x(0));
val minv = mina(0);
</code>```

I would like to write

```<code>val minv = m._2.minBy(x => x(0))(0);
</code>```

but I get a compiler error

```<code>[error] D:\dev\local\spark\httpLogs\src\main\scala\Main.scala:35:38: type mismatch;
[error]  found   : Int(0)
[error]  required: Ordering[String]
[error]                                 val minv = m._2.minBy(x => x(0))(0);
[error]                                                                  ^
</code>```

I also try

```<code>val minv = (m._2.minBy(x => x(0)))(0);
</code>```

but just get another error.

Can this be written in one line ?

答:
Scala implicit parameters are neat, but if you don't know about them, they're confusing.

```<code>val mina = m._2.minBy(x => x(0))
</code>```

is actually (resolved by implicit resolution)

```<code>val mina = m._2.minBy(x => x(0))(Ordering.String)
</code>```

So when you're calling

```<code>val minv = m._2.minBy(x => x(0))(0)
</code>```

You're actually passing the 0 as an explicit argument to the implicit.

By assigning the result to a variable, you're letting the compiler insert the implicit argument. If you're calling it directly, curried function arguments (the implicit is a curried argument after the explicit function) and syntax sugar for apply collide. And the compiler picks curried function arguments.

If you've got an object with an apply method on it, e.g. List:

```<code>val list = List(1, 2, 3)
</code>```

it'll rewrite that to List.apply(1, 2, 3). That's why apply works in the above example, because it's telling the compiler to explicitly use the apply, instead of relying on the syntax sugar which gets overridden by the curried function.

More on implicits: Understanding implicit in Scala

Title: how to inline a minBy result

Body:
I have the following scala code:

val test = rows.groupBy(l => l(8))
val m = test.reduce((a, b) => if (a._2.size > b._2.size) a else b)
val mina = m._2.minBy(x => x(0));
val minv = mina(0);

I would like to write

val minv = m._2.minBy(x => x(0))(0);

but I get a compiler error

[error] D:\dev\local\spark\httpLogs\src\main\scala\Main.scala:35:38: type mismatch;
[error]  found   : Int(0)
[error]  required: Ordering[String]
[error]                                 val minv = m._2.minBy(x => x(0))(0);
[error]                                                                  ^

I also try

val minv = (m._2.minBy(x => x(0)))(0);

but just get another error.

Can this be written in one line ?

Body:
Scala implicit parameters are neat, but if you don't know about them, they're confusing.

val mina = m._2.minBy(x => x(0))

is actually (resolved by implicit resolution)

val mina = m._2.minBy(x => x(0))(Ordering.String)

So when you're calling

val minv = m._2.minBy(x => x(0))(0)

You're actually passing the 0 as an explicit argument to the implicit.

By assigning the result to a variable, you're letting the compiler insert the implicit argument. If you're calling it directly, curried function arguments (the implicit is a curried argument after the explicit function) and syntax sugar for apply collide. And the compiler picks curried function arguments.

If you've got an object with an apply method on it, e.g. List:

val list = List(1, 2, 3)

it'll rewrite that to List.apply(1, 2, 3). That's why apply works in the above example, because it's telling the compiler to explicitly use the apply, instead of relying on the syntax sugar which gets overridden by the curried function.

More on implicits: Understanding implicit in Scala


问:
Regression model/ non-linear regression
The dataset has a timestamp and the water flow values, Now I want to model the data such that if any abnormal value(sudden spike or very low value) comes in it should send a notification that something is wrong. I have tried the ARIMA model to train the data since it was time series but it doesnt produce relevant results which means I am doing something wrong. So please guide me. Thanks. The link to the dataset is: https://drive.google.com/open?id=1cFHSVpY0XBxsEayl2k1cK4_qWZ4PvDBd

```<code>from sklearn.linear_model import LinearRegression
features = [col for col in x2.columns if 'day' in col]
X = x2['median'].reshape(-1,1)
y = x2['time']
# create linear regression object
reg = linear_model.LinearRegression()
# train the model using the training sets
reg.fit(X, y)
# regression coefficients
print('Coefficients: \n', reg.coef_)
</code>```

I have tried using the median of all the water flow value for each time interval as the target variable but it produces negative variance score as well.

The expected result should be a value of water flow at the given time which tells if it is in a normal range or not.

答: Since this problem seems to be a single feature problem, I recommend starting with plotting median water flow with respect to time. The shape of the plot will tell you how best to model the problem. </p>

Title: Regression model/ non-linear regression

Body:
The dataset has a timestamp and the water flow values, Now I want to model the data such that if any abnormal value(sudden spike or very low value) comes in it should send a notification that something is wrong. I have tried the ARIMA model to train the data since it was time series but it doesnt produce relevant results which means I am doing something wrong. So please guide me. Thanks. The link to the dataset is: https://drive.google.com/open?id=1cFHSVpY0XBxsEayl2k1cK4_qWZ4PvDBd

from sklearn.linear_model import LinearRegression
features = [col for col in x2.columns if 'day' in col]
X = x2['median'].reshape(-1,1)
y = x2['time']
# create linear regression object
reg = linear_model.LinearRegression()
# train the model using the training sets
reg.fit(X, y)
# regression coefficients
print('Coefficients: \n', reg.coef_)

I have tried using the median of all the water flow value for each time interval as the target variable but it produces negative variance score as well.

The expected result should be a value of water flow at the given time which tells if it is in a normal range or not.


问:
Unable to run nohup command from jenkins as a background process
UPDATE: Based on below discussion I have edited my answer for more accurate description.

I am trying to run a nohup command from jenkins. The full command is

```<code>nohup java -jar /home/.../jar/server-process-0.35.jar prod >> /var/../server-process-prod.log 2>&1 &
</code>```

This command does not work. I can see status as success in jenkins but no java process in linux. When I do 'ps -ef | grep java'

However when I remove the last '&' , that is I change it from run in forground instead of background

It starts working. I can see the java process started.

The original command works fine If I run it on linux console.

I need to run it from jenkins in the original form that is as a backgorund process. So that it is independant of jenkins.

Any clues why is this happening?

答:
In your jenkins shell script try:

```<code>  export BUILD_ID=dontKillMe
  nohup java -jar your_java_app.jar &
</code>```

It worked for me!

Body:
UPDATE: Based on below discussion I have edited my answer for more accurate description.

I am trying to run a nohup command from jenkins. The full command is

nohup java -jar /home/.../jar/server-process-0.35.jar prod >> /var/../server-process-prod.log 2>&1 &

This command does not work. I can see status as success in jenkins but no java process in linux. When I do 'ps -ef | grep java'

However when I remove the last '&' , that is I change it from run in forground instead of background

It starts working. I can see the java process started.

The original command works fine If I run it on linux console.

I need to run it from jenkins in the original form that is as a backgorund process. So that it is independant of jenkins.

Any clues why is this happening?

Body:
In your jenkins shell script try:

  export BUILD_ID=dontKillMe
  nohup java -jar your_java_app.jar &

It worked for me!


问:
ISPConfig serving wrong site
My website loading from another folder, when I pointed my domain to the ip. I have already added the domain in ISP, and the new folder created with default content, but Apache serving another of my site.</p>

答:
I think you left blank the ipv4 address field in the site settings (or maybe it's wrong). Just select the ip of the host, and retry.

If your site loads with http, but not with https, that means your website  is not reachable with SSL (so check that SSL is enabled).

When the webserver receives a request, it will look through the list of sites configured to run on said IP. If it does not find a site matching the domain requested, it will serve the alphanumerical first site it finds, so that why wrong site loaded.

Title: ISPConfig serving wrong site


问:
Encapsulating constants with dynamic values in a class?
I need to assign functions to constants so this won't work:

```<code>class Config
{
    const foo = strtoupper('bar');
}
</code>```

Since I need to encapsulate the constant in a class, the alternative define('foo', strtoupper('bar')); won't do.

Is my only option is to use public variables? E.g.,

```<code>class Config
{
    public $foo;

    public function __construct()
    {
        $this->foo = strtoupper('bar');
    }

}
</code>```

答:
There is no way in PHP to define class constants dynamically but you can use static methods to achieve the same result:</p>

```<code>class Config
{
    public static function FOO()
    {
        return strtoupper('bar');
    }

}

// Usage:
$value = Config::FOO()
</code>```

Body:
I need to assign functions to constants so this won't work:

class Config
{
    const foo = strtoupper('bar');
}

Since I need to encapsulate the constant in a class, the alternative define('foo', strtoupper('bar')); won't do.

Is my only option is to use public variables? E.g.,

class Config
{
    public $foo;

    public function __construct()
    {
        $this->foo = strtoupper('bar');
    }

}

Body:
There is no way in PHP to define class constants dynamically but you can use static methods to achieve the same result:

class Config
{
    public static function FOO()
    {
        return strtoupper('bar');
    }

}

// Usage:
$value = Config::FOO()


问:
Append values to one dataframe based on their frequency in another dataframe
I have two dataframes, df1 is the product of a groupby, or df.groupby('keyword'):

```<code>df1

keyword     string

   A        "This is a test string for the example"
            "This is also a test string based on the other string"
            "This string is a test string based on the other strings"
   B        "You can probably guess that this is also a test string"
            "Yet again, another test string"
            "This is also a test"
</code>```

and df2

which is an empty dataframe, now I also I have a list of specific values:

```<code>keyword_list = ['string', 'test']
</code>```

Basically I would like to count the frequency of each word that is in keyword_list and within df1 and the word that appears the most append that word to a a specific column in the new dataframe based on the keyword in df1, so df2's 'A' gets assigned the highest occurring value in df1's string column.

So ideally, since 'string' is the highest occuring value in df1's A keyword column it gets assigned string and so on.

```<code>df2

keyword    High_freq_word

   A         "string"
   B         "test"
</code>```

Let me know if you need some clarification or it makes sense!

UPDATE:

@anky_91 provided some awesome code however the output is a little awkward

```<code>df['matches'] = df.description.str.findall('|'.join(keyword_list))

    df.groupby(odf.Type.ffill()).matches.apply(lambda x: ''.join(mode(list(chain.from_iterable(x)))[0]))
</code>```

gets you

df1

```<code>keyword     string

   A        "This is a test string for the example"
            "This is also a test string based on the other string"
            "This string is a test string based on the other strings"
   B        "You can probably guess that this is also a test string"
            "Yet again, another test string"
            "This is also a test"
</code>```

However it adds a new column:

```<code>matches

['string','test']
['test', 'string','string]
[etc...]
</code>```

I can figure out a way to convert it numerically and then assign that value to the column, but the bigger issue is appending this new column to the the new dataframe.

Since it is a groupby there are several duplicate values, I'm trying to find a pythonic way of mapping the "most frequent word" to just the keyword itself instead of the entire mode based on the list of key words.

答:
From what I understand, you can do something like:

```<code>from itertools import chain
from scipy.stats import mode
</code>```

```<code>keyword_list = ['string', 'test']
df['matches']=df.string.str.findall('|'.join(keyword_list)) #find all matches
df.groupby(df.keyword.ffill()).matches.apply(lambda x: ''.join(mode(list(chain.from_iterable(x)))[0]))
</code>```

```<code>keyword
A    string
B      test
Name: matches, dtype: object
</code>```

Body:
I have two dataframes, df1 is the product of a groupby, or df.groupby('keyword'):

df1

keyword     string

   A        "This is a test string for the example"
            "This is also a test string based on the other string"
            "This string is a test string based on the other strings"
   B        "You can probably guess that this is also a test string"
            "Yet again, another test string"
            "This is also a test"

and df2

which is an empty dataframe, now I also I have a list of specific values:

keyword_list = ['string', 'test']

Basically I would like to count the frequency of each word that is in keyword_list and within df1 and the word that appears the most append that word to a a specific column in the new dataframe based on the keyword in df1, so df2's 'A' gets assigned the highest occurring value in df1's string column.

So ideally, since 'string' is the highest occuring value in df1's A keyword column it gets assigned string and so on.

df2

keyword    High_freq_word

   A         "string"
   B         "test"

Let me know if you need some clarification or it makes sense!

UPDATE:

@anky_91 provided some awesome code however the output is a little awkward

df['matches'] = df.description.str.findall('|'.join(keyword_list))

    df.groupby(odf.Type.ffill()).matches.apply(lambda x: ''.join(mode(list(chain.from_iterable(x)))[0]))

gets you

df1

keyword     string

   A        "This is a test string for the example"
            "This is also a test string based on the other string"
            "This string is a test string based on the other strings"
   B        "You can probably guess that this is also a test string"
            "Yet again, another test string"
            "This is also a test"

However it adds a new column:

matches

['string','test']
['test', 'string','string]
[etc...]

I can figure out a way to convert it numerically and then assign that value to the column, but the bigger issue is appending this new column to the the new dataframe.

Since it is a groupby there are several duplicate values, I'm trying to find a pythonic way of mapping the "most frequent word" to just the keyword itself instead of the entire mode based on the list of key words.

Body:
From what I understand, you can do something like:

from itertools import chain
from scipy.stats import mode

keyword_list = ['string', 'test']
df['matches']=df.string.str.findall('|'.join(keyword_list)) #find all matches
df.groupby(df.keyword.ffill()).matches.apply(lambda x: ''.join(mode(list(chain.from_iterable(x)))[0]))

keyword
A    string
B      test
Name: matches, dtype: object


问:
How to remove a single letter/number
I have single letters and numbers in a variable that I would like to remove

example inputs:

```<code>USA-2019-1-aoiwer
USA-A-jowerasf
BB-a_owierlasdf-2019
flsfwer_5_2015-asfdlwer
</code>```

desired outputs:

```<code>USA-2019--aoiwer
USA--jowerasf
BB-_owierlasdf-2019
flsfwer__2015-asfdlwer
</code>```

my code:

```<code>bind pub "-|-" !aa proc:aa
proc proc:aa { nick host handle channel arg } {

    set line [lindex $arg 0]

    set line [string map {[a-z] """} $line]
    set line [string map {[0-9] """} $line]

    putnow "PRIVMSG $channel :$line"
}
</code>```

Unfortunately that does not work and i have no other idea

Regards

答:
string map would remove all the lowercase letters and numbers, if it worked. However, you also have unbalanced quotes, which causes a syntax error when the proc is resolving.

I would recommend using regsub. The hard part, however, would be to get a proper expression to do the task. I will suggest the following:

```<code>bind pub "-|-" !aa proc:aa

proc proc:aa { nick host handle channel arg } {
    set line [lindex $arg 0]
    regsub -nocase -all {([^a-z0-9]|\y)[a-z0-9]([^a-z0-9]|\y)} $line {\1\2} line
    putnow "PRIVMSG $channel :$line"
}
</code>```

Basically ([^a-z0-9]|\y) matches a character that is non alphanumeric, or a word boundary (which will match at the beginning of a sentence for example if it can, or at the end of a sentence), and stores it (this is the purpose of the parens).

The matched groups are stored in order starting with 1, so in the replace portion of regsub, I'm placing the parts that shouldn't be replaced back where they were.

The above should work fine.

You could technically go a little fancier with a slightly different expression:

```<code>regsub -nocase -all {([^a-z0-9]|\y)[a-z0-9](?![a-z0-9])} $line {\1} line
</code>```

Which uses a negative lookahead ((?! ... )).

Anyway, if you do want to get more in depth, I recommend reading the manual on regular expression syntax

Title: How to remove a single letter/number

Body:
I have single letters and numbers in a variable that I would like to remove

example inputs:

USA-2019-1-aoiwer
USA-A-jowerasf
BB-a_owierlasdf-2019
flsfwer_5_2015-asfdlwer

desired outputs:

USA-2019--aoiwer
USA--jowerasf
BB-_owierlasdf-2019
flsfwer__2015-asfdlwer

my code:

bind pub "-|-" !aa proc:aa
proc proc:aa { nick host handle channel arg } {

    set line [lindex $arg 0]

    set line [string map {[a-z] """} $line]
    set line [string map {[0-9] """} $line]

    putnow "PRIVMSG $channel :$line"
}

Unfortunately that does not work and i have no other idea

Regards

Body:
string map would remove all the lowercase letters and numbers, if it worked. However, you also have unbalanced quotes, which causes a syntax error when the proc is resolving.

I would recommend using regsub. The hard part, however, would be to get a proper expression to do the task. I will suggest the following:

bind pub "-|-" !aa proc:aa

proc proc:aa { nick host handle channel arg } {
    set line [lindex $arg 0]
    regsub -nocase -all {([^a-z0-9]|\y)[a-z0-9]([^a-z0-9]|\y)} $line {\1\2} line
    putnow "PRIVMSG $channel :$line"
}

Basically ([^a-z0-9]|\y) matches a character that is non alphanumeric, or a word boundary (which will match at the beginning of a sentence for example if it can, or at the end of a sentence), and stores it (this is the purpose of the parens).

The matched groups are stored in order starting with 1, so in the replace portion of regsub, I'm placing the parts that shouldn't be replaced back where they were.

The above should work fine.

You could technically go a little fancier with a slightly different expression:

regsub -nocase -all {([^a-z0-9]|\y)[a-z0-9](?![a-z0-9])} $line {\1} line

Which uses a negative lookahead ((?! ... )).

Anyway, if you do want to get more in depth, I recommend reading the manual on regular expression syntax


问:
Every time I change the constant, the result is different
I want to code the 01 Knapsack problem with c++. Each time I change the value of a constant MAX to a different value, such as 100,90, or 80, the result is different. What's the cause? I'm using Visual Studio 2019.

The input is a text file, for example.

20

40 35 18 4 10 2 70 20 39 37 7 5 10 8 15 21 50 40 10 30

100 50 45 20 10 5 31 10 20 19 4 3 6 8 12 7 10 2 5 5

137

The first row is the number of objects, the second row is the price, the third row is the weight, and the last row is the size of the knapsack.

```<code>#include <stdio.h>
#include <time.h>
#define MAX 100
#define CLOCKS_PER_MS CLOCKS_PER_SEC/1000

int X_d[MAX] = { 0 }; //solution vector

int max(int a, int b) {
if (a >= b)
    return a;
else
    return b;
}

void dynamic(int n, int M, int p[], int w[]) {
int result;
int i, y, k;
int P[MAX][MAX] = { 0 };
clock_t start, finish;

start = clock();
for (i = 0; i <= n; i++) {
    for (y = 0; y <= M; y++) {
        if (i == 0 || y == 0)
            P[i][y] = 0;
        else if (w[i - 1] > y)
            P[i][y] = P[i - 1][y];
        else
            P[i][y] = max(P[i - 1][y], p[i - 1] + P[i - 1][y - w[i - 1]]);
    }
}
finish = clock();
result = P[n][M];
y = M;
for (i = n; i > 0 && result > 0; i--) {
    if (result == P[i - 1][y]) {
        continue;
    }
    else {
        X_d[i - 1] = 1;
        result = result - p[i - 1];
        y = y - w[i - 1];
    }
}

printf("\n(1) Dynamic Programming");
printf("\nThe maximum profit is $%d", P[n][M]);
printf("\nThe solution vetor X = ( ");
for (k = 0; k < n; k++)
    printf("%d ", X_d[k]);
printf(")\n");
printf("The execution time is %f milliseconds.\n", (float)(finish - start) / CLOCKS_PER_MS);
}

int main() {
int i, j;
int num, M;
int p[MAX] = { 0 }, w[MAX] = { 0 };
FILE* fp = NULL;

fopen_s(&fp, "p2data6.txt", "r");
fscanf_s(fp, "%d", &num);

for (i = 0; i < num; i++)
    fscanf_s(fp, "%d", &p[i]);

for (i = 0; i < num; i++)
    fscanf_s(fp, "%d", &w[i]);

fscanf_s(fp, "%d", &M);

printf("n = %d\n", num);
printf("pi = ");
for (i = 0; i < num; i++)
    printf("%3d ", p[i]);
printf("\nwi = ");
for (i = 0; i < num; i++)
    printf("%3d ", w[i]);
printf("\npi/wi = ");
for (i = 0; i < num; i++)
    printf("%f ", (double)p[i] / w[i]);
printf("\nM = %d\n", M);

dynamic(num, M, p, w);

return 0;
}
</code>```

答:
Geeks for Geeks has a very good explanation of this problem here:

To quote the Geeks for Geeks article by Sam007:

A simple solution is to consider all subsets of items and calculate the total weight and value of all subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets, pick the maximum value subset.

1) Optimal Substructure:
  To consider all subsets of items, there can be two cases for every item: (1) the item is included in the optimal subset, (2) not included in the optimal set.
  Therefore, the maximum value that can be obtained from n items is max of following two values.
  1) Maximum value obtained by n-1 items and W weight (excluding nth item).
  2) Value of nth item plus maximum value obtained by n-1 items and W minus weight of the nth item (including nth item).

If weight of nth item is greater than W, then the nth item cannot be included and case 1> is the only possibility.

2) Overlapping Subproblems
  Following is recursive implementation that simply follows the recursive structure mentioned above.

Body:
I want to code the 01 Knapsack problem with c++. Each time I change the value of a constant MAX to a different value, such as 100,90, or 80, the result is different. What's the cause? I'm using Visual Studio 2019.

The input is a text file, for example.

20

40 35 18 4 10 2 70 20 39 37 7 5 10 8 15 21 50 40 10 30

100 50 45 20 10 5 31 10 20 19 4 3 6 8 12 7 10 2 5 5

137

The first row is the number of objects, the second row is the price, the third row is the weight, and the last row is the size of the knapsack.

#include <stdio.h>
#include <time.h>
#define MAX 100
#define CLOCKS_PER_MS CLOCKS_PER_SEC/1000

int X_d[MAX] = { 0 }; //solution vector

int max(int a, int b) {
if (a >= b)
    return a;
else
    return b;
}

void dynamic(int n, int M, int p[], int w[]) {
int result;
int i, y, k;
int P[MAX][MAX] = { 0 };
clock_t start, finish;

start = clock();
for (i = 0; i <= n; i++) {
    for (y = 0; y <= M; y++) {
        if (i == 0 || y == 0)
            P[i][y] = 0;
        else if (w[i - 1] > y)
            P[i][y] = P[i - 1][y];
        else
            P[i][y] = max(P[i - 1][y], p[i - 1] + P[i - 1][y - w[i - 1]]);
    }
}
finish = clock();
result = P[n][M];
y = M;
for (i = n; i > 0 && result > 0; i--) {
    if (result == P[i - 1][y]) {
        continue;
    }
    else {
        X_d[i - 1] = 1;
        result = result - p[i - 1];
        y = y - w[i - 1];
    }
}

printf("\n(1) Dynamic Programming");
printf("\nThe maximum profit is $%d", P[n][M]);
printf("\nThe solution vetor X = ( ");
for (k = 0; k < n; k++)
    printf("%d ", X_d[k]);
printf(")\n");
printf("The execution time is %f milliseconds.\n", (float)(finish - start) / CLOCKS_PER_MS);
}

int main() {
int i, j;
int num, M;
int p[MAX] = { 0 }, w[MAX] = { 0 };
FILE* fp = NULL;

fopen_s(&fp, "p2data6.txt", "r");
fscanf_s(fp, "%d", &num);

for (i = 0; i < num; i++)
    fscanf_s(fp, "%d", &p[i]);

for (i = 0; i < num; i++)
    fscanf_s(fp, "%d", &w[i]);

fscanf_s(fp, "%d", &M);

printf("n = %d\n", num);
printf("pi = ");
for (i = 0; i < num; i++)
    printf("%3d ", p[i]);
printf("\nwi = ");
for (i = 0; i < num; i++)
    printf("%3d ", w[i]);
printf("\npi/wi = ");
for (i = 0; i < num; i++)
    printf("%f ", (double)p[i] / w[i]);
printf("\nM = %d\n", M);

dynamic(num, M, p, w);

return 0;
}


问:
Interface A incorrectly extends interface B
Given this interface:

```<code>interface Props extends React.HTMLAttributes<HTMLDivElement> {
  compLevel: string;
  property: Property;
  comps: Property[];
}
</code>```

I'm having difficulties with the property attribute given that it already exists on HTMLAttributes as property?: string;:

Interface 'Props' incorrectly extends interface
  'HTMLAttributes'.   Types of property 'property' are
  incompatible.
      Type 'SerializedObject' is not assignable to type 'string'.

Renaming the attribute works though I'd rather not do that.What is a recommended interface to extend/approach to use so that I don't need to redefine className on my Props?

答:
Since the attribute of 'property' already exists on HTMLAttribute, I can see three ways to move forward:

Rename the property to another more precise term that does not overlap with the already existing attribute (e.g. propsProperty)

If the values are somehow similar, the property could be transformed into a SerializedObject to match the type signature

Rename the property to _property, and set the getter and setter of the interface to alter from _property instead of property. (Haven't tested this one yet)

Body:
Given this interface:

interface Props extends React.HTMLAttributes<HTMLDivElement> {
  compLevel: string;
  property: Property;
  comps: Property[];
}

I'm having difficulties with the property attribute given that it already exists on HTMLAttributes as property?: string;:

Interface 'Props' incorrectly extends interface
  'HTMLAttributes'.   Types of property 'property' are
  incompatible.
      Type 'SerializedObject' is not assignable to type 'string'.

Renaming the attribute works though I'd rather not do that.What is a recommended interface to extend/approach to use so that I don't need to redefine className on my Props?


问:
speed up mysql query with multiple subqueries
I'm wondering if there's a way to speed up a mysql query which is ordered by multiple subqueries.

On a music related site users can like different things like artists, songs, albums etc. These "likes" are all stored in the same table. Now I want to show a list of artists ordered by the number of "likes" by the users friends and all users. I want to show all artists, also those who have no likes at all.

I have the following query:

```<code>SELECT `artists`.*,

    // friend likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     AND user_id IN (1,2,3,4, etc) // ids of friends
     GROUP BY like_id
    ) AS `friend_likes`,

    // all likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     GROUP BY like_id
    ) AS `all_likes`

FROM artists
ORDER BY
    friend_likes DESC,
    all_likes DESC,
    artists.name ASC
</code>```

The query takes ± 1.5 seconds on an artist table with 2000 rows. I'm afraid that this takes longer and longer as the table gets bigger and bigger. I tried using JOINS by can't seem to get this working because the subqueries contain WHERE statements.

Any ideas in the right direction would be greatly appreciated!

答: You need to break this down a bit to see where the time goes. You're absolutely right that 1.5 sec on 2000 rows won't scale well. I suspect you need to look at indexes and foreign-key relationships. Look at each count/group-by query individually to get them tuned as best you can then recombine.</p>

Body:
I'm wondering if there's a way to speed up a mysql query which is ordered by multiple subqueries.

On a music related site users can like different things like artists, songs, albums etc. These "likes" are all stored in the same table. Now I want to show a list of artists ordered by the number of "likes" by the users friends and all users. I want to show all artists, also those who have no likes at all.

I have the following query:

SELECT `artists`.*,

    // friend likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     AND user_id IN (1,2,3,4, etc) // ids of friends
     GROUP BY like_id
    ) AS `friend_likes`,

    // all likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     GROUP BY like_id
    ) AS `all_likes`

FROM artists
ORDER BY
    friend_likes DESC,
    all_likes DESC,
    artists.name ASC

The query takes ± 1.5 seconds on an artist table with 2000 rows. I'm afraid that this takes longer and longer as the table gets bigger and bigger. I tried using JOINS by can't seem to get this working because the subqueries contain WHERE statements.

Any ideas in the right direction would be greatly appreciated!


问:
How to scale in paper js
I am trying to write a condition inside the view.onFrame (paper js) which is update function in normal canvas.

//Declaring

```<code>let number = 74;
let minus = true;

 view.onFrame = function(event) {
</code>```

//Start conditioning
// if number become 75 and minus is true Number will start decreasing

```<code>if(number <= 75 && minus == true){
         number -= 1;
         minus = true;
      }
</code>```

//if number reach 0 number will increase up to 75 and the condition become false

```<code> else if(number == 0){
     number += 1;
     minus = false;
  }
</code>```

//else the minus become true again

```<code>else {
minus = true;
}
</code>```

The problem is that the condition never become true

答:
This is a problem with the structuring of your logic. You want to start at 75 and decrement to 0, then back up to 75, but let's look at your logic.

```<code>if(number <= 75 && minus == true){
  number -= 1;
  minus = true;
}
else if (number == 0) {
  number += 1;
  minus = false;
}
</code>```

The first condition, number <= 75 is true even when number == 0 (0 is less than or equal to 75 after all), so it will always begin to execute the first if statement and never get to the else if statement. On top of that, you are only executing number += 1 when number is EXACTLY (==) 0. So even if you did clear up your logic, the output of that code would look like 75, 74, 73... 3, 2, 1, 0, 1, 0, 1, 0, 1 ...

What you want instead is to check whether you exit the bounds that you've set, and if you have, change whether you're incrementing or decrementing:

```<code>if (number > 75) { minus = true }
if (number < 1)  { minus = false }

if (minus) { number -= 1 } else { number += 1 }
</code>```

Title: How to scale in paper js

Body:
I am trying to write a condition inside the view.onFrame (paper js) which is update function in normal canvas.

//Declaring

let number = 74;
let minus = true;

 view.onFrame = function(event) {

//Start conditioning
// if number become 75 and minus is true Number will start decreasing

if(number <= 75 && minus == true){
         number -= 1;
         minus = true;
      }

//if number reach 0 number will increase up to 75 and the condition become false

 else if(number == 0){
     number += 1;
     minus = false;
  }

//else the minus become true again

else {
minus = true;
}

The problem is that the condition never become true

Body:
This is a problem with the structuring of your logic. You want to start at 75 and decrement to 0, then back up to 75, but let's look at your logic.

if(number <= 75 && minus == true){
  number -= 1;
  minus = true;
}
else if (number == 0) {
  number += 1;
  minus = false;
}

The first condition, number <= 75 is true even when number == 0 (0 is less than or equal to 75 after all), so it will always begin to execute the first if statement and never get to the else if statement. On top of that, you are only executing number += 1 when number is EXACTLY (==) 0. So even if you did clear up your logic, the output of that code would look like 75, 74, 73... 3, 2, 1, 0, 1, 0, 1, 0, 1 ...

What you want instead is to check whether you exit the bounds that you've set, and if you have, change whether you're incrementing or decrementing:

if (number > 75) { minus = true }
if (number < 1)  { minus = false }

if (minus) { number -= 1 } else { number += 1 }


问:
How to connect all distant points on a plot which follow a condition?
I am plotting my workout weights against "Date Weekday". I want to connect all the points which match the condition:

weights = ([1471.5, 4026. , 2399.5, 5462. ,    0. , 2758.1, 6229. , 5132. ])
dates = ['16 Thu', '20 Mon', '21 Tue', '22 Wed', '23 Thu', '24 Fri','25 Sat','27 Mon']
any(x in dates[i] for x in ["Mon","Thu"])
```

<p>I saw this question  Plotting lines connecting points But this addresses every two points but my problem is that I might skip some days. I want the code to be robust.</p>

<p>I was using this for the above "dates" and "weights":</p>

```plt.pyplot.plot(dates,weights,'ro-')
plt.pyplot.xticks(dates)
plt.pyplot.grid(b=True, which='major', color='#666666', linestyle='-')
plt.pyplot.yticks(weights)
plt.pyplot.show()
```

<p>Which produced this disconnected plot:</p>

<p><img src="https://i.stack.imgur.com/ZbziV.png" alt="Disconnected plot"></p>

<p>I want this output:</p>

<p><img src="https://i.stack.imgur.com/Drky4.png" alt="enter image description here"></p>

<p>So I did this:</p>

```MonThudate = []
TueFridate = []
WedSatdate = []
MonThuwt = []
TueFriwt = []
WedSatwt = []
for i in range(len(dates)):
    if any(x in dates[i] for x in ["Mon","Thu"]):
        MonThudate.append(dates[i])
        MonThuwt.append(weights[i])
    if any(x in dates[i] for x in ["Tue","Fri"]):
        TueFridate.append(dates[i])
        TueFriwt.append(weights[i])
    if any(x in dates[i] for x in ["Wed","Sat"]):
        WedSatdate.append(dates[i])
        WedSatwt.append(weights[i])
#MonThuDate = ['16 Thu', '20 Mon', '23 Thu', '27 Mon']
#MonThuwt = [1471.5, 4026.0, 0.0, 5132.0]
plt.pyplot.plot(MonThudate,MonThuwt,'ro-')
plt.pyplot.plot(WedSatdate,WedSatwt,'ro-')
plt.pyplot.plot(TueFridate,TueFriwt,'ro-')
```

It produced this:

But here, the x-axis is not the same for the whole graph. It is disjoint.

答:
So basically you want to connect only certain days of the week. Then you need to label those date with the correct group label and plot on each group:

```<code># create day group:
day_groups = [['Thu','Mon'], ['Tue','Fri'], ['Wed', 'Sat'],['Sun']]
day_dict = {day:i for i,groups in enumerate(day_groups) for day in groups}
# {'Thu': 0, 'Mon': 0, 'Tue': 1, 'Fri': 1, 'Wed': 2, 'Sat': 2, 'Sun': 3}

# label the days in the given data set:
# if df.dates is datetime, we can do df.dates.dt.day_name().str[:3]
day_labels = df.dates.str.split(expand=True)[1].map(day_dict)

# groupby and plot:

fig, ax = plt.subplots(figsize=(10,6))
df.weights.groupby(day_labels).plot(ax=ax, marker='o')

ax.set_xticklabels([0] + df.dates.tolist())
ax.grid(b=True, which='major', color='#666666', linestyle='-')
plt.show()
</code>```

Output:

Note: you are recommended to convert your df.dates into datetime for automatically arrangement of the x-axis.

Body:
I am plotting my workout weights against "Date Weekday". I want to connect all the points which match the condition:

weights = ([1471.5, 4026. , 2399.5, 5462. ,    0. , 2758.1, 6229. , 5132. ])
dates = ['16 Thu', '20 Mon', '21 Tue', '22 Wed', '23 Thu', '24 Fri','25 Sat','27 Mon']
any(x in dates[i] for x in ["Mon","Thu"])

I saw this question  Plotting lines connecting points But this addresses every two points but my problem is that I might skip some days. I want the code to be robust.

I was using this for the above "dates" and "weights":

plt.pyplot.plot(dates,weights,'ro-')
plt.pyplot.xticks(dates)
plt.pyplot.grid(b=True, which='major', color='#666666', linestyle='-')
plt.pyplot.yticks(weights)
plt.pyplot.show()

Which produced this disconnected plot:

I want this output:

So I did this:

MonThudate = []
TueFridate = []
WedSatdate = []
MonThuwt = []
TueFriwt = []
WedSatwt = []
for i in range(len(dates)):
    if any(x in dates[i] for x in ["Mon","Thu"]):
        MonThudate.append(dates[i])
        MonThuwt.append(weights[i])
    if any(x in dates[i] for x in ["Tue","Fri"]):
        TueFridate.append(dates[i])
        TueFriwt.append(weights[i])
    if any(x in dates[i] for x in ["Wed","Sat"]):
        WedSatdate.append(dates[i])
        WedSatwt.append(weights[i])
#MonThuDate = ['16 Thu', '20 Mon', '23 Thu', '27 Mon']
#MonThuwt = [1471.5, 4026.0, 0.0, 5132.0]
plt.pyplot.plot(MonThudate,MonThuwt,'ro-')
plt.pyplot.plot(WedSatdate,WedSatwt,'ro-')
plt.pyplot.plot(TueFridate,TueFriwt,'ro-')

It produced this:

But here, the x-axis is not the same for the whole graph. It is disjoint.

Body:
So basically you want to connect only certain days of the week. Then you need to label those date with the correct group label and plot on each group:

# create day group:
day_groups = [['Thu','Mon'], ['Tue','Fri'], ['Wed', 'Sat'],['Sun']]
day_dict = {day:i for i,groups in enumerate(day_groups) for day in groups}
# {'Thu': 0, 'Mon': 0, 'Tue': 1, 'Fri': 1, 'Wed': 2, 'Sat': 2, 'Sun': 3}

# label the days in the given data set:
# if df.dates is datetime, we can do df.dates.dt.day_name().str[:3]
day_labels = df.dates.str.split(expand=True)[1].map(day_dict)

# groupby and plot:

fig, ax = plt.subplots(figsize=(10,6))
df.weights.groupby(day_labels).plot(ax=ax, marker='o')

ax.set_xticklabels([0] + df.dates.tolist())
ax.grid(b=True, which='major', color='#666666', linestyle='-')
plt.show()

Output:

Note: you are recommended to convert your df.dates into datetime for automatically arrangement of the x-axis.


答:
You should try something like this:

```<code>filterFn = lambda f: f[0] == '.' or any(s in f for s in ['BLACKBOX','.RTN','.log'])
files = [f for f in files if not filterFn(f)]
</code>```

My local test shows:

```<code>>>> files = [f for f in ('.', 'TEST', 'test.RTN') if not filterFn(f)]
>>> files
['TEST']
</code>```

Title: How to concatenate several logical operators like 'a and not (b or c or d)'

Body:
How do I write this correctly:

for root, dirs, files in os.walk(SEARCHDIR):
    files = [f for f in files if not f[0] == '.' and not ("BLACKBOX" or ".RTN" or ".log") in f]

I want to achieve my file list to contain all files instead of hidden files or files conaining one of the strings "BLACKBOX" or ".RTN" or ".log".
Anyway only the first expression is evaluated ("BLACKBOX") the others are ignored.

Body:
You should try something like this:

filterFn = lambda f: f[0] == '.' or any(s in f for s in ['BLACKBOX','.RTN','.log'])
files = [f for f in files if not filterFn(f)]

My local test shows:

>>> files = [f for f in ('.', 'TEST', 'test.RTN') if not filterFn(f)]
>>> files
['TEST']


问:
turning a list of numpy.ndarray to a matrix in order to perform multiplication
i have vectors of this form :

```<code>test=np.linspace(0,1,10)
</code>```

i want to stack them horizontally in order to make a matrix .
problem is that i define them in a loop so the first stack is between an empty matrix and the first column vector , which gives the following error:

```<code>ValueError: all the input arrays must have same number of dimensions
</code>```

bottom line - i have a for loop that with every iteration creates a vector p1 and i want to add it to a final matrix of the form :
[p1 p2 p3 p4] which i could then do matrix operations on such as multiplying by the transposed etc

答:
How did you get this dimension error?  What does empty array have to do with it?

A list of arrays of the same length:

```<code>In [610]: alist = [np.linspace(0,1,6), np.linspace(10,11,6)]
In [611]: alist
Out[611]:
[array([0. , 0.2, 0.4, 0.6, 0.8, 1. ]),
 array([10. , 10.2, 10.4, 10.6, 10.8, 11. ])]
</code>```

Several ways of making an array from them:

```<code>In [612]: np.array(alist)
Out[612]:
array([[ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ],
       [10. , 10.2, 10.4, 10.6, 10.8, 11. ]])

In [614]: np.stack(alist)
Out[614]:
array([[ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ],
       [10. , 10.2, 10.4, 10.6, 10.8, 11. ]])
</code>```

If you want to join them in columns, you can transpose one of the above, or use:

```<code>In [615]: np.stack(alist, axis=1)
Out[615]:
array([[ 0. , 10. ],
       [ 0.2, 10.2],
       [ 0.4, 10.4],
       [ 0.6, 10.6],
       [ 0.8, 10.8],
       [ 1. , 11. ]])
</code>```

np.column_stack is also handy.

In newer numpy versions you can do:

```<code>In [617]: np.linspace((0,10),(1,11),6)
Out[617]:
array([[ 0. , 10. ],
       [ 0.2, 10.2],
       [ 0.4, 10.4],
       [ 0.6, 10.6],
       [ 0.8, 10.8],
       [ 1. , 11. ]])
</code>```

You don't specify how you create the 'empty array' and how you attempt to stack.  I can't exactly recreate the error message (full traceback would have helped).  But given that message did you check the number of dimensions of the inputs?  Did they match?

Array stacking in a loop is tricky.  You have to pay close attention to the shapes, especially of the initial 'empty' array.  There isn't a close analog to the empty list []. np.array([]) is 1d with shape (1,).  np.empty((0,6)) is 2d with shape (0,6).  Also all the stacking functions create a new array with each call (non operate in-place), so they are inefficient (compared to list append).

Body:
i have vectors of this form :

test=np.linspace(0,1,10)

i want to stack them horizontally in order to make a matrix .
problem is that i define them in a loop so the first stack is between an empty matrix and the first column vector , which gives the following error:

ValueError: all the input arrays must have same number of dimensions

bottom line - i have a for loop that with every iteration creates a vector p1 and i want to add it to a final matrix of the form :
[p1 p2 p3 p4] which i could then do matrix operations on such as multiplying by the transposed etc

Body:
How did you get this dimension error?  What does empty array have to do with it?

A list of arrays of the same length:

In [610]: alist = [np.linspace(0,1,6), np.linspace(10,11,6)]
In [611]: alist
Out[611]:
[array([0. , 0.2, 0.4, 0.6, 0.8, 1. ]),
 array([10. , 10.2, 10.4, 10.6, 10.8, 11. ])]

Several ways of making an array from them:

In [612]: np.array(alist)
Out[612]:
array([[ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ],
       [10. , 10.2, 10.4, 10.6, 10.8, 11. ]])

In [614]: np.stack(alist)
Out[614]:
array([[ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ],
       [10. , 10.2, 10.4, 10.6, 10.8, 11. ]])

If you want to join them in columns, you can transpose one of the above, or use:

In [615]: np.stack(alist, axis=1)
Out[615]:
array([[ 0. , 10. ],
       [ 0.2, 10.2],
       [ 0.4, 10.4],
       [ 0.6, 10.6],
       [ 0.8, 10.8],
       [ 1. , 11. ]])

np.column_stack is also handy.

In newer numpy versions you can do:

In [617]: np.linspace((0,10),(1,11),6)
Out[617]:
array([[ 0. , 10. ],
       [ 0.2, 10.2],
       [ 0.4, 10.4],
       [ 0.6, 10.6],
       [ 0.8, 10.8],
       [ 1. , 11. ]])

You don't specify how you create the 'empty array' and how you attempt to stack.  I can't exactly recreate the error message (full traceback would have helped).  But given that message did you check the number of dimensions of the inputs?  Did they match?

Array stacking in a loop is tricky.  You have to pay close attention to the shapes, especially of the initial 'empty' array.  There isn't a close analog to the empty list []. np.array([]) is 1d with shape (1,).  np.empty((0,6)) is 2d with shape (0,6).  Also all the stacking functions create a new array with each call (non operate in-place), so they are inefficient (compared to list append).


问:
Is there a way to change a value in all documents on firestore?
I'm a beginner creating an mobile app with react-native and firebase.
I have a value stored in many documents and i want to update the value in all the documents

i tried with .where() clause but i got an error

```<code>firebase.firestore().collection('myCollection').where('myValue','==','oldValue').update({myValue:newValue});
</code>```

I expected the data changed but i got this warning:

```<code>Possible Unhandled Promise Rejection (id: 0):
TypeError: _reactNativeFirebase.default.firestore(...).collection(...).where(...).update is not a function
</code>```

Please excuse my bad english

答: Firestore doesn't provide a way to update documents in bulk based on their current values.  There is no SQL-like "update where" type of syntax. You'll have to first query and read all the documents you want to change, then update them with their new values.</p>

Body:
I'm a beginner creating an mobile app with react-native and firebase.
I have a value stored in many documents and i want to update the value in all the documents

i tried with .where() clause but i got an error

firebase.firestore().collection('myCollection').where('myValue','==','oldValue').update({myValue:newValue});

I expected the data changed but i got this warning:

Possible Unhandled Promise Rejection (id: 0):
TypeError: _reactNativeFirebase.default.firestore(...).collection(...).where(...).update is not a function

Please excuse my bad english


问:
How to deallocate memory for char*
I'm writing text rpg game and i want to, at the end, deallocate memory and the problem is with one char* it deallocates properly and with other char* i get game.exe has triggered a breakpoint error but i can't find how are those cases different.

```<code>skills *_skills;
_skills = (skills*)malloc(moj_konfig.skill_n * sizeof(skills));
for (int i = 0; i < moj_konfig.skill_n; i++)
{
    _skills[i].name = malloc(moj_konfig.ile_znakow * sizeof(char));

}

items **_it;
_it = (items**)malloc(moj_konfig.ekwipunek_wiersze * sizeof(items *));
if (_it == NULL) exit(1);
for (int i = 0; i < moj_konfig.ekwipunek_wiersze; i++)
{
    _it[i] = malloc(moj_konfig.ekwipunek_kolumny * sizeof(items));
    for (int j = 0; j < moj_konfig.ekwipunek_kolumny; j++)
    {
        _it[i][j].nazwa = malloc(moj_konfig.ile_znakow * sizeof(char));
    }
    if (_it[i] == NULL) exit(1);
}

quests *_quests;
_quests = (quests*)malloc(moj_konfig.ilosc_q * sizeof(quests));
for (int i = 0; i < moj_konfig.ilosc_q; i++)
{
    _quests[i].name = malloc(moj_konfig.ile_znakow * sizeof(char));
    _quests[i].done = 0;
    _quests[i].taken = 0;
}
</code>```

it's in the function that returns struct type at the end

```<code>ret->it = _it;
ret->skill = _skills;
ret->quest = _quests;
return ret;
</code>```

And the deallocation looks like that:

```<code>for (int i = 0; i < moj_konfig.max_hero; i++)
{
    for (int j = 0; j < moj_konfig.ekwipunek_wiersze; j++)
    {
        for (int z = 0; z < moj_konfig.ekwipunek_kolumny; z++)
        {
            free(heroes[i].it[j][z].nazwa);
        }
        free(heroes[i].it[j]);
    }
    free(heroes[i].it);

    for (int j = 0; j < moj_konfig.ilosc_q; j++)
    {
        free(heroes[i].quest[j].name);
    }
    free(heroes[i].quest);

    for (int j = 0; j < moj_konfig.skill_n; j++)
    {
        free(heroes[i].skill[j].name);
    }
    free(heroes[i].skill);

    free(heroes[i].name);
    free(heroes);
}
</code>```

And i get error only when i free skills name and quests name but not when i free items name. (it is items)

EDIT:: I changed a few things and it still doesn't work with visual studio but when i tried it in code blocks it works just fine so maybe, just maybe it's some kind of vs problem

答:
heroes does not appear in your code but free(heroes); must be replaced by free(heroes[i]); in your loop

after the loop may be free(heroes); must be done but only if it is a pointer you allocated

Title: How to deallocate memory for char*

Body:
I'm writing text rpg game and i want to, at the end, deallocate memory and the problem is with one char* it deallocates properly and with other char* i get game.exe has triggered a breakpoint error but i can't find how are those cases different.

skills *_skills;
_skills = (skills*)malloc(moj_konfig.skill_n * sizeof(skills));
for (int i = 0; i < moj_konfig.skill_n; i++)
{
    _skills[i].name = malloc(moj_konfig.ile_znakow * sizeof(char));

}

items **_it;
_it = (items**)malloc(moj_konfig.ekwipunek_wiersze * sizeof(items *));
if (_it == NULL) exit(1);
for (int i = 0; i < moj_konfig.ekwipunek_wiersze; i++)
{
    _it[i] = malloc(moj_konfig.ekwipunek_kolumny * sizeof(items));
    for (int j = 0; j < moj_konfig.ekwipunek_kolumny; j++)
    {
        _it[i][j].nazwa = malloc(moj_konfig.ile_znakow * sizeof(char));
    }
    if (_it[i] == NULL) exit(1);
}

quests *_quests;
_quests = (quests*)malloc(moj_konfig.ilosc_q * sizeof(quests));
for (int i = 0; i < moj_konfig.ilosc_q; i++)
{
    _quests[i].name = malloc(moj_konfig.ile_znakow * sizeof(char));
    _quests[i].done = 0;
    _quests[i].taken = 0;
}

it's in the function that returns struct type at the end

ret->it = _it;
ret->skill = _skills;
ret->quest = _quests;
return ret;

And the deallocation looks like that:

for (int i = 0; i < moj_konfig.max_hero; i++)
{
    for (int j = 0; j < moj_konfig.ekwipunek_wiersze; j++)
    {
        for (int z = 0; z < moj_konfig.ekwipunek_kolumny; z++)
        {
            free(heroes[i].it[j][z].nazwa);
        }
        free(heroes[i].it[j]);
    }
    free(heroes[i].it);

    for (int j = 0; j < moj_konfig.ilosc_q; j++)
    {
        free(heroes[i].quest[j].name);
    }
    free(heroes[i].quest);

    for (int j = 0; j < moj_konfig.skill_n; j++)
    {
        free(heroes[i].skill[j].name);
    }
    free(heroes[i].skill);

    free(heroes[i].name);
    free(heroes);
}

And i get error only when i free skills name and quests name but not when i free items name. (it is items)

EDIT:: I changed a few things and it still doesn't work with visual studio but when i tried it in code blocks it works just fine so maybe, just maybe it's some kind of vs problem


问:
Reading in a Google Sheet to R
I don't think I'm understanding how to use the API in the googlesheets package. I'm wanting to read in this:

```<code>library(googlesheets)

url <- "https://docs.google.com/spreadsheets/d/e/2PACX-1vSrr9DRaC2fXzPdmOxLW-egSYtxmEp_RKoYGggt-zOKYXSx4RjPsM4EO19H7OJVX1esTtIoFvlKFWcn/pub#"

dat <- gs_read(url)
</code>```

But I'm getting an error I don't understand:

```<code>Error in gs_read_csv(ss, ws = ws, ..., verbose = verbose) :
  inherits(ss, "googlesheet") is not TRUE
</code>```

答:
So gs_read actually takes a "spreadsheet" object that can be created with the gs_title() function. I would modify your code like the below.

```<code>library(googlesheets)
gs_auth()

name <- "name of google sheet"
spreadsheet_object <- gs_title(name)

dat <- gs_read(spreadsheet_object)
</code>```

Let me know if that helps!

Title: Reading in a Google Sheet to R

Body:
I don't think I'm understanding how to use the API in the googlesheets package. I'm wanting to read in this:

library(googlesheets)

url <- "https://docs.google.com/spreadsheets/d/e/2PACX-1vSrr9DRaC2fXzPdmOxLW-egSYtxmEp_RKoYGggt-zOKYXSx4RjPsM4EO19H7OJVX1esTtIoFvlKFWcn/pub#"

dat <- gs_read(url)

But I'm getting an error I don't understand:

Error in gs_read_csv(ss, ws = ws, ..., verbose = verbose) :
  inherits(ss, "googlesheet") is not TRUE

Body:
So gs_read actually takes a "spreadsheet" object that can be created with the gs_title() function. I would modify your code like the below.

library(googlesheets)
gs_auth()

name <- "name of google sheet"
spreadsheet_object <- gs_title(name)

dat <- gs_read(spreadsheet_object)

Let me know if that helps!


问:
How to cut long labels in Matplotlib
I would like to cut long labels, so that only the first 4 letters are displayed, without changing the values in the original data frame.

Example:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sn

np.random.seed(89)

# Toy Dataset
d = pd.DataFrame(np.random.randint(0,3, size=(100, 1)), columns=['var'])
d['var'] = (np.where(d['var'] == 1,'Long loooooong loooooong text',d['var']))

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=d, orient='h');
```

Current output:

Desirable output:

答:
try this : </p>

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

np.random.seed(89)

# Toy Dataset
d = pd.DataFrame(np.random.randint(0,3, size=(100, 1)), columns=['var'])
d['var'] = (np.where(d['var'] == 1,'Long loooooong loooooong text'[:4],d['var']))

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=d, orient='h');
</code>```

<p>to get the 4 first letters of a string : </p>

```<code>first_four_letters = your_string[:4]

</code>```

Title: How to cut long labels in Matplotlib

Body:
I would like to cut long labels, so that only the first 4 letters are displayed, without changing the values in the original data frame.

Example:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sn

np.random.seed(89)

# Toy Dataset
d = pd.DataFrame(np.random.randint(0,3, size=(100, 1)), columns=['var'])
d['var'] = (np.where(d['var'] == 1,'Long loooooong loooooong text',d['var']))

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=d, orient='h');

Current output:

Desirable output:

Body:
try this :

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

np.random.seed(89)

# Toy Dataset
d = pd.DataFrame(np.random.randint(0,3, size=(100, 1)), columns=['var'])
d['var'] = (np.where(d['var'] == 1,'Long loooooong loooooong text'[:4],d['var']))

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=d, orient='h');

to get the 4 first letters of a string :

first_four_letters = your_string[:4]


问:
Don't quite understand what the address of & operator is doing in this struct and how its able to access the other member variables
I'm starting to get grips with c++ and I thought I would learn about creating vectors and doing manipulations on them and in doing so I would get to grips with pointers and references.
Maybe I've been looking at it too long but I'm not quite sure what is going on the with the section of code related to the return statement with the book I'm following along has given me, more specifically the return ((&x)[i]); part.
Listed below:

```<code>float& operator [](int i)
{
    return ((&x)[i]);
}
</code>```

My understanding is that & - address operator would give you the address of a particular variable. Now if I remember correctly pointers and arrays go hand in hand, so when you get a reference to the x variable like so (&x)[i] you are able to access the next element using an offset operator but I didn't know you could do this with structs.

Am I on the right track or have I lost it?

Using the following links to help me:
http://www.cplusplus.com/doc/tutorial/pointers/
https://en.cppreference.com/w/cpp/language/operator_member_access

struct Vector3D
{
    float       x, y, z;

    Vector3D() = default;

    Vector3D(float a, float b, float c)
    {
        x = a;
        y = b;
        z = c;
    }

    float& operator [](int i)
    {
        return ((&x)[i]);
    }

    const float& operator [](int i) const
    {

        return ((&x)[i]);
    }
};

int main(int argc, char const *argv[])
{

    Vector3D vec = Vector3D(1,2,3);
    auto test = vec[1];
    std::cout << test << std::endl;

    return 0;
}
```

I understand that the value printed here would be 2 but I don't quite get the &x reference being able to access the struct member values?

答:
What

```<code>return ((&x)[i]);
</code>```

does is take the address of x, and then using [i], it gets the object at the offset of i from x.  Basically, you are pretending you have an array of int's, instead of 3 seperate int's, with x being the first element of the array.

This is undefined behavior for a couple of reason though.  First, you cannot access an element that is out of bounds for the array.  An object can be considered an array of one so (&variable)[0] is legal, as it is just variable (ignoring that & could be overloaded).  So any index besides 0 is UB.  Secondly, the compiler is allowed to put padding between member variables of a class.  This means that you can't know, without asserting the class is the size you expect, that y and z are adjacent to x in memory.

The correct way to write the function would be use use a switch statement like

```<code>float& operator [](int i)
{
    switch(i)
    {
        case 0: return x;
        case 1: return y;
        case 2: return z;
        default: // throw an exception or return one of the members or do something else to indicate an error
    }
}
</code>```

Body:
I'm starting to get grips with c++ and I thought I would learn about creating vectors and doing manipulations on them and in doing so I would get to grips with pointers and references.
Maybe I've been looking at it too long but I'm not quite sure what is going on the with the section of code related to the return statement with the book I'm following along has given me, more specifically the return ((&x)[i]); part.
Listed below:

float& operator [](int i)
{
    return ((&x)[i]);
}

My understanding is that & - address operator would give you the address of a particular variable. Now if I remember correctly pointers and arrays go hand in hand, so when you get a reference to the x variable like so (&x)[i] you are able to access the next element using an offset operator but I didn't know you could do this with structs.

Am I on the right track or have I lost it?

Using the following links to help me:
http://www.cplusplus.com/doc/tutorial/pointers/
https://en.cppreference.com/w/cpp/language/operator_member_access

struct Vector3D
{
    float       x, y, z;

    Vector3D() = default;

    Vector3D(float a, float b, float c)
    {
        x = a;
        y = b;
        z = c;
    }

    float& operator [](int i)
    {
        return ((&x)[i]);
    }

    const float& operator [](int i) const
    {

        return ((&x)[i]);
    }
};

int main(int argc, char const *argv[])
{

    Vector3D vec = Vector3D(1,2,3);
    auto test = vec[1];
    std::cout << test << std::endl;

    return 0;
}

I understand that the value printed here would be 2 but I don't quite get the &x reference being able to access the struct member values?

Body:
What

return ((&x)[i]);

does is take the address of x, and then using [i], it gets the object at the offset of i from x.  Basically, you are pretending you have an array of int's, instead of 3 seperate int's, with x being the first element of the array.

This is undefined behavior for a couple of reason though.  First, you cannot access an element that is out of bounds for the array.  An object can be considered an array of one so (&variable)[0] is legal, as it is just variable (ignoring that & could be overloaded).  So any index besides 0 is UB.  Secondly, the compiler is allowed to put padding between member variables of a class.  This means that you can't know, without asserting the class is the size you expect, that y and z are adjacent to x in memory.

The correct way to write the function would be use use a switch statement like

float& operator [](int i)
{
    switch(i)
    {
        case 0: return x;
        case 1: return y;
        case 2: return z;
        default: // throw an exception or return one of the members or do something else to indicate an error
    }
}


问:
How do you debug heavily templated code in c++?
I find it very hard to figure out what is wrong with my code when using C++ template meta-programming. It might be that I am just not very good at understanding the error messages, but as far as I'm aware I can't resort to putting in print statements or breakpoints to figure out what's going on.

What tips or advice can you offer when trying to figure out why something is not compiling other than just picking through the code manually and hoping it will come to me?

答:
Which compiler are you using? VC8 and 9 are actually pretty decent at outputting readable error messages. It still takes a bit of patience to go through, but it can be done, and they essentially show the compile-time equivalent of the call stack. Starting at the bottom, which template instantiation caused the error, and what were the template arguments? Next level up shows the template it was instantiated from and so on, all the way up to the top-level. Of course this is only visible in the "output" tab, not the "errors" one which it normally shows after a failed compile.

The principle is similar in GCC, although last I tried, at least, the formatting was somewhat less readable. But really, you just have to trace through the stack of instantiations, and at each level, verify that it got instantiated with the types you expected, until you find the one that introduced the error.

It's a pain, but it can be done, and it requires nothing more than patience and a willingness to read the error messages. :)

Also, liberal use of static_assert (or BOOST_STATIC_ASSERT) can help a lot by providing sanity checks

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: David Segonds

OwnerDisplayName: jalf


问:
What's the meaning of these two lines of PHP code?
I'm currently programming a script to login the user if the user types the right information in the Password- and Login-field on a login page. The script is working just fine, but I don't actually know what these two lines of code means and does for the overall user experience.

I'm soon going to an exam where I have to explain the meaning of the code, and it would be absolutely amazing if you guys helped me out by explaining what the two lines of code does below. This is the full script:

```<code><?php

require('db_connect.php');

if (isset($_POST['user_id']) and isset($_POST['user_pass'])) {

    $username = $_POST['user_id'];
    $password = $_POST['user_pass'];

    $query = "SELECT * FROM dataforlogin WHERE username='$username' and password='$password'";

    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    $count = mysqli_num_rows($result);

    if ($count == 1) {

        header("location: ../staudal/dashboard/index.php");

    } else {

        echo "Fail";

  }
}

?>
</code>```

The two lines of code that I'm having trouble understanding is:

```<code>$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
</code>```

What do they do and why?

答:
I'm a junior developer but I hope this answer will help according to your code:

$result = mysqli_query($connection, $query) or die(mysqli_error($connection));

$result is a php variable

mysqli_query($connection, $query) means that mysqli_query will use the database connection declared database in your db_connect.php to run the query [$query = "SELECT * FROM dataforlogin WHERE username='$username' and password='$password'";]

or die(mysqli_error($connection)); means that if mysqli_query does not find the specified database or the table, in this case (dataforlogin), it will display the connection error specified in your db_connect.php

$count = mysqli_num_rows($result);

$count is a php variable

mysqli_num_rows($result); means that the $count is equall to the number of the rows found in the table (dataforlogin) for $result when mysqli_query($connection, $query) was run.

Note: Please avoid using the line --- or die(mysqli_error($connection) because it may prevent the page from loading, it's not necessary.

Body:
I'm currently programming a script to login the user if the user types the right information in the Password- and Login-field on a login page. The script is working just fine, but I don't actually know what these two lines of code means and does for the overall user experience.

I'm soon going to an exam where I have to explain the meaning of the code, and it would be absolutely amazing if you guys helped me out by explaining what the two lines of code does below. This is the full script:

<?php

require('db_connect.php');

if (isset($_POST['user_id']) and isset($_POST['user_pass'])) {

    $username = $_POST['user_id'];
    $password = $_POST['user_pass'];

    $query = "SELECT * FROM dataforlogin WHERE username='$username' and password='$password'";

    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    $count = mysqli_num_rows($result);

    if ($count == 1) {

        header("location: ../staudal/dashboard/index.php");

    } else {

        echo "Fail";

  }
}

?>

The two lines of code that I'm having trouble understanding is:

$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);

What do they do and why?