问:
MYSQL storage increasing unexpectedly (RDS)
I am total newbie to database game.
& I am using mysql 8.0 RDS 20GB free tier.

I don't have much data on it.(just 300 Mb)
(wordpress running on ec2 is linked with this rds)

But I always get a mail that you have exceeded 85% of storage limit.(approx 17Gb)

Also Under monitoring tab in rds panel it shows:- Free Storage Space (MB) = 19.330Gb (Constantly without any drop)

I have turned off : general log, slow logs, binlog,

i have done these parameter changes:

```<code>binlog_expire_logs_seconds = 86400
general_log = 0
innodb_autoextend_increment = 1
innodb_buffer_pool_size = 5000000000
log_bin_trust_function_creators = 0
log_output = NONE
max_binlog_cache_size = 5368709120
max_connections = 1000
slow_query_log = 0
innodb_file_per_table = 1
</code>```

SELECT name, count FROM information_schema.innodb_metrics ORDER BY count;

```<code>Highest counts seen on:
buffer_data_written = 6936939008
buffer_pool_size = 402653184
os_log_bytes_written = 313484800
buffer_pool_bytes_data = 204668928
</code>```

Can someone please help me whats consuming these storage. Is this something to do with INNODB?

答:
Ouch!  innodb_buffer_pool_size = 5000000000 inside 1GB of RAM!  This leads to swapping, which uses disk space and slows down MySQL terribly.

Don't set that about, say, 250M.  Even that may be too high.  Do you have other things running in the db.t2.micro?

max_connections = 1000 -- also too high.  Set it to 20

If you want to change anything else, get some advice first.  The general advice is:  1gb of RAM is very limited; raising tunables can lead to bad results.

Body:
I am total newbie to database game.
& I am using mysql 8.0 RDS 20GB free tier.

I don't have much data on it.(just 300 Mb)
(wordpress running on ec2 is linked with this rds)

But I always get a mail that you have exceeded 85% of storage limit.(approx 17Gb)

Also Under monitoring tab in rds panel it shows:- Free Storage Space (MB) = 19.330Gb (Constantly without any drop)

I have turned off : general log, slow logs, binlog,

i have done these parameter changes:

binlog_expire_logs_seconds = 86400
general_log = 0
innodb_autoextend_increment = 1
innodb_buffer_pool_size = 5000000000
log_bin_trust_function_creators = 0
log_output = NONE
max_binlog_cache_size = 5368709120
max_connections = 1000
slow_query_log = 0
innodb_file_per_table = 1

SELECT name, count FROM information_schema.innodb_metrics ORDER BY count;

Highest counts seen on:
buffer_data_written = 6936939008
buffer_pool_size = 402653184
os_log_bytes_written = 313484800
buffer_pool_bytes_data = 204668928

Can someone please help me whats consuming these storage. Is this something to do with INNODB?


来源: stackexchange

问:
Even or odd. If the number is equal to 0, the program must stop
I need to write for each number the sequence output even if the number is even, otherwise, odd. If the number is equal to 0, the program must stop reading and processing numbers.

```<code>Input
1
2
3
0
Output
odd
even
odd
</code>```

My code:

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        int num;
        for (; ; ) {
            Scanner reader = new Scanner(System.in);
            num = reader.nextInt();
            if (num % 2 == 0) {
                System.out.println("even");
            }
            else if(num == 0){
                break;
            }
            else{
                System.out.println("odd");
            }
        }
    }
}
</code>```

答:
The issue with your posted code is addressed in the comment (checking num % 2 == 0 first), but in this case we can improve upon your solution. First, it's "idiomatic" in Java1 to use a while loop with a test after assignment. Second, it's possible to use a ?: conditional operator (a ternary) and remove the remaining if / else. Like,

```<code>int num;
Scanner reader = new Scanner(System.in);
while ((num = reader.nextInt()) != 0) {
    System.out.println(num % 2 == 0 ? "even" : "odd");
}
</code>```

1I don't know who defines idioms, but I didn't invent it. And I've seen this construct in JDK source.

ContentLicense: CC BY-SA 4.0

Body:
I need to write for each number the sequence output even if the number is even, otherwise, odd. If the number is equal to 0, the program must stop reading and processing numbers.

Input
1
2
3
0
Output
odd
even
odd

My code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        int num;
        for (; ; ) {
            Scanner reader = new Scanner(System.in);
            num = reader.nextInt();
            if (num % 2 == 0) {
                System.out.println("even");
            }
            else if(num == 0){
                break;
            }
            else{
                System.out.println("odd");
            }
        }
    }
}

Body:
The issue with your posted code is addressed in the comment (checking num % 2 == 0 first), but in this case we can improve upon your solution. First, it's "idiomatic" in Java1 to use a while loop with a test after assignment. Second, it's possible to use a ?: conditional operator (a ternary) and remove the remaining if / else. Like,

int num;
Scanner reader = new Scanner(System.in);
while ((num = reader.nextInt()) != 0) {
    System.out.println(num % 2 == 0 ? "even" : "odd");
}

1I don't know who defines idioms, but I didn't invent it. And I've seen this construct in JDK source.


问:
ASP.Net Core Serilog How to read from log file during runtime
I'm working on a ASP.NET Core 3.1 application. I want to log events to file and be able to read them during application runtime. To do that I'm trying to use Serilog.Extensions.Logging.File NuGet package and then specifying log file path as following:

Startup.cs

```<code> public void Configure(IApplicationBuilder app, ILoggerFactory logFactory)
 {
     logFactory.AddFile("Log");
 }
</code>```

Any attempt to read or write to file like this way

```<code>string ReadLog(string logPath)
{
    return System.IO.File.ReadAllText(logPath);
}
</code>```

ends in System.IO.IOException: 'The process cannot access the file {log-path} because it is being used by another process.' exception.

EDIT: I have installed Serilog.AspNetCore and made changes shown below while also removing logFactory from Configure function. But exception continues to occur.

Program.cs

```<code>public static int Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
        .Enrich.FromLogContext()
        .WriteTo.Console()
        .WriteTo.File(
            "Logs/log-.txt",
            shared: true,
            flushToDiskInterval: TimeSpan.FromSeconds(5),
            rollingInterval: RollingInterval.Day)
        .CreateLogger();

    try
    {
        Log.Information("Starting web host");
        CreateHostBuilder(args).Build().Run();
        return 0;
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "Host terminated unexpectedly");
        return 1;
    }
    finally
    {
        Log.CloseAndFlush();
    }
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        }).UseSerilog();
</code>```

EDIT 2:
As requested by julealgon I'm sharing my exact read logic. I'm trying to read using a controller, which I declared following way:

```<code>[Controller]
[Route("[controller]")]
public class LogController : Controller
{
    [Route("Read")]
    public IActionResult ReadLog(string logPath)
    {
        if (System.IO.File.Exists(logPath))
        {
            string logContent = System.IO.File.ReadAllText(logPath);//exception appears here.
            return Content(logContent);
        }
        else return NotFound();
    }
}
</code>```

Then using example query below to read log recorded by Friday, March 13, 2020.

```<code>https://localhost:44323/Log/Read?logPath=Logs\log-20200313.txt
</code>```

答:
When reading the file, I think use something like this will work:

using (var stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(stream))
{
    return reader.ReadToEnd();
}
```

The trick appears to be the specification of FileShare.ReadWrite as this is the policy used to write to when the sink opens the log file to write to. There's a similar bug reported over in the serilog-sinks-file repo.

Body:
I'm working on a ASP.NET Core 3.1 application. I want to log events to file and be able to read them during application runtime. To do that I'm trying to use Serilog.Extensions.Logging.File NuGet package and then specifying log file path as following:

Startup.cs

 public void Configure(IApplicationBuilder app, ILoggerFactory logFactory)
 {
     logFactory.AddFile("Log");
 }

Any attempt to read or write to file like this way

string ReadLog(string logPath)
{
    return System.IO.File.ReadAllText(logPath);
}

ends in System.IO.IOException: 'The process cannot access the file {log-path} because it is being used by another process.' exception.

EDIT: I have installed Serilog.AspNetCore and made changes shown below while also removing logFactory from Configure function. But exception continues to occur.

Program.cs

public static int Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
        .Enrich.FromLogContext()
        .WriteTo.Console()
        .WriteTo.File(
            "Logs/log-.txt",
            shared: true,
            flushToDiskInterval: TimeSpan.FromSeconds(5),
            rollingInterval: RollingInterval.Day)
        .CreateLogger();

    try
    {
        Log.Information("Starting web host");
        CreateHostBuilder(args).Build().Run();
        return 0;
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "Host terminated unexpectedly");
        return 1;
    }
    finally
    {
        Log.CloseAndFlush();
    }
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        }).UseSerilog();

EDIT 2:
As requested by julealgon I'm sharing my exact read logic. I'm trying to read using a controller, which I declared following way:

[Controller]
[Route("[controller]")]
public class LogController : Controller
{
    [Route("Read")]
    public IActionResult ReadLog(string logPath)
    {
        if (System.IO.File.Exists(logPath))
        {
            string logContent = System.IO.File.ReadAllText(logPath);//exception appears here.
            return Content(logContent);
        }
        else return NotFound();
    }
}

Then using example query below to read log recorded by Friday, March 13, 2020.

https://localhost:44323/Log/Read?logPath=Logs\log-20200313.txt

Body:
When reading the file, I think use something like this will work:

using (var stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(stream))
{
    return reader.ReadToEnd();
}

The trick appears to be the specification of FileShare.ReadWrite as this is the policy used to write to when the sink opens the log file to write to. There's a similar bug reported over in the serilog-sinks-file repo.


问:
NoReverseMatch at
I've got this issue trying to redirect after submitting a form:

NoReverseMatch at /app_blog/blog/1/blog_update/

Reverse for 'blog_detail' with no arguments not found. 1 pattern(s) tried: ['app_blog/blog/(?P[0-9]+)/blog_detail/$']

views.py:

