问:
timeIntervalSinceDate gives exc_bad_access or autorelease errors
So I have an object which represents a line drawn on the iPhone screen.  I also have a ball moving around on the screen, and when the ball and the line intersect, the string is given a life.  For my current build I am receiving this error constantly, with no crashes, but the ball stops moving on the screen:

2011-08-18 11:00:05.436 myProgram[192:5e03] * __NSAutoreleaseNoPool(): Object 0x1531c0 of class NSCFString autoreleased with no pool in place - just leaking

Line.h:
    @interface Line : NSObject {

```<code>//time properties
NSTimeInterval life;
NSDate *startTime;
NSDate *currentTime;
}

//time properties
@property (nonatomic, retain) NSDate *startTime;

-(void) updateLife;

-(void) beginLifeTracking;

@end
</code>```

Line.m

```<code>@synthesize startTime;

-(void)beginLifeTracking {
[self.startTime release]; //not sure if self is necessary here but startTime is released
                          //in case the same string is hit again
self.startTime = [NSDate date];
startTime = [NSDate dateWithTimeIntervalSince1970:0];
//NSLog(@"Time Interval: %f",startTime);
}

-(void) updateLife {
currentTime = [[NSDate date] retain];
NSLog(@"breakpoint1");
life = [currentTime timeIntervalSinceDate:self.startTime];
[currentTime release];
}
</code>```

I'm assuming this is some sort of memory management error, but all my attempts to remedy it have failed.  I'd really appreciate an explanation of what I'm doing wrong here. Thanks!

答:
This line:

```<code>startTime = [NSDate dateWithTimeIntervalSince1970:0];
</code>```

Will overwrite the instance variable startDate with an autoreleased NSDate. Menaing the instance will be released and become a dangling pointer soon after the method has exited.

This is what causes your crash.

You method should probably look like this:

```<code>-(void)beginLifeTracking {
    self.startTime = [NSDate dateWithTimeIntervalSince1970:0];
    NSLog(@"Time Interval: %@", self.startTime);
}
</code>```

I also uncommented your log statement and made it work.

Body:
So I have an object which represents a line drawn on the iPhone screen.  I also have a ball moving around on the screen, and when the ball and the line intersect, the string is given a life.  For my current build I am receiving this error constantly, with no crashes, but the ball stops moving on the screen:

2011-08-18 11:00:05.436 myProgram[192:5e03] * __NSAutoreleaseNoPool(): Object 0x1531c0 of class NSCFString autoreleased with no pool in place - just leaking

Line.h:
    @interface Line : NSObject {

//time properties
NSTimeInterval life;
NSDate *startTime;
NSDate *currentTime;
}

//time properties
@property (nonatomic, retain) NSDate *startTime;

-(void) updateLife;

-(void) beginLifeTracking;

@end

Line.m

@synthesize startTime;

-(void)beginLifeTracking {
[self.startTime release]; //not sure if self is necessary here but startTime is released
                          //in case the same string is hit again
self.startTime = [NSDate date];
startTime = [NSDate dateWithTimeIntervalSince1970:0];
//NSLog(@"Time Interval: %f",startTime);
}

-(void) updateLife {
currentTime = [[NSDate date] retain];
NSLog(@"breakpoint1");
life = [currentTime timeIntervalSinceDate:self.startTime];
[currentTime release];
}

I'm assuming this is some sort of memory management error, but all my attempts to remedy it have failed.  I'd really appreciate an explanation of what I'm doing wrong here. Thanks!

Body:
This line:

startTime = [NSDate dateWithTimeIntervalSince1970:0];

Will overwrite the instance variable startDate with an autoreleased NSDate. Menaing the instance will be released and become a dangling pointer soon after the method has exited.

This is what causes your crash.

You method should probably look like this:

-(void)beginLifeTracking {
    self.startTime = [NSDate dateWithTimeIntervalSince1970:0];
    NSLog(@"Time Interval: %@", self.startTime);
}

I also uncommented your log statement and made it work.


来源: stackexchange

问:
How can I store data in a table as a trie? (SQL Server)
To make things easier, the table contains all the words in the English dictionary.

What I would like to do is be able to store the data as a trie. This way I can traverse the different branches of the trie and return the most relevant result.

First, how do I store the data in the table as a trie?

Second, how do I traverse the tree?

If it helps at all, the suggestion in this previous question is where this question was sparked from.

Please make sure it's SQL we're talking about. I understood the Mike Dunlavey's C implementation because of pointers but can't see how this part (The trie itself) works in SQL.

Thanks,

Matt

答: I don't think you need to implement Trie in DB. You can simply use like %~word% query and it would work exactly the same. I don't know your reason for trying to implement Trie in DB but it sounds quite inefficient.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Laravel resource pagination meta data missing
Recently I have implemented Laravel pagination with resources. But the problem is when I add some custom attributes or wrappers, pagination metadata gets lost. without wrappers or custom attributes, working fine.

Resource class

```<code>class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}
</code>```

Controller function

```<code>public function index()
{
        return response()->json([
            'success' => 'true',
            'message'=>'Request successful',
            'result' => UserResource::collection(User::paginate(3))
        ]);
}
</code>```

Output

```<code>{
    "success": "true",
    "message": "Request successful",
    "result": [
        {
            "id": 1,
            "name": "System Admin",
            "email": "admin@abc.com"
        }
    ]
}
</code>```

^ pagination data missing

Expectation

```<code>{
  "success": "true",
  "message": "Request successful",
  "result": {
    "data": [
      {
        "id": 1,
        "name": "System Admin",
        "email": "admin@abc.com"
      },
      {
        ......
      }
    ],
    "links": {
      "first": "http://localhost:8080/api/v1/user?page=1",
      "last": "http://localhost:8080/api/v1/user?page=4",
      "prev": null,
      "next": "http://localhost:8080/api/v1/user?page=2"
    },
    "meta": {
      "current_page": 1,
      "from": 1,
      "last_page": 4,
      "path": "http://localhost:8080/api/v1/user",
      "per_page": 3,
      "to": 3,
      "total": 11
    }
  }
}
</code>```

Thanks.

答:
I have solved that issue using</p>
```<code>return response()->json([
       'success' => 'true',
       'message'=>'Request successful',
       'result' => UserResource::collection(User::paginate(3))->response()->getData()
      ]);
</code>```

Body:
Recently I have implemented Laravel pagination with resources. But the problem is when I add some custom attributes or wrappers, pagination metadata gets lost. without wrappers or custom attributes, working fine.

Resource class

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
        ];
    }
}

Controller function

public function index()
{
        return response()->json([
            'success' => 'true',
            'message'=>'Request successful',
            'result' => UserResource::collection(User::paginate(3))
        ]);
}

Output

{
    "success": "true",
    "message": "Request successful",
    "result": [
        {
            "id": 1,
            "name": "System Admin",
            "email": "admin@abc.com"
        }
    ]
}

^ pagination data missing

Expectation

{
  "success": "true",
  "message": "Request successful",
  "result": {
    "data": [
      {
        "id": 1,
        "name": "System Admin",
        "email": "admin@abc.com"
      },
      {
        ......
      }
    ],
    "links": {
      "first": "http://localhost:8080/api/v1/user?page=1",
      "last": "http://localhost:8080/api/v1/user?page=4",
      "prev": null,
      "next": "http://localhost:8080/api/v1/user?page=2"
    },
    "meta": {
      "current_page": 1,
      "from": 1,
      "last_page": 4,
      "path": "http://localhost:8080/api/v1/user",
      "per_page": 3,
      "to": 3,
      "total": 11
    }
  }
}

Thanks.

Body:
I have solved that issue using

return response()->json([
       'success' => 'true',
       'message'=>'Request successful',
       'result' => UserResource::collection(User::paginate(3))->response()->getData()
      ]);


问:
Cannot list contents of db file in Xamarin
I want to create an easy quiz application that gets values from a .db file.

In my MainPage.xaml.cs I want to list all my questions (with just one answer option for testing,  from a database that is embedded and is implemented correctly for both platforms) in a list form just for now, but I get a white empty stuff without any error msg.

DataModels/Questions.cs

```<code>namespace quiztest.DataModels
{
    public class Questions
    {
        [PrimaryKey]
        public int ID { get; set; }
        public string Field{ get; set; }
        public string Question{ get; set; }
        public string Answer1 { get; set; }
        public string Answer2 { get; set; }
        public string Answer3 { get; set; }
        public string Answer4 { get; set; }
        public string CorrectAnswer { get; set; }
    }
}
</code>```

MainPage.xaml.cs

```<code>using quiztest.DataModels;

...

protected override void OnAppearing()
            {
                base.OnAppearing();
                using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
                {
                    var questions = conn.Table<Question>().ToList();
                    quizListView.ItemsSource = questions;

                }

            }
</code>```

MainPage.Xaml

```<code>        <StackLayout>
        <Label Text="Contents:"/>
        <Label x:Name="labelrandom"/>
        <ScrollView>
            <ListView x:Name="quizListView">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Question}" Detail="{Binding Answer1}" TextColor="Aquamarine"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </ScrollView>
    </StackLayout>
</code>```

I feel that the issue is related to getting the correct columns to show up on the textcell but I am just started learning and I am not an expert.

答:
I advice you to use collectionview instead.
to fix your problem bind the listview to a observablecollention

```<code> private ObservableCollection<Questions> questionsList;
        public ObservableCollection<Questions> QuestionsList
        {
            get { return questionsList; }
            set
            {
                if (questionsList != value)
                {
                    questionsList = value;

                }
            }
        }
</code>```

then in your Function :

```<code>protected override void OnAppearing()
            {
                base.OnAppearing();

               string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), dbName);
                var db = new SQLiteConnection (dbPath);
                     var quesList = db.Table<Questions>().toList();
                    QuestionsList = new ObservableCollection<Questions>(quesList);
                    quizListView.ItemsSource = QuestionsList;

                }

            }
</code>```

or you can bind it Directly to the listview

```<code><ListView x:Name="quizListView" ItemsSource={Binding QuestionsList}>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Question}" Detail="{Binding Answer1}" TextColor="Aquamarine"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
</code>```

Body:
I want to create an easy quiz application that gets values from a .db file.

In my MainPage.xaml.cs I want to list all my questions (with just one answer option for testing,  from a database that is embedded and is implemented correctly for both platforms) in a list form just for now, but I get a white empty stuff without any error msg.

DataModels/Questions.cs

namespace quiztest.DataModels
{
    public class Questions
    {
        [PrimaryKey]
        public int ID { get; set; }
        public string Field{ get; set; }
        public string Question{ get; set; }
        public string Answer1 { get; set; }
        public string Answer2 { get; set; }
        public string Answer3 { get; set; }
        public string Answer4 { get; set; }
        public string CorrectAnswer { get; set; }
    }
}

