问:
How to delete a field from UI by clicking its respective delete icon - Angular
I have couple of input fields created using matInput. I have followed parent child structure to create this.I have a delete icon corresponding to each input field.If i click the delete icon, the respective field has to be removed from UI. Attached the image for reference and below is the code .
I have income-field.component which is the child component, and employee-details which is the parent component. Any help on this is appreciated. Thanks!!

income-field.component.html

```<code><div  [formGroup]="parentForm">
  <mat-form-field >
    <div class="delete-icon" *ngIf="showDeleteIcon" (click)="removeIncomeField($event, i)">
      <img src="/assets/icons/delete_income.png"></div>

    <input matInput [(value)]="value" [placeholder]="placeholder" type="number" (input)="change($event.target.value)"
      [formControlName]="name" />
  </mat-form-field>
</div>

income-field.component.ts:

export class IncomeFieldComponent {
  @Input() placeholder;
  @Input() value;
  @Input() name;
  @Input() showDeleteIcon;
  @Output() textValue = new EventEmitter();
  @Output() deleteIncomeField= new EventEmitter();
  @Input() parentForm: FormControl;
  isActive = false;

  removeIncomeField(event: any) {
    this.deleteIncomeField.emit(event);
  }
change(value) {
    this.value = +value;
    this.textValue.emit(this.value);
  }
}

employee-details.component.html:

  <app-income-field placeholder="Business income"  [value]=""
            type="number" name="businessIncome" (textValue)="getTextValue($event, 'businessIncome')" [showDeleteIcon]="true"
              [parentForm]="employee_info_form" id="business" (deleteIncomeField)="deleteSelectedField($event)">
            </app-income-field>

  <app-income-field placeholder="Real estate" [showDeleteIcon]="true" [value]=""
              type="number" name="realEstateIncome" (deleteIncomeField)="deleteSelectedField($event)" (textValue)="getTextValue($event, 'realEstateIncome')"
              [parentForm]="additional_info_form">
            </app-income-field>
</code>```

答:
I am not sure how easiest the solution will be to achieve this. But I have managed to achieve the solution. This might not be the best answer as I had to write  2 separate functions for 2 fields. However the below code works , I am not happy with multiple lines of code. Any refactoring possible on the solution is much appreciated. Thanks!!

income.component.html:

```<code><div  [formGroup]="parentForm">
  <mat-form-field >
   <div class="delete-icon" *ngIf="showDeleteIconForBusiness" (click)="removeBusinessField($event)">
      <img src="/assets/icons/delete_income.png"></div>
<!--added another div for real estate field-->
<div class="delete-icon" *ngIf="showDeleteIconForRealestate" (click)="removeRealEstateField($event)">
        <img src="/assets/icons/delete_income.png"></div>

    <input matInput [(value)]="value" [placeholder]="placeholder" type="number" (input)="change($event.target.value)"
      [formControlName]="name" />
  </mat-form-field>
</div>

export class IncomeFieldComponent {
  @Input() placeholder;
  @Input() value;
  @Input() name;
   @Input() showDeleteIconForBusiness;
  @Input() showDeleteIconForRealestate
  @Output() textValue = new EventEmitter();
  @Output() deleteBusinessField= new EventEmitter();
  @Output() deleteRealestateField=new EventEmitter();
  @Input() parentForm: FormControl;
  isActive = false;

 removeBusinessField(event: any) {
    this.deleteBusinessField.emit(event);
  }
  removeRealEstateField(event:any) {
    this.deleteRealestateField.emit(event);
  }
change(value) {
    this.value = +value;
    this.textValue.emit(this.value);
  }
}

employee-details.component.html:

  <app-income-field placeholder="Business income"  [value]=""
            type="number" name="businessIncome" (textValue)="getTextValue($event, 'businessIncome')" [showDeleteIconForBusiness]="true"
              [parentForm]="employee_info_form" (deleteBusinessField)="deleteBusinessField()">
            </app-income-field>

  <app-income-field placeholder="Real estate" [showDeleteIconForRealestate]="true" [value]=""
              type="number" name="realEstateIncome" (deleteRealestateField)="deleteRealestateField()" (textValue)="getTextValue($event, 'realEstateIncome')"
              [parentForm]="additional_info_form">
            </app-income-field>
</code>```

Body:
I have couple of input fields created using matInput. I have followed parent child structure to create this.I have a delete icon corresponding to each input field.If i click the delete icon, the respective field has to be removed from UI. Attached the image for reference and below is the code .
I have income-field.component which is the child component, and employee-details which is the parent component. Any help on this is appreciated. Thanks!!

income-field.component.html

  <mat-form-field >

    <input matInput [(value)]="value" [placeholder]="placeholder" type="number" (input)="change($event.target.value)"
      [formControlName]="name" />
  </mat-form-field>

income-field.component.ts:

export class IncomeFieldComponent {
  @Input() placeholder;
  @Input() value;
  @Input() name;
  @Input() showDeleteIcon;
  @Output() textValue = new EventEmitter();
  @Output() deleteIncomeField= new EventEmitter();
  @Input() parentForm: FormControl;
  isActive = false;

  removeIncomeField(event: any) {
    this.deleteIncomeField.emit(event);
  }
change(value) {
    this.value = +value;
    this.textValue.emit(this.value);
  }
}

employee-details.component.html:

  <app-income-field placeholder="Business income"  [value]=""
            type="number" name="businessIncome" (textValue)="getTextValue($event, 'businessIncome')" [showDeleteIcon]="true"
              [parentForm]="employee_info_form" id="business" (deleteIncomeField)="deleteSelectedField($event)">
            </app-income-field>

  <app-income-field placeholder="Real estate" [showDeleteIcon]="true" [value]=""
              type="number" name="realEstateIncome" (deleteIncomeField)="deleteSelectedField($event)" (textValue)="getTextValue($event, 'realEstateIncome')"
              [parentForm]="additional_info_form">
            </app-income-field>

Body:
I am not sure how easiest the solution will be to achieve this. But I have managed to achieve the solution. This might not be the best answer as I had to write  2 separate functions for 2 fields. However the below code works , I am not happy with multiple lines of code. Any refactoring possible on the solution is much appreciated. Thanks!!

income.component.html:

<div  [formGroup]="parentForm">
  <mat-form-field >
   <div class="delete-icon" *ngIf="showDeleteIconForBusiness" (click)="removeBusinessField($event)">
      <img src="/assets/icons/delete_income.png"></div>
<!--added another div for real estate field-->
<div class="delete-icon" *ngIf="showDeleteIconForRealestate" (click)="removeRealEstateField($event)">
        <img src="/assets/icons/delete_income.png"></div>

    <input matInput [(value)]="value" [placeholder]="placeholder" type="number" (input)="change($event.target.value)"
      [formControlName]="name" />
  </mat-form-field>
</div>

export class IncomeFieldComponent {
  @Input() placeholder;
  @Input() value;
  @Input() name;
   @Input() showDeleteIconForBusiness;
  @Input() showDeleteIconForRealestate
  @Output() textValue = new EventEmitter();
  @Output() deleteBusinessField= new EventEmitter();
  @Output() deleteRealestateField=new EventEmitter();
  @Input() parentForm: FormControl;
  isActive = false;

 removeBusinessField(event: any) {
    this.deleteBusinessField.emit(event);
  }
  removeRealEstateField(event:any) {
    this.deleteRealestateField.emit(event);
  }
change(value) {
    this.value = +value;
    this.textValue.emit(this.value);
  }
}

employee-details.component.html:

  <app-income-field placeholder="Business income"  [value]=""
            type="number" name="businessIncome" (textValue)="getTextValue($event, 'businessIncome')" [showDeleteIconForBusiness]="true"
              [parentForm]="employee_info_form" (deleteBusinessField)="deleteBusinessField()">
            </app-income-field>

  <app-income-field placeholder="Real estate" [showDeleteIconForRealestate]="true" [value]=""
              type="number" name="realEstateIncome" (deleteRealestateField)="deleteRealestateField()" (textValue)="getTextValue($event, 'realEstateIncome')"
              [parentForm]="additional_info_form">
            </app-income-field>


来源: stackexchange

问:
How to access a shared prefrences create in flutter from java code?
I create a SharedPreferences in flutter and I want to use it in android Native code in my project. How can I do that?</p>

答:
For the noobs out here,</p>

