问:
How do I replace if statements with ? operator for making a shader work on mobile?
I'm porting a custom shader to make it work on mobile phones since shaders inside mobiles can not have if statements.

I tried replacing the if statements of my code with the ? operator but I can not compile in Unity without errors. I'm pretty new to c# so it is obvious to myself I am missing something here to complete this.
Any advice from more experienced programmers here? Many thanks to you all.

// The original code is commented.

I also tried to store the result inside a variable and return it but also didn't work.

/*
if (charCol.r > .8f)
{
    if(_monochromatic == 1)
        return float4(0, gray, 0, 1);
    else
        return col;
}
else
{
    return col * _brightness;
}
*/

charCol.r > .8f ? (_monochromatic == 1) ? return float4(0, gray, 0, 1) : return col : return col * _brightness;
```

Error message:

Shader error in 'Custom/Shader': syntax error: unexpected token 'return'

答:
A ternary operator runs a test and resolves to one value if the test is true or another value if the test is false

```<code> var age = person.Age > 21 : "adult" : "child";
</code>```

The age is tested, one of the values is picked, the expression as a whole resolves to some string and age is this a string. Because the whole thing is effectively a value it can be returned

You might be tempted to nest these; it's possible but I'd say "only do it if it's simple" like:

```<code>var age = person.Age > 21 : "adult" : (person.Age > 12 ? "teenager" : "child");
</code>```

This rapidly descends into a mess if you try to take it much further. Instead prefer a switch expression:

```<code>var age = person.Age switch {
  >21 => "adult",
  >12 => "teenager",
  _ => "child"
};
</code>```

You can read this by imagining the compiler prefixes every line with the thing before the switch, the => is like "then" and the _ is like "else":

```<code>var age = switch {
  person.Age>21 then "adult",
  person.Age>12 then "teenager",
  else then "child"
};
</code>```

And of course with anything that resolves to a value you don't have to store it in a variable before you return it.. you ca swap var age = for return on anything you see here

Body:
I'm porting a custom shader to make it work on mobile phones since shaders inside mobiles can not have if statements.

I tried replacing the if statements of my code with the ? operator but I can not compile in Unity without errors. I'm pretty new to c# so it is obvious to myself I am missing something here to complete this.
Any advice from more experienced programmers here? Many thanks to you all.

// The original code is commented.

I also tried to store the result inside a variable and return it but also didn't work.

/*
if (charCol.r > .8f)
{
    if(_monochromatic == 1)
        return float4(0, gray, 0, 1);
    else
        return col;
}
else
{
    return col * _brightness;
}
*/

charCol.r > .8f ? (_monochromatic == 1) ? return float4(0, gray, 0, 1) : return col : return col * _brightness;

Error message:

Shader error in 'Custom/Shader': syntax error: unexpected token 'return'

Body:
A ternary operator runs a test and resolves to one value if the test is true or another value if the test is false

 var age = person.Age > 21 : "adult" : "child";

The age is tested, one of the values is picked, the expression as a whole resolves to some string and age is this a string. Because the whole thing is effectively a value it can be returned

You might be tempted to nest these; it's possible but I'd say "only do it if it's simple" like:

var age = person.Age > 21 : "adult" : (person.Age > 12 ? "teenager" : "child");

This rapidly descends into a mess if you try to take it much further. Instead prefer a switch expression:

var age = person.Age switch {
  >21 => "adult",
  >12 => "teenager",
  _ => "child"
};

You can read this by imagining the compiler prefixes every line with the thing before the switch, the => is like "then" and the _ is like "else":

var age = switch {
  person.Age>21 then "adult",
  person.Age>12 then "teenager",
  else then "child"
};

And of course with anything that resolves to a value you don't have to store it in a variable before you return it.. you ca swap var age = for return on anything you see here


来源: stackexchange

问:
How to open a link in a new tab
How to open a link in a new tab using twig template language.
Here is my code to open the link

```<code>{% set link = getUrl %}
</code>```

I tried this but failed.

```<code>{% set link = getlUrl, {'target': 'blank_'} %}
</code>```

答:
Try something like this

```<code><a target="_blank" href="{{ path('_welcome') }}">Home</a>
</code>```

Or smyfony 3

```<code><a target="_blank" href="{{ path('homepage', {'_fragment': 'home'}) }}">Home</a>
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to open a link in a new tab

Body:
How to open a link in a new tab using twig template language.
Here is my code to open the link

{% set link = getUrl %}

I tried this but failed.

{% set link = getlUrl, {'target': 'blank_'} %}

Body:
Try something like this

<a target="_blank" href="{{ path('_welcome') }}">Home</a>

Or smyfony 3

<a target="_blank" href="{{ path('homepage', {'_fragment': 'home'}) }}">Home</a>


问:
Grails Config: include another config file
I have in my main config something like:

grails.config.locations = ["file:grails-app/config/Jawr.groovy"].

When running the application with grails run-app, everything is OK.

But, on deployment (creating the war archive) this does not work anymore, as the file "Jawr.groovy" is not kept anymore on the filesystem (it should be only in the war).

Do you have a solution for that? Hw do you include external files into the grails main configuration file?

Thanks.

答:
Okay, a few things here.

First, because you don't have a leading slash on your config path, that is a path relative to who knows where. I played with this in Tomcat, and that path ends up being relative to the working directory you were in when starting the Tomcat server. If you start Tomcat, shut it down, change directories, then start it again, you are going to get two different config paths.

Second, the grails-app directory only exists within the source tree of your Grails project. The structure of an unpacked WAR file is more like the web-app folder of your Grails source tree, with folders like WEB-INF, META-INF, js, images, etc.

Third, you probably want to avoid putting your externalized config file inside the folder of your webapp. The next time you deploy your app, that configuration is going to get wiped away with the old version of the app. One of the points of the externalized config is so that you can redeploy without having to reconfigure.

A simple, but less than ideal, solution would be to use a static, fully qualified path, like /etc/yourApp/conf.groovy, then put that in the documentation. There is also a plug-in that handles this.

http://www.grails.org/plugin/external-config

I haven't used it, but the description makes it sound like it does sensible things.

ContentLicense: CC BY-SA 3.0


问:
System.IO.FileNotException and Could not load OBIDISC4NETnative.dll?
I am facing one new problem in loading Dll in Windows 8.1 WINBOOK tablet.

Problem description:

I have developed C#.NET app and its worked my Laptop (Windows 8.1) fine.
    But
    When I copy the same app to my Windows 8.1 WINBOOK tablet, it could not run,

Exception says, System.IO.FileNotFoundException Could not load file or assembly "OBIDISC4NETnative.Dll" or one of its dependencies,

my laptop system cfg is " 64 -bit OS , x64 based processor"

BUT

my tablet system cfg is " 32 -bit OS , x64 based processor"

答:
Hi I  am using Windows 10 home 64 bit OS and Visual studio 2019-IDE,
After installing  Microsoft Visual C++ latest ,getting the same Error
Could not load file or assembly 'OBIDISC4NETnative.dll' or one of its dependencies. The specified module could not be found.
exception</p>


问:
Entity Framework & MVC Models
Our team is currently developing a web application, in that we have a class library with Entity Framework .edmx added and have generated the POCO classes.

Our Web Application is based on MVC, we have defined our classes in models with the same name and attributes (copy paste of the POCO classes from the .edmx). The .edmx class library is refrenced to MVC web application.

The Views are strongly typed of MVC Model classes. We have used MVC Models for Display, StringLength & Required.

In our controller when there is a CRUD operation we are accepting the POCO Classes Type such as

```<code>     public ActionResult Create(EFModels.User user)    {    }
</code>```

EFModels.User is a class from the .edmx (POCO generated class) and the MVC View is strongly typed to the model which is MvcWebApplication.Models.User.

Question is how are we getting data from the MvcWebApplication.Models.User (from Model) to EFModels.User (EF class) in the ActionResult Create ??

I am able to get the data, I know it is coz of the same property name. I tried changing the class name but still it works, but if we change the property name it does not work. I cannot understand the logic behind it.

Initially we never knew it didn`t work and we were using AutoMapper to convert the Model Class to Edmx POCO class.

Any ideas, Thanks.

The question is how are we getting the values of the Model Class to the EF class with any mapping. I don`t need to use AutoMapper, without using that I am getting the values.

Have a look at the code, hope that explains better...

//POCO CLASS

```<code>namespace EFModels
{
    using System;
    using System.Collections.Generic;

    public partial class User
    {
        public int Id { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
    }
}
</code>```

//MVC Model Class

```<code>namespace MvcWebSamp.Models
{
    public class User
    {
        public int Id { get; set; }

        [Display(ResourceType = typeof(BasicTags), Name = "Type")]
        [StringLength(15, ErrorMessageResourceName = "TypeLength", ErrorMessageResourceType = typeof(BasicTags))]
        [Required(ErrorMessageResourceName = "TypeRequired", ErrorMessageResourceType = typeof(BasicTags))]
        public string TypeName { get; set; }
        public string Name { get; set; }

        public Address Address { get; set; }
    }
}
</code>```

//MVC VIEW PAGE

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWebSamp.Models.User>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    User
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>User</h2>
  <% using (Html.BeginForm("Create", "User", FormMethod.Post))
       {
    %>
     <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>User</legend>
        <div class="editor-field">
            <%: Html.LabelFor(model => model.TypeName) %>
            <%: Html.EditorFor(model => model.TypeName)%>
            <%: Html.ValidationMessageFor(model => model.TypeName)%>
        </div>
        <div class="editor-field">
            <%: Html.LabelFor(model => model.Name) %>
            <%: Html.EditorFor(model => model.Name)%>
             <%: Html.EditorFor(model => model.Address.street)%>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
    <% } %>
</asp:Content>
</code>```

//Controller Method

```<code> public ActionResult Create(EFModels.User user)
    {
        Model1Container con = new Model1Container();
        con.Users.Add(user);
        con.SaveChanges();
        return View("User");
    }