MainPage.xaml.cs

using quiztest.DataModels;

...

protected override void OnAppearing()
            {
                base.OnAppearing();
                using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
                {
                    var questions = conn.Table<Question>().ToList();
                    quizListView.ItemsSource = questions;

                }

            }

MainPage.Xaml

        <StackLayout>

        <ScrollView>
            <ListView x:Name="quizListView">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Question}" Detail="{Binding Answer1}" TextColor="Aquamarine"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </ScrollView>
    </StackLayout>

I feel that the issue is related to getting the correct columns to show up on the textcell but I am just started learning and I am not an expert.

Body:
I advice you to use collectionview instead.
to fix your problem bind the listview to a observablecollention

 private ObservableCollection<Questions> questionsList;
        public ObservableCollection<Questions> QuestionsList
        {
            get { return questionsList; }
            set
            {
                if (questionsList != value)
                {
                    questionsList = value;

                }
            }
        }

then in your Function :

protected override void OnAppearing()
            {
                base.OnAppearing();

               string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), dbName);
                var db = new SQLiteConnection (dbPath);
                     var quesList = db.Table<Questions>().toList();
                    QuestionsList = new ObservableCollection<Questions>(quesList);
                    quizListView.ItemsSource = QuestionsList;

                }

            }

or you can bind it Directly to the listview

<ListView x:Name="quizListView" ItemsSource={Binding QuestionsList}>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Question}" Detail="{Binding Answer1}" TextColor="Aquamarine"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>


问:
How Can I get my app id in Telegram API?
I am trying to get my app id from Telegram API by using the method register.saveDeveloperInfo, but I cannot find the way to do it.

I'm using de MTProto Java library.

This is what I had done by now:

I made my own register.saveDeveloperInfo implemmentation in Java.

I call the method with the corrects params (https://core.telegram.org/api/obtaining_api_id)

The method returns a true boolean but I have not received the sms with my app_id.

When I enter in my app section of the telegram web (https://core.telegram.org/myapp) shows the "Your app is not ready yet" message.

Anyway, I'm trying to use the app_id from the source code of the official client but I can't send or receive message.

Does anyone know how to do it or where can I find more information?

答: Try disabling any anti-spam software or VPN. Disabling ABP for https://my.telegram.org/apps helped me</p>

ContentLicense: CC BY-SA 3.0


问:
.NET error handling
I have been writing .NET applications and have been impressed with the error handling included in the framework.

When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.

For a simple example let's say for instance that we are recording numbers to a log in a method:

```<code>public void ExampleMethod(int number){
    try{
        int num = number
        ...open connection to file
        ...write number to file
    }
    catch(Exception ex){
        .... deal with exception (ex.message,ex.stacktrace etc...)
    }
    finally{
    ...close file connection
    }
}
</code>```

Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.

Any ideas?

答:
In order to do this:

```<code>public void MyProblematicMethod(int id, string name)
{
    try
    {
        object o = null;
        int hash = o.GetHashCode(); // throws NullReferenceException
    }
    catch (Exception ex)
    {
        string errorMessage = SummarizeMethodCall(MethodBase.GetCurrentMethod(), id, name);
        // TODO: do something with errorMessage
    }
}
</code>```

...and get this:

```<code>"MyProblematicMethod invoked: id = 1, name = Charlie"
</code>```

...you could do something like this:

```<code>public static string SummarizeMethodCall(MethodBase method, params object[] values)
{
    var output = new StringBuilder(method.Name + " invoked: ");
    ParameterInfo[] parameters = method.GetParameters();
    for (int i = 0; i < parameters.Length; i++)
    {
        output.AppendFormat("{0} = {1}",
            parameters[i].Name,
            i >= values.Length ? "<empty>" : values[i]
        );
        if (i < parameters.Length - 1)
            output.Append(", ");
    }
    return output.ToString();
}
</code>```

Title: .NET error handling

Body:
I have been writing .NET applications and have been impressed with the error handling included in the framework.

When catching an error that has been throw by the processes or somewhere in the code I like to include the message (ex.Message, which is usually pretty general) but also the stacktrace (ex.stacktrace) which helps to trace the problem back to a specific spot.

For a simple example let's say for instance that we are recording numbers to a log in a method:

public void ExampleMethod(int number){
    try{
        int num = number
        ...open connection to file
        ...write number to file
    }
    catch(Exception ex){
        .... deal with exception (ex.message,ex.stacktrace etc...)
    }
    finally{
    ...close file connection
    }
}

Is there any way to see the method called (in this case ExampleMethod) with the specific number that was passed that potentially crashed the method call? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.

Any ideas?

Body:
In order to do this:

public void MyProblematicMethod(int id, string name)
{
    try
    {
        object o = null;
        int hash = o.GetHashCode(); // throws NullReferenceException
    }
    catch (Exception ex)
    {
        string errorMessage = SummarizeMethodCall(MethodBase.GetCurrentMethod(), id, name);
        // TODO: do something with errorMessage
    }
}

...and get this:

"MyProblematicMethod invoked: id = 1, name = Charlie"

...you could do something like this:

public static string SummarizeMethodCall(MethodBase method, params object[] values)
{
    var output = new StringBuilder(method.Name + " invoked: ");
    ParameterInfo[] parameters = method.GetParameters();
    for (int i = 0; i < parameters.Length; i++)
    {
        output.AppendFormat("{0} = {1}",
            parameters[i].Name,
            i >= values.Length ? "<empty>" : values[i]
        );
        if (i < parameters.Length - 1)
            output.Append(", ");
    }
    return output.ToString();
}


问:
In an object nesting key-value pairs, how to convert a single-value array into just the value itself?
Given an array that nests inner objects which have key-value pairs, I want to convert single-element-arrays to just the value itself.

So let's say that we have the following albums array:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
]
```
<p>Since all the arrays are single-values, I would like to convert this entire <code>albums</code> object to:</p>
<pre class="lang-js prettyprint-override"><code>// desired output
[
    {
        "band": "beetles",
        "album": "yellow_submarine",
        "year": 1969
    },
    {
        "band": "coldplay",
        "album": "Parachutes",
        "year": 2000
    },
    {
        "band": "nirvana",
        "album": "nevermind",
        "year": 1991
    }
]
</code>```

I've seem lots of posts discussing the opposite (i.e., how to convert a single value into an array), but could not find an answer to this current question. Maybe I'm not using the correct search terms...

答:
Map albums to a new array of objects, use a unArray method within the map -lambda

const albums = [{
    "band": ["beetles"],
    "album": ["yellow_submarine"],
    "year": [1969]
  },
  {
    "band": ["coldplay"],
    "album": ["Parachutes"],
    "year": [2000]
  },
  {
    "band": ["nirvana"],
    "album": ["nevermind"],
    "year": [1991]
  }
];

// Note: for a true copy of albums and its arrays,
// the values must be spreaded (e.g. ...album.band)
const noArrays = albums.map(album => {
  const unArray = v => v.length === 1 ? v.shift() : v;
  return { ...{},
    band: unArray(...album.band),
    album: unArray(...album.album),
    year: unArray(...album.year)
  };
});

console.log(noArrays);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
}</code>```

If the keys of the albums entries are not (all) known, using a reducer for all album entries would be more generic:

const albums = [{
    "band": ["beetles"],
    "album": ["yellow_submarine"],
    "year": [1969]
  },
  {
    "band": ["coldplay"],
    "album": ["Parachutes"],
    "year": [2000]
  },
  {
    "band": ["nirvana"],
    "album": ["nevermind"],
    "year": [1991]
  }
];

// Note: for a true copy of albums and its arrays,
// the values ust be spreaded (i.e ...value)
const noArrays = albums.map( album => {
  const unArray = v => v.length === 1 ? v.shift() : v;
  return Object.entries(album).reduce( (acc, [key, value]) =>
    ({...acc, [key]: unArray(...value)}), {});
});

console.log(noArrays);```

Body:
Given an array that nests inner objects which have key-value pairs, I want to convert single-element-arrays to just the value itself.

So let's say that we have the following albums array:

const albums = [
    {
        "band": ["beetles"],
        "album": ["yellow_submarine"],
        "year": [1969]
    },
    {
        "band": [ "coldplay"],
        "album": ["Parachutes"],
        "year": [2000]
    },
    {
        "band": ["nirvana"],
        "album": ["nevermind"],
        "year": [1991]
    }
]

Since all the arrays are single-values, I would like to convert this entire albums object to:

// desired output
[
    {
        "band": "beetles",
        "album": "yellow_submarine",
        "year": 1969
    },
    {
        "band": "coldplay",
        "album": "Parachutes",
        "year": 2000
    },
    {
        "band": "nirvana",
        "album": "nevermind",
        "year": 1991
    }
]

I've seem lots of posts discussing the opposite (i.e., how to convert a single value into an array), but could not find an answer to this current question. Maybe I'm not using the correct search terms...

Body:
Map albums to a new array of objects, use a unArray method within the map -lambda

const albums = [{
    "band": ["beetles"],
    "album": ["yellow_submarine"],
    "year": [1969]
  },
  {
    "band": ["coldplay"],
    "album": ["Parachutes"],
    "year": [2000]
  },
  {
    "band": ["nirvana"],
    "album": ["nevermind"],
    "year": [1991]
  }
];

// Note: for a true copy of albums and its arrays,
// the values must be spreaded (e.g. ...album.band)
const noArrays = albums.map(album => {
  const unArray = v => v.length === 1 ? v.shift() : v;
  return { ...{},
    band: unArray(...album.band),
    album: unArray(...album.album),
    year: unArray(...album.year)
  };
});

console.log(noArrays);

.as-console-wrapper {
  max-height: 100% !important;
}

If the keys of the albums entries are not (all) known, using a reducer for all album entries would be more generic:

const albums = [{
    "band": ["beetles"],
    "album": ["yellow_submarine"],
    "year": [1969]
  },
  {
    "band": ["coldplay"],
    "album": ["Parachutes"],
    "year": [2000]
  },
  {
    "band": ["nirvana"],
    "album": ["nevermind"],
    "year": [1991]
  }
];

// Note: for a true copy of albums and its arrays,
// the values ust be spreaded (i.e ...value)
const noArrays = albums.map( album => {
  const unArray = v => v.length === 1 ? v.shift() : v;
  return Object.entries(album).reduce( (acc, [key, value]) =>
    ({...acc, [key]: unArray(...value)}), {});
});

console.log(noArrays);


问:
Make cells negative based upon the value of another
I'm able to colour cells based upon the value of another with the code below, which I found on this forum