```<code>import android.content.SharedPreferences
...
var PRIVATE_MODE = 0
val mPrefs = getSharedPreferences("FlutterSharedPreferences", PRIVATE_MODE)
mPrefs.getString("flutter." + "key", "")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For the noobs out here,

import android.content.SharedPreferences
...
var PRIVATE_MODE = 0
val mPrefs = getSharedPreferences("FlutterSharedPreferences", PRIVATE_MODE)
mPrefs.getString("flutter." + "key", "")


问:
UITextfield Value in UITableView
I have a textfield inside a UITableviewController. I want to get the user entered data after the user has finished typing and moves to the next field. I want to store that information.

Because once I scroll the user entered data disappears.

Any help is appreciated.

```<code>if (([indexPath section] == 1) && ([indexPath row] == 2))
{
    static NSString *CellIdentifier1 = @"Cell";

    GeneralInfocell *cell = (GeneralInfocell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
    [[NSBundle mainBundle] loadNibNamed:@"GeneralInfocell" owner:self options:nil];

    cell = addresscell;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    addresscell.txtStreet.delegate = self;

    addresscell.txtStreet.font = [UIFont fontWithName:@"Arial" size:14];

    addresscell.txtStreet.keyboardType = UIKeyboardTypeDefault;
    addresscell.txtStreet.returnKeyType = UIReturnKeyNext;

    addresscell.txtStreet.backgroundColor = [UIColor whiteColor];
    addresscell.txtStreet.autocorrectionType = UITextAutocorrectionTypeNo;
    addresscell. txtStreet.autocapitalizationType = UITextAutocapitalizationTypeNone;
    addresscell. txtStreet.textAlignment = UITextAlignmentLeft;

    addresscell.txtStreet.textColor = [UIColor blackColor];

    [addresscell.txtStreet addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
}
</code>```

In the textFieldDidEndEditing method I have,

```<code>- (void)textFieldDidEndEditing:(UITextField *)textField {

    UILabel *label = [NSString stringWithFormat:@"%@",[addresscell.txtCity text]];
    NSLog(@"label:%@",label);

}
</code>```

But I don't get any value.

Thanks

答: Implement the UITextFieldDelegate protocol and the textFieldDidEndEditing: method.

ContentLicense: CC BY-SA 3.0

Title: UITextfield Value in UITableView

Body:
I have a textfield inside a UITableviewController. I want to get the user entered data after the user has finished typing and moves to the next field. I want to store that information.

Because once I scroll the user entered data disappears.

Any help is appreciated.

if (([indexPath section] == 1) && ([indexPath row] == 2))
{
    static NSString *CellIdentifier1 = @"Cell";

    GeneralInfocell *cell = (GeneralInfocell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
    [[NSBundle mainBundle] loadNibNamed:@"GeneralInfocell" owner:self options:nil];

    cell = addresscell;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    addresscell.txtStreet.delegate = self;

    addresscell.txtStreet.font = [UIFont fontWithName:@"Arial" size:14];

    addresscell.txtStreet.keyboardType = UIKeyboardTypeDefault;
    addresscell.txtStreet.returnKeyType = UIReturnKeyNext;

    addresscell.txtStreet.backgroundColor = [UIColor whiteColor];
    addresscell.txtStreet.autocorrectionType = UITextAutocorrectionTypeNo;
    addresscell. txtStreet.autocapitalizationType = UITextAutocapitalizationTypeNone;
    addresscell. txtStreet.textAlignment = UITextAlignmentLeft;

    addresscell.txtStreet.textColor = [UIColor blackColor];

    [addresscell.txtStreet addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
}

In the textFieldDidEndEditing method I have,

- (void)textFieldDidEndEditing:(UITextField *)textField {

    UILabel *label = [NSString stringWithFormat:@"%@",[addresscell.txtCity text]];
    NSLog(@"label:%@",label);

}

But I don't get any value.

Thanks


问:
Take values from one column and create new column from it
I have big database that has one column called "Measurments" and one column with called "data" which contains data about those different measurments, for example, i measurments you can find height, weight and different indices values and in data you will find the value for this "measurment".
I would like to organize this database in a way that each unique measurment type, will have its' own column, so for example i'll have column name weight, height ect. and the  vvalue they got from the column "data".

Until nowI have used this way in order to create many little databases with my relevant data:

```<code>df_NDVI=df[(df['Measurement'] == 'NDVI') & (df['Data']!='Corrupt')]
df_VPP_kg=df[(df['Measurement'] == 'WEIGHT')]
</code>```

But as youcan see, it is not efficient and it creates many databases instead of one with those columns.

My end goal: to take each unique field from "measurments" column and create new column for  it with the correct data from column "data".

答:
Try this:

df["obs"]=df.groupby("Measurements")["Measurements"].cumcount()
df.pivot(index="obs", columns="Measurements", values="Data")
```

So you will get 1 column for each unique value from Measurements, and Data will be order below by order of observation.

Body:
I have big database that has one column called "Measurments" and one column with called "data" which contains data about those different measurments, for example, i measurments you can find height, weight and different indices values and in data you will find the value for this "measurment".
I would like to organize this database in a way that each unique measurment type, will have its' own column, so for example i'll have column name weight, height ect. and the  vvalue they got from the column "data".

Until nowI have used this way in order to create many little databases with my relevant data:

df_NDVI=df[(df['Measurement'] == 'NDVI') & (df['Data']!='Corrupt')]
df_VPP_kg=df[(df['Measurement'] == 'WEIGHT')]

But as youcan see, it is not efficient and it creates many databases instead of one with those columns.

My end goal: to take each unique field from "measurments" column and create new column for  it with the correct data from column "data".

Body:
Try this:

df["obs"]=df.groupby("Measurements")["Measurements"].cumcount()
df.pivot(index="obs", columns="Measurements", values="Data")

So you will get 1 column for each unique value from Measurements, and Data will be order below by order of observation.


问:
Plotting seperate graphs over each other pandas
I have 3 separate plots. I want to put them over each other.

What is the simplest means of doing this?
(The actual graphs have way too much code for me to post here aha.)

答:
There are several ways to do this. The easiest way is to simply plot each graph separately:

```<code>import matplotlib.pyplot as plt

x1 = range(10)
x2= range(10,20)
x3= range(-10,0)

fig = plt.figure()
plt.plot(x1)
fig = plt.figure()
plt.plot(x2)
fig = plt.figure()
plt.plot(x3)
</code>```

To build subplots you can use subplot:

```<code>cols = 1
rows = 3

plt.subplot(rows, cols, 1)
plt.plot(x1)
plt.subplot(rows, cols, 2)
plt.plot(x2)
plt.subplot(rows, cols, 3)
plt.plot(x3)
</code>```

If you need to share an axis, use subplots:

```<code>fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True)
# remove vertical gap between subplots
plt.subplots_adjust(hspace=.0)

ax1.grid()
ax2.grid()
ax3.grid()

ax1.plot(x1)
ax2.plot(x2)
ax3.plot(x3)
</code>```

Body:
There are several ways to do this. The easiest way is to simply plot each graph separately:

import matplotlib.pyplot as plt

x1 = range(10)
x2= range(10,20)
x3= range(-10,0)

fig = plt.figure()
plt.plot(x1)
fig = plt.figure()
plt.plot(x2)
fig = plt.figure()
plt.plot(x3)

To build subplots you can use subplot:

cols = 1
rows = 3

plt.subplot(rows, cols, 1)
plt.plot(x1)
plt.subplot(rows, cols, 2)
plt.plot(x2)
plt.subplot(rows, cols, 3)
plt.plot(x3)

If you need to share an axis, use subplots:

fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True)
# remove vertical gap between subplots
plt.subplots_adjust(hspace=.0)

ax1.grid()
ax2.grid()
ax3.grid()

ax1.plot(x1)
ax2.plot(x2)
ax3.plot(x3)


问:
useState what am I doing wrong?
I'm creating an app that reads the alarm state of several ELK alarm systems. I'm using useState to process the data that I am receiving via socket.io from my server. The data that the server is streaming is an array of arrays.

This is the code that I am using:

```<code>const [startData, updateData] = React.useState([]);

  const socket = io("http://localhost:5000");

  socket.on('data', (dta) => {
    updateData(dta.data);
  });
</code>```

If I console.log(startData) then it becomes evident that my code is causing an infinite loop. I read through examples of users in this forum with similar issues but I wasn't successful in tailoring their solutions to my problem. I was somewhat able to manage the amount of requests with setTimeout but after the app is running for about 2 hours, the page becomes unresponsive (memory leak????).

Do you people have any suggestion on how I could improve my code?

答:
listening to a socket should only happen once, also this is a side effect, both are indicators that these should be inside a useEffect hook:

```<code> useEffect(() => {
   const socket = io("http://localhost:5000");

   socket.on('data', (dta) => {
     updateData(dta.data);
   });
 }, []);
</code>```

Unlike the functions body, which will be run on every rerender, the effect hook will only run on specific state changes, or only once in this case.

Title: useState what am I doing wrong?

Body:
I'm creating an app that reads the alarm state of several ELK alarm systems. I'm using useState to process the data that I am receiving via socket.io from my server. The data that the server is streaming is an array of arrays.

This is the code that I am using:

const [startData, updateData] = React.useState([]);

  const socket = io("http://localhost:5000");

  socket.on('data', (dta) => {
    updateData(dta.data);
  });

If I console.log(startData) then it becomes evident that my code is causing an infinite loop. I read through examples of users in this forum with similar issues but I wasn't successful in tailoring their solutions to my problem. I was somewhat able to manage the amount of requests with setTimeout but after the app is running for about 2 hours, the page becomes unresponsive (memory leak????).

Do you people have any suggestion on how I could improve my code?

Body:
listening to a socket should only happen once, also this is a side effect, both are indicators that these should be inside a useEffect hook:

 useEffect(() => {
   const socket = io("http://localhost:5000");

   socket.on('data', (dta) => {
     updateData(dta.data);
   });
 }, []);

Unlike the functions body, which will be run on every rerender, the effect hook will only run on specific state changes, or only once in this case.


问:
Build failed. Check the Output window for more details - C# publishing fails but build succeeds
I am trying to publish a web application on Visual Studio 2017. The build succeeds but the publishing fails. When it fails an error dialog comes up which says "Publish has encountered an error. Build Failed. A diagnostic log has been written to the following location: .."

This is what the file with the log contains:

System.AggregateException: One or more errors occurred. ---> System.Exception: Build failed. Check the Output window for more details.
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at Microsoft.VisualStudio.Web.Publish.PublishService.VsWebProjectPublish.<>c__DisplayClass41_0.<PublishAsync>b__2()
   at System.Threading.Tasks.Task``1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.ApplicationCapabilities.Publish.ViewModel.ProfileSelectorViewModel.<RunPublishTaskAsync>d__116.MoveNext()
---> (Inner Exception #0) System.Exception: Build failed. Check the Output window for more details.

I've tried running the application as Admin but it still doesn't work. I also searched for the Microsoft.Net.Compilers reference but it's not in my project.

答: There are many causes for this problem. I already had the IIS web site configured, as well as the right permissions for the user. Obviously the project built successfully on my local machine. The problem was I added the absolute windows path on 'Site path' section in VS publish profile. Leave this empty!</p>


问:
I have problems when I try to put the text of the label from a function
I'm doing a calculator with Python 3.8 and Visual Studio. I'm trying to print the result in the label on button click.

This is the error:

Undefined variable 'resultado' pylint(undefined-variable) [37, 32]

This is my code:

```<code>from tkinter import *

r = Tk()
r.title("CALCULADORA")

def operar(num1, num2, signo):

    resultado = IntVar()

    if signo == "+":
        resultado = num1 + num2

    elif signo == "-":
        resultado = num1 - num2

    elif signo == "/":
        resultado = num1 / num2

    elif signo == "X":
        resultado = num1 * num2

    return resultado

textNumUno = Entry(r, width=7)
textNumUno.grid(row=0, column=0)

textOperacion = Entry(r, width=3)
textOperacion.grid(row=0, column=1)

textNumDos = Entry(r, width=7)
textNumDos.grid(row=0, column=2)

btn = Button(r, text="=", width=2, command=operar(textNumUno.get(), textNumDos.get(), textOperacion.get()))
btn.grid(row=0, column=3)

labelResultado = Label(r, text=resultado)
labelResultado.grid(row=0, column=4)

r.mainloop()
</code>```

答: I'm not familiar with the tkinter syntax, but text=resultado looks like an issue. That variable is local to the operar function, so it doesn't make sense to call it globally

Body:
I'm doing a calculator with Python 3.8 and Visual Studio. I'm trying to print the result in the label on button click.

This is the error:

Undefined variable 'resultado' pylint(undefined-variable) [37, 32]

This is my code:

from tkinter import *

r = Tk()
r.title("CALCULADORA")

def operar(num1, num2, signo):

    resultado = IntVar()

    if signo == "+":
        resultado = num1 + num2

    elif signo == "-":
        resultado = num1 - num2

    elif signo == "/":
        resultado = num1 / num2

    elif signo == "X":
        resultado = num1 * num2

    return resultado

textNumUno = Entry(r, width=7)
textNumUno.grid(row=0, column=0)

textOperacion = Entry(r, width=3)
textOperacion.grid(row=0, column=1)

textNumDos = Entry(r, width=7)
textNumDos.grid(row=0, column=2)

btn = Button(r, text="=", width=2, command=operar(textNumUno.get(), textNumDos.get(), textOperacion.get()))
btn.grid(row=0, column=3)

labelResultado = Label(r, text=resultado)
labelResultado.grid(row=0, column=4)

r.mainloop()


问:
Background color stays transparent, though devtools says it's white
Background color of the first paragraph on the main-content of my Drupal website stays transparent, though it is defined as white in the CSS, and even Devtools says it's white... it sounds noobish and so simple, yet I can't figure out what I'm doing wrong.

HTML:

...

```

<p>CSS:</p>

<pre class="lang-css prettyprint-override"><code>.region--white-background {
    background-color: #ffffff;
}
</code>```

答:
 .region--white-background {
            background-color: #ffffff;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=" region--white-background ">
        <div class="container" style="color:black;">If you want to set background color to white then you'll have to set the color of the content to other than white.I have set it to black using in-line css.
Hope you'll be satisfied.
</div>
    </div></code>```

Body:
Background color of the first paragraph on the main-content of my Drupal website stays transparent, though it is defined as white in the CSS, and even Devtools says it's white... it sounds noobish and so simple, yet I can't figure out what I'm doing wrong.

HTML:

...

CSS:

.region--white-background {
    background-color: #ffffff;
}

Body:
 .region--white-background {
            background-color: #ffffff;
        }

<div class=" region--white-background ">
        <div class="container" style="color:black;">If you want to set background color to white then you'll have to set the color of the content to other than white.I have set it to black using in-line css.
Hope you'll be satisfied.
</div>
    </div>


问:
C++ : undetectable change of variable, artificial "volatile" mutex not works
How it is possible, that is such a line just after if statement with unequal, variables are already equal in pull() method? I have already added Mutex variable, but it not helped.

```<code> int fQ::pull(void){ // pull element from the queue
  while(MutexF);
   MutexF = 1;
  if (last != first){
  fQueue[first++]();
  first%=lengthQ;
  MutexF = 0;
  return 0;
  }
  else{
      MutexF = 0;
        return 1;
  }
}
</code>```

STL containers are to heavy for me, I preparing it for a tiny MCU, that's why, I tried to avoid   all this complex staff like (std::mutex, std::atomic, std::mutex etc.). Those  multitheading is needed only for test purpose, instead of testing with the tiny MCU's interrupts, for a while. I supposed not use any stl/thread libraries at all

 photo of the error

https://github.com/WeSpeakEnglish/nortos/blob/master/C_plus_plus_implementation/main.cpp

https://github.com/WeSpeakEnglish/nortos/blob/master/C_plus_plus_implementation/nortos.h

答:
first, you'd better use std::atomic and/or std::mutex for synchronization purposes. At least use std::flag. volatile has issues in general - it isn't suited for atomic operations - it has a different purpose altogether.

Second in your code, there is a bug and I don't know to solve it properly with volatile.

```<code> while(MutexF);
 MutexF = 1;
</code>```

Imagine, someone set MutexF to 0, then two threads simultaneously exited the while loop before setting MutexF=1. What do you think is gonna happen?

Perhaps you can synchronize two thread - one for pull and one for push in this manner - but you'd better abandon such approach.

Body:
How it is possible, that is such a line just after if statement with unequal, variables are already equal in pull() method? I have already added Mutex variable, but it not helped.

 int fQ::pull(void){ // pull element from the queue
  while(MutexF);
   MutexF = 1;
  if (last != first){
  fQueue[first++]();
  first%=lengthQ;
  MutexF = 0;
  return 0;
  }
  else{
      MutexF = 0;
        return 1;
  }
}

STL containers are to heavy for me, I preparing it for a tiny MCU, that's why, I tried to avoid   all this complex staff like (std::mutex, std::atomic, std::mutex etc.). Those  multitheading is needed only for test purpose, instead of testing with the tiny MCU's interrupts, for a while. I supposed not use any stl/thread libraries at all

 photo of the error

https://github.com/WeSpeakEnglish/nortos/blob/master/C_plus_plus_implementation/main.cpp

https://github.com/WeSpeakEnglish/nortos/blob/master/C_plus_plus_implementation/nortos.h

Body:
first, you'd better use std::atomic and/or std::mutex for synchronization purposes. At least use std::flag. volatile has issues in general - it isn't suited for atomic operations - it has a different purpose altogether.

Second in your code, there is a bug and I don't know to solve it properly with volatile.

 while(MutexF);
 MutexF = 1;

Imagine, someone set MutexF to 0, then two threads simultaneously exited the while loop before setting MutexF=1. What do you think is gonna happen?

Perhaps you can synchronize two thread - one for pull and one for push in this manner - but you'd better abandon such approach.


问:
get file path from stdin in C
I am trying to pass a file to my program however it always gives error, cannot open file.

My command is: (I am on desktop path, I am using ubuntu)

```<code>./out < /usr/share/dict/words > out.txt 2> out2.txt
</code>```

Output files are created but file input seems empty. I am getting file path as:

```<code>char *infile;
scanf("%s", infile);
printf("file: %s\n", infile);
</code>```

I also tried:

```<code>fscanf(stdin, "%s", infile);
</code>```

Nothing changed. Also, I have to take input as shown above, I know < means stdin but I cannot read its content somehow.

This is file opening part and error message:

```<code> file = fopen(infile, "r");
 if (file == 0) {
     fprintf(stderr, "File failed\n");
     return 1;
 }
</code>```

答:
There seem to be some confusion in your approach:

you redirect input to your program from a text file containing words, the classic /usr/share/dict/words file. This file is the input to your program, you can read the contents with getchar(), scanf(), fgets() and other stream input functions, but the name of the file is not available to your program, nor do you need to fopen this file to read its contents.

scanf("%s", buf) is an unsafe way to read a word from stdin. You must pass a pointer to a char array, not an uninitialized pointer as you do in the fragment posted. scanf() will write to the memory pointed to by this pointer, so an uninitialized pointer will cause undefined behavior, probably a crash.

To use scanf() safely, you must provide the maximum number of characters to store into the destination array, otherwise a long enough word in the inoput file will cause scanf() to write beyond the end of the array, causing undefined behavior as well. Here is an example of this:

```<code>    // filtering 4 letter words:
    char buf[100];
    while (scanf("%99s", buf) == 1) {
        if (strlen(buf) == 4)
            printf("%s\n", buf);
    }
</code>```

If you want to pass the path of the input file, use command line arguments.

The bash command would become:

```<code>./a.out /usr/share/dict/words > out.txt 2> out2.txt
</code>```

And the main function:

#include <errno.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[) {
    FILE *fp;
    if (argc < 2) {
        fprintf(stderr, "%s: missing file name argument\n", argv[0]);
        return 1;
    }
    if ((fp = fopen(argv[1], "r")) == NULL) {
        fprintf(stderr, "%s: cannot open file %s: %s\n",
                argv[0], argv[1], strerror(errno));
        return 1;
    }
    // for example's sake: filtering 4 letter words:
    char buf[100];
    while (fscanf(fp, "%99s", buf) == 1) {
        if (strlen(buf) == 4)
            printf("%s\n", buf);
    }
    fclose(fp);
    return 0;
}
```

Title: get file path from stdin in C

Body:
I am trying to pass a file to my program however it always gives error, cannot open file.

My command is: (I am on desktop path, I am using ubuntu)

./out < /usr/share/dict/words > out.txt 2> out2.txt

Output files are created but file input seems empty. I am getting file path as:

char *infile;
scanf("%s", infile);
printf("file: %s\n", infile);

I also tried:

fscanf(stdin, "%s", infile);

Nothing changed. Also, I have to take input as shown above, I know < means stdin but I cannot read its content somehow.

This is file opening part and error message:

 file = fopen(infile, "r");
 if (file == 0) {
     fprintf(stderr, "File failed\n");
     return 1;
 }

Body:
There seem to be some confusion in your approach:

you redirect input to your program from a text file containing words, the classic /usr/share/dict/words file. This file is the input to your program, you can read the contents with getchar(), scanf(), fgets() and other stream input functions, but the name of the file is not available to your program, nor do you need to fopen this file to read its contents.

scanf("%s", buf) is an unsafe way to read a word from stdin. You must pass a pointer to a char array, not an uninitialized pointer as you do in the fragment posted. scanf() will write to the memory pointed to by this pointer, so an uninitialized pointer will cause undefined behavior, probably a crash.

To use scanf() safely, you must provide the maximum number of characters to store into the destination array, otherwise a long enough word in the inoput file will cause scanf() to write beyond the end of the array, causing undefined behavior as well. Here is an example of this:

    // filtering 4 letter words:
    char buf[100];
    while (scanf("%99s", buf) == 1) {
        if (strlen(buf) == 4)
            printf("%s\n", buf);
    }

If you want to pass the path of the input file, use command line arguments.

The bash command would become:

./a.out /usr/share/dict/words > out.txt 2> out2.txt

And the main function:

#include <errno.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[) {
    FILE *fp;
    if (argc < 2) {
        fprintf(stderr, "%s: missing file name argument\n", argv[0]);
        return 1;
    }
    if ((fp = fopen(argv[1], "r")) == NULL) {
        fprintf(stderr, "%s: cannot open file %s: %s\n",
                argv[0], argv[1], strerror(errno));
        return 1;
    }
    // for example's sake: filtering 4 letter words:
    char buf[100];
    while (fscanf(fp, "%99s", buf) == 1) {
        if (strlen(buf) == 4)
            printf("%s\n", buf);
    }
    fclose(fp);
    return 0;
}


问:
wpf toolkit line chart without points and with different line colors
I have some chart and I want to add dynamicly LineSeries without DataPoints, just lines with some custom colors. The only way I found to hide data points is:

```<code>Style style = new Style(typeof(LineDataPoint));
style.Setters.Add(new Setter(LineDataPoint.TemplateProperty, null));

var series = new LineSeries()
{
      Title = name,
      DependentValuePath = "Y",
      IndependentValuePath = "X",
      ItemsSource = new ObservableCollection<FloatingPoint>(),
      DataPointStyle = style,

        };
</code>```

Unfortunately when I do this all lines become yellow and I can't change their colors.
I tried to do this:

```<code>Style style = new Style(typeof(LineDataPoint));
        style.Setters.Add(new Setter(LineDataPoint.TemplateProperty, null));

        SolidColorBrush brush = new SolidColorBrush(Colors.Red);

        var series = new LineSeries()
        {
            Title = name,
            DependentValuePath = "Y",
            IndependentValuePath = "X",
            ItemsSource = new ObservableCollection<FloatingPoint>(),
            DataPointStyle = style,
            Background = brush,

        };
</code>```

But it doesn't help - I can't change line color... Even if I write

```<code>series.Background = brush;
</code>```

答:
Try this.</p>

```<code>                    series = new LineSeries();
                    Style dataPointStyle = GetNewDataPointStyle();
                    series.DataPointStyle = dataPointStyle;

    /// <summary>
    /// Gets the new data point style.
    /// </summary>
    /// <returns></returns>
    private static Style GetNewDataPointStyle()
    {
        Color background = Color.FromRgb((byte)random.Next(255),
                                         (byte)random.Next(255),
                                         (byte)random.Next(255));
        Style style = new Style(typeof(DataPoint));
        Setter st1 = new Setter(DataPoint.BackgroundProperty,
                                    new SolidColorBrush(background));
        Setter st2 = new Setter(DataPoint.BorderBrushProperty,
                                    new SolidColorBrush(Colors.White));
        Setter st3 = new Setter(DataPoint.BorderThicknessProperty, new Thickness(0.1));

        Setter st4 = new Setter(DataPoint.TemplateProperty, null);
        style.Setters.Add(st1);
        style.Setters.Add(st2);
        style.Setters.Add(st3);
        style.Setters.Add(st4);
        return style;
    }
</code>```

Body:
I have some chart and I want to add dynamicly LineSeries without DataPoints, just lines with some custom colors. The only way I found to hide data points is:

Style style = new Style(typeof(LineDataPoint));
style.Setters.Add(new Setter(LineDataPoint.TemplateProperty, null));

var series = new LineSeries()
{
      Title = name,
      DependentValuePath = "Y",
      IndependentValuePath = "X",
      ItemsSource = new ObservableCollection<FloatingPoint>(),
      DataPointStyle = style,

        };

Unfortunately when I do this all lines become yellow and I can't change their colors.
I tried to do this:

Style style = new Style(typeof(LineDataPoint));
        style.Setters.Add(new Setter(LineDataPoint.TemplateProperty, null));

        SolidColorBrush brush = new SolidColorBrush(Colors.Red);

        var series = new LineSeries()
        {
            Title = name,
            DependentValuePath = "Y",
            IndependentValuePath = "X",
            ItemsSource = new ObservableCollection<FloatingPoint>(),
            DataPointStyle = style,
            Background = brush,

        };

But it doesn't help - I can't change line color... Even if I write

series.Background = brush;

Body:
Try this.

                    series = new LineSeries();
                    Style dataPointStyle = GetNewDataPointStyle();
                    series.DataPointStyle = dataPointStyle;

    /// <summary>
    /// Gets the new data point style.
    /// </summary>
    /// <returns></returns>
    private static Style GetNewDataPointStyle()
    {
        Color background = Color.FromRgb((byte)random.Next(255),
                                         (byte)random.Next(255),
                                         (byte)random.Next(255));
        Style style = new Style(typeof(DataPoint));
        Setter st1 = new Setter(DataPoint.BackgroundProperty,
                                    new SolidColorBrush(background));
        Setter st2 = new Setter(DataPoint.BorderBrushProperty,
                                    new SolidColorBrush(Colors.White));
        Setter st3 = new Setter(DataPoint.BorderThicknessProperty, new Thickness(0.1));

        Setter st4 = new Setter(DataPoint.TemplateProperty, null);
        style.Setters.Add(st1);
        style.Setters.Add(st2);
        style.Setters.Add(st3);
        style.Setters.Add(st4);
        return style;
    }


问:
Python-My string variable won't add up into one string
I seem to be having issues adding a String together.

I wrote a function which I keep calling up to decode or encode a string.

The issue is when I print the result it only works to print one char out, not the whole code.

Outside of the function this method work though by adding letter after letter.

Here I use numbers.

```<code>def code(s,i):
  result = ""
  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1)
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1)
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return
</code>```

For example if I put in: 01

I expect the result: 3

                     34

But it only prints: 3

                    4

So basically results after replaying deletes/overrides what was in the string before.

I want to print result in one string, not multiple line after line.

This is only part of my code cut short. Why won't result add up?

This is how I defined entered.

entered = input("Please type something.")

答:
I found a solution to my issue.

Everytime I recalled the function it resetted my code, so I passed result as a
parameter of my function:

```<code>def code(s,i,result):

  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1,result)
      return
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1,result)
      return
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return

</code>```

Now result prints out what I needed, thanks for any help! ^^

Body:
I seem to be having issues adding a String together.

I wrote a function which I keep calling up to decode or encode a string.

The issue is when I print the result it only works to print one char out, not the whole code.

Outside of the function this method work though by adding letter after letter.

Here I use numbers.

def code(s,i):
  result = ""
  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1)
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1)
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return