</code>```

When I hit the Create Button, I am posting data of the type MvcWebSamp.Models.User and in the Create Action I am able to get the data of the type EFModels.User user without using any AutoMapper. I want to know how this works???

答:
By giving DbContext to UI Layer you are creating dependancy between UI and database. Try to seperate it and use repository pattern and dependency injection.

Reference:
    http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

```<code>http://prodinner.codeplex.com/releases/view/66899
</code>```

Title: Entity Framework & MVC Models

Body:
Our team is currently developing a web application, in that we have a class library with Entity Framework .edmx added and have generated the POCO classes.

Our Web Application is based on MVC, we have defined our classes in models with the same name and attributes (copy paste of the POCO classes from the .edmx). The .edmx class library is refrenced to MVC web application.

The Views are strongly typed of MVC Model classes. We have used MVC Models for Display, StringLength & Required.

In our controller when there is a CRUD operation we are accepting the POCO Classes Type such as

     public ActionResult Create(EFModels.User user)    {    }

EFModels.User is a class from the .edmx (POCO generated class) and the MVC View is strongly typed to the model which is MvcWebApplication.Models.User.

Question is how are we getting data from the MvcWebApplication.Models.User (from Model) to EFModels.User (EF class) in the ActionResult Create ??

I am able to get the data, I know it is coz of the same property name. I tried changing the class name but still it works, but if we change the property name it does not work. I cannot understand the logic behind it.

Initially we never knew it didn`t work and we were using AutoMapper to convert the Model Class to Edmx POCO class.

Any ideas, Thanks.

The question is how are we getting the values of the Model Class to the EF class with any mapping. I don`t need to use AutoMapper, without using that I am getting the values.

Have a look at the code, hope that explains better...

//POCO CLASS

namespace EFModels
{
    using System;
    using System.Collections.Generic;

    public partial class User
    {
        public int Id { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
    }
}

//MVC Model Class

namespace MvcWebSamp.Models
{
    public class User
    {
        public int Id { get; set; }

        [Display(ResourceType = typeof(BasicTags), Name = "Type")]
        [StringLength(15, ErrorMessageResourceName = "TypeLength", ErrorMessageResourceType = typeof(BasicTags))]
        [Required(ErrorMessageResourceName = "TypeRequired", ErrorMessageResourceType = typeof(BasicTags))]
        public string TypeName { get; set; }
        public string Name { get; set; }

        public Address Address { get; set; }
    }
}

//MVC VIEW PAGE

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWebSamp.Models.User>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    User
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

User

  <% using (Html.BeginForm("Create", "User", FormMethod.Post))
       {
    %>
     <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>User</legend>

            <%: Html.LabelFor(model => model.TypeName) %>
            <%: Html.EditorFor(model => model.TypeName)%>
            <%: Html.ValidationMessageFor(model => model.TypeName)%>

            <%: Html.LabelFor(model => model.Name) %>
            <%: Html.EditorFor(model => model.Name)%>
             <%: Html.EditorFor(model => model.Address.street)%>

            <input type="submit" value="Create" />

    </fieldset>
    <% } %>
</asp:Content>

//Controller Method

 public ActionResult Create(EFModels.User user)
    {
        Model1Container con = new Model1Container();
        con.Users.Add(user);
        con.SaveChanges();
        return View("User");
    }

When I hit the Create Button, I am posting data of the type MvcWebSamp.Models.User and in the Create Action I am able to get the data of the type EFModels.User user without using any AutoMapper. I want to know how this works???

Body:
By giving DbContext to UI Layer you are creating dependancy between UI and database. Try to seperate it and use repository pattern and dependency injection.

Reference:
    http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

http://prodinner.codeplex.com/releases/view/66899


问:
Skiasharp Save desktop image to file (Windows)
I am using net core for a web project.
I have installed in System.Drawing.Common (Nuget) to save the deskop screen to a file.
In .NET (Web too) I do it without problems, but netcore is not giving me processes with Bitmap. (It informs me that : System.Drawing.Common is not supported on this platform.)

I have installed skiasharp (Nuget)

Can someone please give me a complete example of simply saving the desktop screen using skiasharp?
Thank you

答:
The System.Drawing namespace is not recommended for new development because it is not supported in Windows Services, ASP.NET Core, and ASP.NET.

You can use ImageSharp, SkiaSharp instead.

You want to use skiasharp, you can download the source code of this project, maybe it will help you:

https://github.com/hongbai/FontsPrint


问:
"Browser or app may not be secure. Try using a different browser." error with Flutter Firebase Google Login
I am using flutter web and firebase authentication to build a web app. For that
1. Created Firebase app with Google signin as one of the sign in methods.
2. Added the dependencies as given in https://github.com/FirebaseExtended/flutterfire/tree/master/packages/firebase_auth/firebase_auth/example
and https://dart-pub.mirrors.sjtug.sjtu.edu.cn/packages/firebase_auth_web.

When I try to login, the Google sign-in window appears. Once I enter the email address and press enter, it gives the following error.

"Couldn't sign you in This browser or app may not be secure. Try using
  a different browser. If you’re already using a supported browser, you
  can refresh your screen and try again to sign in."

I used Chrome browser.
What should I do to make my app more secure ? For android, we had the option of using SHA keys to encrypt the connection. Do we need to do something similar for web ?

答:
For Test Automation Users-:I saw many testers are facing this issue for sign in using Google but I think below my idea will save their time.

Best Work Around is as below-:

Open automated Chrome browser as shown below

Sign up with new details which you want to use.

Now after successfully completion of sign up.

Then use that email and password for signing into gmail using Selenium or any other test automation tool


问:
How to find out if app has been disconnected from Google Drive?
I'm building an app where I store app data in the app-specific-folder on Google Drive. I've been able to setup everything related to file storage and retrieval. The problem I'm facing is regarding permissions. The user has an option to disconnect the app from the Google Drive settings panel.

I use the DriveScopes.DRIVE_APPDATA meaning https://www.googleapis.com/auth/drive.appdata scope to save data.

I'm trying to figure out how to find out if this has happened on the app side. If I try to continue using the drive related apis, with the app being disconnected, then it crashes with a UserRecoverableAuthException.

```<code>com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException
    at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:297)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:868)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:476)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:409)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:526)
    at abhiank.maplocs.ui.drivesync.DriveSyncService.onHandleIntent(DriveSyncService.kt:68)
    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:78)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.os.HandlerThread.run(HandlerThread.java:67)
 Caused by: com.google.android.gms.auth.UserRecoverableAuthException: NeedPermission
    at com.google.android.gms.auth.zze.zzb(Unknown Source:13)
    at com.google.android.gms.auth.zzd.zza(Unknown Source:77)
    at com.google.android.gms.auth.zzd.zzb(Unknown Source:20)
    at com.google.android.gms.auth.zzd.getToken(Unknown Source:7)
    at com.google.android.gms.auth.zzd.getToken(Unknown Source:5)
    at com.google.android.gms.auth.zzd.getToken(Unknown Source:2)
    at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source:55)
    at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:267)
    at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:292)
