问:
Launch Screen with gif image in android flutter
This is NOT about creating a "Splash Screen" which is loaded after app loads.

I am trying to make animated gifs work in android's launch screen (Section "Define a launch theme")

When I add a non animated image, launch_background.jpg it appears fine. But when I add a gif image with animation (launch_background.gif), it appears as static image.

I followed these steps but when I run the flutter app, I get this error:

```<code>Launching lib\main.dart on SM J610F in debug mode...
Initializing gradle...

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  Output:  E:\flutterProjects\app_name\app_name\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:179: error: :pl.droidsonroids.gif.GifTextView>.

  Command: C:\Users\r\.gradle\caches\transforms-1\files-1.1\aapt2-3.2.1-4818971-windows.jar\15cdf2a9fa9e4ee473d47c95fa8e0c69\aapt2-3.2.1-4818971-windows\aapt2.exe compile --legacy \
          -o \
          E:\flutterProjects\app_name\app_name\build\app\intermediates\res\merged\debug \
          E:\flutterProjects\app_name\app_name\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
  Daemon:  AAPT2 aapt2-3.2.1-4818971-windows Daemon #1
  Output:  C:\Users\r\.gradle\caches\transforms-1\files-1.1\core-1.0.0.aar\e2765643361afa85f13c55b475d0d315\res\values\values.xml:167:5-117: AAPT: error: :pl.droidsonroids.gif.GifTextView>.

  Command: C:\Users\r\.gradle\caches\transforms-1\files-1.1\aapt2-3.2.1-4818971-windows.jar\15cdf2a9fa9e4ee473d47c95fa8e0c69\aapt2-3.2.1-4818971-windows\aapt2.exe compile --legacy \
          -o \
          E:\flutterProjects\app_name\app_name\build\app\intermediates\res\merged\debug \
          E:\flutterProjects\app_name\app\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
  Daemon:  AAPT2 aapt2-3.2.1-4818971-windows Daemon #1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 16s
*******************************************************************************************
The Gradle failure may have been because of AndroidX incompatibilities in this Flutter app.
See https://goo. gl/CP92wY for more information on the problem and how to fix it.
*******************************************************************************************
Resolving dependencies...
Running Gradle task 'assembleDebug'...
Finished with error: Gradle task assembleDebug failed with exit code 1

  [1]: https://flutter.dev/docs/development/add-to-app/android/add-splash-screen
  [2]: https://stackoverflow.com/a/39871506/1291122
</code>```

My app/src/main/res/values/styles.xml looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
        <!-- Show a splash screen on the activity. Automatically removed when
             Flutter draws its first frame -->
<!--        <item name="android:windowBackground">@drawable/launch_background</item>-->
        <pl.droidsonroids.gif.GifTextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@mipmap/launcher_image"
            />
    </style>
</resources>
</code>```

And I have a launcher_image.gif in res/mipmap-hdpi folder.

I would be happy if I could make this android plugin work, or if I could figure out a way to make animated gif work in the "Launch Screen". Google is full of tutorials about "Splash Screen" gif animations. But very few address the issue of doing it in a "Launch Screen" on android.

答:
In your case you need to put a full screen gif image as a splash screen for your application. First I will share you some of the things I found while trying to do this in my application. Flutter is providing us with default splash screen for both android and IOS. The reason for this is is any flutter application to run it need some time for the device to load the dart and set up device for running flutter application .if you didn't do anything in android and ios native code to customize this the application will show a black screen instead of splash screen. To avoid that and add a splash screen with logo you can just customize you launch_background.xml file in android

(C:\Users\XYZ\Desktop\project\nameapp\android\app\src\main\res\drawable\launch_background.xml)

Check the code

```<code><?xml version="1.0" encoding="utf-8"?>
 <!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:drawable="@android:color/white" />
 <!-- You can insert your own image assets here -->
  <item>
   <bitmap
    android:gravity="center"
    android:src="@mipmap/logo" />
   </item>
   </layer-list>
</code>```

after this you can customize you main.dart file to show your gif file.

Check the code

```<code>  import 'dart:async'; import 'package:app/ui/login_screen.dart';
  import 'package:flutter/material.dart';

   void main() { runApp(new MaterialApp( home: new MyApp(), )); }

   class MyApp extends StatefulWidget {

   @override _MyAppState createState() => new _MyAppState();
   }

   class _MyAppState extends State {
    @override void initState() {
    super.initState();
    new Future.delayed( const Duration(seconds: 4), () =>
    Navigator.pushReplacement( context,
    MaterialPageRoute(builder: (context) => LoginScreen()),
       ));
     }

    @override
     Widget build(BuildContext context) {
     return new Scaffold(
      backgroundColor: Colors.white,
       body: Container(
       height: double.infinity,
       width: double.infinity,
      child: Image.asset("assets/yourgif.gif",
      gaplessPlayback: true,
      fit: BoxFit.fill
      )
      ));
      }
      }
</code>```

After this run your application with release build. then you can see your application shows a white screen with app logo for first time for just a second and start showing your gif animation which is to be your splash screen and after that it will go to your applications first screen.

Please try this to show your desired gif file as yopur splash screen.

Body:
This is NOT about creating a "Splash Screen" which is loaded after app loads.

I am trying to make animated gifs work in android's launch screen (Section "Define a launch theme")

When I add a non animated image, launch_background.jpg it appears fine. But when I add a gif image with animation (launch_background.gif), it appears as static image.

I followed these steps but when I run the flutter app, I get this error:

Launching lib\main.dart on SM J610F in debug mode...
Initializing gradle...

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  Output:  E:\flutterProjects\app_name\app_name\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:179: error: :pl.droidsonroids.gif.GifTextView>.

  Command: C:\Users\r\.gradle\caches\transforms-1\files-1.1\aapt2-3.2.1-4818971-windows.jar\15cdf2a9fa9e4ee473d47c95fa8e0c69\aapt2-3.2.1-4818971-windows\aapt2.exe compile --legacy \
          -o \
          E:\flutterProjects\app_name\app_name\build\app\intermediates\res\merged\debug \
          E:\flutterProjects\app_name\app_name\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
  Daemon:  AAPT2 aapt2-3.2.1-4818971-windows Daemon #1
  Output:  C:\Users\r\.gradle\caches\transforms-1\files-1.1\core-1.0.0.aar\e2765643361afa85f13c55b475d0d315\res\values\values.xml:167:5-117: AAPT: error: :pl.droidsonroids.gif.GifTextView>.

  Command: C:\Users\r\.gradle\caches\transforms-1\files-1.1\aapt2-3.2.1-4818971-windows.jar\15cdf2a9fa9e4ee473d47c95fa8e0c69\aapt2-3.2.1-4818971-windows\aapt2.exe compile --legacy \
          -o \
          E:\flutterProjects\app_name\app_name\build\app\intermediates\res\merged\debug \
          E:\flutterProjects\app_name\app\build\app\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
  Daemon:  AAPT2 aapt2-3.2.1-4818971-windows Daemon #1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 16s
*******************************************************************************************
The Gradle failure may have been because of AndroidX incompatibilities in this Flutter app.
See https://goo. gl/CP92wY for more information on the problem and how to fix it.
*******************************************************************************************
Resolving dependencies...
Running Gradle task 'assembleDebug'...
Finished with error: Gradle task assembleDebug failed with exit code 1

  [1]: https://flutter.dev/docs/development/add-to-app/android/add-splash-screen
  [2]: https://stackoverflow.com/a/39871506/1291122

My app/src/main/res/values/styles.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

</resources>

And I have a launcher_image.gif in res/mipmap-hdpi folder.

I would be happy if I could make this android plugin work, or if I could figure out a way to make animated gif work in the "Launch Screen". Google is full of tutorials about "Splash Screen" gif animations. But very few address the issue of doing it in a "Launch Screen" on android.

Body:
In your case you need to put a full screen gif image as a splash screen for your application. First I will share you some of the things I found while trying to do this in my application. Flutter is providing us with default splash screen for both android and IOS. The reason for this is is any flutter application to run it need some time for the device to load the dart and set up device for running flutter application .if you didn't do anything in android and ios native code to customize this the application will show a black screen instead of splash screen. To avoid that and add a splash screen with logo you can just customize you launch_background.xml file in android

(C:\Users\XYZ\Desktop\project\nameapp\android\app\src\main\res\drawable\launch_background.xml)

Check the code

<?xml version="1.0" encoding="utf-8"?>
 <!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:drawable="@android:color/white" />
 <!-- You can insert your own image assets here -->
  <item>
   <bitmap
    android:gravity="center"
    android:src="@mipmap/logo" />
   </item>
   </layer-list>

after this you can customize you main.dart file to show your gif file.

Check the code

  import 'dart:async'; import 'package:app/ui/login_screen.dart';
  import 'package:flutter/material.dart';

   void main() { runApp(new MaterialApp( home: new MyApp(), )); }

   class MyApp extends StatefulWidget {

   @override _MyAppState createState() => new _MyAppState();
   }

   class _MyAppState extends State {
    @override void initState() {
    super.initState();
    new Future.delayed( const Duration(seconds: 4), () =>
    Navigator.pushReplacement( context,
    MaterialPageRoute(builder: (context) => LoginScreen()),
       ));
     }

    @override
     Widget build(BuildContext context) {
     return new Scaffold(
      backgroundColor: Colors.white,
       body: Container(
       height: double.infinity,
       width: double.infinity,
      child: Image.asset("assets/yourgif.gif",
      gaplessPlayback: true,
      fit: BoxFit.fill
      )
      ));
      }
      }

After this run your application with release build. then you can see your application shows a white screen with app logo for first time for just a second and start showing your gif animation which is to be your splash screen and after that it will go to your applications first screen.

Please try this to show your desired gif file as yopur splash screen.


来源: stackexchange

问:
Adding pie chart in excel sheet using Apache POI library?

Possible Duplicate:

  Create excel chart using Apache POI

Is it possible to add different charts in an Excel sheet using Apache POI library?

答:
Not currently. There is talk of support for XSSF on the dev list, from a contributor, but there's nothing yet. If you're willing to monkey with lots of XML, then you can largely get something done with XSSF for now, but it's hard. You'd need to search the dev list for details.

The recommended solution is to create a template file with the charts you want in them. The charts should be defined using named ranges for all the data in them. Now, open this in POI (either HSSF or XSSF), and put in all your data. Finally, update the named range to point to the data you've added. When you open excel, it'll show your chart with the new data.

ContentLicense: CC BY-SA 3.0


问:
ASP.net Core API error by implementing JWT in the configuration
I recently added to my code the JWT method for authenticating users, after implementing all the configuration I am facing Exception at the CreateHostBuilder(args).Build().Run() in the program file.
The error I am facing:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Dmail.Core.Application.Login.LoginBL Lifetime: Transient ImplementationType: Dmail.Core.Application.Login.LoginBL': Unable to activate type 'Dmail.Core.Application.Login.LoginBL'. The following constructors are ambiguous:
  Void .ctor(Microsoft.Extensions.Configuration.IConfiguration)
  Void .ctor(Dmail.Core.Contracts.IUserRepository))'

This is my configuration for login authentication:

```<code>            services.AddCors(options => {
            options.AddPolicy("CorsPolicy", builder =>
            builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials().Build());
        });

        services.AddControllers();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Jwt:Issuer"],
                ValidAudience = Configuration["Jwt: Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
            };
        });

        services.AddMvc(option => option.EnableEndpointRouting = false).AddMvcOptions(o =>
        {
            o.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
        });

        services.AddTransient<IUserRepository, UserRepository>();
        services.AddTransient<LoginBL, LoginBL>();
        services.AddTransient<GetUserBL, GetUserBL>();
        services.AddTransient<UserPresenter, UserPresenter>();
