问:
ordering a list in C#
I have a list of Employee objects .Employee Class can be as below:

```<code>Class Emplyoyee
{
    public string name;
    public string DateOFJoining; //Please note here date is in string format
}
</code>```

Now i want to display the list of employee with latest employee on top so am using below code for it :

```<code>List<Employee> lst = GetEmployes();
lst = lst.OrderByDescending(x => x.DateOFJoining).ToList();

//Here binding to the repeater
rptEmp.DataSource = lst.Take(2);
rptEmp.DataBind();
</code>```

Problem: Here its ordering treating date as string .But i want to order by date.Can anyone help me on this?

Thanks in advance.

答:
You would need to convert x.DateOfJoining into a DateTime in the OrderByDescending expression. If you're confident in the quality of your dates, you could try:

```<code>lst = lst.OrderByDescending(x => DateTime.Parse(x.DateOfJoining)).ToList();
</code>```

Title: ordering a list in C#

Body:
I have a list of Employee objects .Employee Class can be as below:

Class Emplyoyee
{
    public string name;
    public string DateOFJoining; //Please note here date is in string format
}

Now i want to display the list of employee with latest employee on top so am using below code for it :

List<Employee> lst = GetEmployes();
lst = lst.OrderByDescending(x => x.DateOFJoining).ToList();

//Here binding to the repeater
rptEmp.DataSource = lst.Take(2);
rptEmp.DataBind();

Problem: Here its ordering treating date as string .But i want to order by date.Can anyone help me on this?

Thanks in advance.

Body:
You would need to convert x.DateOfJoining into a DateTime in the OrderByDescending expression. If you're confident in the quality of your dates, you could try:

lst = lst.OrderByDescending(x => DateTime.Parse(x.DateOfJoining)).ToList();


来源: stackexchange

问:
Django Management Command best practice for additional file location
I am writing a Django management command. The command itself is located under myapp/management/commands/mycommand.py. I need to write an additional class which I would like to place in an extra file.

Should this file live in

myapp/extrafile.py or

myapp/management/commands/extrafile.py

What would be a recommended location. The class is only need for the management command, not elsewhere in the app.

答:
You can create an additional file in myapp/management/commands/ that starts with underscore. It is not going to be detected as a management command (check this).

So, your command in: myapp/management/commands/mycommand.py

And your helper in: myapp/management/commands/_myhelper.py

ContentLicense: CC BY-SA 4.0


问:
HttpListener cannot start process after receive Request [C#]
im using system.net.httplistener to listen client requests, i start a process after receive request, the process do stuff and then return a response, using postman the process is started properly but wen i use XMLHttpRequest on javascript (with the same headers and body as the postman request) the process does not start. Using logfile the httplistener application reach the "p.Start();" line but does not start.
Do i need some specific header or body value? i think is about permissions but im not sure
Can you help me?

There is the Client Script code

```<code>function scan(path,foil) {

  var url = "http://localhost:1300/ServicioEscaner/"; //direccion a donde se realiza el request
    var method = "POST";

    var shouldBeAsync = true;
    var request = new XMLHttpRequest();

    request.onreadystatechange = function () {
       if ( request.readyState ==  request.DONE) {
        if ( request.status === 200) {
                alert(request.responseText);
        }
      }
    }

    request.open(method, url, shouldBeAsync);

    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    request.send(JSON.stringify(    {
        "config":
        {
            "tag":
            {
                "value":foil,
                "path":path,
                "type":"scann"
            }
        }
    }));

}
</code>```

答: Did you tried adding [FromBody] attribute to method parameter?

Body:
im using system.net.httplistener to listen client requests, i start a process after receive request, the process do stuff and then return a response, using postman the process is started properly but wen i use XMLHttpRequest on javascript (with the same headers and body as the postman request) the process does not start. Using logfile the httplistener application reach the "p.Start();" line but does not start.
Do i need some specific header or body value? i think is about permissions but im not sure
Can you help me?

There is the Client Script code

function scan(path,foil) {

  var url = "http://localhost:1300/ServicioEscaner/"; //direccion a donde se realiza el request
    var method = "POST";

    var shouldBeAsync = true;
    var request = new XMLHttpRequest();

    request.onreadystatechange = function () {
       if ( request.readyState ==  request.DONE) {
        if ( request.status === 200) {
                alert(request.responseText);
        }
      }
    }

    request.open(method, url, shouldBeAsync);

    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    request.send(JSON.stringify(    {
        "config":
        {
            "tag":
            {
                "value":foil,
                "path":path,
                "type":"scann"
            }
        }
    }));

}


问:
EF: Include with where clause
As the title suggest I am looking for a way to do a where clause in combination with an include.

Here is my situations:
I am responsible for the support of a large application full of code smells.
Changing too much code causes bugs everywhere so I am looking for the safest solution.

Let's say I have an object Bus and an object People(Bus has a navigation prop Collection of People).
In my Query I need to select all the Busses with only the Passengers that are awake. This is a simplistic dummy example

In the current code:

```<code>var busses = Context.Busses.Where(b=>b.IsDriving == true);
foreach(var bus in busses)
{
   var passengers = Context.People.Where(p=>p.BusId == bus.Id && p.Awake == true);
   foreach(var person in passengers)
   {
       bus.Passengers.Add(person);
   }
}
</code>```

After this code the Context is disposed and in the calling method the resulting Bus entities are Mapped to a DTO class (100% copy of Entity).

This code causes multiple calls to DB which is a No-Go, so I found this solution ON MSDN Blogs

This worked great when debugging the result but when the entities are mapped to the DTO (Using AutoMapper) I get an exception that the Context/Connection has been closed and that the object can't be loaded. (Context is always closed can’t change this :( )

So I need to make sure that the Selected Passengers are already loaded (IsLoaded on navigation property is also False). If I inspect the Passengers collection The Count also throws the Exception but there is also a collection on the Collection of Passegers called “wrapped related entities” which contain my filtered objects.

Is there a way to load these wrapped related entities into the whole collection?
(I can't change the automapper mapping config because this is used in the whole application).

Is there another way to Get the Active Passengers?

Any hint is welcome...

Edit

Answer of Gert Arnold doesn't work because the data isn't loaded eagerly.
But when I simplify it and delete the where it is loaded. This is realy strange since the execute sql returns all the passengers in both cases. So there must be a problem when putting the results back into the entity.

```<code>Context.Configuration.LazyLoadingEnabled = false;
var buses = Context.Busses.Where(b => b.IsDriving)
        .Select(b => new
                     {
                         b,
                         Passengers = b.Passengers
                     })
        .ToList()
        .Select(x => x.b)
        .ToList();
</code>```

Edit2

After a lot of struggle the answer of Gert Arnold work!
As Gert Arnold suggested you need to disable Lazy Loading and Keep it OFF.
This will ask for some extra changes to the appliaction since the prev developer loved Lazy Loading -_-

答:
For any one still curious about this. there builtin functionality for doing this in EF Core. using .Any inside of a where clause so the code would like similar to something like this</p>
```<code>_ctx.Parent
    .Include(t => t.Children)
    .Where(t => t.Children.Any(t => /* Expression here */))
</code>```

ContentLicense: CC BY-SA 3.0

Title: EF: Include with where clause

Body:
As the title suggest I am looking for a way to do a where clause in combination with an include.

Here is my situations:
I am responsible for the support of a large application full of code smells.
Changing too much code causes bugs everywhere so I am looking for the safest solution.

Let's say I have an object Bus and an object People(Bus has a navigation prop Collection of People).
In my Query I need to select all the Busses with only the Passengers that are awake. This is a simplistic dummy example

In the current code:

var busses = Context.Busses.Where(b=>b.IsDriving == true);
foreach(var bus in busses)
{
   var passengers = Context.People.Where(p=>p.BusId == bus.Id && p.Awake == true);
   foreach(var person in passengers)
   {
       bus.Passengers.Add(person);
   }
}

After this code the Context is disposed and in the calling method the resulting Bus entities are Mapped to a DTO class (100% copy of Entity).

This code causes multiple calls to DB which is a No-Go, so I found this solution ON MSDN Blogs

This worked great when debugging the result but when the entities are mapped to the DTO (Using AutoMapper) I get an exception that the Context/Connection has been closed and that the object can't be loaded. (Context is always closed can’t change this :( )

So I need to make sure that the Selected Passengers are already loaded (IsLoaded on navigation property is also False). If I inspect the Passengers collection The Count also throws the Exception but there is also a collection on the Collection of Passegers called “wrapped related entities” which contain my filtered objects.

Is there a way to load these wrapped related entities into the whole collection?
(I can't change the automapper mapping config because this is used in the whole application).

Is there another way to Get the Active Passengers?

Any hint is welcome...

Edit

Answer of Gert Arnold doesn't work because the data isn't loaded eagerly.
But when I simplify it and delete the where it is loaded. This is realy strange since the execute sql returns all the passengers in both cases. So there must be a problem when putting the results back into the entity.

Context.Configuration.LazyLoadingEnabled = false;
var buses = Context.Busses.Where(b => b.IsDriving)
        .Select(b => new
                     {
                         b,
                         Passengers = b.Passengers
                     })
        .ToList()
        .Select(x => x.b)
        .ToList();

Edit2

After a lot of struggle the answer of Gert Arnold work!
As Gert Arnold suggested you need to disable Lazy Loading and Keep it OFF.
This will ask for some extra changes to the appliaction since the prev developer loved Lazy Loading -_-

Body:
For any one still curious about this. there builtin functionality for doing this in EF Core. using .Any inside of a where clause so the code would like similar to something like this

_ctx.Parent
    .Include(t => t.Children)
    .Where(t => t.Children.Any(t => /* Expression here */))


问:
Asking for user input between 2 genders using a while loop and to be stored in a variable?
Want to create a small program that can ask a user a question. Do you want your character to be Male or Female? And output the result. However as you can tell the results are poor from my side.

Can someone give me a hand in fixing this mess as I feel I have over complicated it.

Just some general rules that the program must have:

It must accept both "Male" and "male" as input and vice versa for
female

The user input must be stored in the variable created.

If the user types anything else that is not: 'female' 'Female' 'male' or 'Male' they must try the question again (which is why I put in a while loop)

It's strange but this should be simple for me normally but I've made a bit of a mess of it.

Any help would be appreciated :)

```<code>gender = None

gender = str(input("Enter your Gender1: "))
while gender != 'Male' or 'male' or 'female' or 'Female':
    gender = input("Enter your Gender2: ")
if gender in ['Male', 'male']:
    print("You have chosen Male")
if gender in ['Female', 'female']:
    print("You have chosen Female")

print(gender)
</code>```

I don't mind the whole method changing where options can be used such as:

Press 1 for 'Male' or 2 for 'Female'

Would be of a help :)

答:
You need to do:

```<code>while gender != 'Male' or gender != 'male' or gender != 'female' or gender != 'Female':
</code>```

Because in your case,  'male' evaluates to False

Body:
Want to create a small program that can ask a user a question. Do you want your character to be Male or Female? And output the result. However as you can tell the results are poor from my side.

Can someone give me a hand in fixing this mess as I feel I have over complicated it.

Just some general rules that the program must have:

It must accept both "Male" and "male" as input and vice versa for
female

The user input must be stored in the variable created.

If the user types anything else that is not: 'female' 'Female' 'male' or 'Male' they must try the question again (which is why I put in a while loop)

It's strange but this should be simple for me normally but I've made a bit of a mess of it.

Any help would be appreciated :)

