问:
Firebase cloud functions - typescript - undefine type
I have an interesting problem here...

I used the official documentation for firestore-events

and from there I get this code in order to test and playing around.

```<code>exports.countNameChanges = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
    // Retrieve the current and previous value
    const data = change.after.data();
    const previousData = change.before.data();

    // We'll only update if the name has changed.
    // This is crucial to prevent infinite loops.
    if (data.name == previousData.name) return null;

    // Retrieve the current count of name changes
    let count = data.name_change_count;
    if (!count) {
        count = 0;
    }

    // Then return a promise of a set operation to update the count
    return change.after.ref.set({
        name_change_count: count + 1
    }, { merge: true });
});
</code>```

with those import's which I've put them (so maybe I miss one)

```<code>import * as functions from 'firebase-functions';

import * as Storage from '@google-cloud/storage';
const gcs = new Storage.Storage();
</code>```

I think everything it looks fine but I get this error message:

```<code>src/index.ts:33:13 - error TS2532: Object is possibly 'undefined'.

33         if (data.name == previousData.name) return null;
               ~~~~

src/index.ts:33:26 - error TS2532: Object is possibly 'undefined'.

33         if (data.name == previousData.name) return null;
                            ~~~~~~~~~~~~

src/index.ts:36:21 - error TS2532: Object is possibly 'undefined'.

36         let count = data.name_change_count;
                       ~~~~
</code>```

What's going on? What I'm missing here? Is anyone knowing what I'm doing wrong and can help me? I was thinking that everything should be fine and workable in the documentation.

答:
It is, in fact, working code, the only thing complaining is your linter.

Actually, the problem is that onUpdate triggers when the doc is created, updated or deleted, so it is possible that change.after.data() is undefined if the document is deleted, that's why the linter is complaining.

I would recommend you to use // @ts-ignore on top on any line that is complaining if your intention is getting started, then later when you feel more confortable, you can investigate more which is this case is to put some validation to ensure that you are executing that line like:

```<code>if (previousData && data.name == previousData.name) return null;
</code>```

Body:
I have an interesting problem here...

I used the official documentation for firestore-events

and from there I get this code in order to test and playing around.

exports.countNameChanges = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
    // Retrieve the current and previous value
    const data = change.after.data();
    const previousData = change.before.data();

    // We'll only update if the name has changed.
    // This is crucial to prevent infinite loops.
    if (data.name == previousData.name) return null;

    // Retrieve the current count of name changes
    let count = data.name_change_count;
    if (!count) {
        count = 0;
    }

    // Then return a promise of a set operation to update the count
    return change.after.ref.set({
        name_change_count: count + 1
    }, { merge: true });
});

with those import's which I've put them (so maybe I miss one)

import * as functions from 'firebase-functions';

import * as Storage from '@google-cloud/storage';
const gcs = new Storage.Storage();

I think everything it looks fine but I get this error message:

src/index.ts:33:13 - error TS2532: Object is possibly 'undefined'.

33         if (data.name == previousData.name) return null;
               ~~~~

src/index.ts:33:26 - error TS2532: Object is possibly 'undefined'.

33         if (data.name == previousData.name) return null;
                            ~~~~~~~~~~~~

src/index.ts:36:21 - error TS2532: Object is possibly 'undefined'.

36         let count = data.name_change_count;
                       ~~~~

What's going on? What I'm missing here? Is anyone knowing what I'm doing wrong and can help me? I was thinking that everything should be fine and workable in the documentation.

Body:
It is, in fact, working code, the only thing complaining is your linter.

Actually, the problem is that onUpdate triggers when the doc is created, updated or deleted, so it is possible that change.after.data() is undefined if the document is deleted, that's why the linter is complaining.

I would recommend you to use // @ts-ignore on top on any line that is complaining if your intention is getting started, then later when you feel more confortable, you can investigate more which is this case is to put some validation to ensure that you are executing that line like:

if (previousData && data.name == previousData.name) return null;


来源: stackexchange

问:
Get difference of two address of array(use & operator)
I want to get the address difference between two elements in an array.

```<code>int vector[] = { 28, 41, 7 };

printf("%d\n", &vector[2]); // 1703652
printf("%d\n", &vector[1]); // 1703648
printf("%d\n", &vector);    // 1703644

printf("%d\n", &vector[1] - &vector); // 1
</code>```

The result I expect(Last Line) is 4 because the data type was int.

Further, each result of address has 4 differences.

But why is the result of

```<code>&vector[1] - &vector
</code>```

1 and not 4?

And how do I get 4 by using subtraction operator?

答:
pointer arithmetics in C language works on the type of the object. It does not matter how big the object is. The reference to the next object minus reference to the previous is always one object

So if we add 5 to the pointer it will point 5 objects ahead. If we increment the pointer it will reference the next object. It helps indexing and iterating across the objects.

When you printf the address (your format is wrong - you should use %p instead) it is printed in bytes. So the difference between the consecutive objects will be equal the size of the object (plus the optional padding).

And How to I get 4 by using subtraction operator???

Cast the pointers to the type which sizeof is one for example char.

```<code>(char *)&vector[1] - (char *)&vector
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to get the address difference between two elements in an array.

int vector[] = { 28, 41, 7 };

printf("%d\n", &vector[2]); // 1703652
printf("%d\n", &vector[1]); // 1703648
printf("%d\n", &vector);    // 1703644

printf("%d\n", &vector[1] - &vector); // 1

The result I expect(Last Line) is 4 because the data type was int.

Further, each result of address has 4 differences.

But why is the result of

&vector[1] - &vector

1 and not 4?

And how do I get 4 by using subtraction operator?

Body:
pointer arithmetics in C language works on the type of the object. It does not matter how big the object is. The reference to the next object minus reference to the previous is always one object

So if we add 5 to the pointer it will point 5 objects ahead. If we increment the pointer it will reference the next object. It helps indexing and iterating across the objects.

When you printf the address (your format is wrong - you should use %p instead) it is printed in bytes. So the difference between the consecutive objects will be equal the size of the object (plus the optional padding).

And How to I get 4 by using subtraction operator???

Cast the pointers to the type which sizeof is one for example char.

(char *)&vector[1] - (char *)&vector


答:
You can calculate the difference of pointers to byte-sized values by casting the pointers to char *:

```<code>printf("%d\n", (char*)&vector[1] - (char*)vector);
</code>```

Title: Get difference of two address of array(use & operator)

Body:
You can calculate the difference of pointers to byte-sized values by casting the pointers to char *:

printf("%d\n", (char*)&vector[1] - (char*)vector);


问:
Custom Authentication in django is not working
I am new to django and I wanted to authenticate user on email or username with password hence I wrote a custom authentication as shown in documentation but it doesn't seem to be called and I have no idea what do I do?

settings.py

```<code>AUTHENTICATION_BACKENDS = ('accounts.backend.AuthBackend',)
</code>```

views.py

```<code>def login(request):
    if request.method == 'POST':
        username_or_email = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username_or_email, password=password)
        print(user)
        if user is not None:
            return reverse('task:home')
        else:
            messages.error(request, "Username or password is invalid")
            return render(request, 'accounts/login.html')
    else:
         return render(request, 'accounts/login.html')
</code>```

backend.py

```<code>from django.contrib.auth.models import User
from django.db.models import Q

class AuthBackend(object):
    supports_object_permissions = True
    supports_anonymous_user = False
    supports_inactive_user = False

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

    def authenticate(self, username, password):
        print('inside custom auth')
        try:
            user = User.objects.get(
                Q(username=username) | Q(email=username) )
            print(user)
        except User.DoesNotExist:
            return None
        print(user)
        if user.check_password(password):
             return user
        else:
            return None
</code>```

I wrote this print statements in my class to check if they are being called and being written in console. However, they are not being printed and the print statement in views.py prints None

答:
```<code>import sys
from django.contrib.auth import get_user_model

from accounts.models import Token

User = get_user_model()

class PasswordlessAuthenticationBackend:

    def authenticate(self, uid=None):
        print('uuuuuuuuu')
        print('uid', uid, file=sys.stderr)
        if not Token.objects.filter(uid=uid).exists():
            print('no token found', file=sys.stderr)
            return None
        token = Token.objects.get(uid=uid)
        print('got token', file=sys.stderr)
        try:
            user = User.objects.get(email=token.email)
            print('got user', file=sys.stderr)
            return user
        except User.DoesNotExist:
            print('new user', file=sys.stderr)
            return User.objects.create(email=token.email)

    def get_user(self, email):
        try:
            return User.objects.get(email=email)
        except User.DoesNotExist:
            return None
</code>```

Body:
I am new to django and I wanted to authenticate user on email or username with password hence I wrote a custom authentication as shown in documentation but it doesn't seem to be called and I have no idea what do I do?

settings.py

AUTHENTICATION_BACKENDS = ('accounts.backend.AuthBackend',)

views.py

def login(request):
    if request.method == 'POST':
        username_or_email = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username_or_email, password=password)
        print(user)
        if user is not None:
            return reverse('task:home')
        else:
            messages.error(request, "Username or password is invalid")
            return render(request, 'accounts/login.html')
    else:
         return render(request, 'accounts/login.html')

backend.py

from django.contrib.auth.models import User
from django.db.models import Q

class AuthBackend(object):
    supports_object_permissions = True
    supports_anonymous_user = False
    supports_inactive_user = False

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

    def authenticate(self, username, password):
        print('inside custom auth')
        try:
            user = User.objects.get(
                Q(username=username) | Q(email=username) )
            print(user)
        except User.DoesNotExist:
            return None
        print(user)
        if user.check_password(password):
             return user
        else:
            return None

I wrote this print statements in my class to check if they are being called and being written in console. However, they are not being printed and the print statement in views.py prints None


问:
CORS in asp.net core 2.1 and angular
There is quite a lot of discussions on this subject, however none is working for me. I have a asp.net core api 2.1 with an angular 7 app.

Error:

"fleet:1 Access to XMLHttpRequest at
  'https://localhost:44354/api/test' from origin 'http://localhost:4200'
  has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
  header is present on the requested resource."

Startup:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

    services.AddCors((options =>
    {
        options.AddPolicy("AzurePolicy", builder => builder
                    .WithOrigins("http://localhost:4200", "https://localhost:4200", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials()
         );
    }));

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

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

    app.UseCors("AzurePolicy");
    app.UseAuthentication();

    app.UseMvc();
}
</code>```

Config:

```<code>{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "xx.com",
    "TenantId": "xx",
    "ClientId": "xx"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}
</code>```

I even added following to controller:

```<code> [EnableCors("AllowSpecificOrigin")]
</code>```

Is there more things you can do here?

答:
Add AzureActiveDirectory settings in appsettings.json

Like this:

```<code>"AzureAd": {
  "Instance": "https://login.microsoftonline.com",
  "Domain": "AD_DOMAIN",
  "TenantId": "TENANT_GUID",
  "ClientId": "APPLICATIONID_GUID"
}
</code>```

For more details, follow this Article

Title: CORS in asp.net core 2.1 and angular

Body:
There is quite a lot of discussions on this subject, however none is working for me. I have a asp.net core api 2.1 with an angular 7 app.

Error:

"fleet:1 Access to XMLHttpRequest at
  'https://localhost:44354/api/test' from origin 'http://localhost:4200'
  has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
  header is present on the requested resource."

Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

    services.AddCors((options =>
    {
        options.AddPolicy("AzurePolicy", builder => builder
                    .WithOrigins("http://localhost:4200", "https://localhost:4200", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials()
         );
    }));

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

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

    app.UseCors("AzurePolicy");
    app.UseAuthentication();

    app.UseMvc();
}

Config:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "xx.com",
    "TenantId": "xx",
    "ClientId": "xx"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

I even added following to controller:

 [EnableCors("AllowSpecificOrigin")]

Is there more things you can do here?

Body:
Add AzureActiveDirectory settings in appsettings.json

Like this:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com",
  "Domain": "AD_DOMAIN",
  "TenantId": "TENANT_GUID",
  "ClientId": "APPLICATIONID_GUID"
}

For more details, follow this Article


问:
How to enable cookies while sending a request with Java Jersey client?
I need to send a get request to an API and get the results. I am using Java, Jersey library in my project and I decided to use Jersey client in order to get the data. However, the API returns an error message which indicates that I should enable cookies to reach out this API. I can get correct response when try with applications like postman, or just with using a normal browser like chrome. But I could not find out how can I enable cookies in Java Jersey client object.

I searched to learn how to enable cookies in a Java Jersey client but I could not find any resource about it. So I could not try any solution.

My code is very simple:

```<code>    Client client = Client.create(); // Create jerseu client
    WebResource webResource = client.resource(BASEURI +  EXCHANGEINFO); // create web resource with a specific URI

    System.out.println(webResource
            .accept("application/json")
            .get(ClientResponse.class)
            .getEntity(String.class)); // Write results to console
</code>```

At the result of this request, I got the error that I mentioned above. How can I enable cookies while sending a request with Java Jersey client?

答:
As per the discussion, I have gone through the api you have provided. Actually, the api provides a misleading message while making rest call. If you look into the details of the error message which is received from the api call, it says.

The owner of this website (api.pro.coinbase.com) has banned your
  access based on your browser's signature (4e0a3c06895d89af-ua21).

So what is the answer ? The api actually wants that the call should be made from browser and each browser sends a header called "User-Agent". See what is user agent. However, I have solved your problem, you can check the complete code below.

```<code>import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class TestGetCallByJersey {
  public static void main(String[] args) {
    String resourceUri = "https://api.pro.coinbase.com/products";
    try {
      Client client = Client.create();
      WebResource webResource = client.resource(resourceUri);
      ClientResponse response =
          webResource
              .accept("application/json")
              .header("User-Agent", "Mozilla/5.0")
              .get(ClientResponse.class);

      System.out.println("response status = " + response.getStatus());
      String result = response.getEntity(String.class);
      System.out.println("Output from api call .... \n" + result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
</code>```

Currently, I have tested in Java 8 and I used the following jar file.

jersey-client version 1.8
If you are using, Maven, you can include the following dependency in pom.xml.

```<code><dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.8</version>
        </dependency>
</code>```

Body:
I need to send a get request to an API and get the results. I am using Java, Jersey library in my project and I decided to use Jersey client in order to get the data. However, the API returns an error message which indicates that I should enable cookies to reach out this API. I can get correct response when try with applications like postman, or just with using a normal browser like chrome. But I could not find out how can I enable cookies in Java Jersey client object.

I searched to learn how to enable cookies in a Java Jersey client but I could not find any resource about it. So I could not try any solution.

My code is very simple:

    Client client = Client.create(); // Create jerseu client
    WebResource webResource = client.resource(BASEURI +  EXCHANGEINFO); // create web resource with a specific URI

    System.out.println(webResource
            .accept("application/json")
            .get(ClientResponse.class)
            .getEntity(String.class)); // Write results to console

At the result of this request, I got the error that I mentioned above. How can I enable cookies while sending a request with Java Jersey client?

Body:
As per the discussion, I have gone through the api you have provided. Actually, the api provides a misleading message while making rest call. If you look into the details of the error message which is received from the api call, it says.

The owner of this website (api.pro.coinbase.com) has banned your
  access based on your browser's signature (4e0a3c06895d89af-ua21).