</code>```

The class LoginBL:

```<code>public class LoginBL
{
    private readonly IUserRepository _userRepo;
    private readonly IConfiguration _config;

    public LoginBL(IConfiguration config)
    {
        _config = config;
    }
    public LoginBL(IUserRepository userRepo)
    {
        _userRepo = userRepo;
    }

    public async Task<LoginResponse> HandleAuthentication(LoginRequest input)
    {
        var auth = await _userRepo.Authenticate(input.Email, input.Password);

        if (auth == null)
        {
            return null;
        }
        else
        {
            var tokenStr = GenerateJSONWebToken(auth);

            var output = new LoginResponse()
            {
                Id = auth.Id,
                Username = auth.Username,
                FirstName = auth.FirstName,
                LastName = auth.LastName,
                Token = tokenStr,
                ListOfEmails = auth.ListOfEmails
            };

            return output;
        }
    }

    private string GenerateJSONWebToken(User userinfo)
    {
        var securityKey = new
   SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var credentials = new SigningCredentials(securityKey,
     SecurityAlgorithms.HmacSha256);

        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, userinfo.FirstName),
            new Claim(JwtRegisteredClaimNames.Email, userinfo.Username),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var token = new JwtSecurityToken(
            issuer: _config["Jwt:Issuer"],
            audience: _config["Jwt:Issuer"],
            claims,
            expires: DateTime.Now.AddMinutes(120),
            signingCredentials: credentials);

        var encodetoken = new JwtSecurityTokenHandler().WriteToken(token);
        return encodetoken;

    }
}
</code>```

If you need me to show you more files let me know, since I have quite a lot of files in my project

答:
You have two different constructors, so the container doesn't know which one to instantiate:

```<code>public LoginBL(IConfiguration config)
{
    _config = config;
}
public LoginBL(IUserRepository userRepo)
{
    _userRepo = userRepo;
}
</code>```

Presumably you want a single constructor that takes both:

```<code>public LoginBL(IConfiguration config, IUserRepository userRepo)
{
    _config = config;
    _userRepo = userRepo;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I recently added to my code the JWT method for authenticating users, after implementing all the configuration I am facing Exception at the CreateHostBuilder(args).Build().Run() in the program file.
The error I am facing:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Dmail.Core.Application.Login.LoginBL Lifetime: Transient ImplementationType: Dmail.Core.Application.Login.LoginBL': Unable to activate type 'Dmail.Core.Application.Login.LoginBL'. The following constructors are ambiguous:
  Void .ctor(Microsoft.Extensions.Configuration.IConfiguration)
  Void .ctor(Dmail.Core.Contracts.IUserRepository))'

This is my configuration for login authentication:

            services.AddCors(options => {
            options.AddPolicy("CorsPolicy", builder =>
            builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials().Build());
        });

        services.AddControllers();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Jwt:Issuer"],
                ValidAudience = Configuration["Jwt: Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
            };
        });

        services.AddMvc(option => option.EnableEndpointRouting = false).AddMvcOptions(o =>
        {
            o.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
        });

        services.AddTransient<IUserRepository, UserRepository>();
        services.AddTransient<LoginBL, LoginBL>();
        services.AddTransient<GetUserBL, GetUserBL>();
        services.AddTransient<UserPresenter, UserPresenter>();

The class LoginBL:

public class LoginBL
{
    private readonly IUserRepository _userRepo;
    private readonly IConfiguration _config;

    public LoginBL(IConfiguration config)
    {
        _config = config;
    }
    public LoginBL(IUserRepository userRepo)
    {
        _userRepo = userRepo;
    }

    public async Task<LoginResponse> HandleAuthentication(LoginRequest input)
    {
        var auth = await _userRepo.Authenticate(input.Email, input.Password);

        if (auth == null)
        {
            return null;
        }
        else
        {
            var tokenStr = GenerateJSONWebToken(auth);

            var output = new LoginResponse()
            {
                Id = auth.Id,
                Username = auth.Username,
                FirstName = auth.FirstName,
                LastName = auth.LastName,
                Token = tokenStr,
                ListOfEmails = auth.ListOfEmails
            };

            return output;
        }
    }

    private string GenerateJSONWebToken(User userinfo)
    {
        var securityKey = new
   SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
        var credentials = new SigningCredentials(securityKey,
     SecurityAlgorithms.HmacSha256);

        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, userinfo.FirstName),
            new Claim(JwtRegisteredClaimNames.Email, userinfo.Username),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
        };

        var token = new JwtSecurityToken(
            issuer: _config["Jwt:Issuer"],
            audience: _config["Jwt:Issuer"],
            claims,
            expires: DateTime.Now.AddMinutes(120),
            signingCredentials: credentials);

        var encodetoken = new JwtSecurityTokenHandler().WriteToken(token);
        return encodetoken;

    }
}

If you need me to show you more files let me know, since I have quite a lot of files in my project

Body:
You have two different constructors, so the container doesn't know which one to instantiate:

public LoginBL(IConfiguration config)
{
    _config = config;
}
public LoginBL(IUserRepository userRepo)
{
    _userRepo = userRepo;
}

Presumably you want a single constructor that takes both:

public LoginBL(IConfiguration config, IUserRepository userRepo)
{
    _config = config;
    _userRepo = userRepo;
}


问:
How to change width and box when using aria?
I using a library for datalist/autocomplate. But I want to change the width and shape of the data container. How do I remove arrow in red box and make the width is dynamic according to content? No css used.
Link for the library(awesomplete)

  <input id="sellerId" name="sellerId" autocomplete="off" aria-   expanded="false" aria-owns="awesomplete_list_1">

anusha - harsha

SRIKAN874 - anush

```

答:
to remove the arrow just add this css

```<code>.awesomplete > ul:before {
    display: none !important;
}
</code>```

Working Sample

.awesomplete > ul:before {
    display: none !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://leaverou.github.io/awesomplete/awesomplete.css" />
<script src="https://cdn.jsdelivr.net/npm/awesomplete@1.1.5/awesomplete.min.js"></script>

<input class="awesomplete" data-list="#mylist" />
<ul id="mylist" style="display:none;">
  <li>Ada</li>
  <li>Java</li>
  <li>JavaScript</li>
  <li>Brainfuck</li>
  <li>LOLCODE</li>
  <li>Node.js</li>
  <li>Ruby on Rails</li>
</ul></code>```

Screenshot

Body:
to remove the arrow just add this css

.awesomplete > ul:before {
    display: none !important;
}

Working Sample

.awesomplete > ul:before {
    display: none !important;
}

<link rel="stylesheet" type="text/css" href="https://leaverou.github.io/awesomplete/awesomplete.css" />
<script src="https://cdn.jsdelivr.net/npm/awesomplete@1.1.5/awesomplete.min.js"></script>

<input class="awesomplete" data-list="#mylist" />
<ul id="mylist" style="display:none;">
  <li>Ada</li>
  <li>Java</li>
  <li>JavaScript</li>
  <li>Brainfuck</li>
  <li>LOLCODE</li>
  <li>Node.js</li>
  <li>Ruby on Rails</li>
</ul>

Screenshot


Title: Replace each element of multidimensional array with tuple of respective indices

Body:
In numpy, let's say I have an array k that has shape (2, 3, 2, 2).

k = np.array([[[[-0.08759809, -0.10987781],
                [-0.18387192, -0.2109216 ]],

               [[ 0.21027089,  0.21661097],
                [ 0.22847626,  0.23004637]],

               [[ 0.50813986,  0.54309974],
                [ 0.64082444,  0.67101435]]],

              [[[-0.98053589, -1.03143541],
                [-1.19128892, -1.24695841]],

               [[ 0.69108355,  0.66880383],
                [ 0.59480972,  0.56776003]],

               [[ 2.36270298,  2.36904306],
                [ 2.38090835,  2.38247847]]]])

How would I create a new array j of shape (2, 3, 2, 2) such that each element of j is the index of the corresponding value in k?

