问:
How can I hide letter counter from bottom of TextField in Flutter

I'm facing a small problem. As you can see, i have set maxLength 1 of TextField in Flutter, But i'm unable to hide bottom label of text counter.

答:
```<code>    Container(
                    height: 48,
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.symmetric(horizontal: 16),
                    decoration: BoxDecoration(
                        border: Border.all(
                          color: CustomColors.kToDark,
                        ),
                        color: CustomColors.White,
                        borderRadius: BorderRadius.all(Radius.circular(8))),
                    child: TextFormField(
                      textAlign: TextAlign.left,
                        cursorColor: CustomColors.kToDark,
                        maxLength: 30,
                        controller: _titleController,
                        keyboardType: TextInputType.text,
                        decoration: InputDecoration(
                          counterText: "",
                            border: InputBorder.none,
                            isDense: true,
                            contentPadding: EdgeInsets.all(0))),
                  ),
</code>```

Use counterText: "" inside InputDecoration()

Body:
    Container(
                    height: 48,
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.symmetric(horizontal: 16),
                    decoration: BoxDecoration(
                        border: Border.all(
                          color: CustomColors.kToDark,
                        ),
                        color: CustomColors.White,
                        borderRadius: BorderRadius.all(Radius.circular(8))),
                    child: TextFormField(
                      textAlign: TextAlign.left,
                        cursorColor: CustomColors.kToDark,
                        maxLength: 30,
                        controller: _titleController,
                        keyboardType: TextInputType.text,
                        decoration: InputDecoration(
                          counterText: "",
                            border: InputBorder.none,
                            isDense: true,
                            contentPadding: EdgeInsets.all(0))),
                  ),

Use counterText: "" inside InputDecoration()


来源: stackexchange

问:
Joining a calendar table on date to a table of items returns all NULLS (adding missing dates to table by a group)
I am trying to join a table of dates to an existing table of items.  I want to add the missing dates for each item see items table:

original dataset

```<code>date    item    price
1/1/2018    toys    22.82
1/3/2018    toys    28.99
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/4/2018    shoes   62.74
1/10/2018   shoes   35.16
</code>```

I need to fill in missing dates for each item with a NULL price so then I can estimate it
so I want this result:
result wanted

```<code>date    item    price
1/1/2018    toys    22.82
1/2/2018    toys    NULL
1/3/2018    toys    28.99
1/4/2018    toys    NULL
1/5/2018    toys    NULL
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/3/2018    shoes   NULL
1/4/2018    shoes   62.74
1/5/2018    shoes   NULL
1/6/2018    shoes   NULL
1/7/2018    shoes   NULL
1/8/2018    shoes   NULL
1/9/2018    shoes   NULL
1/10/2018   shoes   35.16
</code>```

I have tried the following:

```<code>    select c.day, e.item, e.price
from db.days c cross join
     (select distinct item from db.items e)
     left join
     db.items e
     on c.day = e.date_added;
</code>```

It gives me the following:
result

```<code>date    item    price
1/1/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/7/2018    NULL    NULL
1/8/2018    NULL    NULL
1/9/2018    NULL    NULL
1/10/2018   NULL    NULL
</code>```

How can I get rid of the NULLs and get my desired result above? I am using SQLite Studio

答:
You should take into account the min and max date for each item and join accordingly to the days list:

```<code>SELECT d.day, i.item, t.price
FROM (SELECT item, MIN(date_added) min_date, MAX(date_added) max_date FROM items GROUP BY item) i
INNER JOIN days d ON d.day BETWEEN i.min_date AND i.max_date
LEFT JOIN items t ON t.item = i.item AND t.date_added = d.day
ORDER BY i.min_date, i.item, d.day;
</code>```

Note that, your dates as they are they are not comparable and you need to change their format to YYYY-MM-DD in all the tables.

See the demo.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to join a table of dates to an existing table of items.  I want to add the missing dates for each item see items table:

original dataset

date    item    price
1/1/2018    toys    22.82
1/3/2018    toys    28.99
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/4/2018    shoes   62.74
1/10/2018   shoes   35.16

I need to fill in missing dates for each item with a NULL price so then I can estimate it
so I want this result:
result wanted

date    item    price
1/1/2018    toys    22.82
1/2/2018    toys    NULL
1/3/2018    toys    28.99
1/4/2018    toys    NULL
1/5/2018    toys    NULL
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/3/2018    shoes   NULL
1/4/2018    shoes   62.74
1/5/2018    shoes   NULL
1/6/2018    shoes   NULL
1/7/2018    shoes   NULL
1/8/2018    shoes   NULL
1/9/2018    shoes   NULL
1/10/2018   shoes   35.16

I have tried the following:

    select c.day, e.item, e.price
from db.days c cross join
     (select distinct item from db.items e)
     left join
     db.items e
     on c.day = e.date_added;

It gives me the following:
result

date    item    price
1/1/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/7/2018    NULL    NULL
1/8/2018    NULL    NULL
1/9/2018    NULL    NULL
1/10/2018   NULL    NULL

How can I get rid of the NULLs and get my desired result above? I am using SQLite Studio

Body:
You should take into account the min and max date for each item and join accordingly to the days list:

SELECT d.day, i.item, t.price
FROM (SELECT item, MIN(date_added) min_date, MAX(date_added) max_date FROM items GROUP BY item) i
INNER JOIN days d ON d.day BETWEEN i.min_date AND i.max_date
LEFT JOIN items t ON t.item = i.item AND t.date_added = d.day
ORDER BY i.min_date, i.item, d.day;

Note that, your dates as they are they are not comparable and you need to change their format to YYYY-MM-DD in all the tables.

See the demo.


问:
Very basic JSON question
I have this JSON data:

```<code>var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];
</code>```

How can I loop through all the objects inside people and output their names along with their ages like so:

```<code>John 25
Jame 49
followed by the rest...
</code>```

答:
Loop through them. These are Javascript object literals not JSON though, just FYI

```<code>for(var i = 0; i < people.length; i++) {
    alert(people[i].name + " " + people[i].age)
}
</code>```

For example:

```<code>var variable = { 'key': 'value' };  // object
console.log(variable.key); // outputs: value

var json = '{"key":"value"}'; // javascript string representing valid json
console.log(json.key); // outputs: undefined

var jObj = JSON.parse(json); // now a javascript object from the json string
console.log(jObj.key); // outputs: value
</code>```

So JSON only really exists in javascript as a representation.

ContentLicense: CC BY-SA 3.0

Title: Very basic JSON question

Body:
I have this JSON data:

var people = [
     { name : "John",  age : 25 },
     { name : "Jane",  age : 49 },
     { name : "Jim",   age : 31 },
     { name : "Julie", age : 39 },
     { name : "Joe",   age : 19 },
     { name : "Jack",  age : 48 }
];

How can I loop through all the objects inside people and output their names along with their ages like so:

John 25
Jame 49
followed by the rest...

Body:
Loop through them. These are Javascript object literals not JSON though, just FYI

for(var i = 0; i < people.length; i++) {
    alert(people[i].name + " " + people[i].age)
}

For example:

var variable = { 'key': 'value' };  // object
console.log(variable.key); // outputs: value

var json = '{"key":"value"}'; // javascript string representing valid json
console.log(json.key); // outputs: undefined

var jObj = JSON.parse(json); // now a javascript object from the json string
console.log(jObj.key); // outputs: value

So JSON only really exists in javascript as a representation.


问:
Django: update a model with the current user when an non-model form field is changed
I'm building a page that allows users to edit Task and related Activity records (one task can have many activities), all on the same page.  I want to allow the user to "adopt" one or more activities by ticking a box, and have their user record linked to each activity via a ForeignKey.  Here are extracts from my code...

models.py

```<code>from django.contrib.auth.models import User

class Task(models.Model):
    category    = models.CharField(max_length=300)
    description = models.CharField(max_length=300)

class Activity(models.Model):
    task  = models.ForeignKey(Task, on_delete=models.CASCADE)
    title = models.CharField(max_length=150)
    notes = models.TextField(blank=True)
    owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
</code>```

The activity "owner" is linked to a User from the Django standard user model.

I added an extra field in the form definition for the adopt field - I don't want to add it to the model as I don't need to save it once it's done it's job.

forms.py

```<code>class ActivityForm(forms.ModelForm):
    adopt = forms.BooleanField(required=False)

    class Meta:
        model = Activity
        fields = '__all__'
</code>```

views.py

```<code>def manage_task(request, pk):
    task = Task.objects.get(pk = pk)
    TaskInlineFormSet = inlineformset_factory(Task, Activity,
        form = ActivityForm)
    if request.method == "POST":
        form = TaskForm(request.POST, instance = task)
        formset = TaskInlineFormSet(request.POST, instance = task)
        if form.has_changed() and form.is_valid():
            form.save()
        if formset.has_changed() and formset.is_valid():
            ## ? DO SOMETHING HERE ? ##
            formset.save()
        return redirect('manage_task',pk=task.id)
    else:
        form = TaskForm(instance = task)
        formset = TaskInlineFormSet(instance = task)
    context = {'task': task, 'task_form': form, 'formset': formset}
    return render(request, 'tasks/manage_task.html', context)
</code>```

When the adopt field is ticked on the form, I want to be able to set the owner field in that form to the current user before the associated model instance is updated and saved.

I just can't figure out how to do that - if it was a single form (rather than an InlineFormSet), I think I could put code in the view to change the owner value in the form field before it was saved (I haven't tried this).  Or try save(commit = False) and update the model instance  then save() it.
Maybe I have to iterate through the formset in the view code and try one of those options when I find one that had adopt=True?

答:
I'm not happy with this solution but it does work. I iterate through the forms and change the object instance if my adopt field is set.

views.py

```<code>def manage_task(request, pk):
    task = Task.objects.get(pk = pk)
    TaskInlineFormSet = inlineformset_factory(Task, Activity,
        form = ActivityForm)
    if request.method == "POST":
        form = TaskForm(request.POST, instance = task)
        formset = TaskInlineFormSet(request.POST, instance = task)
        if form.has_changed() and form.is_valid():
            form.save()
        if formset.has_changed() and formset.is_valid():

            ## HERE'S WHAT I ADDED ##
            for form in formset:
                if form.cleaned_data['adopt'] is True:
                    form.instance.owner = request.user
            ## END OF ADDITIONS ##

            formset.save()
        ## return redirect('manage_task',pk=task.id) # CHANGED THIS BECAUSE I WASN'T RETURNG ERRORS!
        if not form.errors and not formset.total_error_count():
            return redirect('manage_task',pk=task.id)
    else:
        form = TaskForm(instance = task)
        formset = TaskInlineFormSet(instance = task)
    context = {'task': task, 'task_form': form, 'formset': formset}
    return render(request, 'tasks/manage_task.html', context)
</code>```