```<code>Sub ColorMeElmo()
   Dim i As Long, r1 As Range, r2 As Range

   For i = 2 To 100
      Set r1 = Range("D" & i)
      Set r2 = Range("A" & i & ":C" & i)
      If r1.Value = "Aankoop" Then r2.Interior.Color = vbRed
      If r1.Value = "Verkoop" Then r2.Interior.Color = vbBlue
      If r1.Value = "Dividend" Then r2.Interior.Color = vbYellow
   Next i
End Sub
</code>```

Now I'm trying to make cells negative or possitive based upon the value of r1.
I tried this:

```<code>If r1.Value = "Verkoop" Then r2.Value = r2.Value * (-1)
</code>```

答:
Issue seems to be that r2 contains multiple cells hence below code will not work

```<code>If r1.Value = "Verkoop" Then r2.Value = r2.Value * (-1)
</code>```

This needs to be changed to

```<code>If r1.Value = "Verkoop" Then
 For Each c In r2.Cells
     c.Value = c.Value * (-1)
 Next
End if
</code>```

Body:
I'm able to colour cells based upon the value of another with the code below, which I found on this forum

Sub ColorMeElmo()
   Dim i As Long, r1 As Range, r2 As Range

   For i = 2 To 100
      Set r1 = Range("D" & i)
      Set r2 = Range("A" & i & ":C" & i)
      If r1.Value = "Aankoop" Then r2.Interior.Color = vbRed
      If r1.Value = "Verkoop" Then r2.Interior.Color = vbBlue
      If r1.Value = "Dividend" Then r2.Interior.Color = vbYellow
   Next i
End Sub

Now I'm trying to make cells negative or possitive based upon the value of r1.
I tried this:

If r1.Value = "Verkoop" Then r2.Value = r2.Value * (-1)

Body:
Issue seems to be that r2 contains multiple cells hence below code will not work

If r1.Value = "Verkoop" Then r2.Value = r2.Value * (-1)

This needs to be changed to

If r1.Value = "Verkoop" Then
 For Each c In r2.Cells
     c.Value = c.Value * (-1)
 Next
End if


问:
Why does my tablet display the button differently than it does on my computer?
Why does my tablet display the button differently than it does on my computer?

Code:

<!DOCTYPE HTML>

ENTER CODE

        <form action="topage.php" method="post">
            <input name="code" type="number" oninput="this.value = this.value.slice(0, 8);">

            <input type="submit" value="SUBMIT">
        </form>

```

Website in my tablet:

Website in my computer:

Ma tahan et tahvelarvutis näeks see samasugune välja kui arvutis.

Both screenshots are made in Chrome, my computer is linux and the tablet is an iPad.

Thank you very much to all the respondents!

答:
I found a solution:

Strange button styling on chrome on iOS

To be used:

```<code>-webkit-appearance: none! important;
</code>```

Body:
Why does my tablet display the button differently than it does on my computer?

Code:

<!DOCTYPE HTML>

ENTER CODE

        <form action="topage.php" method="post">
            <input name="code" type="number" oninput="this.value = this.value.slice(0, 8);">

            <input type="submit" value="SUBMIT">
        </form>

Website in my tablet:

Website in my computer:

Ma tahan et tahvelarvutis näeks see samasugune välja kui arvutis.

Both screenshots are made in Chrome, my computer is linux and the tablet is an iPad.

Thank you very much to all the respondents!

Body:
I found a solution:

Strange button styling on chrome on iOS

To be used:

-webkit-appearance: none! important;


问:
What happens when default.aspx page is requested for the first time?
What happens when default.aspx page is requested for the first time?

.net is pure a pure Object Oriented Framework.

_default is a class which extends Page.

Without instantiating, Pre-Init,Init,Load cannot be called.
So How _default class is instantiated?
Who is responsible for that?

I want to know very detailed technical steps?

Pleasa clarify!

答: I suggest you read the ASP.NET Page Life Cycle Overview</p>


问:
Warning: Prop `className` did not match. when using styled components with semantic-ui-react
I use this code to margin my Button from top:

```<code>const makeTopMargin = (elem) => {
    return styled(elem)`
        && {
            margin-top: 1em !important;
        }
    `;
}

const MarginButton = makeTopMargin(Button);
</code>```

and whenever i use MarginButton node, I get this error: Warning: PropclassNamedid not match. Server: "ui icon left labeled button sc-bwzfXH MjXOI" Client: "ui icon left labeled button sc-bdVaJa fKCkqX"

You can see this produced here.

What should I do?

答:
The main reason I am posting this answer to help people understand the tradeoff. When we're using .babelrc in next project it's going to opt of SWC compiler which is based on Rust (Learn More).

It's going to show message something like this when you opt for custom bable config.

```<code>info  - Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc"
</code>```

I did more digging on this to only find out following! Ref

Next.js now uses Rust-based compiler SWC to compile
JavaScript/TypeScript. This new compiler is up to 17x faster than
Babel when compiling individual files and up to 5x faster Fast
Refresh.

So tradeoff was really huge, we can lose significant amout of performance. So I found a better solution which can solve this issue and keep SWC as default compiler.

You can add this experimental flag in your next.config.js to prevent this issue. Ref

```<code>// next.config.js

module.exports = {
  compiler: {
    // ssr and displayName are configured by default
    styledComponents: true,
  },
}
</code>```

Body:
I use this code to margin my Button from top:

const makeTopMargin = (elem) => {
    return styled(elem)`
        && {
            margin-top: 1em !important;
        }
    `;
}

const MarginButton = makeTopMargin(Button);

and whenever i use MarginButton node, I get this error: Warning: PropclassNamedid not match. Server: "ui icon left labeled button sc-bwzfXH MjXOI" Client: "ui icon left labeled button sc-bdVaJa fKCkqX"

You can see this produced here.

What should I do?

Body:
The main reason I am posting this answer to help people understand the tradeoff. When we're using .babelrc in next project it's going to opt of SWC compiler which is based on Rust (Learn More).

It's going to show message something like this when you opt for custom bable config.

info  - Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc"

I did more digging on this to only find out following! Ref

Next.js now uses Rust-based compiler SWC to compile
JavaScript/TypeScript. This new compiler is up to 17x faster than
Babel when compiling individual files and up to 5x faster Fast
Refresh.

So tradeoff was really huge, we can lose significant amout of performance. So I found a better solution which can solve this issue and keep SWC as default compiler.

You can add this experimental flag in your next.config.js to prevent this issue. Ref

// next.config.js

module.exports = {
  compiler: {
    // ssr and displayName are configured by default
    styledComponents: true,
  },
}


问:
Fast file encryption in android
Hi i am creating a sample to lock file or folder in android. I have a issue when i encrypt or decrypt large size (more than 1 GB) file  it takes too much time.
Please help me to encrypt and decrypt file fastly.
Here i am attaching code which i am using on below</p>

```<code> if (!isEncrypted) {
                        FileInputStream fis = new FileInputStream(path);
                        // This stream write the encrypted text. This stream will be wrapped by another stream.
                        FileOutputStream fos = new FileOutputStream(path + ".abcd");

                        // Length is 16 byte
                        SecretKeySpec sks = new SecretKeySpec("abcdefghijklmnop".getBytes(), "AES");
                        // Create cipher
                        Cipher cipher = Cipher.getInstance("AES");
                        cipher.init(Cipher.ENCRYPT_MODE, sks);
                        // Wrap the output stream
                        CipherOutputStream cos = new CipherOutputStream(fos, cipher);
                        // Write bytes
                        int b;
                        byte[] d = new byte[1024];
                        try {
                            while ((b = fis.read(d)) != -1) {
                                cos.write(d, 0, b);
                            }

                            // Flush and close streams.
                            cos.flush();
                            cos.close();
                            fis.close();
                            new File(path).deleteOnExit();
                            isEncrypted = true;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    btnEncrypt.setText("Decrypt Path");
                                    deleteMyFile(path);
                                }
                            });
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    } else {
                        FileInputStream fis = new FileInputStream(path + ".abcd");

                        FileOutputStream fos = new FileOutputStream(path);
                        SecretKeySpec sks = new SecretKeySpec("abcdefghijklmnop".getBytes(), "AES");
                        Cipher cipher = Cipher.getInstance("AES");
                        cipher.init(Cipher.DECRYPT_MODE, sks);
                        CipherInputStream cis = new CipherInputStream(fis, cipher);
                        int b;
                        byte[] d = new byte[1024];

                        while ((b = cis.read(d)) != -1) {
                            fos.write(d, 0, b);
                        }
                        fos.flush();
                        fos.close();
                        cis.close();
                        isEncrypted = false;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                deleteMyFile(path + ".abcd");
                                btnEncrypt.setText("Encrypt Path");
                            }
                        });

                    }
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.setMessage(e.getMessage());
                        }
                    });