</code>```

I tried the following to figure out if the app does not have the permissions or scopes.

Look at data inside GoogleSignInAccount instance received from GoogleSignIn.getLastSignedInAccount(this). This had the following scopes available in account.grantedScopes() after app had been disconnected. drive.appdata is shown even though app is disconnected.

```<code>[https://www.googleapis.com/auth/drive.appdata, https://www.googleapis.com/auth/userinfo.profile, https://www.googleapis.com/auth/userinfo.email, openid, profile, email]
</code>```

Last thing I tried was hasPermissions method available in GoogleSignIn. I checked if the APP_DATA scope was available with this call and it returned true. So no help there either.

```<code>GoogleSignIn.hasPermissions(account, Scope(DriveScopes.DRIVE_APPDATA))
</code>```

I'm really stuck now. Any help will be really appreciated. Thanks.

答:
I ended up using a try-catch around my drive related code and catching the UserRecoverableAuthIOException. According to the documentation, this is called when -

UserRecoverableAuthExceptions signal Google authentication errors that
can be recovered with user action, such as a user login.

This has worked decently well for me. Considering the fact that this question has not received any other answers in 2 years, there doesn't seem to be any method to fetch the information about whether the app is disconnected or not via an API or SDK call.

Here's the code I use

```<code>fun getGoogleDriveService(context: Context): Drive {
    val credential = GoogleAccountCredential.usingOAuth2(context, setOf(DriveScopes.DRIVE_APPDATA))
    credential.selectedAccount = GoogleSignIn.getLastSignedInAccount(context)!!.account
    return Drive.Builder(NetHttpTransport(), GsonFactory(), credential)
            .setApplicationName(DriveSyncService.APP_NAME)
            .build()
}

try {
    val driveService = getGoogleDriveService(this)
    var fileList = driveService.files().list().execute()
    //...
    //more code
} catch (e: UserRecoverableAuthIOException) {
    /*
    Doing a sign-out on the googleSignInClient so that there is no mismatch
    in sign-in state and so that when I start sign-in process again, it
    starts afresh
    */
    googleSignInClient.signOut()
    /*
    Then I show a pop up telling user that app was disconnected and
    to sign in again. And then on click I start the sign-in flow again.
    */
} catch (e: GoogleJsonResponseException) {
    //https://googleapis.dev/java/google-api-client/latest/index.html?com/google/api/client/googleapis/json/GoogleJsonResponseException.html
    //404 is file being updated/deleted was not found
    if (e.message != null && e.message!!.contains("storageQuotaExceeded")) {
        //todo handle storage exceeded error. Inform user
    }
} catch (e: IOException) {
    //todo handle network error
}

</code>```

Body:
I'm building an app where I store app data in the app-specific-folder on Google Drive. I've been able to setup everything related to file storage and retrieval. The problem I'm facing is regarding permissions. The user has an option to disconnect the app from the Google Drive settings panel.

I use the DriveScopes.DRIVE_APPDATA meaning https://www.googleapis.com/auth/drive.appdata scope to save data.

I'm trying to figure out how to find out if this has happened on the app side. If I try to continue using the drive related apis, with the app being disconnected, then it crashes with a UserRecoverableAuthException.

com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException
    at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:297)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:868)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:476)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:409)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:526)
    at abhiank.maplocs.ui.drivesync.DriveSyncService.onHandleIntent(DriveSyncService.kt:68)
    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:78)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.os.HandlerThread.run(HandlerThread.java:67)
 Caused by: com.google.android.gms.auth.UserRecoverableAuthException: NeedPermission
    at com.google.android.gms.auth.zze.zzb(Unknown Source:13)
    at com.google.android.gms.auth.zzd.zza(Unknown Source:77)
    at com.google.android.gms.auth.zzd.zzb(Unknown Source:20)
    at com.google.android.gms.auth.zzd.getToken(Unknown Source:7)
    at com.google.android.gms.auth.zzd.getToken(Unknown Source:5)
    at com.google.android.gms.auth.zzd.getToken(Unknown Source:2)
    at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source:55)
    at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential.getToken(GoogleAccountCredential.java:267)
    at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:292)

I tried the following to figure out if the app does not have the permissions or scopes.

Look at data inside GoogleSignInAccount instance received from GoogleSignIn.getLastSignedInAccount(this). This had the following scopes available in account.grantedScopes() after app had been disconnected. drive.appdata is shown even though app is disconnected.

[https://www.googleapis.com/auth/drive.appdata, https://www.googleapis.com/auth/userinfo.profile, https://www.googleapis.com/auth/userinfo.email, openid, profile, email]

Last thing I tried was hasPermissions method available in GoogleSignIn. I checked if the APP_DATA scope was available with this call and it returned true. So no help there either.

GoogleSignIn.hasPermissions(account, Scope(DriveScopes.DRIVE_APPDATA))

I'm really stuck now. Any help will be really appreciated. Thanks.

Body:
I ended up using a try-catch around my drive related code and catching the UserRecoverableAuthIOException. According to the documentation, this is called when -

UserRecoverableAuthExceptions signal Google authentication errors that
can be recovered with user action, such as a user login.

This has worked decently well for me. Considering the fact that this question has not received any other answers in 2 years, there doesn't seem to be any method to fetch the information about whether the app is disconnected or not via an API or SDK call.

Here's the code I use

fun getGoogleDriveService(context: Context): Drive {
    val credential = GoogleAccountCredential.usingOAuth2(context, setOf(DriveScopes.DRIVE_APPDATA))
    credential.selectedAccount = GoogleSignIn.getLastSignedInAccount(context)!!.account
    return Drive.Builder(NetHttpTransport(), GsonFactory(), credential)
            .setApplicationName(DriveSyncService.APP_NAME)
            .build()
}

try {
    val driveService = getGoogleDriveService(this)
    var fileList = driveService.files().list().execute()
    //...
    //more code
} catch (e: UserRecoverableAuthIOException) {
    /*
    Doing a sign-out on the googleSignInClient so that there is no mismatch
    in sign-in state and so that when I start sign-in process again, it
    starts afresh
    */
    googleSignInClient.signOut()
    /*
    Then I show a pop up telling user that app was disconnected and
    to sign in again. And then on click I start the sign-in flow again.
    */
} catch (e: GoogleJsonResponseException) {
    //https://googleapis.dev/java/google-api-client/latest/index.html?com/google/api/client/googleapis/json/GoogleJsonResponseException.html
    //404 is file being updated/deleted was not found
    if (e.message != null && e.message!!.contains("storageQuotaExceeded")) {
        //todo handle storage exceeded error. Inform user
    }
} catch (e: IOException) {
    //todo handle network error
}


问:
Get all data, but show pending data first then Approved data and rejected data
I am writing a sql query in Laravel to fetch all the data for current year but condition is I want to get status -  Pending data first and Approved and Rejected data. According to 'status' = Pending/Approve and Reject?</p>
```<code>$leaves = Leave::whereRaw('YEAR(start_date) = YEAR(CURDATE()) AND YEAR(end_date)=YEAR(CURDATE())')
                 ->where('created_by', '=', \Auth::user()->creatorId())->get();
</code>```

答:
Try to add "orderBy()" before the "get()" method of the query.

Like this:

```<code>$leaves = Leave::whereRaw('YEAR(start_date) = YEAR(CURDATE()) AND YEAR(end_date)=YEAR(CURDATE())')
->where('created_by', '=', \Auth::user()->creatorId())
->orderBy('approved', 'desc')
->get();
</code>```

Note: Assuming approved as a column in your table where it has boolean value (0 or 1).

Body:
I am writing a sql query in Laravel to fetch all the data for current year but condition is I want to get status -  Pending data first and Approved and Rejected data. According to 'status' = Pending/Approve and Reject?

$leaves = Leave::whereRaw('YEAR(start_date) = YEAR(CURDATE()) AND YEAR(end_date)=YEAR(CURDATE())')
                 ->where('created_by', '=', \Auth::user()->creatorId())->get();

Body:
Try to add "orderBy()" before the "get()" method of the query.

Like this:

$leaves = Leave::whereRaw('YEAR(start_date) = YEAR(CURDATE()) AND YEAR(end_date)=YEAR(CURDATE())')
->where('created_by', '=', \Auth::user()->creatorId())
->orderBy('approved', 'desc')
->get();

Note: Assuming approved as a column in your table where it has boolean value (0 or 1).


问:
High memory usage in React Native FlatList
I am developing an app which allows the user to search for books and then display it in the search results. For displaying the results, I am using a FlatList with 3 columns and displaying the book cover and some basic information about the book.

I am storing the results from the API response in state without the comoponent. As more results are added, the memory consumption increases but the data is in JSON format, no images are store in state.

I have tried, using removeClippedSubviews and few other options that allow setting the window size but that has little to no difference on the memory usage.

Am I missing something here or is there a way to optimise this? Sample code is uploaded to this github repo

Here is the code snippet I am using:

```<code>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import type { Node } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import {
    ActivityIndicator,
    FlatList,
    Platform,
    SafeAreaView,
    StatusBar,
    StyleSheet,
    useColorScheme,
    View,
} from 'react-native';
import { Button, SearchBar, useTheme } from 'react-native-elements';
import { searchBooks } from './api/GoogleBooksService';
import HttpClient from './network/HttpClient';
import BookCard from './components/BookCard';

const searchParamsInitialState = {
    startIndex: 1,
    maxResults: 12,
    totalItems: null,
};

let debounceTimer;
const debounce = (callback, time) => {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(callback, time);
};

const isEndOfList = searchParams => {
    const { startIndex, maxResults, totalItems } = searchParams;
    if (totalItems == null) {
        return false;
    }
    console.log('isEndOfList', totalItems - (startIndex - 1 + maxResults) < 0);
    return totalItems - (startIndex - 1 + maxResults) < 0;
};

const App: () => Node = () => {
    const isDarkMode = useColorScheme() === 'dark';
    const [isLoading, setIsLoading] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [globalSearchResults, setGlobalSearchResults] = useState([]);
    const [searchParams, setSearchParams] = useState(searchParamsInitialState);

    let searchCancelToken;
    let searchCancelTokenSource;

    // This ref will be used to track if the search Term has changed when tab is switched
    const searchRef = useRef();

    const clearSearch = () => {
        console.log('Clear everything!');
        searchRef.current = null;
        setGlobalSearchResults([]);
        setSearchParams(searchParamsInitialState);
        setIsLoading(false);
        searchCancelTokenSource?.cancel();
        searchCancelToken = null;
        searchCancelTokenSource = null;
    };

    useEffect(() => {
        debounce(async () => {
            setIsLoading(true);
            await searchGlobal(searchTerm);
            setIsLoading(false);
        }, 1000);
    }, [searchTerm]);

    /**
     * Search method
     */
    const searchGlobal = async text => {
        if (!text) {
            // Clear everything
            clearSearch();
            return;
        }
        setIsLoading(true);
        try {
            // Use the initial state values if the search term has changed
            let params = searchParams;
            if (searchRef.current !== searchTerm) {
                params = searchParamsInitialState;
            }

            const { items, totalItems } = await searchBooks(
                text,
                params.startIndex,
                params.maxResults,
                searchCancelTokenSource?.token,
            );
            if (searchRef.current === searchTerm) {
                console.log('Search term has not changed. Appending data');
                setGlobalSearchResults(prevState => prevState.concat(items));
                setSearchParams(prevState => ({
                    ...prevState,
                    startIndex: prevState.startIndex + prevState.maxResults,
                    totalItems,
                }));
            } else {
                console.log(
                    'Search term has changed. Updating data',
                    searchTerm,
                );
                if (!searchTerm) {
                    console.log('!searchTerm', searchTerm);
                    clearSearch();
                    return;
                }
                setGlobalSearchResults(items);
                setSearchParams({
                    ...searchParamsInitialState,
                    startIndex:
                        searchParamsInitialState.startIndex +
                        searchParamsInitialState.maxResults,
                    totalItems,
                });
            }
            searchRef.current = text;
        } catch (err) {
            if (HttpClient.isCancel(err)) {
                console.error('Cancelled', err.message);
            }
            console.error(`Error searching for "${text}"`, err);
        }
        setIsLoading(false);
    };

    const renderGlobalItems = ({ item }) => {
        return <BookCard book={item} />;
    };

    const { theme } = useTheme();

    return (
        <SafeAreaView style={styles.backgroundStyle}>
            <StatusBar
                barStyle={isDarkMode ? 'light-content' : 'dark-content'}
            />
            <View style={styles.container}>
                <SearchBar
                    showLoading={isLoading}
                    placeholder="Enter search term here"
                    onChangeText={text => {
                        setSearchTerm(text);
                    }}
                    value={searchTerm}
                    platform={Platform.OS}
                />
                {isLoading && globalSearchResults.length <= 0 && (
                    <ActivityIndicator animating style={styles.loader} />
                )}
                {globalSearchResults.length > 0 && (
                    <FlatList
                        removeClippedSubviews
                        columnWrapperStyle={styles.columnWrapper}
                        data={globalSearchResults}
                        numColumns={3}
                        showsHorizontalScrollIndicator={false}
                        keyExtractor={item => item + item.id}
                        renderItem={renderGlobalItems}
                        ListFooterComponent={
                            <>
                                {!isLoading &&
                                    !isEndOfList(searchParams) &&
                                    searchParams.totalItems > 0 && (
                                        <Button
                                            type="clear"
                                            title="Load more..."
                                            onPress={async () => {
                                                await searchGlobal(searchTerm);
                                            }}
                                        />
                                    )}
                                {isLoading && searchParams.totalItems != null && (
                                    <ActivityIndicator
                                        size="large"
                                        style={{
                                            justifyContent: 'center',
                                        }}
                                        color={theme.colors.primary}
                                    />
                                )}
                            </>
                        }
                    />
                )}
            </View>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    backgroundStyle: 'white',
    container: {
        height: '100%',
        width: '100%',
    },
    columnWrapper: {
        flex: 1,
    },
    loader: {
        flex: 1,
        justifyContent: 'center',
    },
});

export default App;

</code>```

答:
There is something called PureComponent in react native. If you create FlatList as PureComponent, you can see lot of improvement.

It will not rerender items until data has been changed.

for example:

```<code>class MyList extends React.PureComponent {

}
</code>```

For more reference check this

Body:
I am developing an app which allows the user to search for books and then display it in the search results. For displaying the results, I am using a FlatList with 3 columns and displaying the book cover and some basic information about the book.

I am storing the results from the API response in state without the comoponent. As more results are added, the memory consumption increases but the data is in JSON format, no images are store in state.

I have tried, using removeClippedSubviews and few other options that allow setting the window size but that has little to no difference on the memory usage.

Am I missing something here or is there a way to optimise this? Sample code is uploaded to this github repo

Here is the code snippet I am using:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import type { Node } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import {
    ActivityIndicator,
    FlatList,
    Platform,
    SafeAreaView,
    StatusBar,
    StyleSheet,
    useColorScheme,
    View,
} from 'react-native';
import { Button, SearchBar, useTheme } from 'react-native-elements';
import { searchBooks } from './api/GoogleBooksService';
import HttpClient from './network/HttpClient';
import BookCard from './components/BookCard';

const searchParamsInitialState = {
    startIndex: 1,
    maxResults: 12,
    totalItems: null,
};

let debounceTimer;
const debounce = (callback, time) => {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(callback, time);
};

const isEndOfList = searchParams => {
    const { startIndex, maxResults, totalItems } = searchParams;
    if (totalItems == null) {
        return false;
    }
    console.log('isEndOfList', totalItems - (startIndex - 1 + maxResults) < 0);
    return totalItems - (startIndex - 1 + maxResults) < 0;
};

const App: () => Node = () => {
    const isDarkMode = useColorScheme() === 'dark';
    const [isLoading, setIsLoading] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [globalSearchResults, setGlobalSearchResults] = useState([]);
    const [searchParams, setSearchParams] = useState(searchParamsInitialState);

    let searchCancelToken;
    let searchCancelTokenSource;

    // This ref will be used to track if the search Term has changed when tab is switched
    const searchRef = useRef();

    const clearSearch = () => {
        console.log('Clear everything!');
        searchRef.current = null;
        setGlobalSearchResults([]);
        setSearchParams(searchParamsInitialState);
        setIsLoading(false);
        searchCancelTokenSource?.cancel();
        searchCancelToken = null;
        searchCancelTokenSource = null;
    };

    useEffect(() => {
        debounce(async () => {
            setIsLoading(true);
            await searchGlobal(searchTerm);
            setIsLoading(false);
        }, 1000);
    }, [searchTerm]);

    /**
     * Search method
     */
    const searchGlobal = async text => {
        if (!text) {
            // Clear everything
            clearSearch();
            return;
        }
        setIsLoading(true);
        try {
            // Use the initial state values if the search term has changed
            let params = searchParams;
            if (searchRef.current !== searchTerm) {
                params = searchParamsInitialState;
            }

            const { items, totalItems } = await searchBooks(
                text,
                params.startIndex,
                params.maxResults,
                searchCancelTokenSource?.token,
            );
            if (searchRef.current === searchTerm) {
                console.log('Search term has not changed. Appending data');
                setGlobalSearchResults(prevState => prevState.concat(items));
                setSearchParams(prevState => ({
                    ...prevState,
                    startIndex: prevState.startIndex + prevState.maxResults,
                    totalItems,
                }));
            } else {
                console.log(
                    'Search term has changed. Updating data',
                    searchTerm,
                );
                if (!searchTerm) {
                    console.log('!searchTerm', searchTerm);
                    clearSearch();
                    return;
                }
                setGlobalSearchResults(items);
                setSearchParams({
                    ...searchParamsInitialState,
                    startIndex:
                        searchParamsInitialState.startIndex +
                        searchParamsInitialState.maxResults,
                    totalItems,
                });
            }
            searchRef.current = text;
        } catch (err) {
            if (HttpClient.isCancel(err)) {
                console.error('Cancelled', err.message);
            }
            console.error(`Error searching for "${text}"`, err);
        }
        setIsLoading(false);
    };

    const renderGlobalItems = ({ item }) => {
        return <BookCard book={item} />;
    };

    const { theme } = useTheme();

    return (
        <SafeAreaView style={styles.backgroundStyle}>
            <StatusBar
                barStyle={isDarkMode ? 'light-content' : 'dark-content'}
            />
            <View style={styles.container}>
                <SearchBar
                    showLoading={isLoading}
                    placeholder="Enter search term here"
                    onChangeText={text => {
                        setSearchTerm(text);
                    }}
                    value={searchTerm}
                    platform={Platform.OS}
                />
                {isLoading && globalSearchResults.length <= 0 && (
                    <ActivityIndicator animating style={styles.loader} />
                )}
                {globalSearchResults.length > 0 && (
                    <FlatList
                        removeClippedSubviews
                        columnWrapperStyle={styles.columnWrapper}
                        data={globalSearchResults}
                        numColumns={3}
                        showsHorizontalScrollIndicator={false}
                        keyExtractor={item => item + item.id}
                        renderItem={renderGlobalItems}
                        ListFooterComponent={
                            <>
                                {!isLoading &&
                                    !isEndOfList(searchParams) &&
                                    searchParams.totalItems > 0 && (
                                        <Button
                                            type="clear"
                                            title="Load more..."
                                            onPress={async () => {
                                                await searchGlobal(searchTerm);
                                            }}
                                        />
                                    )}
                                {isLoading && searchParams.totalItems != null && (
                                    <ActivityIndicator
                                        size="large"
                                        style={{
                                            justifyContent: 'center',
                                        }}
                                        color={theme.colors.primary}
                                    />
                                )}
                            </>
                        }
                    />
                )}
            </View>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    backgroundStyle: 'white',
    container: {
        height: '100%',
        width: '100%',
    },
    columnWrapper: {
        flex: 1,
    },
    loader: {
        flex: 1,
        justifyContent: 'center',
    },
});

export default App;

Body:
There is something called PureComponent in react native. If you create FlatList as PureComponent, you can see lot of improvement.

It will not rerender items until data has been changed.

for example:

class MyList extends React.PureComponent {

}

For more reference check this


问:
What's the proper configuration or routing so that Default.aspx, "", and "~/" don't get routed?
I've got glimpse.

it's highlighting an empty line on the routes tab

Match Area Url Data constraints DataTokens

True  Root  -- --

Locally it seems cassini doesn't properly emulate a virtual directory so changing from localhost to localhost/site doesn't seem to grant any additional testing insight.

Local testing

cassini (windows 7 (32 and 64 bit are available))

doesn't seem to use or allow integrated

deploy environments

IIS7 Integrated

Tried a http routing setting to push / to /site however I ran into trailing slash issues (/site would route to /site/site, while /site/ would work as expected

web.config

tried a few ways of setting runAllManagedModules=false with various errors

using <remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" /> that was linked

tried

I need /site (/~) requests to go to ~/Default.aspx
would love for a way to have / go there as well.

How do I do it?

答:
To enable Default.aspx as the default url you just need to remove your route handling so that there's no catch-all route.

By default all MVC 3 projects have:

```<code>routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
</code>```

This is a catch-all route that will match everything you pass in your url. If you remove this and no path is defined then it will use whatever you set up as your default page in your web.config.

To map /site to Default.aspx you just need to add a special route:

```<code>routes.MapPageRoute("SitetoDefault", "site", "~/Default.aspx");
</code>```

This will see the /site and route it to your default page.

You'll have to be careful when adding any other routes to your routing table. All of them will have to have a controller defined or you'll have to add a routing constraint. Something like this:

```<code>//controller defined
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

//route constraint
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new {
        controller = "Home",
        action = "Index",
        id = UrlParameter.Optional
    }, // Parameter defaults
    new { controller = "^(products)|(account)|(home)$" }
);
</code>```

Here is more detail on creating more complex routing: http://www.asp.net/mvc/tutorials/creating-a-custom-route-constraint-cs

Body:
To enable Default.aspx as the default url you just need to remove your route handling so that there's no catch-all route.

By default all MVC 3 projects have:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

This is a catch-all route that will match everything you pass in your url. If you remove this and no path is defined then it will use whatever you set up as your default page in your web.config.

To map /site to Default.aspx you just need to add a special route:

routes.MapPageRoute("SitetoDefault", "site", "~/Default.aspx");

This will see the /site and route it to your default page.

You'll have to be careful when adding any other routes to your routing table. All of them will have to have a controller defined or you'll have to add a routing constraint. Something like this:

//controller defined
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

//route constraint
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new {
        controller = "Home",
        action = "Index",
        id = UrlParameter.Optional
    }, // Parameter defaults
    new { controller = "^(products)|(account)|(home)$" }
);

Here is more detail on creating more complex routing: http://www.asp.net/mvc/tutorials/creating-a-custom-route-constraint-cs


问:
SQL: Create pivot table to aggregate data by month and year from timestamp
I have 3 columns in my data set.

email

first name

unsubscribe date (timestamp)

How can i create a pivot table in SQL to have years on the left in rows, and months in columns and count the number of people who unsubscribed by month and year?

Thanks for the help

答: Unfortunately, you can't.  Timestamp is poorly named, and has nothing to do with the time the person unsubscribed.</p>


问:
How can I change the accessible name of the "OK" hamburger button in an app built from the Xamarin AppShell template?
I've built a Xamarin Android app based on the Xamarin AppShell template in VS. The hamburger button which invokes the flyout gets announced by the TalkBack screen reader as having a name of "OK". This doesn't seem a good match for the purpose of the button, perhaps a name of "Menu" would be more helpful. I've not found a way to change the AutomationProperties.Name of the hamburger button.

How can I change the hamburger button such that TalkBack announces it as the "Menu" button?

答:
In the Android, there is a property named toolbar.NavigationContentDescription for the hamburger button in the app shell. You can set it by a custom shell renderer.

custom shell renderer :https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/customrenderers

And set the property

```<code> public class MyShellToolbarAppearanceTracker : ShellToolbarAppearanceTracker
{
    public MyShellToolbarAppearanceTracker(IShellContext context) : base(context)
    {
    }

    public override void SetAppearance(Toolbar toolbar, IShellToolbarTracker toolbarTracker, ShellAppearance appearance)
    {
        base.SetAppearance(toolbar, toolbarTracker, appearance);
        // I had debug the value of description and it's "ok".
       // string description = toolbar.NavigationContentDescription;
        toolbar.NavigationContentDescription = "menu";
    }
}
</code>```

Body:
In the Android, there is a property named toolbar.NavigationContentDescription for the hamburger button in the app shell. You can set it by a custom shell renderer.

custom shell renderer :https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/shell/customrenderers

And set the property

 public class MyShellToolbarAppearanceTracker : ShellToolbarAppearanceTracker
{
    public MyShellToolbarAppearanceTracker(IShellContext context) : base(context)
    {
    }

    public override void SetAppearance(Toolbar toolbar, IShellToolbarTracker toolbarTracker, ShellAppearance appearance)
    {
        base.SetAppearance(toolbar, toolbarTracker, appearance);
        // I had debug the value of description and it's "ok".
       // string description = toolbar.NavigationContentDescription;
        toolbar.NavigationContentDescription = "menu";
    }
}


问:
Copy files generated inside docker container to local host through docker-compose
I have an app which will create a directory storage inside the docker container and store generated files there. I would like these files & sub-folders (inside the storage directory) to get copied to the host directory test.

The directory of the container:

```<code># sudo docker exec -it eajcdfufh /bin/bash
root#eajcdfufh:~# ls
storage
root#eajcdfufh:~ cd storage
folder1        file1
</code>```

To achieve this operation, I have tried to key in volumes params but unfortunately nothing gets copied to local directory.

docker-compose.yml

version: "3.9"
services:
  app:
    build:
        context: ./
    volumes:
        - /home/test:/root/storage
    ports:
        - "8000:8000"

  nginx:
    restart: always
    build:
        context: ./nginx
    ports:
      - "80:80"
    depends_on:
      - app
```

