问:
How to send POSTFIELDS to cURL correctly
I need to send POST data via cURL as shown in the picture.

image with POST data

i have this code

```<code> $data = [
            'action' => 'order_cost',
            'address' => 'http://91.211.117.3:720'
        ];

  $query = http_build_query($data);

   $url = "https://ap4.taxi/api/TaxiAPI.php";
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvJFySHvqeKppEN9W',
            )
        );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        $output = curl_exec($ch);

        curl_close($ch);

        var_dump($output);
</code>```

but I get an error

image with error

I have already tried many options. Postman sends POST normally and I receive the answer.

Please tell me I can not even imagine how this can be done.

答:
```<code>function execute_curl($url, $curlopt = array()){
    $ch = curl_init();
    $strCookie = session_name().'='.session_id().'; path=/';
    session_write_close();
    $default_curlopt = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_COOKIE => $strCookie,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 AlexaToolbar/alxf-1.54 Firefox/3.6.13 GTB7.1"
    );
    $curlopt = $curlopt + $default_curlopt;

    curl_setopt_array($ch, $curlopt);
    $response = curl_exec($ch);
    $errormsg = curl_error($ch);
        $errorCode = curl_errno($ch);
    $results = array();
    if($errormsg)
    {
        $results['status'] = 'error';
        $results['data'] = $errormsg;
        $results['errorcodetxt'] = curl_error_codes($errorCode);
    }
    else
    {
        $results['status'] = 'success';
        $results['data'] = $response;
    }
    curl_close($ch);
    return $results;
}

$curlopt = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => 1);
$curlresponse = execute_curl($url, $curlopt);
</code>```

Body:
I need to send POST data via cURL as shown in the picture.

image with POST data

i have this code

 $data = [
            'action' => 'order_cost',
            'address' => 'http://91.211.117.3:720'
        ];

  $query = http_build_query($data);

   $url = "https://ap4.taxi/api/TaxiAPI.php";
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvJFySHvqeKppEN9W',
            )
        );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        $output = curl_exec($ch);

        curl_close($ch);

        var_dump($output);

but I get an error

image with error

I have already tried many options. Postman sends POST normally and I receive the answer.

Please tell me I can not even imagine how this can be done.


来源: stackexchange

问:
What is the difference between recursion and loops and which one is faster
What is the difference between loops and recursion and which one is more preferred for solving a problem?</p>

答:
Loop is repeated execution of a block of code until the given condition is false.Loop has a linear flow from initial condition to terminating condition.

On the other hand recursion is a method/function being called by itself. Recursion takes place creating stack of task ie, each calling function returns to its caller function after execution.

Loop and recursion aren't exactly alternatives to have preferences, they are used for different type of tasks.

ContentLicense: CC BY-SA 4.0


问:
Unable to block/bypass the user prompt when trying to import self signed CA certificate into Windows Root Truststore using Java KeyStore class
Unable to block/bypass the user prompt when trying to import self signed CA certificate into Windows Root Trust store using Java KeyStore class

I have generated self signed Root CA X509Certificate successfully. Now Since it is a self signed certificate, I want to import it into the Windows Root Trust store (Trusted Root Certification Authority) from Java. While I tried to import the certificate from Java using Keystore class into the Windows-ROOT, the Java code runs but there is a prompt where we need to trust and accept the import by clicking on "YES". How can we prevent or bypass this prompt to accept this certificate import popup and directly import the certificate without any user action?

I tried the same code to import the certificate into Windows-MY "Personal" truststore and I do not get any pop up user prompt. The certificate is imported into Personal truststore from Java successfully. Similarly I want to import the certificate into Windows-ROOT too without any user prompt. Kindly help.

```<code>KeyStore keyStore = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
keyStore.load(null, null);  // Load keystore

keyStore.setCertificateEntry("AliasNameExample", x509Certificate);
keyStore.store(null, null);
</code>```

Using Java code how can we import the self signed CA certificate into Windows Root truststore without getting prompted for user input to accept "Yes/No".

答:
You cannot bypass this prompt dialog. It is embedded in the crypt32.dll library (CertAddCertificateContextToStore function).

The only workaround is to use Local Machine store. However, it requires full administrator permissions.

Body:
Unable to block/bypass the user prompt when trying to import self signed CA certificate into Windows Root Trust store using Java KeyStore class

I have generated self signed Root CA X509Certificate successfully. Now Since it is a self signed certificate, I want to import it into the Windows Root Trust store (Trusted Root Certification Authority) from Java. While I tried to import the certificate from Java using Keystore class into the Windows-ROOT, the Java code runs but there is a prompt where we need to trust and accept the import by clicking on "YES". How can we prevent or bypass this prompt to accept this certificate import popup and directly import the certificate without any user action?

I tried the same code to import the certificate into Windows-MY "Personal" truststore and I do not get any pop up user prompt. The certificate is imported into Personal truststore from Java successfully. Similarly I want to import the certificate into Windows-ROOT too without any user prompt. Kindly help.

KeyStore keyStore = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
keyStore.load(null, null);  // Load keystore

keyStore.setCertificateEntry("AliasNameExample", x509Certificate);
keyStore.store(null, null);

Using Java code how can we import the self signed CA certificate into Windows Root truststore without getting prompted for user input to accept "Yes/No".


问:
Is there a better way to use barcode scanner?
I'm currently using using a BarcodeScanner in UWP App.
To implement it I followed some tutorials on Microsoft docs.

It's working fine but not like I want it to work.

The barcode scanner can only get the value through a DataReceived event.
So when I want to return a value from a BarcodeScanner, it's impossible.

Here I'm registering the scanner :

private static async Task<bool> ClaimScanner()
{
    bool res = false;

    string selector = BarcodeScanner.GetDeviceSelector();
    DeviceInformationCollection deviceCollection = await
    DeviceInformation.FindAllAsync(selector);

    if (_scanner == null)
        _scanner = await BarcodeScanner.FromIdAsync(deviceCollection[0].Id);

    if (_scanner != null)
    {
        if (_claimedBarcodeScanner == null)
            _claimedBarcodeScanner = await _scanner.ClaimScannerAsync();

        if (_claimedBarcodeScanner != null)
        {
            _claimedBarcodeScanner.DataReceived += ClaimedBarcodeScanner_DataReceivedAsync;
            [...]
        }
    }
}
```

<p>And once I'm receiving data it triggers that event :</p>

<pre class="lang-cs prettyprint-override"><code>private static async void ClaimedBarcodeScanner_DataReceivedAsync(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
{
    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        if (CurrentDataContext != null && CurrentDataContext is IScannable)
        {
            IScannable obj = (IScannable)CurrentDataContext;
            obj.NumSerie = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, args.Report.ScanDataLabel);
        }
        else if (CurrentDataContext != null && CurrentDataContext is Poste)
        {
            Poste p = (Poste)CurrentDataContext;
            string code = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, args.Report.ScanDataLabel);
            p.CodePoste = code.Substring(0, 6);
        }
    });
}
</code>```

And as you can see I'm kind of forced to do everything in that method (updating instances of others classes, etc.).

Currently I'm calling the BarcodeScanner like that in the ViewModel :

public void ScanPosteCodeAsync()
{
    BarcodeScannerUtil.ScanBarcodeUtil(CurrentPoste);
}
```

<p>But I have no control of my <code>CurrentPoste</code> instance and what I would do is more like : </p>

<pre class="lang-cs prettyprint-override"><code>public void ScanPosteCodeAsync()
{
    string returnedCode = BarcodeScannerUtil.ScanBarcodeUtil()
    this.CurrentPoste.Code = returnedCode;
}
</code>```

Is there any way to return the value of the scanner in order to use the returned value in my ViewModel ?

答:
Well a similar pattern exists for WPF devs when using MVVM and you need to get/update the models that your view model (VM) is exposing. Perhaps they are in a database. Rather than pollute your nice VM with ugly DB code, a "service" can be passed into the VM. Now, "serivce" doesn't necessarily mean SOA/microservices, maybe its just another class in a different project. The point is you put all your barcode stuff there and when something is received, perhaps it fires an event that your VM listens to or perhaps it just queues it up somewhere ready for your VM to request via the service interface.

I already have all the barcode code in a service class, and there's the problem because I don't want the service class to update my current model. The major issue I have is that I don't know how to do to make my VM listen to the DataReceived event

Well, from what I can see your service is not decoupled from UWP MVVM. For the event, have you considered exposing a secondary event purely for the VM client? I find that works well for me.

Like an event in the VM listening to the data received event ?

Yes, but it doesn't have to be a listending to a physical event type just the concept.  C# events imply that can be more than one subscriber which doesn't really make sense for barcode apps.  There should only be one foreground reader.

Here I shall use Action<string> to pass the barcode from BarcodeScanner to the client, in this case the VM.  By using an Action and moving the barcode processing to the client we keep the BarcodeScanner completely unaware of MVVM.  Windows.ApplicationModel.Core.CoreApplication.MainView was making BarcodeScanner incredibly coupled to stuff it shouldn't care about.

First of all we want to decouple everything so first up is an interface representing the important bits of the barcode scanner:

```<code>public interface IBarcodeScanner
{
    Task<bool> ClaimScannerAsync();
    void Subscribe(Action<string> callback);
    void Unsubscribe();
}
</code>```

With that defined we shall pass it into your VM like so:

```<code>public class MyViewModel
{
    private readonly IBarcodeScanner _scanner;

    /// <summary>
    /// Initializes a new instance of the <see cref="MyViewModel"/> class.
    /// </summary>
    /// <param name="scanner">The scanner, dependency-injected</param>
    public MyViewModel(IBarcodeScanner scanner)
    {
        // all business logic for scanners, just like DB, should be in "service"
        // and not in the VM

        _scanner = scanner;
    }
</code>```

Next we add some command handlers.  Imagine we have a button that when clicked, kicks off   a barcode subscription.  Add the following to the VM:

```<code>public async void OnWidgetExecuted()
{
    await _scanner.ClaimScannerAsync();
    _scanner.Subscribe(OnReceivedBarcode);
}

// Barcode scanner will call this method when a barcode is received
private void OnReceivedBarcode(string barcode)
{
    // update VM accordingly
}
</code>```

Finally, the new look for the BarcodeScanner:

```<code>public class BarcodeScanner : IBarcodeScanner
{
    /// <summary>
    /// The callback, it only makes sense for one client at a time
    /// </summary>
    private static Action<string> _callback; // <--- NEW

    public async Task<bool> ClaimScannerAsync()
    {
        // as per OP's post, not reproduced here
    }

    public void Subscribe(Action<string> callback) // <--- NEW
    {
        // it makes sense to have only one foreground barcode reader client at a time
        _callback = callback;
    }

    public void Unsubscribe() // <--- NEW
    {
        _callback = null;
    }

    private void ClaimedBarcodeScanner_DataReceivedAsync(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
    {
        if (_callback == null) // don't bother with ConvertBinaryToString if we don't need to
            return;

        // all we need do here is convert to a string and pass it to the client

        var barcode = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8,
                                                                args.Report.ScanDataLabel);

        _callback(barcode);

    }
}
</code>```

So what was the problem?

In summary you sort of got yourself caught up in somewhat of a circular dependency problem whereby the VM depended on the BarcodeScanner and the BarcodeScanner depended on presentation APIs - something it shouldn't need to know about.  Even with the good attempt at abstractions you had in the BarcodeScanner with regards to IScannable (sadly not a case with Poste), the scanning layer is making assumptions as to the type of users using it.  It was just to vertical.

With this new approach you could very use it for other types of apps including UWP console apps if you needed to.

Body:
I'm currently using using a BarcodeScanner in UWP App.
To implement it I followed some tutorials on Microsoft docs.

It's working fine but not like I want it to work.

The barcode scanner can only get the value through a DataReceived event.
So when I want to return a value from a BarcodeScanner, it's impossible.

Here I'm registering the scanner :

private static async Task<bool> ClaimScanner()
{
    bool res = false;

    string selector = BarcodeScanner.GetDeviceSelector();
    DeviceInformationCollection deviceCollection = await
    DeviceInformation.FindAllAsync(selector);

    if (_scanner == null)
        _scanner = await BarcodeScanner.FromIdAsync(deviceCollection[0].Id);

    if (_scanner != null)
    {
        if (_claimedBarcodeScanner == null)
            _claimedBarcodeScanner = await _scanner.ClaimScannerAsync();

        if (_claimedBarcodeScanner != null)
        {
            _claimedBarcodeScanner.DataReceived += ClaimedBarcodeScanner_DataReceivedAsync;
            [...]
        }
    }
}

And once I'm receiving data it triggers that event :

private static async void ClaimedBarcodeScanner_DataReceivedAsync(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
{
    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        if (CurrentDataContext != null && CurrentDataContext is IScannable)
        {
            IScannable obj = (IScannable)CurrentDataContext;
            obj.NumSerie = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, args.Report.ScanDataLabel);
        }
        else if (CurrentDataContext != null && CurrentDataContext is Poste)
        {
            Poste p = (Poste)CurrentDataContext;
            string code = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, args.Report.ScanDataLabel);
            p.CodePoste = code.Substring(0, 6);
        }
    });
}

And as you can see I'm kind of forced to do everything in that method (updating instances of others classes, etc.).

Currently I'm calling the BarcodeScanner like that in the ViewModel :

public void ScanPosteCodeAsync()
{
    BarcodeScannerUtil.ScanBarcodeUtil(CurrentPoste);
}

But I have no control of my CurrentPoste instance and what I would do is more like :

public void ScanPosteCodeAsync()
{
    string returnedCode = BarcodeScannerUtil.ScanBarcodeUtil()
    this.CurrentPoste.Code = returnedCode;
}

Is there any way to return the value of the scanner in order to use the returned value in my ViewModel ?

Body:
Well a similar pattern exists for WPF devs when using MVVM and you need to get/update the models that your view model (VM) is exposing. Perhaps they are in a database. Rather than pollute your nice VM with ugly DB code, a "service" can be passed into the VM. Now, "serivce" doesn't necessarily mean SOA/microservices, maybe its just another class in a different project. The point is you put all your barcode stuff there and when something is received, perhaps it fires an event that your VM listens to or perhaps it just queues it up somewhere ready for your VM to request via the service interface.

I already have all the barcode code in a service class, and there's the problem because I don't want the service class to update my current model. The major issue I have is that I don't know how to do to make my VM listen to the DataReceived event

Well, from what I can see your service is not decoupled from UWP MVVM. For the event, have you considered exposing a secondary event purely for the VM client? I find that works well for me.

Like an event in the VM listening to the data received event ?

Yes, but it doesn't have to be a listending to a physical event type just the concept.  C# events imply that can be more than one subscriber which doesn't really make sense for barcode apps.  There should only be one foreground reader.

Here I shall use Action<string> to pass the barcode from BarcodeScanner to the client, in this case the VM.  By using an Action and moving the barcode processing to the client we keep the BarcodeScanner completely unaware of MVVM.  Windows.ApplicationModel.Core.CoreApplication.MainView was making BarcodeScanner incredibly coupled to stuff it shouldn't care about.

First of all we want to decouple everything so first up is an interface representing the important bits of the barcode scanner:

public interface IBarcodeScanner
{
    Task<bool> ClaimScannerAsync();
    void Subscribe(Action<string> callback);
    void Unsubscribe();
}

With that defined we shall pass it into your VM like so:

public class MyViewModel
{
    private readonly IBarcodeScanner _scanner;

    /// <summary>
    /// Initializes a new instance of the <see cref="MyViewModel"/> class.
    /// </summary>
    /// <param name="scanner">The scanner, dependency-injected</param>
    public MyViewModel(IBarcodeScanner scanner)
    {
        // all business logic for scanners, just like DB, should be in "service"
        // and not in the VM

        _scanner = scanner;
    }

Next we add some command handlers.  Imagine we have a button that when clicked, kicks off   a barcode subscription.  Add the following to the VM:

public async void OnWidgetExecuted()
{
    await _scanner.ClaimScannerAsync();
    _scanner.Subscribe(OnReceivedBarcode);
}

// Barcode scanner will call this method when a barcode is received
private void OnReceivedBarcode(string barcode)
{
    // update VM accordingly
}

Finally, the new look for the BarcodeScanner:

public class BarcodeScanner : IBarcodeScanner
{
    /// <summary>
    /// The callback, it only makes sense for one client at a time
    /// </summary>
    private static Action<string> _callback; // <--- NEW

    public async Task<bool> ClaimScannerAsync()
    {
        // as per OP's post, not reproduced here
    }

    public void Subscribe(Action<string> callback) // <--- NEW
    {
        // it makes sense to have only one foreground barcode reader client at a time
        _callback = callback;
    }

    public void Unsubscribe() // <--- NEW
    {
        _callback = null;
    }