</code>```

答:
I hope you found a way to do this. But, here is how I do it.

I realized that writing our own AES classes in java Or C is not recommendable way if you are especially just focused on the end result. Java is pretty slow in comparison with C, but in java you can use multithreading whereas in C you can't. Of course there are aes c programs which do a better job. But using them is difficult. You said you want to encrypt 1GB file under a minute. So, do this.

Install Userland Or Termux and install openssl. Next cd to your file storage location and try aes encrypt command. To automate it, write a bash script and run it. Openssl can easily do 23 MBps to 68 MBps.

Title: Fast file encryption in android

Body:
Hi i am creating a sample to lock file or folder in android. I have a issue when i encrypt or decrypt large size (more than 1 GB) file  it takes too much time.
Please help me to encrypt and decrypt file fastly.
Here i am attaching code which i am using on below

 if (!isEncrypted) {
                        FileInputStream fis = new FileInputStream(path);
                        // This stream write the encrypted text. This stream will be wrapped by another stream.
                        FileOutputStream fos = new FileOutputStream(path + ".abcd");

                        // Length is 16 byte
                        SecretKeySpec sks = new SecretKeySpec("abcdefghijklmnop".getBytes(), "AES");
                        // Create cipher
                        Cipher cipher = Cipher.getInstance("AES");
                        cipher.init(Cipher.ENCRYPT_MODE, sks);
                        // Wrap the output stream
                        CipherOutputStream cos = new CipherOutputStream(fos, cipher);
                        // Write bytes
                        int b;
                        byte[] d = new byte[1024];
                        try {
                            while ((b = fis.read(d)) != -1) {
                                cos.write(d, 0, b);
                            }

                            // Flush and close streams.
                            cos.flush();
                            cos.close();
                            fis.close();
                            new File(path).deleteOnExit();
                            isEncrypted = true;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    btnEncrypt.setText("Decrypt Path");
                                    deleteMyFile(path);
                                }
                            });
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    } else {
                        FileInputStream fis = new FileInputStream(path + ".abcd");

                        FileOutputStream fos = new FileOutputStream(path);
                        SecretKeySpec sks = new SecretKeySpec("abcdefghijklmnop".getBytes(), "AES");
                        Cipher cipher = Cipher.getInstance("AES");
                        cipher.init(Cipher.DECRYPT_MODE, sks);
                        CipherInputStream cis = new CipherInputStream(fis, cipher);
                        int b;
                        byte[] d = new byte[1024];

                        while ((b = cis.read(d)) != -1) {
                            fos.write(d, 0, b);
                        }
                        fos.flush();
                        fos.close();
                        cis.close();
                        isEncrypted = false;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                deleteMyFile(path + ".abcd");
                                btnEncrypt.setText("Encrypt Path");
                            }
                        });

                    }
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.setMessage(e.getMessage());
                        }
                    });


问:
Predefined users on devices
Hello in my job we have alot of branches and users. I want to make some profiles in Intune where each branches has predefined profiles ( with programs and policies ) same for users. They will login with a domain profile that is defined in Azure AD.</p>

答:
•   Yes, you can create predefined device-based profiles in Intune based on branch offices. For that, I would suggest you create user and device groups according to the branch office location and organize the users and devices in them as per their assigned branch office. Once, that has been done successfully, then would suggest you create various device configuration profiles according to the branch offices and their required configuration settings as expected in them and assign these device configuration profile to the respective user and device group in their branch offices.

•   These configuration settings will then reflect in those devices which are assigned to these branch locations. Once done, then change the primary user of those devices using a powershell script or through Intune management portal as there is no provision in Intune to predefine the user to be signed in on a device. Thus, you can either configure the last signed in user to be the primary user of that Intune managed device through a powershell script in a bulk operation or change it through the Intune Management portal.

For more information on the above, please refer to the documentation links below: -

https://learn.microsoft.com/en-us/mem/intune/configuration/device-profile-assign

https://learn.microsoft.com/en-us/mem/intune/remote-actions/find-primary-user

https://learn.microsoft.com/en-us/mem/intune/configuration/device-profile-create

Title: Predefined users on devices


问:
hasManyThrough with morph
I have a projects table that either can be assigned to a user or a team, this is the structure:

```<code>id
assignable_id
assignable_type

class Project extends Model {
    public function assignable(): MorphTo
    {
        return $this->morphTo();
    }
}
</code>```

and my team table contains members with a pivot table:

```<code>id

class Team extends Model {

    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

    public function projects(): MorphMany
    {
        return $this->morphMany(Project::class, 'assignable');
    }
}

// team_user table
team_id
user_id
</code>```

and finally my user table:

```<code>id

class User extends Model {

    public function teams(): BelongsToMany
    {
        return $this->belongsToMany(Team::class);
    }

    public function projects(): MorphMany
    {
        return $this->morphMany(Project::class, 'assignable');
    }
}
</code>```

Now the problem is I want to get all projects that have been assigned to a user either directly or through a team, as expected $user()->projects return the ones that directly have been assigned to the user.

I tried many solutions but none has worked for me yet.

答:
So you actually need something like this:

```<code>public function project()
{
    return $this->hasManyThrough('App\Project', 'App\User', 'assignable_id')
        ->where(
            'assignable_type',
            array_search(static::class, Relation::morphMap()) ?: static::class
        );
}
</code>```

or

```<code>public function project()
{
    return $this->belongsToMany(Project::class, 'assignable', 'assignable_id', 'project_id')
        ->where('assignable_type', static::class);
}
</code>```

Ref: Laravel Polymorphic Relations Has Many Through

Your working solution:

```<code>public function projects() {
    return $this->hasManyThrough(
        Project::class,
        User::class,
        'id',
        'assignable_id',
    )->where(
        'assignable_type', User::class
    )->orWhere(function ($q) {
        $q->where('assignable_type', Team::class)
        ->whereIn('assignable_id', $this->teams->pluck('id'));
    });
}
</code>```

Title: hasManyThrough with morph

Body:
I have a projects table that either can be assigned to a user or a team, this is the structure:

id
assignable_id
assignable_type

class Project extends Model {
    public function assignable(): MorphTo
    {
        return $this->morphTo();
    }
}

and my team table contains members with a pivot table:

id

class Team extends Model {

    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

    public function projects(): MorphMany
    {
        return $this->morphMany(Project::class, 'assignable');
    }
}

// team_user table
team_id
user_id

and finally my user table:

id

class User extends Model {

    public function teams(): BelongsToMany
    {
        return $this->belongsToMany(Team::class);
    }

    public function projects(): MorphMany
    {
        return $this->morphMany(Project::class, 'assignable');
    }
}

Now the problem is I want to get all projects that have been assigned to a user either directly or through a team, as expected $user()->projects return the ones that directly have been assigned to the user.

I tried many solutions but none has worked for me yet.

Body:
So you actually need something like this:

public function project()
{
    return $this->hasManyThrough('App\Project', 'App\User', 'assignable_id')
        ->where(
            'assignable_type',
            array_search(static::class, Relation::morphMap()) ?: static::class
        );
}

or

public function project()
{
    return $this->belongsToMany(Project::class, 'assignable', 'assignable_id', 'project_id')
        ->where('assignable_type', static::class);
}

Ref: Laravel Polymorphic Relations Has Many Through

Your working solution:

public function projects() {
    return $this->hasManyThrough(
        Project::class,
        User::class,
        'id',
        'assignable_id',
    )->where(
        'assignable_type', User::class
    )->orWhere(function ($q) {
        $q->where('assignable_type', Team::class)
        ->whereIn('assignable_id', $this->teams->pluck('id'));
    });
}


问:
Bash: match in a list of files, cases including and excluding pattern
I'd need to find the cleanest way in bash to extract from hundred of files, the files matching some patterns in their contents AND NOT matching some others.

for instance:

```<code>  for transaction in "TXNA" "TXNB" "TXNC" "TXND" "TXNE" ; do
      echo "--> ${transaction}"
      grep -L "EXCLUDE_PATTERN1" $(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/))   >> myReport.txt
    done