For example if I put in: 01

I expect the result: 3

                     34

But it only prints: 3

                    4

So basically results after replaying deletes/overrides what was in the string before.

I want to print result in one string, not multiple line after line.

This is only part of my code cut short. Why won't result add up?

This is how I defined entered.

entered = input("Please type something.")

Body:
I found a solution to my issue.

Everytime I recalled the function it resetted my code, so I passed result as a
parameter of my function:

def code(s,i,result):

  if i < len(s):
    if s[i] == '0':
      result += "3"
      print (result)
      code(s,i+1,result)
      return
    if s[i] == '1':
      result += "4"
      print (result)
      code(s,i+1,result)
      return
    else:
      print ("An Error seems to have occured.")
  else:
    print("Code is done.")
  return

Now result prints out what I needed, thanks for any help! ^^


问:
Java Hash Map(several values for 1 key)
how can I add several values to one key in Hash Map?

```<code>HashMap<String, ArrayList<String>> phonebook = new HashMap<>();
</code>```

For example, I want to phonebook.put("Mike","123") phonebook.put("Mike","321")
And then I want to get all the values for key Mike.

答:
You can use computeIfAbsent for that.

```<code>phonebook.computeIfAbsent("Mike", k -> new ArrayList<>()).add("123");
phonebook.computeIfAbsent("Mike", k -> new ArrayList<>()).add("321");
</code>```

