问:
User.Identity.IsAuthenticated is false in a non-auth methods after successful login in asp.net core
I am new in asp.net core. I try to login with discord as 3rd party login service (like sign-in with facebook, google).

I can login successfully and have my user object, claims and I can enter a class which has an authorize attribute. Below you can see that UserIdentity is fine.

But let assume that user wants to go back to the login page. In this case, I have to redirect him to the index but I want to check whether the user is authenticated or not by using Identity and unfortunately, it is false and no claims etc. As I understand, it may be related with cookies or something similar. I also use different attribute for class (not authorize but AllowAnonymous) You can see below my Identity object

I am sharing my authentication code

```<code>services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

})
  .AddCookie(options =>
   {
      options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
      options.Cookie.MaxAge = options.ExpireTimeSpan;
      options.SlidingExpiration = true;
      options.EventsType = typeof(CustomCookieAuthenticationEvents);
      options.AccessDeniedPath = "/auth/DiscordAuthFailed";

    })
     .AddJwtBearer(options =>
      {
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters()
        {
           ValidateIssuer = false,
           ValidateAudience = false,
           ValidateIssuerSigningKey = true,
           ValidIssuer = Configuration.GetValue<string>("Jwt:Issuer"),
           ValidAudience = Configuration.GetValue<string>("Jwt:Audience"),
           IssuerSigningKey = new SymmetricSecurityKey(
               Encoding.UTF8.GetBytes(Configuration.GetValue<string>("Jwt:EncryptionKey")))
        };
    })
     .AddOAuth("Discord",
         options =>
         {
           options.AuthorizationEndpoint = "https://discord.com/api/oauth2/authorize";
           options.TokenEndpoint = "https://discord.com/api/oauth2/token";
           options.Scope.Add("identify");
           options.Scope.Add("email");
           options.Scope.Add("guilds.join");
           options.Scope.Add("guilds.members.read");

          options.CallbackPath = "/auth/oauthCallback";
          options.ClientId = Configuration.GetValue<string>("Discord:ClientId");
          options.ClientSecret = Configuration.GetValue<string>("Discord:ClientSecret");
          options.UserInformationEndpoint = "https://discord.com/api/users/@me";

          options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
          options.ClaimActions.MapJsonKey(ClaimTypes.Name, "username");
          options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
          options.ClaimActions.MapJsonKey(ClaimTypes.IsPersistent, "verified");

          options.AccessDeniedPath = "/auth/DiscordAuthFailed";
          options.Events = new OAuthEvents()
           {
             OnCreatingTicket = async context =>
              {
               var request = new HttpRequestMessage(HttpMethod.Get,
               context.Options.UserInformationEndpoint);
               request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
               request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                var response = await context.Backchannel.SendAsync(request,
                HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);

                response.EnsureSuccessStatusCode();

                var user=(await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync())).RootElement;

                context.RunClaimActions(user);

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

services.AddTransient();

So my question is that, what is the best approach to access userIdentify object in any class/method after successfully login?

答:
You can use the GetUserAsync method that will check if a user has been logged in. You need to use the UserManager class that falls under the AspNetCore.Identity to a use the above method. In your case, it will look something like this:

You will first need to configure your UserManager class in Startup.cs by simply adding a parameter to the Configure method:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
 // your code
}
</code>```

And then you can use it in your Controller method:

```<code>[Route("Account")]
public class AccountController: Controller
{

   private UserManager<ApplicationUser> _userManager;

   public AccountController(UserManager<ApplicationUser> userManager)
   {
     _userManager = userManager;
   }

   [Route("Login")]
   [AllowAnonymous]
   public IActionResult Login()
   {
      ClaimsPrincipal currentUser = User;
      var user =_userManager.GetUserAsync(User).Result;
      if(user.Identity.IsAuthenticated)
      {
        //redirect here
      }

      return View();
   }
}
</code>```

You need to update your ConfigureServices to include the Default Identity:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseMySql(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
}
</code>```

Body:
I am new in asp.net core. I try to login with discord as 3rd party login service (like sign-in with facebook, google).

I can login successfully and have my user object, claims and I can enter a class which has an authorize attribute. Below you can see that UserIdentity is fine.

But let assume that user wants to go back to the login page. In this case, I have to redirect him to the index but I want to check whether the user is authenticated or not by using Identity and unfortunately, it is false and no claims etc. As I understand, it may be related with cookies or something similar. I also use different attribute for class (not authorize but AllowAnonymous) You can see below my Identity object

I am sharing my authentication code

services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

})
  .AddCookie(options =>
   {
      options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
      options.Cookie.MaxAge = options.ExpireTimeSpan;
      options.SlidingExpiration = true;
      options.EventsType = typeof(CustomCookieAuthenticationEvents);
      options.AccessDeniedPath = "/auth/DiscordAuthFailed";

    })
     .AddJwtBearer(options =>
      {
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters()
        {
           ValidateIssuer = false,
           ValidateAudience = false,
           ValidateIssuerSigningKey = true,
           ValidIssuer = Configuration.GetValue<string>("Jwt:Issuer"),
           ValidAudience = Configuration.GetValue<string>("Jwt:Audience"),
           IssuerSigningKey = new SymmetricSecurityKey(
               Encoding.UTF8.GetBytes(Configuration.GetValue<string>("Jwt:EncryptionKey")))
        };
    })
     .AddOAuth("Discord",
         options =>
         {
           options.AuthorizationEndpoint = "https://discord.com/api/oauth2/authorize";
           options.TokenEndpoint = "https://discord.com/api/oauth2/token";
           options.Scope.Add("identify");
           options.Scope.Add("email");
           options.Scope.Add("guilds.join");
           options.Scope.Add("guilds.members.read");

          options.CallbackPath = "/auth/oauthCallback";
          options.ClientId = Configuration.GetValue<string>("Discord:ClientId");
          options.ClientSecret = Configuration.GetValue<string>("Discord:ClientSecret");
          options.UserInformationEndpoint = "https://discord.com/api/users/@me";

          options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
          options.ClaimActions.MapJsonKey(ClaimTypes.Name, "username");
          options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
          options.ClaimActions.MapJsonKey(ClaimTypes.IsPersistent, "verified");

          options.AccessDeniedPath = "/auth/DiscordAuthFailed";
          options.Events = new OAuthEvents()
           {
             OnCreatingTicket = async context =>
              {
               var request = new HttpRequestMessage(HttpMethod.Get,
               context.Options.UserInformationEndpoint);
               request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
               request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                var response = await context.Backchannel.SendAsync(request,
                HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);

                response.EnsureSuccessStatusCode();

                var user=(await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync())).RootElement;

                context.RunClaimActions(user);

                }
          };
    });

services.AddTransient();

So my question is that, what is the best approach to access userIdentify object in any class/method after successfully login?

Body:
You can use the GetUserAsync method that will check if a user has been logged in. You need to use the UserManager class that falls under the AspNetCore.Identity to a use the above method. In your case, it will look something like this:

You will first need to configure your UserManager class in Startup.cs by simply adding a parameter to the Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
 // your code
}

And then you can use it in your Controller method:

[Route("Account")]
public class AccountController: Controller
{

   private UserManager<ApplicationUser> _userManager;

   public AccountController(UserManager<ApplicationUser> userManager)
   {
     _userManager = userManager;
   }

   [Route("Login")]
   [AllowAnonymous]
   public IActionResult Login()
   {
      ClaimsPrincipal currentUser = User;
      var user =_userManager.GetUserAsync(User).Result;
      if(user.Identity.IsAuthenticated)
      {
        //redirect here
      }

      return View();
   }
}

You need to update your ConfigureServices to include the Default Identity:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseMySql(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
}


来源: stackexchange

问:
how do i go ahead of this docker run command output

I am new to docker. trying to go throw this tutorial. while running docker.

```<code>docker run -it --rm -p 5200:80 --name pizzabackendcontainer pizzabacken
</code>```

I am getting the output in the image. what is the output suggest. i feel something wrong in the docker file

答:
The tutorial guide us docker run -it --rm -p 5200:80 --name pizzabackendcontainer pizzabackend

-it： That means you will execute the container by terminal mode.

-rm： Automatically remove the container when it exits

So when you execute the command you will be interactive container command line and the container will be stopped when you exit.

```<code>docker run -itd -p 5200:80 --name pizzabackendcontainer-1 pizzabackend
</code>```

If you want to run a container and keep it in your original terminal you can try to add -d parameter that will run the container in the background and print container ID.

more detail about docker run parameter you can refer docker run

ContentLicense: CC BY-SA 4.0

Body:
I am new to docker. trying to go throw this tutorial. while running docker.

docker run -it --rm -p 5200:80 --name pizzabackendcontainer pizzabacken

I am getting the output in the image. what is the output suggest. i feel something wrong in the docker file

Body:
The tutorial guide us docker run -it --rm -p 5200:80 --name pizzabackendcontainer pizzabackend

-it： That means you will execute the container by terminal mode.

-rm： Automatically remove the container when it exits

So when you execute the command you will be interactive container command line and the container will be stopped when you exit.

docker run -itd -p 5200:80 --name pizzabackendcontainer-1 pizzabackend

If you want to run a container and keep it in your original terminal you can try to add -d parameter that will run the container in the background and print container ID.

more detail about docker run parameter you can refer docker run


问:
Google Business API
I need to use Google Business API to access information of a particular category of business from a particular location. Can it be done using Google business API or Google MAPS API?</p>

答:
The Places API is open and offers the following details if you know the placeId of the location:

Basic

The Basic category includes the following fields: address_component,
adr_address, business_status, formatted_address, geometry, icon,
icon_mask_base_uri, icon_background_color, name, permanently_closed
(deprecated), photo, place_id, plus_code, type, url, utc_offset,
vicinity.

Contact

The Contact category includes the following fields:
formatted_phone_number, international_phone_number, opening_hours,
website

Atmosphere

The Atmosphere category includes the following fields: price_level,
rating, review, user_ratings_total.

The Google Profile APIs are restricted and offer the following details if you also own or manage the respective location:

languageCode

storeCode

title

phoneNumbers

categories

storefrontAddress

websiteUri

regularHours

specialHours

serviceArea

labels[]

adWordsLocationExtensions

latlng

openInfo

metadata

profile

relationshipData

moreHours[]

serviceItems[]

Title: Google Business API


问:
Disable prettier for a single file
I need to disable prettier for a single file (API URLs file) in my project in Vs-code. actually, I need each API and its URL to be in one line, but prettier breaks them in two lines.

before

```<code>export const GET_SEARCH_TEACHERS = params => myexampleFunction_app_base(`teachers/search/${params.search}`);
</code>```

after

```<code>export const GET_SEARCH_TEACHERS = params =>
myexampleFunction_app_base(`teachers/search/${params.search}`);
</code>```

答:
Another option is to use the prettier block-like toggle, to disable formatting for a "block" within a file.

For example, adding // prettier-ignore before the start of a function definition, will disable prettier formatting for that function.

Similarly, if you put the line above an if statement, only the if block is ignored.

Basically a block is denoted by a pair of { } matching braces.

```<code>... (code up here is formatted by prettier)