</code>```

so here:

```<code>grep -Rl --include \*.txt "+${transaction}:" myDir/
</code>```

grep in myDir recursively all the files.txt matching the TXNA..B

Then

```<code>$(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/)
</code>```

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN2

and finally:

```<code>grep -L "EXCLUDE_PATTERN1"
</code>```

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN1

This is quite ugly as I have around 10 patterns to exclude it will become not readable at all.

Any idea for making this code more readable and easy to debug?

Thanks a lot.

答:
A gawk (standard Linux awk) script that scan each file once.

script.awk

```<code>BEGIN {
  RS="!@!@!@!@!@!@!@"; # set record seperator to something unlikely matched, causing each file to be read entirely as a single record
  wordsListCount = split(wordsListStr, wordsListArr, " +"); # split wordsListStr by newLine into array wordsListArr, saved array length into wordsListCount
  for (i in wordsListArr) wordsListArr[i] = gensub( /(^\")([^\"]*)(\"$)/ , "\\2", "g" , wordsListArr[i]); # clear prefix " and suffix "
}
$0 !~ excludePatter1 && $0 !~ excludePatter2 { # for each file (read as single record)
                                               # not matching excludePatter1  and not matching excludePatter2
  for (currWord in wordsListArr) { # for each matching word
    if ($0 ~ currWord) {  # if found a match to current word in file
          print FILENAME; # print current file name
          next; # proceed to next file
    }
  }
}
</code>```

running command:

```<code>awk -v wordsListFile='"TXNA" "TXNB" "TXNC" "TXND" "TXNE"' \
    -v excludePatter1='regEx1' \
    -v excludePatter2='regEx2' \
    -f script.awk $(find myDir -type f)
</code>```

Body:
I'd need to find the cleanest way in bash to extract from hundred of files, the files matching some patterns in their contents AND NOT matching some others.

for instance:

  for transaction in "TXNA" "TXNB" "TXNC" "TXND" "TXNE" ; do
      echo "--> ${transaction}"
      grep -L "EXCLUDE_PATTERN1" $(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/))   >> myReport.txt
    done

so here:

grep -Rl --include \*.txt "+${transaction}:" myDir/

grep in myDir recursively all the files.txt matching the TXNA..B

Then

$(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/)

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN2

and finally:

grep -L "EXCLUDE_PATTERN1"

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN1

This is quite ugly as I have around 10 patterns to exclude it will become not readable at all.

Any idea for making this code more readable and easy to debug?

Thanks a lot.

Body:
A gawk (standard Linux awk) script that scan each file once.

script.awk

BEGIN {
  RS="!@!@!@!@!@!@!@"; # set record seperator to something unlikely matched, causing each file to be read entirely as a single record
  wordsListCount = split(wordsListStr, wordsListArr, " +"); # split wordsListStr by newLine into array wordsListArr, saved array length into wordsListCount
  for (i in wordsListArr) wordsListArr[i] = gensub( /(^\")([^\"]*)(\"$)/ , "\\2", "g" , wordsListArr[i]); # clear prefix " and suffix "
}
$0 !~ excludePatter1 && $0 !~ excludePatter2 { # for each file (read as single record)
                                               # not matching excludePatter1  and not matching excludePatter2
  for (currWord in wordsListArr) { # for each matching word
    if ($0 ~ currWord) {  # if found a match to current word in file
          print FILENAME; # print current file name
          next; # proceed to next file
    }
  }
}

running command:

awk -v wordsListFile='"TXNA" "TXNB" "TXNC" "TXND" "TXNE"' \
    -v excludePatter1='regEx1' \
    -v excludePatter2='regEx2' \
    -f script.awk $(find myDir -type f)


问:
Why is my JUnit Plugin tests failing with unresolved bundles errors?
I'm trying to get my JUnit Plugin-Test launcher to run for my PDE projects. It was working before, but I changed some of the names of my OSGi bundles and now it's failing with the following:

```<code>!ENTRY org.eclipse.osgi 2 0 2011-08-09 15:43:59.904
!MESSAGE The following is a complete list of bundles which are not resolved, see the prior log entry for the root cause if it exists:
!SUBENTRY 1 org.eclipse.osgi 2 0 2011-08-09 15:43:59.904
!MESSAGE Bundle me.gladwell.android.tools_0.1.1.qualifier [76] was not resolved.
!SUBENTRY 2 me.gladwell.android.tools 2 0 2011-08-09 15:43:59.904
!MESSAGE Package uses conflict: Require-Bundle: org.eclipse.persistence.moxy; bundle-version="2.1.0"
!SUBENTRY 1 org.eclipse.osgi 2 0 2011-08-09 15:43:59.904
!MESSAGE Bundle me.gladwell.eclipse.m2e.android_0.3.1.qualifier [77] was not resolved.
!SUBENTRY 2 me.gladwell.eclipse.m2e.android 2 0 2011-08-09 15:43:59.905
!MESSAGE Missing required bundle me.gladwell.android.tools_0.1.1.
!SUBENTRY 1 org.eclipse.osgi 2 0 2011-08-09 15:43:59.905
!MESSAGE Bundle me.gladwell.eclipse.m2e.android.test_0.3.1.qualifier [78] was not resolved.
!SUBENTRY 2 me.gladwell.eclipse.m2e.android.test 2 0 2011-08-09 15:43:59.905
!MESSAGE Missing required bundle me.gladwell.eclipse.m2e.android_0.0.0.
!SUBENTRY 2 me.gladwell.eclipse.m2e.android.test 2 0 2011-08-09 15:43:59.905
!MESSAGE Missing required bundle me.gladwell.android.tools_0.0.0.
</code>```

Please see full error log

I'm unsure how to diagnose these messages and where/what problems they might refer to. These tests run successfully in my command line, Tycho-Maven build and the project compiles without errors in Eclipse. I've selected "all workspace and enabled target plug-ins" option in my launcher's "Launch with" select box.

Any ideas why I'm getting these error messages?

答: If you're reusing the launch configuration and you've changed anything with the plug-in metadata (like their names), you need to be sure it's "clearing the configuration space".  You'll find this option on the Configuration tab of the launcher.</p>

Body:
I'm trying to get my JUnit Plugin-Test launcher to run for my PDE projects. It was working before, but I changed some of the names of my OSGi bundles and now it's failing with the following:

!ENTRY org.eclipse.osgi 2 0 2011-08-09 15:43:59.904
!MESSAGE The following is a complete list of bundles which are not resolved, see the prior log entry for the root cause if it exists:
!SUBENTRY 1 org.eclipse.osgi 2 0 2011-08-09 15:43:59.904
!MESSAGE Bundle me.gladwell.android.tools_0.1.1.qualifier [76] was not resolved.
!SUBENTRY 2 me.gladwell.android.tools 2 0 2011-08-09 15:43:59.904
!MESSAGE Package uses conflict: Require-Bundle: org.eclipse.persistence.moxy; bundle-version="2.1.0"
!SUBENTRY 1 org.eclipse.osgi 2 0 2011-08-09 15:43:59.904
!MESSAGE Bundle me.gladwell.eclipse.m2e.android_0.3.1.qualifier [77] was not resolved.
!SUBENTRY 2 me.gladwell.eclipse.m2e.android 2 0 2011-08-09 15:43:59.905
!MESSAGE Missing required bundle me.gladwell.android.tools_0.1.1.
!SUBENTRY 1 org.eclipse.osgi 2 0 2011-08-09 15:43:59.905
!MESSAGE Bundle me.gladwell.eclipse.m2e.android.test_0.3.1.qualifier [78] was not resolved.
!SUBENTRY 2 me.gladwell.eclipse.m2e.android.test 2 0 2011-08-09 15:43:59.905
!MESSAGE Missing required bundle me.gladwell.eclipse.m2e.android_0.0.0.
!SUBENTRY 2 me.gladwell.eclipse.m2e.android.test 2 0 2011-08-09 15:43:59.905
!MESSAGE Missing required bundle me.gladwell.android.tools_0.0.0.

Please see full error log

I'm unsure how to diagnose these messages and where/what problems they might refer to. These tests run successfully in my command line, Tycho-Maven build and the project compiles without errors in Eclipse. I've selected "all workspace and enabled target plug-ins" option in my launcher's "Launch with" select box.

Any ideas why I'm getting these error messages?


问:
Unable to get values from switch statement to push in to an array
I've spent hours trying to figure out this exercise and stuck at this point.  I'm unable to get values from my switch statement to push to an array for "displayVal", and "val" variables.</p>
```<code>const getDeck = () => {
  const suits = ['Spades','Hearts','Diamonds','Clubs'];
  let cards = [];

  for(let s=0; s < suits.length; s++){

   for(let d = 0; d < 13; d++){
    let displayVal;
    let val;

     switch (d) {
      case (d === 1):
        displayVal = "Ace";
        val = 11;
        break;
      case (d >=2 && d <= 10):
         displayVal = d;
         val = d;
         break;
        case (d === 11):
          displayVal = "Jack"
          val = 10;
          break;
        case (d === 12):
          displayVal = "Queen"
          val = 10;
          break;
        case (d === 13):
          displayVal = "King"
          val = 10;
     }
    cards.push({
    val,
    displayVal,
    suit: suits[s]
  } );

   }

 }
 return cards;
}

const deck = getDeck();
console.log(`Deck length equals 52? ${deck.length === 52}`);
</code>```

答:
There is an alternative way / approach that may be used here.

Code Snippet

const getDeck = () => {
  const suits = ['Spades','Hearts','Diamonds','Clubs'];
  const getValueOf = x => x === 1 ? 11 : x > 10 ? 10 : x;
  const displayValMap = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'};
  return suits.map(
    suit => (
      [
        ...Array(13)
        .keys()
      ]
      .map(x => x + 1)
      .map(d => ({
        val: getValueOf(d),
        displayVal: d in displayValMap
          ? displayValMap[d]
          : d,
        suit
      }))
    )
  ).flat();
}

const deck = getDeck();
console.log(`Deck length equals 52? ${deck.length === 52}`);
console.log(deck);```
</div>
</div>
</p>
<p><strong>Explanation</strong></p>
<ul>
<li>Set-up ways to get <code>val</code> and <code>displayVal</code> (in above snippet, <code>getValueOf</code> - a one-line method; and <code>displayValMap</code> an object, is used)</li>
<li>Iterate through the <code>suits</code></li>
<li>Use <code>...</code> spread-operator to generate an array of length 13, then get the keys of the array.</li>
<li>Use <code>.map</code> to make the generated array start from 1, instead of 0</li>
<li>For each element in the array, create an object with <code>val</code>, <code>displayVal</code> and <code>suit</code> props</li>
<li>And, finally, use <code>.flat()</code> to return all objects into a single array instead of nested-arrays.</li>
</ul>
<hr />
<p>Another way may be:</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>const getDeck = () => ['Spades','Hearts','Diamonds','Clubs'].map(
    suit => (
      [
        ...Array(13)
        .keys()
      ]
      .map(d => ({
        val: (d === 0 ? 10 : d > 9 ? 9 : d) + 1,
        displayVal: {0: 'Ace', 10: 'Jack', 11: 'Queen', 12: 'King'}[d] || d + 1,
        suit
      }))
    )
).flat();

console.log(getDeck().length);
console.log(getDeck());</code>```

Body:
I've spent hours trying to figure out this exercise and stuck at this point.  I'm unable to get values from my switch statement to push to an array for "displayVal", and "val" variables.

const getDeck = () => {
  const suits = ['Spades','Hearts','Diamonds','Clubs'];
  let cards = [];

  for(let s=0; s < suits.length; s++){

   for(let d = 0; d < 13; d++){
    let displayVal;
    let val;

     switch (d) {
      case (d === 1):
        displayVal = "Ace";
        val = 11;
        break;
      case (d >=2 && d <= 10):
         displayVal = d;
         val = d;
         break;
        case (d === 11):
          displayVal = "Jack"
          val = 10;
          break;
        case (d === 12):
          displayVal = "Queen"
          val = 10;
          break;
        case (d === 13):
          displayVal = "King"
          val = 10;
     }
    cards.push({
    val,
    displayVal,
    suit: suits[s]
  } );

   }

 }
 return cards;
}

const deck = getDeck();
console.log(`Deck length equals 52? ${deck.length === 52}`);

Body:
There is an alternative way / approach that may be used here.

Code Snippet

const getDeck = () => {
  const suits = ['Spades','Hearts','Diamonds','Clubs'];
  const getValueOf = x => x === 1 ? 11 : x > 10 ? 10 : x;
  const displayValMap = {1: 'Ace', 11: 'Jack', 12: 'Queen', 13: 'King'};
  return suits.map(
    suit => (
      [
        ...Array(13)
        .keys()
      ]
      .map(x => x + 1)
      .map(d => ({
        val: getValueOf(d),
        displayVal: d in displayValMap
          ? displayValMap[d]
          : d,
        suit
      }))
    )
  ).flat();
}

const deck = getDeck();
console.log(`Deck length equals 52? ${deck.length === 52}`);
console.log(deck);

Explanation

Set-up ways to get val and displayVal (in above snippet, getValueOf - a one-line method; and displayValMap an object, is used)

Iterate through the suits

Use ... spread-operator to generate an array of length 13, then get the keys of the array.

Use .map to make the generated array start from 1, instead of 0

For each element in the array, create an object with val, displayVal and suit props

And, finally, use .flat() to return all objects into a single array instead of nested-arrays.

Another way may be:

const getDeck = () => ['Spades','Hearts','Diamonds','Clubs'].map(
    suit => (
      [
        ...Array(13)
        .keys()
      ]
      .map(d => ({
        val: (d === 0 ? 10 : d > 9 ? 9 : d) + 1,
        displayVal: {0: 'Ace', 10: 'Jack', 11: 'Queen', 12: 'King'}[d] || d + 1,
        suit
      }))
    )
).flat();

console.log(getDeck().length);
console.log(getDeck());


问:
301 Redirecting the domain if the page doesn't contain query string
I only want to redirect the root page from 1 subdomain domain to another e.g:
from https://checkout.example.com to https://www.example.com/index.php?route=checkout/cart/

however, all other pages and query strings with $ and & should remain untouched. e.g:
https://checkout.example.com/?Amount=1899&Invoice=55498213
should remain as it is

I tried multiple htaccess rules texts: Redirect 301, Redirect, RedirectMatch, RewriteRule. All the rules are redirecting the domain with the query strings.

Here is my current .htaccess rule

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^$
RewriteCond %{HTTP_HOST} ^checkout\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/index.php?route=checkout/cart/ [L,R=301]
</IfModule>
</code>```

答:
This should work for you :</p>
```<code>RewriteEngine On

RewriteCond %{QUERY_STRING} ^$
RewriteCond %{REQUEST_URI} ^/$
RewriteCond %{HTTP_HOST} ^checkout\.domain1\.com$ [NC]
RewriteRule .* https://www.domain2.com/checkout [L,R=301]
</code>```

Body:
I only want to redirect the root page from 1 subdomain domain to another e.g:
from https://checkout.example.com to https://www.example.com/index.php?route=checkout/cart/

however, all other pages and query strings with $ and & should remain untouched. e.g:
https://checkout.example.com/?Amount=1899&Invoice=55498213
should remain as it is

I tried multiple htaccess rules texts: Redirect 301, Redirect, RedirectMatch, RewriteRule. All the rules are redirecting the domain with the query strings.

Here is my current .htaccess rule

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^$
RewriteCond %{HTTP_HOST} ^checkout\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/index.php?route=checkout/cart/ [L,R=301]
</IfModule>

Body:
This should work for you :

RewriteEngine On

RewriteCond %{QUERY_STRING} ^$
RewriteCond %{REQUEST_URI} ^/$
RewriteCond %{HTTP_HOST} ^checkout\.domain1\.com$ [NC]
RewriteRule .* https://www.domain2.com/checkout [L,R=301]


Title: Plotly Sankey Diagram: how to set position of nodes, explicit X and Y values dont work

Body:
Hope someone has a suggestion!
When I dont specify X and Y positions, the Sankey plot looks okay in terms of shape but not in terms of vertical ordering: the vertical/Y order of the elements is not what I want (for every X position the ordering in vertically is different):

When I set pad=100 the Y order is correct for every X position weird enough. But with pad=1, I tried to set X and Y positions explicitly but then the plot looks weird in terms of shape. Dont know why. Any ideas ? See the sample code below:

fig = go.Figure(go.Sankey(
arrangement = "snap",
node = {
    "label": ["0br","0cl","0go","0gr","0hy","1br","1cl","1go","1gr","1hy","2br","2cl","2go","2gr","2hy","3br","3cl","3go","3gr","3hy","4br","4cl","4go","4gr","4hy","5br","5cl","5go","5gr","5hy","6br","6cl","6go","6gr","6hy"],
    "x": [0, 0, 0, 0, 0, 0.16, 0.16, 0.16, 0.16, 0.16, 0.33, 0.33, 0.33, 0.33, 0.33, 0.5, 0.5, 0.5, 0.5, 0.5, 0.66, 0.66, 0.66, 0.66, 0.66, 0.84, 0.84, 0.84, 0.84, 0.84, 1, 1, 1, 1, 1],
    "y": [0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0],
    "color" : ['rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)',                   'rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)','rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)',                   'rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)',                   'rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)',                   'rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)',                   'rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)'],
    'pad':1,
    "thickness" : 20,
    "line" : dict(color = "black", width = 0.5),},
link = {
    "source": [0,0,0,0,0,1,1,1,1,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,6,6,6,6,7,8,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11,12,12,12,13,13,13,13,14,15,15,15,16,16,16,17,17,17,18,18,18,18,19,19,20,20,20,21,21,21,22,22,23,23,23,24,24,24,24,25,25,25,25,26,26,26,26,27,28,28,28,28,29],
    "target": [5,6,7,8,9,5,6,8,9,7,5,6,7,8,9,5,6,7,8,9,10,11,12,13,14,10,11,13,14,12,10,11,13,14,11,12,13,14,15,16,18,19,15,16,18,19,15,17,19,15,16,18,19,19,20,21,23,20,21,23,20,22,24,20,21,23,24,21,24,25,26,28,25,26,28,27,29,25,26,28,25,27,28,29,30,31,33,34,30,31,33,34,32,30,31,33,34,34],
    "value": [322,14,4,6,1,47,1177,36,26,37,8,17,1,209,6,1,4,97,5,333,228,103,5,33,9,110,1016,77,9,139,27,12,203,14,3,5,12,346,336,21,7,1,74,1014,40,6,2,146,1,22,2,286,15,378,377,38,19,4,978,55,2,143,1,1,3,322,7,1,400,362,6,16,9,960,51,139,4,9,9,378,5,1,1,401,377,1,4,3,2,845,127,1,140,11,14,420,1,405]
})) fig.show()

The correct vertical ordering should be br, cl, go, gr, hy for all the horizontal/X values 0...6. So it starts with 0br, 0cl, 0go, 0gr, 0hy and then to the right of it 1br, 1cl, 1go, 1gr, 1hy etc.

KR !

Body:
see also Plotly.py Sankey Diagrams - Controlling Node Destination

x and y need to be >0 and <1.  if 0 or 1 formatting does not quite work

x = [0, 0, 0, 0, 0, 0.16, 0.16, 0.16, 0.16, 0.16, 0.33, 0.33, 0.33, 0.33, 0.33, 0.5, 0.5, 0.5, 0.5, 0.5, 0.66, 0.66, 0.66, 0.66, 0.66, 0.84, 0.84, 0.84, 0.84, 0.84, 1, 1, 1, 1, 1]
y = [0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0,0, 0.25, 0.5, 0.75, 1.0]
x = [.001 if v==0 else .999 if v==1 else v for v in x]
y = [.001 if v==0 else .999 if v==1 else v for v in y]
fig = go.Figure(go.Sankey(
arrangement = "snap",
node = {
    "label": ["0br","0cl","0go","0gr","0hy","1br","1cl","1go","1gr","1hy","2br","2cl","2go","2gr","2hy","3br","3cl","3go","3gr","3hy","4br","4cl","4go","4gr","4hy","5br","5cl","5go","5gr","5hy","6br","6cl","6go","6gr","6hy"],
    "x": x,
    "y": y,
    "color" : ['rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)',                   'rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)','rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)',                   'rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)',                   'rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)',                   'rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)',                   'rgba(177, 86, 15, 0.85)','rgba(0, 0, 0, 1)','rgba(212,175,55, 0.8)','rgba(0, 153, 51, 0.8)','rgba(212,175,55, 0.8)'],
    'pad':1,
    "thickness" : 20,
    "line" : dict(color = "black", width = 0.5),},
link = {
    "source": [0,0,0,0,0,1,1,1,1,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,6,6,6,6,7,8,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11,12,12,12,13,13,13,13,14,15,15,15,16,16,16,17,17,17,18,18,18,18,19,19,20,20,20,21,21,21,22,22,23,23,23,24,24,24,24,25,25,25,25,26,26,26,26,27,28,28,28,28,29],
    "target": [5,6,7,8,9,5,6,8,9,7,5,6,7,8,9,5,6,7,8,9,10,11,12,13,14,10,11,13,14,12,10,11,13,14,11,12,13,14,15,16,18,19,15,16,18,19,15,17,19,15,16,18,19,19,20,21,23,20,21,23,20,22,24,20,21,23,24,21,24,25,26,28,25,26,28,27,29,25,26,28,25,27,28,29,30,31,33,34,30,31,33,34,32,30,31,33,34,34],
    "value": [322,14,4,6,1,47,1177,36,26,37,8,17,1,209,6,1,4,97,5,333,228,103,5,33,9,110,1016,77,9,139,27,12,203,14,3,5,12,346,336,21,7,1,74,1014,40,6,2,146,1,22,2,286,15,378,377,38,19,4,978,55,2,143,1,1,3,322,7,1,400,362,6,16,9,960,51,139,4,9,9,378,5,1,1,401,377,1,4,3,2,845,127,1,140,11,14,420,1,405]
}))

fig.show()


问:
Enable source mapping on CRA with typescript and webpack
I recently converted my create-react-app to typescript. I've lost the feature where I could see the file name when viewing the console in developer tools.

My tsconfig.json is as follows:

"target": "ES2018",
"module": "commonjs",
"checkJs": false,
"jsx": "react",
"sourceMap": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
```
<p>I'm a bit overwhelmed by the size of my <code>webpack.config.js</code> file (I think it was generated when I created my CRA). Here are some sections:</p>
<pre class="lang-js prettyprint-override"><code>{
    devtool: isEnvProduction
      ? shouldUseSourceMap
        ? 'source-map'
        : false
      : isEnvDevelopment && 'cheap-module-source-map',
...
 module: {
      strictExportPresence: true,
      rules: [
        { parser: { requireEnsure: false } },
        {
          test: /\.(ts|js)x?$/i,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: [
                "@babel/preset-env",
                "@babel/preset-react",
                "@babel/preset-typescript",
              ],
            },
          },
        },
      ],
    },
}
</code>```

How do I get my dev tools to show the actual files where errors are coming from?

答:
Suggest you to have 2 separate webpack configs. Then use webpack-merge to join them.

Make sure to set mode in either of those:
dev:
{..., mode: 'development', ... }
prod:
{..., mode: 'production', ... }

set devtools to eval-source-map in development, and to whatever you prefer in production

sourceMap to true in tsconfig (as you do)

Check webpack 5(I presume this is what you have) docs on devtooling.

Body:
I recently converted my create-react-app to typescript. I've lost the feature where I could see the file name when viewing the console in developer tools.

My tsconfig.json is as follows:

"target": "ES2018",
"module": "commonjs",
"checkJs": false,
"jsx": "react",
"sourceMap": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true

I'm a bit overwhelmed by the size of my webpack.config.js file (I think it was generated when I created my CRA). Here are some sections:

{
    devtool: isEnvProduction
      ? shouldUseSourceMap
        ? 'source-map'
        : false
      : isEnvDevelopment && 'cheap-module-source-map',
...
 module: {
      strictExportPresence: true,
      rules: [
        { parser: { requireEnsure: false } },
        {
          test: /\.(ts|js)x?$/i,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: [
                "@babel/preset-env",
                "@babel/preset-react",
                "@babel/preset-typescript",
              ],
            },
          },
        },
      ],
    },
}