May I ask why does nothing gets copied ? And how can I perform such operations?

Thanks, would highly appreciate the help!!!

答:
```<code>version: "3.9"
services:
  app:
    build:
    context: ./
    volumes:
    - ./test:/root/storage
    ports:
    - "8000:8000"

  nginx:
    restart: always
    build:
    context: ./nginx
    ports:
      - "80:80"
    depends_on:
      - app
</code>```

This should work

Body:
I have an app which will create a directory storage inside the docker container and store generated files there. I would like these files & sub-folders (inside the storage directory) to get copied to the host directory test.

The directory of the container:

# sudo docker exec -it eajcdfufh /bin/bash
root#eajcdfufh:~# ls
storage
root#eajcdfufh:~ cd storage
folder1        file1

To achieve this operation, I have tried to key in volumes params but unfortunately nothing gets copied to local directory.

docker-compose.yml

version: "3.9"
services:
  app:
    build:
        context: ./
    volumes:
        - /home/test:/root/storage
    ports:
        - "8000:8000"

  nginx:
    restart: always
    build:
        context: ./nginx
    ports:
      - "80:80"
    depends_on:
      - app

May I ask why does nothing gets copied ? And how can I perform such operations?

Thanks, would highly appreciate the help!!!

Body:
version: "3.9"
services:
  app:
    build:
    context: ./
    volumes:
    - ./test:/root/storage
    ports:
    - "8000:8000"

  nginx:
    restart: always
    build:
    context: ./nginx
    ports:
      - "80:80"
    depends_on:
      - app