```<code>from django.shortcuts import render, redirect
# from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.contrib import messages

from app_users.decorators import unauthenticated_user, allowed_users

from .models import BlogPost
from .forms import BlogUpdateForm

@login_required(login_url='app_users:login')
@allowed_users(allowed_roles=['admin', 'staff', 'users'])
def blog(request):
    posts = BlogPost.objects.all()
    context = {'title': 'Blog', 'posts': posts}
    return render(request, 'app_blog/blog.html', context)

def blog_detail(request, pk):
    user_post = BlogPost.objects.get(id=pk)
    context = {'title': 'Blog', 'user_post': user_post}
    return render(request, 'app_blog/blog_detail.html', context)

def blog_user_detail(request, pk):
    user_detail = BlogPost.objects.get(id=pk)
    user_type = user_detail.author.groups.all()[0].name.capitalize()
    context = {'title': 'Blog', 'user_detail': user_detail, 'user_type': user_type}
    return render(request, 'app_blog/blog_user_detail.html', context)

def blog_update(request, pk):
    if request.method == 'POST':
        blog_update = BlogUpdateForm(request.POST, instance=BlogPost.objects.get(id=pk))
        if blog_update.is_valid():
            blog_update.save()
            messages.success(request, 'Your blog-post has been updated!')
            return redirect('app_blog:blog_detail')
    else:
        blog_update = BlogUpdateForm(instance=BlogPost.objects.get(id=pk))
    context = {'title': 'Blog', 'blog_update': blog_update}
    return render(request, 'app_blog/blog_update.html', context)
</code>```

urls.py:

```<code>from django.urls import path
from .views import *

app_name = 'app_blog'

urlpatterns = [
    path('blog/', blog, name='blog'),
    path('blog/<int:pk>/blog_detail/', blog_detail, name='blog_detail'),
    path('blog/<int:pk>/user_details/', blog_user_detail, name='blog_user_detail'),
    path('blog/<int:pk>/blog_update/', blog_update, name='blog_update'),
]
</code>```

models.py:

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