So what is the answer ? The api actually wants that the call should be made from browser and each browser sends a header called "User-Agent". See what is user agent. However, I have solved your problem, you can check the complete code below.

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class TestGetCallByJersey {
  public static void main(String[] args) {
    String resourceUri = "https://api.pro.coinbase.com/products";
    try {
      Client client = Client.create();
      WebResource webResource = client.resource(resourceUri);
      ClientResponse response =
          webResource
              .accept("application/json")
              .header("User-Agent", "Mozilla/5.0")
              .get(ClientResponse.class);

      System.out.println("response status = " + response.getStatus());
      String result = response.getEntity(String.class);
      System.out.println("Output from api call .... \n" + result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Currently, I have tested in Java 8 and I used the following jar file.

jersey-client version 1.8
If you are using, Maven, you can include the following dependency in pom.xml.

<dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.8</version>
        </dependency>


问:
The variables I updated in my forEach, return to their original value
I am trying to query, that would get all of the earning and withdrawal amount and sum, but somehow after the forEach loop is done and exits, all of the updated values I placed in a variable return to their original values.</p>

```<code>  var withdrawbalance = 0;
  var totalearning = 0;

  userplans.forEach((up) => {
    DepositEarning.findOne({deposit: up.deposit._id})
      .then(depositearning => {
        withdrawbalance += parseInt(depositearning.WithdrawableBalance, 10);
      });
    Earning.findOne({deposit: up.deposit._id})
      .then(earnings => {
        totalearning += parseInt(earnings.Earning, 10);
    });
  })

  console.log(withdrawbalance);
  console.log(totalearning);
</code>```

答:
Here is a functional approach to it that removes the mutation side-effect inside the loop. You need an engine that supports Object Rest spread for this:</p>

```<code>async function calculate(userplans) {
    const add = (acc, n) => acc + n;
    const flatten = (acc, e) => ({
        depositEarnings: [...acc.depositEarnings, e.depositEarnings],
        earnings: [...acc.earnings, e.earnings]
    });

    const {depositEarnings, earnings} = (await Promise.all(userplans
          .map(async (up) => ({
              depositEarnings: await DepositEarning.findOne({deposit: up.deposit._id}),
              earnings: await Earning.findOne({deposit: up.deposit._id})
}))))
          .reduce(flatten, {depositEarnings: [], earnings: []});

    const withdrawalBalance = depositEarnings
          .map(d => parseInt(d.WithdrawableBalance, 10))
          .reduce(add, 0);
    const totalEarning = earnings
          .map(e => parseInt(e.Earning, 10))
          .reduce(add, 0);

    console.log(withdrawalBalance);
    console.log(totalEarning);
}
</code>```

Body:
I am trying to query, that would get all of the earning and withdrawal amount and sum, but somehow after the forEach loop is done and exits, all of the updated values I placed in a variable return to their original values.

  var withdrawbalance = 0;
  var totalearning = 0;

  userplans.forEach((up) => {
    DepositEarning.findOne({deposit: up.deposit._id})
      .then(depositearning => {
        withdrawbalance += parseInt(depositearning.WithdrawableBalance, 10);
      });
    Earning.findOne({deposit: up.deposit._id})
      .then(earnings => {
        totalearning += parseInt(earnings.Earning, 10);
    });
  })

  console.log(withdrawbalance);
  console.log(totalearning);

Body:
Here is a functional approach to it that removes the mutation side-effect inside the loop. You need an engine that supports Object Rest spread for this:

async function calculate(userplans) {
    const add = (acc, n) => acc + n;
    const flatten = (acc, e) => ({
        depositEarnings: [...acc.depositEarnings, e.depositEarnings],
        earnings: [...acc.earnings, e.earnings]
    });

    const {depositEarnings, earnings} = (await Promise.all(userplans
          .map(async (up) => ({
              depositEarnings: await DepositEarning.findOne({deposit: up.deposit._id}),
              earnings: await Earning.findOne({deposit: up.deposit._id})
}))))
          .reduce(flatten, {depositEarnings: [], earnings: []});

    const withdrawalBalance = depositEarnings
          .map(d => parseInt(d.WithdrawableBalance, 10))
          .reduce(add, 0);
    const totalEarning = earnings
          .map(e => parseInt(e.Earning, 10))
          .reduce(add, 0);

    console.log(withdrawalBalance);
    console.log(totalEarning);
}


问:
PHP / LARAVEL 5 ErrorException in MainController.php
all.
I have problems after making some new steps. I'm rails developer, but now i have to do some support in php/laravel project. After making some UI + backend in project(adding OpenGraph in project + admin) - i made a command - php artisan migrate:fresh.
And now i have this code error.

(1/1) ErrorException
Trying to get property 'title' of non-object

in MainController.php line 78

MetaTag.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Setting
 *
 * @mixin \Eloquent
 */
class MetaTag extends Model
{
    /**
     * @var array
     */
    protected $table = "meta_tags";
    protected $fillable = ['title', 'description', 'keywords','og_type','og_title','og_description'];

}
```

<p>part of MainController.php</p>

<pre class="lang-php prettyprint-override"><code>

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use App\Http\Requests;

class MainController extends Controller
{
    public function index()
    {
        $main_banner = \App\Banner::where('type', '1')
            ->where('page', '1')
            ->where('active', '1')
            ->orderBy('order', 'asc')
            ->first();

        $premium_blocks = \App\Banner::where('type', '2')
            ->where('active', '1')
            ->orderBy('order', 'asc')
            ->get();

        $active_animations = \App\Setting::where('alias', 'anumations_active')->first();
        $active_films = \App\Setting::where('alias', 'films_active')->first();
        $active_games = \App\Setting::where('alias', 'games_active')->first();
        $active_heroes = \App\Setting::where('alias', 'heroes_active')->first();
        $active_news = \App\Setting::where('alias', 'news_active')->first();
        $active_soundtracks = \App\Setting::where('alias', 'soundtracks_active')->first();

        $animations = \App\Animation::where('active', '1')
            ->orderBy('order', 'asc')
            ->get();
        $films = \App\Film::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $games = \App\Game::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $heroes = \App\Hero::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $news = \App\News::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $soundtracks = \App\Soundtrack::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();

        $arr_month_rus = \Config::get('settings.arr_month_rus');
        $arr_month_rus_lower = \Config::get('settings.arr_month_rus_lower');
        $arr_games_types = \Config::get('settings.arr_games_types');
        $arr_news_types = \Config::get('settings.arr_news_types');

        $agent = new Agent();

        $browser = $agent->browser();
        $v = explode('.',$agent->version($agent->browser()));
        $version = $v[0];

        if (
            ($browser == "Internet Explorer" && $version > 10) ||
            ($browser == "Edge" && $version > 11) ||
            ($browser == "Firefox" && $version > 46) ||
            ($browser == "Opera" && $version > 38) ||
            ($browser == "Safari" && $version > 8) ||
            ($browser == "Chrome" && $version > 51)
        )
            $outdated = false;
        else $outdated = true;

        $meta_tags = \App\MetaTag::where('alias',  '=', 'main_page')->first();
        $title = $meta_tags->title;
        $description = $meta_tags->description;
        $keywords = $meta_tags->keywords;
        $og_title = $meta_tags->og_title;
        $og_description = $meta_tags->og_description;
        $og_type = $meta_tags->og_type;

        return view((($agent->isMobile()) ? 'mobile.home' : 'home'), compact(
            'main_banner',
            'premium_blocks',
            'animations',
            'films',
            'games',
            'heroes',
            'news',
            'soundtracks',
            'active_animations',
            'active_films',
            'active_games',
            'active_heroes',
            'active_news',
            'active_soundtracks',
            'arr_games_types',
            'arr_month_rus_lower',
            'arr_news_types',
            'arr_month_rus',
            'outdated',
            'title',
            'description',
            'keywords',
            'og_title',
            'og_type',
            'og_description'
        ));
    }
</code>```

I expect just solve this little problem.
Thanks!

答:
I think you should try this. the logic here is to check if the record exist in the database first.</p>

```<code>$meta_tags_count = \App\MetaTag::where('alias', 'main_page')->count();
if($meta_tags_count>0){
    $meta_tags = \App\MetaTag::where('alias', 'main_page')->first(); // You CAN  ignore the equal sign
    $title = $meta_tags->title;
    $description = $meta_tags->description;
    $keywords = $meta_tags->keywords;
    $og_title = $meta_tags->og_title;
    $og_description = $meta_tags->og_description;
    $og_type = $meta_tags->og_type;
}
 else {
    $title = "";
    $description = "";
    $keywords = "";
    $og_title = "";
    $og_description = "";
    $og_type = "";
}
</code>```

Body:
all.
I have problems after making some new steps. I'm rails developer, but now i have to do some support in php/laravel project. After making some UI + backend in project(adding OpenGraph in project + admin) - i made a command - php artisan migrate:fresh.
And now i have this code error.

(1/1) ErrorException
Trying to get property 'title' of non-object

in MainController.php line 78

MetaTag.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Setting
 *
 * @mixin \Eloquent
 */
class MetaTag extends Model
{
    /**
     * @var array
     */
    protected $table = "meta_tags";
    protected $fillable = ['title', 'description', 'keywords','og_type','og_title','og_description'];

}

part of MainController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use App\Http\Requests;

class MainController extends Controller
{
    public function index()
    {
        $main_banner = \App\Banner::where('type', '1')
            ->where('page', '1')
            ->where('active', '1')
            ->orderBy('order', 'asc')
            ->first();

        $premium_blocks = \App\Banner::where('type', '2')
            ->where('active', '1')
            ->orderBy('order', 'asc')
            ->get();

        $active_animations = \App\Setting::where('alias', 'anumations_active')->first();
        $active_films = \App\Setting::where('alias', 'films_active')->first();
        $active_games = \App\Setting::where('alias', 'games_active')->first();
        $active_heroes = \App\Setting::where('alias', 'heroes_active')->first();
        $active_news = \App\Setting::where('alias', 'news_active')->first();
        $active_soundtracks = \App\Setting::where('alias', 'soundtracks_active')->first();

        $animations = \App\Animation::where('active', '1')
            ->orderBy('order', 'asc')
            ->get();
        $films = \App\Film::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $games = \App\Game::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $heroes = \App\Hero::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $news = \App\News::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();
        $soundtracks = \App\Soundtrack::where('active', '1')
            ->where('checked', '1')
            ->orderBy('order', 'asc')
            ->get();

        $arr_month_rus = \Config::get('settings.arr_month_rus');
        $arr_month_rus_lower = \Config::get('settings.arr_month_rus_lower');
        $arr_games_types = \Config::get('settings.arr_games_types');
        $arr_news_types = \Config::get('settings.arr_news_types');

        $agent = new Agent();

        $browser = $agent->browser();
        $v = explode('.',$agent->version($agent->browser()));
        $version = $v[0];

        if (
            ($browser == "Internet Explorer" && $version > 10) ||
            ($browser == "Edge" && $version > 11) ||
            ($browser == "Firefox" && $version > 46) ||
            ($browser == "Opera" && $version > 38) ||
            ($browser == "Safari" && $version > 8) ||
            ($browser == "Chrome" && $version > 51)
        )
            $outdated = false;
        else $outdated = true;

        $meta_tags = \App\MetaTag::where('alias',  '=', 'main_page')->first();
        $title = $meta_tags->title;
        $description = $meta_tags->description;
        $keywords = $meta_tags->keywords;
        $og_title = $meta_tags->og_title;
        $og_description = $meta_tags->og_description;
        $og_type = $meta_tags->og_type;

        return view((($agent->isMobile()) ? 'mobile.home' : 'home'), compact(
            'main_banner',
            'premium_blocks',
            'animations',
            'films',
            'games',
            'heroes',
            'news',
            'soundtracks',
            'active_animations',
            'active_films',
            'active_games',
            'active_heroes',
            'active_news',
            'active_soundtracks',
            'arr_games_types',
            'arr_month_rus_lower',
            'arr_news_types',
            'arr_month_rus',
            'outdated',
            'title',
            'description',
            'keywords',
            'og_title',
            'og_type',
            'og_description'
        ));
    }

I expect just solve this little problem.
Thanks!

Body:
I think you should try this. the logic here is to check if the record exist in the database first.

$meta_tags_count = \App\MetaTag::where('alias', 'main_page')->count();
if($meta_tags_count>0){
    $meta_tags = \App\MetaTag::where('alias', 'main_page')->first(); // You CAN  ignore the equal sign
    $title = $meta_tags->title;
    $description = $meta_tags->description;
    $keywords = $meta_tags->keywords;
    $og_title = $meta_tags->og_title;
    $og_description = $meta_tags->og_description;
    $og_type = $meta_tags->og_type;
}
 else {
    $title = "";
    $description = "";
    $keywords = "";
    $og_title = "";
    $og_description = "";
    $og_type = "";
}


问:
I have a problem about sleep for loop on ruby
guys i write a chat bot for twitch in hobby.  i want to spam a word in chat in a time like that write to chat"hello" and wait 10 sec then write again
i did that but in my code have a answer system like that when anyone write to chat !hey my bot answering hello to him. and when i tried in same system that not working</p>

```<code>until @socket.eof? do
message = @socket.gets
    puts message
    if message.match(/PRIVMSG ##{@channel} :(.*)$/)
     a = Time.now
     b = Time.now + 5
     while a < b do
      write_to_chat("!prime")
      a += 4
      sleep(20)

     end

     end
       if message.match(/PRIVMSG ##{@channel} :(.*)$/)
      content = $~[1]
      username = message.match(/@(.*).tmi.twitch.tv/)[1]

       if content.include? 'theoSea'

       write_to_chat(" theoAse theoAse theoAse")

       end
</code>```

答:
i solved it with scheduler
i wanted a code for write every 5 min i tried lots of method but sleep command
and i found this link "https://github.com/jmettraux/rufus-scheduler"
all in link u can use this gem.
thx for everything guys. </p>

Body:
guys i write a chat bot for twitch in hobby.  i want to spam a word in chat in a time like that write to chat"hello" and wait 10 sec then write again
i did that but in my code have a answer system like that when anyone write to chat !hey my bot answering hello to him. and when i tried in same system that not working

until @socket.eof? do
message = @socket.gets
    puts message
    if message.match(/PRIVMSG ##{@channel} :(.*)$/)
     a = Time.now
     b = Time.now + 5
     while a < b do
      write_to_chat("!prime")
      a += 4
      sleep(20)

     end

     end
       if message.match(/PRIVMSG ##{@channel} :(.*)$/)
      content = $~[1]
      username = message.match(/@(.*).tmi.twitch.tv/)[1]

       if content.include? 'theoSea'

       write_to_chat(" theoAse theoAse theoAse")

       end


问:
How to achieve per-batch-file echo on/off setting?
We have some complex bat files where one calls another, which calls yet another. All of them have a @echo off at the top.

For debugging, I would like to selectively turn echo on in some of them. What is the easiest way to do this? Some ideas I have so far:

Change the setting only in top level files. But this will only work for the few files known to be non-top-level. Otherwise any file can call any other.

Change it back to previous setting before exiting each bat file. I will need to ensure there is a single point of exit. I will also need to know the setting on entry, which I don't know how to find.

Thanks in advance.

答:
Call echo on at the beginning of the files you want to turn it on for and their dependencies (and echo off at the end if you wish).

Note: You said it's for debugging, so it doesn't have to follow a grand scheme - it just has to produce output for now.

...unless I'm missing something, of course.

You could write a quick script to REM out the echo off calls as well. For each file you want to have echo on for, text-search for ".bat" to get the list of dependencies. Then run the REMming script on them and search those for ".bat", rinse-repeat.

Another option is if you don't mind seeing all output, just feed all the files through the REMming script. It's a bit easier than recursively seeking dependencies. Then put a big, blatent ECHO command at the beginning and end of the section you want to trace. Load the whole output into notepad and search for your bookmark.

For reference, if you just run the command ECHO without any parameters, you can see the current echo setting: "ECHO is on|off.".

OwnerDisplayName: Hemal Pandya

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: lc

LastEditorDisplayName: lc


问:
Entity Framework 4 - update/insert views
My EF schema has a mixture of tables and views from my database. My view entities are all read-only, I want to be able to update/insert into these entities. I've tried the following post without any luck:

http://smehrozalam.wordpress.com/2009/08/12/entity-framework-creating-a-model-using-views-instead-of-tables/

Anyone have another ideas/pointers - this must be doable.

cheers
David

答: Generally the post is correct. Using views in EF is hard. Another trick is first using tables to define your model and then replace tables in database with views with same names as tables.</p>

ContentLicense: CC BY-SA 3.0


问:
Confusion regarding kind of data returned by librosa.load and scipy.io.wavfile.read
I am new to audioprocessing, and need some help for my project.
Could someone explain me the difference between the kind of data that is returned by librosa.load, and scipy.io.wavefile.read? The former gives an array of floats while the latter gives an integer array. And the amusing part is that the size of the array returned in both cases are different.

Please provide some insight to this.
(You may use your own audiofile to reproduce the problem)

```<code>sig, sr = librosa.core.load(filepath, sr=None)
sig[:10]
array([ 0.00262944,  0.00108277, -0.00248273, -0.00865669, -0.0161767 ,
   -0.01958228, -0.01867038, -0.01742653, -0.01652605, -0.01589082],
  dtype=float32)

sr, y = scipy.io.wavfile.read(filepath)
y[:10]
array([  94,  -10, -217, -564, -627, -582, -527, -520, -440, -349],
  dtype=int16)

print(sig.shape)
(7711,)

y.shape
(5595,)
</code>```

答:
Take another look at the docstring for librosa.core.load.  It says right there in the first three sentences:

```<code>Load an audio file as a floating point time series.

Audio will be automatically resampled to the given rate (default sr=22050).

To preserve the native sampling rate of the file, use sr=None.
</code>```

So librosa is converting the data to floating point, and (by default) resampling the data to 22050 samples per second.  You used sr=None, so I don't know why the lengths of the arrays are coming out different.

Body:
I am new to audioprocessing, and need some help for my project.
Could someone explain me the difference between the kind of data that is returned by librosa.load, and scipy.io.wavefile.read? The former gives an array of floats while the latter gives an integer array. And the amusing part is that the size of the array returned in both cases are different.

Please provide some insight to this.
(You may use your own audiofile to reproduce the problem)

sig, sr = librosa.core.load(filepath, sr=None)
sig[:10]
array([ 0.00262944,  0.00108277, -0.00248273, -0.00865669, -0.0161767 ,
   -0.01958228, -0.01867038, -0.01742653, -0.01652605, -0.01589082],
  dtype=float32)

sr, y = scipy.io.wavfile.read(filepath)
y[:10]
array([  94,  -10, -217, -564, -627, -582, -527, -520, -440, -349],
  dtype=int16)

print(sig.shape)
(7711,)

y.shape
(5595,)

Body:
Take another look at the docstring for librosa.core.load.  It says right there in the first three sentences:

Load an audio file as a floating point time series.

Audio will be automatically resampled to the given rate (default sr=22050).

To preserve the native sampling rate of the file, use sr=None.

So librosa is converting the data to floating point, and (by default) resampling the data to 22050 samples per second.  You used sr=None, so I don't know why the lengths of the arrays are coming out different.


问:
Printing barcodes on a bluetooth thermal printer
I am working with a bluetooth thermal printer and was able to print normal text and invoice's as well. But i am not able to print barcodes.

I am generating barcode with ZXING library

```<code>OutputStream os = mBluetoothSocket.getOutputStream();

String text = mEditText.getText().toString();

MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

BitMatrix bitMatrix = multiFormatWriter.encode(text,BarcodeFormat.CODE_128,200,200);

BarcodeEncoder barcodeEncoder = new BarcodeEncoder();

Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);

os.write("Hello".getBytes()); //Prints Hello
</code>```

How can i print the bitmap using the same logic ?

I have tried some codes like

```<code>int size = bitmap.getRowBytes() * bitmap.getHeight();

ByteBuffer byteBuffer = ByteBuffer.allocate(size);

bitmap.copyPixelsToBuffer(byteBuffer);

byte[] byteArray = byteBuffer.array();

os.write(byteArray);
</code>```

But this gives a blank print and roll keep rolling

I am using Godex-MX30 printer

答:
You need to tell the printer that you are sending an image to print and specify how to print it.

Typically this is done with ESC/POS codes.  Most printers like this use ESC/POS codes.

ESC * is how that is specified.  You can look at the many examples in this questions java code or in this one's solution as well.

For more information, see Seiko Epson reference.

Not sure about this printer, but many of thermal receipt printers have support for creating and printing barcodes also using Esc/Pos Code.  You could try something like this.

Body:
I am working with a bluetooth thermal printer and was able to print normal text and invoice's as well. But i am not able to print barcodes.

I am generating barcode with ZXING library

OutputStream os = mBluetoothSocket.getOutputStream();

String text = mEditText.getText().toString();

MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

BitMatrix bitMatrix = multiFormatWriter.encode(text,BarcodeFormat.CODE_128,200,200);

BarcodeEncoder barcodeEncoder = new BarcodeEncoder();

Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);

os.write("Hello".getBytes()); //Prints Hello

How can i print the bitmap using the same logic ?

I have tried some codes like

int size = bitmap.getRowBytes() * bitmap.getHeight();

ByteBuffer byteBuffer = ByteBuffer.allocate(size);

bitmap.copyPixelsToBuffer(byteBuffer);

byte[] byteArray = byteBuffer.array();

os.write(byteArray);

But this gives a blank print and roll keep rolling

I am using Godex-MX30 printer


问:
Running shell command with git filter-branch
I'm trying to build an application that change git commit history timestamp with git filter-branch. But I am getting wrong timestamp when I execute following shell script and check git commit history with "git log". Am I doing wrong with using function argument? Any help?</p>

```<code>

fix_commit_date() {
    git filter-branch --env-filter \
    "if [ $GIT_COMMIT =  $(1) ]
     then
         export GIT_AUTHOR_DATE=\"$(2)\"
         export GIT_COMMITTER_DATE=\"$(2)\"
     fi" -f
}
fix_commit_date c1f456c87bd66cad07b24827946df5a44cac95f2 "Tue Mar 3 21:38:53 2009 -0800"

</code>```

答:
The following syntax is meant to evaluate code in a subshell and capture output:

```<code>$(code here)
</code>```

Whereas the following syntax(es) capture some of the ways to dereference positional parameters (see sh(1) for more):

```<code>$1
${1}
</code>```

So you are seeing incorrect results because you’ve attempted to run and capture output of the commands 1 and 2, which in all likelihood don’t exist.

Switch to one of the second syntaxes. And prefer to double quote both expansions.

Body:
I'm trying to build an application that change git commit history timestamp with git filter-branch. But I am getting wrong timestamp when I execute following shell script and check git commit history with "git log". Am I doing wrong with using function argument? Any help?

fix_commit_date() {
    git filter-branch --env-filter \
    "if [ $GIT_COMMIT =  $(1) ]
     then
         export GIT_AUTHOR_DATE=\"$(2)\"
         export GIT_COMMITTER_DATE=\"$(2)\"
     fi" -f
}
fix_commit_date c1f456c87bd66cad07b24827946df5a44cac95f2 "Tue Mar 3 21:38:53 2009 -0800"

Body:
The following syntax is meant to evaluate code in a subshell and capture output:

$(code here)

Whereas the following syntax(es) capture some of the ways to dereference positional parameters (see sh(1) for more):

$1
${1}

So you are seeing incorrect results because you’ve attempted to run and capture output of the commands 1 and 2, which in all likelihood don’t exist.

Switch to one of the second syntaxes. And prefer to double quote both expansions.


问:
Cannot Add Option List to Multiple Select jQuery
I want to create multi select option list like this example plugin. The option list is populated using ajax call to the database. The ajax call works fine but the option list is not being populated. I also followed this guide. Any help highly appreciated.

HTML

```<code><div class="form-group">
    <label for="langOpt">Select Option</label>
    <select class="form-control" name="langOpt[]" multiple id="langOpt">
    <!--option list-->
    </select>
</div>
</code>```

Plugin Call

```<code><script>
$('select[multiple]').multiselect();
</script>
</code>```

jQuery

```<code><script>
$('#langOpt').click(function () {

      $.ajax({
            type : "GET",
            dataType :'json',
            url : "<?php echo base_url('registration/get_opton_list') ?>",
            success : function(data) {
              $('#langOpt').html('');
              jQuery(data).each(function(i, item){
                $('#langOpt').append("<option value='"+ item.optionId+"'>" + item.optionName+ "</option>");

                //this ensure the ajax call, values print on console
                console.log(item.optionId);
                console.log(item.optionName);
              });

            }

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

UPDATE:
Calling plugin into ajax success gives an error

```<code>Uncaught TypeError: $(...).multiselect is not a function
    at Object.<anonymous> ((index):190)
    at Function.each (jquery.min.js:2)
    at k.fn.init.each (jquery.min.js:2)
    at Object.success ((index):183)
    at c (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at l (jquery.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery.min.js:2)
(anonymous) @ (index):190
each @ jquery.min.js:2
each @ jquery.min.js:2
success @ (index):183
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
l @ jquery.min.js:2
(anonymous) @ jquery.min.js:2
load (async)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
(anonymous) @ (index):176
dispatch @ jquery.min.js:2
v.handle @ jquery.min.js:2
</code>```

答:
Please apply multiselect plugin again in ajax respose(sucess)

```<code>  <script>
    $('#langOpt').click(function () {

     $.ajax({
        type : "GET",
        dataType :'json',
        url : "<?php echo base_url('registration/get_opton_list') ?>",
        success : function(data) {
          $('#langOpt').html('');
          jQuery(data).each(function(i, item){
            $('#langOpt').append("<option value='"+ item.optionId+"'>" + item.optionName+ "</option>");
            $('#langOpt').multiselect();
            //this ensure the ajax call, values print on console
            console.log(item.optionId);
            console.log(item.optionName);
          });

        }

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

Note : Make sure the CSS and JS of plugin is added successfully on your page.

Body:
I want to create multi select option list like this example plugin. The option list is populated using ajax call to the database. The ajax call works fine but the option list is not being populated. I also followed this guide. Any help highly appreciated.

HTML

    Select Option
    <select class="form-control" name="langOpt[]" multiple id="langOpt">

    </select>

Plugin Call

jQuery

UPDATE:
Calling plugin into ajax success gives an error

Uncaught TypeError: $(...).multiselect is not a function
    at Object.<anonymous> ((index):190)
    at Function.each (jquery.min.js:2)
    at k.fn.init.each (jquery.min.js:2)
    at Object.success ((index):183)
    at c (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at l (jquery.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery.min.js:2)
(anonymous) @ (index):190
each @ jquery.min.js:2
each @ jquery.min.js:2
success @ (index):183
c @ jquery.min.js:2
fireWith @ jquery.min.js:2
l @ jquery.min.js:2
(anonymous) @ jquery.min.js:2
load (async)
send @ jquery.min.js:2
ajax @ jquery.min.js:2
(anonymous) @ (index):176
dispatch @ jquery.min.js:2
v.handle @ jquery.min.js:2

Body:
Please apply multiselect plugin again in ajax respose(sucess)

  <script>
    $('#langOpt').click(function () {

     $.ajax({
        type : "GET",
        dataType :'json',
        url : "<?php echo base_url('registration/get_opton_list') ?>",
        success : function(data) {
          $('#langOpt').html('');
          jQuery(data).each(function(i, item){
            $('#langOpt').append("<option value='"+ item.optionId+"'>" + item.optionName+ "</option>");
            $('#langOpt').multiselect();
            //this ensure the ajax call, values print on console
            console.log(item.optionId);
            console.log(item.optionName);
          });

        }

      });
});

Note : Make sure the CSS and JS of plugin is added successfully on your page.


问:
Can I convert a null pointer of int to a long type by reinterpret_cast
int *pt = 0;

long i = reinterpret_cast<long>(pt);

Is i guaranteed to be 0? Is this well defined or implementation-defined?
I checked the c++ standard, but it only states that

A pointer to a data object or to a function (but not a pointer to member) can be converted to any integer type large enough to contain it.

In this case, pt doesn't point to any data object. Does the rule apply to this case?

答: I don't see why it wouldn't.  The issue is that the integer type in question wouldn't be able to hold values that high, but if it's a null pointer there's no problem.</p>


答:
I am not sure that the following is what the OP wants, but it corresponds to the problem description.

First, the column Date is coerced to class "POSIXct", to save some steps later on.

Then, compute max(L1) per day, reassemble with the data and apply the given formula.

```<code>library(dplyr)

L1 <- L1 %>% mutate(Date = as.POSIXct(Date, format = "%d.%m.%Y %H:%M"))

max24h_L1 <- L1 %>%
  mutate(Date  = cut(Date, breaks = "day")) %>%
  group_by(Date) %>%
  summarize(maxL1 = max(L1, na.rm = TRUE)) %>%
  mutate(Date = as.Date(as.character(Date))) %>%
  inner_join(L1 %>% mutate(Date = as.Date(Date))) %>%
  mutate(NewL1 = 0.714 * (maxL1/L1 - 1)^1.231)

max24h_L1
#Joining, by = "Date"
## A tibble: 10 x 4
#   Date       maxL1    L1    NewL1
#   <date>     <dbl> <dbl>    <dbl>
# 1 2019-04-08 0.666 0.654 0.00520
# 2 2019-04-08 0.666 0.656 0.00414
# 3 2019-04-08 0.666 0.653 0.00575
# 4 2019-04-08 0.666 0.652 0.00631
# 5 2019-04-08 0.666 0.657 0.00363
# 6 2019-04-08 0.666 0.649 0.00806
# 7 2019-04-08 0.666 0.665 0.000239
# 8 2019-04-08 0.666 0.647 0.00928
# 9 2019-04-08 0.666 0.66  0.00219
#10 2019-04-08 0.666 0.666 0
</code>```

Title: find 24 h max of a day and multiply by data of the day

Body:
I want to find the max of 24h of L1 and multiply the max of 24 by a formula with the data.

What I've tried:

require(dplyr)

    max24h_L1 <-L1 %>%
      group_by(Date = cut(Date, breaks="24 h")) %>%
      summarize(`L1` = max(`L1`, na.rm =T))

    max24h_L1 <- ((0.714) * ((max24h_L1/L1)-1)^1.231)

Data:

structure(list(Date = structure(1:10, .Label = c("08.04.2019 14:45",
"08.04.2019 14:50", "08.04.2019 14:55", "08.04.2019 15:00", "08.04.2019 15:05",
"08.04.2019 15:10", "08.04.2019 15:15", "08.04.2019 15:20", "08.04.2019 15:25",
"08.04.2019 15:30", "08.04.2019 15:35", "08.04.2019 15:40", "08.04.2019 15:45",
"08.04.2019 15:50", "08.04.2019 15:55", "08.04.2019 16:00", "08.04.2019 16:05",
"08.04.2019 16:10", "08.04.2019 16:15", "08.04.2019 16:20", "08.04.2019 16:25",
"08.04.2019 16:30", "08.04.2019 16:35", "08.04.2019 16:40", "08.04.2019 16:45",
"08.04.2019 16:50", "08.04.2019 16:55", "08.04.2019 17:00", "08.04.2019 17:05",
"08.04.2019 17:10", "08.04.2019 17:15", "08.04.2019 17:20", "08.04.2019 17:25",
"08.04.2019 17:30", "08.04.2019 17:35", "08.04.2019 17:40", "08.04.2019 17:45",
"08.04.2019 17:50", "08.04.2019 17:55", "08.04.2019 18:00", "08.04.2019 18:05",
"08.04.2019 18:10", "08.04.2019 18:15", "08.04.2019 18:20", "08.04.2019 18:25",
"08.04.2019 18:30", "08.04.2019 18:35", "08.04.2019 18:40", "08.04.2019 18:45",
"08.04.2019 18:50", "08.04.2019 18:55", "08.04.2019 19:00", "08.04.2019 19:05",
"08.04.2019 19:10", "08.04.2019 19:15", "08.04.2019 19:20", "08.04.2019 19:25",
"08.04.2019 19:30", "08.04.2019 19:35", "08.04.2019 19:40", "08.04.2019 19:45",
"08.04.2019 19:50", "08.04.2019 19:55", "08.04.2019 20:00", "08.04.2019 20:05",
"08.04.2019 20:10", "08.04.2019 20:15", "08.04.2019 20:20", "08.04.2019 20:25",
"08.04.2019 20:30", "08.04.2019 20:35", "08.04.2019 20:40", "08.04.2019 20:45",
"08.04.2019 20:50", "08.04.2019 20:55", "08.04.2019 21:00", "08.04.2019 21:05",
"08.04.2019 21:10", "08.04.2019 21:15", "08.04.2019 21:20", "08.04.2019 21:25",
"08.04.2019 21:30", "08.04.2019 21:35", "08.04.2019 21:40", "08.04.2019 21:45",
"08.04.2019 21:50", "08.04.2019 21:55", "08.04.2019 22:00", "08.04.2019 22:05",
"08.04.2019 22:10", "08.04.2019 22:15", "08.04.2019 22:20", "08.04.2019 22:25",
"08.04.2019 22:30", "08.04.2019 22:35", "08.04.2019 22:40", "08.04.2019 22:45",
"08.04.2019 22:50", "08.04.2019 22:55", "08.04.2019 23:00", "08.04.2019 23:05",
"08.04.2019 23:10", "08.04.2019 23:15", "08.04.2019 23:20", "08.04.2019 23:25",
"08.04.2019 23:30", "08.04.2019 23:35", "08.04.2019 23:40", "08.04.2019 23:45",
"08.04.2019 23:50", "08.04.2019 23:55", "09.04.2019 00:00", "09.04.2019 00:05",
"09.04.2019 00:10", "09.04.2019 00:15", "09.04.2019 00:20", "09.04.2019 00:25",
"09.04.2019 00:30", "09.04.2019 00:35", "09.04.2019 00:40", "09.04.2019 00:45",
"09.04.2019 00:50", "09.04.2019 00:55", "09.04.2019 01:00", "09.04.2019 01:05",
"09.04.2019 01:10", "09.04.2019 01:15", "09.04.2019 01:20", "09.04.2019 01:25",
"09.04.2019 01:30", "09.04.2019 01:35", "09.04.2019 01:40", "09.04.2019 01:45",
"09.04.2019 01:50", "09.04.2019 01:55", "09.04.2019 02:00", "09.04.2019 02:05",
"09.04.2019 02:10", "09.04.2019 02:15", "09.04.2019 02:20", "09.04.2019 02:25",
"09.04.2019 02:30", "09.04.2019 02:35", "09.04.2019 02:40", "09.04.2019 02:45",
"09.04.2019 02:50", "09.04.2019 02:55", "09.04.2019 03:00", "09.04.2019 03:05",
"09.04.2019 03:10", "09.04.2019 03:15", "09.04.2019 03:20", "09.04.2019 03:25",
"09.04.2019 03:30", "09.04.2019 03:35", "09.04.2019 03:40", "09.04.2019 03:45",
"09.04.2019 03:50", "09.04.2019 03:55", "09.04.2019 04:00", "09.04.2019 04:05",
"09.04.2019 04:10", "09.04.2019 04:15", "09.04.2019 04:20", "09.04.2019 04:25",
"09.04.2019 04:30", "09.04.2019 04:35", "09.04.2019 04:40", "09.04.2019 04:45",
"09.04.2019 04:50", "09.04.2019 04:55", "09.04.2019 05:00", "09.04.2019 05:05",
"09.04.2019 05:10", "09.04.2019 05:15", "09.04.2019 05:20", "09.04.2019 05:25",
"09.04.2019 05:30", "09.04.2019 05:35", "09.04.2019 05:40", "09.04.2019 05:45",
"09.04.2019 05:50", "09.04.2019 05:55", "09.04.2019 06:00", "09.04.2019 06:05",
"09.04.2019 06:10", "09.04.2019 06:15", "09.04.2019 06:20", "09.04.2019 06:25",
"09.04.2019 06:30", "09.04.2019 06:35", "09.04.2019 06:40", "09.04.2019 06:45",
"09.04.2019 06:50", "09.04.2019 06:55", "09.04.2019 07:00", "09.04.2019 07:05",
"09.04.2019 07:10", "09.04.2019 07:15", "09.04.2019 07:20", "09.04.2019 07:25",
"09.04.2019 07:30", "09.04.2019 07:35", "09.04.2019 07:40", "09.04.2019 07:45",
"09.04.2019 07:50", "09.04.2019 07:55", "09.04.2019 08:00", "09.04.2019 08:05",
"09.04.2019 08:10", "09.04.2019 08:15", "09.04.2019 08:20", "09.04.2019 08:25",
"09.04.2019 08:30", "09.04.2019 08:35", "09.04.2019 08:40", "09.04.2019 08:45",
"09.04.2019 08:50", "09.04.2019 08:55", "09.04.2019 09:00", "09.04.2019 09:05",
"09.04.2019 09:10", "09.04.2019 09:15", "09.04.2019 09:20", "09.04.2019 09:25",
"09.04.2019 09:30", "09.04.2019 09:35", "09.04.2019 09:40", "09.04.2019 09:45",
"09.04.2019 09:50", "09.04.2019 09:55", "09.04.2019 10:00", "09.04.2019 10:05"
), class = "factor"), L1 = c(0.654, 0.656, 0.653, 0.652, 0.657,
0.649, 0.665, 0.647, 0.66, 0.666)), row.names = c(NA, 10L), class = "data.frame")
>

Body:
I am not sure that the following is what the OP wants, but it corresponds to the problem description.

First, the column Date is coerced to class "POSIXct", to save some steps later on.

Then, compute max(L1) per day, reassemble with the data and apply the given formula.

library(dplyr)

L1 <- L1 %>% mutate(Date = as.POSIXct(Date, format = "%d.%m.%Y %H:%M"))

max24h_L1 <- L1 %>%
  mutate(Date  = cut(Date, breaks = "day")) %>%
  group_by(Date) %>%
  summarize(maxL1 = max(L1, na.rm = TRUE)) %>%
  mutate(Date = as.Date(as.character(Date))) %>%
  inner_join(L1 %>% mutate(Date = as.Date(Date))) %>%
  mutate(NewL1 = 0.714 * (maxL1/L1 - 1)^1.231)

max24h_L1
#Joining, by = "Date"
## A tibble: 10 x 4
#   Date       maxL1    L1    NewL1
#   <date>     <dbl> <dbl>    <dbl>
# 1 2019-04-08 0.666 0.654 0.00520
# 2 2019-04-08 0.666 0.656 0.00414
# 3 2019-04-08 0.666 0.653 0.00575
# 4 2019-04-08 0.666 0.652 0.00631
# 5 2019-04-08 0.666 0.657 0.00363
# 6 2019-04-08 0.666 0.649 0.00806
# 7 2019-04-08 0.666 0.665 0.000239
# 8 2019-04-08 0.666 0.647 0.00928
# 9 2019-04-08 0.666 0.66  0.00219
#10 2019-04-08 0.666 0.666 0


问:
How to use RSA or similar encryption in Python 3?
How do I go about using RSA or similar Public Key-Private Key encryption in Python 3, preferably with a built-in module? All the resources I've found so far are for Python 2.7 </p>

答:
Here is an implementation of RSA Encryption in Python 3 I have made, using the Crypto library (installed with the command pip install pycryptodome)

```<code>from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto.Random import new as Random
from base64 import b64encode
from base64 import b64decode

class RSA_Cipher:
  def generate_key(self,key_length):
    assert key_length in [1024,2048,4096]
    rng = Random().read
    self.key = RSA.generate(key_length,rng)

  def encrypt(self,data):
    plaintext = b64encode(data.encode())
    rsa_encryption_cipher = PKCS1_v1_5.new(self.key)
    ciphertext = rsa_encryption_cipher.encrypt(plaintext)
    return b64encode(ciphertext).decode()

  def decrypt(self,data):
    ciphertext = b64decode(data.encode())
    rsa_decryption_cipher = PKCS1_v1_5.new(self.key)
    plaintext = rsa_decryption_cipher.decrypt(ciphertext,16)
    return b64decode(plaintext).decode()
</code>```

The usage of the following class is like so:

```<code> - cipher = RSA_Cipher()
 - cipher.generate_key(1024) #key length can be 1024, 2048 or 4096
 - cipher.encrypt("hello world") #automatically uses generated key
 - cipher.decrypt("nt3vNNqzyAo2SINPgsb/eOLU2PD0DF0EstvnIHUmYGX4CVAvS0pDEboqGcuitYAzSV10Ii+fliwihu/L0ISrL6w/tRDQILHFM5PrN2pqzK+Lu6QHKUShFdQtikduo1KHXGlJNd25sVlDOhWAq/FK/67Yeoyz6fSP6PNXRjX7Q+Q=)
</code>```

Body:
Here is an implementation of RSA Encryption in Python 3 I have made, using the Crypto library (installed with the command pip install pycryptodome)

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto.Random import new as Random
from base64 import b64encode
from base64 import b64decode

class RSA_Cipher:
  def generate_key(self,key_length):
    assert key_length in [1024,2048,4096]
    rng = Random().read
    self.key = RSA.generate(key_length,rng)

  def encrypt(self,data):
    plaintext = b64encode(data.encode())
    rsa_encryption_cipher = PKCS1_v1_5.new(self.key)
    ciphertext = rsa_encryption_cipher.encrypt(plaintext)
    return b64encode(ciphertext).decode()

  def decrypt(self,data):
    ciphertext = b64decode(data.encode())
    rsa_decryption_cipher = PKCS1_v1_5.new(self.key)
    plaintext = rsa_decryption_cipher.decrypt(ciphertext,16)
    return b64decode(plaintext).decode()

The usage of the following class is like so:

 - cipher = RSA_Cipher()
 - cipher.generate_key(1024) #key length can be 1024, 2048 or 4096
 - cipher.encrypt("hello world") #automatically uses generated key
 - cipher.decrypt("nt3vNNqzyAo2SINPgsb/eOLU2PD0DF0EstvnIHUmYGX4CVAvS0pDEboqGcuitYAzSV10Ii+fliwihu/L0ISrL6w/tRDQILHFM5PrN2pqzK+Lu6QHKUShFdQtikduo1KHXGlJNd25sVlDOhWAq/FK/67Yeoyz6fSP6PNXRjX7Q+Q=)


问:
How to add Confirmation dialog? If press yes, the button will download, if no, the button will cancel
I have this web page that allows to export the file into excel file. It has a button that when click, it will automatically download the file. Now, I want a confirmation or notification button that prompts the user before downloading. When the "export" button is click, a prompt notification asking to export or not. If the "yes" button is click, then it will export the file, if not, then it cancels.

market.php

```<code><button onclick="exportToExcelRequest('tableExport')" class="btn btn-primary">Export Data To Excel File</button>
</code>```

exportToExcelRequest.js

```<code>function exportToExcelRequest(tableID, filename = ''){
    var downloadurl;
    var dataFileType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTMLData = tableSelect.outerHTML.replace(/ /g, '%20');

    filename = filename?filename+'.xls':'MarketOrderRequestReport.xls';
    downloadurl = document.createElement("a");
    document.body.appendChild(downloadurl);
     if(navigator.msSaveOrOpenBlob){
      var blob = new Blob(['\ufeff', tableHTMLData], {
      type: dataFileType
     });
       navigator.msSaveOrOpenBlob(blob, filename);
     }else{
      downloadurl.href = 'data:' + dataFileType + ', '+ tableHTMLData;
       downloadurl.download = filename;
       downloadurl.click();
      }
}
</code>```

答:
It can be done in different ways, here is the simplest one

```<code><button onclick="if(confirm('agree ?')){exportToExcelRequest('tableExport')}" class="btn btn-primary">Export Data To Excel File</button>
</code>```

if you have any question, please let me know

Another way

function check(data){

  if(confirm("Are you sure ?")){

    exportToExcelRequest(data);

  }
}

function exportToExcelRequest(data){
      alert(data);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="check('tableExport')" class="btn btn-primary">Export Data To Excel File</button></code>```

Body:
I have this web page that allows to export the file into excel file. It has a button that when click, it will automatically download the file. Now, I want a confirmation or notification button that prompts the user before downloading. When the "export" button is click, a prompt notification asking to export or not. If the "yes" button is click, then it will export the file, if not, then it cancels.

market.php

<button onclick="exportToExcelRequest('tableExport')" class="btn btn-primary">Export Data To Excel File</button>

exportToExcelRequest.js

function exportToExcelRequest(tableID, filename = ''){
    var downloadurl;
    var dataFileType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTMLData = tableSelect.outerHTML.replace(/ /g, '%20');

    filename = filename?filename+'.xls':'MarketOrderRequestReport.xls';
    downloadurl = document.createElement("a");
    document.body.appendChild(downloadurl);
     if(navigator.msSaveOrOpenBlob){
      var blob = new Blob(['\ufeff', tableHTMLData], {
      type: dataFileType
     });
       navigator.msSaveOrOpenBlob(blob, filename);
     }else{
      downloadurl.href = 'data:' + dataFileType + ', '+ tableHTMLData;
       downloadurl.download = filename;
       downloadurl.click();
      }
}

Body:
It can be done in different ways, here is the simplest one

<button onclick="if(confirm('agree ?')){exportToExcelRequest('tableExport')}" class="btn btn-primary">Export Data To Excel File</button>

if you have any question, please let me know

Another way

function check(data){

  if(confirm("Are you sure ?")){

    exportToExcelRequest(data);

  }
}

function exportToExcelRequest(data){
      alert(data);
    }

<button onclick="check('tableExport')" class="btn btn-primary">Export Data To Excel File</button>


问:
Strip NSString of special characters in setter method in implementation file in Objective-C
I have a property

```<code>@property (strong,nonatomic) NSString *myString;
</code>```

where I store an NSString and this property is called in many places in the implementation file as self.myString.

I have run into a problem where the string sometimes contains an angled apostrophe as opposed to the kind on the QWERTY keyboard and this special character is throwing off string comparisons.

With a managed object, you can use the setter method to do things to a property.  Is there a way that I can use a setter method to convert the angled apostrophe into a regular apostrophe in an implementation file.

Something like:

```<code>-(NSString*) myString {
    NSString * myString = [self stringByReplacingOccurrencesOfString:@"’" withString:@"'"];
}
</code>```

This is a mixed Objc-Swift project, so I guess I could also add an extension to NSString in Swift if that is a better way to do it.

Thanks for any suggestions.

答:
As setter:

```<code>- (void)setMyString:(NSString *)aString {

    _myString=[aString stringByReplacingOccurrencesOfString:@"’" withString:@"'"];
}
</code>```

However you could also leave it a regular property, storing it exactly as received, but providing a derived property that would sanitize the string. Example:

```<code>- (NSString *)myStringSanitized {

    return [self.myString stringByReplacingOccurrencesOfString:@"’" withString:@"'"];
}
</code>```

Optionally if your code uses Key-Value observation (for example with Cocoa Bindings), you could also add this to make sure a change notification for your sanitized string is fired whenever the underlying original changes:

```<code>+ (NSSet *)keyPathsForValuesAffectingMyStringSanitized {

    return [NSSet setWithObjects:@"myString",nil];
}
</code>```

Now you can use self.myStringSanitized anywhere you need the sanitized version of your string, but you still have the unmodified version available as self.myString.

Body:
I have a property

@property (strong,nonatomic) NSString *myString;

where I store an NSString and this property is called in many places in the implementation file as self.myString.

I have run into a problem where the string sometimes contains an angled apostrophe as opposed to the kind on the QWERTY keyboard and this special character is throwing off string comparisons.

With a managed object, you can use the setter method to do things to a property.  Is there a way that I can use a setter method to convert the angled apostrophe into a regular apostrophe in an implementation file.

Something like:

-(NSString*) myString {
    NSString * myString = [self stringByReplacingOccurrencesOfString:@"’" withString:@"'"];
}

This is a mixed Objc-Swift project, so I guess I could also add an extension to NSString in Swift if that is a better way to do it.

Thanks for any suggestions.

Body:
As setter:

- (void)setMyString:(NSString *)aString {

    _myString=[aString stringByReplacingOccurrencesOfString:@"’" withString:@"'"];
}

However you could also leave it a regular property, storing it exactly as received, but providing a derived property that would sanitize the string. Example:

- (NSString *)myStringSanitized {

    return [self.myString stringByReplacingOccurrencesOfString:@"’" withString:@"'"];
}

Optionally if your code uses Key-Value observation (for example with Cocoa Bindings), you could also add this to make sure a change notification for your sanitized string is fired whenever the underlying original changes:

+ (NSSet *)keyPathsForValuesAffectingMyStringSanitized {

    return [NSSet setWithObjects:@"myString",nil];
}

Now you can use self.myStringSanitized anywhere you need the sanitized version of your string, but you still have the unmodified version available as self.myString.


问:
How to use Azure DevOps Extension for Azure CLI with Azure DevOps Server?
The Azure CLI with the Azure DevOps extension has replaced the VSTS CLI. But I can't find any sample on how to connect to Team Foundation Server (TFS) or Azure DevOps Server using Azure CLI with Azure DevOps extension.

I tried to create a PAT on my Azure DevOps Server with all scope permission. Then I use the following command to login:

az devops login --organization https://vm-dev-cgudevops/DefaultCollection --verbose
```

<p>Here is what I've got:</p>

```C:\>az devops login --organization https://vm-dev-cgudevops/DefaultCollection --verbose
Token:
Creating connection with personal access token.
Failed to authenticate using the supplied token.
Suppress exception There are no active accounts.
Suppress exception Please run 'az login' to setup account.
command ran in 25.138 seconds.
```

The token can't be wrong. I don't know what's going on.

答:
There is an extension in Azure DevOps that let's you mange the Azure DevOps from Azure CLI.

As mentioned in the extension you have to :

Install the Azure CLI. You must have at least v2.0.49, which you can
verify with az --version command.

Add the Azure DevOps Extension az extension add --name azure-devops

Run the az login command.

You can also find a sample for it here.

Read this article if you need more information about how to get started with it.

Body:
The Azure CLI with the Azure DevOps extension has replaced the VSTS CLI. But I can't find any sample on how to connect to Team Foundation Server (TFS) or Azure DevOps Server using Azure CLI with Azure DevOps extension.

I tried to create a PAT on my Azure DevOps Server with all scope permission. Then I use the following command to login:

az devops login --organization https://vm-dev-cgudevops/DefaultCollection --verbose

Here is what I've got:

C:\>az devops login --organization https://vm-dev-cgudevops/DefaultCollection --verbose
Token:
Creating connection with personal access token.
Failed to authenticate using the supplied token.
Suppress exception There are no active accounts.
Suppress exception Please run 'az login' to setup account.
command ran in 25.138 seconds.

The token can't be wrong. I don't know what's going on.


问:
What to do when findViewById cannot find a GUI resource while debugging in Eclipse
Spent about an hour on this so I thought I'd save somebody else the trouble. Using Eclipse 3.6.2.

My call to findViewById a GUI widget keep returning null. Check the code and xml over and over and over, no problems. Finally exited and restarted Eclipse and suddenly findViewById worked.

答: I find I have been needing to do Project > Clean when adding a new resource. If I simply tell it to build, the R.java will regenerate, but the resource will not be optimized and packaged in the bundle. Chalk it up to an Android bug and remember to clean.</p>


问:
Why in my JS popup my html form doesn't work?
I make a popup which says "are you sure you want to delete the category?" If they say yes, exec a form but this form doesn't work?

The html code:

var modal = document.getElementById("popup");
var btns = Array.prototype.slice.call(document.querySelectorAll(".remove_openpopup"));
var span = document.getElementsByClassName("close_button")[0];
btns.forEach(function(btn) {
  btn.onclick = function() {
    modal.style.display = "block";
  }
});
span.onclick = function() {
  modal.style.display = "none";
}
span2.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  remove
  remove2
  remove3

  <div id="popup" class="popup">
    <div class="popup_content">
      <span class="close">×</span>
      <p>Are you sure you wan't delete this categorie ?</p>
      <button class="button_popup close_button">No</button>
      <button class="button_popup close_button" onclick='document.getElementByClassName("remove").submit()'>Yes</button>
    </div>
  </div>
  <form class="remove" method="post"><input type="hidden" name="remove" /></form>
</body></code>```

The test script:

```<code>if (isset($_POST['remove'])) {
  echo "a";
}
</code>```

When I click yes nothing happen.
Someone have an idea?

答:
You are using getElementByClassName but it doesn't exist. The closest thing is getElementsByClassName, which returns an array of elements with the requested class name, but in this case I think you should use getElementById and set the id property to your form:</p>

```<code><body>
    <a href="#" class="remove_openpopup">remove</a>
    <a href="#" class="remove_openpopup">remove2</a>
    <a href="#" class="remove_openpopup">remove3</a>

    <div id="popup" class="popup">
      <div class="popup_content">
        <span class="close">×</span>
        <p>Are you sure you wan't delete this categorie ?</p>
        <button class="button_popup close_button">No</button>
        <button class="button_popup close_button" onclick='document.getElementById("remove").submit()'>Yes</button>
      </div>
    </div>
    <form id="remove" method="post"><input type="hidden" name="remove" /></form>
</body>
</code>```

Body:
I make a popup which says "are you sure you want to delete the category?" If they say yes, exec a form but this form doesn't work?

The html code:

var modal = document.getElementById("popup");
var btns = Array.prototype.slice.call(document.querySelectorAll(".remove_openpopup"));
var span = document.getElementsByClassName("close_button")[0];
btns.forEach(function(btn) {
  btn.onclick = function() {
    modal.style.display = "block";
  }
});
span.onclick = function() {
  modal.style.display = "none";
}
span2.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

  remove
  remove2
  remove3

      ×

Are you sure you wan't delete this categorie ?

      <button class="button_popup close_button">No</button>
      <button class="button_popup close_button" onclick='document.getElementByClassName("remove").submit()'>Yes</button>

  <form class="remove" method="post"><input type="hidden" name="remove" /></form>

The test script:

if (isset($_POST['remove'])) {
  echo "a";
}

When I click yes nothing happen.
Someone have an idea?

Body:
You are using getElementByClassName but it doesn't exist. The closest thing is getElementsByClassName, which returns an array of elements with the requested class name, but in this case I think you should use getElementById and set the id property to your form:

<body>
    <a href="#" class="remove_openpopup">remove</a>
    <a href="#" class="remove_openpopup">remove2</a>
    <a href="#" class="remove_openpopup">remove3</a>

    <div id="popup" class="popup">
      <div class="popup_content">
        <span class="close">&times;</span>
        <p>Are you sure you wan't delete this categorie ?</p>
        <button class="button_popup close_button">No</button>
        <button class="button_popup close_button" onclick='document.getElementById("remove").submit()'>Yes</button>
      </div>
    </div>
    <form id="remove" method="post"><input type="hidden" name="remove" /></form>
</body>


问:
Random number generator not random in a batch file
Trying to generate a random number and use it for variable value in Windows batch script file. Maybe I am missing something very basic, but something is not working here for me.

Created a batch file named random_test.bat with the following content.

```<code>SET rnumber=%random%
echo %random%
pause
</code>```

Running the file consecutively three times produces the following set of outputs:

One

```<code>C:\Users\user\Desktop>SET rnumber=28955

C:\Users\user\Desktop>echo 20160
20160

C:\Users\user\Desktop>pause
Press any key to continue . . .
</code>```

Two

```<code>C:\Users\user\Desktop>SET rnumber=29072

C:\Users\user\Desktop>echo 13887
13887

C:\Users\user\Desktop>pause
Press any key to continue . . .
</code>```

Three

```<code>C:\Users\user\Desktop>SET rnumber=29183

C:\Users\user\Desktop>echo 18885
18885

C:\Users\user\Desktop>pause
Press any key to continue . . .
</code>```

As you can see the command echo %random% keeps producing relatively random numbers between 0 and 32,767 as expected.

At the same time using %random% to set a value for variable rnumber does not. It produces a not-so random number (possibly too between 0 and 32,767) but it is not random. If I were to guess right now it seems to be slowly growing in the 0 to 32,767 direction.

To clarify the script keeps producing a random number with line 2 on each execution (20160, 13887, 18885...), but line 1 seems to produce a number that keeps increasing with each execution of the batch file (28955, 29072, 29183, and so on in my multiple tests).

I already tried it on two different computers, Windows 7 x64 and Windows 2012 R2 respectively, running this 3 line script multiple times in row.

Next thing to try will be on a computer from a completely different network, I'm wondering if this has anything to do with domain policies, network, software..

What is going on here?

UPDATE:

When running the commands in sequence from the same CMD window it works as expected, but it does not when executing the same batch file multiple times.

The line in the script echo %random% works as expected.

The line SET rnumber=%random% does not.

(When executing the same script multiple times)

答:
Random numbers from cmd.exe is not for the faint of heart. Neither %RANDOM% nor !RANDOM! will get you there.

This page, https://ss64.com/nt/syntax-random.html, makes for interesting reading.

If you are on a supported Windows platform, PowerShell will work.

```<code>@ECHO OFF
FOR /F %%n IN ('powershell -NoLogo -NoProfile -Command Get-Random') DO (
    SET "RNUM=%%~n"
)
ECHO RNUM is %RNUM%
</code>```

Body:
Trying to generate a random number and use it for variable value in Windows batch script file. Maybe I am missing something very basic, but something is not working here for me.

Created a batch file named random_test.bat with the following content.

SET rnumber=%random%
echo %random%
pause

Running the file consecutively three times produces the following set of outputs:

One

C:\Users\user\Desktop>SET rnumber=28955

C:\Users\user\Desktop>echo 20160
20160

C:\Users\user\Desktop>pause
Press any key to continue . . .

Two

C:\Users\user\Desktop>SET rnumber=29072

C:\Users\user\Desktop>echo 13887
13887

C:\Users\user\Desktop>pause
Press any key to continue . . .

Three

C:\Users\user\Desktop>SET rnumber=29183

C:\Users\user\Desktop>echo 18885
18885

C:\Users\user\Desktop>pause
Press any key to continue . . .

As you can see the command echo %random% keeps producing relatively random numbers between 0 and 32,767 as expected.

At the same time using %random% to set a value for variable rnumber does not. It produces a not-so random number (possibly too between 0 and 32,767) but it is not random. If I were to guess right now it seems to be slowly growing in the 0 to 32,767 direction.

To clarify the script keeps producing a random number with line 2 on each execution (20160, 13887, 18885...), but line 1 seems to produce a number that keeps increasing with each execution of the batch file (28955, 29072, 29183, and so on in my multiple tests).

I already tried it on two different computers, Windows 7 x64 and Windows 2012 R2 respectively, running this 3 line script multiple times in row.

Next thing to try will be on a computer from a completely different network, I'm wondering if this has anything to do with domain policies, network, software..

What is going on here?

UPDATE:

When running the commands in sequence from the same CMD window it works as expected, but it does not when executing the same batch file multiple times.

The line in the script echo %random% works as expected.

The line SET rnumber=%random% does not.

(When executing the same script multiple times)

Body:
Random numbers from cmd.exe is not for the faint of heart. Neither %RANDOM% nor !RANDOM! will get you there.

This page, https://ss64.com/nt/syntax-random.html, makes for interesting reading.

If you are on a supported Windows platform, PowerShell will work.

@ECHO OFF
FOR /F %%n IN ('powershell -NoLogo -NoProfile -Command Get-Random') DO (
    SET "RNUM=%%~n"
)
ECHO RNUM is %RNUM%


问:
Graphics.set_font Ocaml
i m using the Graphics.set_font function to change the font of a text like

```<code>Graphics.set_font "-*-fixed-medium-r-semicondensed--50-*-*-*-*-*-iso8859-1";
</code>```

my question is : What is the default font used by Ocaml ?

Thanks

答:
I'm not intimately familiar with the Graphics library, much less its source code. But a cursory search reveals the following:

On UNIX, the DEFAULT_FONT is set to "fixed", which presumably means it will use whatever is configured as your system's fixed-width font.

On Windows, the gr_reset function loads the "Courier" font.

Title: Graphics.set_font Ocaml

Body:
i m using the Graphics.set_font function to change the font of a text like

Graphics.set_font "-*-fixed-medium-r-semicondensed--50-*-*-*-*-*-iso8859-1";

my question is : What is the default font used by Ocaml ?

Thanks


问:
STM32F746ZG - How to update some part of 256 KB sector in flash
I'm using STM32F103 and moving my code to STM32F746. The F103 was able to update Flash on a per-page basis in 1KB and 2KB.
I have STM32F746ZG Nucleo-board and my code size is big, flash took up to 0x08038000. I want to save other small applications on 0x08040000(sector_5). This applications consist of several 2KB sizes. I need to store multiple applications in Sector_5 and M7 cannot use Flash in 1KB or 2KB increments.

The followings are sector sizes of STM32F746ZG.

```<code>#define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08008000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08010000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_3 ((uint32_t)0x08018000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08020000) // 128 Kbytes
#define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08040000) // 256 Kbytes
#define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08080000) // 256 Kbytes
#define ADDR_FLASH_SECTOR_7 ((uint32_t)0x080C0000) // 256 Kbytes
</code>```

STM32F746 consists of flash in a sector size of 256 KB each from Sector_5 to Sector7. If I want to use the Sector_5, I have to erase the whole of one sector. What if I want to update only about 2KB in the front of the Sector_5 and keep the area after 2KB intact? It means I only update the content from 0x08040000 to 0x08042000. I have to keep from 0x08042001 to 0x0807FFFF.

I can't even copy 256 KB of Flash to RAM. Because F746 only have 240KB of internal RAM and my many tasks already used RAM, so there is not enough RAM to copy one sector. In this case, please let me know how to update part of 256KB in flash.

答:
That depends. On many STM32 microcontrollers you can zero the bits of the FLASH without erasing it. But you cant set the bits of course - it can only be done by the erase operation. Some chips do not allow it as the flash sector has its own CRC.

If your chip allows the writing to the 0xff filled FLASH you can store the data in another place of this sector. If not You need to copy data to another sector, arase the sector and the write the data back.

Body:
I'm using STM32F103 and moving my code to STM32F746. The F103 was able to update Flash on a per-page basis in 1KB and 2KB.
I have STM32F746ZG Nucleo-board and my code size is big, flash took up to 0x08038000. I want to save other small applications on 0x08040000(sector_5). This applications consist of several 2KB sizes. I need to store multiple applications in Sector_5 and M7 cannot use Flash in 1KB or 2KB increments.

The followings are sector sizes of STM32F746ZG.

#define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08008000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08010000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_3 ((uint32_t)0x08018000) // 32 Kbytes
#define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08020000) // 128 Kbytes
#define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08040000) // 256 Kbytes
#define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08080000) // 256 Kbytes
#define ADDR_FLASH_SECTOR_7 ((uint32_t)0x080C0000) // 256 Kbytes

STM32F746 consists of flash in a sector size of 256 KB each from Sector_5 to Sector7. If I want to use the Sector_5, I have to erase the whole of one sector. What if I want to update only about 2KB in the front of the Sector_5 and keep the area after 2KB intact? It means I only update the content from 0x08040000 to 0x08042000. I have to keep from 0x08042001 to 0x0807FFFF.

I can't even copy 256 KB of Flash to RAM. Because F746 only have 240KB of internal RAM and my many tasks already used RAM, so there is not enough RAM to copy one sector. In this case, please let me know how to update part of 256KB in flash.


问:
dyld: Library not loaded: @rpath/libswiftAVFoundation.dylib Reason: image not found
I'm getting this error upon launch of my app.  I am building under Xcode 9.0 (9A235) on MacOS High Sierra 10.13.  I also tried building under Xcode 8.3.3 with the same result.  The project is generally Objective C, but the framework YouAppi.framework is Swift:

```<code>dyld: Library not loaded: @rpath/libswiftAVFoundation.dylib
  Referenced from: /private/var/containers/Bundle/Application/7D3E2815-4CA3-4258-AEF6-C0626055A8F2/dingbats.app/Frameworks/YouAppi.framework/YouAppi
  Reason: image not found
</code>```

At first glance, this appears to be a duplicate of this question, but the error is different in that one.  In that other question, the Reason is no suitable image found, where mine is image not found.

I've tried the following to resolve:

Remove and re-add the framework

Clean and Option+Clean the project

Delete ~/Library/Developer/Xcode/DerivedData folder

Build Settings -> Always Embed Swift Standard Libraries = Yes

Build Settings -> Strip Swift Symbols = No

Build Settings -> Linking -> Runpath Search Paths --

added @loader_path

added @rpath

added @executable_path/Frameworks

Checked developer and distribution certificates that Trust was set to Use System Defaults

Checked that I have latest WWDR and G2 certificates installed

Checked validity of above-mentioned certificates

Moved YouAppi.framework into Frameworks/ folder.  (It was originally in a "Third-Party Frameworks" folder.)

Tried copying libswiftAVFoundation.dylib into my project's Frameworks folder

I haven't moved to a new computer recently.

I have the same result on my iPhone 7+ running iOS 11.0.23 (15A432) as well as an iPad Mini 1 running iOS 9.3.5 (13G36).

Also tried this:

```<code>rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"
rm -rf ~/Library/Developer/Xcode/DerivedData
rm -rf ~/Library/Caches/com.apple.dt.Xcode
</code>```

Ideas?

答:
Simple step to follow

Project -> Build Phases -> Embed Frameworks -> +.

It will works for all.. Perfect solution for everyone.

Add library in Link Binary with Libraries &

Add new Copy Files Phrase, Select framework in destination section and import library there.

And Run your code.. Magic.. Enjoy

NOTE:-Please make sure "Copy only when installing" in Copy files is unchecked

Body:
I'm getting this error upon launch of my app.  I am building under Xcode 9.0 (9A235) on MacOS High Sierra 10.13.  I also tried building under Xcode 8.3.3 with the same result.  The project is generally Objective C, but the framework YouAppi.framework is Swift:

dyld: Library not loaded: @rpath/libswiftAVFoundation.dylib
  Referenced from: /private/var/containers/Bundle/Application/7D3E2815-4CA3-4258-AEF6-C0626055A8F2/dingbats.app/Frameworks/YouAppi.framework/YouAppi
  Reason: image not found

At first glance, this appears to be a duplicate of this question, but the error is different in that one.  In that other question, the Reason is no suitable image found, where mine is image not found.

I've tried the following to resolve:

Remove and re-add the framework

Clean and Option+Clean the project

Delete ~/Library/Developer/Xcode/DerivedData folder

Build Settings -> Always Embed Swift Standard Libraries = Yes

Build Settings -> Strip Swift Symbols = No

Build Settings -> Linking -> Runpath Search Paths --

added @loader_path

added @rpath

added @executable_path/Frameworks

Checked developer and distribution certificates that Trust was set to Use System Defaults

Checked that I have latest WWDR and G2 certificates installed

Checked validity of above-mentioned certificates

Moved YouAppi.framework into Frameworks/ folder.  (It was originally in a "Third-Party Frameworks" folder.)

Tried copying libswiftAVFoundation.dylib into my project's Frameworks folder

I haven't moved to a new computer recently.

I have the same result on my iPhone 7+ running iOS 11.0.23 (15A432) as well as an iPad Mini 1 running iOS 9.3.5 (13G36).

Also tried this:

rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"
rm -rf ~/Library/Developer/Xcode/DerivedData
rm -rf ~/Library/Caches/com.apple.dt.Xcode

Ideas?


问:
How do I automatically fix an invalid JSON string?
From the 2gis API I got the following JSON string.

```<code>{
    "api_version": "1.3",
    "response_code": "200",
    "id": "3237490513229753",
    "lon": "38.969916127827",
    "lat": "45.069889625267",
    "page_url": null,
    "name": "ATB",
    "firm_group": {
        "id": "3237499103085728",
        "count": "1"
    },
    "city_name": "Krasnodar",
    "city_id": "3237585002430511",
    "address": "Turgeneva,   172/1",
    "create_time": "2008-07-22 10:02:04 07",
    "modification_time": "2013-08-09 20:04:36 07",
    "see_also": [
        {
            "id": "3237491513434577",
            "lon": 38.973110606808,
            "lat": 45.029031222211,
            "name": "Advance",
            "hash": "5698hn745A8IJ1H86177uvgn94521J3464he26763737242Cf6e654G62J0I7878e",
            "ads": {
                "sponsored_article": {
                    "title": "Center "ADVANCE"",
                    "text": "Business.English."
                },
                "warning": null
            }
        }
    ]
}
</code>```

But Python doesn't recognize it:

```<code>json.loads(firm_str)
</code>```

Expecting , delimiter: line 1 column 3646 (char 3645)

It looks like a problem with quotes in:
    "title": "Center "ADVANCE""

How can I fix it automatically in Python?

答:
I make a jsonfixer to solve a problem like this.

It's Python Package (2.7) (a half-done command line tool)

just see https://github.com/half-pie/half-json

```<code>from half_json.core import JSONFixer
f = JSONFixer(max_try=100)
new_s = s.replace('\n', '')
result = f.fix(new_s)
d = json.loads(result.line)
# {u'name': u'ATB', u'modification_time': u'2013-08-09 20:04:36 07', u'city_id': u'3237585002430511', u'see_also': [{u'hash': u'5698hn745A8IJ1H86177uvgn94521J3464he26763737242Cf6e654G62J0I7878e', u'ads': {u'warning': None, u'sponsored_article': {u'ADVANCE': u',                    ', u'text': u'Business.English.', u'title': u'Center '}}, u'lon': 38.973110606808, u'lat': 45.029031222211, u'id': u'3237491513434577', u'name': u'Advance'}], u'response_code': u'200', u'lon': u'38.969916127827', u'firm_group': {u'count': u'1', u'id': u'3237499103085728'}, u'create_time': u'2008-07-22 10:02:04 07', u'city_name': u'Krasnodar', u'address': u'Turgeneva,   172/1', u'lat': u'45.069889625267', u'id': u'3237490513229753', u'api_version': u'1.3', u'page_url': None}
</code>```

and test case in https://github.com/half-pie/half-json/blob/master/tests/test_cases.py#L76-L80

```<code>    line = '{"title": "Center "ADVANCE"", "text": "Business.English."}'
    ok, newline, _ = JSONFixer().fix(line)
    self.assertTrue(ok)
    self.assertEqual('{"title": "Center ","ADVANCE":", ","text": "Business.English."}', newline)
</code>```

Body:
From the 2gis API I got the following JSON string.

{
    "api_version": "1.3",
    "response_code": "200",
    "id": "3237490513229753",
    "lon": "38.969916127827",
    "lat": "45.069889625267",
    "page_url": null,
    "name": "ATB",
    "firm_group": {
        "id": "3237499103085728",
        "count": "1"
    },
    "city_name": "Krasnodar",
    "city_id": "3237585002430511",
    "address": "Turgeneva,   172/1",
    "create_time": "2008-07-22 10:02:04 07",
    "modification_time": "2013-08-09 20:04:36 07",
    "see_also": [
        {
            "id": "3237491513434577",
            "lon": 38.973110606808,
            "lat": 45.029031222211,
            "name": "Advance",
            "hash": "5698hn745A8IJ1H86177uvgn94521J3464he26763737242Cf6e654G62J0I7878e",
            "ads": {
                "sponsored_article": {
                    "title": "Center "ADVANCE"",
                    "text": "Business.English."
                },
                "warning": null
            }
        }
    ]
}

But Python doesn't recognize it:

json.loads(firm_str)

Expecting , delimiter: line 1 column 3646 (char 3645)

It looks like a problem with quotes in:
    "title": "Center "ADVANCE""

How can I fix it automatically in Python?

Body:
I make a jsonfixer to solve a problem like this.

It's Python Package (2.7) (a half-done command line tool)

just see https://github.com/half-pie/half-json

from half_json.core import JSONFixer
f = JSONFixer(max_try=100)
new_s = s.replace('\n', '')
result = f.fix(new_s)
d = json.loads(result.line)
# {u'name': u'ATB', u'modification_time': u'2013-08-09 20:04:36 07', u'city_id': u'3237585002430511', u'see_also': [{u'hash': u'5698hn745A8IJ1H86177uvgn94521J3464he26763737242Cf6e654G62J0I7878e', u'ads': {u'warning': None, u'sponsored_article': {u'ADVANCE': u',                    ', u'text': u'Business.English.', u'title': u'Center '}}, u'lon': 38.973110606808, u'lat': 45.029031222211, u'id': u'3237491513434577', u'name': u'Advance'}], u'response_code': u'200', u'lon': u'38.969916127827', u'firm_group': {u'count': u'1', u'id': u'3237499103085728'}, u'create_time': u'2008-07-22 10:02:04 07', u'city_name': u'Krasnodar', u'address': u'Turgeneva,   172/1', u'lat': u'45.069889625267', u'id': u'3237490513229753', u'api_version': u'1.3', u'page_url': None}

and test case in https://github.com/half-pie/half-json/blob/master/tests/test_cases.py#L76-L80

    line = '{"title": "Center "ADVANCE"", "text": "Business.English."}'
    ok, newline, _ = JSONFixer().fix(line)
    self.assertTrue(ok)
    self.assertEqual('{"title": "Center ","ADVANCE":", ","text": "Business.English."}', newline)