This should work


问:
"gs: symbol lookup error: /lib64/libgs.so.9: undefined symbol: FT_Property_Set" Error when converting .ai file to .png with ghostscript 9.25
I'm using ImageMagick with ghostscript 9.25 to convert images. When I try to convert .ai file to .png with image magic I'm getting the below error in command line

My command ./convert /home/sample_ai_file2.ai /home/ai_out.png

```<code>gs: /opt/software/alfresco-one/common/lib/libtiff.so.5: no version information available (required by /lib64/libgs.so.9)
gs: /opt/software/alfresco-one/common/lib/libjpeg.so.62: no version information available (required by /lib64/libgs.so.9)
gs: symbol lookup error: /lib64/libgs.so.9: undefined symbol: FT_Property_Set
.convert.bin: NoImagesForWrite '-write' '/home/sshtest/ai_out.png' at CLI arg 2 @ error/operation.c/CLINoImageOperator/4769.
.convert.bin: NoImageForProperty "%w" @ warning/property.c/GetMagickPropertyLetter/2561.
.convert.bin: UnknownImageProperty "%w" @ warning/property.c/InterpretImageProperties/3499.
.convert.bin: NoImageForProperty "%h" @ warning/property.c/GetMagickPropertyLetter/2449.
.convert.bin: UnknownImageProperty "%h" @ warning/property.c/InterpretImageProperties/3499.
.convert.bin: NoImageForProperty "%m" @ warning/property.c/GetMagickPropertyLetter/2480.
.convert.bin: UnknownImageProperty "%m" @ warning/property.c/InterpretImageProperties/3499.
</code>```

Does any one know the reason for this error ? I can convert all the other image types without any issue.

答:
I was able to find the cause for the above mentioned issue. The error was due to having two versions of GS installed in my system.
When I install ImageMagick, GS 8.64 is also automatically installed by default, then I have again manually installed GS 9.25.
Removing the GS 9.25 resolved my issue.</p>

Body:
I'm using ImageMagick with ghostscript 9.25 to convert images. When I try to convert .ai file to .png with image magic I'm getting the below error in command line

My command ./convert /home/sample_ai_file2.ai /home/ai_out.png

gs: /opt/software/alfresco-one/common/lib/libtiff.so.5: no version information available (required by /lib64/libgs.so.9)
gs: /opt/software/alfresco-one/common/lib/libjpeg.so.62: no version information available (required by /lib64/libgs.so.9)
gs: symbol lookup error: /lib64/libgs.so.9: undefined symbol: FT_Property_Set
.convert.bin: NoImagesForWrite '-write' '/home/sshtest/ai_out.png' at CLI arg 2 @ error/operation.c/CLINoImageOperator/4769.
.convert.bin: NoImageForProperty "%w" @ warning/property.c/GetMagickPropertyLetter/2561.
.convert.bin: UnknownImageProperty "%w" @ warning/property.c/InterpretImageProperties/3499.
.convert.bin: NoImageForProperty "%h" @ warning/property.c/GetMagickPropertyLetter/2449.
.convert.bin: UnknownImageProperty "%h" @ warning/property.c/InterpretImageProperties/3499.
.convert.bin: NoImageForProperty "%m" @ warning/property.c/GetMagickPropertyLetter/2480.
.convert.bin: UnknownImageProperty "%m" @ warning/property.c/InterpretImageProperties/3499.

Does any one know the reason for this error ? I can convert all the other image types without any issue.


问:
Why getExternalCacheDir() return null?
I am using two devices having internal memory and SD card. But in one device i am getting null value when executing context.getExternalCacheDir().

What is the reason for that?

Is it possible to make ExternalCacheDir by calling
  context.getExternalCacheDir().mkdir();

答: Check READ_EXTERNAL_STORAGE permission before</p>

Title: Why getExternalCacheDir() return null?


问:
Optimizing Performance of a Large Dataset in SQL Server
I'm using SQL Server running on an Azure VM with 8 SSDs. The SSDs are grouped together in Storage Spaces as 1 disk - in order to increase the capacity and also to combine the IOPS/Throughput. But the "combine the IOPS" part just doesn't seem to be working as far as I can tell by all of my tests/benchmarks (the "combine the throughput" part is working though). In fact, it looks like the SSD performance (IOPS) are better on 1 single disk than the whole 8-physical-disk virtual disk. So, I'm thinking about just forgetting about Storage Spaces and splitting up my data across 8 disks.