I wish I could find more in the docs about how the form saving works but I think I'll have to look into the code if I want more detail.

Body:
I'm building a page that allows users to edit Task and related Activity records (one task can have many activities), all on the same page.  I want to allow the user to "adopt" one or more activities by ticking a box, and have their user record linked to each activity via a ForeignKey.  Here are extracts from my code...

models.py

from django.contrib.auth.models import User

class Task(models.Model):
    category    = models.CharField(max_length=300)
    description = models.CharField(max_length=300)

class Activity(models.Model):
    task  = models.ForeignKey(Task, on_delete=models.CASCADE)
    title = models.CharField(max_length=150)
    notes = models.TextField(blank=True)
    owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)

The activity "owner" is linked to a User from the Django standard user model.

I added an extra field in the form definition for the adopt field - I don't want to add it to the model as I don't need to save it once it's done it's job.

forms.py

class ActivityForm(forms.ModelForm):
    adopt = forms.BooleanField(required=False)

    class Meta:
        model = Activity
        fields = '__all__'

views.py

def manage_task(request, pk):
    task = Task.objects.get(pk = pk)
    TaskInlineFormSet = inlineformset_factory(Task, Activity,
        form = ActivityForm)
    if request.method == "POST":
        form = TaskForm(request.POST, instance = task)
        formset = TaskInlineFormSet(request.POST, instance = task)
        if form.has_changed() and form.is_valid():
            form.save()
        if formset.has_changed() and formset.is_valid():
            ## ? DO SOMETHING HERE ? ##
            formset.save()
        return redirect('manage_task',pk=task.id)
    else:
        form = TaskForm(instance = task)
        formset = TaskInlineFormSet(instance = task)
    context = {'task': task, 'task_form': form, 'formset': formset}
    return render(request, 'tasks/manage_task.html', context)

When the adopt field is ticked on the form, I want to be able to set the owner field in that form to the current user before the associated model instance is updated and saved.

I just can't figure out how to do that - if it was a single form (rather than an InlineFormSet), I think I could put code in the view to change the owner value in the form field before it was saved (I haven't tried this).  Or try save(commit = False) and update the model instance  then save() it.
Maybe I have to iterate through the formset in the view code and try one of those options when I find one that had adopt=True?

Body:
I'm not happy with this solution but it does work. I iterate through the forms and change the object instance if my adopt field is set.

views.py

def manage_task(request, pk):
    task = Task.objects.get(pk = pk)
    TaskInlineFormSet = inlineformset_factory(Task, Activity,
        form = ActivityForm)
    if request.method == "POST":
        form = TaskForm(request.POST, instance = task)
        formset = TaskInlineFormSet(request.POST, instance = task)
        if form.has_changed() and form.is_valid():
            form.save()
        if formset.has_changed() and formset.is_valid():

            ## HERE'S WHAT I ADDED ##
            for form in formset:
                if form.cleaned_data['adopt'] is True:
                    form.instance.owner = request.user
            ## END OF ADDITIONS ##

            formset.save()
        ## return redirect('manage_task',pk=task.id) # CHANGED THIS BECAUSE I WASN'T RETURNG ERRORS!
        if not form.errors and not formset.total_error_count():
            return redirect('manage_task',pk=task.id)
    else:
        form = TaskForm(instance = task)
        formset = TaskInlineFormSet(instance = task)
    context = {'task': task, 'task_form': form, 'formset': formset}
    return render(request, 'tasks/manage_task.html', context)

I wish I could find more in the docs about how the form saving works but I think I'll have to look into the code if I want more detail.


问:
Displaying Monthly Sales in a Donut Chart
I'm creating a dynamic dashboard where a donut chart would show total amount of sales by month name. For the query I've used:

```<code>$sales_by_month = "SELECT MONTHNAME(pay_time) as mname,
                sum(amount) as total_sales
                FROM aamarpay
                GROUP BY MONTH(pay_time)";

$res_sales_by_month = mysqli_query($conn, $sales_by_month);
</code>```

After that I'm using a template from google chart to display the data. But the chart is only showing one month of data instead of multiple month data I have on my database.

Here's the code to fetch the data:

```<code>function drawChart() {
    <?php
    while($rows_sales = mysqli_fetch_assoc($res_sales_by_month)):
        $month = $rows_sales['mname'];
        $total_sales = $rows_sales['total_sales'];
    ?>
    var data = google.visualization.arrayToDataTable([
      ['Month', 'Totals Sales'],
      ['<?php echo $month; ?>', '<?php echo $total_sales; ?>'  ]

      ]);
      <?php endwhile; ?>
</code>```

Here's how it shows up:
donut chart

How can I fix this?

答:
Found the solution.</p>
```<code>var data = google.visualization.arrayToDataTable([
      ['Month', 'Totals Sales'],
      <?php
      while($row_sales=mysqli_fetch_array($res_sales_by_month))
      {
          echo "['".$row_sales["mname"]."', ".$row_sales["total_sales"]."],";
      }
      ?>
      ]);
</code>```

Body:
I'm creating a dynamic dashboard where a donut chart would show total amount of sales by month name. For the query I've used:

$sales_by_month = "SELECT MONTHNAME(pay_time) as mname,
                sum(amount) as total_sales
                FROM aamarpay
                GROUP BY MONTH(pay_time)";

$res_sales_by_month = mysqli_query($conn, $sales_by_month);

After that I'm using a template from google chart to display the data. But the chart is only showing one month of data instead of multiple month data I have on my database.

Here's the code to fetch the data:

function drawChart() {
    <?php
    while($rows_sales = mysqli_fetch_assoc($res_sales_by_month)):
        $month = $rows_sales['mname'];
        $total_sales = $rows_sales['total_sales'];
    ?>
    var data = google.visualization.arrayToDataTable([
      ['Month', 'Totals Sales'],
      ['<?php echo $month; ?>', '<?php echo $total_sales; ?>'  ]

      ]);
      <?php endwhile; ?>

Here's how it shows up:
donut chart

How can I fix this?

Body:
Found the solution.

var data = google.visualization.arrayToDataTable([
      ['Month', 'Totals Sales'],
      <?php
      while($row_sales=mysqli_fetch_array($res_sales_by_month))
      {
          echo "['".$row_sales["mname"]."', ".$row_sales["total_sales"]."],";
      }
      ?>
      ]);


问:
In SwiftUI how can I clip a part of a view with another view?
I am trying to overlap two circles in SwiftUI and have a margin between them. I am presently using this method:

```<code>ZStack {
    Circle()
        .frame(width: 60, height: 60)
        .foregroundColor(Color.blue)
        .shadow(color: .black.opacity(0.5), radius: 4, x: 2, y: 2)
    ZStack {
        Circle()
            .frame(width: 26, height: 26)
            .foregroundColor(Color(.systemGray5))
        Circle()
            .frame(width: 22, height: 22)
            .foregroundColor(.blue)
    }
    .offset(x: 26, y: 17)
}
</code>```

The problem is that because of the shadow on the big circle I will never be able to perfectly match the background on the smaller circle's border circle (the one that is systemGray5.  So although it looks okay, I only want the margin to appear between the circles.  Not all the way around the smaller circle.

In illustrator or other ways I would clip the big image with my 26 size circle and it would look like a bite taken out of it.  Then I can achieve this effect perfectly.

Is there anyway to clip the bottom of my large circle in SwiftUI?

答:
Here is a demo of possible approach with inverted mask (it is simplified but the idea should be clear - removing hardcoding and "bite" position calculations is on you).

Tested with Xcode 13.2 / iOS 15.2

```<code>struct DemoView: View {
    struct BiteCircle: Shape {
        func path(in rect: CGRect) -> Path {
            let offset = rect.maxX - 26
            let crect = CGRect(origin: .zero, size: CGSize(width: 26, height: 26)).offsetBy(dx: offset, dy: offset)

            var path = Rectangle().path(in: rect)
            path.addPath(Circle().path(in: crect))
            return path
        }
    }
    var body: some View {
        ZStack {
            Circle()
                .frame(width: 60, height: 60)
                .foregroundColor(Color.blue)
                .mask(BiteCircle().fill(style: .init(eoFill: true)))     // << here !!
                .shadow(color: .black.opacity(0.5), radius: 4, x: 2, y: 2)

            Circle()
                .frame(width: 22, height: 22)
                .foregroundColor(.blue)
                .offset(x: 18, y: 18)
        }

    }
}
</code>```

Body:
I am trying to overlap two circles in SwiftUI and have a margin between them. I am presently using this method:

ZStack {
    Circle()
        .frame(width: 60, height: 60)
        .foregroundColor(Color.blue)
        .shadow(color: .black.opacity(0.5), radius: 4, x: 2, y: 2)
    ZStack {
        Circle()
            .frame(width: 26, height: 26)
            .foregroundColor(Color(.systemGray5))
        Circle()
            .frame(width: 22, height: 22)
            .foregroundColor(.blue)
    }
    .offset(x: 26, y: 17)
}

The problem is that because of the shadow on the big circle I will never be able to perfectly match the background on the smaller circle's border circle (the one that is systemGray5.  So although it looks okay, I only want the margin to appear between the circles.  Not all the way around the smaller circle.

In illustrator or other ways I would clip the big image with my 26 size circle and it would look like a bite taken out of it.  Then I can achieve this effect perfectly.

Is there anyway to clip the bottom of my large circle in SwiftUI?

Body:
Here is a demo of possible approach with inverted mask (it is simplified but the idea should be clear - removing hardcoding and "bite" position calculations is on you).

Tested with Xcode 13.2 / iOS 15.2

struct DemoView: View {
    struct BiteCircle: Shape {
        func path(in rect: CGRect) -> Path {
            let offset = rect.maxX - 26
            let crect = CGRect(origin: .zero, size: CGSize(width: 26, height: 26)).offsetBy(dx: offset, dy: offset)

            var path = Rectangle().path(in: rect)
            path.addPath(Circle().path(in: crect))
            return path
        }
    }
    var body: some View {
        ZStack {
            Circle()
                .frame(width: 60, height: 60)
                .foregroundColor(Color.blue)
                .mask(BiteCircle().fill(style: .init(eoFill: true)))     // << here !!
                .shadow(color: .black.opacity(0.5), radius: 4, x: 2, y: 2)

            Circle()
                .frame(width: 22, height: 22)
                .foregroundColor(.blue)
                .offset(x: 18, y: 18)
        }

    }
}


问:
Property is accessed but result is unused
I saw there another similar one to my question but that was very old! , So I have an UIActivityIndicatorView but when i try to call the .hidesWhenStopped it just warns Property is accessed but result is unused for no reason?

What could be the problem?
I tried under viewDidLoad too but same :(

This is a part of my code:

```<code>Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { [self] _ in
   monitorimiTableView.reloadData()
   configureTableView()
   loaderMonitorimi.hidesWhenStopped // Property is accessed but result is unused
}
</code>```

答:
You need to assign a value to the property:

```<code>loaderMonitorimi.hidesWhenStopped = true
</code>```

(or false if you don't want to hide it)

If you just write loaderMonitorimi.hidesWhenStopped without any assignment, this expression will result in the boolean value stored in the hidesWhenStopped property, but the result of the expression is not used, hence the warning.

Body:
I saw there another similar one to my question but that was very old! , So I have an UIActivityIndicatorView but when i try to call the .hidesWhenStopped it just warns Property is accessed but result is unused for no reason?

What could be the problem?
I tried under viewDidLoad too but same :(

This is a part of my code:

Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { [self] _ in
   monitorimiTableView.reloadData()
   configureTableView()
   loaderMonitorimi.hidesWhenStopped // Property is accessed but result is unused
}

Body:
You need to assign a value to the property:

loaderMonitorimi.hidesWhenStopped = true

(or false if you don't want to hide it)

If you just write loaderMonitorimi.hidesWhenStopped without any assignment, this expression will result in the boolean value stored in the hidesWhenStopped property, but the result of the expression is not used, hence the warning.


问:
Reading an integer from standard input
How do I use the fmt.Scanf function in Go to get an integer input from the standard input?

If this can't be done using fmt.Scanf, what's the best way to read a single integer?

答:
You could also use bufio.NewReader to read an integer from the standard input.

The below program:

Prompts for an integer input

Creates a bufio.Reader to read from standard input

Reads input till it encounters a newline character '\n' (Note that this will only read a single integer. Space separated values will not work)

Removes the newline character

Converts string to int

```<code>package main

import (
    "fmt"
    "bufio"
    "os"
    "strconv"
    "strings"
)

func getInt() error {
    fmt.Println("Enter an integer")
    userInput  := bufio.NewReader(os.Stdin)
    userVal, err := userInput.ReadString('\n')
    if err != nil {
        return err
    }

    input := strings.TrimSpace(userVal)
    intVal, err := strconv.Atoi(input)
    if err != nil {
        return err
    }

    fmt.Printf("You entered: %d\n", intVal)
    return nil
}

func main() {
    getInt()
}
</code>```

Title: Reading an integer from standard input

Body:
You could also use bufio.NewReader to read an integer from the standard input.

The below program:

Prompts for an integer input

Creates a bufio.Reader to read from standard input

Reads input till it encounters a newline character '\n' (Note that this will only read a single integer. Space separated values will not work)

Removes the newline character

Converts string to int

package main

import (
    "fmt"
    "bufio"
    "os"
    "strconv"
    "strings"
)

func getInt() error {
    fmt.Println("Enter an integer")
    userInput  := bufio.NewReader(os.Stdin)
    userVal, err := userInput.ReadString('\n')
    if err != nil {
        return err
    }

    input := strings.TrimSpace(userVal)
    intVal, err := strconv.Atoi(input)
    if err != nil {
        return err
    }

    fmt.Printf("You entered: %d\n", intVal)
    return nil
}

func main() {
    getInt()
}


问:
Amazon Cognito: Login option is not available. Please try another one
I have a user pool set up with AWS Cognito to which I have added a SAML identity provider. I also have users added directly to the user pool.

After following the documentation here I tried to log in via SP-initiated SSO. Cognito redirected me to the configured SAML IdP, where I was prompted for the credentials. I authenticate and the SAML response is POSTed back to the Cognito SAML ACS endpoint (which is https://<cognito auth domain>/saml2/idpresponse). At this point Cognito redirects me to an error page (/error?null) with this rather unhelpful error that I mention in the subject.

I've scoured for similar problems faced by anyone but haven't found anything yet (a similar error has been encountered by someone but in the context of AWS amplify and not when using SAML)

Not sure how to debug this; I believe I have done the right configuration in Cognito as well as the SAML IdP (Okta). Any pointers will be helpful.

答: Figured it out. The App Client was setup up before this SAML IdP was added to the Cognito user pool. When it was added it only had the native Cognito user pool enabled. When you add other IdP's for federation you have to go back to the App Client configuration and enable the IdPs explicitly. Once I did that, the error was gone.</p>


问:
How to set a default screen Route in react Tab Navigation in React Native
I want to load dashboard to be active tab in react Native bottom tab. Navigation whenever dashboard is loaded but whenever I move to dashboard it moves to inbox screen which is the first element in my react Bottom Tab Navigation. Is there any way to create a default screen whenever screen bottom tabs is used?

The code I am using for bottom navigation is

```<code> dashboard: {
        screen: createBottomTabNavigator({
            inbox: {
                screen: Chat,
                navigationOptions: ({ navigation }) => ({
                    title: 'Inbox',
                }),
            },
            favourite: {
                screen: Favourite,
                navigationOptions: ({ navigation }) => ({
                    title: 'Favourite',
                }),
            },
            dashboard: {
                screen: Dashboard,
                navigationOptions: ({ navigation }) => ({
                    title: 'Home',
                    initialRouteName: 'dashboard'
                }),
            },
            setting: {
                screen: SettingScreen,
                navigationOptions: ({ navigation }) => ({
                    title: 'Setting',
                }),
            },
            survey: {
                screen: NutritionistSurvey,
                navigationOptions: ({ navigation }) => ({
                    title: 'Survey',
                }),
            },
        }),
        navigationOptions: ({ navigation }) => ({
            title: 'Dashboard',

        }),

    },
</code>```

Even though the navigation works completely fine I just need a way to load dashboard screen whenever the user navigates to Dashboard.

答: For those facing this issue in 2022, v6.x of React Navigation, the correct way is to specify the initalRouteName prop in the Navigator component. Link to docs

Body:
I want to load dashboard to be active tab in react Native bottom tab. Navigation whenever dashboard is loaded but whenever I move to dashboard it moves to inbox screen which is the first element in my react Bottom Tab Navigation. Is there any way to create a default screen whenever screen bottom tabs is used?

The code I am using for bottom navigation is

 dashboard: {
        screen: createBottomTabNavigator({
            inbox: {
                screen: Chat,
                navigationOptions: ({ navigation }) => ({
                    title: 'Inbox',
                }),
            },
            favourite: {
                screen: Favourite,
                navigationOptions: ({ navigation }) => ({
                    title: 'Favourite',
                }),
            },
            dashboard: {
                screen: Dashboard,
                navigationOptions: ({ navigation }) => ({
                    title: 'Home',
                    initialRouteName: 'dashboard'
                }),
            },
            setting: {
                screen: SettingScreen,
                navigationOptions: ({ navigation }) => ({
                    title: 'Setting',
                }),
            },
            survey: {
                screen: NutritionistSurvey,
                navigationOptions: ({ navigation }) => ({
                    title: 'Survey',
                }),
            },
        }),
        navigationOptions: ({ navigation }) => ({
            title: 'Dashboard',

        }),

    },

Even though the navigation works completely fine I just need a way to load dashboard screen whenever the user navigates to Dashboard.


问:
SSH git traffic Access control
My SSH trafic flow is as shown in the diagram below.

Requirement is to Block all SSH traffic and allow only few list of project to be accessed from F5 LB which will be originated from  for DMZ zone.

The Node1 & Node 2 are also part of internal network serving SSH trafic and these nodes /servers has large number of Repos hosted and we do not want to open all repo access through DMZ zone.

I understand end users are able to clone only repos on which SSH key is added however an user from DMZ can add his key to other repo which must not be Approved to access from DMZ zone and get access to a repo hosted on Bitbucket server.

Goal to Achieve:

Block all SSH traffic and allow only few list of project to be accessed from F5 LB which will be originated from  for DMZ zone.

The git SSH traffic will carry URLs like  “ssh://git@my.domain.com:7999/prj_name/repo_name.git”

Questions:

How can I enforce access control for SSH traffic in this environment?

I tried setting up HAproxy however could not block / apply ACL on ssh urls. Is HAproxy helps to block ssh using url strings? if yes please guide / share an example HAProxy rules for SSH URL blocking.

Seeking suggestions / guidance in this regard.

Thank you for your attention in advance :)

答:
There is a blog post which could help you to solve your requirement.

Route SSH Connections with HAProxy

Title: SSH git traffic Access control


问:
How should you pass canvas context to methods in React?
First time working with canvas in react. I am wondering what the best way to provide methods with the canvas context is (like paint below). Should I use Refs? State? Or is there another way. Thanks

Here is what I have for using refs so far:

```<code>class Canvas  extends React.Component{
  canvasRef = React.createRef();
  contextRef = React.createRef();

  componentDidMount() {
    const canvas = this.canvasRef.current;
    const context = canvas.getContext("2d");
    this.contextRef.current = context;
  }

  paint = (e) => {
    this.contextRef.current.lineTo(e.clientX, e.clientY);
    this.contextRef.current.stroke();
  };

  render() {
    return ( <
      canvas id = "canvas"
      ref = {
        this.canvasRef
      }
      onMouseMove = {
        this.paint
      }
      />
    );
  }
}
</code>```

答:
Refs are correct for getting the canvas, but I'd suggest getting the 2D context each time you need it (getContext just returns the same context as the previous time).

You have a few other minor issues with that code, here's an example putting the context in an instance property, and fixing various issues called out inline.

```<code>class Canvas extends React.Component { // *** Note: You need to extend `React.Component`
    canvasRef = React.createRef(); // *** Note: You shouldn't have `this.` here

    paint = (e) => {
        // ** Get the canvas
        const canvas = this.canvasRef.current;
        if (!canvas) {
            return; // This probably won't happen
        }
        // Get the context
        const context = canvas.getContext("2d");
        // Get the point to draw at, allowing for the possibility
        // that the canvas isn't at the top of the doc
        const { left, top } = canvas.getBoundingClientRect();
        const x = e.clientX - left;
        const y = e.clientY - top;
        context.lineTo(x, y);
        context.stroke();
    }; // *** Added missing ; here

    render() {
        return <canvas ref={this.canvasRef} onMouseMove={this.paint} />;
    }
}
</code>```

(I removed the id on the canvas, since your component might get used in more than one place.)

In a comment you mentioned issues with state changes causing trouble (I saw that as well when trying to get and keep the context rather than getting it each time), so I've added state both to a parent container element and also to the Canvas element in the following example to check that it continues to work, which it does:

const { useState } = React;

class Canvas extends React.Component { // *** Note: You need to extend `React.Component`
    canvasRef = React.createRef(); // *** Note: You shouldn't have `this.` here

    state = {
        ticker: 0,
    };

    paint = (e) => {
        // ** Get the canvas
        const canvas = this.canvasRef.current;
        if (!canvas) {
            return; // This probably won't happen
        }
        // Get the context
        const context = canvas.getContext("2d");
        // Get the point to draw at, allowing for the possibility
        // that the canvas isn't at the top of the doc
        const { left, top } = canvas.getBoundingClientRect();
        const x = e.clientX - left;
        const y = e.clientY - top;
        context.lineTo(x, y);
        context.stroke();
    }; // *** Added missing ; here

    increment = () => {
        this.setState(( { ticker }) => ({ ticker: ticker + 1 }));
    };

    render() {
        const { ticker } = this.state;
        return

            <canvas ref={this.canvasRef} onMouseMove={this.paint} />

Canvas ticker: {ticker}

;
    }
}

class Example extends React.Component {
    state = {
        ticker: 0,
    };

    increment = () => {
        this.setState(({ ticker }) => ({ ticker: ticker + 1 }));
    };

    render() {
        const { ticker } = this.state;
        return

Parent ticker: {ticker}

            <Canvas />

;
    }
}

ReactDOM.render(<Example />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script></code>```

Body:
First time working with canvas in react. I am wondering what the best way to provide methods with the canvas context is (like paint below). Should I use Refs? State? Or is there another way. Thanks

Here is what I have for using refs so far:

class Canvas  extends React.Component{
  canvasRef = React.createRef();
  contextRef = React.createRef();

  componentDidMount() {
    const canvas = this.canvasRef.current;
    const context = canvas.getContext("2d");
    this.contextRef.current = context;
  }

  paint = (e) => {
    this.contextRef.current.lineTo(e.clientX, e.clientY);
    this.contextRef.current.stroke();
  };

  render() {
    return ( <
      canvas id = "canvas"
      ref = {
        this.canvasRef
      }
      onMouseMove = {
        this.paint
      }
      />
    );
  }
}

Body:
Refs are correct for getting the canvas, but I'd suggest getting the 2D context each time you need it (getContext just returns the same context as the previous time).

You have a few other minor issues with that code, here's an example putting the context in an instance property, and fixing various issues called out inline.

class Canvas extends React.Component { // *** Note: You need to extend `React.Component`
    canvasRef = React.createRef(); // *** Note: You shouldn't have `this.` here

    paint = (e) => {
        // ** Get the canvas
        const canvas = this.canvasRef.current;
        if (!canvas) {
            return; // This probably won't happen
        }
        // Get the context
        const context = canvas.getContext("2d");
        // Get the point to draw at, allowing for the possibility
        // that the canvas isn't at the top of the doc
        const { left, top } = canvas.getBoundingClientRect();
        const x = e.clientX - left;
        const y = e.clientY - top;
        context.lineTo(x, y);
        context.stroke();
    }; // *** Added missing ; here

    render() {
        return <canvas ref={this.canvasRef} onMouseMove={this.paint} />;
    }
}

(I removed the id on the canvas, since your component might get used in more than one place.)

In a comment you mentioned issues with state changes causing trouble (I saw that as well when trying to get and keep the context rather than getting it each time), so I've added state both to a parent container element and also to the Canvas element in the following example to check that it continues to work, which it does:

const { useState } = React;

class Canvas extends React.Component { // *** Note: You need to extend `React.Component`
    canvasRef = React.createRef(); // *** Note: You shouldn't have `this.` here

    state = {
        ticker: 0,
    };

    paint = (e) => {
        // ** Get the canvas
        const canvas = this.canvasRef.current;
        if (!canvas) {
            return; // This probably won't happen
        }
        // Get the context
        const context = canvas.getContext("2d");
        // Get the point to draw at, allowing for the possibility
        // that the canvas isn't at the top of the doc
        const { left, top } = canvas.getBoundingClientRect();
        const x = e.clientX - left;
        const y = e.clientY - top;
        context.lineTo(x, y);
        context.stroke();
    }; // *** Added missing ; here

    increment = () => {
        this.setState(( { ticker }) => ({ ticker: ticker + 1 }));
    };

    render() {
        const { ticker } = this.state;
        return <div>
            <canvas ref={this.canvasRef} onMouseMove={this.paint} />
            <div onClick={this.increment}>Canvas ticker: {ticker}</div>
        </div>;
    }
}

class Example extends React.Component {
    state = {
        ticker: 0,
    };

    increment = () => {
        this.setState(({ ticker }) => ({ ticker: ticker + 1 }));
    };

    render() {
        const { ticker } = this.state;
        return <div>
            <div onClick={this.increment}>Parent ticker: {ticker}</div>
            <Canvas />
        </div>;
    }
}

ReactDOM.render(<Example />, document.getElementById("root"));

<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>


问:
VMWare Workstation's strange bootloader behaviour (failing to print a character)
```<code>.code16
.text
.org 0x0

.global _start

_start:
  jmp _testing
  nop

_testing:
  mov $0x0E, %ah
  mov the_byte, %al       #the line in question
  int $0x10

  jmp .

the_byte: .byte 0x41

.fill (510-(.-_start)), 1, 0
.word 0xAA55

</code>```

This simple 'bootloader', as it were, is supposed to print out A to the screen, but it fails to do so when I'm using VMWare Workstation 16 (unlike Bochs, which happily shows A on its screen). If I change the line in question to

```<code>mov $0x41, %al
</code>```

I can see A on VMWare Workstation as well.
Have you by any chance got any idea what can be causing such strange behaviour?

PS. It is indeed loaded into 0x7C00 with a separate linker file.

答:
Apparently, mov the_byte, %al is assembled into something akin to mov %ds:0x7C0C, %al, hence DS had to be zeroed out (along with other segment pointers):

```<code>cli
mov  %cs, %ax # CS is set to 0x0
mov  %ax, %es # ES = CS = 0x0
mov  %ax, %ds # DS = CS = 0x0
mov  %ax, %ss # SS = CS = 0x0
sti
</code>```

Body:
.code16
.text
.org 0x0

.global _start

_start:
  jmp _testing
  nop

_testing:
  mov $0x0E, %ah
  mov the_byte, %al       #the line in question
  int $0x10

  jmp .

the_byte: .byte 0x41

.fill (510-(.-_start)), 1, 0
.word 0xAA55

This simple 'bootloader', as it were, is supposed to print out A to the screen, but it fails to do so when I'm using VMWare Workstation 16 (unlike Bochs, which happily shows A on its screen). If I change the line in question to

mov $0x41, %al

I can see A on VMWare Workstation as well.
Have you by any chance got any idea what can be causing such strange behaviour?

PS. It is indeed loaded into 0x7C00 with a separate linker file.

Body:
Apparently, mov the_byte, %al is assembled into something akin to mov %ds:0x7C0C, %al, hence DS had to be zeroed out (along with other segment pointers):

cli
mov  %cs, %ax # CS is set to 0x0
mov  %ax, %es # ES = CS = 0x0
mov  %ax, %ds # DS = CS = 0x0
mov  %ax, %ss # SS = CS = 0x0
sti


问:
How to show the current file being edited in the project view in PyCharm?
I am using PyCharm Community Edition 4.5.1.  Suppose I have a file open in the editor, and I want to see it in the project view (usually so I can open a sibling file).  How do I do that?

I've googled all manner of "navigate" and "find" and such, and it's always some related concept, but not this one.

答:
It is very convenient, in my opinion, to use a sequence of the following keys:

Alt-F1

Just number button 1

This way you can show a file without having to use a mouse.


问:
How do node_modules packages read config files in the project root?
I am creating an npm package that needs to be able to read config files from the project root. I'm not sure how to do this.

For example,

Next.js is able to read ./pages/ and ./next.config.js from the project root

Jest is able to read ./jest.config.js from the project root

ESLint is able to read ./.eslintrc.json from the project root

Prettier is able to read ./.prettierrc.js from the project root

Typescript is able to read ./tsconfig.json from the project root

Babel is able to read ./.babelrc from the project root

I've tried looking at their source code to see how they do it but the projects are so large that I can't find the relevant section.

How do they achieve this?

答:
There are multiple ways to do it. I've created a test-package, and a demo project node-package-test to test it.

For ready reference providing the main code here:

project-main\node_modules\test-package\index.js :

```<code>const path = require('path');
const fs = require('fs');

const CONFIG_NAME = 'cfg.json';

function init(rootDir = null) {
  console.log(`test-package: process.cwd(): ${process.cwd()}`);
  console.log(`test-package: path.resolve('./'): ${path.resolve('./')}`);

  if (!rootDir) {
    //rootDir = path.resolve('./');
    // OR
    rootDir = process.cwd();
  }

  //const configPath = path.resolve('./', CONFIG_NAME);
  // OR
  const configPath = path.join(rootDir, CONFIG_NAME);

  if (fs.existsSync(configPath)) {
    console.log(`test-package: Reading config from: ${configPath}`);
    try {
      //const data = fs.readFileSync(configPath, 'utf8');
      //const config = JSON.parse(data);
      // OR
      const config = require(configPath);
      console.log(config);
    } catch (err) {
      console.error(err)
    }
  } else {

    console.log(`test-package: Couldn't find config file ${configPath}. Using default.`)
  }

  console.log('\n')
}

//init()
const features = {
  init: init,
  message: `Hello from test-package! `
}

module.exports = features;
</code>```

project-main\main.js :

```<code>const utils = require('@onkarruikar/test-package')

utils.init();
// OR use
//utils.init('/path/to/rootdir');

console.log(`${utils.message}`);
</code>```

Output:

```<code>E:\node-package-test-main>npm install

added 1 package, and audited 2 packages in 4s

found 0 vulnerabilities

E:\node-package-test-main>npm start

> start
> node .

test-package: process.cwd(): E:\node-package-test-main
test-package: path.resolve('./'): E:\node-package-test-main
test-package: Reading config from: E:\node-package-test-main\cfg.json
{ compilerOptions: { allowJs: true, checkJs: true, noEmit: true } }

Hello from test-package!
</code>```

Body:
There are multiple ways to do it. I've created a test-package, and a demo project node-package-test to test it.

For ready reference providing the main code here:

project-main\node_modules\test-package\index.js :

const path = require('path');
const fs = require('fs');

const CONFIG_NAME = 'cfg.json';

function init(rootDir = null) {
  console.log(`test-package: process.cwd(): ${process.cwd()}`);
  console.log(`test-package: path.resolve('./'): ${path.resolve('./')}`);

  if (!rootDir) {
    //rootDir = path.resolve('./');
    // OR
    rootDir = process.cwd();
  }

  //const configPath = path.resolve('./', CONFIG_NAME);
  // OR
  const configPath = path.join(rootDir, CONFIG_NAME);

  if (fs.existsSync(configPath)) {
    console.log(`test-package: Reading config from: ${configPath}`);
    try {
      //const data = fs.readFileSync(configPath, 'utf8');
      //const config = JSON.parse(data);
      // OR
      const config = require(configPath);
      console.log(config);
    } catch (err) {
      console.error(err)
    }
  } else {

    console.log(`test-package: Couldn't find config file ${configPath}. Using default.`)
  }

  console.log('\n')
}

//init()
const features = {
  init: init,
  message: `Hello from test-package! `
}

module.exports = features;

project-main\main.js :

const utils = require('@onkarruikar/test-package')

utils.init();
// OR use
//utils.init('/path/to/rootdir');

console.log(`${utils.message}`);

Output:

E:\node-package-test-main>npm install

added 1 package, and audited 2 packages in 4s

found 0 vulnerabilities

E:\node-package-test-main>npm start

> start
> node .

test-package: process.cwd(): E:\node-package-test-main
test-package: path.resolve('./'): E:\node-package-test-main
test-package: Reading config from: E:\node-package-test-main\cfg.json
{ compilerOptions: { allowJs: true, checkJs: true, noEmit: true } }

Hello from test-package!


问:
AWS Unmount Volume without Deleting
How should I unmount a drive well ensuring it wont be deleted?
We want to move

```<code>vol-0de12fb88020aa624
from i-0b727a35caea24013 to i-0dff0911c0ebf45f9
</code>```

we want to move the volume, do not want copy files from one EBS volume to another EBS volume ?? I have EBS Snapshot enable already .
can anyone advice me with the best way for this ?

答:
I don't know if it is the best way to do it but i would take a snapshot and creating a new EBS volume from it and attach it to the new instance and after see that all is good remove the old one. Doing it like this you don't remove a working state before getting a new up.

Read on restoring snapshots here:
https://docs.aws.amazon.com/prescriptive-guidance/latest/backup-recovery/restore.html

Title: AWS Unmount Volume without Deleting

Body:
How should I unmount a drive well ensuring it wont be deleted?
We want to move

vol-0de12fb88020aa624
from i-0b727a35caea24013 to i-0dff0911c0ebf45f9

we want to move the volume, do not want copy files from one EBS volume to another EBS volume ?? I have EBS Snapshot enable already .
can anyone advice me with the best way for this ?


问:
Best way to trigger worker_thread OOM exception in Node.js
I would like to test code that reports when a worker_thread OOMs. Or at least that the parent is OK despite the thread crashing due to OOM reasons. I would like to specifically test Node.js killing a worker_thread.

I'm not even sure this is particularly testable since the environment in which Node.js is running seems to make a difference. Setting low old generation size (docs) using resource limits does not behave the way I thought it would, it seems Node.js and the OS are doing a lot of clever things to keep the process from blowing up in memory. The closest I have gotten is that both Node.js AND the worker are killed. But again, this is not the behaviour I was expecting - Node.js should be killing the worker.

Is there any way to reliably test for something like this? Currently running v16.13.2.

[EDIT]

Here is some sample JS for the worker:

const { isMainThread } = require('worker_threads');

if (!isMainThread) {
  let as = [];

  for (let i = 0; i < 100; i++) {
    let a = '';
    for (let i = 0; i < 9000000; i++) a += i.toString();
    as.push(a);
  }
}
```

答: OK, it looks like adding maxYoungGenerationSizeMb in my case is resulting in the behaviour I was looking for: e.g. { maxOldGenerationSizeMb: 10, maxYoungGenerationSizeMb: 10 }.


问:
Access intranet URL on SharePoint Online?
In my company we have some internal URLs what we would like to link to in the cloud.

I've created an SPFx web part and try to display an HTML img tag with the URL of http://intranetserver/MyPics/user123/headshot.jpg

but I get

Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR

Is there something I need to do within my web part solution or Azure to allow this access?

答:
You're running into an SSL issue because you're trying to load content from a non-secure URL (http instead of https), not to mention it's from another domain, so cross-domain concerns play into it as well.

The two best choices are:

Upload the image(s) directly to your SPO site, in the default images document library

(or another, more private document library if necessary)

Create an SSL certificate and place it on the internal server that's hosting the images


问:
Android: How to access a file in the SD Card
I'm trying to access the image on the SD card using below code but I"m getting File not found exception. Can someone tell me a correct way to acess the file???</p>

```<code>new File("/mnt/sdcard/splah2.jpg")
</code>```

答: Try running: new File(Environment.getExternalStorageDirectory() + "/splah2.jpg")

Body:
I'm trying to access the image on the SD card using below code but I"m getting File not found exception. Can someone tell me a correct way to acess the file???

new File("/mnt/sdcard/splah2.jpg")


问:
Why nested structure is needed in singly linked list?
I'm new to data structures and algorithms. Right know I'm learning singly linked lists and I'm confused with a piece of code that creates a linked list.

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

struct node
{
    int data;
    struct node *next;
};

int main()
{
    int n;
    struct node *head = NULL;
    head = malloc(sizeof(struct node));

    head->data = 36;
    head->next = NULL;

    printf("%d", head->data);
}
</code>```

My question is why we have to use struct node *next; part in order to refer to memory location of next node.

Why can't we instead use int *next?

答:
In fact, you may write like

```<code>struct node
{
    int data;
    int *next;
};
</code>```

To allocate the head node you can write (as you already did)

```<code>head = malloc(sizeof(struct node));

head->data = 36;
head->next = NULL;
</code>```

If you want to allocate the next node you have to write

```<code>head->next = malloc( sizeof( struct node ) );
</code>```

But to assign values to the newly created node you have to write

```<code>( ( struct node * )head->next )->data = 37;
( ( struct node * )head->next )->next = NULL;
</code>```

Such a code will only confuse readers of the code.

That is you are allocating memory for an object of the type struct node but then you are interpreting the pointer to the allocated memory as having the type int * instead of using a pointer of the type struct node *.  And then again to assign values tp an object of the type struct node you need to cast the pointer of the type int * to the type struct node *. Such a code is error-prone.

Body:
I'm new to data structures and algorithms. Right know I'm learning singly linked lists and I'm confused with a piece of code that creates a linked list.

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

struct node
{
    int data;
    struct node *next;
};

int main()
{
    int n;
    struct node *head = NULL;
    head = malloc(sizeof(struct node));

    head->data = 36;
    head->next = NULL;

    printf("%d", head->data);
}

My question is why we have to use struct node *next; part in order to refer to memory location of next node.

Why can't we instead use int *next?

Body:
In fact, you may write like

struct node
{
    int data;
    int *next;
};

To allocate the head node you can write (as you already did)

head = malloc(sizeof(struct node));

head->data = 36;
head->next = NULL;

If you want to allocate the next node you have to write

head->next = malloc( sizeof( struct node ) );

But to assign values to the newly created node you have to write

( ( struct node * )head->next )->data = 37;
( ( struct node * )head->next )->next = NULL;

Such a code will only confuse readers of the code.

That is you are allocating memory for an object of the type struct node but then you are interpreting the pointer to the allocated memory as having the type int * instead of using a pointer of the type struct node *.  And then again to assign values tp an object of the type struct node you need to cast the pointer of the type int * to the type struct node *. Such a code is error-prone.


问:
Populate Controls into User Control from Another User Control in Winforms C# .Net Core 3.1
I want to populate controls(combobox) into user control from another user control. I checked it and check that controls count in target user control already added, but somehow added controls not showing. Please help, why it not showing?

Parent User Control

```<code>ShortcutTemplate shortcutTemp = new ShortcutTemplate();
shortcutTemp.Dock = DockStyle.Fill;
shortcutTemp.ValuesChanged += ShortcutTemp_ValuesChanged;
shortcutTemp.Values = keyBinding.values;
keyValuesPanel.Controls.Add(shortcutTemp);
</code>```

Target User Control

```<code>public void SetValues(List<string> values)
{
    foreach (string value in values)
    {
        ComboBox newComboBox = new ComboBox();
        newComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
        newComboBox.SelectedIndexChanged += NewComboBox_SelectedIndexChanged;
        newComboBox.DataSource = Enum.GetValues(typeof(KeyCode));

        List<Control> currentControls = new List<Control>();
        foreach (var control in flowLayoutPanel1.Controls)
        {
            currentControls.Add(control as Control);
        }
        currentControls.Insert(currentControls.Count - 2, newComboBox);
        flowLayoutPanel1.Controls.Clear();
        flowLayoutPanel1.Controls.AddRange(currentControls.ToArray());
    }
}
</code>```

答: the problem has been resolved, apparently there is another event that initializes the target user control, my bad. </p>

Body:
I want to populate controls(combobox) into user control from another user control. I checked it and check that controls count in target user control already added, but somehow added controls not showing. Please help, why it not showing?

Parent User Control

ShortcutTemplate shortcutTemp = new ShortcutTemplate();
shortcutTemp.Dock = DockStyle.Fill;
shortcutTemp.ValuesChanged += ShortcutTemp_ValuesChanged;
shortcutTemp.Values = keyBinding.values;
keyValuesPanel.Controls.Add(shortcutTemp);

Target User Control

public void SetValues(List<string> values)
{
    foreach (string value in values)
    {
        ComboBox newComboBox = new ComboBox();
        newComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
        newComboBox.SelectedIndexChanged += NewComboBox_SelectedIndexChanged;
        newComboBox.DataSource = Enum.GetValues(typeof(KeyCode));

        List<Control> currentControls = new List<Control>();
        foreach (var control in flowLayoutPanel1.Controls)
        {
            currentControls.Add(control as Control);
        }
        currentControls.Insert(currentControls.Count - 2, newComboBox);
        flowLayoutPanel1.Controls.Clear();
        flowLayoutPanel1.Controls.AddRange(currentControls.ToArray());
    }
}


问:
How to stop & exit jenkins from Kubernetes cluster
I have installed Jenkins through Helm with below commands.

```<code>$ chart=jenkinsci/jenkins
$ helm install jenkins -n jenkins -f jenkins-values.yaml $chart
</code>```

Now how do i stop & exit Jenkins completely from my kubernetes cluster?

```<code># kubectl delete pod jenkins-0 -n jenkins
pod "jenkins-0" deleted
</code>```

After delete pod command, still it creates new pod.

```<code># kubectl get pods -n jenkins
NAME        READY   STATUS     RESTARTS   AGE
jenkins-0   0/2     Init:0/1   0          6s
</code>```

答: Since I have Jenkins installed through helm. So I have removed the pod and complete deployment inside my namespace using # helm uninstall jenkins -n jenkins.

Body:
I have installed Jenkins through Helm with below commands.

$ chart=jenkinsci/jenkins
$ helm install jenkins -n jenkins -f jenkins-values.yaml $chart

Now how do i stop & exit Jenkins completely from my kubernetes cluster?

# kubectl delete pod jenkins-0 -n jenkins
pod "jenkins-0" deleted

After delete pod command, still it creates new pod.

# kubectl get pods -n jenkins
NAME        READY   STATUS     RESTARTS   AGE
jenkins-0   0/2     Init:0/1   0          6s


问:
jQuery css left/right chosen by array
How would I go about doing something like this:

```<code>var positionY = ['left','right'],
    x = Math.ceil(Math.random()*2);

$('#foo').css({positionY[x]: 200});
</code>```

Is it even possible?

Reason being I want to randomise the left/right.

I'm really wanting to use the brackets in the css function, any ideas?

EDIT --

```<code>$('#foo').animate({
   positionX[1]: 300,
   positionY[1]: 300
}, 300);
</code>```

That's the sort of thing I'm after, any ideas?

答:
Try this

```<code>var cssCfg = {};
//Added left/right style - Similarly add other styles and pass the config
cssCfg[positionY[Math.floor(Math.random() * positionY.length)]] = 200;
//cssCfg["top"] = 10;//somevalue
//cssCfg["bottom"] = 10;//somevalue

$('#foo').css(cssCfg);

var animCfg = {};
animCfg[positionX[1]] = 300;
animCfg[positionY[1]] = 300;

$('#foo').animate(animCfg, 300);
</code>```

Working demo

Title: jQuery css left/right chosen by array

Body:
How would I go about doing something like this:

var positionY = ['left','right'],
    x = Math.ceil(Math.random()*2);

$('#foo').css({positionY[x]: 200});

Is it even possible?

Reason being I want to randomise the left/right.

I'm really wanting to use the brackets in the css function, any ideas?

EDIT --

$('#foo').animate({
   positionX[1]: 300,
   positionY[1]: 300
}, 300);

That's the sort of thing I'm after, any ideas?

Body:
Try this

var cssCfg = {};
//Added left/right style - Similarly add other styles and pass the config
cssCfg[positionY[Math.floor(Math.random() * positionY.length)]] = 200;
//cssCfg["top"] = 10;//somevalue
//cssCfg["bottom"] = 10;//somevalue

$('#foo').css(cssCfg);

var animCfg = {};
animCfg[positionX[1]] = 300;
animCfg[positionY[1]] = 300;

$('#foo').animate(animCfg, 300);

Working demo


问:
Snakemake WorkflowError: Failed to group jobs together
BACKGROUND: I have to adapt my Snakemake pipeline from a single-node usage to a cluster with resource management. With a SLURM-specific Snakemake profile, my rules are successfully submitted as SLURM jobs, so I continued to add the Snakemake directive resources to every non-local rule to optimize queue scheduling. These settings were adopted and my pipeline finished as intended.

EXAMPLE:

```<code>rule ruleA:
    group: "group_1_init"
    resources:
        cpus=1,
        time="00:04:00"

rule ruleB:
    group: "group_1_init"
    resources:
        cpus=1,
        time="00:05:00"
</code>```

ruleA and ruleB are submitted as a single job to a computing node.

PROBLEM: My pipeline has many small, single-CPU jobs that I binned with the Snakemake rule directive group. Here is the error:

```<code>WorkflowError:
Failed to group jobs together. Resource time is a string but not all group jobs require the same value. Observed: 00:05:00 != 00:04:00.
</code>```

I guess, there should be only one resource setting per group but I could not find online resources on the logic behind it.

QUESTION: How do I define my varying resource requirements in group jobs? Should e.g. time reflect the computing time of the whole group of jobs or does Snakemake sum-up rule times within a group as a parameter for the SLURM job submission. For cpus in turn, that would be the max cpus among all rules.

答:
Without parameter conversion by an additional script, the resource time has to be an integer and is interpreted as minutes. This is the correction:

```<code>rule ruleA:
    group: "group_1_init"
    resources:
        cpus=1,
        time=4
rule ruleB:
    group: "group_1_init"
    resources:
        cpus=1,
        time=5
</code>```

Body:
BACKGROUND: I have to adapt my Snakemake pipeline from a single-node usage to a cluster with resource management. With a SLURM-specific Snakemake profile, my rules are successfully submitted as SLURM jobs, so I continued to add the Snakemake directive resources to every non-local rule to optimize queue scheduling. These settings were adopted and my pipeline finished as intended.

EXAMPLE:

rule ruleA:
    group: "group_1_init"
    resources:
        cpus=1,
        time="00:04:00"

rule ruleB:
    group: "group_1_init"
    resources:
        cpus=1,
        time="00:05:00"

ruleA and ruleB are submitted as a single job to a computing node.

PROBLEM: My pipeline has many small, single-CPU jobs that I binned with the Snakemake rule directive group. Here is the error:

WorkflowError:
Failed to group jobs together. Resource time is a string but not all group jobs require the same value. Observed: 00:05:00 != 00:04:00.

I guess, there should be only one resource setting per group but I could not find online resources on the logic behind it.

QUESTION: How do I define my varying resource requirements in group jobs? Should e.g. time reflect the computing time of the whole group of jobs or does Snakemake sum-up rule times within a group as a parameter for the SLURM job submission. For cpus in turn, that would be the max cpus among all rules.

Body:
Without parameter conversion by an additional script, the resource time has to be an integer and is interpreted as minutes. This is the correction:

rule ruleA:
    group: "group_1_init"
    resources:
        cpus=1,
        time=4
rule ruleB:
    group: "group_1_init"
    resources:
        cpus=1,
        time=5


问:
Struts2 JSON to Java Action Object (can't find the error)
I have tried multiple versions and read several related answers, but I still cant figure out why Struts is not populating my Action property user.

This is my ajax call

```<code>function save_new_user() {

    var user =
    {       username: $('#new_user_username').val(),
            email: $('#new_user_email').val(),
            password: $('#new_user_password').val()
    };

    user_json = JSON.stringify(user);
    console.log(user_json);

    var data = {'user': user_json};

    $.ajax({
        type : 'GET',
        url : 'SaveNewUser',
        data: data,
        dataType : "json",
        contentType: 'application/json',
        success : function(data, textStatus, jqXHR) {
            if(data) {

            }
        },
    });
}
</code>```

which, by the way, print this in the console

```<code>{"username":"dd","email":"ff","password":"gg"}
</code>```

My Action class (with annotations), (I am not modifying the json-default interceptor from struts2-json-plugin-2.3.24.1) is

```<code>package coproject.cpweb.actions;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;

import coproject.cpweb.utils.db.entities.UserDum;
import coproject.cpweb.utils.db.services.DbServicesImp;

@Action("SaveNewUser")
@ParentPackage("json-default")
@Results({
    @Result(name="success", type="json"),
    @Result(name="input", location="/views/error.jsp")
})
public class SaveNewUser extends ActionSupport{

    private static final long serialVersionUID = 1L;

    /* Services  */
    DbServicesImp dbServices;

    public DbServicesImp getDbServices() {
        return dbServices;
    }

    public void setDbServices(DbServicesImp dbServices) {
        this.dbServices = dbServices;
    }

    /* Input Json  */
    private UserDum user = new UserDum();

    public UserDum getUser() {
        return user;
    }

    public void setUser(UserDum user) {
        this.user = user;
    }

    /* Execute */
    public String execute() throws Exception  {

        // dbServices.saveUser(user);

        System.out.println(user.getUsername());

        return "SUCCESS";
    }

}
</code>```

And the UserDum entity is

```<code>package coproject.cpweb.utils.db.entities;

public class UserDum {

    private String username;
    private String email;
    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}
</code>```

However, when the request arrives, the json interceptor of struts-json-plugin gets an exception trying to set "user".

```<code>feb 04, 2016 12:20:14 PM com.opensymphony.xwork2.interceptor.ParametersInterceptor error
SEVERE: Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'user' on 'class coproject.cpweb.actions.SaveNewUser: Error setting expression 'user' with val
ue ['{"username":"dd","email":"ff","password":"gg"}', ]
feb 04, 2016 12:20:14 PM com.opensymphony.xwork2.util.LocalizedTextUtil warn
WARNING: Missing key [invalid.fieldvalue.user] in bundles [[org/apache/struts2/struts-messages, com/opensymphony/xwork2/xwork-mess
ages]]!
</code>```

Any clues on what might be the error?

答:
I was also stuck with the same error, and it was a silly mistake while using POSTMAN, the Body type should be set to JSON, for me the default option of TEXT type was selected.

Provided I used the JSON Interceptor.

```<code><action name="sample" class="com.wildcard.action.SampleController">
            <interceptor-ref name="json"/>
             <interceptor-ref name="defaultStack"/>

<!-- declarations for mappings from Request JSON Body goes here-->
            <result type="json">
                <param name="root">key_from_json_body</param>
            </result>
        </action>
</code>```

Body:
I have tried multiple versions and read several related answers, but I still cant figure out why Struts is not populating my Action property user.

This is my ajax call

function save_new_user() {

    var user =
    {       username: $('#new_user_username').val(),
            email: $('#new_user_email').val(),
            password: $('#new_user_password').val()
    };

    user_json = JSON.stringify(user);
    console.log(user_json);

    var data = {'user': user_json};

    $.ajax({
        type : 'GET',
        url : 'SaveNewUser',
        data: data,
        dataType : "json",
        contentType: 'application/json',
        success : function(data, textStatus, jqXHR) {
            if(data) {

            }
        },
    });
}

which, by the way, print this in the console

{"username":"dd","email":"ff","password":"gg"}

My Action class (with annotations), (I am not modifying the json-default interceptor from struts2-json-plugin-2.3.24.1) is

package coproject.cpweb.actions;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;

import coproject.cpweb.utils.db.entities.UserDum;
import coproject.cpweb.utils.db.services.DbServicesImp;

@Action("SaveNewUser")
@ParentPackage("json-default")
@Results({
    @Result(name="success", type="json"),
    @Result(name="input", location="/views/error.jsp")
})
public class SaveNewUser extends ActionSupport{

    private static final long serialVersionUID = 1L;

    /* Services  */
    DbServicesImp dbServices;

    public DbServicesImp getDbServices() {
        return dbServices;
    }

    public void setDbServices(DbServicesImp dbServices) {
        this.dbServices = dbServices;
    }

    /* Input Json  */
    private UserDum user = new UserDum();

    public UserDum getUser() {
        return user;
    }

    public void setUser(UserDum user) {
        this.user = user;
    }

    /* Execute */
    public String execute() throws Exception  {

        // dbServices.saveUser(user);

        System.out.println(user.getUsername());

        return "SUCCESS";
    }

}

And the UserDum entity is

package coproject.cpweb.utils.db.entities;

public class UserDum {

    private String username;
    private String email;
    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

However, when the request arrives, the json interceptor of struts-json-plugin gets an exception trying to set "user".

feb 04, 2016 12:20:14 PM com.opensymphony.xwork2.interceptor.ParametersInterceptor error
SEVERE: Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'user' on 'class coproject.cpweb.actions.SaveNewUser: Error setting expression 'user' with val
ue ['{"username":"dd","email":"ff","password":"gg"}', ]
feb 04, 2016 12:20:14 PM com.opensymphony.xwork2.util.LocalizedTextUtil warn
WARNING: Missing key [invalid.fieldvalue.user] in bundles [[org/apache/struts2/struts-messages, com/opensymphony/xwork2/xwork-mess
ages]]!

Any clues on what might be the error?

Body:
I was also stuck with the same error, and it was a silly mistake while using POSTMAN, the Body type should be set to JSON, for me the default option of TEXT type was selected.

Provided I used the JSON Interceptor.

<action name="sample" class="com.wildcard.action.SampleController">
            <interceptor-ref name="json"/>
             <interceptor-ref name="defaultStack"/>

<!-- declarations for mappings from Request JSON Body goes here-->
            <result type="json">
                <param name="root">key_from_json_body</param>
            </result>
        </action>


问:
How can I change slides with useState in react?
It's probably a basic stuff, but I'm trying to figure out how can I change slides clicking on button. I have divs with data from movies API, so I'm clicking a button and I change slides, toggling active class in it. I can imagine doing it in plain javascript, but I'm trying to understand how can I do it in React.
The function looks like this:

```<code> const [currentSlide, setCurrentSlide] = useState(0);
function changeSlide(){
      if(currentSlide <= few_movies.length){
          setCurrentSlide(currentSlide + 1);
      }else if(currentSlide >= few_movies.length){

      }
  }
</code>```

So here, if currentSlide is less than length of movies array, I set the currentSlide to the next one. But I'm trying to figure out what could I do if currentSlide reaches an endpoint. I tried doing setCurrentslide(0) so it starts from the first slide again, but it doesn't really make sense.
Code for slide div:

```<code><div className={`poster__item ${currentSlide===key ? 'active' : ''}`}</div>
</code>```

Edit: So I added useInterval so it'd loop automatically through movives, but now it only changes back and forth between two first items without going further. Code looks like this:

```<code>useEffect(() =>{
        setInterval(() =>{
          if(currentSlide < few_movies.length - 1){
            setCurrentSlide(currentSlide + 1);
        }else(currentSlide >= few_movies.length){
          setCurrentSlide(0);
        }
        }, 2000)
  },[])
</code>```

答:
The updated code you posted, with the setInterval inside the useEffect id problematic because the currentSlide will never change inside it, since the useEffect has no dependencies. It will always remain at 0, the initial value.

You can use setTimeout instead (with the use of the dependency list of useEffect), or you can use the function form which provides the current value and you return the new one.

so either

useEffect(() => {
  const timeout = setTimeout(() => {
    if (currentSlide < few_movies.length - 1) {
      setCurrentSlide(currentSlide + 1);
    } else {
      setCurrentSlide(0);
    }

    return () => clearTimeout(timeout);
  }, 2000);
}, [currentSlide])
```
<p>or</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>useEffect(() => {
  const interval = setInterval(() => {
    setCurrentSlide((currentSlideValue) => {
      if (currentSlide < few_movies.length - 1) {
        return currentSlide + 1;
      }
      return 0;
    })

    return () => clearInterval(interval);
  }, 2000);
}, [])</code>```

Body:
It's probably a basic stuff, but I'm trying to figure out how can I change slides clicking on button. I have divs with data from movies API, so I'm clicking a button and I change slides, toggling active class in it. I can imagine doing it in plain javascript, but I'm trying to understand how can I do it in React.
The function looks like this:

 const [currentSlide, setCurrentSlide] = useState(0);
function changeSlide(){
      if(currentSlide <= few_movies.length){
          setCurrentSlide(currentSlide + 1);
      }else if(currentSlide >= few_movies.length){

      }
  }

So here, if currentSlide is less than length of movies array, I set the currentSlide to the next one. But I'm trying to figure out what could I do if currentSlide reaches an endpoint. I tried doing setCurrentslide(0) so it starts from the first slide again, but it doesn't really make sense.
Code for slide div:

<div className={`poster__item ${currentSlide===key ? 'active' : ''}`}

Edit: So I added useInterval so it'd loop automatically through movives, but now it only changes back and forth between two first items without going further. Code looks like this:

useEffect(() =>{
        setInterval(() =>{
          if(currentSlide < few_movies.length - 1){
            setCurrentSlide(currentSlide + 1);
        }else(currentSlide >= few_movies.length){
          setCurrentSlide(0);
        }
        }, 2000)
  },[])

Body:
The updated code you posted, with the setInterval inside the useEffect id problematic because the currentSlide will never change inside it, since the useEffect has no dependencies. It will always remain at 0, the initial value.

You can use setTimeout instead (with the use of the dependency list of useEffect), or you can use the function form which provides the current value and you return the new one.

so either

useEffect(() => {
  const timeout = setTimeout(() => {
    if (currentSlide < few_movies.length - 1) {
      setCurrentSlide(currentSlide + 1);
    } else {
      setCurrentSlide(0);
    }

    return () => clearTimeout(timeout);
  }, 2000);
}, [currentSlide])

or

useEffect(() => {
  const interval = setInterval(() => {
    setCurrentSlide((currentSlideValue) => {
      if (currentSlide < few_movies.length - 1) {
        return currentSlide + 1;
      }
      return 0;
    })

    return () => clearInterval(interval);
  }, 2000);
}, [])


问:
malloc convert memory for struct
What is the right way to malloc memory ? And what is the difference between them ?

```<code>void parse_cookies(const char *cookie, cookie_bank **my_cookie, int *cookies_num)
{
   *my_cookie = malloc(sizeof(cookie_bank) * 1);
   *my_cookie = (cookie_bank *)malloc(sizeof(cookie_bank) * 1);
   my_cookie = (cookie_bank **)malloc(sizeof(cookie_bank) * 1);
   ///
}
</code>```

I'm trying to malloc array of cookie_bank structs function.

答:
I'm assuming that you want the function to allocate memory for an array and passing the result via a pointer parameter. So, you want to write T * x = malloc(...), and assign the result to a pointer argument, *y = x:

```<code>cookie_bank * myarray;
parse_cookies(..., &myarray, ...);
/* now have myarray[0], myarray[1], ... */
</code>```

So the correct invocation should be, all rolled into one line,

```<code>parse_cookies(..., cookie_bank ** y, ...)
{
  *y = malloc(sizeof(cookie_bank) * NUMBER_OF_ELEMENTS);
}
</code>```

Title: malloc convert memory for struct

Body:
What is the right way to malloc memory ? And what is the difference between them ?

void parse_cookies(const char *cookie, cookie_bank **my_cookie, int *cookies_num)
{
   *my_cookie = malloc(sizeof(cookie_bank) * 1);
   *my_cookie = (cookie_bank *)malloc(sizeof(cookie_bank) * 1);
   my_cookie = (cookie_bank **)malloc(sizeof(cookie_bank) * 1);
   ///
}

I'm trying to malloc array of cookie_bank structs function.

Body:
I'm assuming that you want the function to allocate memory for an array and passing the result via a pointer parameter. So, you want to write T * x = malloc(...), and assign the result to a pointer argument, *y = x:

cookie_bank * myarray;
parse_cookies(..., &myarray, ...);
/* now have myarray[0], myarray[1], ... */

So the correct invocation should be, all rolled into one line,

parse_cookies(..., cookie_bank ** y, ...)
{
  *y = malloc(sizeof(cookie_bank) * NUMBER_OF_ELEMENTS);
}


问:
How to use a new token to push to github?
In order to push something to github it looks like I need to create a new token (again...). But what that new token, how do I tell git to use a new token? What command do I have to use to use the new token?

答:
From the GitHub doc :

Once you have a token, you can enter it instead of your password when
performing Git operations over HTTPS.

so just make sure that the old token is no longer cached in your laptop and use the token generated as a password

you can find in the link how to create a new token


问:
Standard way of representing selection in flowcharts
Okay, so I need know which of below flowcharts has the accepted 'standard' when it comes to representing selection.

AFAIK both are accurate, but which one has the standard representation?

Method 1,

Method 2,

答: I would say that "Method 2" is a standard way of showing this selection flowchart, as a decision (diamond) doesn't usually have both boolean outputs leading to the same point.


问:
why the unless function in perl isn't working
I was writing a simple perl script which calculates payment based on the hours given by the user and the program mustn't allow payments above 500 hrs but has to allow upto 600 for females, and I was using the unless function but it is not working it allows more than 600 hrs for females.

here is the code I used

```<code>print("Enter your working hours");
    $hours=<stdin>;
    print("Enter your gender");
    $gender=<stdin>;
    chomp($gender);
    unless($gender ne "f" && $hours>=600){
        print("Your have earned ",$hours*10," Birr \n");
    }
    else{
         unless($hours>=500){
            print("Your have earned ",$hours*10," Birr \n");
        }
        else{
            print("You have worked beyond the payable hrs!");
        }
    }
</code>```

答:
I always like to state my assumptions up front in a data structure.

```<code>my %allowable_hours = (
  m => 500, # I'm assuming that's your other gender :-)
  f => 600,
);

unless (exists $allowable_hours{$gender}) {
  die "$gender is an unknown gender\n";
}

if ($hours <= $allowable_hours{$gender}) {
  # report
} else {
  # error
}
</code>```

Makes it easier to edit the allowable hours and add new genders (if that ever becomes necessary).

Body:
I was writing a simple perl script which calculates payment based on the hours given by the user and the program mustn't allow payments above 500 hrs but has to allow upto 600 for females, and I was using the unless function but it is not working it allows more than 600 hrs for females.

here is the code I used

print("Enter your working hours");
    $hours=<stdin>;
    print("Enter your gender");
    $gender=<stdin>;
    chomp($gender);
    unless($gender ne "f" && $hours>=600){
        print("Your have earned ",$hours*10," Birr \n");
    }
    else{
         unless($hours>=500){
            print("Your have earned ",$hours*10," Birr \n");
        }
        else{
            print("You have worked beyond the payable hrs!");
        }
    }

Body:
I always like to state my assumptions up front in a data structure.

my %allowable_hours = (
  m => 500, # I'm assuming that's your other gender :-)
  f => 600,
);

unless (exists $allowable_hours{$gender}) {
  die "$gender is an unknown gender\n";
}

if ($hours <= $allowable_hours{$gender}) {
  # report
} else {
  # error
}

Makes it easier to edit the allowable hours and add new genders (if that ever becomes necessary).


问:
Coldfusion, jquery and sending a file using ajax
I'm trying to send file using jquery ajax method, and I don't know how to receive it in Coldfusion, convert it in proper file object, and finally, save it on server in Media folder.

There is something I want:

```<code>var myDocument = $('#fileinput').prop('files');
var formData = new FormData();
formData.append('myDocument', myDocument);

   $.ajax({
        url: "./somePath/file.cfc?method=handleDocument",
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        success: function(result,status,xhr){
            doSomething();
        },
        error: function(xhr,status,error){
            doSomethingElse();
        }
    });
</code>```

Now, we are in ./somePath/file.cfc trying to fetch myDocument object and save it:

```<code><cffunction name="handleDocument" access="remote" returnformat="JSON" returntype="string">

        <cfset requestData = GetHttpRequestData()>
        <cfset content = requestData.content>
        <cfset anyExtesion= content.getExtension()>
        <!---There's no such method getExtension(), but I need something like that--->

        <cffile action="write" file="./Media/myDocument.#anyExtesion#" output="#x.content#"/>

       <cfreturn "File is saved in Media folder.">
</cffunction>
</code>```

答:
It's not necessary to manually parse the raw http request data to extract the file information. CFFile handles it for you:

Single file: cffile action="upload"
and FileUpload() **

Multiple files: cffile action="uploadAll" and FileUploadAll() **

** The term 'upload' in the tag/function names is a misnomer. They handle low level i/o tasks for files already uploaded to the server

cffile action="upload"

Single file uploads require the name of the form field containing the file to be uploaded. To avoid hard-coding a static value, make it an argument to the cffunction instead. Use the result variable to return details about the uploaded file as a structure  (See CFFile - Usage Section for a list of the available properties).

Here's a starter example that allows uploading of a .PNG or .JPG file (any other extension throws an exception). A status structure is returned as json, if successful.

```<code><cfcomponent>
    <cffunction name="handleDocument" access="remote" returnformat="JSON" output="false">
        <cfargument name="fileFieldName" type="string" required="true">

        <!--- demo - only allow JPG files  --->
        <cffile action="upload"
                destination="c:/nonwebaccessbile/path"
                fileField="#arguments.fileFieldName#"
                nameconflict="MakeUnique"
                strict="true"
                result="local.result"
                allowedExtensions=".png,.jpg"
        >

        <!--- for demo return saved file name  --->
        <cfreturn {
            "fileWasSaved": local.result.fileWasSaved
            , "serverFile": local.result.serverFile
        } >
    </cffunction>
</cfcomponent>
</code>```

JavaScript

var myDocument = $('#fileinput').prop('files');

One correction to the js code. The above returns a FileList object, not a file. To access the first File in the list, use $('#fileinput').prop('files')[0] instead.

Then since the cffunction requires a field name, append that value to the FormData object before the ajax call:

```<code>var theFileField = $("#fileinput");
var theFieldName = theFileField.prop("name")
var theFirstFile = theFileField.prop("files")[0];

var formData = new FormData();
formData.append('fileFieldName', theFieldName);
formData.append(theFieldName, theFirstFile);

$.ajax({
    url: "./pathto/file.cfc?method=handleDocument",
    type: "POST",
    data: formData,
    dataType: "json",
    contentType: false,
    processData: false
}).done(function(response, status, xhr){
    // do stuff here ...
}).fail(function(xhr,status,error){
    // do stuff here ...
});
</code>```

Security

File uploads can pose a BIG security risk to web apps. Before putting ANY file uploads into production, read up on how to secure them first. A few good resources:

CFML SecureUpload CFC (Github)

Securing ColdFusion Apps 2021 (see "File Uploads" page 63)

OWASP - File Upload Cheat Sheet

Body:
I'm trying to send file using jquery ajax method, and I don't know how to receive it in Coldfusion, convert it in proper file object, and finally, save it on server in Media folder.

There is something I want:

var myDocument = $('#fileinput').prop('files');
var formData = new FormData();
formData.append('myDocument', myDocument);

   $.ajax({
        url: "./somePath/file.cfc?method=handleDocument",
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        success: function(result,status,xhr){
            doSomething();
        },
        error: function(xhr,status,error){
            doSomethingElse();
        }
    });

Now, we are in ./somePath/file.cfc trying to fetch myDocument object and save it:

<cffunction name="handleDocument" access="remote" returnformat="JSON" returntype="string">

        <cfset requestData = GetHttpRequestData()>
        <cfset content = requestData.content>
        <cfset anyExtesion= content.getExtension()>

        <cffile action="write" file="./Media/myDocument.#anyExtesion#" output="#x.content#"/>

       <cfreturn "File is saved in Media folder.">
</cffunction>

Body:
It's not necessary to manually parse the raw http request data to extract the file information. CFFile handles it for you:

Single file: cffile action="upload"
and FileUpload() **

Multiple files: cffile action="uploadAll" and FileUploadAll() **

** The term 'upload' in the tag/function names is a misnomer. They handle low level i/o tasks for files already uploaded to the server

cffile action="upload"

Single file uploads require the name of the form field containing the file to be uploaded. To avoid hard-coding a static value, make it an argument to the cffunction instead. Use the result variable to return details about the uploaded file as a structure  (See CFFile - Usage Section for a list of the available properties).

Here's a starter example that allows uploading of a .PNG or .JPG file (any other extension throws an exception). A status structure is returned as json, if successful.

<cfcomponent>
    <cffunction name="handleDocument" access="remote" returnformat="JSON" output="false">
        <cfargument name="fileFieldName" type="string" required="true">

        <!--- demo - only allow JPG files  --->
        <cffile action="upload"
                destination="c:/nonwebaccessbile/path"
                fileField="#arguments.fileFieldName#"
                nameconflict="MakeUnique"
                strict="true"
                result="local.result"
                allowedExtensions=".png,.jpg"
        >

        <!--- for demo return saved file name  --->
        <cfreturn {
            "fileWasSaved": local.result.fileWasSaved
            , "serverFile": local.result.serverFile
        } >
    </cffunction>
</cfcomponent>

JavaScript

var myDocument = $('#fileinput').prop('files');

One correction to the js code. The above returns a FileList object, not a file. To access the first File in the list, use $('#fileinput').prop('files')[0] instead.

Then since the cffunction requires a field name, append that value to the FormData object before the ajax call:

var theFileField = $("#fileinput");
var theFieldName = theFileField.prop("name")
var theFirstFile = theFileField.prop("files")[0];

var formData = new FormData();
formData.append('fileFieldName', theFieldName);
formData.append(theFieldName, theFirstFile);

$.ajax({
    url: "./pathto/file.cfc?method=handleDocument",
    type: "POST",
    data: formData,
    dataType: "json",
    contentType: false,
    processData: false
}).done(function(response, status, xhr){
    // do stuff here ...
}).fail(function(xhr,status,error){
    // do stuff here ...
});

Security

File uploads can pose a BIG security risk to web apps. Before putting ANY file uploads into production, read up on how to secure them first. A few good resources:

CFML SecureUpload CFC (Github)

Securing ColdFusion Apps 2021 (see "File Uploads" page 63)

OWASP - File Upload Cheat Sheet