// prettier-ignore
function noPrettierFormattingInHere(){
  ...
}

... (code down here is formatted by prettier)
</code>```

Title: Disable prettier for a single file

Body:
I need to disable prettier for a single file (API URLs file) in my project in Vs-code. actually, I need each API and its URL to be in one line, but prettier breaks them in two lines.

before

export const GET_SEARCH_TEACHERS = params => myexampleFunction_app_base(`teachers/search/${params.search}`);

after

export const GET_SEARCH_TEACHERS = params =>
myexampleFunction_app_base(`teachers/search/${params.search}`);

Body:
Another option is to use the prettier block-like toggle, to disable formatting for a "block" within a file.

For example, adding // prettier-ignore before the start of a function definition, will disable prettier formatting for that function.

Similarly, if you put the line above an if statement, only the if block is ignored.

Basically a block is denoted by a pair of { } matching braces.

... (code up here is formatted by prettier)

// prettier-ignore
function noPrettierFormattingInHere(){
  ...
}

... (code down here is formatted by prettier)


问:
sql group by value within substring of char(255) field
I have a column called image_small for a table images which will have information like this:

```<code>image_small
/images/menu_items/148/5a13140f8ef4503f024d06231037c69e_medium.jpg
/images/menu_items/152/5a14444444444444424d06231037c69e_medium.jpg
 ...
</code>```

I'd like to select out a the count of unique values for the menu item value (148) above (assume 148-400) on Mysql 5.1 using innodb so that output would be like:

```<code>val    count
148    5
101    4
152    1
</code>```

The integer values (148,101,152) don't exist in a column and would rather not loop through.

Any ideas on how to do this? Would seem like would need to create a notion of a variable for the '148' and then a group by but a little clueless.

thx

答:
I'm supposing that all your paths have the same format.

```<code> select
 substring_index(substring_index(str,'/',4),'/',-1) as val,
 count(*)  as `count`
 from table
 group by val