Which would avoid checking if a key exists prior to an insert and if concurrency matters that would be an atomic operation.

Title: Java Hash Map(several values for 1 key)

Body:
how can I add several values to one key in Hash Map?

HashMap<String, ArrayList<String>> phonebook = new HashMap<>();

For example, I want to phonebook.put("Mike","123") phonebook.put("Mike","321")
And then I want to get all the values for key Mike.

Body:
You can use computeIfAbsent for that.

phonebook.computeIfAbsent("Mike", k -> new ArrayList<>()).add("123");
phonebook.computeIfAbsent("Mike", k -> new ArrayList<>()).add("321");

Which would avoid checking if a key exists prior to an insert and if concurrency matters that would be an atomic operation.


问:
Using graphql.config.js and apollo.config.js with ApolloClient
How can I use graphql.config.js and apollo.config.js with ApolloClient? I want client to read graphql endpoint from the config file.

Also, is it possible to use graphql.config.js with Apollo VS Code extension?

答:
For the Apollo Client you need to pass the endpoint yourself as specified in the docs. But if you absolutely need to read the endpoint from a config file, I guess you could use the cosmiconfig library to get the configuration values and pass them yourself to the client.

For the VSCode I do not think this is currently possible. The VS Code extension is using the cosmiconfig library internally to load the configuration. The module name is hard coded to apollo.


答:
You can't insert values to ArrayList like that, you need to initialize it first and than use add. You can use computeIfAbsent  for that

```<code>public void addToList(HashMap<String, ArrayList<String>> phonebook, String key, String value) {
    phonebook.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}

HashMap<String, ArrayList<String>> phonebook = new HashMap<>();
addToList(phonebook, "Mike", "123");
addToList(phonebook, "Mike", "321");
</code>```

To get all the values use get() to get a list

```<code>System.out.print(phonebook.get("Mike")); // [123, 321]
</code>```

Or

```<code>for (String number: phonebook.get("Mike")) {
    System.out.println(number);
}
</code>```

And to get all the values in the map

```<code>for (String key: phonebook.keySet()) {
    System.out.println(key + ": ");
    for (String number: phonebook.get(key)) {
        System.out.println(number);
    }
}
</code>```

Title: Java Hash Map(several values for 1 key)

Body:
You can't insert values to ArrayList like that, you need to initialize it first and than use add. You can use computeIfAbsent  for that

public void addToList(HashMap<String, ArrayList<String>> phonebook, String key, String value) {
    phonebook.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}

HashMap<String, ArrayList<String>> phonebook = new HashMap<>();
addToList(phonebook, "Mike", "123");
addToList(phonebook, "Mike", "321");

To get all the values use get() to get a list

System.out.print(phonebook.get("Mike")); // [123, 321]

Or

for (String number: phonebook.get("Mike")) {
    System.out.println(number);
}