    private void ClaimedBarcodeScanner_DataReceivedAsync(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
    {
        if (_callback == null) // don't bother with ConvertBinaryToString if we don't need to
            return;

        // all we need do here is convert to a string and pass it to the client

        var barcode = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8,
                                                                args.Report.ScanDataLabel);

        _callback(barcode);

    }
}

So what was the problem?

In summary you sort of got yourself caught up in somewhat of a circular dependency problem whereby the VM depended on the BarcodeScanner and the BarcodeScanner depended on presentation APIs - something it shouldn't need to know about.  Even with the good attempt at abstractions you had in the BarcodeScanner with regards to IScannable (sadly not a case with Poste), the scanning layer is making assumptions as to the type of users using it.  It was just to vertical.

With this new approach you could very use it for other types of apps including UWP console apps if you needed to.


问:
How to extend sorting order of Team Members
I'm using Business Lounge theme by RT themes with Elementor.

Wordpress version is current (5.2.1)

On the team page (Demo: https://businesslounge-demo.rtthemes.com/our-team/) there is a list of cards of team members. I want to change the order of the team members to an option that is not currently selectable.

The team member list is done with a shortcode [staff_box]

In Elementor edit mode I looks like this:

Edit:

The edit form is defined in

wp-content/plugins/businesslounge-extensions/inc/elementor-addons/staff.php

```<code><?php
namespace Elementor;
// ...
class Widget_RT_Staff extends Widget_Base {
  // ...
  protected function _register_controls() {
    // ...
    $this->add_control(
      'list_orderby',
        [
          'label'     => esc_html_x( 'List Order By', 'Admin Panel','businesslounge' ),
          'description' => esc_html_x('Sorts the posts by this parameter', 'Admin Panel','businesslounge' ),
          'type'      =>  Controls_Manager::SELECT,
          'default'    =>  "date",
          "options"    => array(
            'date' => esc_html_x('Date',"Admin Panel","businesslounge"),
            'author' => esc_html_x('Author',"Admin Panel","businesslounge"),
            'title' => esc_html_x('Title',"Admin Panel","businesslounge"),
            'modified' => esc_html_x('Modified',"Admin Panel","businesslounge"),
            'ID' => esc_html_x('ID',"Admin Panel","businesslounge"),
            'rand' => esc_html_x('Randomized',"Admin Panel","businesslounge"),
          )
        ]
      );
      // ...
  }
  // ...
}

Plugin::instance()->widgets_manager->register_widget_type( new Widget_RT_Staff() );
</code>```

The edit form is defined in `wp-content/plugins/businesslounge-extensions/inc/editor/staff_box.php`

like so

```<code><?php
vc_map(
    array(
        'base'        => 'staff_box',
        'name'        => _x( 'Team', 'Admin Panel','businesslounge' ),
        'icon'        => 'rt_theme rt_team',
        'category'    => array(_x( 'Content', 'Admin Panel','businesslounge' ), _x( 'Theme Addons', 'Admin Panel','businesslounge' )),
        'description' => _x( 'Displays team members', 'Admin Panel','businesslounge' ),
        'params'      => array(
// ...
          array(
            'param_name'  => 'list_orderby',
            'heading'     => _x( 'List Order By', 'Admin Panel','businesslounge' ),
            "description" => _x("Sorts the posts by this parameter",'Admin Panel','businesslounge'),
            'type'        => 'dropdown',
            "value"       => array(
                                _x('Date','Admin Panel','businesslounge') => 'date',
                                _x('Author','Admin Panel','businesslounge') => 'author',
                                _x('Title','Admin Panel','businesslounge') => 'title',
                                _x('Modified','Admin Panel','businesslounge') => 'modified',
                                _x('ID','Admin Panel','businesslounge') => 'ID',
                                _x('Randomized','Admin Panel','businesslounge') => 'rand',
                            ),
            'save_always' => true
        ),
// ...
</code>```

The output is defined in

wp-content/plugins/businesslounge-extensions/inc/shortcodes/staff_box.php

like so:

```<code><?php
function rt_staff( $atts, $content = null ) {
// ...

    //defaults
    extract(shortcode_atts(array(
        "id"           => 'staff-'.rand(100000, 1000000),
        "class"        => "",
        "list_layout"  => "1/1",
        "list_orderby" => "date",
        "list_order"   => "DESC",
        "ids"          => array(),
        "box_style"    => ""
    ), $atts));

// ...

    //general query
    $args=array(
        'post_status'    => 'publish',
        'post_type'      => 'staff',
        'orderby'        => $list_orderby,
        'order'          => $list_order,
        'showposts'      => 1000
    );
// ...
    $theQuery = query_posts($args);
// ...
</code>```

What I want to do:
Add an option 'post_name' to the select box so that I can sort the team by a different field. I want to add
'Post name' => 'post_name',

How can I do this without changing the original source code?

I already have the child theme of business_lounge theme activated.

Do I need a custom extension for this?

答:
You'd have to modify the original code.
You can't override the function unless the author applied a filter to the value returned, or used an action.

As gael notes in his answer, you can soften the blow of losing changes on updates by copying the original code into your child theme's functions.php then renaming the function - for e.g. to my_rt_staff() before adding in your modifications.

You would however still need to call the my_rt_staff() in the plugin instead of rt_stuff and you would have to make this change whenever the plugin was updated, but you wouldn't lose your code.

(Perhaps you could change the "list_orderby" => "date" in the default shortcode attributes to "list_orderby" => "post_name", as default in your modified my_rt_staff() method so it orders by name as default instead of date)

However, this does not help much in your specific circumstance, as the ideal modification you need to make is to the control itself, on the _register_controls() method in the Widget_RT_Staff class. You can override this by extending Widget_RT_Staff but you would still need to call your new class which results in you modifying the plugin code.

Without seeing how the Widget_RT_Staff class affects the shortocde, I can't be certain this would work, but based on the rt_staff() method, if you use the shortcode as [staff_box orderby="post_name"] you may get your intended result without having to touch any code.

Body:
I'm using Business Lounge theme by RT themes with Elementor.

Wordpress version is current (5.2.1)

On the team page (Demo: https://businesslounge-demo.rtthemes.com/our-team/) there is a list of cards of team members. I want to change the order of the team members to an option that is not currently selectable.

The team member list is done with a shortcode [staff_box]

In Elementor edit mode I looks like this:

Edit:

The edit form is defined in

wp-content/plugins/businesslounge-extensions/inc/elementor-addons/staff.php

<?php
namespace Elementor;
// ...
class Widget_RT_Staff extends Widget_Base {
  // ...
  protected function _register_controls() {
    // ...
    $this->add_control(
      'list_orderby',
        [
          'label'     => esc_html_x( 'List Order By', 'Admin Panel','businesslounge' ),
          'description' => esc_html_x('Sorts the posts by this parameter', 'Admin Panel','businesslounge' ),
          'type'      =>  Controls_Manager::SELECT,
          'default'    =>  "date",
          "options"    => array(
            'date' => esc_html_x('Date',"Admin Panel","businesslounge"),
            'author' => esc_html_x('Author',"Admin Panel","businesslounge"),
            'title' => esc_html_x('Title',"Admin Panel","businesslounge"),
            'modified' => esc_html_x('Modified',"Admin Panel","businesslounge"),
            'ID' => esc_html_x('ID',"Admin Panel","businesslounge"),
            'rand' => esc_html_x('Randomized',"Admin Panel","businesslounge"),
          )
        ]
      );
      // ...
  }
  // ...
}

Plugin::instance()->widgets_manager->register_widget_type( new Widget_RT_Staff() );

The edit form is defined in `wp-content/plugins/businesslounge-extensions/inc/editor/staff_box.php`

like so

<?php
vc_map(
    array(
        'base'        => 'staff_box',
        'name'        => _x( 'Team', 'Admin Panel','businesslounge' ),
        'icon'        => 'rt_theme rt_team',
        'category'    => array(_x( 'Content', 'Admin Panel','businesslounge' ), _x( 'Theme Addons', 'Admin Panel','businesslounge' )),
        'description' => _x( 'Displays team members', 'Admin Panel','businesslounge' ),
        'params'      => array(
// ...
          array(
            'param_name'  => 'list_orderby',
            'heading'     => _x( 'List Order By', 'Admin Panel','businesslounge' ),
            "description" => _x("Sorts the posts by this parameter",'Admin Panel','businesslounge'),
            'type'        => 'dropdown',
            "value"       => array(
                                _x('Date','Admin Panel','businesslounge') => 'date',
                                _x('Author','Admin Panel','businesslounge') => 'author',
                                _x('Title','Admin Panel','businesslounge') => 'title',
                                _x('Modified','Admin Panel','businesslounge') => 'modified',
                                _x('ID','Admin Panel','businesslounge') => 'ID',
                                _x('Randomized','Admin Panel','businesslounge') => 'rand',
                            ),
            'save_always' => true
        ),
// ...

The output is defined in

wp-content/plugins/businesslounge-extensions/inc/shortcodes/staff_box.php

like so:

<?php
function rt_staff( $atts, $content = null ) {
// ...

    //defaults
    extract(shortcode_atts(array(
        "id"           => 'staff-'.rand(100000, 1000000),
        "class"        => "",
        "list_layout"  => "1/1",
        "list_orderby" => "date",
        "list_order"   => "DESC",
        "ids"          => array(),
        "box_style"    => ""
    ), $atts));

// ...

    //general query
    $args=array(
        'post_status'    => 'publish',
        'post_type'      => 'staff',
        'orderby'        => $list_orderby,
        'order'          => $list_order,
        'showposts'      => 1000
    );
// ...
    $theQuery = query_posts($args);
// ...

What I want to do:
Add an option 'post_name' to the select box so that I can sort the team by a different field. I want to add
'Post name' => 'post_name',

How can I do this without changing the original source code?

I already have the child theme of business_lounge theme activated.

Do I need a custom extension for this?


问:
Optimizing a piecewise linear regression
I have written a function that, given parameters, can apply a piecewise linear fit, with arbitrarily many piecewise sections, to some data.

I am trying to fit the function to my data using scipy.optimize.curve_fit, but I am receiving an "OptimizeWarning: Covariance of the parameters could not be estimated" error. I believe this may be because of the nested lambda functions I am using to define the piecewise sections.

Is there an easy way to tweak my code to get round this, or a different scipy optimisation function that might be more suitable?

```<code>#The piecewise function
def piecewise_linear(x, *params):

    N=len(params)/2

    if N.is_integer():N=int(N)
    else:raise(ValueError())

    c=params[0]
    xbounds=params[1:N]
    grads=params[N:]

    #First we define our conditions, which are true if x is a member of a given
    #bin.
    conditions=[]
    #first and last bins are a special case:
    cond0=lambda x: x<xbounds[0]
    condl=lambda x: x>=xbounds[-1]
    conditions.append(cond0(x))

    for i in range(len(xbounds)-1):
        cond=lambda x : (x >= xbounds[i]) & (x < xbounds[i+1])
        conditions.append(cond(x))

    conditions.append(condl(x))

    #Next we define our linear regression function for each bin. The offset
    #for each bin depends on where the previous bin ends, so we define
    #the regression functions recursively:

    functions=[]
    func0 = lambda x: grads[0]*x +c

    functions.append(func0)

    for i in range(len(grads)-1):
        func = (lambda j: lambda x: grads[j+1]*(x-xbounds[j])\
               +functions[j](xbounds[j]))(i)

        functions.append(func)

    return np.piecewise(x,conditions,functions)
#Some data

x=np.arange(100)
y=np.array([*np.arange(0,19,1),*np.arange(20,59,2),\
*np.arange(60,20,-1),*np.arange(21,42,1)]) + np.random.randn(100)

#A first guess of parameters
cguess=0
boundguess=[20,30,50]
gradguess=[1,1,1,1]
p0=[cguess,*boundguess,*gradguess]

fit=scipy.optimize.curve_fit(piecewise_linear,x,y,p0=p0)
</code>```

答:
Here is example code that fits two straight lines to a curved data set with a breakpoint, where the line parameters and breakpoint are all fitted. This example uses scipy's Differential Evolution genetic algorithm to determine initial parameter estimates for the regression. That module uses the Latin Hypercube algorithm to ensure a thorough search of parameter space, which requires bounds within which to search. In this example those search bounds are derived from the data itself. Note that it is much easier to find ranges for the initial parameter estimates than to give specific values.

```<code>import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings

xData = numpy.array([19.1647, 18.0189, 16.9550, 15.7683, 14.7044, 13.6269, 12.6040, 11.4309, 10.2987, 9.23465, 8.18440, 7.89789, 7.62498, 7.36571, 7.01106, 6.71094, 6.46548, 6.27436, 6.16543, 6.05569, 5.91904, 5.78247, 5.53661, 4.85425, 4.29468, 3.74888, 3.16206, 2.58882, 1.93371, 1.52426, 1.14211, 0.719035, 0.377708, 0.0226971, -0.223181, -0.537231, -0.878491, -1.27484, -1.45266, -1.57583, -1.61717])
yData = numpy.array([0.644557, 0.641059, 0.637555, 0.634059, 0.634135, 0.631825, 0.631899, 0.627209, 0.622516, 0.617818, 0.616103, 0.613736, 0.610175, 0.606613, 0.605445, 0.603676, 0.604887, 0.600127, 0.604909, 0.588207, 0.581056, 0.576292, 0.566761, 0.555472, 0.545367, 0.538842, 0.529336, 0.518635, 0.506747, 0.499018, 0.491885, 0.484754, 0.475230, 0.464514, 0.454387, 0.444861, 0.437128, 0.415076, 0.401363, 0.390034, 0.378698])

def func(xArray, breakpoint, slopeA, offsetA, slopeB, offsetB):
    returnArray = []
    for x in xArray:
        if x < breakpoint:
            returnArray.append(slopeA * x + offsetA)
        else:
            returnArray.append(slopeB * x + offsetB)
    return returnArray

# function for genetic algorithm to minimize (sum of squared error)
def sumOfSquaredError(parameterTuple):
    warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
    val = func(xData, *parameterTuple)
    return numpy.sum((yData - val) ** 2.0)

def generate_Initial_Parameters():
    # min and max used for bounds
    maxX = max(xData)
    minX = min(xData)
    maxY = max(yData)
    minY = min(yData)
    slope = 10.0 * (maxY - minY) / (maxX - minX) # times 10 for safety margin

    parameterBounds = []
    parameterBounds.append([minX, maxX]) # search bounds for breakpoint
    parameterBounds.append([-slope, slope]) # search bounds for slopeA
    parameterBounds.append([minY, maxY]) # search bounds for offsetA
    parameterBounds.append([-slope, slope]) # search bounds for slopeB
    parameterBounds.append([minY, maxY]) # search bounds for offsetB

    result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
    return result.x

# by default, differential_evolution completes by calling curve_fit() using parameter bounds
geneticParameters = generate_Initial_Parameters()

# call curve_fit without passing bounds from genetic algorithm
fittedParameters, pcov = curve_fit(func, xData, yData, geneticParameters)
print('Parameters:', fittedParameters)
print()

modelPredictions = func(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print()
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()

##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)
</code>```

Body:
I have written a function that, given parameters, can apply a piecewise linear fit, with arbitrarily many piecewise sections, to some data.

I am trying to fit the function to my data using scipy.optimize.curve_fit, but I am receiving an "OptimizeWarning: Covariance of the parameters could not be estimated" error. I believe this may be because of the nested lambda functions I am using to define the piecewise sections.

Is there an easy way to tweak my code to get round this, or a different scipy optimisation function that might be more suitable?

#The piecewise function
def piecewise_linear(x, *params):

    N=len(params)/2

    if N.is_integer():N=int(N)
    else:raise(ValueError())

    c=params[0]
    xbounds=params[1:N]
    grads=params[N:]

    #First we define our conditions, which are true if x is a member of a given
    #bin.
    conditions=[]
    #first and last bins are a special case:
    cond0=lambda x: x<xbounds[0]
    condl=lambda x: x>=xbounds[-1]
    conditions.append(cond0(x))

    for i in range(len(xbounds)-1):
        cond=lambda x : (x >= xbounds[i]) & (x < xbounds[i+1])
        conditions.append(cond(x))

    conditions.append(condl(x))

    #Next we define our linear regression function for each bin. The offset
    #for each bin depends on where the previous bin ends, so we define
    #the regression functions recursively:

    functions=[]
    func0 = lambda x: grads[0]*x +c

    functions.append(func0)

    for i in range(len(grads)-1):
        func = (lambda j: lambda x: grads[j+1]*(x-xbounds[j])\
               +functions[j](xbounds[j]))(i)

        functions.append(func)

    return np.piecewise(x,conditions,functions)
#Some data

x=np.arange(100)
y=np.array([*np.arange(0,19,1),*np.arange(20,59,2),\
*np.arange(60,20,-1),*np.arange(21,42,1)]) + np.random.randn(100)

#A first guess of parameters
cguess=0
boundguess=[20,30,50]
gradguess=[1,1,1,1]
p0=[cguess,*boundguess,*gradguess]

fit=scipy.optimize.curve_fit(piecewise_linear,x,y,p0=p0)

Body:
Here is example code that fits two straight lines to a curved data set with a breakpoint, where the line parameters and breakpoint are all fitted. This example uses scipy's Differential Evolution genetic algorithm to determine initial parameter estimates for the regression. That module uses the Latin Hypercube algorithm to ensure a thorough search of parameter space, which requires bounds within which to search. In this example those search bounds are derived from the data itself. Note that it is much easier to find ranges for the initial parameter estimates than to give specific values.

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings

xData = numpy.array([19.1647, 18.0189, 16.9550, 15.7683, 14.7044, 13.6269, 12.6040, 11.4309, 10.2987, 9.23465, 8.18440, 7.89789, 7.62498, 7.36571, 7.01106, 6.71094, 6.46548, 6.27436, 6.16543, 6.05569, 5.91904, 5.78247, 5.53661, 4.85425, 4.29468, 3.74888, 3.16206, 2.58882, 1.93371, 1.52426, 1.14211, 0.719035, 0.377708, 0.0226971, -0.223181, -0.537231, -0.878491, -1.27484, -1.45266, -1.57583, -1.61717])
yData = numpy.array([0.644557, 0.641059, 0.637555, 0.634059, 0.634135, 0.631825, 0.631899, 0.627209, 0.622516, 0.617818, 0.616103, 0.613736, 0.610175, 0.606613, 0.605445, 0.603676, 0.604887, 0.600127, 0.604909, 0.588207, 0.581056, 0.576292, 0.566761, 0.555472, 0.545367, 0.538842, 0.529336, 0.518635, 0.506747, 0.499018, 0.491885, 0.484754, 0.475230, 0.464514, 0.454387, 0.444861, 0.437128, 0.415076, 0.401363, 0.390034, 0.378698])

def func(xArray, breakpoint, slopeA, offsetA, slopeB, offsetB):
    returnArray = []
    for x in xArray:
        if x < breakpoint:
            returnArray.append(slopeA * x + offsetA)
        else:
            returnArray.append(slopeB * x + offsetB)
    return returnArray

# function for genetic algorithm to minimize (sum of squared error)
def sumOfSquaredError(parameterTuple):
    warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
    val = func(xData, *parameterTuple)
    return numpy.sum((yData - val) ** 2.0)

def generate_Initial_Parameters():
    # min and max used for bounds
    maxX = max(xData)
    minX = min(xData)
    maxY = max(yData)
    minY = min(yData)
    slope = 10.0 * (maxY - minY) / (maxX - minX) # times 10 for safety margin

    parameterBounds = []
    parameterBounds.append([minX, maxX]) # search bounds for breakpoint
    parameterBounds.append([-slope, slope]) # search bounds for slopeA
    parameterBounds.append([minY, maxY]) # search bounds for offsetA
    parameterBounds.append([-slope, slope]) # search bounds for slopeB
    parameterBounds.append([minY, maxY]) # search bounds for offsetB

    result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
    return result.x

# by default, differential_evolution completes by calling curve_fit() using parameter bounds
geneticParameters = generate_Initial_Parameters()

# call curve_fit without passing bounds from genetic algorithm
fittedParameters, pcov = curve_fit(func, xData, yData, geneticParameters)
print('Parameters:', fittedParameters)
print()

modelPredictions = func(xData, *fittedParameters)

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print()
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()

##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)


问:
Can i get data from multiple tables without jointables or foreign keys at them
I'm trying to get a single data from two tables of database. These tables doesn't have foreign keys and no jointables too. I'm using spring-data to retrieve required data for first data set.

I have two data sets that have a common String value, and want to retrieve data from both tables not using jointables or foreign keys, retrieving data from the first data set.

I'm using simple DataRepository interface

```<code>import org.springframework.data.jpa.repository.JpaRepository;

public interface DataRepository extends JpaRepository<FirstData, Long> {

    DataService getById(Long id);

}
</code>```

FirstData entity:

```<code>@Data
@Entity
@Table(schema = "someschema", name = "firstdata")
public class FirstData {

    @Id
    @Column(name = "id")
    private Long uuid;

    @Column(name = "name")
    private String name;

    @Column(name = "type")
    private String type;

}
</code>```

SecondData entity:

```<code>@Data
@Entity
@Table(schema = "someschema", name = "seconddata")
public class SecondData {

    @Id
    @Column(name = "id")
    private Long uuid;

    @Column(name = "type")
    private String type;

    @Column(name = "value")
    private String value;

}
</code>```

and DataService

```<code>@Service
public class DataService {

    private DataRepository dataRepository;

    public DataService(DataRepository dataRepository){
        this.dataRepository = dataRepository;
    }

    public void getBothFirstAndSecondData() {

        List<FirstData> firstDataSet = dataRepository.findAll();
    }
}
</code>```

I need to get data from both tables, but don't want to modify table structure,  make jointable or add foreign keys. Also, i don't want to add another repository write code arount second data set. I need just to have a "value" from second data set at first data set result. What is the simpliest approach for solving such data retrieveing?

答:
sql query the above problem can be:</p>

```<code>select value from seconddata where id IN (select id from firstdata)
</code>```

Body:
I'm trying to get a single data from two tables of database. These tables doesn't have foreign keys and no jointables too. I'm using spring-data to retrieve required data for first data set.

I have two data sets that have a common String value, and want to retrieve data from both tables not using jointables or foreign keys, retrieving data from the first data set.

I'm using simple DataRepository interface

import org.springframework.data.jpa.repository.JpaRepository;

public interface DataRepository extends JpaRepository<FirstData, Long> {

    DataService getById(Long id);

}

FirstData entity:

@Data
@Entity
@Table(schema = "someschema", name = "firstdata")
public class FirstData {

    @Id
    @Column(name = "id")
    private Long uuid;

    @Column(name = "name")
    private String name;

    @Column(name = "type")
    private String type;

}

SecondData entity:

@Data
@Entity
@Table(schema = "someschema", name = "seconddata")
public class SecondData {

    @Id
    @Column(name = "id")
    private Long uuid;

    @Column(name = "type")
    private String type;

    @Column(name = "value")
    private String value;

}

and DataService

@Service
public class DataService {

    private DataRepository dataRepository;

    public DataService(DataRepository dataRepository){
        this.dataRepository = dataRepository;
    }

    public void getBothFirstAndSecondData() {

        List<FirstData> firstDataSet = dataRepository.findAll();
    }
}

I need to get data from both tables, but don't want to modify table structure,  make jointable or add foreign keys. Also, i don't want to add another repository write code arount second data set. I need just to have a "value" from second data set at first data set result. What is the simpliest approach for solving such data retrieveing?

Body:
sql query the above problem can be:

select value from seconddata where id IN (select id from firstdata)


问:
Change image orientation before upload
I am using this answer to display the uploaded image in an img tag and also I am able to change the orientation of the image using the loadImage() mentioned in the answer.

My problem is that I am not able to replace the re-oriented image with the uploaded image in the input tag.

The image is not saved unless the form is submitted. So I am not able to do this in AJAX also. Any help is much appreciated.

$('img#image-pre').click(function(e) {
  var loadingImage = loadImage($('input#uploadform-file')[0].files[0], function(img) {
    var dataURI = img.toDataURL();
    document.getElementById("image-pre").src = img.toDataURL();
    $('input#uploadform-file')[0].files[0] = function(dataURI) { // create the new blob from the changed image.
      var binary = atob(dataURI.split(',')[1]);
      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {
        type: mimeString
      });
    };
  }, {
    orientation: or,
    maxWidth: 500,
    maxHeight: 300,
    minWidth: 100,
    minHeight: 50,
  });
  or = or <= 8 ? or + 1 : 1;
  console.log($('input#uploadform-file')[0].files[0]);
});
```

答:
You may want to look at this:
https://stackoverflow.com/a/20285053/1990724

You can parse the image to base64 string and then using ajax you could post the base64 string to the server. This could be done after you had the user orientate the image the correct way.

Title: Change image orientation before upload


问:
Is there a way, in bash, to search a list of integers for consecutive sequences and remove all but the last numbers in those sequences?
My question is, given a list of integers, is it possible in bash to a) find all the sequences of consecutive numbers, then b) remove all but the last numbers in those sequences?

For example, given this list and assuming that the numbers are stored, one per line, in a .txt file,

```<code>001
002
003
005
007
010
011
012
</code>```

is there a program/set of programs that would produce output

```<code>003
005
007
012
</code>```

and if so, how? Thank you for your time.

EDIT:

Here's what I have so far:

```<code>#!/bin/bash

cat file.txt | numinterval >> interval.txt

integer=''
while read -u 3 interval
do
    if [[ "$interval" -ne "1" ]]
    then echo "$integer" >> desequenced.txt
    else read -u 4 integer
    fi
done 3< interval.txt 4< file.txt
</code>```

The central idea is to run the sorted list of integers through numinterval, then to check if the numinterval list has any ones. If it does, move on to the next integer. If not, print the corresponding integer to a file.

```<code>
10508
10861
10862
10906
10906
10909
10909
10950
10950
11179
11181
11182
11325
11325
11341
11341
11428
11428

</code>```

Here is the output. Obviously something has gone wrong, as not only are consecutives not removed, there is a huge amount of whitespace after the list has ended.

Any help is appreciated.

答:
Try this Shellcheck-clean pure Bash code:

```<code>#! /bin/bash -p

prev=
while read -r curr || [[ -n $curr ]] ; do
    [[ -n $prev ]] && (( 10#$curr != (10#$prev+1) )) && printf '%s\n' "$prev"
    prev=$curr
done <file.txt
[[ -n $prev ]] && printf '%s\n' "$prev"
</code>```

|| [[ -n $curr ]] is to enable the code to work even if the last line in the input file is not terminated.  See Read a file line by line assigning the value to a variable.

The 10# prefix in 10#$curr and 10#$prev forces the variable contents to be treated as decimal numbers.  Otherwise 010 would be treated as decimal 8 instead of decimal 10.

No checks are done to ensure that the input lines contain (only) decimal numbers.  A real program should do such checks.

Since no checks are done on the validity of the input, the code uses 'printf' instead of 'echo' to reduce the possibilities for confusion if the input is bad.  See Why is printf better than echo?.

Body:
My question is, given a list of integers, is it possible in bash to a) find all the sequences of consecutive numbers, then b) remove all but the last numbers in those sequences?

For example, given this list and assuming that the numbers are stored, one per line, in a .txt file,

001
002
003
005
007
010
011
012

is there a program/set of programs that would produce output

003
005
007
012

and if so, how? Thank you for your time.

EDIT:

Here's what I have so far:

#!/bin/bash

cat file.txt | numinterval >> interval.txt

integer=''
while read -u 3 interval
do
    if [[ "$interval" -ne "1" ]]
    then echo "$integer" >> desequenced.txt
    else read -u 4 integer
    fi
done 3< interval.txt 4< file.txt

The central idea is to run the sorted list of integers through numinterval, then to check if the numinterval list has any ones. If it does, move on to the next integer. If not, print the corresponding integer to a file.

10508
10861
10862
10906
10906
10909
10909
10950
10950
11179
11181
11182
11325
11325
11341
11341
11428
11428

Here is the output. Obviously something has gone wrong, as not only are consecutives not removed, there is a huge amount of whitespace after the list has ended.

Any help is appreciated.

Body:
Try this Shellcheck-clean pure Bash code:

#! /bin/bash -p

prev=
while read -r curr || [[ -n $curr ]] ; do
    [[ -n $prev ]] && (( 10#$curr != (10#$prev+1) )) && printf '%s\n' "$prev"
    prev=$curr
done <file.txt
[[ -n $prev ]] && printf '%s\n' "$prev"

|| [[ -n $curr ]] is to enable the code to work even if the last line in the input file is not terminated.  See Read a file line by line assigning the value to a variable.

The 10# prefix in 10#$curr and 10#$prev forces the variable contents to be treated as decimal numbers.  Otherwise 010 would be treated as decimal 8 instead of decimal 10.

No checks are done to ensure that the input lines contain (only) decimal numbers.  A real program should do such checks.

Since no checks are done on the validity of the input, the code uses 'printf' instead of 'echo' to reduce the possibilities for confusion if the input is bad.  See Why is printf better than echo?.


问:
Full humanized durations in moment.js
I tried this in moment.js

```<code>moment.duration(375,'days').humanize()
</code>```

and get "a year" as answer, but I would expect "a year and 10 days". Is there a way in moment.js to get the full humanized value?

答:
One of the solutions:

```<code>function getCountdown() {
  // diff in seconds, comes through function's params
  const diff = 60*60*24*4 + 60*60*22 + 60*35 + 5;
  const MINUTE = 60;
  const HOUR = MINUTE * 60;
  const DAY = HOUR * 24;

  const days = Math.floor(diff / DAY);
  const hDiff = diff % DAY;
  const hours = Math.floor(hDiff / HOUR);
  const mDiff = hDiff % HOUR;
  const minutes = Math.floor(mDiff / MINUTE);
  const seconds = mDiff % MINUTE;

  return [days, hours, minutes, seconds]
    .map(v => (''+v)[1] ? ''+v : '0'+v)
}

output: ["04", "22", "35", "05"]
</code>```

I needed it up to days only, but can be easily extended to weeks.
Doesn't make sense with months since diff says nothing about start date.
Having a period split to parts, adding "days"/"hours"/... is obvious.

ContentLicense: CC BY-SA 3.0

Title: Full humanized durations in moment.js

Body:
I tried this in moment.js

moment.duration(375,'days').humanize()

and get "a year" as answer, but I would expect "a year and 10 days". Is there a way in moment.js to get the full humanized value?

Body:
One of the solutions:

function getCountdown() {
  // diff in seconds, comes through function's params
  const diff = 60*60*24*4 + 60*60*22 + 60*35 + 5;
  const MINUTE = 60;
  const HOUR = MINUTE * 60;
  const DAY = HOUR * 24;

  const days = Math.floor(diff / DAY);
  const hDiff = diff % DAY;
  const hours = Math.floor(hDiff / HOUR);
  const mDiff = hDiff % HOUR;
  const minutes = Math.floor(mDiff / MINUTE);
  const seconds = mDiff % MINUTE;

  return [days, hours, minutes, seconds]
    .map(v => (''+v)[1] ? ''+v : '0'+v)
}

output: ["04", "22", "35", "05"]

I needed it up to days only, but can be easily extended to weeks.
Doesn't make sense with months since diff says nothing about start date.
Having a period split to parts, adding "days"/"hours"/... is obvious.


问:
JQuery active class a tag don't execute
I am trying to create a navbar with a dynamic active menu using jquery.
I have already the code and it is working except on 1 things

```<code>$(document).ready(function(){
          $('ul li a').click(function(){
            $('li a').removeClass("active");
            $(this).addClass("active");
            return false;
          });
});

 <li class="nav-item">
     <a class="nav-link" href="index.php?page=logout">Logout</a>
 </li>
</code>```

The above code work and I get a active menu when I click on a  tag.
Only the  tag won't work. And when I commend out the return false the  tag is working but I don't get a active class.
I also tried e.preventDefault() but then I prevent my a tag to execute. I know that return false in preventDefault() the function has to stop executing on my a tag. But how can I work around that ?

I hope that I get my active class dynamic and my a tag is still executing.

答:
How about this one liner?

```<code><script>
    $(function () {
        $("a[href='"+window.location.pathname+"']").prop("href", "#")
        .addClass("active");
    });
</script>
</code>```

You don't have to wait for the click event anymore.
Above code will try to find the url in the dom and will add active class and disables the url routing by replacing its actual url to #.

Place the above code before the ending body tag and ... voila.

Title: JQuery active class a tag don't execute

Body:
I am trying to create a navbar with a dynamic active menu using jquery.
I have already the code and it is working except on 1 things

$(document).ready(function(){
          $('ul li a').click(function(){
            $('li a').removeClass("active");
            $(this).addClass("active");
            return false;
          });
});

     Logout

The above code work and I get a active menu when I click on a  tag.
Only the  tag won't work. And when I commend out the return false the  tag is working but I don't get a active class.
I also tried e.preventDefault() but then I prevent my a tag to execute. I know that return false in preventDefault() the function has to stop executing on my a tag. But how can I work around that ?

I hope that I get my active class dynamic and my a tag is still executing.

Body:
How about this one liner?

<script>
    $(function () {
        $("a[href='"+window.location.pathname+"']").prop("href", "#")
        .addClass("active");
    });
</script>

You don't have to wait for the click event anymore.
Above code will try to find the url in the dom and will add active class and disables the url routing by replacing its actual url to #.

Place the above code before the ending body tag and ... voila.


问:
TimeSpan to friendly string library (C#)
Does anyone know of a good library (or code snippet) for converting a TimeSpan object to a "friendly" string such as:

Two years, three months and four days

One week and two days

(It's for a document expiry system, where the expiry could be anything from a few days to several decades)

Just to clarify, say I had a TimeSpan with 7 days, that should print "1 week", 14 days "2 weeks", 366 days "1 year and 1 day", etc etc.

答:
Here is my solution to this. It is based on other answers in this thread, with added support for year and month as that was requested in the original question (and was what I needed).

As for the discussion whether or not this makes sense I would say that there are cases where it does so. In my case we wanted to show the duration of agreements that in some cases are just a few days, and in other cases several years.

Tests;

```<code>[Test]
public void ToFriendlyDuration_produces_expected_result()
{
    new DateTime(2019, 5, 28).ToFriendlyDuration(null).Should().Be("Until further notice");
    new DateTime(2019, 5, 28).ToFriendlyDuration(new DateTime(2020, 5, 28)).Should().Be("1 year");
    new DateTime(2019, 5, 28).ToFriendlyDuration(new DateTime(2021, 5, 28)).Should().Be("2 years");
    new DateTime(2019, 5, 28).ToFriendlyDuration(new DateTime(2021, 8, 28)).Should().Be("2 years, 3 months");
    new DateTime(2019, 5, 28).ToFriendlyDuration(new DateTime(2019, 8, 28)).Should().Be("3 months");
    new DateTime(2019, 5, 28).ToFriendlyDuration(new DateTime(2019, 8, 31)).Should().Be("3 months, 3 days");
    new DateTime(2019, 5, 1).ToFriendlyDuration(new DateTime(2019, 5, 31)).Should().Be("30 days");
    new DateTime(2010, 5, 28).ToFriendlyDuration(new DateTime(2020, 8, 28)).Should().Be("10 years, 3 months");
    new DateTime(2010, 5, 28).ToFriendlyDuration(new DateTime(2020, 5, 29)).Should().Be("10 years, 1 day");
}
</code>```

Implementation;

```<code>private class TermAndValue
{
    public TermAndValue(string singular, string plural, int value)
    {
        Singular = singular;
        Plural = plural;
        Value = value;
    }

    public string Singular { get; }
    public string Plural { get; }
    public int Value { get; }
    public string Term => Value > 1 ? Plural : Singular;
}

public static string ToFriendlyDuration(this DateTime value, DateTime? endDate, int maxNrOfElements = 2)
{
    if (!endDate.HasValue)
        return "Until further notice";

    var extendedTimeSpan = new TimeSpanWithYearAndMonth(value, endDate.Value);
    maxNrOfElements = Math.Max(Math.Min(maxNrOfElements, 5), 1);
    var termsAndValues = new[]
    {
        new TermAndValue("year", "years", extendedTimeSpan.Years),
        new TermAndValue("month", "months", extendedTimeSpan.Months),
        new TermAndValue("day", "days", extendedTimeSpan.Days),
        new TermAndValue("hour", "hours", extendedTimeSpan.Hours),
        new TermAndValue("minute", "minutes", extendedTimeSpan.Minutes)
    };

    var parts = termsAndValues.Where(i => i.Value != 0).Take(maxNrOfElements);

    return string.Join(", ", parts.Select(p => $"{p.Value} {p.Term}"));
}

internal class TimeSpanWithYearAndMonth
{
    internal TimeSpanWithYearAndMonth(DateTime startDate, DateTime endDate)
    {
        var span = endDate - startDate;

        Months = 12 * (endDate.Year - startDate.Year) + (endDate.Month - startDate.Month);
        Years = Months / 12;
        Months -= Years * 12;

        if (Months == 0 && Years == 0)
        {
            Days = span.Days;
        }
        else
        {
            var startDateExceptYearsAndMonths = startDate.AddYears(Years);
            startDateExceptYearsAndMonths = startDateExceptYearsAndMonths.AddMonths(Months);
            Days = (endDate - startDateExceptYearsAndMonths).Days;
        }

        Hours = span.Hours;
        Minutes = span.Minutes;
    }

    public int Minutes { get; }
    public int Hours { get; }
    public int Days { get; }
    public int Years { get; }
    public int Months { get; }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here is my solution to this. It is based on other answers in this thread, with added support for year and month as that was requested in the original question (and was what I needed).

As for the discussion whether or not this makes sense I would say that there are cases where it does so. In my case we wanted to show the duration of agreements that in some cases are just a few days, and in other cases several years.

Tests;

[Test]
public void ToFriendlyDuration_produces_expected_result()
{
    new DateTime(2019, 5, 28).ToFriendlyDuration(null).Should().Be("Until further notice");
    new DateTime(2019, 5, 28).ToFriendlyDuration(new DateTime(2020, 5, 28)).Should().Be("1 year");
    new DateTime(2019, 5, 28).ToFriendlyDuration(new DateTime(2021, 5, 28)).Should().Be("2 years");
    new DateTime(2019, 5, 28).ToFriendlyDuration(new DateTime(2021, 8, 28)).Should().Be("2 years, 3 months");
    new DateTime(2019, 5, 28).ToFriendlyDuration(new DateTime(2019, 8, 28)).Should().Be("3 months");
    new DateTime(2019, 5, 28).ToFriendlyDuration(new DateTime(2019, 8, 31)).Should().Be("3 months, 3 days");
    new DateTime(2019, 5, 1).ToFriendlyDuration(new DateTime(2019, 5, 31)).Should().Be("30 days");
    new DateTime(2010, 5, 28).ToFriendlyDuration(new DateTime(2020, 8, 28)).Should().Be("10 years, 3 months");
    new DateTime(2010, 5, 28).ToFriendlyDuration(new DateTime(2020, 5, 29)).Should().Be("10 years, 1 day");
}

Implementation;

private class TermAndValue
{
    public TermAndValue(string singular, string plural, int value)
    {
        Singular = singular;
        Plural = plural;
        Value = value;
    }

    public string Singular { get; }
    public string Plural { get; }
    public int Value { get; }
    public string Term => Value > 1 ? Plural : Singular;
}

public static string ToFriendlyDuration(this DateTime value, DateTime? endDate, int maxNrOfElements = 2)
{
    if (!endDate.HasValue)
        return "Until further notice";

    var extendedTimeSpan = new TimeSpanWithYearAndMonth(value, endDate.Value);
    maxNrOfElements = Math.Max(Math.Min(maxNrOfElements, 5), 1);
    var termsAndValues = new[]
    {
        new TermAndValue("year", "years", extendedTimeSpan.Years),
        new TermAndValue("month", "months", extendedTimeSpan.Months),
        new TermAndValue("day", "days", extendedTimeSpan.Days),
        new TermAndValue("hour", "hours", extendedTimeSpan.Hours),
        new TermAndValue("minute", "minutes", extendedTimeSpan.Minutes)
    };

    var parts = termsAndValues.Where(i => i.Value != 0).Take(maxNrOfElements);

    return string.Join(", ", parts.Select(p => $"{p.Value} {p.Term}"));
}

internal class TimeSpanWithYearAndMonth
{
    internal TimeSpanWithYearAndMonth(DateTime startDate, DateTime endDate)
    {
        var span = endDate - startDate;

        Months = 12 * (endDate.Year - startDate.Year) + (endDate.Month - startDate.Month);
        Years = Months / 12;
        Months -= Years * 12;

        if (Months == 0 && Years == 0)
        {
            Days = span.Days;
        }
        else
        {
            var startDateExceptYearsAndMonths = startDate.AddYears(Years);
            startDateExceptYearsAndMonths = startDateExceptYearsAndMonths.AddMonths(Months);
            Days = (endDate - startDateExceptYearsAndMonths).Days;
        }

        Hours = span.Hours;
        Minutes = span.Minutes;
    }

    public int Minutes { get; }
    public int Hours { get; }
    public int Days { get; }
    public int Years { get; }
    public int Months { get; }
}


问:
Error : Writing in a non-empty collection
I have been facing issue while writing json to my Cosmos DB. I could able to read data and having an issue while writing the same

An applied following version of Cosmos db connectors
https://docs.azuredatabricks.net/spark/latest/data-sources/azure/cosmosdb-connector.html
and tried different versions too. The issue remains to persist.

```<code>RawFilePath="/mnt/ADLS/Users/test/CosmosDB/testfile.json"
DFRead=spark.read.json(RawFilePath)
DFNew = DFRead.selectExpr("activity", "partition AS xfactor","response", "source", "type")

writeConfig  = {
 "Endpoint" : "{End Point}",
 "Masterkey" : "{MasterKey}",
 "Database" : "{DB Name}",
 "Collection" : "{Connection name}",
 "Upsert" : "true"
}

DFNew.write.format("com.microsoft.azure.cosmosdb.spark").options(**writeConfig).save()
</code>```

Getting the following error.

```<code>Error : java.lang.UnsupportedOperationException: Writing in a non-empty collection.
</code>```

Expecting to write json into cosmos DB collection. But, could not able to resolve non-empty collection error in Databricks. Its really appreciate your help.

thank you..

答:
Try by specifying mode</p>

```<code>DFNew.write.format("com.microsoft.azure.cosmosdb.spark").mode("append").options(**writeConfig).save()
</code>```

Body:
I have been facing issue while writing json to my Cosmos DB. I could able to read data and having an issue while writing the same

An applied following version of Cosmos db connectors
https://docs.azuredatabricks.net/spark/latest/data-sources/azure/cosmosdb-connector.html
and tried different versions too. The issue remains to persist.

RawFilePath="/mnt/ADLS/Users/test/CosmosDB/testfile.json"
DFRead=spark.read.json(RawFilePath)
DFNew = DFRead.selectExpr("activity", "partition AS xfactor","response", "source", "type")

writeConfig  = {
 "Endpoint" : "{End Point}",
 "Masterkey" : "{MasterKey}",
 "Database" : "{DB Name}",
 "Collection" : "{Connection name}",
 "Upsert" : "true"
}

DFNew.write.format("com.microsoft.azure.cosmosdb.spark").options(**writeConfig).save()

Getting the following error.

Error : java.lang.UnsupportedOperationException: Writing in a non-empty collection.

Expecting to write json into cosmos DB collection. But, could not able to resolve non-empty collection error in Databricks. Its really appreciate your help.

thank you..

Body:
Try by specifying mode

DFNew.write.format("com.microsoft.azure.cosmosdb.spark").mode("append").options(**writeConfig).save()


问:
Rxjs with Axios Http Get, execute code after request finished
I have a Vue application using TypeScript, Rxjs and Axios.

After making an http get request I want to execute some code, for example to hide a loading indicator.
What would the best way to do this be using Rxjs?
I know I'm subscribing to a stream of data here. Would a promise be better?

I currently have the below code...

```<code>Axios.get<Array<account>>(`https://localhost:5003/api/accounts`)
      .pipe(
        concatMap(response => response.data),
        filter(response => filerFunction(response))
      )
      .subscribe(
        response => {this.tableData.push(response); console.log('response: ' + response)},
        error => console.log(error)
      );
</code>```

答:
I've worked it out. You could use the Finalize operator or the Complete function...</p>

```<code>Axios.get<Array<account>>(`https://localhost:5003/api/accounts`)
  .pipe(
    mergeMap(response => response.data),
    filter(response => filerFunction(response)),
    finalize(()=>{console.log("stop spinner in this function")})
  )
  .subscribe(
    response => this.tableData.push(response),
    error => console.log(error),
    () => console.log("or stop spinner in this function")
  );
</code>```

Body:
I have a Vue application using TypeScript, Rxjs and Axios.

After making an http get request I want to execute some code, for example to hide a loading indicator.
What would the best way to do this be using Rxjs?
I know I'm subscribing to a stream of data here. Would a promise be better?

I currently have the below code...

Axios.get<Array<account>>(`https://localhost:5003/api/accounts`)
      .pipe(
        concatMap(response => response.data),
        filter(response => filerFunction(response))
      )
      .subscribe(
        response => {this.tableData.push(response); console.log('response: ' + response)},
        error => console.log(error)
      );

Body:
I've worked it out. You could use the Finalize operator or the Complete function...

Axios.get<Array<account>>(`https://localhost:5003/api/accounts`)
  .pipe(
    mergeMap(response => response.data),
    filter(response => filerFunction(response)),
    finalize(()=>{console.log("stop spinner in this function")})
  )
  .subscribe(
    response => this.tableData.push(response),
    error => console.log(error),
    () => console.log("or stop spinner in this function")
  );


问:
How to use custom name instead of related_name in serializer in case of reverse relation?
In case of reverse relation between two models we can fetch all related child rows in our parent serializer via the related_name argument of ForeginKeyField. I want to use a different name instead of the related_name
to fetch those row.

Below is the example that is conventionally used.

Models

```<code>class Library(models.Model):
    libraryId = models.AutoField(primary_key = True)
    libraryName = models.CharField(max_length=150)

class Book(models.Model):
    bookId = models.AutoField(primary_key = True)
    fk_book_libraryId = models.ForeignKey('Library', related_name='library_book_relation', on_delete=models.CASCADE )
</code>```

Serializers

```<code>class BookSerializer(models.HyperlinkedModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

class LibrarySerializer(serializers.ModelSerializer):
    lib_name = serializers.CharField(source='libraryName')
    library_book_relation = BookSerializer(many=True, read_only=True)

    '''
    I don't want to use the name 'library_book_relation'. I want to make   it as short custom name like the 'lib_name'.
    '''

    class Meta:
        model = Library
        fields = '__all__'
        extra_fields = ['library_book_relation']
</code>```

I want some thing like below:

```<code>class Meta:
        model = Library
        fields = '__all__'
        extra_fields = ['all_books']
</code>```

Please don't make it as duplicate someone. Although some similar questions exist but my problem was not solved yet, that's why this question arisen here.

答:
Are you sure this is not duplicated? Looks exactly like what's said in this answer.

In summary, you can use a SerializerMethodField to give it a custom name and then return what you want inside of it (just remember it is read-only) or, depending on which property you want from the ForeignKey model, you can use the source attribute in a regular field (CharField, for instance).

Update:

Doesn't something like this work for you?

short_name = serializers.SerializerMethodField()

[...]

def get_short_name(self, obj):
    return obj.library_book_relation
```

Body:
In case of reverse relation between two models we can fetch all related child rows in our parent serializer via the related_name argument of ForeginKeyField. I want to use a different name instead of the related_name
to fetch those row.

Below is the example that is conventionally used.

Models

class Library(models.Model):
    libraryId = models.AutoField(primary_key = True)
    libraryName = models.CharField(max_length=150)

class Book(models.Model):
    bookId = models.AutoField(primary_key = True)
    fk_book_libraryId = models.ForeignKey('Library', related_name='library_book_relation', on_delete=models.CASCADE )

Serializers

class BookSerializer(models.HyperlinkedModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

class LibrarySerializer(serializers.ModelSerializer):
    lib_name = serializers.CharField(source='libraryName')
    library_book_relation = BookSerializer(many=True, read_only=True)

    '''
    I don't want to use the name 'library_book_relation'. I want to make   it as short custom name like the 'lib_name'.
    '''

    class Meta:
        model = Library
        fields = '__all__'
        extra_fields = ['library_book_relation']

I want some thing like below:

class Meta:
        model = Library
        fields = '__all__'
        extra_fields = ['all_books']

Please don't make it as duplicate someone. Although some similar questions exist but my problem was not solved yet, that's why this question arisen here.


问:
Modifying a regular expression by another by adding a something to it
I am trying to modifying my regex expression using replace. What ultimately want to do is to add 01/ in the front of my existing pattern.It is litterally replacing a pattern by another.
Here is what I am doing with replace:

```<code> df['found_d'].str.replace(pattern2, '1/'+pattern2)
 #must be str, not _sre.SRE_Pattern
</code>```

I would like to use sub it takes 3 arguments and I am not too sure of how to use it at this point.
Here is an expected input:

```<code> df['found_d']= 01/07/91 or 01/07/1991
</code>```

I need to add a missing date to my pattern.

答:
No need for callables, re provides dedicated means to access the matched text during replacement.

In order to append a literal 01/ to a pattern match, use a \g<0> unambiguous backreference to the whole pattern in the replacement pattern rather than using the regex pattern:

```<code>df['found_d'] = df['found_d'].str.replace(pattern2, r'01/\g<0>')
                                                    ^^^^^^^^^^^
</code>```

Body:
I am trying to modifying my regex expression using replace. What ultimately want to do is to add 01/ in the front of my existing pattern.It is litterally replacing a pattern by another.
Here is what I am doing with replace:

 df['found_d'].str.replace(pattern2, '1/'+pattern2)
 #must be str, not _sre.SRE_Pattern

I would like to use sub it takes 3 arguments and I am not too sure of how to use it at this point.
Here is an expected input:

 df['found_d']= 01/07/91 or 01/07/1991

I need to add a missing date to my pattern.

Body:
No need for callables, re provides dedicated means to access the matched text during replacement.

In order to append a literal 01/ to a pattern match, use a \g<0> unambiguous backreference to the whole pattern in the replacement pattern rather than using the regex pattern:

df['found_d'] = df['found_d'].str.replace(pattern2, r'01/\g<0>')
                                                    ^^^^^^^^^^^


问:
Duplicate Symbols for Architecture arm64
When I try running my Xcode Project it fails with an error stating that I have duplicate symbols. I looked online where the find these duplicates but have had no luck:

Any ideas how to fix this?

答: The problem for me was I had manually included a framework but then also included that same framework in CocoaPods not knowing I did so. Once I removed one or the other, the problem went away</p>


问:
Editing unity scene files post-compile
I'm working on a mod engine for a unity game. It is 2D based and stores all the level data in separate files ("level1", "level2") in the game data folder (I believe this is standard for unity). I am looking to be able to edit these in post to add/remove game objects in the scene. I wish to be able  to do this programmatically in C#.

I've already had a look at the file in the hex editor, and it seems like this is possible (I can see basic game object data).

Currently im loading the scene then moving all objects around or instantiating new ones, but this is proving to be unstable because of the way the game handles objects.

If anyone could point me in the direction of how i would go about this, it would be greatly appreciated.

Update for those that are asking for additional info: Yes, by levels I mean scenes, unity saves them as “level0”, “level1”, etc

I am not the author of the game, the game was not designed with changing the scenes in mind, almost all of the interacatble objects have special riggers crafted to them, so in order to move them it requires me to be extremely careful or the game crashes.

答: From what you write it seems your separate files are actual Unity3D scenes. You should only have once scene and a system in place that reads and loads your data, for example from text files, then programmatically instantiate those object at run time.</p>

Title: Editing unity scene files post-compile


问:
AWS execute-api endpoint request timeout / dial tcp i/o timeout
I want to access a public Rest Api gateway from a AWS Lambda within a VPC.

I already created an execute-api endpoint and added the 443 port to the security group. I also disabled private DNS Names, but I am still getting a "Endpoint request timed out"/ dial tcp 52.28..:443: i/o timeout error.
I also tested the API I want to access with postman, which works as intended.
What am I missing.

答:
By default Lambda in a VPC does not have public internet access.

One option you have is to setup up a NAT gateway in the subnet Lambda is deployed to give it internet access, hence access to public REST API. More here -> Internet access for lambda functions

AWS Lambda uses the VPC information you provide to set up ENIs that allow your Lambda function to access VPC resources. Each ENI is assigned a private IP address from the IP address range within the Subnets you specify, but is not assigned any public IP addresses. Therefore, if your Lambda function requires Internet access (for example, to access AWS services that don't have VPC endpoints ), you can configure a NAT instance inside your VPC or you can use the Amazon VPC NAT gateway. For more information, see NAT Gateways in the Amazon VPC User Guide. You cannot use an Internet gateway attached to your VPC, since that requires the ENI to have public IP addresses.

Or you can have a look here ->  Why can't I connect to my public API from an API Gateway VPC endpoint. It suggests this

Use the curl command line tool to test your private API. In your curl command, include the base URL used to invoke the API, as well as a Host header or x-apigw-api-id header. For more information, see Invoking Your Private API Using Endpoint-Specific Public DNS Hostnames.

The base URL to invoke the API includes the DNS name and stage name. It looks like this:
  https://vpceId.execute-api.awsRegion.vpce.amazonaws.com/stageName

Note: Replace vpceId with the VPC endpoint ID you copied. Replace awsRegion with your private API's AWS Region (for example, us-east-1). Replace stageName with the name of the stage to which your API is deployed.

The Host header looks like this:

Host:apiId.execute-api.awsRegion.amazonaws.com

Note: Replace apiId with the API ID you copied. Replace awsRegion with your private API's AWS Region (for example, us-east-1).

The x-apigw-api-id header looks like this:

x-apigw-api-id:apiId

Note: Replace apiId with the API ID you copied.

If you set up everything correctly, you get a 200 response code.


问:
NodeJs Decrypt AES256 Encryption From JAVA
I'm doing an integration with another system and the data given is encrypted in AES-256-CBC(Java) and need to decrypt it in NodeJs in order to proceed.

I have tried many ways from internet and stuck in error. Below is the sample code of Java(decryption) which is working and NodeJs(my code of decryption)

private static final int ITERATION_COUNT = 65536;
private static final int KEY_LENGTH = 256;
private static final byte[] DEFAULT_IV = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

public static byte[] decryptToBytes(String src, String secret, String salt, byte[] iv) {
        try{
            IvParameterSpec ivspec = new IvParameterSpec(iv);

            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
            KeySpec spec = new PBEKeySpec(secret.toCharArray(), salt.getBytes(), ITERATION_COUNT, KEY_LENGTH);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
            return cipher.doFinal(Base64.getDecoder().decode(src));
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

public static String decrypt(String src, String secret, String salt, byte[] iv) {
        try{
            return new String(decryptToBytes(src, secret, salt, iv));
        }catch (Exception ex) {
            return null;
        }
    }

public static void main(String[] args) {
        String secret  = "abcd123456";
        String salt = "123abc";
        String plainText ="This is AES256 encryption test";
        String cipherText = "gbYgtu5EWxOYRSUmMsEtdn8oQLxBjejfwUBSRhhls08=";

        byte[] IV = new byte[16];

        String originalText = decrypt(cipherText,secret, salt, IV);

    }
```

<pre class="lang-js prettyprint-override"><code>import crypto from "crypto";
public aesCdcDecrypt(input: string) {
        let iterationCount = 65536;
        let keyLength = 256;
        let iv = new Buffer(16);
        let keyHex = "abcd123456";
        let salt = "123abc";

        let decryptText: string;
        try {
            crypto.pbkdf2(new Buffer(keyHex), new Buffer(salt), iterationCount, keyLength, "sha256", function (err, key) {
                let secretKey = key.toString("hex");
                let decipher = crypto.createDecipheriv("aes-256-cbc", secretKey, iv);
                decryptText = decipher.update(input, "binary", "utf8");
                decryptText += decipher.final("utf8");

                console.log('Result: ' + decryptText);
            });
        } catch (e) {
            console.log(e);
        }
        return decryptText;
    }
</code>```

Result getting this error -->
Error: Invalid key length
    at new Decipheriv (crypto.js:267:16)
    at Object.createDecipheriv (crypto.js:627:10)

答:
There are a few minor issues in your TS code:

key length is in bytes, not bits

new Buffer() does not decode base64 by default

Here's a working version (JS):

```<code>const crypto = require('crypto')
function aesCdcDecrypt(ciphertext) {
    let iterationCount = 65536;
    let keyLength = 32;
    let iv = Buffer.alloc(16);
    let keyHex = "abcd123456";
    let salt = "123abc";

    let key = crypto.pbkdf2Sync(keyHex, Buffer.from(salt), iterationCount, keyLength, "sha256");
    var cipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
    cipher.setAutoPadding(true);
    let ciph = cipher.update(Buffer.from(ciphertext, "base64"));
    let ciphf = cipher.final();
    return Buffer.concat([ciph, ciphf]).toString();
}
console.log(aesCdcDecrypt("gbYgtu5EWxOYRSUmMsEtdn8oQLxBjejfwUBSRhhls08="));
</code>```

Prints:

```<code>This is AES256 encryption test
</code>```

Body:
I'm doing an integration with another system and the data given is encrypted in AES-256-CBC(Java) and need to decrypt it in NodeJs in order to proceed.

I have tried many ways from internet and stuck in error. Below is the sample code of Java(decryption) which is working and NodeJs(my code of decryption)

private static final int ITERATION_COUNT = 65536;
private static final int KEY_LENGTH = 256;
private static final byte[] DEFAULT_IV = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

public static byte[] decryptToBytes(String src, String secret, String salt, byte[] iv) {
        try{
            IvParameterSpec ivspec = new IvParameterSpec(iv);

            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
            KeySpec spec = new PBEKeySpec(secret.toCharArray(), salt.getBytes(), ITERATION_COUNT, KEY_LENGTH);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
            return cipher.doFinal(Base64.getDecoder().decode(src));
        }catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

public static String decrypt(String src, String secret, String salt, byte[] iv) {
        try{
            return new String(decryptToBytes(src, secret, salt, iv));
        }catch (Exception ex) {
            return null;
        }
    }

public static void main(String[] args) {
        String secret  = "abcd123456";
        String salt = "123abc";
        String plainText ="This is AES256 encryption test";
        String cipherText = "gbYgtu5EWxOYRSUmMsEtdn8oQLxBjejfwUBSRhhls08=";

        byte[] IV = new byte[16];

        String originalText = decrypt(cipherText,secret, salt, IV);

    }

import crypto from "crypto";
public aesCdcDecrypt(input: string) {
        let iterationCount = 65536;
        let keyLength = 256;
        let iv = new Buffer(16);
        let keyHex = "abcd123456";
        let salt = "123abc";

        let decryptText: string;
        try {
            crypto.pbkdf2(new Buffer(keyHex), new Buffer(salt), iterationCount, keyLength, "sha256", function (err, key) {
                let secretKey = key.toString("hex");
                let decipher = crypto.createDecipheriv("aes-256-cbc", secretKey, iv);
                decryptText = decipher.update(input, "binary", "utf8");
                decryptText += decipher.final("utf8");

                console.log('Result: ' + decryptText);
            });
        } catch (e) {
            console.log(e);
        }
        return decryptText;
    }

Result getting this error -->
Error: Invalid key length
    at new Decipheriv (crypto.js:267:16)
    at Object.createDecipheriv (crypto.js:627:10)

Body:
There are a few minor issues in your TS code:

key length is in bytes, not bits

new Buffer() does not decode base64 by default

Here's a working version (JS):

const crypto = require('crypto')
function aesCdcDecrypt(ciphertext) {
    let iterationCount = 65536;
    let keyLength = 32;
    let iv = Buffer.alloc(16);
    let keyHex = "abcd123456";
    let salt = "123abc";

    let key = crypto.pbkdf2Sync(keyHex, Buffer.from(salt), iterationCount, keyLength, "sha256");
    var cipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
    cipher.setAutoPadding(true);
    let ciph = cipher.update(Buffer.from(ciphertext, "base64"));
    let ciphf = cipher.final();
    return Buffer.concat([ciph, ciphf]).toString();
}
console.log(aesCdcDecrypt("gbYgtu5EWxOYRSUmMsEtdn8oQLxBjejfwUBSRhhls08="));

Prints:

This is AES256 encryption test


问:
File Transfer via Internet ( using java)
I've a java(swing) application running on server and client(or assume two different

computers),These two are connected through Internet not by LAN or WAN..The client has to send

some data (around 200 kb) to the server.Which method is preferable for transferring data..I used

TCP through LAN,but it's working slow through Internet..So can I use UDP for internet ?  If yes, I don't

know how to divide my data into chunks and send it & again re-assemble the data at the server.

I am really thankful if source code is provided for UDP transfer(bulk data in java).

thanks in advance..

答:
Ravi is struggeling for some days now with this problem. Now UDP is expected to bring help, but, of course, it won't!

Ravi, I give you some more hints for free (as you have not upvoted even one of the 7 answers you have received until now, I guess the reputation system in StackOverflow is and remains a mystery to you):

Computer 2D-images are nothing more
than a 2 dimensional array of pixels, i.e. color
values (usually int values).

The BufferedImage class has methods to get and set each pixel individually, I told you yesterday.

Two equal sized Images are different, if there is a coordinate x,y where the corresponding pixel in one image is not the same as in the other image.

BTW, may I ask what your profession is?


问:
Text color is not updating in ListView
I am building an Android application and I need to change the text color of all cells in the ListView.

This is the code I use to populate and connect the ListView with the Activity file:

protected void onCreate(Bundle savedInstanceState) {
        ...

        // Create a temp array.
        ListView lv = (ListView) findViewById(R.id.gamesList);
        displayGames = new ArrayList<String>();

        // Populates ListView
        updateList();

        // Create Array Adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,displayGames);
        lv.setAdapter(adapter);
    }
```

<p>My problem is that the text of the TextView in the cells does not have the correct color even though I specifically changed it on the XML file. See this code below: </p>

<p>This is the XML code for the creation of the ListView:</p>

```<ListView
        android:id="@+id/gamesList"
        android:layout_width="396dp"
        android:layout_height="342dp"
        android:layout_marginStart="9dp"
        android:layout_marginEnd="10dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout6"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout5"
        app:layout_constraintVertical_bias="0.854" />
```

<p>I defined the Text cells in a new XML file called <code>simple_list_item_1.xml</code>.</p>

```<TextView
        android:id="@+id/game"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"
        android:paddingStart="?android:attr/listPreferredItemPaddingStart"
        android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:textColor="@color/white"
        android:textColorHint="@color/white"
        tools:ignore="MissingConstraints" />
```

I am running the app on a Pixel 2 emulator using API 22 Android 5,1.

答:
Change android.R.layout.simple_list_item_1 to R.layout.simple_list_item_1

```<code>       // Create Array Adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1,displayGames);
</code>```

Title: Text color is not updating in ListView

Body:
I am building an Android application and I need to change the text color of all cells in the ListView.

This is the code I use to populate and connect the ListView with the Activity file:

protected void onCreate(Bundle savedInstanceState) {
        ...

        // Create a temp array.
        ListView lv = (ListView) findViewById(R.id.gamesList);
        displayGames = new ArrayList<String>();

        // Populates ListView
        updateList();

        // Create Array Adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,displayGames);
        lv.setAdapter(adapter);
    }

My problem is that the text of the TextView in the cells does not have the correct color even though I specifically changed it on the XML file. See this code below:

This is the XML code for the creation of the ListView:

<ListView
        android:id="@+id/gamesList"
        android:layout_width="396dp"
        android:layout_height="342dp"
        android:layout_marginStart="9dp"
        android:layout_marginEnd="10dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout6"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout5"
        app:layout_constraintVertical_bias="0.854" />

I defined the Text cells in a new XML file called simple_list_item_1.xml.

<TextView
        android:id="@+id/game"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"
        android:paddingStart="?android:attr/listPreferredItemPaddingStart"
        android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:textColor="@color/white"
        android:textColorHint="@color/white"
        tools:ignore="MissingConstraints" />

I am running the app on a Pixel 2 emulator using API 22 Android 5,1.

Body:
Change android.R.layout.simple_list_item_1 to R.layout.simple_list_item_1

       // Create Array Adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1,displayGames);


问:
Filter specifik patern in a complex file
I have this logfile and im trying to avoid printing the text containing patern" APLHA".

```<code>   +++ skdfhahjsahsdjk >
** ALPHA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
* KJENRFKES DFJKLSDFJEDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
CL mesukww juwaehdiearfa
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
*C KJENRFKESDFJ ksludhieokdaewmdp
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

 +++ skdfhahjsahsdjk >
** BETA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-
</code>```

I tried via this way but not successful.It prints the rest of the text, except "ALPHA"

cat logfile |grep -v "ALPHA"

result:

```<code>+++ skdfhahjsahsdjk >
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-
</code>```

What i expect is the whole log containing "ALPHA" is not printed, like hereunder:

```<code> +++ skdfhahjsahsdjk >
* KJENRFKES DFJKLSDFJEDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
CL mesukww juwaehdiearfa
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
*C KJENRFKESDFJ ksludhieokdaewmdp
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

 +++ skdfhahjsahsdjk >
** BETA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-
</code>```

Can you please advise on any other solution to this case?

Regards Dom

答:
give this a try:</p>

```<code>awk 'BEGIN{RS=ORS="\n\n"}!/ALPHA/' file
</code>```

Body:
I have this logfile and im trying to avoid printing the text containing patern" APLHA".

   +++ skdfhahjsahsdjk >
** ALPHA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
* KJENRFKES DFJKLSDFJEDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
CL mesukww juwaehdiearfa
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
*C KJENRFKESDFJ ksludhieokdaewmdp
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

 +++ skdfhahjsahsdjk >
** BETA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

I tried via this way but not successful.It prints the rest of the text, except "ALPHA"

cat logfile |grep -v "ALPHA"

result:

+++ skdfhahjsahsdjk >
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

What i expect is the whole log containing "ALPHA" is not printed, like hereunder:

 +++ skdfhahjsahsdjk >
* KJENRFKES DFJKLSDFJEDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
CL mesukww juwaehdiearfa
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

   +++ skdfhahjsahsdjk >
*C KJENRFKESDFJ ksludhieokdaewmdp
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

 +++ skdfhahjsahsdjk >
** BETA EDFJDJFKLJDKFJKSDLFJL
   SDFSDGDRGRTG
   WEFETTFYRT #168113++-

Can you please advise on any other solution to this case?

Regards Dom

Body:
give this a try:

awk 'BEGIN{RS=ORS="\n\n"}!/ALPHA/' file