class BlogPost(models.Model):
    title = models.CharField(max_length=100, null=True)
    content = models.TextField(null=True)
    date_posted = models.DateTimeField(default=timezone.now, null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title
</code>```

blog_detail.html:

{% extends 'app_t35/main.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block content %}

                    {{ user_post.author }}
                    {{ user_post.date_posted|date:"d F, Y" }}
                    {% if user_post.author == request.user %}

                            Update
                            Delete

                    {% endif %}

{{ user_post.title }}

{{ user_post.content|safe }}

{% endblock %}```
</div>
</div>
</p>
<p><em><strong>blog_update.html:</strong></em></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{% extends 'app_t35/main.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block content %}

<br>
<div class="card card-body container">
    <div class="card-deck">
        <img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
        <h5 style="text-align: left;">{{ user.username }}:</h5>
        <div class="card card-body">
            <form action="" method="POST">
                {% csrf_token %}
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">If you wish to update your blog-post:</legend>
                    {{ blog_update|crispy }}
                </fieldset>
                <div class="form-group">
                    <button class="btn btn-outline-info  btn-sm btn-block" style="width: 150px; align-self: center;" type="submit">Update Details</button>
                </div>
            </form>
        </div>
    </div>
</div>
<br>

{% endblock %}</code>```

答: use reverse function from django shortcuts

Title: NoReverseMatch at

Body:
I've got this issue trying to redirect after submitting a form:

NoReverseMatch at /app_blog/blog/1/blog_update/

Reverse for 'blog_detail' with no arguments not found. 1 pattern(s) tried: ['app_blog/blog/(?P[0-9]+)/blog_detail/$']

views.py:

from django.shortcuts import render, redirect
# from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.contrib import messages

from app_users.decorators import unauthenticated_user, allowed_users

from .models import BlogPost
from .forms import BlogUpdateForm

@login_required(login_url='app_users:login')
@allowed_users(allowed_roles=['admin', 'staff', 'users'])
def blog(request):
    posts = BlogPost.objects.all()
    context = {'title': 'Blog', 'posts': posts}
    return render(request, 'app_blog/blog.html', context)

def blog_detail(request, pk):
    user_post = BlogPost.objects.get(id=pk)
    context = {'title': 'Blog', 'user_post': user_post}
    return render(request, 'app_blog/blog_detail.html', context)

def blog_user_detail(request, pk):
    user_detail = BlogPost.objects.get(id=pk)
    user_type = user_detail.author.groups.all()[0].name.capitalize()
    context = {'title': 'Blog', 'user_detail': user_detail, 'user_type': user_type}
    return render(request, 'app_blog/blog_user_detail.html', context)

def blog_update(request, pk):
    if request.method == 'POST':
        blog_update = BlogUpdateForm(request.POST, instance=BlogPost.objects.get(id=pk))
        if blog_update.is_valid():
            blog_update.save()
            messages.success(request, 'Your blog-post has been updated!')
            return redirect('app_blog:blog_detail')
    else:
        blog_update = BlogUpdateForm(instance=BlogPost.objects.get(id=pk))
    context = {'title': 'Blog', 'blog_update': blog_update}
    return render(request, 'app_blog/blog_update.html', context)

urls.py:

from django.urls import path
from .views import *

app_name = 'app_blog'

urlpatterns = [
    path('blog/', blog, name='blog'),
    path('blog/<int:pk>/blog_detail/', blog_detail, name='blog_detail'),
    path('blog/<int:pk>/user_details/', blog_user_detail, name='blog_user_detail'),
    path('blog/<int:pk>/blog_update/', blog_update, name='blog_update'),
]

models.py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class BlogPost(models.Model):
    title = models.CharField(max_length=100, null=True)
    content = models.TextField(null=True)
    date_posted = models.DateTimeField(default=timezone.now, null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

blog_detail.html:

{% extends 'app_t35/main.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block content %}

                    {{ user_post.author }}
                    {{ user_post.date_posted|date:"d F, Y" }}
                    {% if user_post.author == request.user %}

                            Update
                            Delete

                    {% endif %}

{{ user_post.title }}

{{ user_post.content|safe }}

{% endblock %}

blog_update.html:

{% extends 'app_t35/main.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block content %}

{{ user.username }}:

            <form action="" method="POST">
                {% csrf_token %}
                <fieldset class="form-group">
                    <legend class="border-bottom mb-4">If you wish to update your blog-post:</legend>
                    {{ blog_update|crispy }}
                </fieldset>

                    <button class="btn btn-outline-info  btn-sm btn-block" style="width: 150px; align-self: center;" type="submit">Update Details</button>

            </form>

{% endblock %}


问:
WordPress wp_safe_remote_get() in offline
You must continue executing the code after the wp_safe_remote_get() failed to execute offline.
By default, the wp_safe_remote_get() stops code execution offline.</p>

答: We get the error not when we try to download the content, but after applying the variable. Before using the downloaded content, you need to check the variable for errors with the is_wp_error() function</p>


问:
new Twilio.TaskRouter.Workspace() gives WebSocket Unexpected response code: 403
So I have the following code:

```<code><?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once '../vendor/autoload.php'; // Loads the library
use Twilio\Jwt\TaskRouter\WorkerCapability;

// Your Account Sid and Auth Token from twilio.com/user/account
$accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$authToken = "your_auth_token";
$workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

$capability = new WorkerCapability($accountSid, $authToken, $workspaceSid);
$capability->allowFetchSubresources();
$capability->allowActivityUpdates();
$capability->allowReservationUpdates();
$token = $capability->generateToken();
// By default, tokens are good for one hour.
// Override this default timeout by specifiying a new value (in seconds).
// For example, to generate a token good for 8 hours:
$token = $capability->generateToken(28800);  // 60 * 60 * 8
?>
<script type="text/javascript" src="//media.twiliocdn.com/taskrouter/js/v1.20/taskrouter.min.js"></script>
<script>
    var workspace = new Twilio.TaskRouter.Workspace("<?= $token ?>");
</script>
</code>```

The PHP code generates a token just fine but the JS generates the following error:

```<code>WebSocket connection to '...' failed: Error during WebSocket handshake: Unexpected response code: 403
</code>```

Any ideas what's up with that?

Thanks!

答: You are setting up a WorkerCapability in your JWT but are trying to use it with the SDK Workspace object.  I believe you need to be using a WorkspaceCapability token if you want to instantiate a Workspace object from the SDK.

Body:
So I have the following code:

<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once '../vendor/autoload.php'; // Loads the library
use Twilio\Jwt\TaskRouter\WorkerCapability;

// Your Account Sid and Auth Token from twilio.com/user/account
$accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$authToken = "your_auth_token";
$workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

$capability = new WorkerCapability($accountSid, $authToken, $workspaceSid);
$capability->allowFetchSubresources();
$capability->allowActivityUpdates();
$capability->allowReservationUpdates();
$token = $capability->generateToken();
// By default, tokens are good for one hour.
// Override this default timeout by specifiying a new value (in seconds).
// For example, to generate a token good for 8 hours:
$token = $capability->generateToken(28800);  // 60 * 60 * 8
?>

The PHP code generates a token just fine but the JS generates the following error:

WebSocket connection to '...' failed: Error during WebSocket handshake: Unexpected response code: 403

Any ideas what's up with that?

Thanks!


问:
What is `@media screen` in CSS?
I’m learning about Flexbox in CSS and I wonder what the first line exactly does, i.e. what is @media screen and what exactly is one em?

@media screen and (min-width: 30em) {
  .single-nav ul {
    display: flex;
    justify-content: space-between;
  }

  .single-nav li {
    flex: 1 0 auto;
    text-align: center;
  }
}
```

答:
The @media is used for responsive html css design.
using the @media screen and (min-width: 30em) it indicates that if the screen size is 30em or larger then that specific css properties will be applied.See the small example for better understanding.

The em is used for dynamic font size.If you use px for font size then font will not resize when you change your system font-size.
Other hand em or rem is dynamically changed in size when you change your system font size.

.example{
background-color:red;
padding:100px;
}
@media only screen and (max-width: 700px){
.example{
background-color:yellow;
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<style>

</style>
</head>

<body>
<div class="example">
<p>when screen size is 700px or lesser then background will be yellow otherwise red</p>

</div>
</body>
</html></code>```

Title: What is `@media screen` in CSS?

Body:
The @media is used for responsive html css design.
using the @media screen and (min-width: 30em) it indicates that if the screen size is 30em or larger then that specific css properties will be applied.See the small example for better understanding.

The em is used for dynamic font size.If you use px for font size then font will not resize when you change your system font-size.
Other hand em or rem is dynamically changed in size when you change your system font size.

.example{
background-color:red;
padding:100px;
}
@media only screen and (max-width: 700px){
.example{
background-color:yellow;
}
}

<html>
<head>
<style>

</style>
</head>

<body>
<div class="example">
<p>when screen size is 700px or lesser then background will be yellow otherwise red</p>

</div>
</body>
</html>


问:
Unable to create exactly equal data partitions using createDataPartition in R- getting 1396 and 1398 observations each but need 1397
I am quite familiar with R but never had this requirement where I need to create exactly equal data partition randomly using createDataPartition in R.

```<code>index = createDataPartition(final_ts$SAR,p=0.5, list = F)
final_test_data = final_ts[index,]
final_validation_data = final_ts[-index,]
</code>```

This code creates two datasets with sizes 1396 and 1398 observations respectively.

I am surprised why p=0.5 doesn't do what it is supposed to do. Does it have something to do with resulting dataset not having odd number of observations by default?
Thanks in advance!

答:
Here is another thread which explains why the number returned from createDataPartition might seem to be "off" to us but not according to what this function is trying to do.
So, it depends on what you have in final_ts$SAR and the spread of the data.
If it is categorical value, ex: T and F, if you have 100 total, 55 are T, 45 are F. When you invoke the way in your code, it will return you 51 because:
55*0.5=27.5, 45*0.5=22.5, round each result up, 28+23=51.

You can refer to below thread which has a great explanation about this when the values you want to split are numbers.

R - caret createDataPartition returns more samples than expected

Body:
I am quite familiar with R but never had this requirement where I need to create exactly equal data partition randomly using createDataPartition in R.

index = createDataPartition(final_ts$SAR,p=0.5, list = F)
final_test_data = final_ts[index,]
final_validation_data = final_ts[-index,]

This code creates two datasets with sizes 1396 and 1398 observations respectively.

I am surprised why p=0.5 doesn't do what it is supposed to do. Does it have something to do with resulting dataset not having odd number of observations by default?
Thanks in advance!


问:
Git: How to squash all commits on branch
I make new branch from master with:

```<code>git checkout -b testbranch
</code>```

I make 20 commits into it.

Now I want to squash those 20 commits. I do that with:

```<code>git rebase -i HEAD~20
</code>```

What about if I don't know how many commits? Is there any way to do something like:

```<code>git rebase -i all on this branch
</code>```

答:
You can use tool I've created specifically for this task:

https://github.com/sheerun/git-squash

Basically you need to call git squash master and you're done

Body:
I make new branch from master with:

git checkout -b testbranch

I make 20 commits into it.

Now I want to squash those 20 commits. I do that with:

git rebase -i HEAD~20

What about if I don't know how many commits? Is there any way to do something like:

git rebase -i all on this branch


问:
Why Function returning None in Python Output
I want to know why the following two codes are returning None in Python output? Can somebody help me writing both codes correctly separately and tell me what's causing it to return None and explain please? I need the following output: Pay 498.75</p>

```<code># 1st Code - Returning None
def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print ("Error, please enter a numeric input")
        quit()
    if h >= 40:
        pay1 = 40 * r + (h - 40) * r * 1.5

        #print(pay1)
    else:
        pay2 = h * r
        #print( pay2)
p = computepay(45,10)
print("Pay",p)
</code>```

```<code># 2nd Code - Returning None
def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print ("Error, please enter a numeric input")
        quit()
    if h >= 40:
        pay1 = 40 * r + (h - 40) * r * 1.5

        print(pay1)
    else:
        pay2 = h * r
        print( pay2)
print("Pay",computepay(45,10.5))
#print("Pay",p)
</code>```

答:
You need to include a return statement in order for python to know what to return:</p>

```<code>def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print("Error, please enter a numeric input")
        quit()
    if h >= 40:
        return 40 * r + (h - 40) * r * 1.5
    else:
        return h * r
p = computepay(45,10.5)
print("Pay",p)
</code>```

Body:
I want to know why the following two codes are returning None in Python output? Can somebody help me writing both codes correctly separately and tell me what's causing it to return None and explain please? I need the following output: Pay 498.75

# 1st Code - Returning None
def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print ("Error, please enter a numeric input")
        quit()
    if h >= 40:
        pay1 = 40 * r + (h - 40) * r * 1.5

        #print(pay1)
    else:
        pay2 = h * r
        #print( pay2)
p = computepay(45,10)
print("Pay",p)

# 2nd Code - Returning None
def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print ("Error, please enter a numeric input")
        quit()
    if h >= 40:
        pay1 = 40 * r + (h - 40) * r * 1.5

        print(pay1)
    else:
        pay2 = h * r
        print( pay2)
print("Pay",computepay(45,10.5))
#print("Pay",p)

Body:
You need to include a return statement in order for python to know what to return:

def computepay(int1,int2):
    try:
        h = float(int1)
        r = float(int2)
    except:
        print("Error, please enter a numeric input")
        quit()
    if h >= 40:
        return 40 * r + (h - 40) * r * 1.5
    else:
        return h * r
p = computepay(45,10.5)
print("Pay",p)


问:
How can I divide a table into pages without using Bootstrap?
I have a table with about 14000 rows and I want to split the table into 1400 pages(10 rows each) and on changing the page I wanna read some data with AJAX... How is it possible? I don't want to use Bootstrap table datatype or anything...

Any solution?
Thanks in advance. :)

Here is my table :

```<code><?php
    echo '<table id="table" class="table">
        <thead>
            <th>username</th>
            <th>service</th>
            <th>Date_created</th>
            <th></th>
        </thead>';

        foreach($$list as &$res){
            $username = $res['username'];
            $group = $res['service'];
            $cr = $res['creation'];

            echo "
            <tbody>
                <td>$username</td>
                <td>$group</td>
                <td>$cr</td>
                <td><button type='button' rel='tooltip' title='More info' class='btn btn-primary btn-link btn-  sm' onclick='userDetailsModal(`$username`)'><i class='material-icons'>edit</i></button></td>
            </tbody>
            ";
        }

        echo '</table>
    </div>';
?>
</code>```

答:
If someone held a gun to me while coding and wouldn't allow a lib, I would take something like this approach:

```<code><table id=tab1>
  <tbody id=t1 class=active><tr><td>a</td></tr></tbody>
  <tbody id=t2><tr><td>b</td></tr></tbody>
  <tbody id=t3><tr><td>c</td></tr></tbody>
</table>
<style> tbody:not(.active) { display: none;} </style>
</code>```

I would generate the tbody with an ES6 template string by looping the ajax response array to set tab1.innerHTML. Your bodies will have many rows, and your rows many columns, but the tbody "trick" is key here. You then set a class of active on one tbody to show that page. You will need to figure out a dropdown or breadcrumb or page list widget at the bottom to document.querySelector("#tab1 .active").classList.remove("active"); and set active on the selected page.

Body:
I have a table with about 14000 rows and I want to split the table into 1400 pages(10 rows each) and on changing the page I wanna read some data with AJAX... How is it possible? I don't want to use Bootstrap table datatype or anything...

Any solution?
Thanks in advance. :)

Here is my table :

<?php
    echo '

            username
            service
            Date_created

';

        foreach($$list as &$res){
            $username = $res['username'];
            $group = $res['service'];
            $cr = $res['creation'];

            echo "

                $username
                $group
                $cr
                <button type='button' rel='tooltip' title='More info' class='btn btn-primary btn-link btn-  sm' onclick='userDetailsModal(`$username`)'>edit</button>

            ";
        }

        echo '

';
?>

Body:
If someone held a gun to me while coding and wouldn't allow a lib, I would take something like this approach:

<table id=tab1>
  <tbody id=t1 class=active><tr><td>a</td></tr></tbody>
  <tbody id=t2><tr><td>b</td></tr></tbody>
  <tbody id=t3><tr><td>c</td></tr></tbody>
</table>
<style> tbody:not(.active) { display: none;} </style>

I would generate the tbody with an ES6 template string by looping the ajax response array to set tab1.innerHTML. Your bodies will have many rows, and your rows many columns, but the tbody "trick" is key here. You then set a class of active on one tbody to show that page. You will need to figure out a dropdown or breadcrumb or page list widget at the bottom to document.querySelector("#tab1 .active").classList.remove("active"); and set active on the selected page.


问:
Iterator of Strings to Inputstream of bytes
I would like to convert an iterator of Strings to Inputstream of bytes. Usually, I can do this by appending all the strings in a StringBuilder and doing:
InputStream is = new ByteArrayInputStream(sb.toString().getBytes());

But I want to do it lazily because my iterable is provided by Spark and could be very large in length. I found this example to do it in Scala:

```<code>  def rowsToInputStream(rows: Iterator[String], delimiter: String): InputStream = {
  val bytes: Iterator[Byte] = rows.map { row =>
    (row + "\n").getBytes
  }.flatten

  new InputStream {
    override def read(): Int = if (bytes.hasNext) {
      bytes.next & 0xff // bitwise AND - make the signed byte an unsigned int from 0-255
    } else {
      -1
    }
  }
}
</code>```

But I could not find an easy way to convert this into Java. I converted the iterator to stream using Spliterators.spliteratorUnknownSize but then getBytes outputs an array which could not flatten easily. Overall it became pretty messy.

Is there an elegant way to do this in Java?

答:
As per @Kayaman's suggestion, I took a page from ByteArrayInputStream and handled switching of byte array using Iterator<String> manually. This one turned to be much more performant than the streams approach:

```<code>import java.io.InputStream;
import java.util.Iterator;

public class StringIteratorInputStream extends InputStream {
    protected byte buf[];
    protected int pos;
    protected int count;
    private Iterator<String> rows;

    public StringIteratorInputStream(Iterator<String> rows) {
        this.rows = rows;
        this.count = -1;
    }

    private void init(byte[] buf) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }

    public int read() {
        if (pos < count) {
           return (buf[pos++] & 0xff);
        } else if (rows.hasNext()) {
            init(rows.next().getBytes());
            return (buf[pos++] & 0xff);
        } else {
            return -1;
        }
    }

}
</code>```

I did not extend ByteArrayInputStream because it's read is synchronized and I didn't need that.

Body:
I would like to convert an iterator of Strings to Inputstream of bytes. Usually, I can do this by appending all the strings in a StringBuilder and doing:
InputStream is = new ByteArrayInputStream(sb.toString().getBytes());

But I want to do it lazily because my iterable is provided by Spark and could be very large in length. I found this example to do it in Scala:

  def rowsToInputStream(rows: Iterator[String], delimiter: String): InputStream = {
  val bytes: Iterator[Byte] = rows.map { row =>
    (row + "\n").getBytes
  }.flatten

  new InputStream {
    override def read(): Int = if (bytes.hasNext) {
      bytes.next & 0xff // bitwise AND - make the signed byte an unsigned int from 0-255
    } else {
      -1
    }
  }
}

But I could not find an easy way to convert this into Java. I converted the iterator to stream using Spliterators.spliteratorUnknownSize but then getBytes outputs an array which could not flatten easily. Overall it became pretty messy.

Is there an elegant way to do this in Java?

Body:
As per @Kayaman's suggestion, I took a page from ByteArrayInputStream and handled switching of byte array using Iterator<String> manually. This one turned to be much more performant than the streams approach:

import java.io.InputStream;
import java.util.Iterator;

public class StringIteratorInputStream extends InputStream {
    protected byte buf[];
    protected int pos;
    protected int count;
    private Iterator<String> rows;

    public StringIteratorInputStream(Iterator<String> rows) {
        this.rows = rows;
        this.count = -1;
    }

    private void init(byte[] buf) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }

    public int read() {
        if (pos < count) {
           return (buf[pos++] & 0xff);
        } else if (rows.hasNext()) {
            init(rows.next().getBytes());
            return (buf[pos++] & 0xff);
        } else {
            return -1;
        }
    }

}

I did not extend ByteArrayInputStream because it's read is synchronized and I didn't need that.


问:
Crop black padding and resize back to original 1920x1080
I have video of resolution 1920x1080 (16:9 aspect ratio). When played its padded with black box on all sides. How to remove the black boxes to get the 1920x1080 video?

Screenshot of video

Below the audio and video details:

```<code>Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'Maths Logic.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.19.102
  Duration: 00:43:11.24, start: 0.000000, bitrate: 1475 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 1405 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 64 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
</code>```

答:
Use cropdetect filter to get crop values:

```<code>ffmpeg -i input.mp4 -vf cropdetect -frames:v 3 -f null -
...
[Parsed_cropdetect_0 @ 0x559116cfe440] x1:240 x2:1679 y1:56 y2:1078 w:1440 h:1008 x:240 y:64 pts:2 t:2.000000 crop=1440:1008:240:64
</code>```

Then use crop filter to crop the black, scale to upscale back to 1080, and then pad to fill in missing area to make 16:9 aspect ratio:

```<code>ffmpeg -i input.mp4 -vf "crop=1440:1008:240:64,scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:-1:-1" -c:a copy output.mp4
</code>```

Before and after:

Body:
I have video of resolution 1920x1080 (16:9 aspect ratio). When played its padded with black box on all sides. How to remove the black boxes to get the 1920x1080 video?

Screenshot of video

Below the audio and video details:

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'Maths Logic.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf58.19.102
  Duration: 00:43:11.24, start: 0.000000, bitrate: 1475 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080 [SAR 1:1 DAR 16:9], 1405 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 64 kb/s (default)
    Metadata:
      handler_name    : SoundHandler

Body:
Use cropdetect filter to get crop values:

ffmpeg -i input.mp4 -vf cropdetect -frames:v 3 -f null -
...
[Parsed_cropdetect_0 @ 0x559116cfe440] x1:240 x2:1679 y1:56 y2:1078 w:1440 h:1008 x:240 y:64 pts:2 t:2.000000 crop=1440:1008:240:64

Then use crop filter to crop the black, scale to upscale back to 1080, and then pad to fill in missing area to make 16:9 aspect ratio:

ffmpeg -i input.mp4 -vf "crop=1440:1008:240:64,scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:-1:-1" -c:a copy output.mp4

Before and after:


问:
Jquery mobile - Android browser
I have developed a jquery mobile application for my site http://tastykhana.in/m there is an issue when the application is opened in the Android default web-kit browser.

I have to zoom in to view the UI correctly as it does not fit the screen and the fonts, input are very small.

What am i doing wrong here, as the site works well in the opera mini browser.

答:
Should be something with the page's CSS, have you tried using something like

```<code>content="width=device-width; initial-scale=1.0; maximum-scale=1.0;
</code>```

Here is a simple tutorial:
http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

ContentLicense: CC BY-SA 3.0

Title: Jquery mobile - Android browser

Body:
Should be something with the page's CSS, have you tried using something like

content="width=device-width; initial-scale=1.0; maximum-scale=1.0;

Here is a simple tutorial:
http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/


问:
Logrotation in openshift apache - not working
I am trying to rotate the apache logs in openshift using logrotate.

While trying to test the logrotate functionality, its giving me the below error

logrotate -d httpd

where httpd is the file present in /etc/logrotate.d

error: Logrotate UID is not in passwd file.
error: error creating state file /var/lib/..../logrotate.status

Please let me know if there is a fix to this or even logrotation is possible in openshift ?

答:
You should avoid using logrotate witin a container. In general, you should not use log files within a container and should always log to stdout.

This is a best practice from the Twelve-Factor App and OpenShift comes with its own Logging Stack to handle the logs.


问:
Absolute layout uasage
Is that ok to use absolute layout in my application if i know exactly the x,y that i'll draw the widget at or it'll affect the application appearance on the device ?

I'm asking this question as I've read that it's deprecated

答: In case of absolute layout, your application will adjust itself in every phn ,of any resolution or screen size. But in case of fixed coordinates may be screen size becomes a limitation.  </p>

Title: Absolute layout uasage


问:
Git squash all commits in branch without conflicting
A common development workflow for us is to checkout branch b, commit a bunch to it, then squash all those commits into one (still on b).

However, during the rebase -i process to squash all the commits, there are frequently conflicts at multiple steps.

I essentially want to alter the branch into one commit that represents the state of the repository at the time of the final commit on b

I've done some searching but I haven't found exactly what I'm looking for. I don't want to merge --squash because we would like to test the squashed feature branch before merging.

答:
I've created a tool specifically for this task:

https://github.com/sheerun/git-squash

For example you can call following to squash all commits from "master" commit up to HEAD, no matter how many conflicts there would be along the way:

```<code>git squash master
</code>```

It's basically what GitHub does when you "squash and merge" pull request.

Body:
I've created a tool specifically for this task:

https://github.com/sheerun/git-squash

For example you can call following to squash all commits from "master" commit up to HEAD, no matter how many conflicts there would be along the way:

git squash master

It's basically what GitHub does when you "squash and merge" pull request.


问:
Sequelize - Update FOREIGN KEY constraint win ONDELETE CASCADE
I'm using Postgres with Sequelize and I need to update an existing ForeignKey Constraint with onDelete = Cascade.

I have updated my model, but the migration file comes up as a skeleton. I haven't found a way to update this constraint.

My model file:

```<code>export const Property = sequelize.define<PropertyModel, PropertyAttribute>('property', {
  id: {
    type: Sequelize.UUID,
    primaryKey: true,
    defaultValue: Sequelize.UUIDV4,
    allowNull: false
  },
  name: Sequelize.STRING,
  status: {
    type: Sequelize.BOOLEAN,
    defaultValue: true
  },
  publishedAt: Sequelize.DATE
});

Property.associate = models => {
  Property.belongsTo(models.User, {
    foreignKey: { allowNull: false },
    allowNull: false
  });
  Property.hasMany(
    models.PropertyService, {onDelete: "cascade"});

  Property.hasMany(
    models.Visitor, {onDelete: "cascade"});
};
</code>```

My migration file:

```<code>module.exports = {
  up: (queryInterface, Sequelize) => {
      // How can I update a FK constraint??
  },

  down: (queryInterface, Sequelize) => {
      // How can I undo an FK update constraint??
  }
};
</code>```

Any ideas on how to make this migration?

答:
I found it simplest to first remove the existing constraint and then add it back with onDelete. Sequelize has queryInterface.removeConstraint and queryInterface.addConstraint methods for this.

Here is a contrived example:

```<code>'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      await queryInterface.removeConstraint(
        'users',
        'users_address_id_fkey',
        { transaction }
      );
      await queryInterface.addConstraint('users', ['address_id'], {
        type: 'foreign key',
        name: 'users_address_id_fkey',
        references: {
          table: 'addresses',
          field: 'id',
        },
        onDelete: 'CASCADE',
        transaction
      });
      return transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  },

  down: async (queryInterface, Sequelize) => {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      await queryInterface.removeConstraint(
        'users',
        'users_address_id_fkey',
        { transaction }
      );
      await queryInterface.addConstraint('users', ['address_id'], {
        type: 'foreign key',
        name: 'users_address_id_fkey',
        references: {
          table: 'addresses',
          field: 'id',
        },
        transaction
      });
      return transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  },
};
</code>```

Body:
I'm using Postgres with Sequelize and I need to update an existing ForeignKey Constraint with onDelete = Cascade.

I have updated my model, but the migration file comes up as a skeleton. I haven't found a way to update this constraint.

My model file:

export const Property = sequelize.define<PropertyModel, PropertyAttribute>('property', {
  id: {
    type: Sequelize.UUID,
    primaryKey: true,
    defaultValue: Sequelize.UUIDV4,
    allowNull: false
  },
  name: Sequelize.STRING,
  status: {
    type: Sequelize.BOOLEAN,
    defaultValue: true
  },
  publishedAt: Sequelize.DATE
});

Property.associate = models => {
  Property.belongsTo(models.User, {
    foreignKey: { allowNull: false },
    allowNull: false
  });
  Property.hasMany(
    models.PropertyService, {onDelete: "cascade"});

  Property.hasMany(
    models.Visitor, {onDelete: "cascade"});
};

My migration file:

module.exports = {
  up: (queryInterface, Sequelize) => {
      // How can I update a FK constraint??
  },

  down: (queryInterface, Sequelize) => {
      // How can I undo an FK update constraint??
  }
};

Any ideas on how to make this migration?

Body:
I found it simplest to first remove the existing constraint and then add it back with onDelete. Sequelize has queryInterface.removeConstraint and queryInterface.addConstraint methods for this.

Here is a contrived example:

'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      await queryInterface.removeConstraint(
        'users',
        'users_address_id_fkey',
        { transaction }
      );
      await queryInterface.addConstraint('users', ['address_id'], {
        type: 'foreign key',
        name: 'users_address_id_fkey',
        references: {
          table: 'addresses',
          field: 'id',
        },
        onDelete: 'CASCADE',
        transaction
      });
      return transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  },

  down: async (queryInterface, Sequelize) => {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      await queryInterface.removeConstraint(
        'users',
        'users_address_id_fkey',
        { transaction }
      );
      await queryInterface.addConstraint('users', ['address_id'], {
        type: 'foreign key',
        name: 'users_address_id_fkey',
        references: {
          table: 'addresses',
          field: 'id',
        },
        transaction
      });
      return transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  },
};


问:
iphone: unable to create URL
I am working with facebook apis

I am trying to fetch attributes of an image with id '105502842870274' for this I tried to create a url like this

```<code>NSString *firstComponent=@"https://graph.facebook.com/105502842870274?access_token=";
firstComponent=[firstComponent stringByAppendingFormat:[NSString stringWithFormat:@"%@",_accessToken]];