But what would be the best way to do that? (I don't have much experience with mulitple files, or filegroups, or partitioning tables, and that sort of thing.)

Just make 8 mdf files (1 on each disk) and let SQL Server redistribute the data across all of these files? If so, I would like to know how SQL Server knows which disk a given record is on. Would doing this speed things up?

And maybe split up the ldf files too?

What about multiple filegroups? I really don't know what the practical difference is between multiple files and filegroups.

What about splitting up the big tables somehow by using a partitioning function? Would that help, since now, maybe, SQL Server would "have a better idea" of where (in which file) a given record would be - since that is defined by a partition function?

Please don't try to close this question because it seems very general or open-ended.  Life is tough enough as it is. This is a very good question. And I'm sure there are a lot of people out there who could give very helpful, experienced answers to this which would help a lot of people. Just because there might not be one exact answer to this question, doesn't mean it's a bad question. And anyway, if you think about it, there IS one best answer to this question - there is a best way to do things in this - very common - situation.

答:
The details you are asking in a single thread require too much of depth research. The use case varies from project to project.

I recommend you to go in-depth on Storage: Performance best practices for SQL Server on Azure VMs, Microsoft's official document. Go through the Checklist details. Refer the disk type most suitable for your use case based on IOPS. You will get the answers to all your queries within this document.


问:
Get command prompt via "sudo su -" then run command using Paramiko exec_command
Could you help me with following.
I need to login as user then sudo su - then run command ex. parted -l using Paramiko exec_command
when I run following code it hangs. Please let me know how I can check before gets to hanged.

```<code>with SSHClient() as client:
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('172.20.xxx.xx', port=22, username='xxx', password='xxxxxxx',timeout=15.0)
    transport = client.get_transport()
    session = transport.open_session()
    session.set_combine_stderr(True)
    session.get_pty()
    session.exec_command('sudo su -')
    time.sleep(5)
    stdin = session.makefile('wb', -1)
    stdout = session.makefile('rb', -1)
    stderr = session.makefile_stderr('rb', -1)
    stdin.write('xxxxxxx' + '\n')
    stdin.flush()
    session.exec_command('parted -l')
    time.sleep(5)
    stdin = session.makefile('wb', -1)
    stdout = session.makefile('rb', -1)
    stderr = session.makefile_stderr('rb', -1)
    stdin.flush()
    for line in stdout.read().splitlines():
        print 'LINE: %s' % (line)
</code>```

答:
Do you want to check result of the individual parted command? If you want to check results of individual commands, do not run shell (su in this case). Run the command only:

```<code>sudo su -c "parted -l"
</code>```

See also Executing command using "su -l" in SSH using Python

Then you can use recv_exit_status():

How can you get the SSH return code using Paramiko?

If you want to keep your current approach for whatever reason, see:

Execute multiple dependent commands individually with Paramiko and find out when each command finishes

Combining interactive shell and recv_exit_status method using Paramiko

Body:
Could you help me with following.
I need to login as user then sudo su - then run command ex. parted -l using Paramiko exec_command
when I run following code it hangs. Please let me know how I can check before gets to hanged.

with SSHClient() as client:
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('172.20.xxx.xx', port=22, username='xxx', password='xxxxxxx',timeout=15.0)
    transport = client.get_transport()
    session = transport.open_session()
    session.set_combine_stderr(True)
    session.get_pty()
    session.exec_command('sudo su -')
    time.sleep(5)
    stdin = session.makefile('wb', -1)
    stdout = session.makefile('rb', -1)
    stderr = session.makefile_stderr('rb', -1)
    stdin.write('xxxxxxx' + '\n')
    stdin.flush()
    session.exec_command('parted -l')
    time.sleep(5)
    stdin = session.makefile('wb', -1)
    stdout = session.makefile('rb', -1)
    stderr = session.makefile_stderr('rb', -1)
    stdin.flush()
    for line in stdout.read().splitlines():
        print 'LINE: %s' % (line)

Body:
Do you want to check result of the individual parted command? If you want to check results of individual commands, do not run shell (su in this case). Run the command only:

sudo su -c "parted -l"

See also Executing command using "su -l" in SSH using Python

Then you can use recv_exit_status():

How can you get the SSH return code using Paramiko?

If you want to keep your current approach for whatever reason, see:

Execute multiple dependent commands individually with Paramiko and find out when each command finishes

Combining interactive shell and recv_exit_status method using Paramiko


问:
Change brightness of JUST the background with CSS
I want to change the brightness of a DIV's background, without affected the other contents in a div.

When I apply a hover brightness filter on the div, other elements in it are also affected. Which I do not want.

The other solution I have is simply replacing the background of the div with a photo edited one. But that asks for double the storage, which I do not like.

Is there a way to change just the brightness of the background-image?

JSFIDDLE

```<code>    <div id="replace">
    <div id="transparent">
        <span id="text">Random unaffected text</span>
    </div>
</div>

    <div id="brightnessfilter">
    <div id="transparent">
        <span id="text">Random AFFECTED text (it glows)</span>
    </div>
</div>

#replace {
width:700px;
height:465px;
background-image:url('http://i42.tinypic.com/351dff5.jpg');
}

#brightnessfilter {
    width:700px;
    height:465px;
    background-image:url('http://i42.tinypic.com/351dff5.jpg');
}

#brightnessfilter:hover {
     -webkit-filter: brightness(1.3);
-moz-filter: brightness(1.3);
-o-filter:  brightness(1.3);
-ms-filter:  brightness(1.3);
}

#transparent {
    position:relative;
    top:400px;
    width:700px;
    height:65px;
    background-color:rgba(0,0,0,.5);
    border-radius:8px;
}

#text {
    color:white;
    font-weight:bold;
    position:relative;
    top:9px;
    left:9px;
    font-size:16px;
}

#replace:hover {
    background-image:url('http://i40.tinypic.com/2cft7dl.jpg');
}
</code>```

Above here is a link to a fiddle with my two attempts at creating the desired effect. But both have a disadvantage in using it.

Thanks in advance!

答:
I Used this tricks for my self

.demo-wrap {
  overflow: hidden;
  position: relative;
}

.demo-bg {
  opacity: 0.6;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: auto;
}

.demo-content {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="demo-wrap">
  <img
    class="demo-bg"
    src="https://assets.digitalocean.com/labs/images/community_bg.png"
    alt=""
  >
  <div class="demo-content">
    <h1>Hello World!</h1>
  </div>
</div></code>```

https://www.digitalocean.com/community/tutorials/how-to-change-a-css-background-images-opacity

Body:
I want to change the brightness of a DIV's background, without affected the other contents in a div.

When I apply a hover brightness filter on the div, other elements in it are also affected. Which I do not want.

The other solution I have is simply replacing the background of the div with a photo edited one. But that asks for double the storage, which I do not like.

Is there a way to change just the brightness of the background-image?

JSFIDDLE

        Random unaffected text

        Random AFFECTED text (it glows)

#replace {
width:700px;
height:465px;
background-image:url('http://i42.tinypic.com/351dff5.jpg');
}

#brightnessfilter {
    width:700px;
    height:465px;
    background-image:url('http://i42.tinypic.com/351dff5.jpg');
}

#brightnessfilter:hover {
     -webkit-filter: brightness(1.3);
-moz-filter: brightness(1.3);
-o-filter:  brightness(1.3);
-ms-filter:  brightness(1.3);
}

#transparent {
    position:relative;
    top:400px;
    width:700px;
    height:65px;
    background-color:rgba(0,0,0,.5);
    border-radius:8px;
}

#text {
    color:white;
    font-weight:bold;
    position:relative;
    top:9px;
    left:9px;
    font-size:16px;
}

#replace:hover {
    background-image:url('http://i40.tinypic.com/2cft7dl.jpg');
}

Above here is a link to a fiddle with my two attempts at creating the desired effect. But both have a disadvantage in using it.

Thanks in advance!

Body:
I Used this tricks for my self

.demo-wrap {
  overflow: hidden;
  position: relative;
}

.demo-bg {
  opacity: 0.6;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: auto;
}

.demo-content {
  position: relative;
}

<div class="demo-wrap">
  <img
    class="demo-bg"
    src="https://assets.digitalocean.com/labs/images/community_bg.png"
    alt=""
  >
  <div class="demo-content">
    <h1>Hello World!</h1>
  </div>
</div>

https://www.digitalocean.com/community/tutorials/how-to-change-a-css-background-images-opacity


问:
How can I write a where clause in SQL to filter a DATETIME column by the time of day?
I have data that is timestamped with a DATETIME column and I want to filter it down to the set of records where the DATETIME is between 9:30am and 5:30pm for any day.  What's the best way to do this?

UPDATE: Changed because I need precision to the minute, not just hour.  Sorry about that.

OwnerDisplayName: Bialecki

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Milen A. Radev

Body:
You could always write it as a User Defined Function, particularly if you need to do this regularly

CREATE function  dbo.timepart (@date as SMALLDATETIME)
RETURNS SMALLDATETIME
AS
BEGIN
    RETURN @date - DATEADD(d, DATEDIFF(d,0,@date), 0)
END

and then use like so

SELECT * FROM table
WHERE dbo.timepart(date_field) BETWEEN '9:30' AND '17:30'

Tested with the following in SQL Server 2005

DECLARE @dates TABLE (date DATETIME)

DECLARE @date DATETIME
SET @date = '20 MAR 2009'

WHILE @date < '22 MAR 2009'
    BEGIN
        INSERT INTO @dates VALUES(@date)
        SET @date = DATEADD(hour, 1, @date)
    END

SELECT *
FROM
    @dates
WHERE
    dbo.timepart(date) BETWEEN '9:30' AND '17:30'

results in

date
-----------------------
2009-03-20 10:00:00.000
2009-03-20 11:00:00.000
2009-03-20 12:00:00.000
2009-03-20 13:00:00.000
2009-03-20 14:00:00.000
2009-03-20 15:00:00.000
2009-03-20 16:00:00.000
2009-03-20 17:00:00.000
2009-03-21 10:00:00.000
2009-03-21 11:00:00.000
2009-03-21 12:00:00.000
2009-03-21 13:00:00.000
2009-03-21 14:00:00.000
2009-03-21 15:00:00.000
2009-03-21 16:00:00.000
2009-03-21 17:00:00.000

OwnerDisplayName: Russ Cam

LastEditorDisplayName: Russ Cam


问:
Remove specific file from directory using shell script
I am trying to write a script to delete a file from a folder using shell script.

I am new to shell scripting and I tried to write one shell script program to delete a specific file from the directory.
here is the sample program that I tried and I want to delete specific jar from REPORT_HOME/lib folder.

```<code>    set OLD_DIR=%cd%
echo %REPORT_HOME%
set REPORT_HOME=%REPORT_HOME%\REPORT_HOME
cd %REPORT_HOME%\lib
if [ -f antlr-2.7.7.jar ]; then
   rm -rf "antlr-2.7.7.jar"
cd %OLD_DIR%
</code>```

Here REPORT_HOME is the environment variable that I set and lib is the folder from which I want to delete antlr-2.7.7.jar file.

From the command prompt, I can directly delete the specific file but I want to delete the file by running the shell script from command prompt only.

After running the above sh file from the command prompt that specific file is not getting deleted.

答:
You are mixing in Windows CMD syntax. The proper sh script would look like

```<code>OLD_DIR=$(pwd)
echo "$REPORT_HOME"
REPORT_HOME="$REPORT_HOME/REPORT_HOME"
cd "$REPORT_HOME/lib"
if [ -f antlr-2.7.7.jar ]; then
   rm -rf "antlr-2.7.7.jar"
cd "$OLD_DIR"
</code>```

However, this is humongously overcomplicated. To delete the file, just

```<code>rm -f "$REPORT_HOME/REPORT_HOME/lib/antlr-2.7.7.jar"
</code>```

The -f flag says to just proceed without an error if the file doesn't exist (and also proceed without asking if there are permissions which would otherwise cause rm to prompt for a confirmation).

Perhaps see also What exactly is current working directory?

This assumes that the variable REPORT_DIR isn't empty, and doesn't start with a dash. For maximal robustness, try

```<code>rm -f -- "${REPORT_HOME?variable must be set}/REPORT_HOME/lib/antlr-2.7.7.jar"
</code>```

Body:
I am trying to write a script to delete a file from a folder using shell script.

I am new to shell scripting and I tried to write one shell script program to delete a specific file from the directory.
here is the sample program that I tried and I want to delete specific jar from REPORT_HOME/lib folder.

    set OLD_DIR=%cd%
echo %REPORT_HOME%
set REPORT_HOME=%REPORT_HOME%\REPORT_HOME
cd %REPORT_HOME%\lib
if [ -f antlr-2.7.7.jar ]; then
   rm -rf "antlr-2.7.7.jar"
cd %OLD_DIR%

Here REPORT_HOME is the environment variable that I set and lib is the folder from which I want to delete antlr-2.7.7.jar file.

From the command prompt, I can directly delete the specific file but I want to delete the file by running the shell script from command prompt only.

After running the above sh file from the command prompt that specific file is not getting deleted.

Body:
You are mixing in Windows CMD syntax. The proper sh script would look like

OLD_DIR=$(pwd)
echo "$REPORT_HOME"
REPORT_HOME="$REPORT_HOME/REPORT_HOME"
cd "$REPORT_HOME/lib"
if [ -f antlr-2.7.7.jar ]; then
   rm -rf "antlr-2.7.7.jar"
cd "$OLD_DIR"

However, this is humongously overcomplicated. To delete the file, just

rm -f "$REPORT_HOME/REPORT_HOME/lib/antlr-2.7.7.jar"

The -f flag says to just proceed without an error if the file doesn't exist (and also proceed without asking if there are permissions which would otherwise cause rm to prompt for a confirmation).

Perhaps see also What exactly is current working directory?

This assumes that the variable REPORT_DIR isn't empty, and doesn't start with a dash. For maximal robustness, try

rm -f -- "${REPORT_HOME?variable must be set}/REPORT_HOME/lib/antlr-2.7.7.jar"


问:
get total sum of Interactive Grid Column Oracle APEX
I have one interactive grid and i want to sum the amount at bottom, i have created aggregate on report but the values are not changing in the interactive grid,  how to get total sum of Interactive Grid  Amount Column values</p>

答:
You don't have to do anything special; using the Actions menu, go to Data and then Aggregate. Choose column you want to sum and - that's it:

Aha; as you commented, you want to refresh that value once you change something in the grid.

You could create a dynamic action on the Interactive Grid region.

Event: Save [Interactive Grid]

Selection Type: Region

Region: put region name here, e.g. "IG emp" or whatever that region is named on your page

True action will then be:

Action: Refresh

Selection type: Region

Region: as above ("IG emp")

That's it - run the page, change some value, push the "Save" button - the total value should now change.


问:
How to create an array without declaring the size in C?
I'm trying to create a int and a float array without a size (it might be 0 or it might increment while the user use the program).

I was trying to do the follow:

```<code>int bills[];

float totalAmount[];
</code>```

I can't assign a max size because I'm printing each array with a for loop (If I assign a size of 99 I'll print 99 lines, and I don't want that).

答: i think you can give it  a max size ,if you only want to show the first few elements you can put a a for loop upto that element only,same goes for input if u want to initiallize first 30 elements put a for loop upto 30.</p>

Body:
I'm trying to create a int and a float array without a size (it might be 0 or it might increment while the user use the program).

I was trying to do the follow:

int bills[];

float totalAmount[];

I can't assign a max size because I'm printing each array with a for loop (If I assign a size of 99 I'll print 99 lines, and I don't want that).


问:
transaction in Algorand v2 using flask
This is the error I got when I try to make a transfer:

```<code>algosdk.error.AlgodHTTPError: TransactionPool.Remember: transaction WA5KXR7UGIA4BZTKCK5X5MWQNZOZRB6726ISQVLVE5FQHW2BAHHQ: overspend (account KD3DOFNWGWBFVZUNCS5JYIUOSJMC6VECXKTY6WXMQQBPEPD4ZXQNH76GGY, data {_struct:{} Status:Offline MicroAlgos:{Raw:0} RewardsBase:0 RewardedMicroAlgos:{Raw:0} VoteID:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] SelectionID:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] VoteFirstValid:0 VoteLastValid:0 VoteKeyDilution:0 AssetParams:map[] Assets:map[] AuthAddr:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ AppLocalStates:map[] AppParams:map[] TotalAppSchema:{_struct:{} NumUint:0 NumByteSlice:0} TotalExtraAppPages:0}, tried to spend {1000})
</code>```

This error shows i tried to spend {1000} which is not the amount but a fee.

```<code>params = algod_client.suggested_params()
    form = TransferForm(request.form)
    if request.method == 'POST' and form.validate():
        sender = form.sender.data
        receiver = form.receiver.data
        #amount = int(form.amount.data)

    # Debugging
        #params = algod_client.suggested_params()
        # comment out the next two (2) lines to use suggested fees
        params.flat_fee = True
        params.fee = 1000
        #receiver = "HZ57J3K46JIJXILONBBZOHX6BKPXEM2VVXNRFSUED6DKFD5ZD24PMJ3MVA"
        note = "Hello World".encode()
        amount = 10000000
        unsigned_txn = PaymentTxn(sender, params, receiver, amount, None, note)

        #return unsigned_txn
    # End

        try:
            signed_txn = unsigned_txn.sign(mnemonic.to_private_key(session['passphrase']))