How do I get my dev tools to show the actual files where errors are coming from?


问:
Reading values from a key within a Directory within a List from a JSON file using Python
I've got a rather ML ugly JSON file that I'm trying to pull values from.

Below is the first entry on the list: [ {"ID":"ckzjqmtvf3ltd0z7yhogt3ttm", "DataRow ID":"ckzjq9ry03hfp0zux8xwkhkvv", "Label":{"objects": [{"featureId":"ckzjqnrn600012469dfbkfr1q", "schemaId":"ckzjqkttm3m8v0z78e7rdbkda", "color":"#1CE6FF", "title":"Weed", "value":"weed", "bbox":{"top":1003, "left":810, "height":848, "width":881}, {"featureId":"ckzjqo6iy000724690onwpxax", "schemaId":"ckzjqkttm3m8v0z78e7rdbkda", "color":"#1CE6FF", "title":"Weed", "value":"weed", "bbox"{"top":1780, "left":410, "height":264, "width":254}, {"featureId":"ckzjqobrv000a24697tc84nrr", "schemaId":"ckzjqkttm3m8v0z78e7rdbkda", "color":"#1CE6FF", "title":"Weed", "value":"weed", "bbox":{"top":1060, "left":1799, "height":471, "width":523},]

I am trying to extract the title and bbox information.

I have tried data["Label"][0]["title"], but I get:

KeyError: 0

Any help would be amazing!

答:
Code to read title and bbox information of all items in json file:</p>
```<code>import json

with open("data.json") as file:
    data = json.load(file)

for item in data:
    objects = item['Label']['objects']
    for obj in objects:
        title = obj['title']
        bbox = obj['bbox']
</code>```

Body:
Code to read title and bbox information of all items in json file:

import json

with open("data.json") as file:
    data = json.load(file)

for item in data:
    objects = item['Label']['objects']
    for obj in objects:
        title = obj['title']
        bbox = obj['bbox']


问:
How to create a random string and use it in jinja in Ansible
I would like to create a random string in Ansible tasks and use it in jinja2.

The string should contain 0-9, a-z, A-Z with a length of 32 characters.

I found out this function but can't use it in a set_fact

lookup('community.general.random_string', length=12)
```

I'm using Ansible 2.12.1
set_fact writes the string "lookup('community.general.random_string', length=12)" in me template.
I need to create once a random string to use it as passphrase in a config file. On the second run the random string should not be touched - need to add also a check if file exists or something like that.

答:
A way to create a random string and then add it as a fact would be something like this

---
- hosts: test

  vars:
    my_pass_var: "{{ lookup('password', '/dev/null length=32 chars=ascii_letters,digits') }}"

  tasks:
    - set_fact:
        my_pass_as_fact: "{{ my_pass_var }}"
    - debug:
        msg: "{{ my_pass_as_fact }}"
```

Body:
I would like to create a random string in Ansible tasks and use it in jinja2.

The string should contain 0-9, a-z, A-Z with a length of 32 characters.

I found out this function but can't use it in a set_fact

lookup('community.general.random_string', length=12)

I'm using Ansible 2.12.1
set_fact writes the string "lookup('community.general.random_string', length=12)" in me template.
I need to create once a random string to use it as passphrase in a config file. On the second run the random string should not be touched - need to add also a check if file exists or something like that.


问:
I get "no data in the table"
II'm having a problem setting the body in the dynamic content table.

I get no data in the table.

In fact, thead has been set correctly, but most likely the problem is the tbody; the header of the columns is perfectly displayed, but the content is not.

Can anyone kindly help me?

var allart = JSON.parse(this.responseText);
                console.log(allart);
                var tbdy = document.createElement('tbody');
                allart.Items.forEach(function (item) {
                    let child = document.createElement("tr");
                    child.innerHTML = `
                    ${item.id}
                    ${item.titolo}
                    ${item.marca}
                    ${item.immagine}
                    ${item.sezione}
                    ${item.data}
                    `;
                    table.appendChild(child);
                })
                tbdy.appendChild(tr);
                table.appendChild(tbdy);

$(document).ready(function () {
            $('#my-table').DataTable({
                "pagingType": "full_numbers",
                "lengthMenu": [5, 10, 20, 50, 100, 200, 500],
            });
            $('.dataTables_length').addClass('bs-select');
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="my-table" class="row-border hover" width="90%">
        <thead>
            <tr>
                <th class="th-sm">Id</th>
                <th class="th-sm">Titolo</th>
                <th class="th-sm">Marca</th>
                <th class="th-sm">Immagine</th>
                <th class="th-sm">Sezione</th>
                <th class="th-sm">Data</th>

            </tr>
        </thead>

    </table></code>```

allart is:

0: {title: 'Moto Guzzi V100 Mandello, the queen of EICMA 2021', date: '27 / 11/2021 ', brand:' Guzzi ', section:' In evidence ', id:' 123456 ',…}
1: {title: "Bimota: an adventure based on Tesi will arrive", date: '04 / 12/2021 ', brand:' Bimota ', section:' In evidence ', id:' 135623 ',…}
2: {title: "Chaleco López inaugurates' his' museum", date: '22 / 01/2022 ', brand:' Chaleco ', section:' On the front page ', id:' 256346 ',…}```

答:
In your loop, your adding the row to the table. I guess you want to add it to the body.

Try this.

```<code>var allart = JSON.parse(this.responseText);
                console.log(allart);
                var tbdy = document.createElement('tbody');
                allart.Items.forEach(function (item) {
                    let child = document.createElement("tr");
                    child.innerHTML = `
                    <td>${item.id}</td>
                    <td>${item.titolo}</td>
                    <td>${item.marca}</td>
                    <td>${item.immagine}</td>
                    <td>${item.sezione}</td>
                    <td>${item.data}</td>
                    `;
                    // table.appendChild(child);
                    // add row to table body
                    tbdy.appendChild(tr);
                })
                // we dont need this
                // tbdy.appendChild(tr);
                table.appendChild(tbdy);

$(document).ready(function () {
            $('#my-table').DataTable({
                "pagingType": "full_numbers",
                "lengthMenu": [5, 10, 20, 50, 100, 200, 500],
            });
            $('.dataTables_length').addClass('bs-select');
        });
</code>```

Title: I get "no data in the table"

Body:
II'm having a problem setting the body in the dynamic content table.

I get no data in the table.

In fact, thead has been set correctly, but most likely the problem is the tbody; the header of the columns is perfectly displayed, but the content is not.

Can anyone kindly help me?

var allart = JSON.parse(this.responseText);
                console.log(allart);
                var tbdy = document.createElement('tbody');
                allart.Items.forEach(function (item) {
                    let child = document.createElement("tr");
                    child.innerHTML = `
                    ${item.id}
                    ${item.titolo}
                    ${item.marca}
                    ${item.immagine}
                    ${item.sezione}
                    ${item.data}
                    `;
                    table.appendChild(child);
                })
                tbdy.appendChild(tr);
                table.appendChild(tbdy);

$(document).ready(function () {
            $('#my-table').DataTable({
                "pagingType": "full_numbers",
                "lengthMenu": [5, 10, 20, 50, 100, 200, 500],
            });
            $('.dataTables_length').addClass('bs-select');
        });

                Id
                Titolo
                Marca
                Immagine
                Sezione
                Data

allart is:

0: {title: 'Moto Guzzi V100 Mandello, the queen of EICMA 2021', date: '27 / 11/2021 ', brand:' Guzzi ', section:' In evidence ', id:' 123456 ',…}
1: {title: "Bimota: an adventure based on Tesi will arrive", date: '04 / 12/2021 ', brand:' Bimota ', section:' In evidence ', id:' 135623 ',…}
2: {title: "Chaleco López inaugurates' his' museum", date: '22 / 01/2022 ', brand:' Chaleco ', section:' On the front page ', id:' 256346 ',…}

Body:
In your loop, your adding the row to the table. I guess you want to add it to the body.

Try this.

var allart = JSON.parse(this.responseText);
                console.log(allart);
                var tbdy = document.createElement('tbody');
                allart.Items.forEach(function (item) {
                    let child = document.createElement("tr");
                    child.innerHTML = `
                    <td>${item.id}</td>
                    <td>${item.titolo}</td>
                    <td>${item.marca}</td>
                    <td>${item.immagine}</td>
                    <td>${item.sezione}</td>
                    <td>${item.data}</td>
                    `;
                    // table.appendChild(child);
                    // add row to table body
                    tbdy.appendChild(tr);
                })
                // we dont need this
                // tbdy.appendChild(tr);
                table.appendChild(tbdy);

$(document).ready(function () {
            $('#my-table').DataTable({
                "pagingType": "full_numbers",
                "lengthMenu": [5, 10, 20, 50, 100, 200, 500],
            });
            $('.dataTables_length').addClass('bs-select');
        });


问:
PHP send variable value external webpage
I'm currently trying to send the two variable values, $incorrect and $correct from a form.

I have tried to use $_POST[] to create this functionality, yet it doesn't work!

Could anyone help me when creating such a functionality  ?

page1.php

```<code><form action="testresult.php" method="POST">
    <label for="qn1">Question 1: <?php echo $array_question[$question_num_array[0]] ?></label><br>
    <input type="text" id="question1_answer" name="question1_answer" required><br><br>

    <label for="qn2">Question 2: <?php echo $array_question[$question_num_array[1]] ?></label><br>
    <input type="text" id="question2_answer" name="question2_answer" required><br><br>

    <label for="qn3">Question 3: <?php echo $array_question[$question_num_array[2]] ?></label><br>
    <input type="text" id="question3_answer" name="question3_answer" required><br><br>

    <input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
    <input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" />

    <input type="submit" name="submitAnswers" value="Submit">
</form>

<?php
        if(isset($_POST["submitAnswers"])){
            $correct = 0;
            $incorrect = 0;
            $qn1_ans = $_POST['question1_answer'];
            $qn2_ans = $_POST['question2_answer'];
            $qn3_ans = $_POST['question3_answer'];

            if ($qn1_ans == $array_answer[$question_num_array[0]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn2_ans == $array_answer[$question_num_array[1]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn3_ans == $array_answer[$question_num_array[2]]){ $correct ++; }
            else { $incorrect ++; }

        }
    ?>
</code>```

And on the receiving end
page2.php

```<code><html>
    <head>
    <title>Results</title>
    </head>
    <body>
        <?php
        $correct = $_POST['correct'];
        $incorrect = $_POST['incorrect'];

        echo $correct."test ".$incorrect;
        ?>
    </body>
</html>
</code>```

答:
Your first page should JUST show the questions, it will be like this.

```<code><form action="testresult.php" method="POST">
    <label for="qn1">Question 1: <?php echo $array_question[$question_num_array[0]] ?></label><br>
    <input type="text" id="question1_answer" name="question1_answer" required><br><br>

    <label for="qn2">Question 2: <?php echo $array_question[$question_num_array[1]] ?></label><br>
    <input type="text" id="question2_answer" name="question2_answer" required><br><br>

    <label for="qn3">Question 3: <?php echo $array_question[$question_num_array[2]] ?></label><br>
    <input type="text" id="question3_answer" name="question3_answer" required><br><br>

    <!--input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
    <input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" /-->

    <input type="submit" name="submitAnswers" value="Submit">
</form>
</code>```

When you hit the submit button, the answers are posted to testresult.php.

In this file, first checking the answers, then showing the result.

The page doesn't contain questions, so you need to include the php file too.

```<code><html>
    <head>
    <title>Results</title>
    </head>
    <body>
        <?php
        if(isset($_POST["submitAnswers"])){
            include 'question.php'; #include the question array.

            $correct = 0;
            $incorrect = 0;
            $qn1_ans = $_POST['question1_answer'];
            $qn2_ans = $_POST['question2_answer'];
            $qn3_ans = $_POST['question3_answer'];

            if ($qn1_ans == $array_answer[$question_num_array[0]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn2_ans == $array_answer[$question_num_array[1]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn3_ans == $array_answer[$question_num_array[2]]){ $correct ++; }
            else { $incorrect ++; }

            echo $correct."test ".$incorrect;
        }
        ?>
    </body>
</html>
</code>```

Body:
I'm currently trying to send the two variable values, $incorrect and $correct from a form.

I have tried to use $_POST[] to create this functionality, yet it doesn't work!

Could anyone help me when creating such a functionality  ?

page1.php

<form action="testresult.php" method="POST">
    Question 1: <?php echo $array_question[$question_num_array[0]] ?>

    <input type="text" id="question1_answer" name="question1_answer" required>

    Question 2: <?php echo $array_question[$question_num_array[1]] ?>

    <input type="text" id="question2_answer" name="question2_answer" required>

    Question 3: <?php echo $array_question[$question_num_array[2]] ?>

    <input type="text" id="question3_answer" name="question3_answer" required>

    <input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
    <input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" />

    <input type="submit" name="submitAnswers" value="Submit">
</form>

<?php
        if(isset($_POST["submitAnswers"])){
            $correct = 0;
            $incorrect = 0;
            $qn1_ans = $_POST['question1_answer'];
            $qn2_ans = $_POST['question2_answer'];
            $qn3_ans = $_POST['question3_answer'];

            if ($qn1_ans == $array_answer[$question_num_array[0]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn2_ans == $array_answer[$question_num_array[1]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn3_ans == $array_answer[$question_num_array[2]]){ $correct ++; }
            else { $incorrect ++; }

        }
    ?>

And on the receiving end
page2.php

    <title>Results</title>

        <?php
        $correct = $_POST['correct'];
        $incorrect = $_POST['incorrect'];

        echo $correct."test ".$incorrect;
        ?>

Body:
Your first page should JUST show the questions, it will be like this.

<form action="testresult.php" method="POST">
    <label for="qn1">Question 1: <?php echo $array_question[$question_num_array[0]] ?></label><br>
    <input type="text" id="question1_answer" name="question1_answer" required><br><br>

    <label for="qn2">Question 2: <?php echo $array_question[$question_num_array[1]] ?></label><br>
    <input type="text" id="question2_answer" name="question2_answer" required><br><br>

    <label for="qn3">Question 3: <?php echo $array_question[$question_num_array[2]] ?></label><br>
    <input type="text" id="question3_answer" name="question3_answer" required><br><br>

    <!--input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
    <input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" /-->

    <input type="submit" name="submitAnswers" value="Submit">
</form>

When you hit the submit button, the answers are posted to testresult.php.

In this file, first checking the answers, then showing the result.

The page doesn't contain questions, so you need to include the php file too.

<html>
    <head>
    <title>Results</title>
    </head>
    <body>
        <?php
        if(isset($_POST["submitAnswers"])){
            include 'question.php'; #include the question array.

            $correct = 0;
            $incorrect = 0;
            $qn1_ans = $_POST['question1_answer'];
            $qn2_ans = $_POST['question2_answer'];
            $qn3_ans = $_POST['question3_answer'];

            if ($qn1_ans == $array_answer[$question_num_array[0]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn2_ans == $array_answer[$question_num_array[1]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn3_ans == $array_answer[$question_num_array[2]]){ $correct ++; }
            else { $incorrect ++; }

            echo $correct."test ".$incorrect;
        }
        ?>
    </body>
</html>


问:
Getting the logical path in VIM when there's a symlink
I have the following setup:

```<code>mkdir /1
mkdir /1/2
mkdir /1/2/3
ln -s /1/2/3 /1/3
</code>```

If I do cd /1/3, and then pwd, I get /1/3. If I use pwd -P, I can get /1/2/3, or pwd -L to force /1/3.

In VIM, I'm looking for a way to get the /1/3.

If I open a file in /1/3/foo.txt, and I use something like fnamemodify(bufname(winbufnr(0)), ':p:h'), it returns /1/2/3.

How can I tell it to give me the same directory that pwd would give?

答:
It appears you can't, other than via system('pwd -L').  According to the vim_use mailing list Vim automatically resolves symlinks nowadays.

See the text around :h E773 for rationale; if Vim went by symlinks instead of resolved filename, it'd be possible to have the same file open in two buffers under two different names, and Vim would become confused trying to figure out where the swap file should be.  See also in :h version7.txt:

Unix: When editing a file through a symlink the swap file would use the name
  of the symlink.  Now use the name of the actual file, so that editing the same
  file twice is detected.

OwnerDisplayName: Mikeage

Body:
I have the following setup:

mkdir /1
mkdir /1/2
mkdir /1/2/3
ln -s /1/2/3 /1/3

If I do cd /1/3, and then pwd, I get /1/3. If I use pwd -P, I can get /1/2/3, or pwd -L to force /1/3.

In VIM, I'm looking for a way to get the /1/3.

If I open a file in /1/3/foo.txt, and I use something like fnamemodify(bufname(winbufnr(0)), ':p:h'), it returns /1/2/3.

How can I tell it to give me the same directory that pwd would give?

LastEditorDisplayName: VonC

OwnerDisplayName: Brian Carper


问:
how to parse twitter API v2 timestamps to python datetime
Twitter API v2 specifies how their timestamps are formated here.

An example of a timestamp from a tweet's created_at is: 2021-12-31T12:34:56.000Z

Question: How to parse this format with python's datetime?

答:
This can be achieved by knowing that the .000 refers to the microseconds and Z to the UTC timezone, and using an adaptation of the ISO-8601 format "%Y-%m-%dT%H:%M:%S.%fZ":

from datetime import datetime

# or: tweet["data"]["created_at"] from the API
tweet_created_at = "2021-12-31T12:34:56.000Z"

dt = datetime.strptime(tweet_created_at ,"%Y-%m-%dT%H:%M:%S.%fZ")
print(dt) # outputs: 2021-12-31 12:34:56
```


问:
What is difference between primary and onPrimary properties in ColorScheme Flutter
While defining ThemeData of the Flutter app, we can define colorScheme property.
This property has inner-properties such as background & onBackground, primary & onPrimary, secondary & onSecondary, etc. Also, all these properties are set as required.

```<code>  static final ThemeData lightTheme = ThemeData(
    colorScheme: ColorScheme(
      background: appBackgroundColor,
      brightness: Brightness.light,
      error: Colors.white,
      onBackground: primaryColor,
      onError: null,
      onPrimary: null,
      onSecondary: null,
      onSurface: null,
      primary: null,
      secondary: secondaryColor,
      surface: null,
    ),
  );
</code>```

I tried referring the documentation of Flutter but I was not quite able to understand the difference between them.

答:
Many of the colors have matching 'on' colors, which are used for drawing content on top of the matching color. For example, if something is using primary for a background color, onPrimary would be used to paint text and icons on top of it. For this reason, the 'on' colors should have a contrast ratio with their matching colors of at least 4.5:1 in order to be readable.

Got this from https://api.flutter.dev/flutter/material/ColorScheme-class.html

Body:
While defining ThemeData of the Flutter app, we can define colorScheme property.
This property has inner-properties such as background & onBackground, primary & onPrimary, secondary & onSecondary, etc. Also, all these properties are set as required.

  static final ThemeData lightTheme = ThemeData(
    colorScheme: ColorScheme(
      background: appBackgroundColor,
      brightness: Brightness.light,
      error: Colors.white,
      onBackground: primaryColor,
      onError: null,
      onPrimary: null,
      onSecondary: null,
      onSurface: null,
      primary: null,
      secondary: secondaryColor,
      surface: null,
    ),
  );

I tried referring the documentation of Flutter but I was not quite able to understand the difference between them.


问:
here is an API that changes after some time I want previous data to be stored in an array and latest data too I dont how to figure this out?
I want data state to be an array which adds up the data when the data in the API changes
such that it stores previous data as well as new data so I can map them and display them

App.js

```<code>import React, { useEffect, useState } from "react";

const App = () => {
  const [data, setData] = useState([]);
  const [entireData, setEntireDate] = useState([]);

  let arr = [];
  const fetchAPI = async () => {
    const API = await fetch("https://randomuser.me/api");
    const json = await API.json();
    let results = json.results;
    setData(results);
  };

  useEffect(() => {
    fetchAPI();
  }, []);

  useEffect(() => {}, [data]);

  return (
    <>
      <div className="container">
        <p>
          {data.map((val, idx, arr) => {
            return val.login.username;
          })}
        </p>
        <img
          src={data.map((val, idx, arr) => {
            return val.picture.large;
          })}
          alt="getPicFromJson"
        />
      </div>
    </>
  );
};

export default App;
</code>```

index.js

```<code>import { StrictMode } from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);
</code>```

答:
maybe try something like this

```<code>  const fetchAPI = async () => {
    const API = await fetch("https://randomuser.me/api");
    const json = await API.json();
    let results = json.results;
    // here you get the old data and pushing the results into Data
    Data.push(results)
    // and setData to Data that has (Data + results)
    setData(Data);
  };
</code>```

also if you want to have your data after refreshing your browser , you may need to store Data in localstorage and get the initial data from that

Body:
I want data state to be an array which adds up the data when the data in the API changes
such that it stores previous data as well as new data so I can map them and display them

App.js

import React, { useEffect, useState } from "react";

const App = () => {
  const [data, setData] = useState([]);
  const [entireData, setEntireDate] = useState([]);

  let arr = [];
  const fetchAPI = async () => {
    const API = await fetch("https://randomuser.me/api");
    const json = await API.json();
    let results = json.results;
    setData(results);
  };

  useEffect(() => {
    fetchAPI();
  }, []);

  useEffect(() => {}, [data]);

  return (
    <>

          {data.map((val, idx, arr) => {
            return val.login.username;
          })}

         {
            return val.picture.large;
          })}
          alt="getPicFromJson"
        />

    </>
  );
};

export default App;

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);

Body:
maybe try something like this

  const fetchAPI = async () => {
    const API = await fetch("https://randomuser.me/api");
    const json = await API.json();
    let results = json.results;
    // here you get the old data and pushing the results into Data
    Data.push(results)
    // and setData to Data that has (Data + results)
    setData(Data);
  };

also if you want to have your data after refreshing your browser , you may need to store Data in localstorage and get the initial data from that


问:
Bootstrap datetime picker without any javascript or jQuery
Is there anyway of using bootstrap to have a datetime keeper without using any javascript or jQuery? Bootstrap should have some sort of classes for that but I can't find them?</p>

答:
Vanilla JS Datepicker

A vanilla JavaScript remake of bootstrap-datepicker for Bulma and other CSS frameworks

This package is written from scratch as ECMAScript modules/Sass stylesheets to reproduce similar usability to bootstrap-datepicker.

You can get rid of jQuery.