gender = None

gender = str(input("Enter your Gender1: "))
while gender != 'Male' or 'male' or 'female' or 'Female':
    gender = input("Enter your Gender2: ")
if gender in ['Male', 'male']:
    print("You have chosen Male")
if gender in ['Female', 'female']:
    print("You have chosen Female")

print(gender)

I don't mind the whole method changing where options can be used such as:

Press 1 for 'Male' or 2 for 'Female'

Would be of a help :)

Body:
You need to do:

while gender != 'Male' or gender != 'male' or gender != 'female' or gender != 'Female':

Because in your case,  'male' evaluates to False


问:
Git Log Displays Nothing
I have a number of git repositories (with commits) and each displays nothing when running git log. If I run the command outside a project directory (without a git repository) I get:

fatal: Not a git repository (or any of the parent directories): .git

I tried re-installing Git (I'm now running 1.7.5.4) and re-cloning my repositories to no avail. Any ideas?

答: i had the similar issue with a log to a file. 1] get a list of your config files git config --list 2] check this entry core.filemode=false change it to true git config core.filemode true 3] check your files path in gitk 4] i had the wrong path. now it works. git log --  ./Documents/holdMe.txt

Title: Git Log Displays Nothing


问:
how to remove other rows with same Word in the SQL table column
how to remove other rows with same Word in the SQL Table column

For example

```<code>StudentUserID     SessionID

DSteve             101
DSteve             102
CJohn              101
</code>```

For Reporting purpose we only need first ever row with StudentUserID

答:
or make it otherwise

```<code> WITH b AS (SELECT t.*,
 row_number() over(partition by student_name order by student_name ) as _rnk
 from t )
 SELECT * FROM b WHERE _rnk=1
</code>```

although the purpose of that reporting is questionable :)
this will give you a unique student name output others will be dropped
but normally you would want to have a unique id for each student because there can be
multiple John Smiths etc.

Body:
how to remove other rows with same Word in the SQL Table column

For example

StudentUserID     SessionID

DSteve             101
DSteve             102
CJohn              101

For Reporting purpose we only need first ever row with StudentUserID

Body:
or make it otherwise

 WITH b AS (SELECT t.*,
 row_number() over(partition by student_name order by student_name ) as _rnk
 from t )
 SELECT * FROM b WHERE _rnk=1

although the purpose of that reporting is questionable :)
this will give you a unique student name output others will be dropped
but normally you would want to have a unique id for each student because there can be
multiple John Smiths etc.


问:
(change) vs (ngModelChange) in angular
Angular 1 does not accept onchange() event, it's only accepts ng-change() event.

Angular 2, on the other hand, accepts both (change) and (ngModelChange) events, which both seems to be doing the same thing.

What's the difference?

which one is best for performance?

ngModelChange:

```<code><input type="text" pInputText class="ui-widget ui-text"
    (ngModelChange)="clearFilter()" placeholder="Find"/>
</code>```

vs change:

```<code><input type="text" pInputText class="ui-widget ui-text"
    (change)="clearFilter()" placeholder="Find"/>
</code>```

答:
1 - (change) is bound to the HTML onchange event. The documentation about HTML onchange says the following :

Execute a JavaScript when a user changes the selected option of a <select> element

Source : https://www.w3schools.com/jsref/event_onchange.asp

2 - As stated before, (ngModelChange) is bound to the model variable binded to your input.

So, my interpretation is :

(change) triggers when the user changes the input

(ngModelChange) triggers when the model changes, whether it's consecutive to a user action or not

Title: (change) vs (ngModelChange) in angular

Body:
Angular 1 does not accept onchange() event, it's only accepts ng-change() event.

Angular 2, on the other hand, accepts both (change) and (ngModelChange) events, which both seems to be doing the same thing.

What's the difference?

which one is best for performance?

ngModelChange:

<input type="text" pInputText class="ui-widget ui-text"
    (ngModelChange)="clearFilter()" placeholder="Find"/>

vs change:

<input type="text" pInputText class="ui-widget ui-text"
    (change)="clearFilter()" placeholder="Find"/>


问:
SVG rotate path
I'm starting to use SVG and so far it's all okay, but when I try to do some animation with CSS the result isn't what I expect it to be.

I want to rotate a gear like in this Fiddle.

Below is the CSS I used to rotate the elements:

```<code>.gear {
    -webkit-animation: rotation 2s infinite linear;
    -moz-animation: rotation 2s infinite linear;
    -o-animation: rotation 2s infinite linear;
    animation: rotation 2s infinite linear;
}

@-webkit-keyframes rotation {
    from {-webkit-transform: rotate(0deg);}
    to   {-webkit-transform: rotate(359deg);}
}
@-moz-keyframes rotation {
    from {-moz-transform: rotate(0deg);}
    to   {-moz-transform: rotate(359deg);}
}
@-o-keyframes rotation {
    from {-o-transform: rotate(0deg);}
    to   {-o-transform: rotate(359deg);}
}
@keyframes rotation {
    from {transform: rotate(0deg);}
    to   {transform: rotate(359deg);}
}
</code>```

答:
You can add this tag inside your svg tag to rotate it around it's center:

```<code><animateTransform attributeType="xml" attributeName="transform" type="rotate" from="360 0 0" to="0 0 0" dur="9s" additive="sum" repeatCount="indefinite" />
</code>```

Title: SVG rotate path

Body:
I'm starting to use SVG and so far it's all okay, but when I try to do some animation with CSS the result isn't what I expect it to be.

I want to rotate a gear like in this Fiddle.

Below is the CSS I used to rotate the elements:

.gear {
    -webkit-animation: rotation 2s infinite linear;
    -moz-animation: rotation 2s infinite linear;
    -o-animation: rotation 2s infinite linear;
    animation: rotation 2s infinite linear;
}

@-webkit-keyframes rotation {
    from {-webkit-transform: rotate(0deg);}
    to   {-webkit-transform: rotate(359deg);}
}
@-moz-keyframes rotation {
    from {-moz-transform: rotate(0deg);}
    to   {-moz-transform: rotate(359deg);}
}
@-o-keyframes rotation {
    from {-o-transform: rotate(0deg);}
    to   {-o-transform: rotate(359deg);}
}
@keyframes rotation {
    from {transform: rotate(0deg);}
    to   {transform: rotate(359deg);}
}

Body:
You can add this tag inside your svg tag to rotate it around it's center:

<animateTransform attributeType="xml" attributeName="transform" type="rotate" from="360 0 0" to="0 0 0" dur="9s" additive="sum" repeatCount="indefinite" />


问:
Emulating GCC's __builtin_unreachable?
I get a whole lot of warnings about switches that only partially covers the range of an enumeration switched over. Therefor, I would like to have a "default" for all those switches and put __builtin_unreachable (GCC builtin) in that case, so that the compiler know that case is not reachable.

However, I came to know that GCC4.3 does not support that builtin yet. Is there any good way to emulate that functionality? I thought about dereferencing a null pointer instead, but that may have other undesirable effects/warnings and such. Do you have any better idea?

答:
Hmm, something like (since __builtin_unreachable() appeared in 4.5):</p>

```
<code>
#define GCC_VERSION (__GNUC__ * 10000 \
                               + __GNUC_MINOR__ * 100 \
                               + __GNUC_PATCHLEVEL__)
#if GCC_VERSION >= 40500
#define my_unreachable()  __builtin_unreachable()
#else
#define my_unreachable() do { printf("Oh noes!!!111\n"); abort(); } while(0)
#endif
</code>
```

Title: Emulating GCC's __builtin_unreachable?

Body:
Hmm, something like (since __builtin_unreachable() appeared in 4.5):

#define GCC_VERSION (__GNUC__ * 10000 \
                               + __GNUC_MINOR__ * 100 \
                               + __GNUC_PATCHLEVEL__)
#if GCC_VERSION >= 40500
#define my_unreachable()  __builtin_unreachable()
#else
#define my_unreachable() do { printf("Oh noes!!!111\n"); abort(); } while(0)
#endif


问:
Why does a user-provided default constructor lead to an uninitialized member?
Please consider the following code:

```<code>#include <iostream>

struct A{ // with implicit default constructor
       int number;
};

struct B{
       int number;
       B(){}; // user-provided default constructor
};

int main()
{
    A aa = {};
    B bb = {};

    std::cout << "aa.number: " << aa.number << std::endl;
    std::cout << "bb.number: " << bb.number << std::endl;
}
</code>```

Running the code online
results in the following output:

```<code>aa.number: 0
bb.number: 19715
</code>```

Why is bb.number uninitialized?
I thought that zero initialisation is guaranteed by using ={} ?

答: struct B has a user-provided constructor, so it doesn't get the default constructor that can initialize the members to zero.  Your user-provided constructor replaces that, so you have to do the work yourself.

Body:
Please consider the following code:

#include <iostream>

struct A{ // with implicit default constructor
       int number;
};

struct B{
       int number;
       B(){}; // user-provided default constructor
};

int main()
{
    A aa = {};
    B bb = {};

    std::cout << "aa.number: " << aa.number << std::endl;
    std::cout << "bb.number: " << bb.number << std::endl;
}

Running the code online
results in the following output:

aa.number: 0
bb.number: 19715

Why is bb.number uninitialized?
I thought that zero initialisation is guaranteed by using ={} ?


问:
RabbitMQ logging connection times, queues creation times and other stats
I am wondering if Masstransit offers the option to log how long it takes for it to connect to the host, creating queues and so on.

Reasing behind this question is that Masstransit (connected to RabbitMQ) works pretty smooth locally.
When I deploy my application instead, it takes quite some time for it to connect to a cluster (which is on another serve). Therefore I would like to have some info about how expensive (in terms of time) is it to connect towards the cluster, how long does it take to create the queues it needs and so on.