And to get all the values in the map

for (String key: phonebook.keySet()) {
    System.out.println(key + ": ");
    for (String number: phonebook.get(key)) {
        System.out.println(number);
    }
}


问:
Where does the word "Pascal Case" come from?
In general, there are four common case styles.

camelCase

PascalCase

snake_case

kebab-case

Etymology of first, third and fourth styles are trivial. But what about second one (i.e. PascalCase)?

According to wikitionary,

Etymology

Referring to the Pascal programming language.

and the link only says

Letter case is ignored in Pascal source.

According to Free Pascal wiki,

Rules for identifiers:

Must begin with a letter from the English alphabet or an underscore (_).

Can be followed by alphanumeric characters (alphabetic characters and numerals), or the underscore (_).

May not contain special characters, such as: ~ ! @ # ...

(snip)

Pascal is not case sensitive! MyProgram, MYPROGRAM, and mYpRoGrAm are equivalent. But for readability purposes, it is a good idea to use meaningful capitalization!

There are two possible methods you could choose to apply to your identifiers: CamelCase and underscore as space. CamelCase, as it appears, means that separate words in an identifier are capitalized, so that you have newPerson or NewPerson instead of newperson. Using underscore as space means you separate words in an identifier with underscores, so that you have new_person instead of newperson. Or you could combine the two, so that you have new_Person or New_Person instead of newperson.

, which implies it is not required to use a camel-case identifier such as StackOverflow or RedHatLinux.

Then, where does the word "camel case" come from? Did pascal programmers first started using PascalCase style?

答:
The history about putting words together using casing goes back a long time.

From Capitalize My Title:

CamelCase was primarily used in chemistry as a way to notate chemical compounds and formulas. In 1813, Berzelius, a Swedish chemist, suggested that the chemical elements should be represented consisting of one or two letters with the first one capitalized. The term used for this convention was medical capitals.

A step into the twentieth century:

In the early twentieth century, medical capitals used in Chemistry has been adopted in product trademarks and corporate names. However, the use is not yet prevalent. Some examples of these products include DryIce Corporation, CinemaScope, a widescreen movie format, MisterRogers, and VistaVision, among others.

And in programming language:

Around the 1970s and 1980s, the use of medical capitals was also adopted as an alternative naming convention for identifiers in various programming languages. For instance, on the General Purpose Macro Processor (GPM) by Christopher Strachey, a program includes identifiers using medical capitals. These include “WriteSymbol,” and “NextCh.”

Late 1990s:

By the late 1990s, the lower camel case became a popular trend in many brands. The lowercase for “i” which may stand for internet, information, or intelligent, and “e” which stands for electronic, became prefixes to various words. Examples of these words include eBay, iMac, eBox, and iPod.

The name CamelCase:

The term CamelCase only came into existence in the 1990s. Before that, the term medical capitals was commonly used. In April 1990, the term “InterCaps” was used by Avi Rappoport to describe the manner of capitalization. In 1991, Eric S. Raymond made mention of BiCapitalization to identify it.

It was not until 1995, however, that its current name was used. In a post by Newton Love, he mentioned that the humpiness of the style made him call it HumpyCase at first, before settling with CamelCase.

The origin of the name PascalCasing (from History around Pascal Casing and Camel Casing):

In the initial design of the Framework we had hundreds of hours of debate about naming style.  To facilitate these debates we coined a number of terms.  With Anders Heilsberg (the original designer of Turbo Pascal) a key member of the design team, it is no wonder that we chose the term Pascal Casing for the casing style popularized by the Pascal programming language.

We were somewhat cute in using the term camelCasing for the casing style that looks something like the humps on a camel.  We used the term SCREAMING CAPS to indicate an all upper case style. Luckily this style (and name) did not survive in the final guideline.

```<code>>Did pascal programmers first started using PascalCase style?
</code>```

No, it was a common convention at that time when programming languages was evolved.

More references about Camel Case

Body:
The history about putting words together using casing goes back a long time.

From Capitalize My Title:

CamelCase was primarily used in chemistry as a way to notate chemical compounds and formulas. In 1813, Berzelius, a Swedish chemist, suggested that the chemical elements should be represented consisting of one or two letters with the first one capitalized. The term used for this convention was medical capitals.

A step into the twentieth century:

In the early twentieth century, medical capitals used in Chemistry has been adopted in product trademarks and corporate names. However, the use is not yet prevalent. Some examples of these products include DryIce Corporation, CinemaScope, a widescreen movie format, MisterRogers, and VistaVision, among others.

And in programming language:

Around the 1970s and 1980s, the use of medical capitals was also adopted as an alternative naming convention for identifiers in various programming languages. For instance, on the General Purpose Macro Processor (GPM) by Christopher Strachey, a program includes identifiers using medical capitals. These include “WriteSymbol,” and “NextCh.”

Late 1990s:

By the late 1990s, the lower camel case became a popular trend in many brands. The lowercase for “i” which may stand for internet, information, or intelligent, and “e” which stands for electronic, became prefixes to various words. Examples of these words include eBay, iMac, eBox, and iPod.

The name CamelCase:

The term CamelCase only came into existence in the 1990s. Before that, the term medical capitals was commonly used. In April 1990, the term “InterCaps” was used by Avi Rappoport to describe the manner of capitalization. In 1991, Eric S. Raymond made mention of BiCapitalization to identify it.

It was not until 1995, however, that its current name was used. In a post by Newton Love, he mentioned that the humpiness of the style made him call it HumpyCase at first, before settling with CamelCase.

The origin of the name PascalCasing (from History around Pascal Casing and Camel Casing):

In the initial design of the Framework we had hundreds of hours of debate about naming style.  To facilitate these debates we coined a number of terms.  With Anders Heilsberg (the original designer of Turbo Pascal) a key member of the design team, it is no wonder that we chose the term Pascal Casing for the casing style popularized by the Pascal programming language.

We were somewhat cute in using the term camelCasing for the casing style that looks something like the humps on a camel.  We used the term SCREAMING CAPS to indicate an all upper case style. Luckily this style (and name) did not survive in the final guideline.

>Did pascal programmers first started using PascalCase style?

No, it was a common convention at that time when programming languages was evolved.

More references about Camel Case


问:
Remove duplicates from the string in CPP
I wrote the following code for removing the duplicates from a given string i.e. if ARRUN is the input then the output will be ARUN.

```<code>#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(string &s,int n){
    char arr[n];
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    return arr;
}

//driver code
int main(){
    string str;
    cin >> str;
    cout<<removeDuplicates(str,str.length())<<endl;
    return 0;
}
</code>```

The code produces no output at all, however, it works fine if I use char arr[] instead of string class.

答:
@Arun Suryan, You pointed out correctly. But you can do it without using vector by using global char array.

Also don't forget to append the newline at the end!

Have a look at the following code:

```<code>#include<string>
#include<iostream>
#include<unordered_map>

char* removeDuplicates(std::string &s,int n){

    std::unordered_map<char,int> exists;
    char* arr = (char*)(malloc(n*sizeof(char)));
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    arr[index] = '\n';
    return arr;
}

//driver code
int main(){
    std::string str;
    std::cin >> str;
    std::cout<<removeDuplicates(str,str.length())<<std::endl;
    return 0;
}
</code>```

Body:
I wrote the following code for removing the duplicates from a given string i.e. if ARRUN is the input then the output will be ARUN.

#include <bits/stdc++.h>
using namespace std;
char* removeDuplicates(string &s,int n){
    char arr[n];
    unordered_map<char,int> exists;
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    return arr;
}

//driver code
int main(){
    string str;
    cin >> str;
    cout<<removeDuplicates(str,str.length())<<endl;
    return 0;
}

The code produces no output at all, however, it works fine if I use char arr[] instead of string class.

Body:
@Arun Suryan, You pointed out correctly. But you can do it without using vector by using global char array.

Also don't forget to append the newline at the end!

Have a look at the following code:

#include<string>
#include<iostream>
#include<unordered_map>

char* removeDuplicates(std::string &s,int n){

    std::unordered_map<char,int> exists;
    char* arr = (char*)(malloc(n*sizeof(char)));
    int index = 0;
    for(int i=0;i<n;i++){
        if(exists[s[i]]==0)
        {
            arr[index++] = s[i];
            exists[s[i]]++;
        }
    }
    arr[index] = '\n';
    return arr;
}

//driver code
int main(){
    std::string str;
    std::cin >> str;
    std::cout<<removeDuplicates(str,str.length())<<std::endl;
    return 0;
}


问:
LinearRegression Predict: No applicable method for 'predict' applied to an object of class "data.Frame"
I have my data (currently dummy data):

```<code>data_for_prediction <- original_data[,c(1,3)]
</code>```

if you want to reproduce the issues the following is enough for this error:

```<code>data_for_prediction <- data.frame(
  diff = c(1,2,3),
  f.mean_slope = c (1,2,3)
)
</code>```

which consists of only two rows: "diff" (Y) and "f.mean_slope" (x)

then I sample the whole thing:

```<code>set.seed(101)
trainingRowIndex <- sample(1:nrow(data_for_prediction), 0.8*nrow(data_for_prediction))
trainingData <- data_for_prediction[trainingRowIndex, ]
testData  <- data_for_prediction[-trainingRowIndex, ]
</code>```

After that I create a fit:

```<code>model_fit <- lm(diff ~ ., data = trainingData, method = "model.frame")
</code>```

And when I now try to predict something:

```<code>newdata <- data.frame(
  f.mean_slope = c(1,2,3)
)

distPred <- predict(model_fit, newdata)
</code>```

And R Studio then just return the error message:

Error in UseMethod("predict"): No applicable method for 'predict' applied to an object of class "data.Frame"

Which drives me nuts, since I've searched tons of questions of the internet with a somewhat similar problem, but none worked...

Does anybody have an idea?

答:
That's because you used:

```<code>model_fit <- lm(diff ~ ., data = trainingData, method = "model.frame")
class(model_fit)
[1] "data.frame"
</code>```

The above gives you the model matrix used to fit the data.

You can do instead:

```<code>model_fit <- lm(diff ~ ., data = trainingData,model=TRUE)
newdata <- data.frame(
  f.mean_slope = c(1,2,3)
)

distPred <- predict(model_fit, newdata)
</code>```

And the model matrix can be found in model_fit$model