</code>```

It seems to work but I'm afraid about performance on large tables. Do some tests.
Could you add a field with this value? I think it would be better.

ContentLicense: CC BY-SA 3.0

Body:
I have a column called image_small for a table images which will have information like this:

image_small
/images/menu_items/148/5a13140f8ef4503f024d06231037c69e_medium.jpg
/images/menu_items/152/5a14444444444444424d06231037c69e_medium.jpg
 ...

I'd like to select out a the count of unique values for the menu item value (148) above (assume 148-400) on Mysql 5.1 using innodb so that output would be like:

val    count
148    5
101    4
152    1

The integer values (148,101,152) don't exist in a column and would rather not loop through.

Any ideas on how to do this? Would seem like would need to create a notion of a variable for the '148' and then a group by but a little clueless.

thx

Body:
I'm supposing that all your paths have the same format.

 select
 substring_index(substring_index(str,'/',4),'/',-1) as val,
 count(*)  as `count`
 from table
 group by val

It seems to work but I'm afraid about performance on large tables. Do some tests.
Could you add a field with this value? I think it would be better.


问:
How to check if event propagation was stopped?
I am writing an event dispatcher in JavaScript and I've decided to base on standard js CustomEvent class. I can't find out how to detect if event propagation was stopped in the listener (via e.stopPropagation()). Should I rather write an Event object implementation myself?

答:
Just as an idea: why not overwriting the stopPropagation function like this?

```<code>const nativeStopPropagation = Event.prototype.stopPropagation;
Event.prototype.stopPropagation = function() {
    console.log('stopPropagation called');
    nativeStopPropagation.call(this);
};
</code>```

Where the "console.log('Propagation stopped');" is, you can basically put any callback function.

Also works for preventDefault() the exactly same way.

Soluton found here: Is there a way to overwrite event objects and do what I prefer instead?

Best regards
Christian

Body:
Just as an idea: why not overwriting the stopPropagation function like this?

const nativeStopPropagation = Event.prototype.stopPropagation;
Event.prototype.stopPropagation = function() {
    console.log('stopPropagation called');
    nativeStopPropagation.call(this);
};

Where the "console.log('Propagation stopped');" is, you can basically put any callback function.

Also works for preventDefault() the exactly same way.

Soluton found here: Is there a way to overwrite event objects and do what I prefer instead?

Best regards
Christian


问:
Access n:th element of every list in list of lists
I have a problem in python and one step I need to do is to access the second element of every list in a list of lists. The list is:

```<code>[(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')]

[(0, 'A', 'DET' 'det'), (1 'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]
</code>```

The list goes on like that with different sentences for each list.

What I am trying to do is access the third (index 2) element of every list of every tuple. So from the first list, I want to get:

PROPN (from 'Gallery')

VERB (from 'unveils')

ADJ (from 'interactive')

And from the second list I want to get:

DET (from 'A')

PROPN (from 'Christmas')

NOUN (from 'nsubjpass)

What I've tried to do is this:

```<code>for word in list:
      print(list[word[0]][2])
</code>```

But that only outputs the second element from the first list. I tried creating another foor-loop but that didn't work, I suspect I did it wrong but I'm not sure how to solve it

Help would be appreciated

Thanks in advance!

答:
```<code>word= [[(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')],[(0, 'A', 'DET' 'det'), (1,'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]]

[j[2] for i in word for j in i]
</code>```

==> Outputs ['PROPN', 'VERB', 'ADJ', 'DETdet', 'PROPN', 'NOUN']

```<code>[j[1] for i in word for j in i]
</code>```

==> Outputs ['Gallery', 'unveils', 'interactive', 'A', 'Christmas', 'tree']

Body:
I have a problem in python and one step I need to do is to access the second element of every list in a list of lists. The list is:

[(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')]

[(0, 'A', 'DET' 'det'), (1 'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]

The list goes on like that with different sentences for each list.

What I am trying to do is access the third (index 2) element of every list of every tuple. So from the first list, I want to get:

PROPN (from 'Gallery')

VERB (from 'unveils')

ADJ (from 'interactive')

And from the second list I want to get:

DET (from 'A')

PROPN (from 'Christmas')

NOUN (from 'nsubjpass)

What I've tried to do is this:

for word in list:
      print(list[word[0]][2])

But that only outputs the second element from the first list. I tried creating another foor-loop but that didn't work, I suspect I did it wrong but I'm not sure how to solve it

Help would be appreciated

Thanks in advance!

Body:
word= [[(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')],[(0, 'A', 'DET' 'det'), (1,'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]]

[j[2] for i in word for j in i]

==> Outputs ['PROPN', 'VERB', 'ADJ', 'DETdet', 'PROPN', 'NOUN']

[j[1] for i in word for j in i]

==> Outputs ['Gallery', 'unveils', 'interactive', 'A', 'Christmas', 'tree']


问:
Looking for a way to split cells in excel based the last five numbers in a cell
I am looking for a way to fix a mixed data set representing addresses in Excel.

Here is an example dataset.

```<code>Kirchgasse 2389179 Beimerstetten
</code>```

All this should result in three datasets.

```<code>A1 = Kirchgasse 2389179 Beimerstetten
A2 = Kirchgasse 23
A3 = 89179
A4 = Beimerstetten
</code>```

Pattern is, that A3 is always the last 5 numbers in the dataset.

I am totally lost here, as Excel is usually not my weapon of choice.

答:
Put Kirchgasse 2389179 Beimerstetten in the A1 cell, and use the below VBA codes to set the D1 cell value as the last 5 numbers

```<code>Sub Test_Pattern()

    Dim stringOne   As String
    Dim regexOne    As Object

    Set regexOne = New RegExp

    regexOne.Pattern = "(\d{5})(?!.*\d)"
    regexOne.Global = TRUE
    regexOne.IgnoreCase = IgnoreCase
    stringOne = Range("A1").Value

    Set theMatches = regexOne.Execute(stringOne)

    For Each Match In theMatches
        Range("D1").Value = Match.Value
    Next

End Sub
</code>```

To learn how to use regex in VBA, see this ref

Body:
I am looking for a way to fix a mixed data set representing addresses in Excel.

Here is an example dataset.

Kirchgasse 2389179 Beimerstetten

All this should result in three datasets.

A1 = Kirchgasse 2389179 Beimerstetten
A2 = Kirchgasse 23
A3 = 89179
A4 = Beimerstetten

Pattern is, that A3 is always the last 5 numbers in the dataset.

I am totally lost here, as Excel is usually not my weapon of choice.

Body:
Put Kirchgasse 2389179 Beimerstetten in the A1 cell, and use the below VBA codes to set the D1 cell value as the last 5 numbers

Sub Test_Pattern()

    Dim stringOne   As String
    Dim regexOne    As Object

    Set regexOne = New RegExp

    regexOne.Pattern = "(\d{5})(?!.*\d)"
    regexOne.Global = TRUE
    regexOne.IgnoreCase = IgnoreCase
    stringOne = Range("A1").Value

    Set theMatches = regexOne.Execute(stringOne)

    For Each Match In theMatches
        Range("D1").Value = Match.Value
    Next

End Sub

To learn how to use regex in VBA, see this ref


问:
Normalized Cross-Correlation in Python
I have been struggling the last days trying to compute the degrees of freedom of two pair of vectors (x and y) following reference of Chelton (1983) which is:

degrees of freedom according to Chelton(1983)

and I can't find a proper way to calculate the normalized cross correlation function using np.correlate,
I always get an output that it isn't in between -1, 1.

Is there any easy way to get the cross correlation function normalized in order to compute the degrees of freedom of two vectors?

答:
MATLAB ➜ xcorr(a, b, 'normalized');

MATLAB normalized cross-correlation implementation in Python.

```<code>import numpy as np
a = [1, 2, 3, 4]
b = [2, 4, 6, 8]
norm_a = np.linalg.norm(a)
a = a / norm_a
norm_b = np.linalg.norm(b)
b = b / norm_b
c = np.correlate(a, b, mode = 'full')
</code>```

Title: Normalized Cross-Correlation in Python

Body:
MATLAB ➜ xcorr(a, b, 'normalized');

MATLAB normalized cross-correlation implementation in Python.

import numpy as np
a = [1, 2, 3, 4]
b = [2, 4, 6, 8]
norm_a = np.linalg.norm(a)
a = a / norm_a
norm_b = np.linalg.norm(b)
b = b / norm_b
c = np.correlate(a, b, mode = 'full')


问:
Angular multi-language input field for entering text in multiple languages
I am working on a multi-language web application using Angular 12 and ASP.NET Core 6 for the backend. For the most part, all interactions with the backend are simple CRUD operations. In many cases, the entities being used in the application have properties (such as names) which have different values depending on the (browser) language. This means that, depending on the language of the frontend, a different value should be displayed for such properties. In order to do this, the backend returns such properties as a dictionary where they key is the language and the value is the translation for the property in the specific language. Here is an example:

```<code> id: 1,
      name: {
        en: "Apple",
        de: "Apfel",
      },
...
</code>```

The frontend then uses the browser language to decide which translation should be displayed. If there is no translation for the browser language, the english translation will be used. For static text, such as labels of controls, headlines etc., ngx-translate is used.

This approach already works perfectly fine, but so far there is no way to allow the user to specify multiple translations when a new entity is created via the frontend. Instead, the property is entered via a mat-form-field like this:

```<code><mat-form-field>
  <mat-label>{{ "translations.name" | translate }}</mat-label>
  <input matInput formControlName="name" />
  <mat-error
    *ngIf="createForm.hasError('required', 'name')"
    [innerHtml]="'translations.errors.required' | translate | markdown"
  ></mat-error>
</mat-form-field>
</code>```

The entered text is then added to the name dictionary with the current browser language as key.

What I am now looking for is a way to replace this standard input field with something that supports entering multiple strings for different languages. I'd prefer this input field to be similar to the normal text input field but with an additional button/icon that opens a new dialog where multiple translations can be entered for different languages (e.g. in a table). Does such a control already exist, or is this something I would have to implement myself?

答:
I think it's something you would implement yourself, however, you can use a 3rd-party library that supports multi-languages input such as Angular Formly.

And here is their related example that you can use or take a look at how it's implemented to implement something similar using ngx-translate:

https://formly.dev/examples/advanced/i18n

Body:
I am working on a multi-language web application using Angular 12 and ASP.NET Core 6 for the backend. For the most part, all interactions with the backend are simple CRUD operations. In many cases, the entities being used in the application have properties (such as names) which have different values depending on the (browser) language. This means that, depending on the language of the frontend, a different value should be displayed for such properties. In order to do this, the backend returns such properties as a dictionary where they key is the language and the value is the translation for the property in the specific language. Here is an example:

 id: 1,
      name: {
        en: "Apple",
        de: "Apfel",
      },
...

The frontend then uses the browser language to decide which translation should be displayed. If there is no translation for the browser language, the english translation will be used. For static text, such as labels of controls, headlines etc., ngx-translate is used.

This approach already works perfectly fine, but so far there is no way to allow the user to specify multiple translations when a new entity is created via the frontend. Instead, the property is entered via a mat-form-field like this:

<mat-form-field>
  <mat-label>{{ "translations.name" | translate }}</mat-label>
  <input matInput formControlName="name" />
  <mat-error
    *ngIf="createForm.hasError('required', 'name')"
    [innerHtml]="'translations.errors.required' | translate | markdown"
  ></mat-error>
</mat-form-field>

The entered text is then added to the name dictionary with the current browser language as key.

What I am now looking for is a way to replace this standard input field with something that supports entering multiple strings for different languages. I'd prefer this input field to be similar to the normal text input field but with an additional button/icon that opens a new dialog where multiple translations can be entered for different languages (e.g. in a table). Does such a control already exist, or is this something I would have to implement myself?


问:
What is this Objective-C syntax, ellipse style dot notation? "..."
I noticed this in Joe Hewitt's source for Three20 and I've never seen this particular syntax in Objective-C before. Not even sure how to reference it in an appropriate Google search.

From TTTableViewDataSource:

```<code>+ (TTSectionedDataSource*)dataSourceWithObjects:(id)object,... {
</code>```

The "..." is what's throwing me off here. I'm assuming it's a form of enumeration where a variable amount of arguments may be supplied. If it is, what's the official name for this operator and where can I reference the documentation for it?

Thank you kindly.

答:
It's a variadic method, meaning it takes a variable number of arguments.  This page has a good demonstration of how to use it:</p>

```<code>#import <Cocoa/Cocoa.h>

@interface NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...;  // This method takes a nil-terminated list of objects.

@end

@implementation NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...
{
id eachObject;
va_list argumentList;
if (firstObject)                      // The first argument isn't part of the varargs list,
  {                                   // so we'll handle it separately.
  [self addObject: firstObject];
  va_start(argumentList, firstObject);          // Start scanning for arguments after firstObject.
  while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
    [self addObject: eachObject];               // that isn't nil, add it to self's contents.
  va_end(argumentList);
  }
}
</code>```

OwnerDisplayName: anon

ContentLicense: CC BY-SA 2.5

Body:
I noticed this in Joe Hewitt's source for Three20 and I've never seen this particular syntax in Objective-C before. Not even sure how to reference it in an appropriate Google search.

From TTTableViewDataSource:

+ (TTSectionedDataSource*)dataSourceWithObjects:(id)object,... {

The "..." is what's throwing me off here. I'm assuming it's a form of enumeration where a variable amount of arguments may be supplied. If it is, what's the official name for this operator and where can I reference the documentation for it?

Thank you kindly.

Body:
It's a variadic method, meaning it takes a variable number of arguments.  This page has a good demonstration of how to use it:

#import <Cocoa/Cocoa.h>

@interface NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...;  // This method takes a nil-terminated list of objects.

@end

@implementation NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...
{
id eachObject;
va_list argumentList;
if (firstObject)                      // The first argument isn't part of the varargs list,
  {                                   // so we'll handle it separately.
  [self addObject: firstObject];
  va_start(argumentList, firstObject);          // Start scanning for arguments after firstObject.
  while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
    [self addObject: eachObject];               // that isn't nil, add it to self's contents.
  va_end(argumentList);
  }
}

OwnerDisplayName: Pesto


问:
Disabling web.config inheritance for behaviorExtensions
I'm trying to add a web application in IIS under an existing (root level) website. The root level website's web.config file defines certain behaviorExtensions under system.serviceModel:

```<code>    <extensions>
        <behaviorExtensions>
            <add name="errorHandler" type="API.ErrorHandler.WCFErrorHandlerElement, API.ErrorHandler, Version=1.5.1.832, Culture=neutral, PublicKeyToken=null" />
        </behaviorExtensions>
    </extensions>
</code>```

The extension is used like this:

```<code>        <serviceBehaviors>
            <behavior name="DefaultRESTBasedHTTPSServiceBehavior">
                <errorHandler />
            </behavior>
        </serviceBehaviors>
</code>```

For certain reasons I'm not allowed to add a reference to the required assembly in the added website, so I want to disable the extension's inheritance by this way (in the added website's web.config of course):

```<code><behaviors>
  <serviceBehaviors>
    <clear/>
  </serviceBehaviors>
  <endpointBehaviors>
    <clear/>
  </endpointBehaviors>
</behaviors>
</code>```

I was also trying to prevent the inheritance of the extensions section like this: <extensions><clear/></extensions>. It seems though, that <clear/> is not supported for the extensions node.

Yet I get the following exception when a WCF error happens on the added website (the problem is at Line 191):

```<code>Parser Error Message: The type 'API.ErrorHandler.WCFErrorHandlerElement, API.ErrorHandler, Version=1.5.1.832, Culture=neutral, PublicKeyToken=null' registered for extension 'errorHandler' could not be loaded.

Line 189:           <serviceBehaviors>
Line 190:               <behavior name="DefaultRESTBasedHTTPSServiceBehavior">
Line 191:                   <errorHandler />
Line 192:               </behavior>
Line 193:               <behavior name="DefaultSOAPBasedHTTPSServiceBehavior">
</code>```

Please consider, that it is not possible to prohibit inheritance in the root level website's web.config, because other added websites are using the settings in question.

答:
If you are able to use the <location> element in the root web.config then you can chose which sections not to inherit using the inheritInChildApplications attribute:

For example:

```<code><location path="MyWebApp" inheritInChildApplications="false">
    <system.serviceModel>
    </system.serviceModel>
</location>
</code>```

Body:
I'm trying to add a web application in IIS under an existing (root level) website. The root level website's web.config file defines certain behaviorExtensions under system.serviceModel:

    <extensions>
        <behaviorExtensions>
            <add name="errorHandler" type="API.ErrorHandler.WCFErrorHandlerElement, API.ErrorHandler, Version=1.5.1.832, Culture=neutral, PublicKeyToken=null" />
        </behaviorExtensions>
    </extensions>

The extension is used like this:

        <serviceBehaviors>
            <behavior name="DefaultRESTBasedHTTPSServiceBehavior">
                <errorHandler />
            </behavior>
        </serviceBehaviors>

For certain reasons I'm not allowed to add a reference to the required assembly in the added website, so I want to disable the extension's inheritance by this way (in the added website's web.config of course):

<behaviors>
  <serviceBehaviors>
    <clear/>
  </serviceBehaviors>
  <endpointBehaviors>
    <clear/>
  </endpointBehaviors>
</behaviors>

I was also trying to prevent the inheritance of the extensions section like this: <extensions><clear/></extensions>. It seems though, that <clear/> is not supported for the extensions node.

Yet I get the following exception when a WCF error happens on the added website (the problem is at Line 191):

Parser Error Message: The type 'API.ErrorHandler.WCFErrorHandlerElement, API.ErrorHandler, Version=1.5.1.832, Culture=neutral, PublicKeyToken=null' registered for extension 'errorHandler' could not be loaded.

Line 189:           <serviceBehaviors>
Line 190:               <behavior name="DefaultRESTBasedHTTPSServiceBehavior">
Line 191:                   <errorHandler />
Line 192:               </behavior>
Line 193:               <behavior name="DefaultSOAPBasedHTTPSServiceBehavior">

Please consider, that it is not possible to prohibit inheritance in the root level website's web.config, because other added websites are using the settings in question.

Body:
If you are able to use the <location> element in the root web.config then you can chose which sections not to inherit using the inheritInChildApplications attribute:

For example:

<location path="MyWebApp" inheritInChildApplications="false">
    <system.serviceModel>
    </system.serviceModel>
</location>


问:
How do i animate the opacity of an element when scrolling is selected?
I'm at the very beginning of learning JS, right now what's bugging me is I want to animate the opacity of a div when scrolling is detected
I have 2 options from what i've found online:

```<code>window.addEventListener('scroll',function());
</code>```

or

```<code>window.onscroll()=function();
</code>```

Using the first variant, and the console, I see it is detecting the scrolling but here comes my trouble.

Let:

```<code>let loadingscreen=document.getElementsByTagName('div')[3];
loadingscreen.style.opacity="0";
</code>```

Why won't this work?

```<code>window.addEventListener('scroll',()=>{
console.log("!"); //detecting the scroll in the console
setInterval(function(){loadingscreen.style.opacity+=".1"},100);});`
</code>```

The opacity only changes once, i believe it is from 0 to 0.1

Is it that my opacity goes from 0 to 0.1 to 0.11 to 0.111? Tho i cant understand why that would be.
Thank you for taking your time to read this, any response is apreciated!!

I know the code doesn't look that tidy, i promise it is better in my vsc, im having a little trouble with stackoverflow

答:
const loadingscreen = document.getElementsByTagName('div')[2];

loadingscreen.style.opacity= 0;

let incOpa = 0

function callIncOpacity(){
      let refreshIntervalId = setInterval(function(){
        console.log(incOpa); //detecting the scroll in the console
        if(incOpa < 1) {
          incOpa += 0.1;
            loadingscreen.style.opacity = incOpa
        }
      }, 10);

    setTimeout(function(){
      clearInterval(refreshIntervalId);
    }, 100)
}

window.addEventListener('scroll',()=>{

    if(incOpa < 1) callIncOpacity()

}); ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content-container,
.second-div,
.third-div{
  height: 500px;
  width: 100%
}</code>```

<!DOCTYPE html>

<title>Title of the document</title>

Test content

test content 1

test content 2

```

Two things to be kept in mind.

Style property can't be incremented

When you call the setInterval at some point it's better to stop it once the job is done.

Body:
I'm at the very beginning of learning JS, right now what's bugging me is I want to animate the opacity of a div when scrolling is detected
I have 2 options from what i've found online:

window.addEventListener('scroll',function());

or

window.onscroll()=function();

Using the first variant, and the console, I see it is detecting the scrolling but here comes my trouble.

Let:

let loadingscreen=document.getElementsByTagName('div')[3];
loadingscreen.style.opacity="0";

Why won't this work?

window.addEventListener('scroll',()=>{
console.log("!"); //detecting the scroll in the console
setInterval(function(){loadingscreen.style.opacity+=".1"},100);});`

The opacity only changes once, i believe it is from 0 to 0.1

Is it that my opacity goes from 0 to 0.1 to 0.11 to 0.111? Tho i cant understand why that would be.
Thank you for taking your time to read this, any response is apreciated!!

I know the code doesn't look that tidy, i promise it is better in my vsc, im having a little trouble with stackoverflow

Body:
const loadingscreen = document.getElementsByTagName('div')[2];

loadingscreen.style.opacity= 0;

let incOpa = 0

function callIncOpacity(){
      let refreshIntervalId = setInterval(function(){
        console.log(incOpa); //detecting the scroll in the console
        if(incOpa < 1) {
          incOpa += 0.1;
            loadingscreen.style.opacity = incOpa
        }
      }, 10);

    setTimeout(function(){
      clearInterval(refreshIntervalId);
    }, 100)
}

window.addEventListener('scroll',()=>{

    if(incOpa < 1) callIncOpacity()

});

.content-container,
.second-div,
.third-div{
  height: 500px;
  width: 100%
}

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>

<div class="content-container">
<p>
Test content
</p>
</div>

<div class="second-div">
<p>
test content 1
</p>
</div>

<div class="third-div">
<p>
test content 2
</p>
</div>

</body>
</html>

Two things to be kept in mind.

Style property can't be incremented

When you call the setInterval at some point it's better to stop it once the job is done.


问:
jquery $.each() for objects
```<code><script>
    $(document).ready(function() {
        var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
        $.each(data.programs[0], function(key,val) {
            alert(key+val);
        });
    });
</script>
</code>```

This code retrieves the first data. name:zonealarm and price:500.

How can I retrieve all the data in the object?

I tried $.each(data.programs, function(key,val) but it didn't work.

Should I put it in a loop?

答:
```<code>var arType = [];
$.each($("input[name='archiveType[]']:checked"), function() {
   arType.push($(this).val());
});
arType = arType.join(",");
</code>```

Title: jquery $.each() for objects


问:
Lua: Connect with MSSQL DB
I'm learning about Lua (version 5.3),Is there a way to connect to an mssql database?
I try to do it as follows

```<code>print("Connection to the db:")
local dbuser = '....'
local dbpass = '...'
local dbsource = '....'
local dbname = 'xx.xx.xxx.xx'
database.open("Provider= ODBC ; Initial Catalog = dbname; Data Source = dbsource ; User ID = dbuser ; Password = dbpass ")
print("Database opened succesfully.")
print("Connection to the db:")
</code>```

But didn´t work, execution returns me:

```<code> attempt to index a nil value (global 'database')
</code>```

Thanks,

答:
I try to do it as follows

```<code>database.open("Provider= ODBC ; Initial Catalog = dbname; Data Source = dbsource ; User ID = dbuser ; Password = dbpass ")
</code>```

What made you think you can do that? You get that error because there is no global variable database unless you define one.
Hence you may not index it. Trial and error with random code is not a very good way to get things done in programming.

Also you cannot handle strings like that in Lua. You either need to use string.format or the concatenation operator .. to get your variables into that string.

There's also no printf in Lua unless you define it.

I suggest you learn the basics of Lua befor you get into interfacing databases.

From reading the Lua reference manual it should become obvious that Lua does not know anything about databases.

Either you run Lua embedded into some host application that provides database access through its Lua API or you need to load a library that supports that.

Searching the web for "lua sql" instantly yields

https://keplerproject.github.io/luasql/

and others.

Title: Lua: Connect with MSSQL DB

Body:
I'm learning about Lua (version 5.3),Is there a way to connect to an mssql database?
I try to do it as follows

print("Connection to the db:")
local dbuser = '....'
local dbpass = '...'
local dbsource = '....'
local dbname = 'xx.xx.xxx.xx'
database.open("Provider= ODBC ; Initial Catalog = dbname; Data Source = dbsource ; User ID = dbuser ; Password = dbpass ")
print("Database opened succesfully.")
print("Connection to the db:")

But didn´t work, execution returns me:

 attempt to index a nil value (global 'database')

Thanks,

Body:
I try to do it as follows

database.open("Provider= ODBC ; Initial Catalog = dbname; Data Source = dbsource ; User ID = dbuser ; Password = dbpass ")

What made you think you can do that? You get that error because there is no global variable database unless you define one.
Hence you may not index it. Trial and error with random code is not a very good way to get things done in programming.

Also you cannot handle strings like that in Lua. You either need to use string.format or the concatenation operator .. to get your variables into that string.

There's also no printf in Lua unless you define it.

I suggest you learn the basics of Lua befor you get into interfacing databases.

From reading the Lua reference manual it should become obvious that Lua does not know anything about databases.

Either you run Lua embedded into some host application that provides database access through its Lua API or you need to load a library that supports that.

Searching the web for "lua sql" instantly yields

https://keplerproject.github.io/luasql/

and others.


问:
How can i use HTextView scale textview effect (com.hanks.htextview.HTextView) as multiline effect?
At the moment it works with single line and when I input a text with more than one line, the application crashes.

MainActivity:

```<code>    HTextView tvQuestion_hanks = (HTextView) findViewById(R.id.tvQs_hanks);
    tvQuestion_hanks.setAnimateType(HTextViewType.SCALE);
    tvQuestion_hanks.animateText("Hello world");
</code>```

Layout:

```<code>    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:htext="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

         <com.hanks.htextview.HTextView

                android:id="@+id/tvQs_hanks"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginTop="16dp"
                android:textColor="#000000"
                android:textSize="17dp"
                android:text="Question"
                htext:animateType="scale"
                android:gravity="start">

         </com.hanks.htextview.HTextView>

     </RelativeLayout>
</code>```

I've tried different layout codes like;

```<code>     android:lines="5"
     android:maxLines="5"
     android:nestedScrollingEnabled="true"
</code>```

but it didn't work . This is my logcat just after i press the button and a multiline text is sent to HTextView (as I said the app crashes) :

```<code>            02-13 20:01:18.074 4456-4456/com.example.moham.myapplication D/AndroidRuntime:
            Shutting down VM
            02-13 20:01:18.074 4456-4456/com.example.moham.myapplication W/dalvikvm:
            threadid=1: thread exiting with uncaught exception (group=0x94caeb20)
            02-13 20:01:18.074 4456-4456/com.example.moham.myapplication E/AndroidRuntime:
            FATAL EXCEPTION: main
                                                                           Process: com.example.moham.myapplication, PID:
           4456
                                                                           java.lang.ArrayIndexOutOfBoundsException:
           length=100; index=100
                                                                               at
           com.hanks.htextview.animatetext.HText.prepareAnimate(HText.java:88)
                                                                               at
           com.hanks.htextview.animatetext.HText.animateText(HText.java:74)
                                                                               at
           com.hanks.htextview.HTextView.animateText(HTextView.java:107)
                                                                               at
           com.example.moham.myapplication.MainActivity$1.onClick(MainActivity.java:34)
                                                                               at
           android.view.View.performClick(View.java:4438)
                                                                               at
           android.view.View$PerformClick.run(View.java:18422)
                                                                               at
           android.os.Handler.handleCallback(Handler.java:733)
                                                                               at
           android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:136)
                                                                               at
           android.app.ActivityThread.main(ActivityThread.java:5019)
                                                                               at java.lang.reflect.Method.invokeNative(Native
           Method)
                                                                               at
           java.lang.reflect.Method.invoke(Method.java:515)
                                                                               at
           com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                                               at
           com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                                               at dalvik.system.NativeStart.main(Native
           Method)
</code>```

HTextView GitHub page: https://github.com/hanks-zyh/HTextView

HTextView GitHub page2: https://github.com/yikwing/HTextView

答:
Try this method... It will surely work for you as it's working perfectly for me with multiline text as well...

Thanks me later :)

Animations are a great way to bring life into our app. Animating views are easy, but How to animate text. For animating text (not TextView) we are going to use HTextView a free library available on GitHub.

For this demo app, we have six HTextView and we are animating different texts in all the HTextView. For using HTextView we are going to add HTextView dependencies in-app Gradle file.

build.gradle (Module:App)

```<code>def htextview_version = "0.1.2"
compile "com.hanks:htextview-base:$htextview_version"        // base library
compile "com.hanks:htextview-fall:$htextview_version"        // optional
compile "com.hanks:htextview-fade:$htextview_version"        // optional
compile "com.hanks:htextview-line:$htextview_version"        // optional
compile "com.hanks:htextview-rainbow:$htextview_version"     // optional
compile "com.hanks:htextview-typer:$htextview_version"       // optional
compile "com.hanks:htextview-scale:$htextview_version"       // optional
compile "com.hanks:htextview-evaporate:$htextview_version"   // optional
</code>```

Sync, your project.

Following are the code for activity_main.xml file.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.hanks.htextview.fall.FallTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textView"
        android:textSize="20sp"
        android:gravity="center"
         />

    <com.hanks.htextview.line.LineTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textViewLine"
        app:animationDuration="1000"
        android:textSize="20sp"
        app:lineColor="#1367bc"
        app:lineWidth="4dp"
        android:gravity="center"
        />

    <com.hanks.htextview.fade.FadeTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textViewFade"
        app:animationDuration="1000"
        android:textSize="20sp"
        android:gravity="center"
        />

    <com.hanks.htextview.typer.TyperTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textViewTyper"
        app:charIncrease="3"
        app:typerSpeed="80"
        android:textSize="20sp"
        android:gravity="center"
        />

    <com.hanks.htextview.rainbow.RainbowTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textViewRainBow"
        android:textSize="20sp"
        app:colorSpace="150dp"
        app:colorSpeed="4dp"
        android:gravity="center"
        />

    <com.hanks.htextview.scale.ScaleTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textViewScale"
        android:textSize="20sp"
        android:gravity="center"
        />

</LinearLayout>
</code>```

In our MainActivity.java file, we are first initializing all the HTextView. We have a String Array for different messages. We are changing all HTextView text with time using String Array. Following is the code for MainActivity.java file...

```<code>package com.vlemonn.java.blog.htextview;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.hanks.htextview.base.HTextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private HTextView textView,textViewScale,textViewRainBow,textViewTyper,textViewFade,textViewLine;
    int delay = 2000; //milliseconds
    Handler handler;
    ArrayList<String> arrMessages = new ArrayList<>();
    int position=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /* Some Sample Messages for Animation */
        arrMessages.add("Hello, vLemonn!");
        arrMessages.add("Hello, World!");
        arrMessages.add("Free Android Tutorials");
        arrMessages.add("By Mayank Sanghvi");
        arrMessages.add("@vLemonn");
        arrMessages.add("Subscribe, Share, Like");
        arrMessages.add("Support Us");

        /* Initialize HTextView */
        textView = findViewById(R.id.textView);
        textViewScale= findViewById(R.id.textViewScale);
        textViewRainBow= findViewById(R.id.textViewRainBow);
        textViewTyper= findViewById(R.id.textViewTyper);
        textViewFade= findViewById(R.id.textViewFade);
        textViewLine= findViewById(R.id.textViewLine);

        /* First Message */
        textView.animateText(arrMessages.get(position));
        textViewScale.animateText(arrMessages.get(position));
        textViewRainBow.animateText(arrMessages.get(position));
        textViewTyper.animateText(arrMessages.get(position));
        textViewFade.animateText(arrMessages.get(position));
        textViewLine.animateText(arrMessages.get(position));
        position++;

        /* Change Messages every 2 Seconds */
        handler = new Handler();
        handler.postDelayed(new Runnable(){
            public void run(){

                handler.postDelayed(this, delay);
                if(position>=arrMessages.size())
                    position=0;
                textView.animateText(arrMessages.get(position));
                textViewScale.animateText(arrMessages.get(position));
                textViewRainBow.animateText(arrMessages.get(position));
                textViewTyper.animateText(arrMessages.get(position));
                textViewFade.animateText(arrMessages.get(position));
                textViewLine.animateText(arrMessages.get(position));
                position++;
            }
        }, delay);

    }
}
</code>```

Final Demo (Output):
Final Demo (Output)

If you find this answer useful then please Accept it so that everyone can use this easily...

Body:
At the moment it works with single line and when I input a text with more than one line, the application crashes.

MainActivity:

    HTextView tvQuestion_hanks = (HTextView) findViewById(R.id.tvQs_hanks);
    tvQuestion_hanks.setAnimateType(HTextViewType.SCALE);
    tvQuestion_hanks.animateText("Hello world");

Layout:

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:htext="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

         <com.hanks.htextview.HTextView

                android:id="@+id/tvQs_hanks"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginTop="16dp"
                android:textColor="#000000"
                android:textSize="17dp"
                android:text="Question"
                htext:animateType="scale"
                android:gravity="start">

         </com.hanks.htextview.HTextView>

     </RelativeLayout>

I've tried different layout codes like;

     android:lines="5"
     android:maxLines="5"
     android:nestedScrollingEnabled="true"

but it didn't work . This is my logcat just after i press the button and a multiline text is sent to HTextView (as I said the app crashes) :

            02-13 20:01:18.074 4456-4456/com.example.moham.myapplication D/AndroidRuntime:
            Shutting down VM
            02-13 20:01:18.074 4456-4456/com.example.moham.myapplication W/dalvikvm:
            threadid=1: thread exiting with uncaught exception (group=0x94caeb20)
            02-13 20:01:18.074 4456-4456/com.example.moham.myapplication E/AndroidRuntime:
            FATAL EXCEPTION: main
                                                                           Process: com.example.moham.myapplication, PID:
           4456
                                                                           java.lang.ArrayIndexOutOfBoundsException:
           length=100; index=100
                                                                               at
           com.hanks.htextview.animatetext.HText.prepareAnimate(HText.java:88)
                                                                               at
           com.hanks.htextview.animatetext.HText.animateText(HText.java:74)
                                                                               at
           com.hanks.htextview.HTextView.animateText(HTextView.java:107)
                                                                               at
           com.example.moham.myapplication.MainActivity$1.onClick(MainActivity.java:34)
                                                                               at
           android.view.View.performClick(View.java:4438)
                                                                               at
           android.view.View$PerformClick.run(View.java:18422)
                                                                               at
           android.os.Handler.handleCallback(Handler.java:733)
                                                                               at
           android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:136)
                                                                               at
           android.app.ActivityThread.main(ActivityThread.java:5019)
                                                                               at java.lang.reflect.Method.invokeNative(Native
           Method)
                                                                               at
           java.lang.reflect.Method.invoke(Method.java:515)
                                                                               at
           com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                                               at
           com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                                               at dalvik.system.NativeStart.main(Native
           Method)

HTextView GitHub page: https://github.com/hanks-zyh/HTextView

HTextView GitHub page2: https://github.com/yikwing/HTextView

Body:
Try this method... It will surely work for you as it's working perfectly for me with multiline text as well...

Thanks me later :)

Animations are a great way to bring life into our app. Animating views are easy, but How to animate text. For animating text (not TextView) we are going to use HTextView a free library available on GitHub.

For this demo app, we have six HTextView and we are animating different texts in all the HTextView. For using HTextView we are going to add HTextView dependencies in-app Gradle file.

build.gradle (Module:App)

def htextview_version = "0.1.2"
compile "com.hanks:htextview-base:$htextview_version"        // base library
compile "com.hanks:htextview-fall:$htextview_version"        // optional
compile "com.hanks:htextview-fade:$htextview_version"        // optional
compile "com.hanks:htextview-line:$htextview_version"        // optional
compile "com.hanks:htextview-rainbow:$htextview_version"     // optional
compile "com.hanks:htextview-typer:$htextview_version"       // optional
compile "com.hanks:htextview-scale:$htextview_version"       // optional
compile "com.hanks:htextview-evaporate:$htextview_version"   // optional

Sync, your project.

Following are the code for activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.hanks.htextview.fall.FallTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textView"
        android:textSize="20sp"
        android:gravity="center"
         />

    <com.hanks.htextview.line.LineTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textViewLine"
        app:animationDuration="1000"
        android:textSize="20sp"
        app:lineColor="#1367bc"
        app:lineWidth="4dp"
        android:gravity="center"
        />

    <com.hanks.htextview.fade.FadeTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textViewFade"
        app:animationDuration="1000"
        android:textSize="20sp"
        android:gravity="center"
        />

    <com.hanks.htextview.typer.TyperTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textViewTyper"
        app:charIncrease="3"
        app:typerSpeed="80"
        android:textSize="20sp"
        android:gravity="center"
        />

    <com.hanks.htextview.rainbow.RainbowTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textViewRainBow"
        android:textSize="20sp"
        app:colorSpace="150dp"
        app:colorSpeed="4dp"
        android:gravity="center"
        />

    <com.hanks.htextview.scale.ScaleTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text=""
        android:id="@+id/textViewScale"
        android:textSize="20sp"
        android:gravity="center"
        />

</LinearLayout>

In our MainActivity.java file, we are first initializing all the HTextView. We have a String Array for different messages. We are changing all HTextView text with time using String Array. Following is the code for MainActivity.java file...

package com.vlemonn.java.blog.htextview;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.hanks.htextview.base.HTextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private HTextView textView,textViewScale,textViewRainBow,textViewTyper,textViewFade,textViewLine;
    int delay = 2000; //milliseconds
    Handler handler;
    ArrayList<String> arrMessages = new ArrayList<>();
    int position=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /* Some Sample Messages for Animation */
        arrMessages.add("Hello, vLemonn!");
        arrMessages.add("Hello, World!");
        arrMessages.add("Free Android Tutorials");
        arrMessages.add("By Mayank Sanghvi");
        arrMessages.add("@vLemonn");
        arrMessages.add("Subscribe, Share, Like");
        arrMessages.add("Support Us");

        /* Initialize HTextView */
        textView = findViewById(R.id.textView);
        textViewScale= findViewById(R.id.textViewScale);
        textViewRainBow= findViewById(R.id.textViewRainBow);
        textViewTyper= findViewById(R.id.textViewTyper);
        textViewFade= findViewById(R.id.textViewFade);
        textViewLine= findViewById(R.id.textViewLine);

        /* First Message */
        textView.animateText(arrMessages.get(position));
        textViewScale.animateText(arrMessages.get(position));
        textViewRainBow.animateText(arrMessages.get(position));
        textViewTyper.animateText(arrMessages.get(position));
        textViewFade.animateText(arrMessages.get(position));
        textViewLine.animateText(arrMessages.get(position));
        position++;

        /* Change Messages every 2 Seconds */
        handler = new Handler();
        handler.postDelayed(new Runnable(){
            public void run(){

                handler.postDelayed(this, delay);
                if(position>=arrMessages.size())
                    position=0;
                textView.animateText(arrMessages.get(position));
                textViewScale.animateText(arrMessages.get(position));
                textViewRainBow.animateText(arrMessages.get(position));
                textViewTyper.animateText(arrMessages.get(position));
                textViewFade.animateText(arrMessages.get(position));
                textViewLine.animateText(arrMessages.get(position));
                position++;
            }
        }, delay);

    }
}

Final Demo (Output):
Final Demo (Output)

If you find this answer useful then please Accept it so that everyone can use this easily...


问:
React native Animated stop is not working
I am trying to use React Native Animated to do simple animation with View width and Height.
Following the official syntax from here React Animated. But the stop functionality is not working.

Here is my code snippet:

```<code>import React, { useRef } from "react";
import { Animated, View, StyleSheet, Button } from "react-native";

const App = () => {
 const sizeAnimBase = new Animated.Value(100);
 const sizeAnim = useRef(sizeAnimBase).current;

 const startAnimation = () => {
  Animated.timing(sizeAnim, {
      toValue: 500,
      duration: 100,
      useNativeDriver: false
    }).start(() => {

    });
 }

 const stopAnimation = () => {
  // Tried both ways but didn't work
  Animated.timing(sizeAnimBase).stop();
  Animated.timing(sizeAnim).stop();
 }

return (
 <View>
   <Animated.View
        style={
            width: sizeAnim,
           height: sizeAnim
          }
      >
        <Text>Animated view</Text>
      </Animated.View>
    <Button title="Start Animation" onPress={startAnimation} />
        <Button title="Stop Animation" onPress={stopAnimation} />
 </View>
)
}
</code>```

答:
This worked for me normally</p>
```<code>const App = () => {
 const sizeAnim = useRef(new Animated.Value(100)).current;

  const startAnimation = () => {
    Animated.timing(sizeAnim, {
      toValue: 500,
      duration: 2000,
      useNativeDriver: false,
    }).start();
  };

  const stopAnimation = () => {
    Animated.timing(sizeAnim, {
      duration: 0,
      toValue: 0,
      useNativeDriver: true,
    }).stop();
  };

  return (
    <View>
      <Animated.View style={{width: sizeAnim, height: sizeAnim}}>
        <Text>Animated view</Text>
      </Animated.View>
      <Button title="Start Animation" onPress={startAnimation} />
      <Button title="Stop Animation" onPress={stopAnimation} />
    </View>
  );
}
</code>```

Body:
I am trying to use React Native Animated to do simple animation with View width and Height.
Following the official syntax from here React Animated. But the stop functionality is not working.

Here is my code snippet:

import React, { useRef } from "react";
import { Animated, View, StyleSheet, Button } from "react-native";

const App = () => {
 const sizeAnimBase = new Animated.Value(100);
 const sizeAnim = useRef(sizeAnimBase).current;

 const startAnimation = () => {
  Animated.timing(sizeAnim, {
      toValue: 500,
      duration: 100,
      useNativeDriver: false
    }).start(() => {

    });
 }

 const stopAnimation = () => {
  // Tried both ways but didn't work
  Animated.timing(sizeAnimBase).stop();
  Animated.timing(sizeAnim).stop();
 }

return (
 <View>
   <Animated.View
        style={
            width: sizeAnim,
           height: sizeAnim
          }
      >
        <Text>Animated view</Text>
      </Animated.View>
    <Button title="Start Animation" onPress={startAnimation} />
        <Button title="Stop Animation" onPress={stopAnimation} />
 </View>
)
}

Body:
This worked for me normally

const App = () => {
 const sizeAnim = useRef(new Animated.Value(100)).current;

  const startAnimation = () => {
    Animated.timing(sizeAnim, {
      toValue: 500,
      duration: 2000,
      useNativeDriver: false,
    }).start();
  };

  const stopAnimation = () => {
    Animated.timing(sizeAnim, {
      duration: 0,
      toValue: 0,
      useNativeDriver: true,
    }).stop();
  };

  return (
    <View>
      <Animated.View style={{width: sizeAnim, height: sizeAnim}}>
        <Text>Animated view</Text>
      </Animated.View>
      <Button title="Start Animation" onPress={startAnimation} />
      <Button title="Stop Animation" onPress={stopAnimation} />
    </View>
  );
}


问:
Getting "ViCommand: no such keymap" errors while using Term::Readline:Zoid
I have a simple bit of code that works well until I export

```<code>PERL_RL='Zoid default_mode=ViCommand'
</code>```

in order to use vi mode while editing.  When I test the code I'm getting the error: ViCommand: no such keymap.  I installed libterm-readline-zoid-perl and from what I can tell ViCommand is built in so I should be good to go but apparently not.

```<code>#!/usr/bin/env perl
use warnings;
use strict;
use Term::ReadLine;

my $term = new Term::ReadLine 'LineEdit';

while ( defined ($_ = $term->readline($ARGV[0],$ARGV[1])) ) {
    print $_;
    exit;
}
</code>```

答:
Seems like there is no command named ViCommand. However, by inspecting the source, see line 80:

```<code>command => { _use => 'Term::ReadLine::Zoid::ViCommand'  },
</code>```

you should be able to use "ViCommand" line editing by setting the environment variable PERL_RL like this:

```<code>PERL_RL='Zoid default_mode=command'
</code>```

Body:
I have a simple bit of code that works well until I export

PERL_RL='Zoid default_mode=ViCommand'

in order to use vi mode while editing.  When I test the code I'm getting the error: ViCommand: no such keymap.  I installed libterm-readline-zoid-perl and from what I can tell ViCommand is built in so I should be good to go but apparently not.

#!/usr/bin/env perl
use warnings;
use strict;
use Term::ReadLine;

my $term = new Term::ReadLine 'LineEdit';

while ( defined ($_ = $term->readline($ARGV[0],$ARGV[1])) ) {
    print $_;
    exit;
}

Body:
Seems like there is no command named ViCommand. However, by inspecting the source, see line 80:

command => { _use => 'Term::ReadLine::Zoid::ViCommand'  },

you should be able to use "ViCommand" line editing by setting the environment variable PERL_RL like this:

PERL_RL='Zoid default_mode=command'


问:
Authentication of rails backend server for users' authenticated with iPhone app via Facebook using FBConnect
I am developing iPhone app that let user login using their facebook account using FBConnect SDK. The app talks to rails backend server for data retrieval. Because I do not want to make users create account, I want to let users log in to the rails backend server using their facebook account. Is using access key and secret of FBConnect as user name and password on rails server right way to do this?</p>

答: You should use the user's Facebook id to uniquely identify them (i.e., as their username). Then have the app send that and their Facebook token to authenticate them. You can authenticate that the token is actually valid by passing it to Facebook and asking it to verify the token.</p>


问:
How to uninstall mongodb on arch linux?
I have install mongodb but isnt working, so i wan to remove it, but i dont know how to doit.enter image description here</p>

答:
Enter this command to uninstall mongodb-bin from Arch</p>
```<code>sudo pacman -R mongodb-bin
</code>```

Title: How to uninstall mongodb on arch linux?

Body:
Enter this command to uninstall mongodb-bin from Arch

sudo pacman -R mongodb-bin


问:
Coding with c: warning: incompatible implicit declaration of built-in function ‘exp10’
//SOLVED HERE: https://askubuntu.com/questions/962252/coding-with-c-warning-incompatible-implicit-declaration-of-built-in-function

I don't understand how to compile this.

I've didnt put all of the functions that i've made in this library because all of them work properly, and it's the first time that i have to use math.h

Until now i've compiled like this without issues:

```<code>gcc -c -g f.c

gcc -c -g main.c

gcc -o main main.o f.o
</code>```

I've tried to insert -lm but i don't get how and where it has to be putted.

//header

```<code>#include<math.h>
#define MAX 5

typedef enum {FALSE, TRUE} bool;

typedef enum {ERROR=-1, OK=1} status;

status parse_int(char s[], int *val);
</code>```

//function

```<code>#include<stdio.h>
#include<math.h>
#include <stdlib.h>
#include"f.h"

status parse_int(char s[], int *val) {

    int l, val_convertito = 0, val_momentaneo = 0;
    for(l = 0; s[l] != '\0'; l++);
    for(int i = 0; s[i] != '\0'; i++) {
        if(s[i] >= '0' && s[i] <= '9') {
            val_momentaneo = ((int) (s[i]-48)) * ((int)exp10((double)l--));
            val_convertito += val_momentaneo;
            *val = val_convertito;
        } else return ERROR;
    }

    return OK;
}
</code>```

//main

```<code>#include<stdio.h>
#include<math.h>
#include <stdlib.h>
#include"f.h"

int main() {

    int val_con, *val, ls;
    char s_int[ls];

    printf("Inserisci la lunghezza della stringa: ");
    scanf("%d", &ls);

    printf("\n");
    printf("Inserisci l'intero da convertire: \n");
    scanf("%s", s_int);

    val = &val_con;

    status F8 = parse_int(s_int, val);

    switch(F8) {
        case OK:  printf("Valore convertito %d\n", val_con);
                  break;
        case ERROR: printf("E' presente un carattere non numerico.\n");
                    break;
    }

}
</code>```

答: pow(10.0, x) does what exp10(x) does.

Body:
//SOLVED HERE: https://askubuntu.com/questions/962252/coding-with-c-warning-incompatible-implicit-declaration-of-built-in-function

I don't understand how to compile this.

I've didnt put all of the functions that i've made in this library because all of them work properly, and it's the first time that i have to use math.h

Until now i've compiled like this without issues:

gcc -c -g f.c

gcc -c -g main.c

gcc -o main main.o f.o

I've tried to insert -lm but i don't get how and where it has to be putted.

//header

#include<math.h>
#define MAX 5

typedef enum {FALSE, TRUE} bool;

typedef enum {ERROR=-1, OK=1} status;

status parse_int(char s[], int *val);

//function

#include<stdio.h>
#include<math.h>
#include <stdlib.h>
#include"f.h"

status parse_int(char s[], int *val) {

    int l, val_convertito = 0, val_momentaneo = 0;
    for(l = 0; s[l] != '\0'; l++);
    for(int i = 0; s[i] != '\0'; i++) {
        if(s[i] >= '0' && s[i] <= '9') {
            val_momentaneo = ((int) (s[i]-48)) * ((int)exp10((double)l--));
            val_convertito += val_momentaneo;
            *val = val_convertito;
        } else return ERROR;
    }

    return OK;
}

//main

#include<stdio.h>
#include<math.h>
#include <stdlib.h>
#include"f.h"

int main() {

    int val_con, *val, ls;
    char s_int[ls];

    printf("Inserisci la lunghezza della stringa: ");
    scanf("%d", &ls);

    printf("\n");
    printf("Inserisci l'intero da convertire: \n");
    scanf("%s", s_int);

    val = &val_con;

    status F8 = parse_int(s_int, val);

    switch(F8) {
        case OK:  printf("Valore convertito %d\n", val_con);
                  break;
        case ERROR: printf("E' presente un carattere non numerico.\n");
                    break;
    }

}

Body: pow(10.0, x) does what exp10(x) does.


问:
How can I count the number of items in inventory available on any given day?
I have a table that contains records for items that are available. Each of the records contains a field for the date it was added to the inventory, the date it was removed from inventory (otherwise NULL) and a unique serial number (separate from the primary key). There are also other fields giving metadata about the item, like brand, model, height, weight, etc.

Using that table I want to come up with a new table that tells me item availability for every day, from the first item availability date until present, for all items. , ie I want to convert the item availability data from a sparse to dense representation.

I know this involves doing a join to a table of dates, but I don’t know how to do that, or even how to describe more formally what I am trying to do. My mental model for this would be to create an X rows by Y columns, with each row a given serial number and column for date, but I don’t know how to do this in sql and I think it will make unmanageable large tables. I think a better way would be to have a long narrow table, with one column for date and another for serial number and a third indicating it’s presence or absence. But I don’t know if this is feasible at all.

Currently I am trying to accomplish this in MySQL, but I can do it either in Postgres or MS Sql/SQL Server if needed.

Thanks

答:
When I understand correctly this DBFIDDLE does do what you want:

```<code>WITH RECURSIVE dates AS(
    SELECT
      min(dateadded) AS d,
      0 as x
    FROM items

    UNION ALL
    SELECT DATE_ADD(d,INTERVAL 1 DAY),x+1
    FROM dates
    WHERE d<=(SELECT MAX(dateadded) FROM items)
)
SELECT
   d,
   serialnumber
FROM dates
LEFT JOIN items ON d BETWEEN items.dateadded
                         AND COALESCE(items.dateremoved,'2099-12-31')
ORDER BY 1,2
</code>```

The dates part is created containing all available dates, from the first dateadded to the last dateadded+1.

The query will only select all available serialnumbers per date.

It should not be hard to change this to add also a column available to show if the serialnumber is available, or not, but this is left as an exercise to the reader .

Body:
When I understand correctly this DBFIDDLE does do what you want:

WITH RECURSIVE dates AS(
    SELECT
      min(dateadded) AS d,
      0 as x
    FROM items

    UNION ALL
    SELECT DATE_ADD(d,INTERVAL 1 DAY),x+1
    FROM dates
    WHERE d<=(SELECT MAX(dateadded) FROM items)
)
SELECT
   d,
   serialnumber
FROM dates
LEFT JOIN items ON d BETWEEN items.dateadded
                         AND COALESCE(items.dateremoved,'2099-12-31')
ORDER BY 1,2

The dates part is created containing all available dates, from the first dateadded to the last dateadded+1.

The query will only select all available serialnumbers per date.

It should not be hard to change this to add also a column available to show if the serialnumber is available, or not, but this is left as an exercise to the reader .


问:
React State update a nested array with objects based on the id when iterated
I have an react state with objects/array that is filled, but also then later I want to edit text inputs and edit the related fields on object also, i found no solutions until now.

So this is my state for example:

```<code>const [data, setData] = useState({
    working_hours: [
      {
        id: 1,
        description: 'Random Text',
        price: 100,

      },
      {
        id: 2,
        description: 'Text Random',
        price: 100,
      },
    ]
  });
</code>```

Here is my Jsx:

```<code>{data.working_hours.map(item =>
<>
  <input type={text} value={item.description}
   onChange={(e) => handleChange(e)} />

  <input type={text} value={item.price}
   onChange={(e) => handleChange(e)} />
</>
)}
</code>```

Here is what I tried:

```<code>function handleChange(e){
 const value = e.target.value;
 setData({...data, [...data.working_hours, e.target.value]})
}
</code>```

答:
You need to pass additional parameters to your handleChange as item ID which you want to update and property name because without these you will not be able to identify which property to update dynamically. This way you can use the same handleChange for multiple inputs.

See below code -

```<code>function handleChange(e, itemId, property) {
    const value = e.target.value;
    //copying data to temp variable so that we do not directly mutate original state
    const tempWorkingHours = [...data.working_hours];
    //findIndex to find location of item we need to update
    let index = tempWorkingHours.findIndex(item => item.id == itemId);
    // -1 check to see if we found that object in working hours
    if(index != -1){
       tempWorkingHours[index] = {
         ...tempWorkingHours[index], //keeping existing values in object
         [property]: value  //here property can be "price" or "description"
       }
    }

    setData({ ...data, working_hours: tempWorkingHours })
}

{
    data.working_hours.map(item =>
        <>
            <input type={text} value={item.description}
                onChange={(e) => handleChange(e, item.id, "description")} />

            <input type={text} value={item.price}
                onChange={(e) => handleChange(e, item.id, "price")} />
        </>
    )
}
</code>```

Body:
I have an react state with objects/array that is filled, but also then later I want to edit text inputs and edit the related fields on object also, i found no solutions until now.

So this is my state for example:

const [data, setData] = useState({
    working_hours: [
      {
        id: 1,
        description: 'Random Text',
        price: 100,

      },
      {
        id: 2,
        description: 'Text Random',
        price: 100,
      },
    ]
  });

Here is my Jsx:

{data.working_hours.map(item =>
<>
  <input type={text} value={item.description}
   onChange={(e) => handleChange(e)} />

  <input type={text} value={item.price}
   onChange={(e) => handleChange(e)} />
</>
)}

Here is what I tried:

function handleChange(e){
 const value = e.target.value;
 setData({...data, [...data.working_hours, e.target.value]})
}

Body:
You need to pass additional parameters to your handleChange as item ID which you want to update and property name because without these you will not be able to identify which property to update dynamically. This way you can use the same handleChange for multiple inputs.

See below code -

function handleChange(e, itemId, property) {
    const value = e.target.value;
    //copying data to temp variable so that we do not directly mutate original state
    const tempWorkingHours = [...data.working_hours];
    //findIndex to find location of item we need to update
    let index = tempWorkingHours.findIndex(item => item.id == itemId);
    // -1 check to see if we found that object in working hours
    if(index != -1){
       tempWorkingHours[index] = {
         ...tempWorkingHours[index], //keeping existing values in object
         [property]: value  //here property can be "price" or "description"
       }
    }

    setData({ ...data, working_hours: tempWorkingHours })
}

{
    data.working_hours.map(item =>
        <>
            <input type={text} value={item.description}
                onChange={(e) => handleChange(e, item.id, "description")} />

            <input type={text} value={item.price}
                onChange={(e) => handleChange(e, item.id, "price")} />
        </>
    )
}


问:
How to update loop?
I have string like this

```<code>txt = 'hi how are you user alex12 ?'
</code>```

and I need to make some changes like this

```<code> col1          |  col2
 --------------|------------
'hi'           |  'H1'
'are you'      |  'B1'
'user alex12'  |  'A1 B2 C1'
</code>```

I want this result

```<code>txt = 'H1 how B1 A1 B2 C1 ?'
</code>```

and this is the hard part, the col1 is a list of 1,000 item's, I made this code but it's not work well

```<code>check_list = ['hi', 'are you', ...]
temp = txt.split()
for i in range(len(temp)):
    if temp in check_list:
        temp[i] = check_list[check_list.index(temp[i])
</code>```

答:
If you have:

```<code>txt = 'hi how are you user alex12 ?'

check_list = ["hi", "are you", "user alex12"]
replace_to = ["H1","B1","A1 B2 C1"]
</code>```

You can do:

```<code>for c, r in zip(check_list,replace_to):
    txt = txt.replace(c,r)
</code>```

txt will be:

```<code>H1 how B1 A1 B2 C1 ?
</code>```

Title: How to update loop?

Body:
I have string like this

txt = 'hi how are you user alex12 ?'

and I need to make some changes like this

 col1          |  col2
 --------------|------------
'hi'           |  'H1'
'are you'      |  'B1'
'user alex12'  |  'A1 B2 C1'

I want this result

txt = 'H1 how B1 A1 B2 C1 ?'

and this is the hard part, the col1 is a list of 1,000 item's, I made this code but it's not work well

check_list = ['hi', 'are you', ...]
temp = txt.split()
for i in range(len(temp)):
    if temp in check_list:
        temp[i] = check_list[check_list.index(temp[i])

Body:
If you have:

txt = 'hi how are you user alex12 ?'

check_list = ["hi", "are you", "user alex12"]
replace_to = ["H1","B1","A1 B2 C1"]

You can do:

for c, r in zip(check_list,replace_to):
    txt = txt.replace(c,r)

txt will be:

H1 how B1 A1 B2 C1 ?


答: If you split like you did you will never get your second row, you need to go about it the other way, go over the first column and search it in your text.</p>

Title: How to update loop?