</code>```

答:
Any transaction on Algorand requires payment of a fee (at least 0.001 Algo = 1,000 microAlgos).

The account you are using (KD3DOFNWGWBFVZUNCS5JYIUOSJMC6VECXKTY6WXMQQBPEPD4ZXQNH76GGY) is empty and cannot pay the fee.

You need to add Algos to the account:

on MainNet, you need to buy Algos, e.g., on an exchange

on TestNet, you need to get fake/TestNet Algos from the TestNet dispenser https://bank.testnet.algorand.network/

on a private network, you need to manually send Algos from a genesis account

If you have Algos in your accounts (and see them on a block explorer such as algoexplorer.io), then you need to check that the node you are connected to is:

connected to the right network (MainNet, TestNet, private)

is synced to the network (goal node status should show Sync time: 0.0 and the last round should match the one on a block explorer such as algoexplorer.io)

PS: I recommend asking questions related to Algorand directly on https://forum.algorand.org

Title: transaction in Algorand v2 using flask

Body:
This is the error I got when I try to make a transfer:

algosdk.error.AlgodHTTPError: TransactionPool.Remember: transaction WA5KXR7UGIA4BZTKCK5X5MWQNZOZRB6726ISQVLVE5FQHW2BAHHQ: overspend (account KD3DOFNWGWBFVZUNCS5JYIUOSJMC6VECXKTY6WXMQQBPEPD4ZXQNH76GGY, data {_struct:{} Status:Offline MicroAlgos:{Raw:0} RewardsBase:0 RewardedMicroAlgos:{Raw:0} VoteID:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] SelectionID:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] VoteFirstValid:0 VoteLastValid:0 VoteKeyDilution:0 AssetParams:map[] Assets:map[] AuthAddr:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ AppLocalStates:map[] AppParams:map[] TotalAppSchema:{_struct:{} NumUint:0 NumByteSlice:0} TotalExtraAppPages:0}, tried to spend {1000})

This error shows i tried to spend {1000} which is not the amount but a fee.

params = algod_client.suggested_params()
    form = TransferForm(request.form)
    if request.method == 'POST' and form.validate():
        sender = form.sender.data
        receiver = form.receiver.data
        #amount = int(form.amount.data)

    # Debugging
        #params = algod_client.suggested_params()
        # comment out the next two (2) lines to use suggested fees
        params.flat_fee = True
        params.fee = 1000
        #receiver = "HZ57J3K46JIJXILONBBZOHX6BKPXEM2VVXNRFSUED6DKFD5ZD24PMJ3MVA"
        note = "Hello World".encode()
        amount = 10000000
        unsigned_txn = PaymentTxn(sender, params, receiver, amount, None, note)

        #return unsigned_txn
    # End

        try:
            signed_txn = unsigned_txn.sign(mnemonic.to_private_key(session['passphrase']))


问:
Reference Error variable is not defined with ejs and nodejs
I'm trying to send a variable from nodejs(expressjs) to html page with ejs. But i'm getting  ReferenceError: ...... variable is not defined error.

folder structure:

node_modules

src

static-pages-server

static-pages-server.js

views

pages

journey-analize-report.ejs

partials

journey-analize-report.ejs:

```<code><script type="text/javascript">
        console.log('<%-currentCulture%>');
</script>
</code>```

static-pages-server.js:

```<code>   const express = require('express');
    const app = express();
    const bodyParser = require('body-parser');
    const ejs = require('ejs');
    var path = require('path');
    var currentCulture;

    app.get('/', function(req, res) {
    res.render("pages/journey-analize-report", {currentCulture:"Hello"});
});
</code>```

Error:

```<code> ReferenceError: D:\Project-UI\views\pages\journey-analize-report.ejs:46
            44|     <script type="text/javascript">
            45|
         >> 46|         console.log('<%-currentCulture%>');
            47|

        currentCulture is not defined
            at eval (eval at compile (D:\SeyirMobilNG-UI\node_modules\ejs\lib\ejs.js:662:12), <anonymous>:12:16)
            at journey-analize-report (D:\SeyirMobilNG-UI\node_modules\ejs\lib\ejs.js:692:17)
            at tryHandleCache (D:\SeyirMobilNG-UI\node_modules\ejs\lib\ejs.js:272:36)
            at View.exports.renderFile [as engine] (D:\SeyirMobilNG-UI\node_modules\ejs\lib\ejs.js:489:10)
            at View.render (D:\SeyirMobilNG-UI\node_modules\express\lib\view.js:135:8)
            at tryRender (D:\SeyirMobilNG-UI\node_modules\express\lib\application.js:640:10)
            at Function.render (D:\SeyirMobilNG-UI\node_modules\express\lib\application.js:592:3)
            at ServerResponse.render (D:\SeyirMobilNG-UI\node_modules\express\lib\response.js:1012:7)
            at D:\SeyirMobilNG-UI\static-page-server\static-pages-server.js:41:9
            at Layer.handle [as handle_request] (D:\SeyirMobilNG-UI\node_modules\express\lib\router\layer.js:95:5)