Body:
I have my data (currently dummy data):

data_for_prediction <- original_data[,c(1,3)]

if you want to reproduce the issues the following is enough for this error:

data_for_prediction <- data.frame(
  diff = c(1,2,3),
  f.mean_slope = c (1,2,3)
)

which consists of only two rows: "diff" (Y) and "f.mean_slope" (x)

then I sample the whole thing:

set.seed(101)
trainingRowIndex <- sample(1:nrow(data_for_prediction), 0.8*nrow(data_for_prediction))
trainingData <- data_for_prediction[trainingRowIndex, ]
testData  <- data_for_prediction[-trainingRowIndex, ]

After that I create a fit:

model_fit <- lm(diff ~ ., data = trainingData, method = "model.frame")

And when I now try to predict something:

newdata <- data.frame(
  f.mean_slope = c(1,2,3)
)

distPred <- predict(model_fit, newdata)

And R Studio then just return the error message:

Error in UseMethod("predict"): No applicable method for 'predict' applied to an object of class "data.Frame"

Which drives me nuts, since I've searched tons of questions of the internet with a somewhat similar problem, but none worked...

Does anybody have an idea?

Body:
That's because you used:

model_fit <- lm(diff ~ ., data = trainingData, method = "model.frame")
class(model_fit)
[1] "data.frame"

The above gives you the model matrix used to fit the data.

You can do instead:

model_fit <- lm(diff ~ ., data = trainingData,model=TRUE)
newdata <- data.frame(
  f.mean_slope = c(1,2,3)
)

distPred <- predict(model_fit, newdata)

And the model matrix can be found in model_fit$model


问:
In a hexagon graph, how do I store 3D coordinates as an index for a 1D container / retrieve an element from a 1D container using 3D coordinates?
I'm trying to store a graph of hexagons using cubical coordinates as detailed at https://www.redblobgames.com/grids/hexagons/#coordinates

I want to use a vector or some easily iteratable container to store Hex objects, basically collections of 3D integer coordinates plus a vector containing indexes of adjacent Hexes.

My problem is that I am having trouble coming up with functions to convert cubical X/Y/Z coordinates (which allows for negative integer values) into corresponding 1D container indices. Given any valid set of coordinates, I want to be able to get the particular index number of the hex.

I am aware of a function that works like

1D_index = f(x,y,z) = x + (max_width)*y + (max_width)(max_height)*z,

for an Cartesian grid, but I am having trouble producing a similar function for in hexagon space:

My Hex class and container is as such:

```<code>class Hex
{
private:
    int xCell, yCell, zCell;
    std::vector<int>neighbours;

public:
    Hex();
    Hex(int x, int y, int z) : _x(x), _y(y), _z(z);
    ~Hex();
};

std::vector<Hex*>hexGraph;
</code>```

To populate the graph with unconnected nodes, I am using just listing all the coordinates that can exist, given the graph's positive and negative x/y/z dimensions:

```<code>
for(int x = effectiveWorldNegX; x < effectiveWorldPosX; x++)
        for(int y = effectiveWorldPosY; y > effectiveWorldNegY; y--)
            hexGraph.push_back(new Hex(x,y,(x*-1)-y)); // x+y+z=0, so z=(-x-y)
</code>```

Now here is where I am stumped. I want to connect the nodes using a loop like this:

```<code>for(std::vector<Hex*>iterator it = hexGraph.begin(); it != hexGraph.end(); ++it)
{
(*it)->neighbours.push_back( /* Index of upper left hex node */ )
(*it)->neighbours.push_back( /* Index of upper center hex node */ )
(*it)->neighbours.push_back( /* Index of upper right hex node */ )
...

}

</code>```

And so on, but in order to do so, I need a way to find the index of, say, any cell +1x, -1y, +0z.

From the loop above, all I have determined is
1) the exact order that the Hexes are pushed back into the hexGraph vector, given the start/end of my loops

2) I may or may not need to offset all coordinate values by the negative X/Y/Z's distance from 0 to remove negatives

but where can I go from here?

Help is very much appreciated.

答:
One way of solving the issue is to give an id to every Vertex of the graph and then reference neighbour vertices by id's.

Example

```<code>using VertexId = size_t;

class Hex {
    std::vector<VertexId>neighbours;
  public:
    Hex(int x, int y, int z);
};

class VertexStorage {
    std::unordered_map<VertexId, Hex> _id_to_hex;
    std::unordered_map<Hex, VertexId> _hex_to_id;
  public:
    // check if hex is in storage, return id
    // if not, assign new id an push tostorage
    // id could be increasing counter
    VertexId getId(const Hex &hex);
    Hex getHex(VertexId id);
};
</code>```

Body:
I'm trying to store a graph of hexagons using cubical coordinates as detailed at https://www.redblobgames.com/grids/hexagons/#coordinates

I want to use a vector or some easily iteratable container to store Hex objects, basically collections of 3D integer coordinates plus a vector containing indexes of adjacent Hexes.

My problem is that I am having trouble coming up with functions to convert cubical X/Y/Z coordinates (which allows for negative integer values) into corresponding 1D container indices. Given any valid set of coordinates, I want to be able to get the particular index number of the hex.

I am aware of a function that works like

1D_index = f(x,y,z) = x + (max_width)*y + (max_width)(max_height)*z,

for an Cartesian grid, but I am having trouble producing a similar function for in hexagon space:

My Hex class and container is as such:

class Hex
{
private:
    int xCell, yCell, zCell;
    std::vector<int>neighbours;

public:
    Hex();
    Hex(int x, int y, int z) : _x(x), _y(y), _z(z);
    ~Hex();
};

std::vector<Hex*>hexGraph;

To populate the graph with unconnected nodes, I am using just listing all the coordinates that can exist, given the graph's positive and negative x/y/z dimensions:

for(int x = effectiveWorldNegX; x < effectiveWorldPosX; x++)
        for(int y = effectiveWorldPosY; y > effectiveWorldNegY; y--)
            hexGraph.push_back(new Hex(x,y,(x*-1)-y)); // x+y+z=0, so z=(-x-y)

Now here is where I am stumped. I want to connect the nodes using a loop like this:

for(std::vector<Hex*>iterator it = hexGraph.begin(); it != hexGraph.end(); ++it)
{
(*it)->neighbours.push_back( /* Index of upper left hex node */ )
(*it)->neighbours.push_back( /* Index of upper center hex node */ )
(*it)->neighbours.push_back( /* Index of upper right hex node */ )
...

}

And so on, but in order to do so, I need a way to find the index of, say, any cell +1x, -1y, +0z.

From the loop above, all I have determined is
1) the exact order that the Hexes are pushed back into the hexGraph vector, given the start/end of my loops

2) I may or may not need to offset all coordinate values by the negative X/Y/Z's distance from 0 to remove negatives

but where can I go from here?

Help is very much appreciated.

Body:
One way of solving the issue is to give an id to every Vertex of the graph and then reference neighbour vertices by id's.

Example

using VertexId = size_t;

class Hex {
    std::vector<VertexId>neighbours;
  public:
    Hex(int x, int y, int z);
};

class VertexStorage {
    std::unordered_map<VertexId, Hex> _id_to_hex;
    std::unordered_map<Hex, VertexId> _hex_to_id;
  public:
    // check if hex is in storage, return id
    // if not, assign new id an push tostorage
    // id could be increasing counter
    VertexId getId(const Hex &hex);
    Hex getHex(VertexId id);
};


问:
Exception on Java.time Package
I'm using Hibernate 5.0.0CR1 for it's ability to use the JDK8 time package, but I'm getting an exception at this code when I try to persist an entity. Can someone tell me what is happening, and how to fix it? I'm using the EntityManager API's.

Mapping:

```<code>@Temporal(TemporalType.TIMESTAMP)
@Column(name = "Creation_Date", nullable = false)
private final ZonedDateTime creationDate;
</code>```

Exception:

```<code>Caused by: org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property
</code>```

答:
I also faced similar issue while I was converting from Date to ZonedDateTime, you can apply annotation '@CreationTimestamp' instead of  @Temporal(TemporalType.TIMESTAMP) and it will work; </p>

```<code>@CreationTimestamp
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private final ZonedDateTime creationDate;
</code>```

Title: Exception on Java.time Package

Body:
I'm using Hibernate 5.0.0CR1 for it's ability to use the JDK8 time package, but I'm getting an exception at this code when I try to persist an entity. Can someone tell me what is happening, and how to fix it? I'm using the EntityManager API's.

Mapping:

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "Creation_Date", nullable = false)
private final ZonedDateTime creationDate;

Exception:

Caused by: org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property

Body:
I also faced similar issue while I was converting from Date to ZonedDateTime, you can apply annotation '@CreationTimestamp' instead of  @Temporal(TemporalType.TIMESTAMP) and it will work;

@CreationTimestamp
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private final ZonedDateTime creationDate;


问:
IDN conversion failed
I built a system with laravel-admin and guzzle. I send api requests to Shopify with Guzzle and everything works fine on my local environment. However, when I try to create a product in production , it gives me this error.

IDN conversion failed

I looked into it on Google, and it seems Guzzle is giving me this error because I get the error only when I try to create the kinds of products that I sync with Shopify with guzzle.

There is not much information about the error on Google, and I am lost as to why it is happening. Has anyone experienced the same issue?

答:
Could you please add PHP and Guzzle versions to the question? I'm one of the authors of this feature, and (unfortunately) there were some issues related in specific cases. But to say something I need more details.

Generally, try to upgrade to the latest version. Things probably should be fine with the latest Guzzle 6.5.2.

Title: IDN conversion failed


答:
You can't use char arr[n] without being n constant or constexpr.

You don't need map. set is sufficient.

Note that map and set remove duplicates already, then you can check if any element is inserted or not to get your new string in the same order of the first, as follows

```<code>#include<string>
#include<iostream>
#include<unordered_set>

std::string removeDuplicates(const std::string &s){
    std::string arr;
    std::unordered_set<char> exists;

    for(const auto&el:s)
        if(exists.insert(el).second) arr+=el;

    return arr;
}

//driver code
int main(){
    std::string str;
    std::cin >> str;
    std::cout<<removeDuplicates(str)<<std::endl;
    return 0;
}
</code>```

Title: Remove duplicates from the string in CPP