NSURL *url = [NSURL URLWithString:firstComponent];
</code>```

but every time url is passes as nil.

Please let me know if I am doing something wrong or suggest someother way to fetch attributes of an image.

Thanx in advance

答:
this will resolve your issue. Its html encoding problem.

```<code>firstComponent = [firstComponent stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
</code>```

also look: reference page

Title: iphone: unable to create URL

Body:
I am working with facebook apis

I am trying to fetch attributes of an image with id '105502842870274' for this I tried to create a url like this

NSString *firstComponent=@"https://graph.facebook.com/105502842870274?access_token=";
firstComponent=[firstComponent stringByAppendingFormat:[NSString stringWithFormat:@"%@",_accessToken]];

NSURL *url = [NSURL URLWithString:firstComponent];

but every time url is passes as nil.

Please let me know if I am doing something wrong or suggest someother way to fetch attributes of an image.

Thanx in advance

Body:
this will resolve your issue. Its html encoding problem.

firstComponent = [firstComponent stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

also look: reference page


问:
How to parse hostname in URI.js to remove 'www.'?
I want to use URI.js to parse a URL to get the hostname without the 'www.'.

```<code>const hostname = URI('http//www.example.com').hostname()
// -> Produces: 'www.example.com'
// Instead, I want: 'example.com'
</code>```

What am I doing wrong?

答:
It should be

```<code>const hostname = URI('http//www.example.com').domain()
</code>```

More details on https://medialize.github.io/URI.js/docs.html#accessors-domain

Body:
I want to use URI.js to parse a URL to get the hostname without the 'www.'.

const hostname = URI('http//www.example.com').hostname()
// -> Produces: 'www.example.com'
// Instead, I want: 'example.com'

What am I doing wrong?

Body:
It should be

const hostname = URI('http//www.example.com').domain()

More details on https://medialize.github.io/URI.js/docs.html#accessors-domain


问:
Using Substring to pull out a fixed number of characters starting a given number in a separate column in SQL Server Management Studio
I have a database of webchats that has a single string field of the complete chat transcript (including visitor time, text, advisor's responses and times etc)  that I want to pull data from.

I have previously used some Substring code to pull out 8 characters, starting from the 10th character in order to get me the timestamp attached to when a visitor starting talking to the advisor;

```<code>SubString([chat transcript], 10, 8) as [visitor message time]
</code>```

I have also used CharIndex to pull from the field to tell me the character number at which the Advisor is first mentioned (aka, when they first reply).

```<code>CharIndex([chat agent alias],[chat transcript],0) as [alias location in chat]
</code>```

This doesn't tell me when the advisor first replied however. In the transcript the advisor's first reply is followed by a timestamp, and what I want to be able to do is pull the timestamp for each different advisor.

I was wondering it's possible to do something similar with the Substring function as above, but instead of stating the fixed Character number it should start from, it instead uses the number in the Alias Location In Chat field instead. (see table below, of which I want it to for row 4 for example, search for the 138th character in the Chat Transcript field, and pull out the next eight characters in that field)

Something like:

```<code>SubString([chat transcript], [alias location in chat], 8) as [visitor message time]
</code>```

Does anyone have an idea of how to do this?

答: I would not do that in bare T-SQL as it is pathetic when it comes to string manipulation. For example it doesn't implement regular expressions which I think would be of tremendous help here. Given this task I would probably use Python to connect to this database using pyodbc and then fetch and process the textual data using wealth of Python libraries available.

Body:
I have a database of webchats that has a single string field of the complete chat transcript (including visitor time, text, advisor's responses and times etc)  that I want to pull data from.

I have previously used some Substring code to pull out 8 characters, starting from the 10th character in order to get me the timestamp attached to when a visitor starting talking to the advisor;

SubString([chat transcript], 10, 8) as [visitor message time]

I have also used CharIndex to pull from the field to tell me the character number at which the Advisor is first mentioned (aka, when they first reply).

CharIndex([chat agent alias],[chat transcript],0) as [alias location in chat]

This doesn't tell me when the advisor first replied however. In the transcript the advisor's first reply is followed by a timestamp, and what I want to be able to do is pull the timestamp for each different advisor.

I was wondering it's possible to do something similar with the Substring function as above, but instead of stating the fixed Character number it should start from, it instead uses the number in the Alias Location In Chat field instead. (see table below, of which I want it to for row 4 for example, search for the 138th character in the Chat Transcript field, and pull out the next eight characters in that field)

Something like:

SubString([chat transcript], [alias location in chat], 8) as [visitor message time]

Does anyone have an idea of how to do this?


问:
Can't run Perl script on other computer
When I try to run script on my second computer I get this message:

```
malformed JSON string, neither array, object, number, string or atom, at character offset 0
(before "LWP will support htt...") at iptest.pl line 21,  line 2.
```

On my first computer, the script works fine.

Line 21:

```<code>my $data = decode_json($resp->content);
</code>```

Does anyone know what the problem can be?

Thanks in advance

答:
I got in the same situation. After I used 'yum' to install perl, I still got the error when run the perl script.

```<code>$ sudo yum install perl
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management
...
</code>```

Eventually I did these, and it works.

```<code>$ lwp-request https://google.com/

It returned an error message .. (LWP::Protocol::https not installed)

$ sudo rpm -ivh ~/perl-LWP-Protocol-https-6.07-4.el8.noarch.rpm

$ lwp-request https://google.com/
</code>```

it returned a HTML page.

and my perl script can run without error.

(my system is:

$ cat /etc/os-release
   PRETTY_NAME=Red Hat Enterprise Linux 8.0 )

Title: Can't run Perl script on other computer

Body:
When I try to run script on my second computer I get this message:

malformed JSON string, neither array, object, number, string or atom, at character offset 0
(before "LWP will support htt...") at iptest.pl line 21,  line 2.

On my first computer, the script works fine.

Line 21:

my $data = decode_json($resp->content);

Does anyone know what the problem can be?

Thanks in advance

Body:
I got in the same situation. After I used 'yum' to install perl, I still got the error when run the perl script.

$ sudo yum install perl
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management
...

Eventually I did these, and it works.

$ lwp-request https://google.com/

It returned an error message .. (LWP::Protocol::https not installed)

$ sudo rpm -ivh ~/perl-LWP-Protocol-https-6.07-4.el8.noarch.rpm

$ lwp-request https://google.com/

it returned a HTML page.

and my perl script can run without error.

(my system is:

$ cat /etc/os-release
   PRETTY_NAME=Red Hat Enterprise Linux 8.0 )


问:
Can Typescript guard / discriminate based on field presence (undefined / absent) rather than value?
Can anyone explain why Typescript can narrow types with the in keyword, but not by presence an non-undefined value? I'm porting a large codebase from JS to TS, and very extensive use has been made of the if (x.something) { ... } construct.

```<code>declare const x: { a?: object } | { b: number };

if ('a' in x) {
  const Q = x.a;  // Q: object | undefined, correct but not very helpful - still have to test Q for non-undefined
}

if (x.a) {
  const Q = x.a; // Doesn't work, but if it did, Q: object, which is helpful
}

if (typeof x.a !== "undefined") {
  const Q = x.a; // Same as above
}
</code>```

Note that if it's not a union, it works as expected:

```<code>declare const x: { a?: object }

if ('a' in x) {
  const Q = x.a;  // Q: object | undefined, correct but not very helpful
}

if (x.a) {
  const Q = x.a; // Q: object (yay!)
}
</code>```

答:
Can you use a custom type check?
For example:</p>

```<code>export const instanceOfIImportNotification = (_o: any): _o is IImportNotification => {
  return 'metaData' in _o && 'importType' in _o.metaData && 'azureFilePath' in _o.metaData;
};
</code>```

Body:
Can anyone explain why Typescript can narrow types with the in keyword, but not by presence an non-undefined value? I'm porting a large codebase from JS to TS, and very extensive use has been made of the if (x.something) { ... } construct.

declare const x: { a?: object } | { b: number };

if ('a' in x) {
  const Q = x.a;  // Q: object | undefined, correct but not very helpful - still have to test Q for non-undefined
}

if (x.a) {
  const Q = x.a; // Doesn't work, but if it did, Q: object, which is helpful
}

if (typeof x.a !== "undefined") {
  const Q = x.a; // Same as above
}

Note that if it's not a union, it works as expected:

declare const x: { a?: object }

if ('a' in x) {
  const Q = x.a;  // Q: object | undefined, correct but not very helpful
}

if (x.a) {
  const Q = x.a; // Q: object (yay!)
}

Body:
Can you use a custom type check?
For example:

export const instanceOfIImportNotification = (_o: any): _o is IImportNotification => {
  return 'metaData' in _o && 'importType' in _o.metaData && 'azureFilePath' in _o.metaData;
};


问:
treatment of `common` memoized python functions
For a python application including the following modules:

commons.py

```<code>    @lru_cache(maxsize=2)
    def memoized_f(x):
        ...

</code>```

pipeline_a.py

```<code>from commons import memoized_f

x = memoized_f(10)
y = memoized_f(11)
</code>```

pipeline_b.py

```<code>from commons import memoized_f

x = memoized_f(20)
y = memoized_f(21)
</code>```

does python store one memoized_f cache per pipeline_* module? so in the example above, there will be two caches, total for memoized_f? or

because the caching is defined for memoized_f, there is only cache stored here for memoized_f in the application containing all the modules above?

答:
@functools.lru_cache doesn't do any magic. It is a function decorator, meaning it takes the annotated function (here: memoized_f) as input and defines a new function. Essentially it does memoized_f = lru_cache(memoized_f, maxsize=2, ...) (see here)

So your question boils down to whether a (function in a) module imported by two other modules shares state, to which the answer is yes, there is a common cache. This is because each module is only imported once.

See e.g. the official documentation

Body:
For a python application including the following modules:

commons.py

    @lru_cache(maxsize=2)
    def memoized_f(x):
        ...

pipeline_a.py

from commons import memoized_f

x = memoized_f(10)
y = memoized_f(11)

pipeline_b.py

from commons import memoized_f

x = memoized_f(20)
y = memoized_f(21)

does python store one memoized_f cache per pipeline_* module? so in the example above, there will be two caches, total for memoized_f? or

because the caching is defined for memoized_f, there is only cache stored here for memoized_f in the application containing all the modules above?


问:
Execute JavaScript using Selenium WebDriver in C#
How is this achieved? Here it says the java version is:

```<code>WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return document.title");
</code>```

But I can't find the C# code to do this.

答:
The shortest code</p>

```<code>ChromeDriver drv = new ChromeDriver();

drv.Navigate().GoToUrl("https://stackoverflow.com/questions/6229769/execute-javascript-using-selenium-webdriver-in-c-sharp");

drv.ExecuteScript("return alert(document.title);");

</code>```

Body:
How is this achieved? Here it says the java version is:

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return document.title");

But I can't find the C# code to do this.

Body:
The shortest code

ChromeDriver drv = new ChromeDriver();

drv.Navigate().GoToUrl("https://stackoverflow.com/questions/6229769/execute-javascript-using-selenium-webdriver-in-c-sharp");

drv.ExecuteScript("return alert(document.title);");


问:
Sharing links with query strings
I'm trying to set up a LinkedIn share button that needs to share a URL with a query string included. I've tried various combinations of encoding the URL but LinkedIn breaks every option either by removing everything starting with the "=" or by sharing a link with the "=" encoded to "%3D"

How am I supposed to get this to work or is LinkedIn just not going to fix this?

I've set a simple demo of this here: https://jsfiddle.net/09dopxm5/

For brevity sake, here's the Javascript I tried to generate a link that would work...

var original_link = "https://www.simplifyingthemarket.com/en/2019/03/07/why-an-economic-slowdown-will-not-crush-real-estate-this-time/?a=311651-adc5cc7d14b39be55e90ff0b2b7bbf6a";

var link1 = escape(original_link);
var link2 = encodeURI(original_link);
var link3 = encodeURIComponent(original_link);

var linkedinLink = "https://www.linkedin.com/shareArticle?mini=true&url=";

document.getElementById("link-1").href = linkedinLink + link1;
document.getElementById("link-2").href = linkedinLink + link2;
document.getElementById("link-3").href = linkedinLink + link3;
document.getElementById("link-4").href = linkedinLink + original_link;```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Share Attempt 1<br/>
Share Attempt 2<br/>
Share Attempt 3<br/>
Share Attempt 4<br/></code>```

EDIT -
An added piece of info is that we are not sharing the URL that the user is currently on. We're trying to share a personalized version of the post they're currently viewing.

答:
Your third link works perfectly for me!  See:

So, that means the solution, in terms of JavaScript is...

```<code>var original_link = "https://www.simplifyingthemarket.com/en/2019/03/07/why-an-economic-slowdown-will-not-crush-real-estate-this-time/?a=311651-adc5cc7d14b39be55e90ff0b2b7bbf6a";

var link3 = encodeURIComponent(original_link);
var linkedinLink = "https://www.linkedin.com/shareArticle?mini=true&url=";
document.getElementById("link-3").href = linkedinLink + link3;
</code>```

And your HTML solution is...

```<code><a href='#' id='link-3' target="_blank">Share Attempt 3</a><br/>
</code>```

In case you're uncertain, you can check with the LinkedIn Post Inspector.

Also helpful:

Microsoft LinkedIn Share Documentation : for URL formatting.

LinkedIn Shareable Documentation : for og: tag formatting.

Title: Sharing links with query strings

Body:
I'm trying to set up a LinkedIn share button that needs to share a URL with a query string included. I've tried various combinations of encoding the URL but LinkedIn breaks every option either by removing everything starting with the "=" or by sharing a link with the "=" encoded to "%3D"

How am I supposed to get this to work or is LinkedIn just not going to fix this?

I've set a simple demo of this here: https://jsfiddle.net/09dopxm5/

For brevity sake, here's the Javascript I tried to generate a link that would work...

var original_link = "https://www.simplifyingthemarket.com/en/2019/03/07/why-an-economic-slowdown-will-not-crush-real-estate-this-time/?a=311651-adc5cc7d14b39be55e90ff0b2b7bbf6a";

var link1 = escape(original_link);
var link2 = encodeURI(original_link);
var link3 = encodeURIComponent(original_link);

var linkedinLink = "https://www.linkedin.com/shareArticle?mini=true&url=";

document.getElementById("link-1").href = linkedinLink + link1;
document.getElementById("link-2").href = linkedinLink + link2;
document.getElementById("link-3").href = linkedinLink + link3;
document.getElementById("link-4").href = linkedinLink + original_link;

Share Attempt 1

Share Attempt 2

Share Attempt 3

Share Attempt 4

EDIT -
An added piece of info is that we are not sharing the URL that the user is currently on. We're trying to share a personalized version of the post they're currently viewing.

Body:
Your third link works perfectly for me!  See:

So, that means the solution, in terms of JavaScript is...

var original_link = "https://www.simplifyingthemarket.com/en/2019/03/07/why-an-economic-slowdown-will-not-crush-real-estate-this-time/?a=311651-adc5cc7d14b39be55e90ff0b2b7bbf6a";

var link3 = encodeURIComponent(original_link);
var linkedinLink = "https://www.linkedin.com/shareArticle?mini=true&url=";
document.getElementById("link-3").href = linkedinLink + link3;

And your HTML solution is...

<a href='#' id='link-3' target="_blank">Share Attempt 3</a><br/>

In case you're uncertain, you can check with the LinkedIn Post Inspector.

Also helpful:

Microsoft LinkedIn Share Documentation : for URL formatting.

LinkedIn Shareable Documentation : for og: tag formatting.


问:
Get second Onclicklistener values
I have  String values in firebase database
I would like to get this String
in onClick i make a toast for display the value but the value is toasted in the second click

```<code>protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_souslistecuisine);
    cuisinecomplet=(ImageView)findViewById(R.id.cuisinecomplett);

    FirebaseDatabase database= FirebaseDatabase.getInstance();
    DatabaseReference myRef=database.getReference("Produit");
    DatabaseReference key=myRef.child("Cuisine");
    DatabaseReference text=key.child("cuisine complet");
    text1=text.child("text1");
    text1.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            txt=dataSnapshot.getValue(String.class);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}