Example in the first element of the first dimension and first element of the second dimension. (Corresponding to

[[[[-0.08759809, -0.10987781],
   [-0.18387192, -0.2109216 ]],

)

[[[[(0, 0, 0, 0), (0, 0, 0, 1)],
   [(0, 0, 1, 0), (0, 0, 1, 1)]],

.... and so on.

Body:
The idea is to use np.ndindex as follows:

j = np.fromiter(np.ndindex(k.shape), dtype='i4,'*k.ndim).reshape(k.shape)

Result:

array([[[[(0, 0, 0, 0), (0, 0, 0, 1)],
          [(0, 0, 1, 0), (0, 0, 1, 1)]],

        [[(0, 1, 0, 0), (0, 1, 0, 1)],
          [(0, 1, 1, 0), (0, 1, 1, 1)]],

        [[(0, 2, 0, 0), (0, 2, 0, 1)],
          [(0, 2, 1, 0), (0, 2, 1, 1)]]],

        [[[(1, 0, 0, 0), (1, 0, 0, 1)],
          [(1, 0, 1, 0), (1, 0, 1, 1)]],

        [[(1, 1, 0, 0), (1, 1, 0, 1)],
          [(1, 1, 1, 0), (1, 1, 1, 1)]],

        [[(1, 2, 0, 0), (1, 2, 0, 1)],
          [(1, 2, 1, 0), (1, 2, 1, 1)]]]],
      dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<i4')])


问:
How do I insert a new TR into the MIDDLE of a HTML table using JQuery?
I know how to append a new row to a table using JQuery:

```<code>var newRow = $("<tr>..."</tr>");
$("#mytable tbody").append(newRow);
</code>```

The question is how do I create a new row that precedes some existing row.

答:
```<code>where_you_want_it.before(newRow)
</code>```

or

```<code>newRow.insertBefore(where_you_want_it)
</code>```

-- MarkusQ

OwnerDisplayName: Decker

ContentLicense: CC BY-SA 2.5

Body:
I know how to append a new row to a table using JQuery:

var newRow = $("
..."
");
$("#mytable tbody").append(newRow);

The question is how do I create a new row that precedes some existing row.

Body:
where_you_want_it.before(newRow)

or

newRow.insertBefore(where_you_want_it)

-- MarkusQ

OwnerDisplayName: MarkusQ


问:
Detect Android phone via Javascript / jQuery
How would i detect that the device in use is an Android for a mobile website?

I need to apply certain css attributes to the Android platform.

Thanks

答:
Take a look at that : http://davidwalsh.name/detect-android

JavaScript:

```<code>var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
  // Do something!
  // Redirect to Android-site?
  window.location = 'http://android.davidwalsh.name';
}
</code>```

PHP:

```<code>$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
  header('Location: http://android.davidwalsh.name');
  exit();
}
</code>```

Edit : As pointed out in some comments, this will work in 99% of the cases, but some edge cases are not covered. If you need a much more advanced and bulletproofed solution in JS, you should use platform.js : https://github.com/bestiejs/platform.js

Body:
Take a look at that : http://davidwalsh.name/detect-android

JavaScript:

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
  // Do something!
  // Redirect to Android-site?
  window.location = 'http://android.davidwalsh.name';
}

PHP:

$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
  header('Location: http://android.davidwalsh.name');
  exit();
}

Edit : As pointed out in some comments, this will work in 99% of the cases, but some edge cases are not covered. If you need a much more advanced and bulletproofed solution in JS, you should use platform.js : https://github.com/bestiejs/platform.js


Body:
A simple solution would be to iterate over j and explicitly fill each element with its index j[idx, :] = idx:

k = np.round(np.random.random((4, 5)), 2)
j = np.empty(k.shape+(k.ndim,))
for idx in np.ndindex(k.shape):
    j[idx, :] = idx

# array([[[0., 0.],
#         [0., 1.],
#         [0., 2.],
#         [0., 3.],
#         [0., 4.]],
#        [[1., 0.],
#         [1., 1.],
#         [1., 2.],
#         [1., 3.],
#         [1., 4.]],
#        [[2., 0.],
#         [2., 1.],
#         [2., 2.],
#         [2., 3.],
#         [2., 4.]],
#        [[3., 0.],
#         [3., 1.],
#         [3., 2.],
#         [3., 3.],
#         [3., 4.]]])


问:
How to modify parent public member variable from child member function?
programming beginner here. I've been trying to figure this out myself for a while,
Can anyone tell me why this prints 5 and not 8? As far as I know this should work I've tried pass by reference and using pointers but as I'm still a bit of a noob perhaps I haven't quite got it yet so if anyone could help me out and point me in the right direction id appreciate it.
Cheers.</p>

```<code>#include <iostream>
using namespace std;

class classA {
  public:
    int a = 5;

    void print(){
      cout << a << endl;
    }
};

 class classB : public classA {
   public:
     int one;
     void modify (){
       cin >> one;
       if (one == 1){
         a =+ 3;
       }
     }
 };

int main()
{

    cout << "Hi, push '1'" << endl;
    classA printobj;
    classB modifyobj;
    modifyobj.modify();
    printobj.print();

    return 0;
}
</code>```

答:
printobj and modifyobj are two totally unrelated objects, each with a unique and unrelated and distinct member variable a.

To make your example work you need one object of type classB:

```<code>classB obj;
obj.print();
obj.modify();
obj.print();
</code>```

Body:
programming beginner here. I've been trying to figure this out myself for a while,
Can anyone tell me why this prints 5 and not 8? As far as I know this should work I've tried pass by reference and using pointers but as I'm still a bit of a noob perhaps I haven't quite got it yet so if anyone could help me out and point me in the right direction id appreciate it.
Cheers.

#include <iostream>
using namespace std;

class classA {
  public:
    int a = 5;

    void print(){
      cout << a << endl;
    }
};

 class classB : public classA {
   public:
     int one;
     void modify (){
       cin >> one;
       if (one == 1){
         a =+ 3;
       }
     }
 };

int main()
{

    cout << "Hi, push '1'" << endl;
    classA printobj;
    classB modifyobj;
    modifyobj.modify();
    printobj.print();

    return 0;
}

Body:
printobj and modifyobj are two totally unrelated objects, each with a unique and unrelated and distinct member variable a.

To make your example work you need one object of type classB:

classB obj;
obj.print();
obj.modify();
obj.print();


答: You modify modifyobj but then print printobj. The two objects have no relationship to each other at all, so changing one won't affect the other.

Title: How to modify parent public member variable from child member function?


问:
Can't find adb, but I've really looked hard
I know this question has been asked many times - I've read them all and followed most of the suggestions.

I have a new computer, windows 10, so a clean install of AS 3.5.3 . All fine, except trying to get adb to work. I get 'Unable to locate ADB' when after finding no devices I try to restart ADB.

There's also a series of error messages in the event log:

18:16   Adb connection Error:An existing connection was forcibly closed by the remote host

18:16   Unable to open connection to: localhost/127.0.0.1:5037, due to: java.net.ConnectException: Connection refused: connect

18:16   Connection attempts: 1

18:16   * daemon not running; starting now at tcp:5037

18:16   * daemon started successfully

adb.exe is visible in the right place in platform-tools. But I've tried deleting and reinstalling platform-tools. Reinstalling AS, and not using old setup configurations. I've run AS as an administrator, checked file properties in platform-tools, rebooted the computer, I don't have antivirus except windows defender, and I've run that over the platform-tools folder and it didn't object to that... so I've run out of ideas! The setup looks just the same as in my old computer, and everything works on my old computer (but slowly!).

Any other suggestions? Are those error messages significant.

Thanks.

答:
I should have said I was trying to connect adb using wifi. I installed and android wifi adb plugin (File, Settings, Plugins) and now it's working.

I have 2 other machines with AS on them, and adb over wifi works fine and I never had to do this before.

Edit: I have been asked not to use this post as an answer. It's true, my experience doesn't offer a useful solution to anyone (can't be sure that installing the adb plugin actually helped) but adb is working now, so I don't need anyone bothering themselves trying to figure out a problem that no longer exists. In that sense, it's an answer.


问:
creating an array basedon dataframe values
If i have an id that has a start date = 1988 and end date as = 2018 and value = 21100 and i want to create a array or dataframe of the dates from 1988 - 2018 i.e (1988,1989,1990...2018) with each date = to the same value of 21100
So i basically want something that looks like:

```<code>date, id1, id2
1988, 21100,0
1989, 21100,0
1990,21000 ,0
...
1994,21100,4598
...
2013,21100,4598
...
2018,21100,0
</code>```

how could i do this? I want the array to start populating the value based on the start date and to end populating based on the end date. i have multiple id's (268) and i want them to loop through each adding a new column (id2, id3 ... id268). So for example id2 starts at 1994 to 2013 with a value of 4598.

Body:
If i have an id that has a start date = 1988 and end date as = 2018 and value = 21100 and i want to create a array or dataframe of the dates from 1988 - 2018 i.e (1988,1989,1990...2018) with each date = to the same value of 21100
So i basically want something that looks like:

date, id1, id2
1988, 21100,0
1989, 21100,0
1990,21000 ,0
...
1994,21100,4598
...
2013,21100,4598
...
2018,21100,0

how could i do this? I want the array to start populating the value based on the start date and to end populating based on the end date. i have multiple id's (268) and i want them to loop through each adding a new column (id2, id3 ... id268). So for example id2 starts at 1994 to 2013 with a value of 4598.

Body:
EDIT:

example = pd.DataFrame({
'id': ['id1', 'id2', 'id3', 'id4'],
'start date': ['1988', '1988', '2000', '2005'],
'end date': ['2018', '2013', '2005', '2017'],
'value': [2100, 4568, 7896, 68909]
})
print (example)
    id start date end date  value
0  id1       1988     2018   2100
1  id2       1988     2013   4568
2  id3       2000     2005   7896
3  id4       2005     2017  68909

You can create Series in list comprehension and join them together by concat, replace missing values, convert to integers and last convert index to column Date :

L = [pd.Series(v, index=range(int(s), int(e)+1)) for s,e,v in
     zip(example['start date'], example['end date'], example['value'])]
df1 = (pd.concat(L, axis=1, keys=example['id'])
         .fillna(0)
         .astype(int)
         .rename_axis('date')
         .reset_index())

print (df1)
id  date   id1   id2   id3    id4
0   1988  2100  4568     0      0
1   1989  2100  4568     0      0
2   1990  2100  4568     0      0
3   1991  2100  4568     0      0
4   1992  2100  4568     0      0
5   1993  2100  4568     0      0
6   1994  2100  4568     0      0
7   1995  2100  4568     0      0
8   1996  2100  4568     0      0
9   1997  2100  4568     0      0
10  1998  2100  4568     0      0
11  1999  2100  4568     0      0
12  2000  2100  4568  7896      0
13  2001  2100  4568  7896      0
14  2002  2100  4568  7896      0
15  2003  2100  4568  7896      0
16  2004  2100  4568  7896      0
17  2005  2100  4568  7896  68909
18  2006  2100  4568     0  68909
19  2007  2100  4568     0  68909
20  2008  2100  4568     0  68909
21  2009  2100  4568     0  68909
22  2010  2100  4568     0  68909
23  2011  2100  4568     0  68909
24  2012  2100  4568     0  68909
25  2013  2100  4568     0  68909
26  2014  2100     0     0  68909
27  2015  2100     0     0  68909
28  2016  2100     0     0  68909
29  2017  2100     0     0  68909
30  2018  2100     0     0      0

Use DataFrame constructor with range:

start = 1988
end = 2019
val = 21100
df = pd.DataFrame({'date':range(start, end),
                   'id1': val})

print (df)
    date    id1
0   1988  21100
1   1989  21100
2   1990  21100
3   1991  21100
4   1992  21100
5   1993  21100
6   1994  21100
7   1995  21100
8   1996  21100
9   1997  21100
10  1998  21100
11  1999  21100
12  2000  21100
13  2001  21100
14  2002  21100
15  2003  21100
16  2004  21100
17  2005  21100
18  2006  21100
19  2007  21100
20  2008  21100
21  2009  21100
22  2010  21100
23  2011  21100
24  2012  21100
25  2013  21100
26  2014  21100
27  2015  21100
28  2016  21100
29  2017  21100
30  2018  21100


问:
Setting download directory in webdriver using JS
I want to change default download directory for chrome using JS (TypeScript). Tryed to set options like this :

let options = webdriver.ChromeOptions;

options.add_argument("download.default_directory=C:/Downloads")

let driver = webdriver.chrome(options);

But, options sets to undefined and ChromeOptions doesn't exist on webdriver.

Here is full code:

```<code>let webdriver = require('selenium-webdriver');
let chrome = require('selenium-webdriver/chrome');
let chromedriver = require('chromedriver');

chrome.setDefaultService(new chrome.ServiceBuilder(chromedriver.path).build());

// let driver = new webdriver.Builder()
//     .withCapabilities(webdriver.Capabilities.chrome())
//     .build();
let options = webdriver.ChromeOptions;

options.add_argument("download.default_directory=C:/Downloads")

let driver = webdriver.chrome(options);

let figma = 'https://www.figma.com/';
driver.get (figma).then(
    backup
);

function backup() {
    driver.sleep(3000);
    driver.quit();
}
</code>```

答:
According to this issue, chromeOptions key doesn't work as intended. Use goog:chromeOptions to set options for chrome capabilities:

const chromeCapabilities = webdriver.Capabilities.chrome();

chromeCapabilities.set('goog:chromeOptions', {
    'args': ['disable-infobars'],
    'prefs': {
      'download': {
        'default_directory': '/home/{user}/Downloads/Chrome_test',
        'prompt_for_download': 'false'
      }
    }
});

const driver = new webdriver.Builder()
  .withCapabilities(chromeCapabilities)
  .build();
```

Body:
I want to change default download directory for chrome using JS (TypeScript). Tryed to set options like this :

let options = webdriver.ChromeOptions;

options.add_argument("download.default_directory=C:/Downloads")

let driver = webdriver.chrome(options);

But, options sets to undefined and ChromeOptions doesn't exist on webdriver.

Here is full code:

let webdriver = require('selenium-webdriver');
let chrome = require('selenium-webdriver/chrome');
let chromedriver = require('chromedriver');

chrome.setDefaultService(new chrome.ServiceBuilder(chromedriver.path).build());

// let driver = new webdriver.Builder()
//     .withCapabilities(webdriver.Capabilities.chrome())
//     .build();
let options = webdriver.ChromeOptions;

options.add_argument("download.default_directory=C:/Downloads")

let driver = webdriver.chrome(options);

let figma = 'https://www.figma.com/';
driver.get (figma).then(
    backup
);

function backup() {
    driver.sleep(3000);
    driver.quit();
}


问:
Setting local config in SQL before INSERT
newbie in SQL coming from a JS world needing some advice on triggers.

My user has an id column and my GraphQL API always calls INSERT INTO .... RETURNING * and then doing the transforms on the GraphQL layer to return what I want.

The goal is to allow a query like INSERT INTO .... RETURNING * work with RLS in place.

The policies are:

CREATE POLICY USER_SELECT_RESTRICTIONS
ON "user"
FOR SELECT
USING ("id" = current_user_id() OR current_user_role() = 'admin' OR current_user_role() = 'partner');

CREATE POLICY USER_INSERT_RESTRICTIONS
ON "user"
FOR INSERT
WITH CHECK (true);
```

<p>This breaks for guest users (more context at the bottom) because they are allowed to <code>INSERT</code> but cannot <code>SELECT</code> (because of the restriction that only authorized users can select their own rows).</p>

<p>So I had the idea to somehow set the user setting manually in a trigger before/after insert (don't know which because I couldn't move forward due to the syntax error).</p>

<p>I've tried this but I get a syntax error at the <code>NEW.id</code>? (it just says "Syntax Error" to me)</p>

<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION after_user_insert()
RETURNS TRIGGER AS $$
BEGIN
  SET LOCAL jwt.claims.userId NEW.id;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER set_user_id_on_insert
AFTER INSERT ON "user"
FOR EACH ROW
EXECUTE PROCEDURE after_user_insert();
</code>```

Searched around a lot and to be honest I think I may just not find anything because I am missing the correct terminology to find what I need to find.

Would appreciate not only help on what on this specific problem but also any related advice on policies for guest users that need priviliges.

Context:

These are the relevant tables and functions

CREATE TYPE "user_role" AS ENUM (
  'customer',
  'partner',
  'admin'
);

CREATE TABLE "user" (
  "id" uuid UNIQUE PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),
  "first_name" varchar NOT NULL,
  "last_name" varchar NOT NULL,
  "email" text UNIQUE NOT NULL,
  "role" user_role NOT NULL DEFAULT 'customer',
  "created_at" timestamp NOT NULL DEFAULT NOW(),
  "updated_at" timestamp NOT NULL DEFAULT NOW()
);

CREATE FUNCTION current_user_id() RETURNS uuid AS $$
  SELECT nullif(current_setting('jwt.claims.userId', true), '')::uuid;
$$ LANGUAGE SQL stable;

CREATE FUNCTION current_user_role() RETURNS user_role AS $$
  SELECT nullif(current_setting('jwt.claims.role', true), '')::user_role;
$$ LANGUAGE SQL stable
```

<p>The RLS restricts <code>SELECT</code> to rows where the <code>id</code> column of the <code>user</code> table matches <code>current_setting('jwt.claims.userId')</code>.<br>
This was set previously by Postgraphile as seen here (https://www.graphile.org/postgraphile/security/).</p>

<p>One possible workaround I thought of would be this but I don't know if this would lead to some kind of vulnerabilities because of the obvious role elevation:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION after_user_insert()
RETURNS TRIGGER AS $$
BEGIN
  SET LOCAL jwt.claims.role TO "customer";
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION before_user_insert()
RETURNS TRIGGER AS $$
BEGIN
  SET LOCAL jwt.claims.role TO "admin";
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER before_insert
BEFORE INSERT ON "user"
FOR EACH ROW
EXECUTE PROCEDURE before_user_insert();

CREATE TRIGGER after_insert
AFTER INSERT ON "user"
FOR EACH ROW
EXECUTE PROCEDURE after_user_insert();
</code>```

答:
Your don't say what a guest is, but your approach seems wrong.

Rather than disabling your checks on a low level, which gives you a bad feeling for good reasons, you should choose one of the following approaches:

fix your policies to allow the necessary operation (perhaps by adding a permissive policy)

have certain operations performed by a SECURITY DEFINER function that belongs to a user not subject to the restrictions.

If you insist on a trigger based solution, you have to use a BEFORE trigger. Also, consider that you cannot use parameterss with a SET statement. You'd either have to use dynamic SQL or (better) use a function:

```<code>CREATE OR REPLACE FUNCTION before_user_insert() RETURNS TRIGGER AS
$$BEGIN
   SELECT set_config('jwt.claims.userId', NEW.id::text, TRUE);
   RETURN NEW;
END;$$ LANGUAGE plpgsql;

CREATE TRIGGER set_user_id_on_insert BEFORE INSERT ON "user"
FOR EACH ROW EXECUTE PROCEDURE before_user_insert();
</code>```

Body:
newbie in SQL coming from a JS world needing some advice on triggers.

My user has an id column and my GraphQL API always calls INSERT INTO .... RETURNING * and then doing the transforms on the GraphQL layer to return what I want.

The goal is to allow a query like INSERT INTO .... RETURNING * work with RLS in place.

The policies are:

CREATE POLICY USER_SELECT_RESTRICTIONS
ON "user"
FOR SELECT
USING ("id" = current_user_id() OR current_user_role() = 'admin' OR current_user_role() = 'partner');

CREATE POLICY USER_INSERT_RESTRICTIONS
ON "user"
FOR INSERT
WITH CHECK (true);

This breaks for guest users (more context at the bottom) because they are allowed to INSERT but cannot SELECT (because of the restriction that only authorized users can select their own rows).

So I had the idea to somehow set the user setting manually in a trigger before/after insert (don't know which because I couldn't move forward due to the syntax error).

I've tried this but I get a syntax error at the NEW.id? (it just says "Syntax Error" to me)

CREATE OR REPLACE FUNCTION after_user_insert()
RETURNS TRIGGER AS $$
BEGIN
  SET LOCAL jwt.claims.userId NEW.id;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER set_user_id_on_insert
AFTER INSERT ON "user"
FOR EACH ROW
EXECUTE PROCEDURE after_user_insert();

Searched around a lot and to be honest I think I may just not find anything because I am missing the correct terminology to find what I need to find.

Would appreciate not only help on what on this specific problem but also any related advice on policies for guest users that need priviliges.

Context:

These are the relevant tables and functions

CREATE TYPE "user_role" AS ENUM (
  'customer',
  'partner',
  'admin'
);

CREATE TABLE "user" (
  "id" uuid UNIQUE PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),
  "first_name" varchar NOT NULL,
  "last_name" varchar NOT NULL,
  "email" text UNIQUE NOT NULL,
  "role" user_role NOT NULL DEFAULT 'customer',
  "created_at" timestamp NOT NULL DEFAULT NOW(),
  "updated_at" timestamp NOT NULL DEFAULT NOW()
);

CREATE FUNCTION current_user_id() RETURNS uuid AS $$
  SELECT nullif(current_setting('jwt.claims.userId', true), '')::uuid;
$$ LANGUAGE SQL stable;

CREATE FUNCTION current_user_role() RETURNS user_role AS $$
  SELECT nullif(current_setting('jwt.claims.role', true), '')::user_role;
$$ LANGUAGE SQL stable

The RLS restricts SELECT to rows where the id column of the user table matches current_setting('jwt.claims.userId').

This was set previously by Postgraphile as seen here (https://www.graphile.org/postgraphile/security/).

One possible workaround I thought of would be this but I don't know if this would lead to some kind of vulnerabilities because of the obvious role elevation:

CREATE OR REPLACE FUNCTION after_user_insert()
RETURNS TRIGGER AS $$
BEGIN
  SET LOCAL jwt.claims.role TO "customer";
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION before_user_insert()
RETURNS TRIGGER AS $$
BEGIN
  SET LOCAL jwt.claims.role TO "admin";
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER before_insert
BEFORE INSERT ON "user"
FOR EACH ROW
EXECUTE PROCEDURE before_user_insert();

CREATE TRIGGER after_insert
AFTER INSERT ON "user"
FOR EACH ROW
EXECUTE PROCEDURE after_user_insert();

Body:
Your don't say what a guest is, but your approach seems wrong.

Rather than disabling your checks on a low level, which gives you a bad feeling for good reasons, you should choose one of the following approaches:

fix your policies to allow the necessary operation (perhaps by adding a permissive policy)

have certain operations performed by a SECURITY DEFINER function that belongs to a user not subject to the restrictions.

If you insist on a trigger based solution, you have to use a BEFORE trigger. Also, consider that you cannot use parameterss with a SET statement. You'd either have to use dynamic SQL or (better) use a function:

CREATE OR REPLACE FUNCTION before_user_insert() RETURNS TRIGGER AS
$$BEGIN
   SELECT set_config('jwt.claims.userId', NEW.id::text, TRUE);
   RETURN NEW;
END;$$ LANGUAGE plpgsql;

CREATE TRIGGER set_user_id_on_insert BEFORE INSERT ON "user"
FOR EACH ROW EXECUTE PROCEDURE before_user_insert();


问:
how to work with $lookup and $regex search in mongodb
```<code>  var query = req.params.query;

    const messages = await Message.aggregate([
      {
        $lookup: {
          from: 'users',
          localField: 'reference_id',
          foreignField: '_id',
          as: 'users'
        }
      },
      {'text': {'$regex': `.*${query}.*`}}
    ])
</code>```

$lookup is providing me right information but $regex is not properly working When add {'text': {'$regex': .*${query}.*}} tells me Arguments must be aggregate pipeline operators   after $lookup i have data

```<code>{
    "response": {
        "messages": [
            {
                "_id": "5e4a8e640b92852e110af62f",
                "text": "Gsshha",
                "reference_id": null,
                "date": 1581944420262,
                "users": [
                    {
                        "_id": "5e4a8d2d3952132a08ae5764",
                        "phone": "1111111111",
                        "first_name": "Test1",
                        "last_name": "Test1",
                        "timestamp": 1581944109860
                    }
                ]
            },
            {
                "_id": "5e4ce3a4f55dd93292cbe149",
                "unreads": [
                "text": "Hi",
                "reference_id": null,
                "date": 1582097316013,
                "users": [
                    {
                        "_id": "5e4a8d2d3952132a08ae5764",
                        "phone": "1111111111",
                        "first_name": "Test1",
                        "last_name": "Test1",
                        "timestamp": 1581944109860
                    }
                ]
            }
        ]
    }
}
</code>```

What I want to achieve get all the value from $lookup and the search string from text field, first_name field and last_name field how to achieve this

答:
You've syntax error in query, Try as like given below :

```<code>var query = req.params.query;

const messages = await Message.aggregate([
    {
        $lookup: {
            from: 'users',
            localField: 'reference_id',
            foreignField: '_id',
            as: 'users'
        }
    }, { $match: { 'text': { '$regex': `.*${query}.*` } } }
])
</code>```

So the issue is when you get this error : Arguments must be aggregate pipeline operators, As you can see there are certain stages or operators in aggregation like Ex:- $lookup, $match, $project etc.. so if aggregate finds anything other it would throw an error. Since you need to filter data you need to wrap you piece of code 'text': { '$regex':.${query}.} in $match.

Ref : aggregation-pipeline

Body:
  var query = req.params.query;

    const messages = await Message.aggregate([
      {
        $lookup: {
          from: 'users',
          localField: 'reference_id',
          foreignField: '_id',
          as: 'users'
        }
      },
      {'text': {'$regex': `.*${query}.*`}}
    ])

$lookup is providing me right information but $regex is not properly working When add {'text': {'$regex': .*${query}.*}} tells me Arguments must be aggregate pipeline operators   after $lookup i have data

{
    "response": {
        "messages": [
            {
                "_id": "5e4a8e640b92852e110af62f",
                "text": "Gsshha",
                "reference_id": null,
                "date": 1581944420262,
                "users": [
                    {
                        "_id": "5e4a8d2d3952132a08ae5764",
                        "phone": "1111111111",
                        "first_name": "Test1",
                        "last_name": "Test1",
                        "timestamp": 1581944109860
                    }
                ]
            },
            {
                "_id": "5e4ce3a4f55dd93292cbe149",
                "unreads": [
                "text": "Hi",
                "reference_id": null,
                "date": 1582097316013,
                "users": [
                    {
                        "_id": "5e4a8d2d3952132a08ae5764",
                        "phone": "1111111111",
                        "first_name": "Test1",
                        "last_name": "Test1",
                        "timestamp": 1581944109860
                    }
                ]
            }
        ]
    }
}

What I want to achieve get all the value from $lookup and the search string from text field, first_name field and last_name field how to achieve this

Body:
You've syntax error in query, Try as like given below :

var query = req.params.query;

const messages = await Message.aggregate([
    {
        $lookup: {
            from: 'users',
            localField: 'reference_id',
            foreignField: '_id',
            as: 'users'
        }
    }, { $match: { 'text': { '$regex': `.*${query}.*` } } }
])

So the issue is when you get this error : Arguments must be aggregate pipeline operators, As you can see there are certain stages or operators in aggregation like Ex:- $lookup, $match, $project etc.. so if aggregate finds anything other it would throw an error. Since you need to filter data you need to wrap you piece of code 'text': { '$regex':.${query}.} in $match.

Ref : aggregation-pipeline


问:
How to change the color of a DisplayObject when it moves in a specific zone?
I am coding a graphical interface using Flex, and I have a qestion related to masks in Flash.

I want to create a kind of mask that defines which color and which alpha value a text will have according to its position on the screen. It is very easy to do that with the text being the mask of a bitmap, for instance.

However, I also want to take into account the color of the text itself.

For instance, if I create a red text, in some zone it will be red with a modified alpha value, but on another zone, the text will be full white, as if there was a kind of mask which also applies its own color on top of it.

Is there a way to easily do this kind of thing?

Of course, I can manually apply the format on the text according to where it is, but I wonder if there is an automatic processing like mask or blend mode using a DisplayObject as a processing pattern.

Thank you!

答: Personally, I would have states in my component that changes color, and have something be able to set those when your component rolls over your 'section'.</p>


问:
How to get child element by class name?
I'm trying to get the child span that has a class = 4. Here is an example element:

```<code><div id="test">
 <span class="one"></span>
 <span class="two"></span>
 <span class="three"></span>
 <span class="four"></span>
</div>
</code>```

The tools I have available are JS and YUI2. I can do something like this:

```<code>doc = document.getElementById('test');
notes = doc.getElementsByClassName('four');

//or

doc = YAHOO.util.Dom.get('#test');
notes = doc.getElementsByClassName('four');
</code>```

These do not work in IE. I get an error that the object (doc) doesn't support this method or property (getElementsByClassName). I've tried a few examples of cross browser implementations of getElementsByClassName but I could not get them to work and still got that error.

I think what I need is a cross browser getElementsByClassName or I need to use doc.getElementsByTagName('span') and loop through until I find class 4. I'm not sure how to do that though.

答:
You can fetch the parent class by adding the line below. If you had an id, it would be easier with getElementById. Nonetheless,

```<code>var parentNode = document.getElementsByClassName("progress__container")[0];
</code>```

Then you can use querySelectorAll on the parent
 to fetch all matching divs with class .progress__marker

```<code>var progressNodes = progressContainer.querySelectorAll('.progress__marker');
</code>```

querySelectorAll will fetch every div with the class of progress__marker

Title: How to get child element by class name?

Body:
I'm trying to get the child span that has a class = 4. Here is an example element:

The tools I have available are JS and YUI2. I can do something like this:

doc = document.getElementById('test');
notes = doc.getElementsByClassName('four');

//or

doc = YAHOO.util.Dom.get('#test');
notes = doc.getElementsByClassName('four');

These do not work in IE. I get an error that the object (doc) doesn't support this method or property (getElementsByClassName). I've tried a few examples of cross browser implementations of getElementsByClassName but I could not get them to work and still got that error.

I think what I need is a cross browser getElementsByClassName or I need to use doc.getElementsByTagName('span') and loop through until I find class 4. I'm not sure how to do that though.

Body:
You can fetch the parent class by adding the line below. If you had an id, it would be easier with getElementById. Nonetheless,

var parentNode = document.getElementsByClassName("progress__container")[0];

Then you can use querySelectorAll on the parent <div> to fetch all matching divs with class .progress__marker

var progressNodes = progressContainer.querySelectorAll('.progress__marker');

querySelectorAll will fetch every div with the class of progress__marker


问:
React Native Center align Body Title text
How can I center a title text in native base?

```<code><Header>
  <Left style={{flex:1}}>
    <Button
       transparent
       onPress={() => NavigationService.navigate('Home')}
    >
      <Icon name='arrow-back' />
    </Button>
    </Left>
    <Body style={{flex:1}}>
      <Title>Vacancy Snapshot</Title>
    </Body>
</Header>
</code>```

The result above is a text align to the right.

If I include the Right tag <Right style={{flex:1}} /> after the Body, it center the text, but doesn't display the whole text:

答:
by including the <Right style={{flex:1}}/>, the title text will be centered. and increase the flex to 3 from 1 so that the full length of the text can be displayed, like this:

```<code><Header>
  <Left style={{flex:1}}>
    <Button
      transparent
    >
      <Icon name='arrow-back' />
    </Button>
    </Left>
    <Body style={{flex:3}}>
      <Title>Vacancy Snapshot</Title>
    </Body>
    <Right style={{flex:1}}/>
</Header>
</code>```

i've also included an expo snack here for further experimentation. have fun!

Body:
How can I center a title text in native base?

  <Left style={{flex:1}}>
    <Button
       transparent
       onPress={() => NavigationService.navigate('Home')}
    >
      <Icon name='arrow-back' />
    </Button>
    </Left>

      <Title>Vacancy Snapshot</Title>

The result above is a text align to the right.

If I include the Right tag <Right style={{flex:1}} /> after the Body, it center the text, but doesn't display the whole text:

Body:
by including the <Right style={{flex:1}}/>, the title text will be centered. and increase the flex to 3 from 1 so that the full length of the text can be displayed, like this:

<Header>
  <Left style={{flex:1}}>
    <Button
      transparent
    >
      <Icon name='arrow-back' />
    </Button>
    </Left>
    <Body style={{flex:3}}>
      <Title>Vacancy Snapshot</Title>
    </Body>
    <Right style={{flex:1}}/>
</Header>

i've also included an expo snack here for further experimentation. have fun!


问:
How to run two node versions on linux system?
How to run two different node versions parallel on same system? I've tried looking for solution on web, but all solutions are about switching node versions.</p>

答:
```<code>nvm run {version} {command}
</code>```

e.g.

```<code>nvm run 9 abc.js
</code>```

This will run with Node.js v9

More info on: https://medium.com/@luongnhutoan/how-to-run-multiple-versions-of-nodejs-with-nvm-3c40aa25c359

Body:
nvm run {version} {command}

e.g.

nvm run 9 abc.js

This will run with Node.js v9

More info on: https://medium.com/@luongnhutoan/how-to-run-multiple-versions-of-nodejs-with-nvm-3c40aa25c359


问:
How do I center a custom checkbox vertically in div?
I am trying to use flex to align elements vertically, but the custom checkbox is not aligned, the code below shows the problem clearly.Does anyone know what the problem is?

input[type=checkbox] {
  cursor: pointer;
  font-size: 17px;
  visibility: hidden;
  transform: scale(1.2);
}

input[type=checkbox]:after {
  content: " ";
  background-color: #fff;
  display: inline-block;
  color: #00BFF0;
  width: 14px;
  height: 18px;
  visibility: visible;
  border: 1px solid #FFF;
  padding: 0 3px;
  margin: 2px 0;
  border-radius: 8px;
  box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.09), 0 0 5px 0 rgba(0, 0, 0, 0.18);
}

input[type=checkbox]:checked:after {
  content: "\2714";
  display: unset;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display:inline-block; height:40px; display: flex;  align-items: center; border: 1px solid
        black;">

  <input type="checkbox">
  <span id="text">TEXTTEXTTEXTTEXT</span>
</div></code>```

答:
Please update "input[type=checkbox]:after" in CSS, you have to set display:block, height:14px and margin:0. I have added snippet below, please update below CSS code in your file and try: </p>

```<code>input[type=checkbox]:after {
 content: " ";
 background-color: #fff;
 display: block;
 color: #00BFF0;
 width: 14px;
 height: 14px;
 visibility: visible;
 border: 1px solid #FFF;
 padding: 0 3px;
 margin: 0;
 border-radius: 8px;
 box-shadow: 0 0 15px 0 rgba(0,0,0,0.09), 0 0 2px 0 rgba(0,0,0,0.18);}
</code>```

Body:
I am trying to use flex to align elements vertically, but the custom checkbox is not aligned, the code below shows the problem clearly.Does anyone know what the problem is?

input[type=checkbox] {
  cursor: pointer;
  font-size: 17px;
  visibility: hidden;
  transform: scale(1.2);
}

input[type=checkbox]:after {
  content: " ";
  background-color: #fff;
  display: inline-block;
  color: #00BFF0;
  width: 14px;
  height: 18px;
  visibility: visible;
  border: 1px solid #FFF;
  padding: 0 3px;
  margin: 2px 0;
  border-radius: 8px;
  box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.09), 0 0 5px 0 rgba(0, 0, 0, 0.18);
}

input[type=checkbox]:checked:after {
  content: "\2714";
  display: unset;
  font-weight: bold;
}

  <input type="checkbox">
  TEXTTEXTTEXTTEXT

Body:
Please update "input[type=checkbox]:after" in CSS, you have to set display:block, height:14px and margin:0. I have added snippet below, please update below CSS code in your file and try:

input[type=checkbox]:after {
 content: " ";
 background-color: #fff;
 display: block;
 color: #00BFF0;
 width: 14px;
 height: 14px;
 visibility: visible;
 border: 1px solid #FFF;
 padding: 0 3px;
 margin: 0;
 border-radius: 8px;
 box-shadow: 0 0 15px 0 rgba(0,0,0,0.09), 0 0 2px 0 rgba(0,0,0,0.18);}


问:
Update data in existing column with EF Core Migration
My table in SQL has two fields: Id and Status. It looks something like this

ID | Status

1  | "Status1"

2  | "Status2"

I should make a migration that will change those status values into those that I want?
How can I achieve this?

答:
I should make a migration that will change those status values into those that I want?

Try add SQL statements  into Up method of the generated migration file manually like below

```<code>protected override void Up(MigrationBuilder migrationBuilder)
{
        migrationBuilder.Sql("UPDATE A SET AName = 'Jhon' WHERE Id=3");
}
</code>```

For updating multiple records , you could refer to the following code

```<code>protected override void Up(MigrationBuilder migrationBuilder)
{
        migrationBuilder.Sql(
           "UPDATE A SET AName = CASE Id " +
                   "WHEN 1 THEN 'Shariy' " +
                   "WHEN 2 THEN 'Mary'" +
                   "ELSE AName END " +
                   "WHERE Id IN(1,2)");
}
</code>```

Body:
I should make a migration that will change those status values into those that I want?

Try add SQL statements  into Up method of the generated migration file manually like below

protected override void Up(MigrationBuilder migrationBuilder)
{
        migrationBuilder.Sql("UPDATE A SET AName = 'Jhon' WHERE Id=3");
}

For updating multiple records , you could refer to the following code

protected override void Up(MigrationBuilder migrationBuilder)
{
        migrationBuilder.Sql(
           "UPDATE A SET AName = CASE Id " +
                   "WHEN 1 THEN 'Shariy' " +
                   "WHEN 2 THEN 'Mary'" +
                   "ELSE AName END " +
                   "WHERE Id IN(1,2)");
}


问:
semPlot package Rstudio
I have been having trouble with the r package "semPlot" successfully installing onto Rstudio 1.2.5033

Each time I have tried installing the semplot package I get the following error.

```<code>install.packages('semPlot')
library(semPlot)
</code>```

Error: package or namespace load failed for ‘semPlot’ in
  loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck =
  vI[[j]]):  there is no package called ‘data.table’

I have tried installing the package that is being called to not be there (in the above case 'data.table'), but I have done this 5 or 6 times and feeling like continuous this process is insanity.

Alternatively, is there any alternative to reviewing the path diagrams from SEM if the semPlot package (for the semPaths function) continues this process?

答:
The problem seems to be with your installer not with semPlot. Try

```<code>install.packages('semPlot', dependencies = T)
</code>```

would be helpful if you mention your OS

Title: semPlot package Rstudio

Body:
I have been having trouble with the r package "semPlot" successfully installing onto Rstudio 1.2.5033

Each time I have tried installing the semplot package I get the following error.

install.packages('semPlot')
library(semPlot)

Error: package or namespace load failed for ‘semPlot’ in
  loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck =
  vI[[j]]):  there is no package called ‘data.table’

I have tried installing the package that is being called to not be there (in the above case 'data.table'), but I have done this 5 or 6 times and feeling like continuous this process is insanity.

Alternatively, is there any alternative to reviewing the path diagrams from SEM if the semPlot package (for the semPaths function) continues this process?

Body:
The problem seems to be with your installer not with semPlot. Try

install.packages('semPlot', dependencies = T)

would be helpful if you mention your OS


问:
how to use regular expression for this below stuff in php
I have a database of more than 70000 records and its primary key value started from 1 single digit.

So I want user have to type nm0000001 instead of 1 in url.And in code part I have to discard the rest of the value except 1.

But my problem is i want this type of things having 9 letters in the string and the pattern is like this

```<code>1    - nm0000001
9    - nm0000009
10   - nm0000010
2020 - nm0002020
</code>```

And from the above pattern i want only the digits like 1,9,10,2020 in php.

答:
This function will do the trick:

```<code>function extractID($pInput)
{
    $Matches = array();
    preg_match('/^nm0*(.*)$/', $pInput, $Matches);
    return intval($Matches[1]);
}
</code>```

Here's why /^nm0+(.*)$/ works:

The line must start (^) with exactly one nm

The pattern must continue with at least one 0

At the first non-zero character after nm0..., capture the value (that's the job of the parentheses)

Continue until the end of the line ($)

Body:
I have a database of more than 70000 records and its primary key value started from 1 single digit.

So I want user have to type nm0000001 instead of 1 in url.And in code part I have to discard the rest of the value except 1.

But my problem is i want this type of things having 9 letters in the string and the pattern is like this

1    - nm0000001
9    - nm0000009
10   - nm0000010
2020 - nm0002020

And from the above pattern i want only the digits like 1,9,10,2020 in php.

Body:
This function will do the trick:

function extractID($pInput)
{
    $Matches = array();
    preg_match('/^nm0*(.*)$/', $pInput, $Matches);
    return intval($Matches[1]);
}

Here's why /^nm0+(.*)$/ works:

The line must start (^) with exactly one nm

The pattern must continue with at least one 0

At the first non-zero character after nm0..., capture the value (that's the job of the parentheses)

Continue until the end of the line ($)


问:
Google Sheets Array formula for counting the number of values in each column
I'm trying to create an array formula to auto-populate the total count of values for each column as columns are added.

I've tried doing this using a combination of count and indirect, as well as tried my hand at query, but I can't seem to get it to show unique value counts for each column.

This is my first time attempting to use query, and at first it seemed possible from reading through the documentation on the query language, but I haven't been able to figure it out.

Here's the shared document: https://docs.google.com/spreadsheets/d/15VwsL7uTsORLqBDrnT3VdwAWlXLh-JgoJVbz7wkoMAo/edit?usp=sharing

I know I can do this by writing a custom function in apps script, but I'd like to use the built-in functions if I can for performance reasons (there is going to be a lot of data), and I want quick refresh rates.

答:
In B3 try</p>

```<code>=ArrayFormula(IF(LEN(B5:5), COUNTIF(IF(B6:21<>"", COLUMN(B6:21)), COLUMN(B6:21)),))
</code>```

Body:
In B3 try

=ArrayFormula(IF(LEN(B5:5), COUNTIF(IF(B6:21<>"", COLUMN(B6:21)), COLUMN(B6:21)),))


问:
Android.mk, include all cpp files
I'm trying to build an Android project using the ndk, but I have run into some troubles.

Here's the Android.mk file that works:

```<code>LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := mylib
LOCAL_CFLAGS    := -Werror
LOCAL_SRC_FILES := main.cpp, Screen.cpp, ScreenManager.cpp
LOCAL_LDLIBS    := -llog

include $(BUILD_SHARED_LIBRARY)
</code>```

Is there a way that allows me to specify all the *.cpp files in the directory, without listing them manually under LOCAL_SRC_FILES?

So far I tried using LOCAL_SRC_FILES = $(wildcard *.cpp), but it did now work, it seems that no files get selected.

答:
Using this:</p>

```<code>LOCAL_SRC_FILES += $($(wildcard $(LOCAL_PATH)/*.cpp):$(LOCAL_PATH)/%=%)
</code>```

Title: Android.mk, include all cpp files

Body:
I'm trying to build an Android project using the ndk, but I have run into some troubles.

Here's the Android.mk file that works:

LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := mylib
LOCAL_CFLAGS    := -Werror
LOCAL_SRC_FILES := main.cpp, Screen.cpp, ScreenManager.cpp
LOCAL_LDLIBS    := -llog

include $(BUILD_SHARED_LIBRARY)

Is there a way that allows me to specify all the *.cpp files in the directory, without listing them manually under LOCAL_SRC_FILES?

So far I tried using LOCAL_SRC_FILES = $(wildcard *.cpp), but it did now work, it seems that no files get selected.

Body:
Using this:

LOCAL_SRC_FILES += $($(wildcard $(LOCAL_PATH)/*.cpp):$(LOCAL_PATH)/%=%)


问:
makeValidWord(std::string word) not working properly
I'm programming a hash table thing in C++, but this specific piece of code will not run properly. It should return a string of alpha characters and ' and -, but I get cases like "t" instead of "art" when I try to input "'aRT-*".

isWordChar() return a bool value depending on whether the input is a valid word character or not using isAlpha()

```<code> // Words cannot contain any digits, or special characters EXCEPT for
 // hyphens (-) and apostrophes (') that occur in the middle of a
 // valid word (the first and last characters of a word must be an alpha
 // character). All upper case characters in the word should be convertd
 // to lower case.
 // For example, "can't" and "good-hearted" are considered valid words.
 // "12mOnkEYs-$" will be converted to "monkeys".
 // "Pa55ive" will be stripped "paive".

std::string WordCount::makeValidWord(std::string word) {
    if (word.size() == 0) {
        return word;
    }
    string r = "";
    string in = "";
    size_t incr = 0;
    size_t decr = word.size() - 1;
    while (incr < word.size() && !isWordChar(word.at(incr))) {
        incr++;
    }
    while (0 < decr && !isWordChar(word.at(decr))) {
        decr--;
    }
    if (incr > decr) {
        return r;
    }
    while (incr <= decr) {
        if (isWordChar(word.at(incr)) || word.at(incr) == '-' || word.at(incr) == '\'') {
            in =+ word.at(incr);
        }
        incr++;
    }
    for (size_t i = 0; i < in.size(); i++) {
        r += tolower(in.at(i));
    }
    return r;
}
</code>```

答:
I am going to echo @Someprogrammerdude and say: Learn to use a debugger!

I pasted your code into Visual Studio (changed isWordChar() to isalpha()), and stepped it through with the debugger. Then it was pretty trivial to notice this happening:

First loop of while (incr <= decr) {:

Second loop:

Ooh, look at that; the variable in does not update correctly - instead of collecting a string of the correct characters it only holds the last one. How can that be?

in =+ word.at(incr); Hey, that is not right, that operator should be +=.

Many errors are that easy and effortless to find and correct if you use a debugger. Pick one up today. :)

Body:
I'm programming a hash table thing in C++, but this specific piece of code will not run properly. It should return a string of alpha characters and ' and -, but I get cases like "t" instead of "art" when I try to input "'aRT-*".

isWordChar() return a bool value depending on whether the input is a valid word character or not using isAlpha()

 // Words cannot contain any digits, or special characters EXCEPT for
 // hyphens (-) and apostrophes (') that occur in the middle of a
 // valid word (the first and last characters of a word must be an alpha
 // character). All upper case characters in the word should be convertd
 // to lower case.
 // For example, "can't" and "good-hearted" are considered valid words.
 // "12mOnkEYs-$" will be converted to "monkeys".
 // "Pa55ive" will be stripped "paive".

std::string WordCount::makeValidWord(std::string word) {
    if (word.size() == 0) {
        return word;
    }
    string r = "";
    string in = "";
    size_t incr = 0;
    size_t decr = word.size() - 1;
    while (incr < word.size() && !isWordChar(word.at(incr))) {
        incr++;
    }
    while (0 < decr && !isWordChar(word.at(decr))) {
        decr--;
    }
    if (incr > decr) {
        return r;
    }
    while (incr <= decr) {
        if (isWordChar(word.at(incr)) || word.at(incr) == '-' || word.at(incr) == '\'') {
            in =+ word.at(incr);
        }
        incr++;
    }
    for (size_t i = 0; i < in.size(); i++) {
        r += tolower(in.at(i));
    }
    return r;
}


问:
how can I format this string as the question asks?
I am stumped on a homework problem. I don't need to describe it because its all explained in the image. But I have no clue where to start I'm new to Python and I'm on a time limit so this is my only option, thanks guys.

答:
```<code>user_input = input()
lines = user_input.split(',')

multi_table = [[ int(num) for num in line.split()] for line in lines]
for j in multi_table:
    print(str(j).replace(',', ' |').replace('[',' ').replace(']',' '))
</code>```

1 | 2 | 3

  4 | 5 | 6

  7 | 8 | 9

Body:
user_input = input()
lines = user_input.split(',')

multi_table = [[ int(num) for num in line.split()] for line in lines]
for j in multi_table:
    print(str(j).replace(',', ' |').replace('[',' ').replace(']',' '))

1 | 2 | 3

  4 | 5 | 6

  7 | 8 | 9


Title: Pandas: add column based on groupby with condition

Body:
I have a dataframe with four columns: id1, id2, age, stime.  For example

df = pd.DataFrame(np.array([[1, 1, 3, pd.to_datetime('2020-01-10 00:30:16')],
                         [2, 1, 10, pd.to_datetime('2020-01-27 00:20:20')],
                         [3, 1, 60, pd.to_datetime('2020-01-26 00:10:08')],
                         [4, 2, 1, pd.to_datetime('2020-01-13 00:20:19')],
                         [5, 2, 2, pd.to_datetime('2020-01-12 00:40:17')],
                         [6, 2, 3, pd.to_datetime('2020-01-10 00:10:53')],
                         [7, 3, 20, pd.to_datetime('2020-01-21 00:20:57')],
                         [8, 3, 40, pd.to_datetime('2020-01-20 00:10:38')],
                         [9, 3, 60, pd.to_datetime('2020-01-01 00:30:38')],
                       ]),
                       columns=['id1', 'id2', 'age', 'stime'])

I want to add a column where the value is the maximum value of age, that also has a matching id2 and was within the last 2 weeks of the stime for that row.  So for the above example I want to get

df2 = pd.DataFrame(np.array([[1, 1, 3, pd.to_datetime('2020-01-10 00:30:16'), 3],
                         [2, 1, 10, pd.to_datetime('2020-01-27 00:20:20'), 60],
                         [3, 1, 60, pd.to_datetime('2020-01-26 00:10:08'), 60],
                         [4, 2, 1, pd.to_datetime('2020-01-13 00:20:19'), 3],
                         [5, 2, 2, pd.to_datetime('2020-01-12 00:40:17'), 3],
                         [6, 2, 3, pd.to_datetime('2020-01-10 00:10:53'), 3],
                         [7, 3, 20, pd.to_datetime('2020-01-21 00:20:57'), 40],
                         [8, 3, 40, pd.to_datetime('2020-01-20 00:10:38'), 40],
                         [9, 3, 60, pd.to_datetime('2020-01-01 00:30:38'), 60]
                       ]),
                       columns=['id1', 'id2', 'age', 'stime', 'max_age_last_2w'])

As the df I want to do this is on is very large, any help on how to do this efficiently would be greatly appreciated - thanks in advance!

Body:
Try:

df['max_age_last_2w'] = df.groupby(['id2', pd.Grouper(key='stime', freq='2W', closed='right')])['age'].transform('max')

Output:

  id1 id2 age               stime  max_age_last_2w
0   1   1   3 2020-01-10 00:30:16                3
1   2   1  10 2020-01-27 00:20:20               60
2   3   1  60 2020-01-26 00:10:08               60
3   4   2   1 2020-01-13 00:20:19                3
4   5   2   2 2020-01-12 00:40:17                3
5   6   2   3 2020-01-10 00:10:53                3
6   7   3  20 2020-01-21 00:20:57               40
7   8   3  40 2020-01-20 00:10:38               40
8   9   3  60 2020-01-01 00:30:38               60


问:
Start video call in Hangouts or Duo using intent?
I am looking for a way to start a video call in either Hangouts or Duo.
There seems to be 0 documentation regarding what intents should be used.
Does anyone have an idea?</p>

答:
Let's consider Duo here.

Research

1.First of all, to find out the intent, you should activate the USB debug mode on your phone - please refer to this answer to find out how to do it.

2.Then, connect your phone to your computer so that you could see the logcat from your device (debug level should be info).

3.Open Contacts(from Google) and find a contact to whom you can call using Duo. Now, start the call and search for com.google.android.apps.tachyon. There will be a couple of matches but the important one looks something like:

START u0 {act=com.google.android.apps.tachyon.action.CALL typ=null flg=0x0 cmp=ComponentInfo{com.google.android.apps.tachyon/com.google.android.apps.tachyon.ExternalCallActivity}} from uid 10031

4.So, once you know the component info for your Duo app, just add the following code in your app from where you'd like to start a video call.

```<code>val intent = Intent()
intent.setAction("com.google.android.apps.tachyon.action.CALL")
intent.setClassName("com.google.android.apps.tachyon",
    "com.google.android.apps.tachyon.ExternalCallActivity")
startActivity(intent)
</code>```

5.You'll see a video call screen with possible contacts.

Conclusion

If you'd like to find out how to start a video call or chat or something else, try to do the same as above - do it manually first and check what intents (and arguments) are used in those cases.

Body:
Let's consider Duo here.

Research

1.First of all, to find out the intent, you should activate the USB debug mode on your phone - please refer to this answer to find out how to do it.

2.Then, connect your phone to your computer so that you could see the logcat from your device (debug level should be info).

3.Open Contacts(from Google) and find a contact to whom you can call using Duo. Now, start the call and search for com.google.android.apps.tachyon. There will be a couple of matches but the important one looks something like:

START u0 {act=com.google.android.apps.tachyon.action.CALL typ=null flg=0x0 cmp=ComponentInfo{com.google.android.apps.tachyon/com.google.android.apps.tachyon.ExternalCallActivity}} from uid 10031

4.So, once you know the component info for your Duo app, just add the following code in your app from where you'd like to start a video call.

val intent = Intent()
intent.setAction("com.google.android.apps.tachyon.action.CALL")
intent.setClassName("com.google.android.apps.tachyon",
    "com.google.android.apps.tachyon.ExternalCallActivity")
startActivity(intent)

5.You'll see a video call screen with possible contacts.

Conclusion

If you'd like to find out how to start a video call or chat or something else, try to do the same as above - do it manually first and check what intents (and arguments) are used in those cases.


问:
jQuery selection help
```<code>    jQuery.subscribe('setIdComFamOnEditForm', function(event,ui) {
        var idButton = ui.id;
        var idComFam = jQuery("#" + idButton).name.split("-")[1];
        $("#formFamigliare").attr('action', 'detraz_update');
        $("#IdComFam").val(idComFam);
    });
</code>```

The above code does not find the jQuery("#" + idButton).

Where Am I wrong?

答: I'm not that familiar with subscribe but are you sure that ui.id is returning a value? Furthermore I don't think a jquery wrapped set  has a name property. So I don't think jQuery("#" + idButton).name will work. If you want the name attribute you would need to use the attr() method.</p>

Title: jQuery selection help

Body:
    jQuery.subscribe('setIdComFamOnEditForm', function(event,ui) {
        var idButton = ui.id;
        var idComFam = jQuery("#" + idButton).name.split("-")[1];
        $("#formFamigliare").attr('action', 'detraz_update');
        $("#IdComFam").val(idComFam);
    });

The above code does not find the jQuery("#" + idButton).

Where Am I wrong?


问:
Laravel - How to Make Lesson aggregate score not more than course max score
I am developing a web application  on Student Course Management using Laravel-5.8

Models

```<code>class Lesson extends Model
{
      protected $table = 'Lessons';
      protected $fillable = [
              'lesson_name',
          'course_id',
          'student_id',
              'score_obtained',
          ];

   public function gradelevel()
    {
        return $this->belongsTo('App\Models\Course','course_id');
    }
    public function student()
    {
        return $this->belongsTo('App\Models\Student','student_id');
    }

}

class Course extends Model
{
  protected $table = 'courses';
  protected $fillable = [
              'course_code',
              'course_name',
              'max_score',
          ];
}
</code>```

Controller

```<code>class LessonController extends Controller
{
    public function create()
    {
      $courses = Course::all();
      $students = Student::all();
      return view('lessons.create')->with('courses', $courses)->with('students', $students);
    }

    public function store(StoreLessonRequest $request)
    {
     try {
            $lesson = Lesson::create([
                'lesson_name'       => $request->lesson_name,
                'course_id'             => $request->course_id,
                'lesson_id'             => $request->lesson_id,
                'score_obtained'            => $request->score_obtained,
            ]);
            Session::flash('success', 'Lesson is created successfully');
            return redirect()->route('lessons.index');
    } catch (Exception $exception) {
            Session::flash('danger', 'Lesson creation failed!');
            return redirect()->route('lessons.index');
    }
 }
}
</code>```

create.blade

```<code>   <form  action="{{route('lessons.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
       {{csrf_field()}}
       <div class="card-body">
        <div class="form-body">
        <div class="row">

          <div class="col-sm-6">
            <div class="form-group">
                <label>Course</label>
                <select class="form-control select2bs4" data-placeholder="Choose Course" tabindex="1" name="course_id" style="width: 100%;">>
                    <option value="">Select Course</option>
                    @if($courses->count() > 0)
                        @foreach($courses as $course)
                            <option value="{{$course->id}}">{{$course->course_name}}</option>
                        @endforeach
                    @endif
                </select>
            </div>
          </div>

          <div class="col-sm-6">
            <div class="form-group">
                <label>Student</label>
                <select class="form-control select2bs4" data-placeholder="Choose Course" tabindex="1" name="student_id" style="width: 100%;">>
                    <option value="">Select Student</option>
                    @if($students->count() > 0)
                        @foreach($students as $student)
                            <option value="{{$student->id}}">{{$student->student_name}}</option>
                        @endforeach
                    @endif
                </select>
            </div>
          </div>

          <div class="col-sm-6">
            <div class="form-group">
                <label>Lesson<span style="color:red;">*</span></label>
               <input  type="text" name="lesson_name" placeholder="Enter lesson here" class="form-control" value="{{old('lesson_name')}}">
            </div>
          </div>

          <div class="col-sm-6">
            <div class="form-group">
                <label>Obtained Score<span style="color:red;">*</span></label>
               <input  type="text" name="score_obtained" placeholder="Enter score obtained here" class="form-control" value="{{old('score_obtained')}}">
            </div>
          </div>

       </div>
     </div>
    </div>
    <!-- /.card-body -->
    <div class="card-footer">
            <button type="submit" id="submit_create" class="btn btn-primary">Score</button>
    </div>

    </form>
</code>```

Each core have maximum score allocated and this is done at the setting. For each course, students have lesson and scores are obtained for each lesson.

What I want to achieve is that on the lesson create form, what student score_obtained are being entered the application should sum up all the scores (from the lesson table and the just entered one) the student obtained for that particular course including the one in the textbox, if its more that what is in the max_score in the courses table for that particular course the application should display a message and shouldn't allow the user to submit.

How do I achieve this?

Thank you.

答:
In store method, you can write below code:

```<code>$maxScore = Course::find($request->course_id)->max_score;
$scoresObtained = Lession::where('course_id' , $request->course_id)->sum('score_obtained');
$totalScore = intval($scoresObtained) + intval($request->score_obtained);
if($totalScore > $maxScore)
{
   return redirect()->back()->withErrors([__('Total score exceeds max score for selected course')]);
}
</code>```

You can use floatval() in place of intval() in case your scores are in decimals

Body:
I am developing a web application  on Student Course Management using Laravel-5.8

Models

class Lesson extends Model
{
      protected $table = 'Lessons';
      protected $fillable = [
              'lesson_name',
          'course_id',
          'student_id',
              'score_obtained',
          ];

   public function gradelevel()
    {
        return $this->belongsTo('App\Models\Course','course_id');
    }
    public function student()
    {
        return $this->belongsTo('App\Models\Student','student_id');
    }

}

class Course extends Model
{
  protected $table = 'courses';
  protected $fillable = [
              'course_code',
              'course_name',
              'max_score',
          ];
}

Controller

class LessonController extends Controller
{
    public function create()
    {
      $courses = Course::all();
      $students = Student::all();
      return view('lessons.create')->with('courses', $courses)->with('students', $students);
    }

    public function store(StoreLessonRequest $request)
    {
     try {
            $lesson = Lesson::create([
                'lesson_name'       => $request->lesson_name,
                'course_id'             => $request->course_id,
                'lesson_id'             => $request->lesson_id,
                'score_obtained'            => $request->score_obtained,
            ]);
            Session::flash('success', 'Lesson is created successfully');
            return redirect()->route('lessons.index');
    } catch (Exception $exception) {
            Session::flash('danger', 'Lesson creation failed!');
            return redirect()->route('lessons.index');
    }
 }
}

create.blade

   <form  action="{{route('lessons.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
       {{csrf_field()}}

                Course
                <select class="form-control select2bs4" data-placeholder="Choose Course" tabindex="1" name="course_id" style="width: 100%;">>
                    <option value="">Select Course</option>
                    @if($courses->count() > 0)
                        @foreach($courses as $course)
                            <option value="{{$course->id}}">{{$course->course_name}}</option>
                        @endforeach
                    @endif
                </select>

                Student
                <select class="form-control select2bs4" data-placeholder="Choose Course" tabindex="1" name="student_id" style="width: 100%;">>
                    <option value="">Select Student</option>
                    @if($students->count() > 0)
                        @foreach($students as $student)
                            <option value="{{$student->id}}">{{$student->student_name}}</option>
                        @endforeach
                    @endif
                </select>

                Lesson*
               <input  type="text" name="lesson_name" placeholder="Enter lesson here" class="form-control" value="{{old('lesson_name')}}">

                Obtained Score*
               <input  type="text" name="score_obtained" placeholder="Enter score obtained here" class="form-control" value="{{old('score_obtained')}}">

            <button type="submit" id="submit_create" class="btn btn-primary">Score</button>

    </form>

Each core have maximum score allocated and this is done at the setting. For each course, students have lesson and scores are obtained for each lesson.

What I want to achieve is that on the lesson create form, what student score_obtained are being entered the application should sum up all the scores (from the lesson table and the just entered one) the student obtained for that particular course including the one in the textbox, if its more that what is in the max_score in the courses table for that particular course the application should display a message and shouldn't allow the user to submit.

How do I achieve this?

Thank you.

Body:
In store method, you can write below code:

$maxScore = Course::find($request->course_id)->max_score;
$scoresObtained = Lession::where('course_id' , $request->course_id)->sum('score_obtained');
$totalScore = intval($scoresObtained) + intval($request->score_obtained);
if($totalScore > $maxScore)
{
   return redirect()->back()->withErrors([__('Total score exceeds max score for selected course')]);
}

You can use floatval() in place of intval() in case your scores are in decimals


问:
How to pick one element from each row of a matrix given column indices for each row?
For example, if a matrix is

A = [11 22 33 11; ...
     44 55 66 34; ...
     67 45 33 22]
```

<p>then from each row I want to pick </p>

<pre class="lang-matlab prettyprint-override"><code>col_idx = [2 4 1]
</code>```

so that the result would be

```<code>ans = 22
      34
      67
</code>```

Other questions similar to this are based on R or Python. However, I am looking for a MATLAB based answer. Any help would be appreciated.

答:
I'd use sub2ind for that:

A = [11 22 33 11; 44 55 66 34; 67 45 33 22];

col_idx = [2 4 1]
row_idx = 1:size(A, 1)

A(sub2ind(size(A), row_idx, col_idx))
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>col_idx =
   2   4   1

row_idx =
   1   2   3

ans =
   22   34   67
</code>```

Hope that helps!

Body:
For example, if a matrix is

A = [11 22 33 11; ...
     44 55 66 34; ...
     67 45 33 22]

then from each row I want to pick

col_idx = [2 4 1]

so that the result would be

ans = 22
      34
      67

Other questions similar to this are based on R or Python. However, I am looking for a MATLAB based answer. Any help would be appreciated.

Body:
I'd use sub2ind for that:

A = [11 22 33 11; 44 55 66 34; 67 45 33 22];

col_idx = [2 4 1]
row_idx = 1:size(A, 1)

A(sub2ind(size(A), row_idx, col_idx))

Output:

col_idx =
   2   4   1

row_idx =
   1   2   3

ans =
   22   34   67

Hope that helps!


问:
Calling function from DevTools console does not trigger breakpoint
My Chrome DevTools pauses at a breakpoint I set.

I go to the console, and I manually call a function (say, myFunc()) and it executes properly.

However, the breakpoint I set inside myFunc() is never hit! I expect that when I call the function, the function in the code should be called and the breakpoint should be hit!

The source code is extremely simple:

```<code>// Import stylesheets
import './style.css';

// Write TypeScript code!
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = `<h1>TypeScript Starter</h1>`;

appDiv.__proto__.myFunc = function(){
  var myCoolFunction = "My cool function"; //. <---- breakpoint on this line is never hit
  console.log('myCoolFunction:', myCoolFunction);
}
console.log('appDiv', appDiv); // <---- manually call appDiv.myFunc() while paused on this line
</code>```

Here is the link to the page: https://typescript-gmngl3.stackblitz.io/~/index.ts

Link to source code in Stackblitz: https://stackblitz.com/edit/typescript-gmngl3

Screenshot:

答:
You can call debug(function) in your console, and it should add a breakpoint on the first line on your function. Here are some more details: https://developers.google.com/web/tools/chrome-devtools/javascript/breakpoints#function

In your case, write this into console:

debug(appDiv.myFunc);

// now you can call myFunc and it should hit a breakpoint

appDiv.myFunc()
```

Body:
My Chrome DevTools pauses at a breakpoint I set.

I go to the console, and I manually call a function (say, myFunc()) and it executes properly.

However, the breakpoint I set inside myFunc() is never hit! I expect that when I call the function, the function in the code should be called and the breakpoint should be hit!

The source code is extremely simple:

// Import stylesheets
import './style.css';

// Write TypeScript code!
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = `<h1>TypeScript Starter</h1>`;

appDiv.__proto__.myFunc = function(){
  var myCoolFunction = "My cool function"; //. <---- breakpoint on this line is never hit
  console.log('myCoolFunction:', myCoolFunction);
}
console.log('appDiv', appDiv); // <---- manually call appDiv.myFunc() while paused on this line

Here is the link to the page: https://typescript-gmngl3.stackblitz.io/~/index.ts

Link to source code in Stackblitz: https://stackblitz.com/edit/typescript-gmngl3

Screenshot:


问:
How to remove data-* attributes using the HTML dataset attribute
According to the dataset specification, how is element.dataset meant to delete data attributes? Consider:

```<code><p id="example" data-a="string a" data-b="string b"></p>
</code>```

If you do this:

```<code>var elem = document.querySelector('#example');
elem.dataset.a = null;
elem.dataset.b = undefined;
elem.dataset.c = false;
elem.dataset.d = 3;
elem.dataset.e = [1, 2, 3];
elem.dataset.f = {prop: 'value'};
elem.dataset.g = JSON.stringify({prop: 'value'});
</code>```

the DOM becomes this in Chrome and Firefox:

```<code><p id="example"
   data-a="null"
   data-b="undefined"
   data-c="false"
   data-d="3"
   data-e="1,2,3"
   data.f="[object Object]"
   data.g="{"prop":"value"}"
></p>
</code>```

The Chrome/Firefox implementations mimic setAttribute. It basically applies .toString() first. This makes sense to me except for the treatment of null because I would expect that null would remove the attribute. Otherwise how does the dataset API do the equivalent of:

```<code>elem.removeAttribute('data-a');
</code>```

And what about boolean attributes:

 is equivalent to
 Hmm.

答:
As per MDN you need to use the delete operator to remove a dataset element

When you want to remove an attribute, you can use the delete operator.

const p = document.getElementById('example')
delete p.dataset.a
delete p.dataset.b```

Body:
According to the dataset specification, how is element.dataset meant to delete data attributes? Consider:

If you do this:

var elem = document.querySelector('#example');
elem.dataset.a = null;
elem.dataset.b = undefined;
elem.dataset.c = false;
elem.dataset.d = 3;
elem.dataset.e = [1, 2, 3];
elem.dataset.f = {prop: 'value'};
elem.dataset.g = JSON.stringify({prop: 'value'});

the DOM becomes this in Chrome and Firefox:

The Chrome/Firefox implementations mimic setAttribute. It basically applies .toString() first. This makes sense to me except for the treatment of null because I would expect that null would remove the attribute. Otherwise how does the dataset API do the equivalent of:

elem.removeAttribute('data-a');

And what about boolean attributes:

 is equivalent to
 Hmm.