I have set up the logging for MassTransit but I don't see much more than the events sent and received. So I was wondering if this option is offered somewhere that I couldn't find.

答:
You can connect to the DiagnosticSource which will output those metrics.

DiagnosticSource

If you have logging configured, you can look at the logs as well to see timings of those activities. Every declare and bind statement is output as the broker topology is configured.

If you're seeing slow times on a cluster, make sure you have configured enough resources for each broker instance. Most RabbitMQ performance issues are related to deploying in a wimpy docker container with insufficient memory, a single CPU, or slow disks. RabbitMQ should be treated as critical as a SQL server when it comes to resources. It's important.


问:
unable to inject dependency in .net core 3.1
Hi i am following microsoft docs ...

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#json-configuration-provider

in order to inject configurations as singleton in .NET Core Web API

Here is Program.cs code where i load my configurations:

```<code>public class Program
{
    public static Dictionary<string, string> arrayDict =
   new Dictionary<string, string>
   {
        {"connString", "Data Source =xxx/xxx;User Id =xxx;Password =xxx"}
   };
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(builder =>
        {
            builder.AddInMemoryCollection(arrayDict);
            builder.AddJsonFile(
                "appsettings.json", optional: false, reloadOnChange: false);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });
}
</code>```

Here in Startup.cs i use following

```<code>public class Startup
{
    private readonly IConfiguration Configuration;

    public Startup(IConfiguration config)
    {
        Configuration = config;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSingleton<IConfiguration>(Configuration);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
</code>```

Still when i am using dependency injection in my Controller i am unable to inject IConfiguration, and get following error at invoking cotroller action (runtime error):

A suitable constructor for type 'IrisDotNetCore.Controllers.LoginController' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.

LoginController.cs Code:

```<code>[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
    IConfiguration _configuration;

    LoginController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}
</code>```

What is possibly wrong here?

答: Your constructor has to be public or internal - remember that in your situation the instance of the LoginController can't be created (because LoginController method is private). Even the error message (Ensure the type is concrete and services are registered for all parameters of a public constructor) suggests this.

Body:
Hi i am following microsoft docs ...

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#json-configuration-provider

in order to inject configurations as singleton in .NET Core Web API

Here is Program.cs code where i load my configurations:

public class Program
{
    public static Dictionary<string, string> arrayDict =
   new Dictionary<string, string>
   {
        {"connString", "Data Source =xxx/xxx;User Id =xxx;Password =xxx"}
   };
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(builder =>
        {
            builder.AddInMemoryCollection(arrayDict);
            builder.AddJsonFile(
                "appsettings.json", optional: false, reloadOnChange: false);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });
}

Here in Startup.cs i use following

public class Startup
{
    private readonly IConfiguration Configuration;