public void complet(View view) {

    Toast.makeText(souslistecuisine.this, txt, Toast.LENGTH_LONG).show();

}
</code>```

I tried to put text1.addValueEventListener(new ValueEventListener())  in Onclick method but same result

答:
Just add the Toast after you already receive the String value from Firebase, as Firebase callbacks run in background thread and take time to response.

```<code>text1.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        txt=dataSnapshot.getValue(String.class);
        Toast.makeText(souslistecuisine.this, txt, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
</code>```

Title: Get second Onclicklistener values

Body:
I have  String values in firebase database
I would like to get this String
in onClick i make a toast for display the value but the value is toasted in the second click

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_souslistecuisine);
    cuisinecomplet=(ImageView)findViewById(R.id.cuisinecomplett);

    FirebaseDatabase database= FirebaseDatabase.getInstance();
    DatabaseReference myRef=database.getReference("Produit");
    DatabaseReference key=myRef.child("Cuisine");
    DatabaseReference text=key.child("cuisine complet");
    text1=text.child("text1");
    text1.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            txt=dataSnapshot.getValue(String.class);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}
public void complet(View view) {

    Toast.makeText(souslistecuisine.this, txt, Toast.LENGTH_LONG).show();

}

I tried to put text1.addValueEventListener(new ValueEventListener())  in Onclick method but same result

Body:
Just add the Toast after you already receive the String value from Firebase, as Firebase callbacks run in background thread and take time to response.

text1.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        txt=dataSnapshot.getValue(String.class);
        Toast.makeText(souslistecuisine.this, txt, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});


问:
Change initial position and rotation of a model
Got a simple .html file using A-Frame that loads a specific model.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Octant Cube - by Dodds, H. & Peres, T.</title>
    <meta name="description" content="Present in the Taxonomy article">
    <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
  </head>
  <body>
    <a-scene background="color: #FAFAFA">
      <a-assets>
        <a-asset-item id="octant" src="octant.glb"></a-asset-item>
      </a-assets>
      <a-entity gltf-model="#octant"></a-entity>
  </body>
</html>
</code>```

The object loads fine on the page (as the documentation suggests) but this is what I see at first

If I look all down I'm able to see one plane

But would like to see the following at start

Using the A-Frame Inspector I was able to see this would suit nice in the position 0 , 0.347, -3 and rotation 0, 58.0274, -0.27.

I tried adding the position and rotation to  and  but no change was possible to be seen.

How can I change the initial position and the rotation of the model?

答:
One needs to add that information in  instead, like this

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Octant Cube - by Dodds, H. & Peres, T.</title>
    <meta name="description" content="Present in the Taxonomy article">
    <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
  </head>
  <body>
    <a-scene background="color: #FAFAFA">
      <a-assets>
        <a-asset-item id="octant" src="octant.glb"></a-asset-item>
      </a-assets>
      <a-entity position="0 0.347 -4" rotation="0 60 -1"  gltf-model="#octant"></a-entity>
  </body>
</html>
</code>```

This is the final result

Body:
Got a simple .html file using A-Frame that loads a specific model.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Octant Cube - by Dodds, H. & Peres, T.</title>
    <meta name="description" content="Present in the Taxonomy article">

The object loads fine on the page (as the documentation suggests) but this is what I see at first

If I look all down I'm able to see one plane

But would like to see the following at start

Using the A-Frame Inspector I was able to see this would suit nice in the position 0 , 0.347, -3 and rotation 0, 58.0274, -0.27.

I tried adding the position and rotation to  and  but no change was possible to be seen.

How can I change the initial position and the rotation of the model?

Body:
One needs to add that information in <a-entity> instead, like this

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Octant Cube - by Dodds, H. & Peres, T.</title>
    <meta name="description" content="Present in the Taxonomy article">
    <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
  </head>
  <body>
    <a-scene background="color: #FAFAFA">
      <a-assets>
        <a-asset-item id="octant" src="octant.glb"></a-asset-item>
      </a-assets>
      <a-entity position="0 0.347 -4" rotation="0 60 -1"  gltf-model="#octant"></a-entity>
  </body>
</html>

This is the final result


问:
How to calculate the price of a product using a discount in mysql?
I have a products table where I store the original price and a discount percentage:

```<code>mysql> select * from products;
+---------------+--------+-----------+--------+
| concept       | price  | discount  | currency |
+---------------+--------+-----------+--------+
| yyy           |      1 |      0.00 | usd    |
| xxx           |     10 |     50.00 | usd    |
+---------------+--------+-----------+--------+
</code>```

How could I calculate the total price of each item in a SELECT stament using the price and discount column so I can get the following

```<code>mysql> select ???????
+---------------+--------+--------+
| concepto      | total  | currency |
+---------------+--------+--------+
| yyy           |     1  | usd    |
| xxx           |     5  | usd    |
+---------------+--------+--------+

</code>```

答:
That's simple arithmetics:</p>

```<code>select
    concept,
    price * (1 - discount / 100) total,
    currency
from products
</code>```

Body:
I have a products table where I store the original price and a discount percentage:

mysql> select * from products;
+---------------+--------+-----------+--------+
| concept       | price  | discount  | currency |
+---------------+--------+-----------+--------+
| yyy           |      1 |      0.00 | usd    |
| xxx           |     10 |     50.00 | usd    |
+---------------+--------+-----------+--------+

How could I calculate the total price of each item in a SELECT stament using the price and discount column so I can get the following

mysql> select ???????
+---------------+--------+--------+
| concepto      | total  | currency |
+---------------+--------+--------+
| yyy           |     1  | usd    |
| xxx           |     5  | usd    |
+---------------+--------+--------+

Body:
That's simple arithmetics:

select
    concept,
    price * (1 - discount / 100) total,
    currency
from products


问:
Teechart VCL - how to change Marks border color and mark length at runtime?
I'm using Delphi 10.3-upd 1 with Teechart component .

At run-time I need to put marks for specific points and customize its texts, colors and sizes.  I've succeded in changing texts using the following commands :

```<code>Chart1.[idxserie].Marks.Item[idxelement].Visible  := True;
Chart1.[idxserie].Marks.Iidxelement]].Font.Color  := clRed;
Chart1.[idxserie].Marks.item[idxelement].Text.Add('My text is here');
</code>```

now  I need to change the color of the line that links the text to the point in the graph curve.  In design time, this property is located at  :

Editing chart window  :

```<code>      Series -- myserie1 -
                tab : Marks
                           -- tab Arrows
                                         -- tab Border
                                                     tab  -- Format
                                                                 Button : Color