Body:
You can't use char arr[n] without being n constant or constexpr.

You don't need map. set is sufficient.

Note that map and set remove duplicates already, then you can check if any element is inserted or not to get your new string in the same order of the first, as follows

#include<string>
#include<iostream>
#include<unordered_set>

std::string removeDuplicates(const std::string &s){
    std::string arr;
    std::unordered_set<char> exists;

    for(const auto&el:s)
        if(exists.insert(el).second) arr+=el;

    return arr;
}

//driver code
int main(){
    std::string str;
    std::cin >> str;
    std::cout<<removeDuplicates(str)<<std::endl;
    return 0;
}


问:
Access instance variables from an activity inside a AsyncTask
I have an AsyncTask (in a separate file) which is invoked on an
activity. When I instantiate the AsyncTask, I send the activity as a
param. How can I access the acitivity's instance variables from the
onPostExecute method of the AsyncTask?

Thanks!

答:
Similar to Programmer Bruce's answer but instead of passing the Activity as a Param through the AsyncTask itself, simply add a constructor to take the parent Activity. Example from my own code...

```<code>public class FileDownloader extends AsyncTask<..., ..., ...> {
    private MyActivity parentActivity = null;

    public FileDownloader(MyActivity parentActivity) {
        this.parentActivity = parentActivity;
    }
}
</code>```

When you create it in your Activity just do this...

```<code>FileDownloader fdl = new FileDownloader(this);
fdl.execute(...);
</code>```

EDIT: In reply to your comment, make sure mLogin is declared as public then use...

```<code>parentActivity.mLogin
</code>```

If that doesn't work, try...

```<code>((MyActivity)parentActivity).mLogin
</code>```

Body:
Similar to Programmer Bruce's answer but instead of passing the Activity as a Param through the AsyncTask itself, simply add a constructor to take the parent Activity. Example from my own code...

public class FileDownloader extends AsyncTask<..., ..., ...> {
    private MyActivity parentActivity = null;

    public FileDownloader(MyActivity parentActivity) {
        this.parentActivity = parentActivity;
    }
}

When you create it in your Activity just do this...

FileDownloader fdl = new FileDownloader(this);
fdl.execute(...);

EDIT: In reply to your comment, make sure mLogin is declared as public then use...

parentActivity.mLogin

If that doesn't work, try...

((MyActivity)parentActivity).mLogin


问:
Where do I put my error trapping for password here?
So my error-trapped code for password is this

```<code>if (txtPassword.Text != txtConfirmPassword.Text)
    lblErrorMessage.Text = "Password do not match!";
</code>```

I'm having a hard time where will I put it since I always get an error.

```<code>btnSave_Click(object sender, EventArgs e)
{
    if (sqlCon.State == ConnectionState.Closed)
        sqlCon.Open();
        SqlCommand sqlCmd = new SqlCommand("UserCreateOrUpdate",sqlCon);
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Parameters.AddWithValue("@UserID",(hfUserID.Value==""?0:Convert.ToInt32(hfUserID.Value)));
        sqlCmd.Parameters.AddWithValue("@FName",txtFName.Text.Trim());
        sqlCmd.Parameters.AddWithValue("@LName",txtLName.Text.Trim());
        sqlCmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
        sqlCmd.Parameters.AddWithValue("@Password", txtPassword.Text);
        sqlCmd.ExecuteNonQuery();
        sqlCon.Close();
        string userID = hfUserID.Value;
    Clear();
    if (userID == "")
        lblSuccessMessage.Text = "Saved Successfully";
    else
        lblSuccessMessage.Text = "Updated Successfully";
    FillGridView();
}
</code>```

答:
Please Attention TODO Help In Code. </p>

```<code>  btnSave_Click(object sender, EventArgs e)
        {
               bool isUpdate=false;

                if (txtPassword.Text != txtConfirmPassword.Text)
                    lblErrorMessage.Text = "Password do not match!";

                if (sqlCon.State == ConnectionState.Closed)
                    sqlCon.Open();

                if(hfUserID.Value!="")
                {
               // TODO: Check UserId there is In Table Or not(Similar to the bottom ADO.net).
               // TODO: then If Exist then isUpdate=true else isUpdate=false
                }

                SqlCommand sqlCmd = new SqlCommand("UserCreateOrUpdate",sqlCon);
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@UserID",(hfUserID.Value==""?0:Convert.ToInt32(hfUserID.Value)));
                sqlCmd.Parameters.AddWithValue("@FName",txtFName.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@LName",txtLName.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Password", txtPassword.Text);

                int a= sqlCmd.ExecuteNonQuery();

                sqlCon.Close();

                Clear();

            if (a==0)
                lblSuccessMessage.Text =isUpdate? "Not updated.":"Not Saved";
            else
                lblSuccessMessage.Text = isUpdate? "Updated." : "Saved";

            FillGridView();
        }
</code>```

Body:
So my error-trapped code for password is this

if (txtPassword.Text != txtConfirmPassword.Text)
    lblErrorMessage.Text = "Password do not match!";

I'm having a hard time where will I put it since I always get an error.

btnSave_Click(object sender, EventArgs e)
{
    if (sqlCon.State == ConnectionState.Closed)
        sqlCon.Open();
        SqlCommand sqlCmd = new SqlCommand("UserCreateOrUpdate",sqlCon);
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Parameters.AddWithValue("@UserID",(hfUserID.Value==""?0:Convert.ToInt32(hfUserID.Value)));
        sqlCmd.Parameters.AddWithValue("@FName",txtFName.Text.Trim());
        sqlCmd.Parameters.AddWithValue("@LName",txtLName.Text.Trim());
        sqlCmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
        sqlCmd.Parameters.AddWithValue("@Password", txtPassword.Text);
        sqlCmd.ExecuteNonQuery();
        sqlCon.Close();
        string userID = hfUserID.Value;
    Clear();
    if (userID == "")
        lblSuccessMessage.Text = "Saved Successfully";
    else
        lblSuccessMessage.Text = "Updated Successfully";
    FillGridView();
}

Body:
Please Attention TODO Help In Code.

  btnSave_Click(object sender, EventArgs e)
        {
               bool isUpdate=false;

                if (txtPassword.Text != txtConfirmPassword.Text)
                    lblErrorMessage.Text = "Password do not match!";

                if (sqlCon.State == ConnectionState.Closed)
                    sqlCon.Open();

                if(hfUserID.Value!="")
                {
               // TODO: Check UserId there is In Table Or not(Similar to the bottom ADO.net).
               // TODO: then If Exist then isUpdate=true else isUpdate=false
                }

                SqlCommand sqlCmd = new SqlCommand("UserCreateOrUpdate",sqlCon);
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@UserID",(hfUserID.Value==""?0:Convert.ToInt32(hfUserID.Value)));
                sqlCmd.Parameters.AddWithValue("@FName",txtFName.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@LName",txtLName.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Password", txtPassword.Text);

                int a= sqlCmd.ExecuteNonQuery();

                sqlCon.Close();

                Clear();

            if (a==0)
                lblSuccessMessage.Text =isUpdate? "Not updated.":"Not Saved";
            else
                lblSuccessMessage.Text = isUpdate? "Updated." : "Saved";

            FillGridView();
        }


问:
Reference workbook by path and name error: Subscript out of range
I get the "Subscript out of range" error from the line below:

```<code>Set WBset =  Workbooks("FilePath\PK18 - Unformatted.xls").Worksheets("PK18 - Unformatted")
</code>```

I checked the sheet name and the filename and they are correct. The sheet exists.

答:
Presuming WBset is a Workbook Object, you need to remove the file path from the command so it looks like the following.  The file needs to be open as Workbooks is a collection of the Workbook objects open.</p>

```<code>Set WBset =  Workbooks("PK18 - Unformatted.xls").Worksheets("PK18 - Unformatted")
</code>```

Body:
I get the "Subscript out of range" error from the line below:

Set WBset =  Workbooks("FilePath\PK18 - Unformatted.xls").Worksheets("PK18 - Unformatted")

I checked the sheet name and the filename and they are correct. The sheet exists.

Body:
Presuming WBset is a Workbook Object, you need to remove the file path from the command so it looks like the following.  The file needs to be open as Workbooks is a collection of the Workbook objects open.

Set WBset =  Workbooks("PK18 - Unformatted.xls").Worksheets("PK18 - Unformatted")


问:
Accessing Anaconda in Gitbash-> bash: conda: command not found, unexpected token '('
Path of my Anaconda3 folder:

```<code>  C:\Users\shail\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)
</code>```

Commands tried in Git bash terminal:

```<code>  conda init bash
  echo '. ${HOME}/.bash_profile' >> ~/.bashrc
  base *c:\Users\shail\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)
</code>```

Error:

```<code>  bash: syntax error near unexpected token '(' #on using the base command
</code>```

I have read many blogs but all the codes are mostly outdated and do not work for me. Pls guide. I have anaconda installed which workd perfectly on cmd terminal and anaconda prompt but I am unable to access anaconda in git bash.

答:
You need quotes around $HOME if it contains any shell special characters.

```<code>echo '. "$HOME"/.bash_profile'>>~/.bashrc
</code>```

Equivalently, use ~ without quotes, just like you already do in ~/.bashrc

Either way, obviously take out the old erroneous assignment from .bashrc, too.

The braces around ${HOME} did no harm, but also don't contribute anything useful (braces are useful when you need to interpolate a variable net to verbatim text, like ${HOME}LY which means the value of HOME next to the literal text LY, as opposed to $HOMELY which would attempt yo expand a variable with that name, which produces an empty string if the variable doesn't exist).

Body:
Path of my Anaconda3 folder:

  C:\Users\shail\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)

Commands tried in Git bash terminal:

  conda init bash
  echo '. ${HOME}/.bash_profile' >> ~/.bashrc
  base *c:\Users\shail\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)

Error:

  bash: syntax error near unexpected token '(' #on using the base command

I have read many blogs but all the codes are mostly outdated and do not work for me. Pls guide. I have anaconda installed which workd perfectly on cmd terminal and anaconda prompt but I am unable to access anaconda in git bash.

Body:
You need quotes around $HOME if it contains any shell special characters.

echo '. "$HOME"/.bash_profile'>>~/.bashrc

Equivalently, use ~ without quotes, just like you already do in ~/.bashrc