    public Startup(IConfiguration config)
    {
        Configuration = config;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSingleton<IConfiguration>(Configuration);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

Still when i am using dependency injection in my Controller i am unable to inject IConfiguration, and get following error at invoking cotroller action (runtime error):

A suitable constructor for type 'IrisDotNetCore.Controllers.LoginController' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.

LoginController.cs Code:

[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
    IConfiguration _configuration;

    LoginController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}

What is possibly wrong here?


答:
A is an aggregate type, because it doesn't have any user-provided constructors (and fulfills a few other requirements).

Therefore A aa = {}; does not call the implicitly generated default constructor. Instead initialization with brace-enclosed initializer lists performs aggregate initialization, which for an empty list means that the members are initialized as if by a {} initializer, which in turn means for a member of scalar type such as int that it will be initialized to zero.

B is not an aggregate type, because it does have a user-provided constructor.

Therefore B bb = {}; cannot do aggregate initialization and will call the default constructor instead. The default constructor (in either A or B) does not specify an initializer for the members and so the member is default-initialized, which for a fundamental type, such as int, means that it will not be set to any value. Its value will remain indeterminate.

Accessing the indeterminate value, which your program does, causes undefined behavior.

If you declare a constructor yourself, then it becomes that constructor's responsibility to initialize all the members appropriately. The rule that = {} or {} always initializes only holds under the assumption that a user-provided default constructor, if it exists, does the right thing in the sense that it provides sensible initializers to all its members and it doesn't have to mean zero-initialization necessarily.

Title: Why does a user-provided default constructor lead to an uninitialized member?


问:
Grep for exact match when there is no more words
I have two strings like below:

Word

More than one word

How to use grep to match only with the first one?
I would like to have results when there is no more characters around the word I'm searching for.
When there is a string like the second one, it should find nothing.

Is it possible to achieve with grep?

答:
Use this expression

```<code>grep -i ^word$ file
</code>```

Explanation:

Find all lines starting with (^) at the end of the line ($).

The -i flag makes the match insensitive, remove it if you want a case sensitive match

Body:
Use this expression

grep -i ^word$ file

Explanation:

Find all lines starting with (^) at the end of the line ($).

The -i flag makes the match insensitive, remove it if you want a case sensitive match


问:
I am trying to create a VBA macro that duplicates a worksheet and then copies data in the worksheet to a new column
this is my first time posting on stack overflow, so any feedback is appreciated.

Right now I am trying to program a macro that does the following:

Duplicates current worksheet and moves new sheet to beginning of workbook (new sheet is also named by user via input screen)

Copies data in Column D to Column E based on 3 criteria in Columns A-C

I've coded Step 1, but Step 2 is where I am having trouble. I need to copy data from one location on the worksheet to another based on criteria. Below is an example of something what I'm trying to do

Example for Step 2 Macro:

Basically, I want it to copy the "Day's Sales" to the "Previous Day's Sales" in the new worksheet according to each of the 3 criteria (Name, Country, Product) in case anything changes and to make sure the values are being copied correctly.

Please let me know if any other information needs to be provided!

FYI here is the code I already have for Step 1:

```<code>Public Sub CopySheetAndRename()

Dim newName As String

    On Error Resume Next
    newName = InputBox("Enter the date for the new worksheet")

    If newName <> "" Then
        ActiveSheet.Copy Before:=Sheets(1)
        On Error Resume Next
        ActiveSheet.Name = newName
    End If
End Sub
</code>```

答:
Please test the next code, also. It works fast (in memory, using arrays) for a big range:</p>

```<code>Sub testMoveData()
  Dim shA As Worksheet, newSh As Worksheet, arrA As Variant, ArrFin As Variant
  Dim i As Long, newName As String
    Set shA = ActiveSheet
    arrA = shA.Range("A1:E" & shA.Range("A" & Cells.Rows.count).End(xlUp).row).Value
    ReDim ArrFin(1 To UBound(arrA, 1), 1 To 5)
    For i = 1 To UBound(arrA, 1)
        If i = 1 Then
            ArrFin(i, 1) = arrA(i, 1): ArrFin(i, 2) = arrA(i, 2): ArrFin(i, 3) = arrA(i, 3)
            ArrFin(i, 4) = arrA(i, 4): ArrFin(i, 5) = arrA(i, 5)
        Else
            ArrFin(i, 1) = arrA(i, 1): ArrFin(i, 2) = arrA(i, 2): ArrFin(i, 3) = arrA(i, 3)
            ArrFin(i, 5) = arrA(i, 4)
        End If
    Next i

    newName = InputBox("Enter the date for the new worksheet", "New sheet name setting")
    If newName = "" Then MsgBox "No sheet name allocated": Exit Sub
    Set newSh = ActiveWorkbook.Sheets.Add(Before:=ActiveWorkbook.Worksheets(1)
      newSh.Name = newName
      With newSh.Range("A1").Resize(UBound(ArrFin, 1), UBound(ArrFin, 2))
        .Value = ArrFin
        'A little formatting on the new sheet:
        .Borders(xlEdgeLeft).Weight = xlThin
        .Borders(xlEdgeTop).Weight = xlThin
        .Borders(xlEdgeBottom).Weight = xlThin
        .Borders(xlEdgeRight).Weight = xlThin
        .Borders(xlInsideVertical).Weight = xlThin
        .Borders(xlInsideHorizontal).Weight = xlThin
        .BorderAround Weight:=xlThick
      End With
      With newSh.Range(newSh.Cells(1, 1), newSh.Cells(1, UBound(ArrFin, 2)))
        .Font.Bold = True
        .EntireColumn.AutoFit
      End With
End Sub
</code>```

Body:
this is my first time posting on stack overflow, so any feedback is appreciated.

Right now I am trying to program a macro that does the following:

Duplicates current worksheet and moves new sheet to beginning of workbook (new sheet is also named by user via input screen)

Copies data in Column D to Column E based on 3 criteria in Columns A-C

I've coded Step 1, but Step 2 is where I am having trouble. I need to copy data from one location on the worksheet to another based on criteria. Below is an example of something what I'm trying to do

Example for Step 2 Macro:

Basically, I want it to copy the "Day's Sales" to the "Previous Day's Sales" in the new worksheet according to each of the 3 criteria (Name, Country, Product) in case anything changes and to make sure the values are being copied correctly.

Please let me know if any other information needs to be provided!

FYI here is the code I already have for Step 1:

Public Sub CopySheetAndRename()

Dim newName As String

    On Error Resume Next
    newName = InputBox("Enter the date for the new worksheet")

    If newName <> "" Then
        ActiveSheet.Copy Before:=Sheets(1)
        On Error Resume Next
        ActiveSheet.Name = newName
    End If
End Sub

Body:
Please test the next code, also. It works fast (in memory, using arrays) for a big range:

Sub testMoveData()
  Dim shA As Worksheet, newSh As Worksheet, arrA As Variant, ArrFin As Variant
  Dim i As Long, newName As String
    Set shA = ActiveSheet
    arrA = shA.Range("A1:E" & shA.Range("A" & Cells.Rows.count).End(xlUp).row).Value
    ReDim ArrFin(1 To UBound(arrA, 1), 1 To 5)
    For i = 1 To UBound(arrA, 1)
        If i = 1 Then
            ArrFin(i, 1) = arrA(i, 1): ArrFin(i, 2) = arrA(i, 2): ArrFin(i, 3) = arrA(i, 3)
            ArrFin(i, 4) = arrA(i, 4): ArrFin(i, 5) = arrA(i, 5)
        Else
            ArrFin(i, 1) = arrA(i, 1): ArrFin(i, 2) = arrA(i, 2): ArrFin(i, 3) = arrA(i, 3)
            ArrFin(i, 5) = arrA(i, 4)
        End If
    Next i

    newName = InputBox("Enter the date for the new worksheet", "New sheet name setting")
    If newName = "" Then MsgBox "No sheet name allocated": Exit Sub
    Set newSh = ActiveWorkbook.Sheets.Add(Before:=ActiveWorkbook.Worksheets(1)
      newSh.Name = newName
      With newSh.Range("A1").Resize(UBound(ArrFin, 1), UBound(ArrFin, 2))
        .Value = ArrFin
        'A little formatting on the new sheet:
        .Borders(xlEdgeLeft).Weight = xlThin
        .Borders(xlEdgeTop).Weight = xlThin
        .Borders(xlEdgeBottom).Weight = xlThin
        .Borders(xlEdgeRight).Weight = xlThin
        .Borders(xlInsideVertical).Weight = xlThin
        .Borders(xlInsideHorizontal).Weight = xlThin
        .BorderAround Weight:=xlThick
      End With
      With newSh.Range(newSh.Cells(1, 1), newSh.Cells(1, UBound(ArrFin, 2)))
        .Font.Bold = True
        .EntireColumn.AutoFit
      End With
End Sub


问:
Comparing two dates in SQL in where clause using CASE WHEN?
I am using following query which is working fine for me.

```<code>   SELECT   SO.OrderNumber, TransactionsLookup.TransactionName, Branches.new_Name AS Branchname, i.new_PostedDate,
                  min(i.new_PostedDate) over(partition by SO.OrderNumber) FirstPostedDate,

          FROM       SalesOrders AS SO INNER JOIN
                     Temp_Invoices i  on SO.SalesOrderId = i.SalesOrderId INNER JOIN
                     Branches ON SO.new_Branch = Branches.new_BranchId INNER JOIN
                     StatusReasonsLookup sl on i.StatusCode = sl.Id
                WHERE
                     SO.new_Transaction =  @AbstractTransactionID
                     AND SO.new_Branch <> @BranchID_Metro
                   AND ((month(new_CanceledDate) <> month(new_PostedDate) AND year(new_CanceledDate) <> year(new_PostedDate))
                    OR (month(new_CanceledDate) <> month(new_PostedDate) AND year(new_CanceledDate) = year(new_PostedDate))
                    OR (month(new_CanceledDate) = month(new_PostedDate) AND year(new_CanceledDate) <> year(new_PostedDate)) OR (i.new_CanceledDate IS NULL))
</code>```

Now I have to make date compare cause conditional in where clause using case when something like this;

```<code>   SELECT   SO.OrderNumber, TransactionsLookup.TransactionName, Branches.new_Name AS Branchname, i.new_PostedDate,
                  min(i.new_PostedDate) over(partition by SO.OrderNumber) FirstPostedDate,

          FROM       SalesOrders AS SO INNER JOIN
                     Temp_Invoices i  on SO.SalesOrderId = i.SalesOrderId INNER JOIN
                     Branches ON SO.new_Branch = Branches.new_BranchId INNER JOIN
                     StatusReasonsLookup sl on i.StatusCode = sl.Id
                WHERE

                  ( CASE When sl.StatusCodeName = 'Canceled'  Then  ((month(new_CanceledDate) <> month(new_PostedDate) AND year(new_CanceledDate) <> year(new_PostedDate))
                                OR (month(new_CanceledDate) <> month(new_PostedDate) AND year(new_CanceledDate) = year(new_PostedDate))
                                OR (month(new_CanceledDate) = month(new_PostedDate) AND year(new_CanceledDate) <> year(new_PostedDate))

                            ) ELSE  (i.new_CanceledDate IS NULL)) END )
                    AND SO.new_Transaction =  @AbstractTransactionID
                     AND SO.new_Branch <> @BranchID_Metro
</code>```

Can something please guide how can I achieve this. I have tried but still unable to get it done.

答:
Try something using AND OR

possibly

```<code>SELECT SO.OrderNumber
    ,TransactionsLookup.TransactionName
    ,Branches.new_Name AS Branchname
    ,i.new_PostedDate
    ,min(i.new_PostedDate) OVER (PARTITION BY SO.OrderNumber) FirstPostedDate
FROM SalesOrders AS SO
INNER JOIN Temp_Invoices i ON SO.SalesOrderId = i.SalesOrderId
INNER JOIN Branches ON SO.new_Branch = Branches.new_BranchId
INNER JOIN StatusReasonsLookup sl ON i.StatusCode = sl.Id
WHERE (
        (sl.StatusCodeName = 'Canceled'
        AND (
            month(new_CanceledDate) <> month(new_PostedDate)
            AND year(new_CanceledDate) <> year(new_PostedDate)
            OR month(new_CanceledDate) <> month(new_PostedDate)
            AND year(new_CanceledDate) = year(new_PostedDate)
            OR month(new_CanceledDate) = month(new_PostedDate)
            AND year(new_CanceledDate) <> year(new_PostedDate)
            )
            OR sl.StatusCodeName != 'Canceled'
            AND i.new_CanceledDate IS NULL)
        AND SO.new_Transaction = @AbstractTransactionID
        AND SO.new_Branch <> @BranchID_Metro
        )
</code>```

Body:
I am using following query which is working fine for me.

   SELECT   SO.OrderNumber, TransactionsLookup.TransactionName, Branches.new_Name AS Branchname, i.new_PostedDate,
                  min(i.new_PostedDate) over(partition by SO.OrderNumber) FirstPostedDate,

          FROM       SalesOrders AS SO INNER JOIN
                     Temp_Invoices i  on SO.SalesOrderId = i.SalesOrderId INNER JOIN
                     Branches ON SO.new_Branch = Branches.new_BranchId INNER JOIN
                     StatusReasonsLookup sl on i.StatusCode = sl.Id
                WHERE
                     SO.new_Transaction =  @AbstractTransactionID
                     AND SO.new_Branch <> @BranchID_Metro
                   AND ((month(new_CanceledDate) <> month(new_PostedDate) AND year(new_CanceledDate) <> year(new_PostedDate))
                    OR (month(new_CanceledDate) <> month(new_PostedDate) AND year(new_CanceledDate) = year(new_PostedDate))
                    OR (month(new_CanceledDate) = month(new_PostedDate) AND year(new_CanceledDate) <> year(new_PostedDate)) OR (i.new_CanceledDate IS NULL))

Now I have to make date compare cause conditional in where clause using case when something like this;

   SELECT   SO.OrderNumber, TransactionsLookup.TransactionName, Branches.new_Name AS Branchname, i.new_PostedDate,
                  min(i.new_PostedDate) over(partition by SO.OrderNumber) FirstPostedDate,

          FROM       SalesOrders AS SO INNER JOIN
                     Temp_Invoices i  on SO.SalesOrderId = i.SalesOrderId INNER JOIN
                     Branches ON SO.new_Branch = Branches.new_BranchId INNER JOIN
                     StatusReasonsLookup sl on i.StatusCode = sl.Id
                WHERE

                  ( CASE When sl.StatusCodeName = 'Canceled'  Then  ((month(new_CanceledDate) <> month(new_PostedDate) AND year(new_CanceledDate) <> year(new_PostedDate))
                                OR (month(new_CanceledDate) <> month(new_PostedDate) AND year(new_CanceledDate) = year(new_PostedDate))
                                OR (month(new_CanceledDate) = month(new_PostedDate) AND year(new_CanceledDate) <> year(new_PostedDate))

                            ) ELSE  (i.new_CanceledDate IS NULL)) END )
                    AND SO.new_Transaction =  @AbstractTransactionID
                     AND SO.new_Branch <> @BranchID_Metro

Can something please guide how can I achieve this. I have tried but still unable to get it done.

Body:
Try something using AND OR

possibly

SELECT SO.OrderNumber
    ,TransactionsLookup.TransactionName
    ,Branches.new_Name AS Branchname
    ,i.new_PostedDate
    ,min(i.new_PostedDate) OVER (PARTITION BY SO.OrderNumber) FirstPostedDate
FROM SalesOrders AS SO
INNER JOIN Temp_Invoices i ON SO.SalesOrderId = i.SalesOrderId
INNER JOIN Branches ON SO.new_Branch = Branches.new_BranchId
INNER JOIN StatusReasonsLookup sl ON i.StatusCode = sl.Id
WHERE (
        (sl.StatusCodeName = 'Canceled'
        AND (
            month(new_CanceledDate) <> month(new_PostedDate)
            AND year(new_CanceledDate) <> year(new_PostedDate)
            OR month(new_CanceledDate) <> month(new_PostedDate)
            AND year(new_CanceledDate) = year(new_PostedDate)
            OR month(new_CanceledDate) = month(new_PostedDate)
            AND year(new_CanceledDate) <> year(new_PostedDate)
            )
            OR sl.StatusCodeName != 'Canceled'
            AND i.new_CanceledDate IS NULL)
        AND SO.new_Transaction = @AbstractTransactionID
        AND SO.new_Branch <> @BranchID_Metro
        )


问:
Initializing LSTM hidden state Tensorflow/Keras
Can someone explain how can I initialize hidden state of LSTM in tensorflow? I am trying to build LSTM recurrent auto-encoder, so after i have that model trained i want to transfer learned hidden state of unsupervised model to hidden state of supervised model.
Is that even possible with current API?
This is paper I am trying to recreate:

http://papers.nips.cc/paper/5949-semi-supervised-sequence-learning.pdf

答:
As stated in the Keras API documentation for recurrent layers (https://keras.io/layers/recurrent/):

Note on specifying the initial state of RNNs

You can specify the initial state of RNN layers symbolically by calling them with the keyword argument initial_state. The value of initial_state should be a tensor or list of tensors representing the initial state of the RNN layer.

You can specify the initial state of RNN layers numerically by calling reset_states with the keyword argument states. The value of states should be a numpy array or list of numpy arrays representing the initial state of the RNN layer.

Since the LSTM layer has two states (hidden state and cell state) the value of initial_state and states is a list of two tensors.

Examples

Stateless LSTM

Input shape: (batch, timesteps, features) = (1, 10, 1)

Number of units in the LSTM layer = 8 (i.e. dimensionality of hidden and cell state)

import tensorflow as tf
import numpy as np

inputs = np.random.random([1, 10, 1]).astype(np.float32)

lstm = tf.keras.layers.LSTM(8)

c_0 = tf.convert_to_tensor(np.random.random([1, 8]).astype(np.float32))
h_0 = tf.convert_to_tensor(np.random.random([1, 8]).astype(np.float32))

outputs = lstm(inputs, initial_state=[h_0, c_0])
```
<h3>Stateful LSTM</h3>
<p>Input shape: (batch, timesteps, features) = (1, 10, 1)<br />
Number of units in the LSTM layer = 8 (i.e. dimensionality of hidden and cell state)</p>
<p>Note that for stateful lstm you need to specify also <code>batch_size</code>.</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import numpy as np
from pprint import pprint

inputs = np.random.random([1, 10, 1]).astype(np.float32)

lstm = tf.keras.layers.LSTM(8, stateful=True, batch_size=(1, 10, 1))

c_0 = tf.convert_to_tensor(np.random.random([1, 8]).astype(np.float32))
h_0 = tf.convert_to_tensor(np.random.random([1, 8]).astype(np.float32))

outputs = lstm(inputs, initial_state=[h_0, c_0])
</code>```

With a Stateful LSTM, the states are not reset at the end of each sequence and we can notice that the output of the layer correspond to the hidden state (i.e. lstm.states[0]) at the last timestep:

```<code>>>> pprint(outputs)
<tf.Tensor: id=821, shape=(1, 8), dtype=float32, numpy=
array([[ 0.07119043,  0.07012419, -0.06118739, -0.11008392,  0.00573938,
        -0.05663438,  0.11196419,  0.02663924]], dtype=float32)>
>>>
>>> pprint(lstm.states)
[<tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=
array([[ 0.07119043,  0.07012419, -0.06118739, -0.11008392,  0.00573938,
        -0.05663438,  0.11196419,  0.02663924]], dtype=float32)>,
 <tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=
array([[ 0.14726108,  0.13584498, -0.12986949, -0.22309153,  0.0125412 ,
        -0.11446435,  0.22290672,  0.05397629]], dtype=float32)>]
</code>```

Calling reset_states() it is possible to reset the states:

```<code>>>> lstm.reset_states()
>>> pprint(lstm.states)
[<tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=array([[0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)>,
 <tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=array([[0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)>]
>>>
</code>```

or to set them to a specific value:

```<code>>>> lstm.reset_states(states=[h_0, c_0])
>>> pprint(lstm.states)
[<tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=
array([[0.59103394, 0.68249655, 0.04518601, 0.7800545 , 0.3799634 ,
        0.27347744, 0.54415804, 0.9889024 ]], dtype=float32)>,
 <tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=
array([[0.43390197, 0.28252542, 0.27139077, 0.19655049, 0.7568088 ,
        0.05909375, 0.68569875, 0.19087408]], dtype=float32)>]
>>>
>>> pprint(h_0)
<tf.Tensor: id=422, shape=(1, 8), dtype=float32, numpy=
array([[0.59103394, 0.68249655, 0.04518601, 0.7800545 , 0.3799634 ,
        0.27347744, 0.54415804, 0.9889024 ]], dtype=float32)>
>>>
>>> pprint(c_0)
<tf.Tensor: id=421, shape=(1, 8), dtype=float32, numpy=
array([[0.43390197, 0.28252542, 0.27139077, 0.19655049, 0.7568088 ,
        0.05909375, 0.68569875, 0.19087408]], dtype=float32)>
>>>
</code>```

Body:
As stated in the Keras API documentation for recurrent layers (https://keras.io/layers/recurrent/):

Note on specifying the initial state of RNNs

You can specify the initial state of RNN layers symbolically by calling them with the keyword argument initial_state. The value of initial_state should be a tensor or list of tensors representing the initial state of the RNN layer.

You can specify the initial state of RNN layers numerically by calling reset_states with the keyword argument states. The value of states should be a numpy array or list of numpy arrays representing the initial state of the RNN layer.

Since the LSTM layer has two states (hidden state and cell state) the value of initial_state and states is a list of two tensors.

Examples

Stateless LSTM

Input shape: (batch, timesteps, features) = (1, 10, 1)

Number of units in the LSTM layer = 8 (i.e. dimensionality of hidden and cell state)

import tensorflow as tf
import numpy as np

inputs = np.random.random([1, 10, 1]).astype(np.float32)

lstm = tf.keras.layers.LSTM(8)

c_0 = tf.convert_to_tensor(np.random.random([1, 8]).astype(np.float32))
h_0 = tf.convert_to_tensor(np.random.random([1, 8]).astype(np.float32))

outputs = lstm(inputs, initial_state=[h_0, c_0])

Stateful LSTM

Input shape: (batch, timesteps, features) = (1, 10, 1)

Number of units in the LSTM layer = 8 (i.e. dimensionality of hidden and cell state)

Note that for stateful lstm you need to specify also batch_size.

import tensorflow as tf
import numpy as np
from pprint import pprint

inputs = np.random.random([1, 10, 1]).astype(np.float32)

lstm = tf.keras.layers.LSTM(8, stateful=True, batch_size=(1, 10, 1))

c_0 = tf.convert_to_tensor(np.random.random([1, 8]).astype(np.float32))
h_0 = tf.convert_to_tensor(np.random.random([1, 8]).astype(np.float32))

outputs = lstm(inputs, initial_state=[h_0, c_0])

With a Stateful LSTM, the states are not reset at the end of each sequence and we can notice that the output of the layer correspond to the hidden state (i.e. lstm.states[0]) at the last timestep:

>>> pprint(outputs)
<tf.Tensor: id=821, shape=(1, 8), dtype=float32, numpy=
array([[ 0.07119043,  0.07012419, -0.06118739, -0.11008392,  0.00573938,
        -0.05663438,  0.11196419,  0.02663924]], dtype=float32)>
>>>
>>> pprint(lstm.states)
[<tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=
array([[ 0.07119043,  0.07012419, -0.06118739, -0.11008392,  0.00573938,
        -0.05663438,  0.11196419,  0.02663924]], dtype=float32)>,
 <tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=
array([[ 0.14726108,  0.13584498, -0.12986949, -0.22309153,  0.0125412 ,
        -0.11446435,  0.22290672,  0.05397629]], dtype=float32)>]

Calling reset_states() it is possible to reset the states:

>>> lstm.reset_states()
>>> pprint(lstm.states)
[<tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=array([[0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)>,
 <tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=array([[0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)>]
>>>

or to set them to a specific value:

>>> lstm.reset_states(states=[h_0, c_0])
>>> pprint(lstm.states)
[<tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=
array([[0.59103394, 0.68249655, 0.04518601, 0.7800545 , 0.3799634 ,
        0.27347744, 0.54415804, 0.9889024 ]], dtype=float32)>,
 <tf.Variable 'lstm_1/Variable:0' shape=(1, 8) dtype=float32, numpy=
array([[0.43390197, 0.28252542, 0.27139077, 0.19655049, 0.7568088 ,
        0.05909375, 0.68569875, 0.19087408]], dtype=float32)>]
>>>
>>> pprint(h_0)
<tf.Tensor: id=422, shape=(1, 8), dtype=float32, numpy=
array([[0.59103394, 0.68249655, 0.04518601, 0.7800545 , 0.3799634 ,
        0.27347744, 0.54415804, 0.9889024 ]], dtype=float32)>
>>>
>>> pprint(c_0)
<tf.Tensor: id=421, shape=(1, 8), dtype=float32, numpy=
array([[0.43390197, 0.28252542, 0.27139077, 0.19655049, 0.7568088 ,
        0.05909375, 0.68569875, 0.19087408]], dtype=float32)>
>>>


问:
How CPU predicts, the instruction and data limits in the sequence of binary information of binary file?
How CPU Differentiate the instruction from the data? </p>

<p>How CPUs determines the length of instruction(it varies from 1 byte upto 15 byte max) while executing the code? if suppose the cpu does not determine the length of instruction, it may  take the data as a part of instruction. In that case ,  undesired result may come or cpu doesn't execute that instruction(if not in opcode sheet).  How cpu determines, whether it is data or instruction? </p>

答:
It doesn't have to predict.  Logically it decodes one byte at a time until it sees a complete instruction.  (or dword chunks for disp32 or imm32, or other multi-byte parts of an instruction implied by an earlier byte.)  The length of the instruction is implied by prefixes and the opcode + modrm + SIB bytes.  After looking at those, the CPU knows for sure how many more instruction bytes it needs to fetch.

But a real CPU only has to give the illusion of doing that, and can look at later bytes as long as it eventually does the right thing if they turn out not to be part of an instruction that should execute.

Physically in a real implementation, there's no problem speculatively loading later bytes as long as you eventually do the right thing.

e.g. L1 instruction cache uses 64-byte lines, so logical execution reaching a byte means the whole 64-byte chunk of memory will be in the I-cache, even if it's also in the L1 D-cache because you did some data load instructions on other bytes in that same line.

And fetch from L1I cache isn't single bytes at a time either, of course.  On modern x86, decode looks at blocks of 32 or 16 bytes to find instruction boundaries.  e.g. lets look at P6-family, which doesn't have a uop cache so it does always fetch/decode from L1I.

From Agner Fog's microarch PDF, in the PPro/PII/PIII section:

6.2 Instruction fetch

Instruction codes are fetched from the code cache in aligned 16-byte chunks into a double
buffer that can hold two 16-byte chunks. The purpose of the double buffer is to make it
possible to decode an instruction that crosses a 16-byte boundary (i.e. an address divisible
by 16). The code is passed on from the double buffer to the decoders in blocks which I will
call IFETCH blocks (instruction fetch blocks).  The IFETCH blocks are up to 16 bytes long. In
most cases, the instruction fetch unit makes each IFETCH block start at an instruction
boundary rather than a 16-byte boundary. However, the instruction fetch unit needs
information from the instruction length decoder in order to know where the instruction
boundaries are. If this information is not available in time then it may start an IFETCH block
at a 16-byte boundary. This complication will be discussed in more detail below.

The pre-decoder pipeline stage then finds instruction boundaries (assuming they're all valid instructions), then (following the predictions made by the branch-prediction unit) the machine code for 3 instructions is sent to the 3 decoders in parallel.  (Core2 widened to 4 decoders, Skylake widened to 5 decoders even though the pipeline width stays at 4 uops wide).

If there's an illegal instruction in there somewhere (or an unconditional jmp, or a jcc that happens to be taken), then later "instructions" are meaningless and get discarded upon discovery of that fact.

https://www.realworldtech.com/nehalem/5/ talks about the decode stages in Nehalem, the last generation of P6-family microarchitectures.  But Agner Fog's description is probably more useful in terms of understanding how the CPU can look at a bunch of bytes, and then end up only using the ones that should logically be executed as instructions.

Body:
How CPU Differentiate the instruction from the data?

How CPUs determines the length of instruction(it varies from 1 byte upto 15 byte max) while executing the code? if suppose the cpu does not determine the length of instruction, it may  take the data as a part of instruction. In that case ,  undesired result may come or cpu doesn't execute that instruction(if not in opcode sheet).  How cpu determines, whether it is data or instruction?


问:
Issue on Connection with Cordapp to Springboot
I am new to Springboot. Currently, I am working on Corda Blockchain, I am facing some issues in connecting my cordapp through spring-boot.
enter image description here

enter image description here

If anyone have any reference or solution,kindly share it help me to solve this problem

答:
You don't set the values inside NodeRPCConnection; see example here:

https://github.com/corda/samples/blob/release-V4/cordapp-example/clients/src/main/kotlin/com/example/server/NodeRPCConnection.kt

They are injected when you run one of the runPartyServer gradle tasks:

https://github.com/corda/samples/blob/release-V4/cordapp-example/clients/build.gradle

For example to start PartyA webserver, all you have to do is type: ./gradlew runPartyAServer.

Obviously, you must first start your node then run the webserver.


问:
Can I have multiple packages inside a single go module? How?
I have a Go module whose name is 'tatata'. It is only developed in my machine and thus it does not contain any path to any URL in the module name.

If I have only one main package in my module it works correctly.
However, if I create two packages in the module, I am experiencing some problems.

This is the tree:

```<code>./|
  |- go.mod
  |-src
     |- main
     |   | - main.go
     |
     |- api
         | - api.go

</code>```

The content of the files:

go.mod

```<code>module tatata

go 1.13
</code>```

main.go

```<code>package main

import "fmt"
import "tatata/api"

func main() {
  fmt.Println("Hello world")
  api.Test1()
}
</code>```

api.go

```<code>package api

import "fmt"
func Test1() {
   fmt.Println("Testing API")
}
</code>```

When I try to build, I issue go build ./src/main and I get the following error:
build tatata/src/main: cannot load tatata/api: malformed module path "tatata/api": missing dot in first path element

Now, if I try to put a dummy dot, like renaming the module to tatata.com I get the error build tatata.com/src/main: cannot load tatata.com/api: cannot find module providing package tatata.com/api as obviously my package/module is not available in that URL.

GOPATH is empty, i.e. not set.

Questions:

a) What is the right way, i.e. naming of modules and imports when using multiple packages inside a single Go module?

b) Is it impossible to have a Go module without dots in its name?!

c) Can you point me to any working example that has a building set-up with a single go module and multiple packages in the module?

答:
Can I have multiple packages inside a single go module?

Yes, of course.

How?

You have to do nothing, it just works.

(Your problem is: You try to import your api package by a wrong name.
Import paths inside a module are of the form <modulename>/<relative-filepath-from-module-root>.)

Body:
I have a Go module whose name is 'tatata'. It is only developed in my machine and thus it does not contain any path to any URL in the module name.

If I have only one main package in my module it works correctly.
However, if I create two packages in the module, I am experiencing some problems.

This is the tree:

./|
  |- go.mod
  |-src
     |- main
     |   | - main.go
     |
     |- api
         | - api.go

The content of the files:

go.mod

module tatata

go 1.13

main.go

package main

import "fmt"
import "tatata/api"

func main() {
  fmt.Println("Hello world")
  api.Test1()
}

api.go

package api

import "fmt"
func Test1() {
   fmt.Println("Testing API")
}

When I try to build, I issue go build ./src/main and I get the following error:
build tatata/src/main: cannot load tatata/api: malformed module path "tatata/api": missing dot in first path element

Now, if I try to put a dummy dot, like renaming the module to tatata.com I get the error build tatata.com/src/main: cannot load tatata.com/api: cannot find module providing package tatata.com/api as obviously my package/module is not available in that URL.

GOPATH is empty, i.e. not set.

Questions:

a) What is the right way, i.e. naming of modules and imports when using multiple packages inside a single Go module?

b) Is it impossible to have a Go module without dots in its name?!

c) Can you point me to any working example that has a building set-up with a single go module and multiple packages in the module?


问:
Is it possible to use tqdm for a process that isn't a loop?
I am writing a program in which an operation takes a few seconds (loading a large file). Luckily, it always takes the same amount of time. So, for the sake of the user, I want to make a progress bar. However, tqdm seems to be designed for loops. Let's say that sleep(10) is the process that takes time. How do I work this out?

I want to make a progress bar for a long process that is not a loop.

```<code>from time import time, sleep
from tqdm import tqdm

for i in tqdm([1]):
    sleep(10)
</code>```

The problem with this code is that the progress bar will stay at zero, then jump to 100% at the end of the process. I want a progress bar that evolves consistently over the course of 10 seconds.

答:
You can define a chunk size. A bar that lasts 10 seconds assumes you already know the time it takes to load the file...

Try this

```<code>from tqdm import tqdm_notebook as tqdm

chunk_size = 1000
total_chunks=nrows/chunk_size

chunks = pd.read_sql_query(query, connection, index_col='index_name',chunksize= chunk_size)
raw_train_data=pd.DataFrame()

with tqdm(total=total_chunks) as pbar:

    for chunk in chunks:
        raw_train_data = pd.concat([raw_train_data, chunk])
        pbar.update(1)
</code>```

Body:
I am writing a program in which an operation takes a few seconds (loading a large file). Luckily, it always takes the same amount of time. So, for the sake of the user, I want to make a progress bar. However, tqdm seems to be designed for loops. Let's say that sleep(10) is the process that takes time. How do I work this out?

I want to make a progress bar for a long process that is not a loop.

from time import time, sleep
from tqdm import tqdm

for i in tqdm([1]):
    sleep(10)

The problem with this code is that the progress bar will stay at zero, then jump to 100% at the end of the process. I want a progress bar that evolves consistently over the course of 10 seconds.

Body:
You can define a chunk size. A bar that lasts 10 seconds assumes you already know the time it takes to load the file...

Try this

from tqdm import tqdm_notebook as tqdm

chunk_size = 1000
total_chunks=nrows/chunk_size

chunks = pd.read_sql_query(query, connection, index_col='index_name',chunksize= chunk_size)
raw_train_data=pd.DataFrame()

with tqdm(total=total_chunks) as pbar:

    for chunk in chunks:
        raw_train_data = pd.concat([raw_train_data, chunk])
        pbar.update(1)


问:
How do I get formatted JSON in .NET using C#?
I am using .NET JSON parser and would like to serialize my config file so it is readable. So instead of:

{"blah":"v", "blah2":"v2"}
```
<p>I would like something nicer like:</p>
<pre class="lang-json prettyprint-override"><code>{
    "blah":"v",
    "blah2":"v2"
}
</code>```

My code is something like this:

using System.Web.Script.Serialization;

var ser = new JavaScriptSerializer();
configSz = ser.Serialize(config);
using (var f = (TextWriter)File.CreateText(configFn))
{
    f.WriteLine(configSz);
    f.Close();
}
```

答:
This worked for me. In case someone is looking for a VB.NET version.

@imports System
@imports System.IO
@imports Newtonsoft.Json

Public Shared Function JsonPrettify(ByVal json As String) As String
  Using stringReader = New StringReader(json)

    Using stringWriter = New StringWriter()
      Dim jsonReader = New JsonTextReader(stringReader)
      Dim jsonWriter = New JsonTextWriter(stringWriter) With {
          .Formatting = Formatting.Indented
      }
      jsonWriter.WriteToken(jsonReader)
      Return stringWriter.ToString()
    End Using
  End Using
End Function
```

Body:
I am using .NET JSON parser and would like to serialize my config file so it is readable. So instead of:

{"blah":"v", "blah2":"v2"}

I would like something nicer like:

{
    "blah":"v",
    "blah2":"v2"
}

My code is something like this:

using System.Web.Script.Serialization;

var ser = new JavaScriptSerializer();
configSz = ser.Serialize(config);
using (var f = (TextWriter)File.CreateText(configFn))
{
    f.WriteLine(configSz);
    f.Close();
}


问:
Alignment image
I'm working on a site which needs an image centered in the div on the left side, centered off the right div with a background.

I tried to a common solution, but for some reason, it won't work. It must be responsive as well, so I'm a bit in the dark over here. See my fiddle for the example.

```<code><div class="container-fluid">
 <div class="row">
<div class="col-12 col-sm-6">
  <div class="leftSide">
    <img src="https://images.pexels.com/photos/3755760/pexels-photo-3755760.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" class="img-fluid imgLeft">
  </div>
</div>
<div class="col-12 col-sm-6">
  <div class="rightSide">
    <h3>
    Some text
    </h3>
    <p>
    Some more text
    </p>
   <button type="button" class="btn btn-primary">Some text</button>
  </div>
</div>
</code>```

https://jsfiddle.net/Onno0297/grvwxby2/1/

答:
If I understand your question correctly then below code will work.

Visit https://jsfiddle.net/alishapatel/n3ap1vjo/4/!

.leftSide {
  height: 100%;
  display: flex;
  align-items: center;
}

.rightSide {
  background: #313131;
  height: 546px;
  color: #fff;
}

.rightSide h3 {
  text-align: center;
  padding-top: 200px;
}

.rightSide p {
  text-align: center;
}
.btn.btn-primary {
  margin: 0 auto;
  display: block;
}

.imgLeft {
  max-height: 400px;
  max-width: 300px;
  margin: 0 auto;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container-fluid">
  <div class="row">
    <div class="col-12 col-sm-6">
      <div class="leftSide">
        <img src="https://images.pexels.com/photos/3755760/pexels-photo-3755760.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" class="img-fluid imgLeft">
      </div>
    </div>
    <div class="col-12 col-sm-6">
      <div class="rightSide">
        <h3>
        Some text
        </h3>
        <p>
        Some more text
        </p>
       <button type="button" class="btn btn-primary">Some text</button>
      </div>
    </div>
  </div>
</div></code>```

Title: Alignment image

Body:
I'm working on a site which needs an image centered in the div on the left side, centered off the right div with a background.

I tried to a common solution, but for some reason, it won't work. It must be responsive as well, so I'm a bit in the dark over here. See my fiddle for the example.

    Some text

    Some more text

   <button type="button" class="btn btn-primary">Some text</button>

https://jsfiddle.net/Onno0297/grvwxby2/1/

Body:
If I understand your question correctly then below code will work.

Visit https://jsfiddle.net/alishapatel/n3ap1vjo/4/!

.leftSide {
  height: 100%;
  display: flex;
  align-items: center;
}

.rightSide {
  background: #313131;
  height: 546px;
  color: #fff;
}

.rightSide h3 {
  text-align: center;
  padding-top: 200px;
}

.rightSide p {
  text-align: center;
}
.btn.btn-primary {
  margin: 0 auto;
  display: block;
}

.imgLeft {
  max-height: 400px;
  max-width: 300px;
  margin: 0 auto;
  width: 100%;
}

<div class="container-fluid">
  <div class="row">
    <div class="col-12 col-sm-6">
      <div class="leftSide">
        <img src="https://images.pexels.com/photos/3755760/pexels-photo-3755760.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" class="img-fluid imgLeft">
      </div>
    </div>
    <div class="col-12 col-sm-6">
      <div class="rightSide">
        <h3>
        Some text
        </h3>
        <p>
        Some more text
        </p>
       <button type="button" class="btn btn-primary">Some text</button>
      </div>
    </div>
  </div>
</div>


问:
How to pass to the next element when the requested value is not found in a json file
I am quite a beginner on Python. I am trying to extract analytics infos from homebrew packackages APIs through Request module. To do so I first dynamically get the urls for each package and then I loop over each url to get the infos I need. The script runs well until the loop stops over the "carina" package. I suppose the stopping is due to the fact the path package_json['analytics']['install']['30d'][package_name] is no longer correct in the [package_name] part (the package name in the analytics dictionary becomes "carina --HEAD").

For this time I would like the loop just pass to the next package and print an error message.

So far I tried to solve it using the following:

```<code>    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass
</code>```

but it doesn't work.

Could anyone help me, please?

The script

```<code>r = requests.get("https://formulae.brew.sh/api/formula.json")
packages_json = r.json()
packages_string = json.dumps(packages_json, indent=2)

results = []

t1 = time.perf_counter()

for package in packages_json:

    package_name = package["name"]
    package_desc = package["desc"]
    package_url = f'https://formulae.brew.sh/api/formula/{package_name}.json'

    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass

    installs_30 = package_json['analytics']['install']['30d'][package_name]
    installs_90 = package_json['analytics']['install']['90d'][package_name]
    installs_365 = package_json['analytics']['install']['365d'][package_name]

    data = {
        "nome": package_name,
        "descrizione": package_desc,
        "analytics": {
            "30d": installs_30,
            "90d": installs_90,
            "365d": installs_365
        }
    }

    results.append(data)

    time.sleep(r.elapsed.total_seconds())

    if r.status_code != 200:
        print (f"Got error for {package_name}")
    else:
        print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')

t2 = time.perf_counter()

print(f"Finito in {t2-t1} secondi")

with open("packages_info.json", "w") as f:
    json.dump(results, f, indent=2)
</code>```

The Error message

```<code>---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-42e0fb795383> in <module>
     16
     17
---> 18     installs_30 = package_json['analytics']['install']['30d'][package_name]
     19     installs_90 = package_json['analytics']['install']['90d'][package_name]
     20     installs_365 = package_json['analytics']['install']['365d'][package_name]

KeyError: 'carina'
</code>```

答:
I think there are issues in your syntax in the code mentioned above.
Try this -</p>

```<code>try:
    r = requests.get(package_url)
    package_json = r.json()
    installs_30 = package_json['analytics']['install']['30d'[package_name]
    installs_90 = package_json['analytics']['install']['90d'[package_name]
    installs_365 = package_json['analytics']['install']['365d'[package_name]
except KeyError:
    pass
</code>```

Body:
I am quite a beginner on Python. I am trying to extract analytics infos from homebrew packackages APIs through Request module. To do so I first dynamically get the urls for each package and then I loop over each url to get the infos I need. The script runs well until the loop stops over the "carina" package. I suppose the stopping is due to the fact the path package_json['analytics']['install']['30d'][package_name] is no longer correct in the [package_name] part (the package name in the analytics dictionary becomes "carina --HEAD").

For this time I would like the loop just pass to the next package and print an error message.

So far I tried to solve it using the following:

    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass

but it doesn't work.

Could anyone help me, please?

The script

r = requests.get("https://formulae.brew.sh/api/formula.json")
packages_json = r.json()
packages_string = json.dumps(packages_json, indent=2)

results = []

t1 = time.perf_counter()

for package in packages_json:

    package_name = package["name"]
    package_desc = package["desc"]
    package_url = f'https://formulae.brew.sh/api/formula/{package_name}.json'

    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass

    installs_30 = package_json['analytics']['install']['30d'][package_name]
    installs_90 = package_json['analytics']['install']['90d'][package_name]
    installs_365 = package_json['analytics']['install']['365d'][package_name]

    data = {
        "nome": package_name,
        "descrizione": package_desc,
        "analytics": {
            "30d": installs_30,
            "90d": installs_90,
            "365d": installs_365
        }
    }

    results.append(data)

    time.sleep(r.elapsed.total_seconds())

    if r.status_code != 200:
        print (f"Got error for {package_name}")
    else:
        print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')

t2 = time.perf_counter()

print(f"Finito in {t2-t1} secondi")

with open("packages_info.json", "w") as f:
    json.dump(results, f, indent=2)

The Error message

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-42e0fb795383> in <module>
     16
     17
---> 18     installs_30 = package_json['analytics']['install']['30d'][package_name]
     19     installs_90 = package_json['analytics']['install']['90d'][package_name]
     20     installs_365 = package_json['analytics']['install']['365d'][package_name]

KeyError: 'carina'

Body:
I think there are issues in your syntax in the code mentioned above.
Try this -

try:
    r = requests.get(package_url)
    package_json = r.json()
    installs_30 = package_json['analytics']['install']['30d'[package_name]
    installs_90 = package_json['analytics']['install']['90d'[package_name]
    installs_365 = package_json['analytics']['install']['365d'[package_name]
except KeyError:
    pass


问:
how to remove other rows with same Word in the SQL table column
how to remove other rows with same Word in the SQL Table column

For example

```<code>StudentUserID     SessionID

DSteve             101
DSteve             102
CJohn              101
</code>```

For Reporting purpose we only need first ever row with StudentUserID

答:
You can use row_number() :

```<code>select t.*
from (select t.*,
             row_number() over (partition by StudentUserID order by SessionID) as seq
      from table t
     ) t
where seq = 1;
</code>```

Body:
how to remove other rows with same Word in the SQL Table column

For example

StudentUserID     SessionID

DSteve             101
DSteve             102
CJohn              101

For Reporting purpose we only need first ever row with StudentUserID

Body:
You can use row_number() :

select t.*
from (select t.*,
             row_number() over (partition by StudentUserID order by SessionID) as seq
      from table t
     ) t
where seq = 1;


答:
Match the entire line:

```<code>grep -E '^Word$'
</code>```

or

```<code>grep -P '^Word$'
</code>```

Use -i to make it case insensitive, -w to only match entire words only.

Title: Grep for exact match when there is no more words

Body:
I have two strings like below:

Word

More than one word

How to use grep to match only with the first one?
I would like to have results when there is no more characters around the word I'm searching for.
When there is a string like the second one, it should find nothing.

Is it possible to achieve with grep?

Body:
Match the entire line:

grep -E '^Word$'

or

grep -P '^Word$'

Use -i to make it case insensitive, -w to only match entire words only.


答:
Would abort (leaving a core dump) or throw (allowing for alternate data capture) accommodate your needs?

Do you really want to have switch statements that don't cover the full enumeration? I nearly always try to list all the possible cases (to no-op) with no default case so that gcc will warn me if new enumerations are added, as it may be required to handle them rather than letting it silently (during compile) fall into the default.

Title: Emulating GCC's __builtin_unreachable?

Body:
I get a whole lot of warnings about switches that only partially covers the range of an enumeration switched over. Therefor, I would like to have a "default" for all those switches and put __builtin_unreachable (GCC builtin) in that case, so that the compiler know that case is not reachable.

However, I came to know that GCC4.3 does not support that builtin yet. Is there any good way to emulate that functionality? I thought about dereferencing a null pointer instead, but that may have other undesirable effects/warnings and such. Do you have any better idea?


问:
Hide package in conda environment (without removing)
I need to check if a piece of Python code works as expected when a given package is installed and when it is not. My conda working environment already has this package installed, and I'm looking for a way to "hide" it. I know I could:

Remove + test + re-install the package

Create a brand new environment without this package

but:

I need to run checks multiple times as the code evolves, and this quickly becomes a hassle

The environment is rather large (numerous packages) and I also need to test this on other packages, which means I'd need several similar environments

It would be ideal if I could just tell conda: "act as if this package is not installed". Can this be done?

答:
How about creating a mock module with the same name and put it first in your PYTHONTPATH? Its only content could be

```<code>raise ImportError
</code>```

This way, any import in your code will receive an ImportError as if it hadn't found the module.

To revert, simply reset your PYTHONPATH

Body:
How about creating a mock module with the same name and put it first in your PYTHONTPATH? Its only content could be

raise ImportError

This way, any import in your code will receive an ImportError as if it hadn't found the module.

To revert, simply reset your PYTHONPATH


问:
Calculating daily averages in pd.Series
I have a Dataframe series with 30s frequency.

```<code>df.head()
</code>```

I want to calculate the daily averages for all signals in that series but it doesnt seem to work. I tried both

```<code>df_average = df.to_period('D')
df.resample('D')
</code>```

And i get:

I want to have only 1 line per day. Why do i get more?
Thank you

答:
@jezrael is sure way to go. Could also try;</p>

```<code>df.groupby(df.index.date).mean()
</code>```

Title: Calculating daily averages in pd.Series

Body:
I have a Dataframe series with 30s frequency.

df.head()

I want to calculate the daily averages for all signals in that series but it doesnt seem to work. I tried both

df_average = df.to_period('D')
df.resample('D')

And i get:

I want to have only 1 line per day. Why do i get more?
Thank you

Body:
@jezrael is sure way to go. Could also try;

df.groupby(df.index.date).mean()


问:
Angular Parameter $routeParams and http.get params method didn't worked
I am trying to build a blog website using only front-end. My blog data is in an api.
 I have already build the blog feeds where list of different blogs are shown using angularjs get method. But for the detailed view of the blog, I need to a single blog data result from the api.
I have already tried using $routeParams option. But it didn't worked. My blog api has id parameter which return the blog data of the specific blogid. Please help me to solve this problem.

blogdetail.html (template)

```<code><div>
  <div><h1>Blog Details</h1></div>

  <div ng-repeat="xr in blog">
    {{xr.BLOGID}}

  <div>
</div>
</code>```

blogController.js (Controller)

```<code>'use strict';
app.controller('blogController', ['$scope','$http', function ($scope, $http, $routeParams) {
    $http.get('http://example.com/api/blog/', {
        params: {id: $routeParams.id}
    })
       .then(function(res){
          $scope.blog = res.data;
        }).catch(function(response) {
        console.log("ERROR:", response);
    });
}]);
</code>```

route Provider of blog detail part of the website

```<code>$routeProvider
    .when("/Blog/:id", {
        controller : "blogController" ,
        templateUrl : "views/BlogDetail.html"
    })
</code>```

This was the error i was getting -
TypeError: Cannot read property 'id' of undefined

答:
u need to add all parameters in the array before the function which are needed in the function, otherwise they are not defined.

the issue is here ['$scope','$http', function

```<code>'use strict';
    app.controller('blogController', ['$scope','$http', '$routeParams', function ($scope, $http, $routeParams) {
        $http.get('http://example.com/api/blog/', {
            params: {id: $routeParams.id}
        })
           .then(function(res){
              $scope.blog = res.data;
            }).catch(function(response) {
            console.log("ERROR:", response);
        });
    }]);
</code>```

Body:
I am trying to build a blog website using only front-end. My blog data is in an api.
 I have already build the blog feeds where list of different blogs are shown using angularjs get method. But for the detailed view of the blog, I need to a single blog data result from the api.
I have already tried using $routeParams option. But it didn't worked. My blog api has id parameter which return the blog data of the specific blogid. Please help me to solve this problem.

blogdetail.html (template)

Blog Details

    {{xr.BLOGID}}

blogController.js (Controller)

'use strict';
app.controller('blogController', ['$scope','$http', function ($scope, $http, $routeParams) {
    $http.get('http://example.com/api/blog/', {
        params: {id: $routeParams.id}
    })
       .then(function(res){
          $scope.blog = res.data;
        }).catch(function(response) {
        console.log("ERROR:", response);
    });
}]);

route Provider of blog detail part of the website

$routeProvider
    .when("/Blog/:id", {
        controller : "blogController" ,
        templateUrl : "views/BlogDetail.html"
    })

This was the error i was getting -
TypeError: Cannot read property 'id' of undefined

Body:
u need to add all parameters in the array before the function which are needed in the function, otherwise they are not defined.

the issue is here ['$scope','$http', function

'use strict';
    app.controller('blogController', ['$scope','$http', '$routeParams', function ($scope, $http, $routeParams) {
        $http.get('http://example.com/api/blog/', {
            params: {id: $routeParams.id}
        })
           .then(function(res){
              $scope.blog = res.data;
            }).catch(function(response) {
            console.log("ERROR:", response);
        });
    }]);


问:
unauthenticated calls return 200 status
I have a spring boot application. I have added a security layer for it goes like this:

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${allowed.paths}")
    private List<String> allowedPaths;

    @Autowired
    private TestCenterAuthProvider authProvider;

    @Override
    public void configure(AuthenticationManagerBuilder auth){
        auth.authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors().disable()
                .authorizeRequests()
                .antMatchers(allowedPaths.toArray(new String[0]))
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}
</code>```

this provides POST localhost:8080/login endpoint by default with default HTML representation.

Now any unauthenticated call I do returns 200 OK with HTML response for the login page. I need this to just return 403. and I am unable to figure this out.

答:
insert

```<code>.exceptionHandling()
                .defaultAuthenticationEntryPointFor(
                        new Http403ForbiddenEntryPoint(),
                        new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"))
            .and()
            .authorizeRequests()
</code>```

to enable 403's

Title: unauthenticated calls return 200 status

Body:
I have a spring boot application. I have added a security layer for it goes like this:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${allowed.paths}")
    private List<String> allowedPaths;

    @Autowired
    private TestCenterAuthProvider authProvider;

    @Override
    public void configure(AuthenticationManagerBuilder auth){
        auth.authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors().disable()
                .authorizeRequests()
                .antMatchers(allowedPaths.toArray(new String[0]))
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
}

this provides POST localhost:8080/login endpoint by default with default HTML representation.

Now any unauthenticated call I do returns 200 OK with HTML response for the login page. I need this to just return 403. and I am unable to figure this out.

Body:
insert

.exceptionHandling()
                .defaultAuthenticationEntryPointFor(
                        new Http403ForbiddenEntryPoint(),
                        new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"))
            .and()
            .authorizeRequests()

to enable 403's


问:
Asking for user input between 2 genders using a while loop and to be stored in a variable?
Want to create a small program that can ask a user a question. Do you want your character to be Male or Female? And output the result. However as you can tell the results are poor from my side.

Can someone give me a hand in fixing this mess as I feel I have over complicated it.

Just some general rules that the program must have:

It must accept both "Male" and "male" as input and vice versa for
female

The user input must be stored in the variable created.

If the user types anything else that is not: 'female' 'Female' 'male' or 'Male' they must try the question again (which is why I put in a while loop)

It's strange but this should be simple for me normally but I've made a bit of a mess of it.

Any help would be appreciated :)

```<code>gender = None

gender = str(input("Enter your Gender1: "))
while gender != 'Male' or 'male' or 'female' or 'Female':
    gender = input("Enter your Gender2: ")
if gender in ['Male', 'male']:
    print("You have chosen Male")
if gender in ['Female', 'female']:
    print("You have chosen Female")

print(gender)
</code>```

I don't mind the whole method changing where options can be used such as:

Press 1 for 'Male' or 2 for 'Female'

Would be of a help :)

答:
Instead of comparing twice eg. gender != 'Male' or gender != 'male' use lower.

while gender.lower() != 'male' ...
```

Body:
Want to create a small program that can ask a user a question. Do you want your character to be Male or Female? And output the result. However as you can tell the results are poor from my side.

Can someone give me a hand in fixing this mess as I feel I have over complicated it.

Just some general rules that the program must have:

It must accept both "Male" and "male" as input and vice versa for
female

The user input must be stored in the variable created.

If the user types anything else that is not: 'female' 'Female' 'male' or 'Male' they must try the question again (which is why I put in a while loop)

It's strange but this should be simple for me normally but I've made a bit of a mess of it.

Any help would be appreciated :)

gender = None

gender = str(input("Enter your Gender1: "))
while gender != 'Male' or 'male' or 'female' or 'Female':
    gender = input("Enter your Gender2: ")
if gender in ['Male', 'male']:
    print("You have chosen Male")
if gender in ['Female', 'female']:
    print("You have chosen Female")

print(gender)

I don't mind the whole method changing where options can be used such as:

Press 1 for 'Male' or 2 for 'Female'

Would be of a help :)


问:
Importing tensorflow tensors into tensorflow js
I was hoping to load a tensor image (can also be numpy array) into tensorflow js as an input tensor. I was wondering if there was any possible way of accomplishing this. (I don't want to load the raw image, I want to load it after preprocessing done in python). Thanks!</p>

答:
Numpy array can be serialized and saved to json

```<code>with open('data.json', 'w') as f:
  json.dump(numpy_array.tolist(), f)
</code>```

Once the data is saved to a json file, it can be retrieved in a js code

```<code>const data = fs.readFileSync('data.json', 'utf8')

tf.tensor(data).print()
</code>```

Body:
Numpy array can be serialized and saved to json

with open('data.json', 'w') as f:
  json.dump(numpy_array.tolist(), f)

Once the data is saved to a json file, it can be retrieved in a js code

const data = fs.readFileSync('data.json', 'utf8')

tf.tensor(data).print()


问:
Conflicts in Subversion when updating to old revision. The problem seems to be a merge -r I did some days ago. Should I have avoided this merge?
I've been coding on a single branch in Subversion for some days. Today I've decided to update to an old revision, buried like 30 revisions ago.

Strangely enough, I got conflicts in one of my files. The only reason I see for a problem with this branch would be a merge -r I did some days ago to make my (at the time) head go back to what it was on an old revision.

So, assuming the problem was with the merge -r, I have 2 questions:

I did the -r merge so that I could come back to an old revision and then commit it, such that I could start working on from that point on (I basically wanted to discard my X last commits at the time). Was doing this -r merge the right approach? Should I just have created another branch instead? That's certainly what I'd do with git's logical branches, as that'd be way cleaner, but then again, I don't want to "flood" this subversion repo with branches of mine. Maybe I could just create a branch with the old revision and delete this one?

Let's say I'll now correct the conflicts. My initial idea when coming back to this revision was to do a -r merge (again). So if in a week I decide I want to come back again, I'll have conflicts again, right? How to avoid this cycle?

This question can, maybe, be formulated in another way. When doing "try and error" coding (with this I mean that I'll have to "come back" many times), how should I organize my Subversion repo?

Thanks

答: It looks like you need to do a set of modifications parting from one specific revision, then discard the whole set of revisions, and start all over again, several times. If this is the case then I would recommend creating a new branch for each "attempt" and deleting the whole branch for discarding the modifications, or re-integrate it then delete it when you are happy with the code. I think any other approach will give you "merge headaches", but of course I might be wrong.</p>


问:
Correct way to check Java version from BASH script
How can I check whether Java is available (in the PATH or via JAVA_HOME) from a bash script and make sure the version is at least 1.5?</p>

答:
You could also compare the jdk class version number with javap:

```<code>javap -verbose java.lang.String | grep "major version" | cut -d " " -f5
</code>```

If its java 8, this will print 52, and 55 for java 11. With this you can make a simple comparison and you don't have to deal with the version string parsing.

Body:
You could also compare the jdk class version number with javap:

javap -verbose java.lang.String | grep "major version" | cut -d " " -f5

If its java 8, this will print 52, and 55 for java 11. With this you can make a simple comparison and you don't have to deal with the version string parsing.


问:
V-for is not iterating through objects
I have an array of coupon objects named offers:

```<code> [{ "coupon":
             { "id": "1", "name": "Coupon 1" }
  },
  { "coupon":
             { "id": "2", "name": "Coupon 2" }
  }]
</code>```

And i try to iterate trough it like this:

```<code><div v-for="(coupon, $index) in offers" :key="$index">
     <p>{{coupon.id}}</p>
</div>
</code>```

The problem is that div does not iterate anything.

答:
you have to travel through the object, the First coupon is an element name so try this. This should work</p>

```<code>div v-for="(coupon, $index) in offers" :key="$index">
    <p>{{coupon.coupon.id}}</p>
</div>
</code>```

Title: V-for is not iterating through objects

Body:
I have an array of coupon objects named offers:

 [{ "coupon":
             { "id": "1", "name": "Coupon 1" }
  },
  { "coupon":
             { "id": "2", "name": "Coupon 2" }
  }]

And i try to iterate trough it like this:

{{coupon.id}}

The problem is that div does not iterate anything.

Body:
you have to travel through the object, the First coupon is an element name so try this. This should work

div v-for="(coupon, $index) in offers" :key="$index">
    <p>{{coupon.coupon.id}}</p>
</div>