</code>```

How do I access and change the value of this property on run-time ?

I've alreeady  tried :

```<code>Chart1.[idxserie].Marks.Arrow.Color  := clRed  // ==> nothing changed !
</code>```

This is where I change the property at design time :

In below picture, the dotted red line for some points I want it in different color.  When I use Chart1.[idxserie].Marks.Arrow.Color  := clRed  it changes  the color of all points .

I appreciate your support.

Thanks.

答:
The Arrow is global.
You can overwrite it yourself using one of the AfterDraw events of Series or Chart.

An example:
Creation:

```<code>procedure TForm1.FormCreate(Sender: TObject);
begin
  series1.FillSampleValues(5);
  series1.Marks.Visible := true; // A global flag. if false, no Mark will be visible

  series1.Marks[0].Visible := false;
  series1.Marks[1].Visible := true;
  series1.Marks[2].Visible := false;
  series1.Marks[3].Visible := true;
  series1.Marks[4].Visible := false;

  series1.Marks[3].Font.Color := clRed;
  series1.Marks[3].Font.Style := [fsBold];
  series1.Marks[3].Transparent:= true;

  series1.Marks.Arrow.Color    := clGreen;
  series1.Marks.ArrowLength    := 24;
  series1.Marks.Arrow.EndStyle := esFlat;
  series1.Marks.Arrow.Visible  := true;