Either way, obviously take out the old erroneous assignment from .bashrc, too.

The braces around ${HOME} did no harm, but also don't contribute anything useful (braces are useful when you need to interpolate a variable net to verbatim text, like ${HOME}LY which means the value of HOME next to the literal text LY, as opposed to $HOMELY which would attempt yo expand a variable with that name, which produces an empty string if the variable doesn't exist).


问:
Filtering results in MySQL in join result
I am beginner programmer. I have small problem with my MySQL Queries.
This is my MySQL data: https://pastebin.com/69PcBSVH

I have this tables:

```<code>CREATE TABLE `dishes` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1',
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `dish_values` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `dishes_id` bigint(20) UNSIGNED NOT NULL,
  `food_ingredient_id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `quantity` decimal(9,2) NOT NULL DEFAULT '0.00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `food_ingredients` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(120) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `garbage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `energy_value` decimal(9,2) NOT NULL DEFAULT '0.00',
  `protein` decimal(9,2) NOT NULL DEFAULT '0.00',
  `fat` decimal(9,2) NOT NULL DEFAULT '0.00',
  `available_carbohydrates` decimal(9,2) NOT NULL DEFAULT '0.00',
  `roughage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `url_address` varchar(160) COLLATE utf8mb4_unicode_ci NOT NULL,
  `allergen` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen1` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen2` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen3` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `available_in_demo` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
</code>```

My base is a base of dishes and ingredients needed to prepare a dish.

I need to display all dishes that are not allergens (food_ingredients.allergen = 0).

```<code>Table dishes = given dishes
Table dish_values = ingredients that are assigned to a given dish
Food_ingredients table = ingredients of the dish.
</code>```

Dishes that are allergens have a value of 1 in the allergen column and those that are not allergens 0.

I make query to show my dish (without allergens):

```<code>SELECT
  dishes.id, dishes.company_id, dishes.name, dishes.description, dishes.enable
FROM `dishes`  join dish_values on dish_values.dishes_id = dishes.id
      join food_ingredients on food_ingredients.id = dish_values.food_ingredient_id
WHERE food_ingredients.allergen = 0
GROUP BY dishes.id
</code>```

But it's not working correct.

As a result, I have both dishes that contain allergens and those that do not have them.

How can I repair it?

答:
I would use not’exists with a correlated subquery: this avoids the need for aggregation, which is generally not good for performance on large datasets:

```<code>select d.*
from dishes d
where not exists (
    select 1
    from dish_values v
    inner join food_ingredients i on i.id = v.food_ingredient_id
    where
        v.dishes_id = d.id
        and i.allergen = 1
)
</code>```

For performance, you want the following index: food_ingredients(allergen, id).

Side note: you should change the data type of allergen from char(1) to tinyint(1) since it only contains 0/1 values.

Body:
I am beginner programmer. I have small problem with my MySQL Queries.
This is my MySQL data: https://pastebin.com/69PcBSVH

I have this tables:

CREATE TABLE `dishes` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1',
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `dish_values` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `dishes_id` bigint(20) UNSIGNED NOT NULL,
  `food_ingredient_id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `quantity` decimal(9,2) NOT NULL DEFAULT '0.00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `food_ingredients` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(120) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `garbage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `energy_value` decimal(9,2) NOT NULL DEFAULT '0.00',
  `protein` decimal(9,2) NOT NULL DEFAULT '0.00',
  `fat` decimal(9,2) NOT NULL DEFAULT '0.00',
  `available_carbohydrates` decimal(9,2) NOT NULL DEFAULT '0.00',
  `roughage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `url_address` varchar(160) COLLATE utf8mb4_unicode_ci NOT NULL,
  `allergen` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen1` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen2` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen3` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `available_in_demo` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

My base is a base of dishes and ingredients needed to prepare a dish.

I need to display all dishes that are not allergens (food_ingredients.allergen = 0).

Table dishes = given dishes
Table dish_values = ingredients that are assigned to a given dish
Food_ingredients table = ingredients of the dish.

Dishes that are allergens have a value of 1 in the allergen column and those that are not allergens 0.

I make query to show my dish (without allergens):

SELECT
  dishes.id, dishes.company_id, dishes.name, dishes.description, dishes.enable
FROM `dishes`  join dish_values on dish_values.dishes_id = dishes.id
      join food_ingredients on food_ingredients.id = dish_values.food_ingredient_id
WHERE food_ingredients.allergen = 0
GROUP BY dishes.id

But it's not working correct.

As a result, I have both dishes that contain allergens and those that do not have them.

How can I repair it?

Body:
I would use not’exists with a correlated subquery: this avoids the need for aggregation, which is generally not good for performance on large datasets:

select d.*
from dishes d
where not exists (
    select 1
    from dish_values v
    inner join food_ingredients i on i.id = v.food_ingredient_id
    where
        v.dishes_id = d.id
        and i.allergen = 1
)

For performance, you want the following index: food_ingredients(allergen, id).

Side note: you should change the data type of allergen from char(1) to tinyint(1) since it only contains 0/1 values.


问:
pass output from terraform to Azure Devops Pipeline with state file in azure backend store
I cannot seem to retrieve the public ip address output of Terraform for next step in build pipeline in AzureDevops.

Terraform state pull works and outputs to json file, cannot grep on output.

Terraform state show [options] ADDRESS does not support azure backend so cannot use or grep or filter the output

also tried to store as file and read in the value.

```<code>resource "local_file" "foo" {
    content     = "foo!"
    filename = "${path.module}/foo.bar"
}

data "azurerm_public_ip" "buildserver-pip" {
  name                = "${azurerm_public_ip.buildserver-pip.name}"
  resource_group_name = "${azurerm_virtual_machine.buildserver.resource_group_name}"
}

output "public_ip_address" {
  value = "${data.azurerm_public_ip.buildserver-pip.ip_address}"
}
</code>```

expect the public ip address to be passed out so can be used in ansible  playbooks, bash or python script in next step

答:
Building on @JleruOHeP answer above the following solution will automatically create a variable for every output provided by the terraform script

Create a PowerShell step in your release and insert the following inline PowerShell:

```<code>$json = Get-Content $env:jsonPath | Out-String | ConvertFrom-Json

foreach($prop in $json.psobject.properties) {
    Write-Host("##vso[task.setvariable variable=$($prop.Name);]$($prop.Value.value)")
}
</code>```

Make sure you have provided the environment variable jsonPath like this:

Body:
I cannot seem to retrieve the public ip address output of Terraform for next step in build pipeline in AzureDevops.

Terraform state pull works and outputs to json file, cannot grep on output.

Terraform state show [options] ADDRESS does not support azure backend so cannot use or grep or filter the output

also tried to store as file and read in the value.

resource "local_file" "foo" {
    content     = "foo!"
    filename = "${path.module}/foo.bar"
}

data "azurerm_public_ip" "buildserver-pip" {
  name                = "${azurerm_public_ip.buildserver-pip.name}"
  resource_group_name = "${azurerm_virtual_machine.buildserver.resource_group_name}"
}

output "public_ip_address" {
  value = "${data.azurerm_public_ip.buildserver-pip.ip_address}"
}

expect the public ip address to be passed out so can be used in ansible  playbooks, bash or python script in next step

Body:
Building on @JleruOHeP answer above the following solution will automatically create a variable for every output provided by the terraform script

Create a PowerShell step in your release and insert the following inline PowerShell:

$json = Get-Content $env:jsonPath | Out-String | ConvertFrom-Json

foreach($prop in $json.psobject.properties) {
    Write-Host("##vso[task.setvariable variable=$($prop.Name);]$($prop.Value.value)")
}

Make sure you have provided the environment variable jsonPath like this:


问:
Map.Entry without type declaration
I am new to Java, but I need to quickly grasp some fundamentals to be able to work with some basic data structures.

Here's a small example I would like to understand better, namely the Map.Entry<Integer,String> part.

```<code>HashMap<Integer,String> my_hashmap = new HashMap<>();

 my_hashmap.put(20,"twenty");
 my_hashmap.put(30,"thirty");

 for (Map.Entry<Integer,String> m:my_hashmap.entrySet()) {
     System.out.println(m.getKey() + " " + m.getValue());
 }
</code>```

It turns out that I can omit the <Integer, String> declaration and it makes no difference at all. Is that a bad practice? As far as I understand, under the hood, this is somehow interpreted as the Object type so there's no problem, but that doesn't benefit from using generics. Is my understanding correct? Thanks.

答:
It is bad practice to use raw types.

In your example, since you are simply printing the key and value of each entry, the code passes compilation and works, since it uses the toString() method implemented by all classes in order to print them.

If, on the other hand, you want to print the length() of the value String instead of the actual String, you would write

```<code>System.out.println(m.getKey() + " " + m.getValue().getLength());
</code>```

Now, this won't pass compilation if you changed

```<code>for (Map.Entry<Integer,String> m:my_hashmap.entrySet())
</code>```

to

```<code>for (Map.Entry m:my_hashmap.entrySet())
</code>```

since Object doesn't have a length() method.

Title: Map.Entry without type declaration

Body:
I am new to Java, but I need to quickly grasp some fundamentals to be able to work with some basic data structures.

Here's a small example I would like to understand better, namely the Map.Entry<Integer,String> part.

HashMap<Integer,String> my_hashmap = new HashMap<>();

 my_hashmap.put(20,"twenty");
 my_hashmap.put(30,"thirty");

 for (Map.Entry<Integer,String> m:my_hashmap.entrySet()) {
     System.out.println(m.getKey() + " " + m.getValue());
 }

It turns out that I can omit the <Integer, String> declaration and it makes no difference at all. Is that a bad practice? As far as I understand, under the hood, this is somehow interpreted as the Object type so there's no problem, but that doesn't benefit from using generics. Is my understanding correct? Thanks.

Body:
It is bad practice to use raw types.

In your example, since you are simply printing the key and value of each entry, the code passes compilation and works, since it uses the toString() method implemented by all classes in order to print them.

If, on the other hand, you want to print the length() of the value String instead of the actual String, you would write

System.out.println(m.getKey() + " " + m.getValue().getLength());

Now, this won't pass compilation if you changed

for (Map.Entry<Integer,String> m:my_hashmap.entrySet())

to

for (Map.Entry m:my_hashmap.entrySet())

since Object doesn't have a length() method.