</code>```

答:
I think you should use this syntax

```<code><%= currentCulture %>
</code>```

But you used

```<code><%-currentCulture%>
</code>```

Body:
I'm trying to send a variable from nodejs(expressjs) to html page with ejs. But i'm getting  ReferenceError: ...... variable is not defined error.

folder structure:

node_modules

src

static-pages-server

static-pages-server.js

views

pages

journey-analize-report.ejs

partials

journey-analize-report.ejs:

static-pages-server.js:

   const express = require('express');
    const app = express();
    const bodyParser = require('body-parser');
    const ejs = require('ejs');
    var path = require('path');
    var currentCulture;

    app.get('/', function(req, res) {
    res.render("pages/journey-analize-report", {currentCulture:"Hello"});
});

Error:

 ReferenceError: D:\Project-UI\views\pages\journey-analize-report.ejs:46
            44|

Body:
I think you should use this syntax

<%= currentCulture %>

But you used

<%-currentCulture%>


问:
How to make the entire asp.net solution as a user control
How to make the entire asp.net solution as a user control so that it could be used with other application.i have a asp.net solution including the wcf services in it. I want to make it a user control so that it could be used as if like a user control with other application.

Thanks in advance.

答:
What you want is a iframe like this:

```<code><iframe src="http://www.YourSite.com/page.aspx" width="400px" height="300px" />
</code>```

Body:
What you want is a iframe like this:

<iframe src="http://www.YourSite.com/page.aspx" width="400px" height="300px" />


问:
How can I remove dynamically generated event handlers in JavaScript
When I click the buttons, I see the console message showing that I've clicked them. When I uncheck the checkbox and then click the buttons, I expect no console messages but I still see them. Why doesn't the removeEventListener remove the event listener?

const buttons = document.querySelectorAll('ul li button');

function initialize() {
  for (let i = 0; i < buttons.length; i++) {
    function doSomething() {
      console.log(`You clicked on ${buttons[i].textContent}`);
    }

    if (document.querySelector('#mode').checked) {
      buttons[i].addEventListener('click', doSomething);
    } else {
      buttons[i].removeEventListener('click', doSomething);
    }
  }
}

document.querySelector('#mode').addEventListener('click', initialize);
initialize();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id='mode' type='checkbox' checked/>
<label for='mode'>Do something when you click</label>
<ul>
  <li><button>One</button>
  <li><button>Two</button>
  <li><button>Three</button>
  <li><button>Four</button></code>```

I can't define doSomething outside of the for loop because I need i to do other stuff (not shown here for the sake of simplicity). I do need different handlers for each index.

答:
Currently, doSomething is defined inside the for loop which means that every time initialize executes, you end up with a new function called doSomething. So addEventListener adds one function called doSomething, and removeEventListener attempts to remove a different function (also called doSomething). The new doSomething was never registered as an event listener so it can't be removed, and the old doSomething is out of scope so we can't reference it to remove it. Instead, you can dynamically generate the functions once and reference them in initialize.

const buttons = document.querySelectorAll('ul li button');

const buttonFunctions = [];

for (let i = 0; i < buttons.length; i++) {
  buttonFunctions[i] = function doSomething() {
    console.log(`You clicked on ${buttons[i].textContent}`);
  }
}

function initialize() {
  for (let i = 0; i < buttons.length; i++) {
    if (document.querySelector('#mode').checked) {
      buttons[i].addEventListener('click', buttonFunctions[i]);
    } else {
      buttons[i].removeEventListener('click', buttonFunctions[i]);
    }
  }
}

document.querySelector('#mode').addEventListener('click', initialize);
initialize();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id='mode' type='checkbox' checked/>
<label for='mode'>Do something when you click</label>
<ul>
  <li><button>One</button>
  <li><button>Two</button>
  <li><button>Three</button>
  <li><button>Four</button></code>```

Body:
When I click the buttons, I see the console message showing that I've clicked them. When I uncheck the checkbox and then click the buttons, I expect no console messages but I still see them. Why doesn't the removeEventListener remove the event listener?

const buttons = document.querySelectorAll('ul li button');

function initialize() {
  for (let i = 0; i < buttons.length; i++) {
    function doSomething() {
      console.log(`You clicked on ${buttons[i].textContent}`);
    }

    if (document.querySelector('#mode').checked) {
      buttons[i].addEventListener('click', doSomething);
    } else {
      buttons[i].removeEventListener('click', doSomething);
    }
  }
}

document.querySelector('#mode').addEventListener('click', initialize);
initialize();

<input id='mode' type='checkbox' checked/>
Do something when you click

<button>One</button>

<button>Two</button>

<button>Three</button>

<button>Four</button>

I can't define doSomething outside of the for loop because I need i to do other stuff (not shown here for the sake of simplicity). I do need different handlers for each index.

Body:
Currently, doSomething is defined inside the for loop which means that every time initialize executes, you end up with a new function called doSomething. So addEventListener adds one function called doSomething, and removeEventListener attempts to remove a different function (also called doSomething). The new doSomething was never registered as an event listener so it can't be removed, and the old doSomething is out of scope so we can't reference it to remove it. Instead, you can dynamically generate the functions once and reference them in initialize.

const buttons = document.querySelectorAll('ul li button');

const buttonFunctions = [];

for (let i = 0; i < buttons.length; i++) {
  buttonFunctions[i] = function doSomething() {
    console.log(`You clicked on ${buttons[i].textContent}`);
  }
}

function initialize() {
  for (let i = 0; i < buttons.length; i++) {
    if (document.querySelector('#mode').checked) {
      buttons[i].addEventListener('click', buttonFunctions[i]);
    } else {
      buttons[i].removeEventListener('click', buttonFunctions[i]);
    }
  }
}

document.querySelector('#mode').addEventListener('click', initialize);
initialize();

<input id='mode' type='checkbox' checked/>
<label for='mode'>Do something when you click</label>
<ul>
  <li><button>One</button>
  <li><button>Two</button>
  <li><button>Three</button>
  <li><button>Four</button>


问:
AwaitingReactions is practically not working on mine. Discord.js
I dont know why but i followed the guide in discord.js about awaiting reactions but it seems it doesnt work on mine. I dont know why. Whenever i hit the emoji it doesnt collect it. I pretty much goes to every answered question here in stackoverflow but i still cannot fix it.

```<code>const { Client, Message, MessageEmbed } = require("discord.js");

module.exports = {
  name: "error",
  /**
   * @param {Client} client
   * @param {Message} message
   * @param {String[]} args
   */
  run: async (client, message, args) => {
    message.delete({ timeout:2000 })
    var randstr = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
    var randnum = Math.floor(Math.random() * 100);
    var comb = randstr + randnum;
    var sayEmbed = new MessageEmbed()
        .setTitle('Console Error #'+ '`' + comb + '`' + ' sent by ' + message.member.user.tag)
        .setDescription('```' + args.join(" ") + '```')
        .setTimestamp()
        .setColor("BLACK")
        .setTimestamp()
        .setFooter("Copyright ©  2022, Mythic Realms, or its associates. All Rights Reserved.")

    message.channel.send({embed: sayEmbed}).then(embedMessage => {
    embedMessage.react('✅');
    })

        const filter = (reaction, user) => reaction.emoji.name === '✅' && user.id === message.author.id;
        const collector = message.createReactionCollector(filter, { max: 1, time: 5 * 60 * 1000 });

    collector.on('collect', () => {
      message.clearReactions();

      console.log('SUCCESS');
    });
  },
};
</code>```

Please help with this bot :< thank you.

答:
You're creating a message collector at message whereas the reaction itself is at embedMessage.

embedMessage.createReactionCollector would be the correct.

Plus, said embedMessage is within the scope of the message.send().then()

You can either assign the return value of the message.send() promise to embedMessage on the same level so it is accessible by the collector or set the collector inside the then() function from message.send()

const embedMessage = await message.send(...);
const collector = embedMessage.createReactionCollector(...);
```
<p>or</p>
<pre class="lang-js prettyprint-override"><code>message.send(...).then(embedMessage => {
  const collector = embedMessage.createReactionCollector(...);
});
</code>```

Body:
I dont know why but i followed the guide in discord.js about awaiting reactions but it seems it doesnt work on mine. I dont know why. Whenever i hit the emoji it doesnt collect it. I pretty much goes to every answered question here in stackoverflow but i still cannot fix it.

const { Client, Message, MessageEmbed } = require("discord.js");

module.exports = {
  name: "error",
  /**
   * @param {Client} client
   * @param {Message} message
   * @param {String[]} args
   */
  run: async (client, message, args) => {
    message.delete({ timeout:2000 })
    var randstr = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
    var randnum = Math.floor(Math.random() * 100);
    var comb = randstr + randnum;
    var sayEmbed = new MessageEmbed()
        .setTitle('Console Error #'+ '`' + comb + '`' + ' sent by ' + message.member.user.tag)
        .setDescription('```' + args.join(" ") + '```')
        .setTimestamp()
        .setColor("BLACK")
        .setTimestamp()
        .setFooter("Copyright ©  2022, Mythic Realms, or its associates. All Rights Reserved.")

    message.channel.send({embed: sayEmbed}).then(embedMessage => {
    embedMessage.react('✅');
    })

        const filter = (reaction, user) => reaction.emoji.name === '✅' && user.id === message.author.id;
        const collector = message.createReactionCollector(filter, { max: 1, time: 5 * 60 * 1000 });

    collector.on('collect', () => {
      message.clearReactions();

      console.log('SUCCESS');
    });
  },
};

Please help with this bot :< thank you.

Body:
You're creating a message collector at message whereas the reaction itself is at embedMessage.

embedMessage.createReactionCollector would be the correct.

Plus, said embedMessage is within the scope of the message.send().then()

You can either assign the return value of the message.send() promise to embedMessage on the same level so it is accessible by the collector or set the collector inside the then() function from message.send()

const embedMessage = await message.send(...);
const collector = embedMessage.createReactionCollector(...);

or

message.send(...).then(embedMessage => {
  const collector = embedMessage.createReactionCollector(...);
});


问:
How to migrate millions of rows of data from SQL Server to any client or cloud?
I have code to upload data from SQL Server to snowflake.
Steps:

Load data from SQL server & create CSV file along with data

Upload CSV to Snowflake staging tables & then process staging & push data to actual  tables.

This works fine.
Now I want to process millions of records. What is efficient way to do so?
How do I work with batches?
I'm using WEB API 2.0

Thanks

答:
create csv file of database you want to upload

upload the csv file to AWS(S3 bucket)

upload data from S3 bucket to snowflake
more details


问:
Cannot make a mask for BTJD format of a Time object
I cannot make a mask using the following code:

mask = (flat_lc['time'] < 1346) | (flat_lc['time'] > 1350)

You can see what the dataframe looks like here: Dataframe

I get the following error:

'<' not supported between instances of 'Time' and 'int'

I think there has been an update recently that has changed this. The tutorial I'm following has their mask like this. I get the same error if I change the mask values to a string instead of an int.

答:
the object flat_lc is a astropy Time object so I checked the documentation for that and found out you can access the values of the object by doing:

flat_lc['time'].value

The mask then becomes:

mask = (flat_lc['time'].value < 1346) | (flat_lc['time'].value>1350)