end;
</code>```

Now, draw a line on the Chart Canvas:

```<code>procedure TForm1.Series1AfterDrawValues(Sender: TObject);
var
  nInx, nX, nY: integer;
begin
  for nInx := 0 to Series1.Count-1 do
    if Series1.Marks[nInx].Font.Color = clRed then
      begin
        nX := Series1.CalcXPos(nInx);
        nY := Series1.CalcYPos(nInx);
        Chart1.Canvas.Pen.Color := clRed;
        Chart1.Canvas.MoveTo(nX, nY);
        Chart1.Canvas.LineTo(nX, nY - series1.Marks.ArrowLength);
      end;
end;
</code>```

You will get:

Body:
I'm using Delphi 10.3-upd 1 with Teechart component .

At run-time I need to put marks for specific points and customize its texts, colors and sizes.  I've succeded in changing texts using the following commands :

Chart1.[idxserie].Marks.Item[idxelement].Visible  := True;
Chart1.[idxserie].Marks.Iidxelement]].Font.Color  := clRed;
Chart1.[idxserie].Marks.item[idxelement].Text.Add('My text is here');

now  I need to change the color of the line that links the text to the point in the graph curve.  In design time, this property is located at  :

Editing chart window  :

      Series -- myserie1 -
                tab : Marks
                           -- tab Arrows
                                         -- tab Border
                                                     tab  -- Format
                                                                 Button : Color

How do I access and change the value of this property on run-time ?

I've alreeady  tried :

Chart1.[idxserie].Marks.Arrow.Color  := clRed  // ==> nothing changed !

This is where I change the property at design time :

In below picture, the dotted red line for some points I want it in different color.  When I use Chart1.[idxserie].Marks.Arrow.Color  := clRed  it changes  the color of all points .

I appreciate your support.

Thanks.

Body:
The Arrow is global.
You can overwrite it yourself using one of the AfterDraw events of Series or Chart.

An example:
Creation:

procedure TForm1.FormCreate(Sender: TObject);
begin
  series1.FillSampleValues(5);
  series1.Marks.Visible := true; // A global flag. if false, no Mark will be visible

  series1.Marks[0].Visible := false;
  series1.Marks[1].Visible := true;
  series1.Marks[2].Visible := false;
  series1.Marks[3].Visible := true;
  series1.Marks[4].Visible := false;

  series1.Marks[3].Font.Color := clRed;
  series1.Marks[3].Font.Style := [fsBold];
  series1.Marks[3].Transparent:= true;

  series1.Marks.Arrow.Color    := clGreen;
  series1.Marks.ArrowLength    := 24;
  series1.Marks.Arrow.EndStyle := esFlat;
  series1.Marks.Arrow.Visible  := true;
end;

Now, draw a line on the Chart Canvas:

procedure TForm1.Series1AfterDrawValues(Sender: TObject);
var
  nInx, nX, nY: integer;
begin
  for nInx := 0 to Series1.Count-1 do
    if Series1.Marks[nInx].Font.Color = clRed then
      begin
        nX := Series1.CalcXPos(nInx);
        nY := Series1.CalcYPos(nInx);
        Chart1.Canvas.Pen.Color := clRed;
        Chart1.Canvas.MoveTo(nX, nY);
        Chart1.Canvas.LineTo(nX, nY - series1.Marks.ArrowLength);
      end;
end;

You will get:


问:
How do I overcome "Permission Denial....obtain access using ACTION_OPEN_DOCUMENT or related APIs"?
I'm using react-native-firebase and react-native-document-picker and I'm trying to follow the face detection tutorial.

Currently getting the following error despite having read access through PermissionsAndroid:

Permission Denial: reading com.android.provides.media.MediaDocumentsProvider uri [uri] from pid=4746, uid=10135 requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

I am able to display the selected image by the user on the screen but the react-native-firebase functions seems to not be able to have permission. The error happens at this call: const faces = await vision().faceDetectorProcessImage(localPath);.

Any suggestions on how to give the face detection function access or what am I doing wrong?

My AndroidManifest.xml file contains the following:

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Here is all the code in that component for reference:

```<code>import React, {useState} from 'react';
import { Button, Text, Image, PermissionsAndroid } from 'react-native';
import vision, { VisionFaceContourType } from '@react-native-firebase/ml-vision';
import DocumentPicker from 'react-native-document-picker';

async function processFaces(localPath) {

  console.log(localPath)
  const faces = await vision().faceDetectorProcessImage(localPath);
  console.log("Got faces")

  faces.forEach(face => {
    console.log('Head rotation on Y axis: ', face.headEulerAngleY);
    console.log('Head rotation on Z axis: ', face.headEulerAngleZ);

    console.log('Left eye open probability: ', face.leftEyeOpenProbability);
    console.log('Right eye open probability: ', face.rightEyeOpenProbability);
    console.log('Smiling probability: ', face.smilingProbability);

    face.faceContours.forEach(contour => {
      if (contour.type === VisionFaceContourType.FACE) {
        console.log('Face outline points: ', contour.points);
      }
    });
  });
}

async function pickFile () {
    // Pick a single file
    try {
        const res = await DocumentPicker.pick({
            type: [DocumentPicker.types.images],
        });
        console.log(
            res.uri,
            res.type, // mime type
            res.name,
            res.size
        );
        return res
    } catch (err) {
        if (DocumentPicker.isCancel(err)) {
        // User cancelled the picker, exit any dialogs or menus and move on
            console.log("User cancelled")
        } else {
            console.log("Error picking file or processing faces")
            throw err;
        }
    }
}

const requestPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        {
          title: "Files Permission",
          message:
            "App needs access to your files " +
            "so you can run face detection.",
          buttonNeutral: "Ask Me Later",
          buttonNegative: "Cancel",
          buttonPositive: "OK"
        }
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("We can now read files");
      } else {
        console.log("File read permission denied");
      }
      return granted
    } catch (err) {
      console.warn(err);
    }
  };

function FaceDetectionScreen ({navigation}) {
    const [image, setImage] = useState("");
    return (
        <>
            <Text>This is the Face detection screen.</Text>
            <Button title="Select Image to detect faces" onPress={async () => {
                const permission = await requestPermission();
                if (permission === PermissionsAndroid.RESULTS.GRANTED) {
                    const pickedImage = await pickFile();
                    const pickedImageUri = pickedImage.uri
                    setImage(pickedImageUri);
                    processFaces(pickedImageUri).then(() => console.log('Finished processing file.'));
                }
                }}/>
            <Image style={{flex: 1}} source={{ uri: image}}/>
        </>
    );
}

export default FaceDetectionScreen;
</code>```

答:
Thanks to this comment on a github issue I was able to update my code and get it to work by updating the first three lines of processFaces as:

```<code>async function processFaces(contentUri) {
  const stat = await RNFetchBlob.fs.stat(contentUri)
  const faces = await vision().faceDetectorProcessImage(stat.path);
</code>```

after importing import RNFetchBlob from 'rn-fetch-blob'.

rn-fetch-blob

Body:
I'm using react-native-firebase and react-native-document-picker and I'm trying to follow the face detection tutorial.

Currently getting the following error despite having read access through PermissionsAndroid:

Permission Denial: reading com.android.provides.media.MediaDocumentsProvider uri [uri] from pid=4746, uid=10135 requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

I am able to display the selected image by the user on the screen but the react-native-firebase functions seems to not be able to have permission. The error happens at this call: const faces = await vision().faceDetectorProcessImage(localPath);.

Any suggestions on how to give the face detection function access or what am I doing wrong?

My AndroidManifest.xml file contains the following:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Here is all the code in that component for reference:

import React, {useState} from 'react';
import { Button, Text, Image, PermissionsAndroid } from 'react-native';
import vision, { VisionFaceContourType } from '@react-native-firebase/ml-vision';
import DocumentPicker from 'react-native-document-picker';

async function processFaces(localPath) {

  console.log(localPath)
  const faces = await vision().faceDetectorProcessImage(localPath);
  console.log("Got faces")

  faces.forEach(face => {
    console.log('Head rotation on Y axis: ', face.headEulerAngleY);
    console.log('Head rotation on Z axis: ', face.headEulerAngleZ);

    console.log('Left eye open probability: ', face.leftEyeOpenProbability);
    console.log('Right eye open probability: ', face.rightEyeOpenProbability);
    console.log('Smiling probability: ', face.smilingProbability);

    face.faceContours.forEach(contour => {
      if (contour.type === VisionFaceContourType.FACE) {
        console.log('Face outline points: ', contour.points);
      }
    });
  });
}

async function pickFile () {
    // Pick a single file
    try {
        const res = await DocumentPicker.pick({
            type: [DocumentPicker.types.images],
        });
        console.log(
            res.uri,
            res.type, // mime type
            res.name,
            res.size
        );
        return res
    } catch (err) {
        if (DocumentPicker.isCancel(err)) {
        // User cancelled the picker, exit any dialogs or menus and move on
            console.log("User cancelled")
        } else {
            console.log("Error picking file or processing faces")
            throw err;
        }
    }
}

const requestPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        {
          title: "Files Permission",
          message:
            "App needs access to your files " +
            "so you can run face detection.",
          buttonNeutral: "Ask Me Later",
          buttonNegative: "Cancel",
          buttonPositive: "OK"
        }
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("We can now read files");
      } else {
        console.log("File read permission denied");
      }
      return granted
    } catch (err) {
      console.warn(err);
    }
  };

function FaceDetectionScreen ({navigation}) {
    const [image, setImage] = useState("");
    return (
        <>
            <Text>This is the Face detection screen.</Text>
            <Button title="Select Image to detect faces" onPress={async () => {
                const permission = await requestPermission();
                if (permission === PermissionsAndroid.RESULTS.GRANTED) {
                    const pickedImage = await pickFile();
                    const pickedImageUri = pickedImage.uri
                    setImage(pickedImageUri);
                    processFaces(pickedImageUri).then(() => console.log('Finished processing file.'));
                }
                }}/>
            <Image style={{flex: 1}} source={{ uri: image}}/>
        </>
    );
}

export default FaceDetectionScreen;

Body:
Thanks to this comment on a github issue I was able to update my code and get it to work by updating the first three lines of processFaces as:

async function processFaces(contentUri) {
  const stat = await RNFetchBlob.fs.stat(contentUri)
  const faces = await vision().faceDetectorProcessImage(stat.path);

after importing import RNFetchBlob from 'rn-fetch-blob'.

rn-fetch-blob


问:
Do a for each loop in a folder in flutter
I have a folder with csv files. For now I have to go manually and write manually each file. Is it somehow to get all the files and do a for loop? This is the current code I have and thank you so much!</p>

```<code>static List<Widget> getPlates(String file) {
    List<Widget> listWidgets = [];
    loadAsset('assets/$file.csv').then((dynamic output) {
      List<String> list = output.split('\n');
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
    });

    return listWidgets;
  }

  static Future<String> loadAsset(String path) async {
    return await rootBundle.loadString(path);
  }
</code>```

答:
Are you talking something like this, or even more indepth?

output.split('\n').forEach((String entry) {
  List<String> sublist = entry.split(';');
    listWidgets.add(CardPlate(
    name: sublist[0],
    ingredients: sublist[1],
    price: sublist[2],
  ));
})
```

Body:
I have a folder with csv files. For now I have to go manually and write manually each file. Is it somehow to get all the files and do a for loop? This is the current code I have and thank you so much!

static List<Widget> getPlates(String file) {
    List<Widget> listWidgets = [];
    loadAsset('assets/$file.csv').then((dynamic output) {
      List<String> list = output.split('\n');
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
    });

    return listWidgets;
  }

  static Future<String> loadAsset(String path) async {
    return await rootBundle.loadString(path);
  }


问:
Read file loop is not looping through whole file Python
I am new to Pytho. I am using it to read a large file. To do this, I am using the file object as iterator as specified in the sixth answer here by jyoti das: How can I read large text files in Python, line by line, without loading it into memory?

My code:

```<code>with open(filename, 'r', buffering=100000) as f:
    time_data_count = 0
    for line in f:
        if 'TIME_DATA' in f:
            time_data_count += 1
    if time_data_count > 20:
        print("time_data complete")
    else:
        print("incomplete time_data data")
</code>```

However, my code only reads the first line of the file and then exists the loop so time_data_count stays at 0. Why is this?

I have tried stepping into the code but I don't see why it only stops at first line

答:
You tested if 'TIME_DATA' in f:, which consumes the whole file looking for the string (which it won't find unless the last line is just that string, and isn't newline terminated). That means the file iterator is exhausted when the for loop tries to go to the next line.

You meant to test if 'TIME_DATA' in line:.

Body:
I am new to Pytho. I am using it to read a large file. To do this, I am using the file object as iterator as specified in the sixth answer here by jyoti das: How can I read large text files in Python, line by line, without loading it into memory?

My code:

with open(filename, 'r', buffering=100000) as f:
    time_data_count = 0
    for line in f:
        if 'TIME_DATA' in f:
            time_data_count += 1
    if time_data_count > 20:
        print("time_data complete")
    else:
        print("incomplete time_data data")

However, my code only reads the first line of the file and then exists the loop so time_data_count stays at 0. Why is this?

I have tried stepping into the code but I don't see why it only stops at first line