问:
How to reload a javascript function and reload a footer on html page without reloading the whole page?
i have a main.page.php that loads a javascript funtion to get a server up or down status.
i would like to reload this function every 10 seconds to check the server status and update the status message in footer div by refreshing the footer not the whole page.

main.page.php

```<code><head>

<?php require_once 'inc/meta.php'; ?>

<?php require_once 'inc/css.php'; ?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  <script type="text/javascript">

    'use strict';

    function queryPlex (query) {
          return $.ajax({
          type: 'POST',
          url: 'inc/plex-api.php',
          cache: false,
          data: {'postData': query},
          dataType: 'json'
        });
    }

    $(document).ready(function () {
          getServerStatus();
    });

    function getServerStatus () {

         const serverStatusDiv = $('#server-status-msg');
         const getServerStatus = queryPlex('/');
         getServerStatus.done(function (data) {
                 if (data) {
                 serverStatusDiv.html(' <i style="color:green; font-style:normal;">  ONLINE <span style="color:green;" class="fas fa-fw fa-check-circle" data-fa-transform="grow-4"></span></i>');
                } else {
                 serverStatusDiv.html(' <i style="color:red; font-style:normal;">  OFFLINE <span style="color:red;" class="fas fa-fw fa-exclamation-circle" data-fa-transform="grow-4"></span></i>');
                }
            });

         getServerStatus.fail(function () {
         serverStatusDiv.html(' <i style="color:red; font-style:normal;">  OFFLINE <span style="color:red;" class="fas fa-fw fa-exclamation-circle" data-fa-transform="grow-4"></span></i>');
                    });
}
   </script>

</head>

<body id="body_iframe"  onload="getServerStatus ()">

<!-- ============ Fixed Nav ============ -->

     <?php require_once 'inc/nav_main.php'; ?>

<!-- ============ Begin page content ============= -->

    <div id="container_iframe" style="background-color:black;">
          <iframe id="iframe" name="frame" frameBorder="0" scrollbar="no" src="./?page=media"></iframe>
        </div>

<!-- ============ Sticky Footer ============ -->

    <?php require_once 'inc/footer.php'; ?>

<!-- ============== Bootstrap core JavaScript  ================= -->

<script src="js/jquery.min.js" type="text/javascript"></script>

<?php require_once 'inc/javascripts.php'; ?>

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

footer.php

```<code><!-- ============ Footer ============ -->

<div id="footer_iframe" class="bg-black">
  <div class="text-right">

    <!-- ============ Check Server Status ============ -->

    <p class="text-right">StreamNet Server: <span id="server-status-msg"> checking status ....</span></p>

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

How can i achieve this?

Thanks.

UPDATE

i updated my main.page.php

added setTimout to the function an added script to reload the footer div.

```<code> <script type="text/javascript">

    'use strict';

    function queryPlex (query) {
          return $.ajax({
          type: 'POST',
          url: 'inc/plex-api.php',
          cache: false,
          data: {'postData': query},
          dataType: 'json'
        });
    }

    $(document).ready(function () {
          getServerStatus();
    });

    function getServerStatus () {

         const serverStatusDiv = $('#server-status-msg');
         const getServerStatus = queryPlex('/');
         getServerStatus.done(function (data) {
                 if (data) {
                 serverStatusDiv.html(' <i style="color:green; font-style:normal;">  ONLINE <span style="color:green;" class="fas fa-fw fa-check-circle" data-fa-transform="grow-4"></span></i>');
                } else {
                 serverStatusDiv.html(' <i style="color:red; font-style:normal;">  OFFLINE <span style="color:red;" class="fas fa-fw fa-exclamation-circle" data-fa-transform="grow-4"></span></i>');
                }
            });

         getServerStatus.fail(function () {
         serverStatusDiv.html(' <i style="color:red; font-style:normal;">  OFFLINE <span style="color:red;" class="fas fa-fw fa-exclamation-circle" data-fa-transform="grow-4"></span></i>');
                    });

      setTimeout(getServerStatus, 10000);

}
   </script>

<script>
$(document).ready(function(){
    setInterval(function(){
        $("#footer").load('inc/footer.php')
    }, 10000);
});
</script>
</code>```

also i removed the php code to load the footer.php at the end of the main.page.php.

```<code><body id="body_iframe"  onload="getServerStatus ()">

<!-- ============ Fixed Nav ============ -->

     <?php require_once 'inc/nav_main.php'; ?>

<!-- ============ Begin page content ============= -->

    <div id="container_iframe" style="background-color:black;">
          <iframe id="iframe" name="frame" frameBorder="0" scrollbar="no" src="./?page=media"></iframe>
        </div>

<!-- ============ Sticky Footer ============ -->
<div id="footer"></div>

<!-- ============== Bootstrap core JavaScript  ================= -->

<script src="js/jquery.min.js" type="text/javascript"></script>

<?php require_once 'inc/javascripts.php'; ?>

</body>
</code>```

but now my footer isn't loading anymore?

答:
You can use a setInterval

setInterval(getServerStatus, 10000);

setInterval

And for the footer, you can just replace the content using jQuery.

```<code>$('#server-status-msg').html('Server is Up');
</code>```

Body:
i have a main.page.php that loads a javascript funtion to get a server up or down status.
i would like to reload this function every 10 seconds to check the server status and update the status message in footer div by refreshing the footer not the whole page.

main.page.php

<?php require_once 'inc/meta.php'; ?>

<?php require_once 'inc/css.php'; ?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

     <?php require_once 'inc/nav_main.php'; ?>

    <?php require_once 'inc/footer.php'; ?>

<?php require_once 'inc/javascripts.php'; ?>

footer.php

StreamNet Server:  checking status ....

How can i achieve this?

Thanks.

UPDATE

i updated my main.page.php

added setTimout to the function an added script to reload the footer div.

also i removed the php code to load the footer.php at the end of the main.page.php.

     <?php require_once 'inc/nav_main.php'; ?>

<?php require_once 'inc/javascripts.php'; ?>

but now my footer isn't loading anymore?

Body:
You can use a setInterval

setInterval(getServerStatus, 10000);

setInterval

And for the footer, you can just replace the content using jQuery.

$('#server-status-msg').html('Server is Up');


来源: stackexchange

问:
Report Viewer Font getting stretched on WIndows Server Machine only
I did a small app to make shipping bills, where a user enters the information they want and can either Preview (a form with a ReportViewer control is opening up) or Print direclty. The reportviewer uses a Local report embedded into the application.

Example Here : http://i.stack.imgur.com/z90z8.jpg

I have tried the app on a WinXP, Vista and Windows 7 machine and there is no problem, the report is previewed correctly.

But when installing it on the server directly (2003 R2, 64 bit) the Font are stretched (even Printing from the control). When printing directly (I created my own code to do it, the report is rendered in EMF and then prints it) I have the same problem.

But when saving in PDF or Word from the ReportViewer control the do appear correctly.

This is an annoyance because we remote desktop to the server to use our main MRP program, so using the program inside the server will be best, so we don't have so switch back to the desktop machine just for a single operation.

By the way this is the normal Arial Font, so it is not a missing font issue. Also the server does have a couple of Crystal (version 9 I think) and SQL server 2003 reporting runtime installed on them. This is using Visual Studio 2010.

答:
I ran into the same problem with a virtual machine hosted on a Win2008R2 box.  The solution I found was posted by user Cassisi:

the key to fixing the server itself is to ensure the desktop resolution picked up by the SSRS service is 1024x768 (i.e. a 4:3 ratio) if the server is being remoting into via Desktop Services.

As a workaround I am going to try the solution described in his article on high-fidelity printing.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
IntelliJ: Error:java: error: release version 5 not supported
I'm using IntelliJ IDEA Ultimate 2019.3.1. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:

```<code>Error:java: error: release version 5 not supported
</code>```

Running java --version by terminal I get the following output:

```<code>openjdk 11.0.5 2019-10-15
OpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)
OpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)
</code>```

Running javac --version by terminal I get the following output:

```<code>javac 11.0.5
</code>```

Going to the Settings of the Java Compiler ( as suggested here ) I see this:

I tried editing the "Target bytecode version" to 1.8 but I get the following errors:

```<code>Error:(1, 26) java: package javafx.application does not exist
Error:(2, 20) java: package javafx.stage does not exist
Error:(4, 27) java: cannot find symbol
  symbol: class Application
Error:(12, 23) java: cannot find symbol
  symbol:   class Stage
  location: class Main
Error:(7, 9) java: cannot find symbol
  symbol:   method launch(java.lang.String[])
  location: class Main
Error:(11, 5) java: method does not override or implement a method from a supertype
</code>```

Changing it to version 1.11 I get this error instead:

```<code>Error:java: Source option 5 is no longer supported. Use 6 or later.
</code>```

What do you think is the problem? How may I solve it?

答:
Took me a while to aggregate an actual solution, but here's how to get rid of this compile error.

Open IntelliJ preferences.

Search for "compiler" (or something like "compi").

Scroll down to Maven -->java compiler. In the right panel will be a list of
modules and their associated java compile version "target bytecode version."

Select a version >1.5. You may need to upgrade your jdk if one is not available.

ContentLicense: CC BY-SA 4.0

Body:
I'm using IntelliJ IDEA Ultimate 2019.3.1. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:

Error:java: error: release version 5 not supported

Running java --version by terminal I get the following output:

openjdk 11.0.5 2019-10-15
OpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)
OpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)

Running javac --version by terminal I get the following output:

javac 11.0.5

Going to the Settings of the Java Compiler ( as suggested here ) I see this:

I tried editing the "Target bytecode version" to 1.8 but I get the following errors:

Error:(1, 26) java: package javafx.application does not exist
Error:(2, 20) java: package javafx.stage does not exist
Error:(4, 27) java: cannot find symbol
  symbol: class Application
Error:(12, 23) java: cannot find symbol
  symbol:   class Stage
  location: class Main
Error:(7, 9) java: cannot find symbol
  symbol:   method launch(java.lang.String[])
  location: class Main
Error:(11, 5) java: method does not override or implement a method from a supertype

Changing it to version 1.11 I get this error instead:

Error:java: Source option 5 is no longer supported. Use 6 or later.

What do you think is the problem? How may I solve it?


问:
VIEWS with SELECT inside conditions delaying the query
In one of my SQL views I am using an inline select statement with a where clause.

The outline of my view is like

```<code>ALTER VIEW [dbo].[vw_autumn]
AS
    SELECT
        BookNumber, Title, shopNo
    FROM
        (SELECT
             BookNumber, Title, shopNO
         FROM
             (SELECT DISTINCT
                  (sum_vnr) AS BookNumber,
                  navn1 AS Title,
                  tik AS ShopNO,
                  ROW_NUMBER() OVER (PARTITION BY sum_vnr, tik ORDER BY sum_vnr DESC) AS rownumber
              FROM
                  sum s
              INNER JOIN
                  hod h ON s.tik = h.tik
              WHERE
                  s.aar = (SELECT currentyear
                           FROM SemesterInfo
                           WHERE SemName = 'Autumn')
                  AND CAST(s.sum_vnr AS BIGINT) > 10000
                  AND (s.id LIKE 'h%' OR s.id LIKE 'H%' OR s.id LIKE 'j%'
                       OR s.id LIKE 'J%')) a
    WHERE rownumber = 1
    ) b
LEFT JOIN (
    ------
    ) p ON b.ShopNO = p.tikk
    AND b.ISBN = p.vnr
LEFT JOIN table_k k ON p.aar = k.aar

GO
</code>```

And if I remove the WHERE clause of

```<code> WHERE
     s.aar = (SELECT currentyear
              FROM SemesterInfo
              WHERE SemName = 'Autumn')
</code>```

and shorten it to

```<code>WHERE s.aar =19
</code>```

I am getting the result of view very quickly. But I am trying to add some dynamic nature to this query and selecting this constant from a settings table

Any thoughts on this? Why is the query taking an indefinite time to load with an inline Where clause?

答:
Rewrite the subquery as a join.

```<code>INNER JOIN SemesterInfo si
ON s.aer = si.currentYear
WHERE si.SemName = 'Autumn'
</code>```

If that doesn't do it, consider keeping this syntax and creating an index on SemName

Body:
In one of my SQL views I am using an inline select statement with a where clause.

The outline of my view is like

ALTER VIEW [dbo].[vw_autumn]
AS
    SELECT
        BookNumber, Title, shopNo
    FROM
        (SELECT
             BookNumber, Title, shopNO
         FROM
             (SELECT DISTINCT
                  (sum_vnr) AS BookNumber,
                  navn1 AS Title,
                  tik AS ShopNO,
                  ROW_NUMBER() OVER (PARTITION BY sum_vnr, tik ORDER BY sum_vnr DESC) AS rownumber
              FROM
                  sum s
              INNER JOIN
                  hod h ON s.tik = h.tik
              WHERE
                  s.aar = (SELECT currentyear
                           FROM SemesterInfo
                           WHERE SemName = 'Autumn')
                  AND CAST(s.sum_vnr AS BIGINT) > 10000
                  AND (s.id LIKE 'h%' OR s.id LIKE 'H%' OR s.id LIKE 'j%'
                       OR s.id LIKE 'J%')) a
    WHERE rownumber = 1
    ) b
LEFT JOIN (
    ------
    ) p ON b.ShopNO = p.tikk
    AND b.ISBN = p.vnr
LEFT JOIN table_k k ON p.aar = k.aar

GO

And if I remove the WHERE clause of

 WHERE
     s.aar = (SELECT currentyear
              FROM SemesterInfo
              WHERE SemName = 'Autumn')

and shorten it to

WHERE s.aar =19

I am getting the result of view very quickly. But I am trying to add some dynamic nature to this query and selecting this constant from a settings table

Any thoughts on this? Why is the query taking an indefinite time to load with an inline Where clause?

Body:
Rewrite the subquery as a join.

INNER JOIN SemesterInfo si
ON s.aer = si.currentYear
WHERE si.SemName = 'Autumn'

If that doesn't do it, consider keeping this syntax and creating an index on SemName


问:
What is the channel uri when registering a device via Microsoft's Azure Create a Registration call
Following what's outlined here I've been able to so far read all registered devices, delete a device registration by id, and get a specific device registration by tag. What I want to do is register a device with a specific tag.

I found the page that specifies using this POST endpoint:

```<code>https://{namespace}.servicebus.windows.net/{NotificationHub}/registrations/?api-version=2015-01
</code>```

I've applied the correct headers - Content Type, Authorization, and x-ms-version.

My question comes in the XML body that is getting sent. Where do I find the correct ChannelUri or is there something else in Azure / Firebase that I should be using in place of the channel uri?

```<code><?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<content type="application/xml">
    <WindowsRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
        <Tags>myTag, myOtherTag</Tags>
        <ChannelUri>{ChannelUri}</ChannelUri>
    </WindowsRegistrationDescription>
</content>
</code>```

Also, am I correct in thinking that the above api call will successfully register a device with the azure notification hub or am I missing a step somewhere?

答:
The ChannelUri is a value that will be provided to you via UWP that allows you to target the particular Windows machine your application is running on (e.g.the example that you've provided above is WNS specific payload.)

Each Push Notification Service (PNS) has its own mechanism for uniquely identifying a device that should receive notifications. Other examples are included on the reference page you found, for instance you'll notice that Apple devices require a DeviceToken instead.

Body:
Following what's outlined here I've been able to so far read all registered devices, delete a device registration by id, and get a specific device registration by tag. What I want to do is register a device with a specific tag.

I found the page that specifies using this POST endpoint:

https://{namespace}.servicebus.windows.net/{NotificationHub}/registrations/?api-version=2015-01

I've applied the correct headers - Content Type, Authorization, and x-ms-version.

My question comes in the XML body that is getting sent. Where do I find the correct ChannelUri or is there something else in Azure / Firebase that I should be using in place of the channel uri?

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<content type="application/xml">
    <WindowsRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
        <Tags>myTag, myOtherTag</Tags>
        <ChannelUri>{ChannelUri}</ChannelUri>
    </WindowsRegistrationDescription>
</content>

Also, am I correct in thinking that the above api call will successfully register a device with the azure notification hub or am I missing a step somewhere?


问:
Eloquent relation on data types (fields) table
Here my tables, User is the classic Auth table:

DataTypes

```<code>+----+--------------+
| id |    field     |
+----+--------------+
|  1 | address      |
|  2 | mobile_phone |
|  3 | city         |
+----+--------------+
</code>```

UserData

```<code>+----+----------+--------------+---------+
| id |  value   | data_type_id | user_id |
+----+----------+--------------+---------+
|  1 | Milan    |            3 |       1 |
|  2 | 99123233 |            2 |       1 |
+----+----------+--------------+---------+
</code>```

My current crazy model:

```<code>class User extends Authenticatable {
    public function field($field){
        $field=DataType::where('field',$field)->first();
        return $this->hasMany('App\UserData')->where('datatype_id',(isset($field->id) ? $field->id : 0));
    }
}
</code>```

Of course it works fine when I have to find values:

```<code>auth()->user()->field('mobile_phone')->get();
</code>```

But how do I set or update a new mobile phone?

答:
Another approach is link User and DataTypes as a many to many relationship and use a scope to handle it.

First of all, change UserData table to dataTypeUser, so you could use default eloquent relationships.
In any model put the belongsToMany relationship.
User Model

```<code>public function dataTypes()
    {
        return $this->belongsToMany('App\DataType')
            ->withPivot(['value']);
    }

public function scopeField($query, $field)
    {
       return $query->whith(['dataTypes'=>function($q)use($field){
                  $q->where('data_types.field',$field);
              }]);
    }

</code>```

DataType Model

```<code>public function users()
    {
        return $this->belongsToMany('App\User')
            ->withPivot(['value']);
    }
</code>```

To get some value you can use $field = $user->field('something')->first() to save new data could use $user->field('something')->updateExistingPivot($field->id,['value'=>$newValue]).

Anyway, if you don't have many data of same type attached to your user (more than one phone number for example), it could be a better approach to use one single table extending user migration, or at last an userData with columns for each datatype. In small applications you have no problems but as your application grows performance will be a problem with many tables and many relationships.

To avoid a long declaration, you could overwrite magic methods __get and __set. Both are declared in Illuminate\Database\Eloquent\Model so put in your User Model:

```<code>public function __get($key)
    {
        return $this->getAttribute($key) ?? $this->getAttributesFromPivot($key);
    }

    public function __set($key, $value)
    {
        if(in_array($key,array_keys($this->original)))
            $this->setAttribute($key, $value);
        else
            $this->setAttributeFromPivot($key, $value);
    }

    public function setAttributeFromPivot($key, $value)
    {
        $this->dataTypes()->where('field',$key)->update(['value'=>$value]);
    }

    protected function getAttributesFromPivot($key)
    {
        return $this->dataTypes()
            ->where('field',$key)
                // use this to get only one value direct
                ->first()->pivot->value ?? null;
                // or use this to get all of them as array
//                ->get()
//                ->map(function($item){ return $item->pivot->value;}) ?? null;

    }
</code>```

In this approach, you could use $user->city to get field city or another one replacing ->city. Or you could use $user->address = 'foo'; to set a new value in pivot table. Note that it will update database directly.

Now, if you are not comfortable to overwrite those methods, you don't need to. Change the signatures of setAttributeFromPivot and getAttributeFromPivot to public function getField($key) and public function setField($key, $value). Now you can use them as common methods.

Body:
Here my tables, User is the classic Auth table:

DataTypes

+----+--------------+
| id |    field     |
+----+--------------+
|  1 | address      |
|  2 | mobile_phone |
|  3 | city         |
+----+--------------+

UserData

+----+----------+--------------+---------+
| id |  value   | data_type_id | user_id |
+----+----------+--------------+---------+
|  1 | Milan    |            3 |       1 |
|  2 | 99123233 |            2 |       1 |
+----+----------+--------------+---------+

My current crazy model:

class User extends Authenticatable {
    public function field($field){
        $field=DataType::where('field',$field)->first();
        return $this->hasMany('App\UserData')->where('datatype_id',(isset($field->id) ? $field->id : 0));
    }
}

Of course it works fine when I have to find values:

auth()->user()->field('mobile_phone')->get();

But how do I set or update a new mobile phone?

Body:
Another approach is link User and DataTypes as a many to many relationship and use a scope to handle it.

First of all, change UserData table to dataTypeUser, so you could use default eloquent relationships.
In any model put the belongsToMany relationship.
User Model

public function dataTypes()
    {
        return $this->belongsToMany('App\DataType')
            ->withPivot(['value']);
    }

public function scopeField($query, $field)
    {
       return $query->whith(['dataTypes'=>function($q)use($field){
                  $q->where('data_types.field',$field);
              }]);
    }

DataType Model

public function users()
    {
        return $this->belongsToMany('App\User')
            ->withPivot(['value']);
    }

To get some value you can use $field = $user->field('something')->first() to save new data could use $user->field('something')->updateExistingPivot($field->id,['value'=>$newValue]).

Anyway, if you don't have many data of same type attached to your user (more than one phone number for example), it could be a better approach to use one single table extending user migration, or at last an userData with columns for each datatype. In small applications you have no problems but as your application grows performance will be a problem with many tables and many relationships.

To avoid a long declaration, you could overwrite magic methods __get and __set. Both are declared in Illuminate\Database\Eloquent\Model so put in your User Model:

public function __get($key)
    {
        return $this->getAttribute($key) ?? $this->getAttributesFromPivot($key);
    }

    public function __set($key, $value)
    {
        if(in_array($key,array_keys($this->original)))
            $this->setAttribute($key, $value);
        else
            $this->setAttributeFromPivot($key, $value);
    }

    public function setAttributeFromPivot($key, $value)
    {
        $this->dataTypes()->where('field',$key)->update(['value'=>$value]);
    }

    protected function getAttributesFromPivot($key)
    {
        return $this->dataTypes()
            ->where('field',$key)
                // use this to get only one value direct
                ->first()->pivot->value ?? null;
                // or use this to get all of them as array
//                ->get()
//                ->map(function($item){ return $item->pivot->value;}) ?? null;

    }

In this approach, you could use $user->city to get field city or another one replacing ->city. Or you could use $user->address = 'foo'; to set a new value in pivot table. Note that it will update database directly.

Now, if you are not comfortable to overwrite those methods, you don't need to. Change the signatures of setAttributeFromPivot and getAttributeFromPivot to public function getField($key) and public function setField($key, $value). Now you can use them as common methods.


问:
How to shift elements after adding in Doubly Linked List
I have added an element to a specified position in a Doubly Linked List, but I want to shift all the elements that was at that position and after it to the right? Any tips on how to approach this problem?</p>

```<code>public void addFirst(E e){
    DNode<E> headerNext = header.getNext();
    DNode<E> tempN = new DNode <E>(e, header, headerNext);
    headerNext.setPrev(tempN);
    header.setNext(tempN);
    size++;
}
public void add(int pos , E e ){
    DNode<E> ptr = new DNode<E> (e, null, null);
        if(pos == 1){
            addFirst(e);
            return;
        }
    DNode<E> optr = header;
    for (int i = 2; i <= size; i++) {
        if (i == pos) {
            DNode<E> tempN = optr.getNext();
            ptr.setNext(ptr);
            ptr.setPrev(optr);
            ptr.setPrev(tempN);
            tempN.setPrev(ptr);
        }
        ptr = ptr.getNext();
    }
    size++ ;
}
    }
</code>```

答:
Any tips on how to approach this problem?

Since you asked for tips on how to get started and you already have a doubly linked list here is a simple example.

Given the following is a Node in a Doubly Linked List.

```<code>// Doubly Linked list Node
class Node {
    int data;
    Node prev;
    Node next;

    // Constructor to create a new node
    // next and prev is by default initialized as null
    Node(int d) { data = d; }
}
</code>```

The following method can be implemented for your doubly linked list. You would provide a Node that would have a new Node inserted after the Node that you provide and the next and prev pointers for the current Node and the newly added Node would all be updated to reflect the newly added Node.

```<code>/* Given a node (currentnode). insert a new node after the given
  node(currentNode) */
public void InsertAfterNode(Node currentNode, int newData)
{

// check if the given current node is NULL
if (currentNode == null) {
    System.out.println("The given current node cannot be NULL ");
    return;
}

//  allocate node
//  put in the data
Node new_node = new Node(newData);

//  Make next of new node as next of current node
new_node.next = currentNode.next;

//  Make the next of current node as new_node
currentNode.next = new_node;

//  Make current node as previous of new_node
new_node.prev = currentNode;

//  Change previous of new_node's next node
if (new_node.next != null)
    new_node.next.prev = new_node;
}
</code>```

You could implement a similar method, in reverse, to insert a new Node before the specific Node.

Body:
I have added an element to a specified position in a Doubly Linked List, but I want to shift all the elements that was at that position and after it to the right? Any tips on how to approach this problem?

public void addFirst(E e){
    DNode<E> headerNext = header.getNext();
    DNode<E> tempN = new DNode <E>(e, header, headerNext);
    headerNext.setPrev(tempN);
    header.setNext(tempN);
    size++;
}
public void add(int pos , E e ){
    DNode<E> ptr = new DNode<E> (e, null, null);
        if(pos == 1){
            addFirst(e);
            return;
        }
    DNode<E> optr = header;
    for (int i = 2; i <= size; i++) {
        if (i == pos) {
            DNode<E> tempN = optr.getNext();
            ptr.setNext(ptr);
            ptr.setPrev(optr);
            ptr.setPrev(tempN);
            tempN.setPrev(ptr);
        }
        ptr = ptr.getNext();
    }
    size++ ;
}
    }

Body:
Any tips on how to approach this problem?

Since you asked for tips on how to get started and you already have a doubly linked list here is a simple example.

Given the following is a Node in a Doubly Linked List.

// Doubly Linked list Node
class Node {
    int data;
    Node prev;
    Node next;

    // Constructor to create a new node
    // next and prev is by default initialized as null
    Node(int d) { data = d; }
}

The following method can be implemented for your doubly linked list. You would provide a Node that would have a new Node inserted after the Node that you provide and the next and prev pointers for the current Node and the newly added Node would all be updated to reflect the newly added Node.

/* Given a node (currentnode). insert a new node after the given
  node(currentNode) */
public void InsertAfterNode(Node currentNode, int newData)
{

// check if the given current node is NULL
if (currentNode == null) {
    System.out.println("The given current node cannot be NULL ");
    return;
}

//  allocate node
//  put in the data
Node new_node = new Node(newData);

//  Make next of new node as next of current node
new_node.next = currentNode.next;

//  Make the next of current node as new_node
currentNode.next = new_node;

//  Make current node as previous of new_node
new_node.prev = currentNode;

//  Change previous of new_node's next node
if (new_node.next != null)
    new_node.next.prev = new_node;
}

You could implement a similar method, in reverse, to insert a new Node before the specific Node.


问:
Matching UITableView and UIViewController background colours
I have a UITableView in a UIViewController. I'm trying to set both backgrounds to the same colour but despite both background having identical RGB values, they end up displaying a slight mismatch - see image below.

I have tried setting the UITableView background colour to clear as well but this has no effect either.

Any ideas why this might be occurring?

答:
Make sure to set the background color of tableView like below

I would also recommend you to debug via Debug View Hierarchy in XCode to see which view has what color.


问:
Where can I learn ffmpeg?
I really want to get more into video/audio encoding and decoding, and I’ve heard that ffmpeg is a good tool, but I can’t find any good tutorials for it. Does anyone know a good way to learn it?</p>

答:
Official Sources

Resources

FFmpeg Documentation - Start here.

FFmpeg Wiki - Has many articles to supplement the documentation.

FFmpeg Twitter - Provides occasional, random tips.

Doxygen - Library and API documentation

doc/examples in the FFmpeg source code

Help

#ffmpeg IRC channel on Freenode

ffmpeg-user mailing list for help using the command-line tools (ffmpeg, ffprobe, ffplay)

libav-user mailing list for help using the libraries (libavcodec, libavformat, etc)

Development

See FFmpeg Developer Documentation, hang out in the #ffmpeg-devel IRC channel, and subscribe to the ffmpeg-devel mailing list.

Stack Exchange

Stack Overflow, Super User, and Video.SE all have many ffmpeg usage questions. Searching these sites probably already have the answer you're looking for.

You can use the search bar with the ffmpeg tag, such as:

```<code>[ffmpeg] adding silent audio
</code>```

reddit

There is an active subreddit at r/ffmpeg.

Title: Where can I learn ffmpeg?

Body:
Official Sources

Resources

FFmpeg Documentation - Start here.

FFmpeg Wiki - Has many articles to supplement the documentation.

FFmpeg Twitter - Provides occasional, random tips.

Doxygen - Library and API documentation

doc/examples in the FFmpeg source code

Help

#ffmpeg IRC channel on Freenode

ffmpeg-user mailing list for help using the command-line tools (ffmpeg, ffprobe, ffplay)

libav-user mailing list for help using the libraries (libavcodec, libavformat, etc)

Development

See FFmpeg Developer Documentation, hang out in the #ffmpeg-devel IRC channel, and subscribe to the ffmpeg-devel mailing list.

Stack Exchange

Stack Overflow, Super User, and Video.SE all have many ffmpeg usage questions. Searching these sites probably already have the answer you're looking for.

You can use the search bar with the ffmpeg tag, such as:

[ffmpeg] adding silent audio

reddit

There is an active subreddit at r/ffmpeg.


问:
Using Circe to decode Json String
I have a Json string as

```<code>val configInfo =   {
      "car": {
        "requesters": {
          "request1": "key1",
          "request2": "key2"
        },
        "provider": {
          "request1": "key3",
          "request2": "key4"
        }
      },
      "truck": {
        "requesters": {
          "request1": "key2",
          "request2": "key3"
        },
        "provider": {
          "request1": "key2",
          "request2": "key3"
        }
      }
    }
</code>```

I have the following case class to decode json string.

```<code>final case class TenantSettings(requesters: Map[String, String], provider: Map[String, String] = Map.empty)
</code>```

Also, providers in above case class is optional, it may or may not be present in json string.

I want to decode this using circe to

```<code>val value = decode[Map[String, TenantSettings]](configInfo)
</code>```

I understand I need to use custom circe codec, but I am unable to do it, Can someone please help out on this.

答:
Circe provides all Decoder instances you need except the one for TenantSettings since it's a custom type. Map and String are no problem.

circe-generic-extras or circe-derivation are very useful to generate Decoder instances for case classes. In this case you want to enable "defaults" in the config, so it falls back to the empty map instead of failing.

Here's the code:

// you need circe-core, circe-parser and circe-generic-extras as dependencies
import io.circe._
import io.circe.parser.decode
import io.circe.generic.extras.Configuration
import io.circe.generic.extras.semiauto._

val configInfo = """{
    "car": {
      "requesters": {
        "request1": "key1",
        "request2": "key2"
      },
      "provider": {
        "request1": "key3",
        "request2": "key4"
      }
    },
    "truck": {
      "requesters": {
        "request1": "key2",
        "request2": "key3"
      },
      "provider": {
        "request1": "key2",
        "request2": "key3"
      }
    }
  }
  """

final case class TenantSettings(
  requesters: Map[String, String],
  provider: Map[String, String] = Map.empty
)
object TenantSettings {
  implicit private val derivationConfig: Configuration = Configuration.default.withDefaults

  implicit val decodeTenantSettings: Decoder[TenantSettings] = deriveConfiguredDecoder
}

val value = decode[Map[String, TenantSettings]](configInfo)
println(value) // Right(Map(car -> TenantSettings(Map(request1 -> key1, request2 -> ...
```

Title: Using Circe to decode Json String

Body:
I have a Json string as

val configInfo =   {
      "car": {
        "requesters": {
          "request1": "key1",
          "request2": "key2"
        },
        "provider": {
          "request1": "key3",
          "request2": "key4"
        }
      },
      "truck": {
        "requesters": {
          "request1": "key2",
          "request2": "key3"
        },
        "provider": {
          "request1": "key2",
          "request2": "key3"
        }
      }
    }

I have the following case class to decode json string.

final case class TenantSettings(requesters: Map[String, String], provider: Map[String, String] = Map.empty)

Also, providers in above case class is optional, it may or may not be present in json string.

I want to decode this using circe to

val value = decode[Map[String, TenantSettings]](configInfo)

I understand I need to use custom circe codec, but I am unable to do it, Can someone please help out on this.


问:
MS Access Dropdown List/Combo Box
This should probably be pretty simple but my Google-Fu is as yet unable to find an answer. I simply want to create a dropdown list in Access so that upon selection I can perform some action based on the value of the selection. For instance, I have a list of people and I would like to populate the combo box so that their names appear in the list but the "value" is set to their ID (the primary key).</p>

答:
How have you set the properties for your combo box?

Perhaps you could try setting (assuming you are pulling data from Table1 with fields ID and Field1

Row Source: SELECT [Table1].[ID], [Table1].[Field1] FROM Table1;

Row Source Type: Table/Query

Bound Column: 1

Column Count: 2

Column Widths: 0", 1"

and then hook into the onchange event as Chris Ballance suggests.  The value property of the combo box is ID; the text will be what is in Field1.

OwnerDisplayName: noblethrasher

Title: MS Access Dropdown List/Combo Box

LastEditorDisplayName: Chris Ballance

OwnerDisplayName: Azim


问:
How to customize error message on Siri intent response of type `failureRequiringAppLaunch`
I'm adding a Siri intent to my app for it to be used within the Shortcuts app. The user needs to be logged in in order to use the intent. When he is not, I send a failure completion with the code .failureRequiringAppLaunch.

For classic errors, ie not needing the app to be launched, I added a String property to customize the error message for the user.

Unfortunately, when I call the completion with the .failureRequiringAppLaunch code, the error message is not displayed, and the message "An unknown error occurred." is displayed to the user:

Here is my code:

```<code>let intentResponse = AllMeetingsIntentResponse(code: .failureRequiringAppLaunch, userActivity: nil)
intentResponse.failureReason = "You must log in to use this function."
return intentResponse
</code>```

So if someone is able to tell me how I can customize the "app launch" alert, thanks in advance.

答:
You can customize your error message by doing the following:

```<code>let response = AllMeetingsIntentResponse.failure(failureReason: "Fail because Bla bla bla")
completion(response)
</code>```

I hope it helped you

Body:
I'm adding a Siri intent to my app for it to be used within the Shortcuts app. The user needs to be logged in in order to use the intent. When he is not, I send a failure completion with the code .failureRequiringAppLaunch.

For classic errors, ie not needing the app to be launched, I added a String property to customize the error message for the user.

Unfortunately, when I call the completion with the .failureRequiringAppLaunch code, the error message is not displayed, and the message "An unknown error occurred." is displayed to the user:

Here is my code:

let intentResponse = AllMeetingsIntentResponse(code: .failureRequiringAppLaunch, userActivity: nil)
intentResponse.failureReason = "You must log in to use this function."
return intentResponse

So if someone is able to tell me how I can customize the "app launch" alert, thanks in advance.

Body:
You can customize your error message by doing the following:

let response = AllMeetingsIntentResponse.failure(failureReason: "Fail because Bla bla bla")
completion(response)

I hope it helped you


问:
how to save parent object containing child object using spring boot in @ManyToOne unidirectional mapping?
I am new in spring boot. I've two model classes Party(parent) and PartyCategory(child). PartyCategory stores data id, labelAr and labelEn successfully.

Now I am passing child id in json request and getting null values for labelAr and labelEn in json response as pasted below. Can someone please help what and doing wrong here.

I've pasted my code as well.

Json Request:

```<code>{

    "name": "Party A",
    "description": "Description of Party A",
    "category": {
        "id": 1
    }
}
</code>```

Json response;

```<code>{
    "id": 6,
    "name": "Party A",
    "description": "Description of Party A",
    "category": {
        "id": 1,
        "labelAr": null,
        "labelEn": null
    }
}
</code>```

Party.java:

```<code>   public class Party {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;
        private String name;
        private String description;
        @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
        @JoinColumn(name = "category_id")
        private PartyCategory category;

        ....setters and getters
   }
</code>```

PartyCategory.java:-

```<code>public class PartyCategory {

    @Id
    @GeneratedValue
    private Integer id;
    private String labelAr;
    private String labelEn;

    ...setters and getters..
</code>```

Repositories:

```<code>public interface PartyCategoryRepository extends JpaRepository<PartyCategory, Integer> {

}

public interface PartyRepository extends JpaRepository<Party, Integer> {

}
</code>```

Services:

```<code>public class PartyServiceImpl {
    @Autowired
    PartyRepository partyRepository;

public Party saveParty(Party party) {

        return partyRepository.save(party);
    }
</code>```

Controller:

```<code>@RestController
public class PartyController {

    @Autowired
    PartyServiceImpl partyServiceIml;

    @PostMapping(value = "/party/save")
    public Party saveParty(@RequestBody Party party ) {
        Party returnedParty = partyServiceIml.saveParty(party);
        return returnedParty;
    }
}
</code>```

答:
The problem is that the category you are posting is not recognised as being an existing category.

You can then do something like the below. Firstly, Create a Jackson converter class to customise the Json deserialisation. I was not sure if these were Spring managed but they are so you can then inject the necessary repository.

```<code>import com.fasterxml.jackson.databind.util.StdConverter;

@Component
public class CategoryConverter extends StdConverter<Integer, PartyCategory> {

    @Autowired
    private PartyCategoryRepository repo;

    @Override
    public PartyCategory convert(Integer value) {
        return repo.findById(value).get();
    }
}
</code>```

Then update your entity as follows so that the category Json property will be handled via the converter created above. Note that in reality I would use a Jackson mix-in to apply this custom deserializer as this would avoid 'polluting' the entity class with Json processing instructions. You can look up how to do that.

```<code>@Entity
public class Party {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;

    private String description;

    @ManyToOne
    @JoinColumn(name = "category_id")
    @JsonDeserialize(converter = CategoryConverter.class) //in real life use a 'mix-in'
    private PartyCategory category;
}
</code>```

Then you can post JSON as below where we simply specify the id of an existing category:

```<code>{

    "name": "Party A",
    "description": "Description of Party A",
    "category": 1
}
</code>```

By enhancing this solution to use mix-ins as suggested then it is possible then to cleanly separate the view model from the entity model without having to create a DTO layer which will typically largely duplicate the entity model and which will required tedious mapping code to handle the conversions.

Body:
I am new in spring boot. I've two model classes Party(parent) and PartyCategory(child). PartyCategory stores data id, labelAr and labelEn successfully.

Now I am passing child id in json request and getting null values for labelAr and labelEn in json response as pasted below. Can someone please help what and doing wrong here.

I've pasted my code as well.

Json Request:

{

    "name": "Party A",
    "description": "Description of Party A",
    "category": {
        "id": 1
    }
}

Json response;

{
    "id": 6,
    "name": "Party A",
    "description": "Description of Party A",
    "category": {
        "id": 1,
        "labelAr": null,
        "labelEn": null
    }
}

Party.java:

   public class Party {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;
        private String name;
        private String description;
        @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
        @JoinColumn(name = "category_id")
        private PartyCategory category;

        ....setters and getters
   }

PartyCategory.java:-

public class PartyCategory {

    @Id
    @GeneratedValue
    private Integer id;
    private String labelAr;
    private String labelEn;

    ...setters and getters..

Repositories:

public interface PartyCategoryRepository extends JpaRepository<PartyCategory, Integer> {

}

public interface PartyRepository extends JpaRepository<Party, Integer> {

}

Services:

public class PartyServiceImpl {
    @Autowired
    PartyRepository partyRepository;

public Party saveParty(Party party) {

        return partyRepository.save(party);
    }

Controller:

@RestController
public class PartyController {

    @Autowired
    PartyServiceImpl partyServiceIml;

    @PostMapping(value = "/party/save")
    public Party saveParty(@RequestBody Party party ) {
        Party returnedParty = partyServiceIml.saveParty(party);
        return returnedParty;
    }
}

Body:
The problem is that the category you are posting is not recognised as being an existing category.

You can then do something like the below. Firstly, Create a Jackson converter class to customise the Json deserialisation. I was not sure if these were Spring managed but they are so you can then inject the necessary repository.

import com.fasterxml.jackson.databind.util.StdConverter;

@Component
public class CategoryConverter extends StdConverter<Integer, PartyCategory> {

    @Autowired
    private PartyCategoryRepository repo;

    @Override
    public PartyCategory convert(Integer value) {
        return repo.findById(value).get();
    }
}

Then update your entity as follows so that the category Json property will be handled via the converter created above. Note that in reality I would use a Jackson mix-in to apply this custom deserializer as this would avoid 'polluting' the entity class with Json processing instructions. You can look up how to do that.

@Entity
public class Party {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;

    private String description;

    @ManyToOne
    @JoinColumn(name = "category_id")
    @JsonDeserialize(converter = CategoryConverter.class) //in real life use a 'mix-in'
    private PartyCategory category;
}

Then you can post JSON as below where we simply specify the id of an existing category:

{

    "name": "Party A",
    "description": "Description of Party A",
    "category": 1
}

By enhancing this solution to use mix-ins as suggested then it is possible then to cleanly separate the view model from the entity model without having to create a DTO layer which will typically largely duplicate the entity model and which will required tedious mapping code to handle the conversions.


问:
Kubernetes load balancer External IP pending
I create RabbitMQ cluster inside Kubernetes. I am trying to add loadbalancer. But I cant get the loadbalancer External-IP it is still pending.

```<code>apiVersion: v1
kind: Service
metadata:
  name: rabbitmq
  labels:
    run: rabbitmq
spec:
  type: NodePort
  ports:
  - port: 5672
    protocol: TCP
    name: mqtt
  - port: 15672
    protocol: TCP
    name: ui
  selector:
    run: rabbitmq
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rabbitmq
spec:
  replicas: 1
  selector:
    matchLabels:
      run: rabbitmq
  template:
    metadata:
      labels:
        run: rabbitmq
    spec:
      containers:
      - name: rabbitmq
        image: rabbitmq:latest
        imagePullPolicy: Always
</code>```

And My load balancer is below. I gave loadbalancer
nodePort is random,
port number is from kubernetes created RabbitMQ mqtt port number,
target port number is from kubernetes created RabbitMQ UI port number

```<code>apiVersion: v1
kind: Service
metadata:
  name: loadbalanceservice
  labels:
    app: rabbitmq
spec:
  selector:
    app: rabbitmq
  type: LoadBalancer
  ports:
  - nodePort: 31022
    port: 30601
    targetPort: 31533
</code>```

答:
LoadBalancer service doesn't work on bare metal clusters. Your LoadBalancer service will act as NodePort service as well. You can use nodeIP:nodePort combination to access your service from outside the cluster.

If you do want an external IP with custom port combination to access your service, then look into metallb which implements support for LoadBalancer type services on bare metal clusters.

Body:
I create RabbitMQ cluster inside Kubernetes. I am trying to add loadbalancer. But I cant get the loadbalancer External-IP it is still pending.

apiVersion: v1
kind: Service
metadata:
  name: rabbitmq
  labels:
    run: rabbitmq
spec:
  type: NodePort
  ports:
  - port: 5672
    protocol: TCP
    name: mqtt
  - port: 15672
    protocol: TCP
    name: ui
  selector:
    run: rabbitmq
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rabbitmq
spec:
  replicas: 1
  selector:
    matchLabels:
      run: rabbitmq
  template:
    metadata:
      labels:
        run: rabbitmq
    spec:
      containers:
      - name: rabbitmq
        image: rabbitmq:latest
        imagePullPolicy: Always

And My load balancer is below. I gave loadbalancer
nodePort is random,
port number is from kubernetes created RabbitMQ mqtt port number,
target port number is from kubernetes created RabbitMQ UI port number

apiVersion: v1
kind: Service
metadata:
  name: loadbalanceservice
  labels:
    app: rabbitmq
spec:
  selector:
    app: rabbitmq
  type: LoadBalancer
  ports:
  - nodePort: 31022
    port: 30601
    targetPort: 31533


问:
Position of button using Vue.js
It's been awhile since I have been coding but I was wondering how do I position my Login button at the bottom centre of the screen and have the image displayed over it? Thanks

Code:

```<code><template>

    <div class="container-fluid">
      <img alt="Sportly logo" src="~@/assets/sportly.png">
        <div class="row">
            <div class="col-md-6">
                <h3>Login</h3>
                <button class="btn btn-primary"
                    @click="signIn">
                    <i class="fa fa-twitter"></i>
                    Sign In with Twitter
                </button>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    methods: {
        signIn () {
            this.$store.dispatch('signIn')
        }
    }
}
</script>

<style scoped>
h3 {
    font-weight: 700;
}
button {
    background-color: #1dcaff;
    border: 1px solid  #1dcaff;
    positioning: absolute;
bottom: 0px;

}
div button:hover {
    background-color: #00aced;
    border: 1px solid  #00aced;
}
</style>
</code>```

答: Your problem is class col-md-6. In your case it has style: {width: 50%}. You neen another class that suits your case

Title: Position of button using Vue.js

Body:
It's been awhile since I have been coding but I was wondering how do I position my Login button at the bottom centre of the screen and have the image displayed over it? Thanks

Code:

<template>

Login

                <button class="btn btn-primary"
                    @click="signIn">

                    Sign In with Twitter
                </button>

</template>


问:
How to return matches and non matches when comparing two ranges/arrays
I'm attempting to return a count of the total number of matching and non-matching entries in a set of two ranges.

I'm trying to avoid looping over the array twice like this:

```<code>#expected output:
#inside: 421 | outside: 55

constant_range = 240..960
sample_range   = 540..1015
sample_range_a = sample_range.to_a

def generate_range
  inside = sample_range_a.select { |val| constant_range.include?(val) }.count
  outside = sample_range_a.select { |val| !constant_range.include?(val) }.count
end

# I was thinking of a counter, but thought that would be even more ineffective
def generate_range
  a = 0
  b = 0
  sample_range_a.select { |val| constant_range.include?(val) ? a++ : b++ }
end
</code>```

答:
```<code>constant_range = (240..960).to_a

sample_range   = (540..1015).to_a

inside_count = (sample_range & constant_range).count #inside: 421

outside_count = sample_range.count - inside_count #outside: 55
</code>```

Body:
I'm attempting to return a count of the total number of matching and non-matching entries in a set of two ranges.

I'm trying to avoid looping over the array twice like this:

#expected output:
#inside: 421 | outside: 55

constant_range = 240..960
sample_range   = 540..1015
sample_range_a = sample_range.to_a

def generate_range
  inside = sample_range_a.select { |val| constant_range.include?(val) }.count
  outside = sample_range_a.select { |val| !constant_range.include?(val) }.count
end

# I was thinking of a counter, but thought that would be even more ineffective
def generate_range
  a = 0
  b = 0
  sample_range_a.select { |val| constant_range.include?(val) ? a++ : b++ }
end


问:
Is there a way to configure separate serviceCredentialsFile for each Android build variant with Firebase App Distribution?
We have several Firebase projects which share the same code base via build types and flavors. We aim to use the app distribution via Gradle and authenticate using service account credentials.

In the docs, it is shown that firebaseAppDistribution block can be used to configure the parameters and the service credential file path is one of them. Since each variant is a Firebase project and each project has its own service credentials, as far as I can understand we need to point to separate service credential file paths in the Gradle configuration.

I've tried to update the file path with a gradle task depending on the variant but couldn't make it work. The current build file looks like:

```<code>...

apply plugin: 'com.google.firebase.appdistribution'

class StringExtension {
  String value

  StringExtension(String value) {
    this.value = value
  }

  public void setValue(String value) {
    this.value = value
  }

  public String getValue() {
    return value
  }
}

android {

  ...

  productFlavors.whenObjectAdded {
    flavor -> flavor.extensions.create("service_key_prefix", StringExtension, '')
  }

  productFlavors {

    flavor1 {
      ...
      service_key_prefix.value = "flavor1"
    }

    flavor2 {
      ...
      service_key_prefix.value = "flavor2"
    }
  }

  buildTypes {

    debug {
      firebaseAppDistribution {
        releaseNotesFile = file("internal_release_notes.txt").path
        groupsFile = file("group_aliases_debug_fb.txt").path
      }
    }

    release {
      firebaseAppDistribution {
        releaseNotesFile = file("release_notes.txt").path
        groupsFile = file("group_aliases_prod_fb.txt").path
      }
    }
  }
}

...

android.applicationVariants.all { variant ->

  task("firebaseCredentials${variant.name.capitalize()}", overwrite: true) {
    variant.productFlavors.each { flavor ->

      doLast {
        firebaseAppDistribution {

          def serviceKeyFile = file(
              "../${flavor.service_key_prefix.value}-${variant.buildType.name}-service-key.json")
          if (serviceKeyFile != null) {
            serviceCredentialsFile = serviceKeyFile.path
          }
        }
      }
    }
  }
}

android.applicationVariants.all { variant ->
  def distTask = tasks.named("appDistributionUpload${variant.name.capitalize()}")
  def configTask = tasks.named("firebaseCredentials${variant.name.capitalize()}")
  distTask.configure {
    dependsOn(configTask)
  }
}

apply plugin: 'com.google.gms.google-services'
</code>```

The tasks seem to run correctly but I guess the file path is not updated because it still gives the following error when I run appDistributionUpload :

Could not find credentials. To authenticate, you have a few options:

Set the serviceCredentialsFile property in your gradle plugin

Set a refresh token with the FIREBASE_TOKEN environment variable

Log in with the Firebase CLI

Set service credentials with the GOOGLE_APPLICATION_CREDENTIALS environment variable

Any ideas on how to achieve such distribution configuration?

答:
After contacting the support team, I've learned  that this configuration is not available yet out of the box and exists as a feature request as of now.

Here is the workaround from the Firebase support team, which modifies the related environment variable in memory at the beginning of each upload task:

```<code>android {

  applicationVariants.all { variant ->

    final uploadTaskName = "appDistributionUpload${variant.name.capitalize()}"
    final uploadTask = project.tasks.findByName(uploadTaskName)

    if (uploadTask != null) {
      uploadTask.doFirst {
        resetCredentialsCache()
        final value = "$projectDir/src/${variant.name}/app-distribution-key.json"
        setEnvInMemory('GOOGLE_APPLICATION_CREDENTIALS', value)
      }
    }
  }
}

private static void setEnvInMemory(String name, String val) {
  // There is no way to dynamically set environment params, but we can update it in memory
  final env = System.getenv()
  final field = env.getClass().getDeclaredField("m")
  field.setAccessible(true)
  field.get(env).put(name, val)
}

private static void resetCredentialsCache() {
  // Google caches credentials provided by environment param, we are going to reset it
  final providerClass = Class.forName(
      'com.google.firebase.appdistribution.buildtools.reloc.com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider')
  final providerCtor = providerClass.getDeclaredConstructor()
  providerCtor.setAccessible(true)
  final provider = providerCtor.newInstance()

  final credsClass = Class.forName(
      'com.google.firebase.appdistribution.buildtools.reloc.com.google.api.client.googleapis.auth.oauth2.GoogleCredential')
  final field = credsClass.getDeclaredField('defaultCredentialProvider')
  field.setAccessible(true)
  field.set(null, provider)
}
</code>```

EDIT: The above solution works only for app distribution plugin version 1.3.1.

I didn't contact the support further and used GOOGLE_APPLICATION_CREDENTIALS environment variable on Jenkins CI, as explained here

Body:
We have several Firebase projects which share the same code base via build types and flavors. We aim to use the app distribution via Gradle and authenticate using service account credentials.

In the docs, it is shown that firebaseAppDistribution block can be used to configure the parameters and the service credential file path is one of them. Since each variant is a Firebase project and each project has its own service credentials, as far as I can understand we need to point to separate service credential file paths in the Gradle configuration.

I've tried to update the file path with a gradle task depending on the variant but couldn't make it work. The current build file looks like:

...

apply plugin: 'com.google.firebase.appdistribution'

class StringExtension {
  String value

  StringExtension(String value) {
    this.value = value
  }

  public void setValue(String value) {
    this.value = value
  }

  public String getValue() {
    return value
  }
}

android {

  ...

  productFlavors.whenObjectAdded {
    flavor -> flavor.extensions.create("service_key_prefix", StringExtension, '')
  }

  productFlavors {

    flavor1 {
      ...
      service_key_prefix.value = "flavor1"
    }

    flavor2 {
      ...
      service_key_prefix.value = "flavor2"
    }
  }

  buildTypes {

    debug {
      firebaseAppDistribution {
        releaseNotesFile = file("internal_release_notes.txt").path
        groupsFile = file("group_aliases_debug_fb.txt").path
      }
    }

    release {
      firebaseAppDistribution {
        releaseNotesFile = file("release_notes.txt").path
        groupsFile = file("group_aliases_prod_fb.txt").path
      }
    }
  }
}

...

android.applicationVariants.all { variant ->

  task("firebaseCredentials${variant.name.capitalize()}", overwrite: true) {
    variant.productFlavors.each { flavor ->

      doLast {
        firebaseAppDistribution {

          def serviceKeyFile = file(
              "../${flavor.service_key_prefix.value}-${variant.buildType.name}-service-key.json")
          if (serviceKeyFile != null) {
            serviceCredentialsFile = serviceKeyFile.path
          }
        }
      }
    }
  }
}

android.applicationVariants.all { variant ->
  def distTask = tasks.named("appDistributionUpload${variant.name.capitalize()}")
  def configTask = tasks.named("firebaseCredentials${variant.name.capitalize()}")
  distTask.configure {
    dependsOn(configTask)
  }
}

apply plugin: 'com.google.gms.google-services'

The tasks seem to run correctly but I guess the file path is not updated because it still gives the following error when I run appDistributionUpload :

Could not find credentials. To authenticate, you have a few options:

Set the serviceCredentialsFile property in your gradle plugin

Set a refresh token with the FIREBASE_TOKEN environment variable

Log in with the Firebase CLI

Set service credentials with the GOOGLE_APPLICATION_CREDENTIALS environment variable

Any ideas on how to achieve such distribution configuration?

Body:
After contacting the support team, I've learned  that this configuration is not available yet out of the box and exists as a feature request as of now.

Here is the workaround from the Firebase support team, which modifies the related environment variable in memory at the beginning of each upload task:

android {

  applicationVariants.all { variant ->

    final uploadTaskName = "appDistributionUpload${variant.name.capitalize()}"
    final uploadTask = project.tasks.findByName(uploadTaskName)

    if (uploadTask != null) {
      uploadTask.doFirst {
        resetCredentialsCache()
        final value = "$projectDir/src/${variant.name}/app-distribution-key.json"
        setEnvInMemory('GOOGLE_APPLICATION_CREDENTIALS', value)
      }
    }
  }
}

private static void setEnvInMemory(String name, String val) {
  // There is no way to dynamically set environment params, but we can update it in memory
  final env = System.getenv()
  final field = env.getClass().getDeclaredField("m")
  field.setAccessible(true)
  field.get(env).put(name, val)
}

private static void resetCredentialsCache() {
  // Google caches credentials provided by environment param, we are going to reset it
  final providerClass = Class.forName(
      'com.google.firebase.appdistribution.buildtools.reloc.com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider')
  final providerCtor = providerClass.getDeclaredConstructor()
  providerCtor.setAccessible(true)
  final provider = providerCtor.newInstance()

  final credsClass = Class.forName(
      'com.google.firebase.appdistribution.buildtools.reloc.com.google.api.client.googleapis.auth.oauth2.GoogleCredential')
  final field = credsClass.getDeclaredField('defaultCredentialProvider')
  field.setAccessible(true)
  field.set(null, provider)
}

EDIT: The above solution works only for app distribution plugin version 1.3.1.

I didn't contact the support further and used GOOGLE_APPLICATION_CREDENTIALS environment variable on Jenkins CI, as explained here


问:
what type of code will contain inside JVM?
I know the intenal architecture of the JVM upto some extent.

My question is: What kind of code internally contains in Runtime Areas (such as Heap area, Stack area, Method area, etc.) of JVM?

Whether these areas contain byte code or interpreter converted machine code?

答:
The stack and heap usually don't usually contain executable code: neither byte code nor native code. They contain data only (local variables and parameters on the stack, objects on the heap).

The method area contains internal control structures of the JVM. The information about loaded classes, methods, etc. This will probably contain the bytecode of each method. It can very well contain compiled (native) code of some methods (or smaller/larger parts) as well, that depends on what kind of optimizations the JVM does.


问:
Jquery toggle sidebar with 2 buttons
I am trying to create a toggle on a sidebar so that the toggle button opens the sidebar. This works great on desktop, however, if I am using mobile, the toggle button gets hidden. Is it possible to add a close button in the sidebar which can close the sidebar without breaking the script? The script I have is:</p>

```<code><div id="sidebar">content</div>
<div id="filter-icon">Refine Selection <div id="filterswitch"></div></div>
</code>```

```<code><script>
jQuery(document).ready(function() {
    jQuery("#filter-icon").click(function() {
        jQuery("#filterswitch").toggleClass('active');
        jQuery("#sidebar").toggleClass('show-sidebar');
    });
});
</script>
</code>```

答:
Shouldn't be a problem, have you tried something like this?</p>

```<code><div id="sidebar"><button id="closeSidebar">Close</button></div>
<div id="filter-icon">Refine Selection <div id="filterswitch"></div></div>

<script>
    const toggleSidebarAndSwitch = () => {
      jQuery("#filterswitch").toggleClass('active');
      jQuery("#sidebar").toggleClass('show-sidebar');
    }

    jQuery(document).ready(() => {
        jQuery("#filter-icon").click(() => {
          toggleSidebarAndSwitch()
        });
        jQuery("#closeSidebar").click(()=>{
          toggleSidebarAndSwitch()
        })
    });
    </script>
</code>```

Title: Jquery toggle sidebar with 2 buttons

Body:
I am trying to create a toggle on a sidebar so that the toggle button opens the sidebar. This works great on desktop, however, if I am using mobile, the toggle button gets hidden. Is it possible to add a close button in the sidebar which can close the sidebar without breaking the script? The script I have is:

content

Refine Selection

Body:
Shouldn't be a problem, have you tried something like this?

<div id="sidebar"><button id="closeSidebar">Close</button></div>
<div id="filter-icon">Refine Selection <div id="filterswitch"></div></div>

<script>
    const toggleSidebarAndSwitch = () => {
      jQuery("#filterswitch").toggleClass('active');
      jQuery("#sidebar").toggleClass('show-sidebar');
    }

    jQuery(document).ready(() => {
        jQuery("#filter-icon").click(() => {
          toggleSidebarAndSwitch()
        });
        jQuery("#closeSidebar").click(()=>{
          toggleSidebarAndSwitch()
        })
    });
    </script>


问:
RoR : serialized data in built response object
I'm building a Rails API, and I have this controller method that responds with a custom object:

```<code>class V1::AppInitController < ApplicationController
  def init
    json_response({
      user: UserSerializer.new(current_user, {}).as_json,
      categories: ActiveModel::Serializer::CollectionSerializer.new(Category.all, each_serializer: CategorySerializer).as_json,
      last_seen_products: current_user.last_seen_products
    })
  end
end
</code>```

Since I'm building a custom object here, I have to manually call the serializers if I want them to be applied.
Is it possible to configure my controllers so that serializers are applied automatically?

What I want in the end is being able to write my method this way, being automatically serialized:

```<code>class V1::AppInitController < ApplicationController
  def init
    json_response({
      user: current_user,
      categories: Category.all,
      last_seen_products: current_user.last_seen_products
    })
  end
end
</code>```

答:
modify your init method as below and try it.

```<code>class V1::AppInitController < ApplicationController
 def init
  json_response({
    user: UserSerializer(current_user),
    categories: CategorySerializer(Category.all),
    last_seen_products: current_user.last_seen_products
  })
 end
end
</code>```

I hope it's work for you.

Body:
I'm building a Rails API, and I have this controller method that responds with a custom object:

class V1::AppInitController < ApplicationController
  def init
    json_response({
      user: UserSerializer.new(current_user, {}).as_json,
      categories: ActiveModel::Serializer::CollectionSerializer.new(Category.all, each_serializer: CategorySerializer).as_json,
      last_seen_products: current_user.last_seen_products
    })
  end
end

Since I'm building a custom object here, I have to manually call the serializers if I want them to be applied.
Is it possible to configure my controllers so that serializers are applied automatically?

What I want in the end is being able to write my method this way, being automatically serialized:

class V1::AppInitController < ApplicationController
  def init
    json_response({
      user: current_user,
      categories: Category.all,
      last_seen_products: current_user.last_seen_products
    })
  end
end

Body:
modify your init method as below and try it.

class V1::AppInitController < ApplicationController
 def init
  json_response({
    user: UserSerializer(current_user),
    categories: CategorySerializer(Category.all),
    last_seen_products: current_user.last_seen_products
  })
 end
end

I hope it's work for you.


问:
querying mails without categories not supported
We are trying to use Microsoft graph to query a mailbox and return us all uncategorized mails.
Following the OData spec here: https://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part2-url-conventions/odata-v4.0-errata03-os-part2-url-conventions-complete.html#_Toc453752358

We should be able to do something like this:

$filter=Categories/$count eq 0

But the call returns an operation not supported exception.
Is there another way to query for uncategorized Mail messages?

答:
Querying mails without categories doesn't appear to be supported at this time. Please add a feature request to Microsoft Graph User Voice. I might as well share what I found in case it is useful to someone.

Unfortunately, the following doesn't work:

```<code>https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=not categories/any()&$select=categories
https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=categories/$count eq 0
</code>```

This will return all mail with categories:

```<code>https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=categories/any()&$select=categories
</code>```

This will return all mail of a particular category:

```<code>https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=categories/any(x:x eq 'particular category')&$select=categories
</code>```

Body:
Querying mails without categories doesn't appear to be supported at this time. Please add a feature request to Microsoft Graph User Voice. I might as well share what I found in case it is useful to someone.

Unfortunately, the following doesn't work:

https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=not categories/any()&$select=categories
https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=categories/$count eq 0

This will return all mail with categories:

https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=categories/any()&$select=categories

This will return all mail of a particular category:

https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=categories/any(x:x eq 'particular category')&$select=categories


问:
git pull added tons of untracked files and modified files
I am not very familiar with git as I just use it in the most basic manner. Lately I've been running into this strange behavior which makes no sense to me and causes a huge disturbance in my productivity. For certain branches when I run git pull instead of just getting the latest commits from the remote repository like I expect, I get an ENORMOUS list of modified/deleted/added files as well as an enormous list of untracked files. The branch I am pulling from is our team's master branch. I am just trying to keep my local copy of master in sync. What are these other untracked files showing up as well as these modified files? I didn't touch any of these other files.

What makes the problem worse is that I can't delete these untracked files or anything. I've tried `git clean -fx' and it only removes 3-4 files but still leaves hundreds. At this point I just want to get rid of all of these files, delete the branch, and pull the branch from remote again.

I tried doing the following:

git fetch --all
git reset --hard origin/<remote_branch_name>
```

but I received an error because Git couldn't create a symbolic link. I am using Git on Windows.

Why is git pull doing this, and what should I do?

EDIT: I was finally able to run the git reset command when I ran my prompt as an admin, but it still doesn't explain this weird git pull behavior.

答:
It seems to me that the 'git pull' action did not complete successfully.

It is possible that you modified some of the files as an admin, and when pulling as non-admin user git tries to modify or delete a file and has no permissions to it.

Therefore you stay in some half baked state.

What do you see when you run git status?
Is there any error in the git pull?

Body:
I am not very familiar with git as I just use it in the most basic manner. Lately I've been running into this strange behavior which makes no sense to me and causes a huge disturbance in my productivity. For certain branches when I run git pull instead of just getting the latest commits from the remote repository like I expect, I get an ENORMOUS list of modified/deleted/added files as well as an enormous list of untracked files. The branch I am pulling from is our team's master branch. I am just trying to keep my local copy of master in sync. What are these other untracked files showing up as well as these modified files? I didn't touch any of these other files.

What makes the problem worse is that I can't delete these untracked files or anything. I've tried `git clean -fx' and it only removes 3-4 files but still leaves hundreds. At this point I just want to get rid of all of these files, delete the branch, and pull the branch from remote again.

I tried doing the following:

git fetch --all
git reset --hard origin/<remote_branch_name>

but I received an error because Git couldn't create a symbolic link. I am using Git on Windows.

Why is git pull doing this, and what should I do?

EDIT: I was finally able to run the git reset command when I ran my prompt as an admin, but it still doesn't explain this weird git pull behavior.


问:
How can i make the sidebar responsive?
I have two problems in this code

The first one is  making the currentLocation component appears on top of the sidebar component

The second one is that the sidebar is not responsive(mobile first approach)

can anyone help me  please?

Code to codesandbox

答:
Here you go

currentLocation component appears on top of the sidebar component

The sidebar is now responsive (mobile first approach)

Notes: I have kept some of the colors and styles from your original it seems they were chosen to be those. It is set to hit a break points on small screens to go full width otherwise it takes 4 out of 12 columns of the screen. The class you would look for to change this is col-sm-4 Hope I was of help to you.

Happy coding!

Title: How can i make the sidebar responsive?


答:
To center an element try :

display:flex;
justify-content: center;

or
margin:0 auto;

but you need to change col-md-6 to col-md-12

Title: Position of button using Vue.js


问:
Convert a number column into a time format in Power BI
I'm looking for a way to convert a decimal number into a valid HH:mm:ss format.

I'm importing data from an SQL database.

One of the columns in my database is labelled Actual Start Time.

The values in my database are stored in the following decimal format:

```<code>73758    // which translates to 07:27:58
114436   // which translates to 11:44:36
</code>```

I cannot simply convert this Actual Start Time column into a Time format in my Power BI import as it returns errors for some values, saying it doesn't recognise 73758 as a valid 'time'. It needs to have a leading zero for cases such as 73758.

To combat this, I created a new Text column with the following code to append a leading zero:

```<code>Column = FORMAT([Actual Start Time], "000000")
</code>```

This returns the following results:

```<code>073758
114436
</code>```

-- which is perfect. Exactly what I needed.

I now want to convert these values into a Time.

Simply changing the data type field to Time doesn't do anything, returning:

Cannot convert value '073758' of type Text to type Date.

So I created another column with the following code:

```<code>Column 2 = FORMAT(TIME(LEFT([Column], 2), MID([Column], 3, 2), RIGHT([Column], 2)), "HH:mm:ss")
</code>```

To pass the values 07, 37 and 58 into a TIME format.

This returns the following:

```<code> _______________________________________
| Actual Start Date | Column | Column 2 |
|_______________________________________|
|       73758       | 073758 | 07:37:58 |
|       114436      | 114436 | 11:44:36 |

</code>```

Which is what I wanted but is there any other way of doing this? I want to ideally do it in one step without creating additional columns.

答:
You could use a variable as suggested by Aldert or you can replace Column by the format function:

```<code>Time Format = FORMAT(
                    TIME(
                        LEFT(FORMAT([Actual Start Time],"000000"),2),
                        MID(FORMAT([Actual Start Time],"000000"),3,2),
                        RIGHT([Actual Start Time],2)),
                "hh:mm:ss")
</code>```

Edit:

If you want to do this in Power query, you can create a customer column with the following calculation:

```<code>Time.FromText(
     if Text.Length([Actual Start Time])=5 then Text.PadStart( [Actual Start Time],6,"0")
     else [Actual Start Time])
</code>```

Once this column is created you can drop the old column, so that you only have one time column in the data. Hope this helps.

Body:
I'm looking for a way to convert a decimal number into a valid HH:mm:ss format.

I'm importing data from an SQL database.

One of the columns in my database is labelled Actual Start Time.

The values in my database are stored in the following decimal format:

73758    // which translates to 07:27:58
114436   // which translates to 11:44:36

I cannot simply convert this Actual Start Time column into a Time format in my Power BI import as it returns errors for some values, saying it doesn't recognise 73758 as a valid 'time'. It needs to have a leading zero for cases such as 73758.

To combat this, I created a new Text column with the following code to append a leading zero:

Column = FORMAT([Actual Start Time], "000000")

This returns the following results:

073758
114436

-- which is perfect. Exactly what I needed.

I now want to convert these values into a Time.

Simply changing the data type field to Time doesn't do anything, returning:

Cannot convert value '073758' of type Text to type Date.

So I created another column with the following code:

Column 2 = FORMAT(TIME(LEFT([Column], 2), MID([Column], 3, 2), RIGHT([Column], 2)), "HH:mm:ss")

To pass the values 07, 37 and 58 into a TIME format.

This returns the following:

 _______________________________________
| Actual Start Date | Column | Column 2 |
|_______________________________________|
|       73758       | 073758 | 07:37:58 |
|       114436      | 114436 | 11:44:36 |

Which is what I wanted but is there any other way of doing this? I want to ideally do it in one step without creating additional columns.

Body:
You could use a variable as suggested by Aldert or you can replace Column by the format function:

Time Format = FORMAT(
                    TIME(
                        LEFT(FORMAT([Actual Start Time],"000000"),2),
                        MID(FORMAT([Actual Start Time],"000000"),3,2),
                        RIGHT([Actual Start Time],2)),
                "hh:mm:ss")

Edit:

If you want to do this in Power query, you can create a customer column with the following calculation:

Time.FromText(
     if Text.Length([Actual Start Time])=5 then Text.PadStart( [Actual Start Time],6,"0")
     else [Actual Start Time])

Once this column is created you can drop the old column, so that you only have one time column in the data. Hope this helps.


答:
Yes it's possible just add another div in your sidebar like this:

```<code><div id="sidebar">
  content
  <div class="filterswitch"></div>
</div>
<div id="filter-icon">
  Refine Selection
  <div class="filterswitch"></div>
</div>
</code>```

If you ad the class filterswitch to both div's jQuery will automatically listen for clicks on both elements.

Title: Jquery toggle sidebar with 2 buttons

Body:
Yes it's possible just add another div in your sidebar like this:

<div id="sidebar">
  content
  <div class="filterswitch"></div>
</div>
<div id="filter-icon">
  Refine Selection
  <div class="filterswitch"></div>
</div>

If you ad the class filterswitch to both div's jQuery will automatically listen for clicks on both elements.


问:
what is the diff b/w pset and psetx in php redis?Is it possible set a array as value with it?
```<code>$redisClient -> setex('key', 3600, 'value' );
</code>```

and

```<code>$redisClient -> psetex('key', 3600, 'value' );
</code>```

答:
psetex is precise setex, meaning the units for the TTL are in milliseconds, not in seconds. See https://redis.io/commands/psetex

As value, you can set any binary-safe string. You can store an array serialized in your preferred format, like JSON or CSV, but every operation you do on the array you have to read in full and write back in full.

Consider the other data types in Redis: lists, sets, sorted sets, hash (maps). Chances are another data type is a better fit for your requirement. See https://redis.io/topics/data-types

You can always set an expiration on any type of key using EXPIRE or PEXPIRE.

Body:
$redisClient -> setex('key', 3600, 'value' );

and

$redisClient -> psetex('key', 3600, 'value' );


问:
How can I compile c++ to multiple files?
I have a program (cpp) with many classes. Every class is in separate source file (.h + .cpp).

How can I split the compiled program into multiple files (instead of one big executable file)?

Let's say, one file for every class (same as the code structure).

So that every time there is change in a specific class, I compile only that class, and replace the specific compiled file related to that class.

(Something similar to .DLL files in Windows.)

Example from real life:

I am making TUI interface for managing mysql.

I would like to create mysql text editor (TUI) with ncurses.

the code (class) for creating and managing single window object is in
'textWin.cpp' + 'textWin.h'

the code (class) for managing multiple windows, by creating windows objects from previous class is in winMan.cpp winMan.h

the code (class) for managing mysql database is in :
mysql.cpp mysql.h

and so on...

so, I have the following files:

MyProgram.cpp

- winMan.cpp + winMan.h

- textWin.cpp + textWin.h

- mysql.cpp + mysql.h

- ..

- ..

After g++ compilation, I get one executable file, './MyProgram' (size about 15Mb.) which I deliver to all my customers (1000's of them).

I Just found a typo in textWin.cpp, I fixed it, and I told to all customers that there is an update... all of them need to download one big 15Mb file, this consumes allot of bandwidth and server resources, for just a small update.

Is there a way to send to all my customers smaller file, that contains only the compiled code for textWin class ?

I use g++ on Centos7

答:
Of course, you could put your texts into separate text-files and only deploy those in the an error is there. For your special use case, where binary differences must be deployed, this question might be helpful: How do I create binary patches?

Another option, do proper versioning. That way, your customers might be able to decide for themselves. That is, if they need this update.


问:
Shadow effect is not displaying properly for UIView
I have a login screen as below. Around each text field I have added a view and for that view I want to display a drop shadow. I kind of achieved what I was trying but this thing is not working for iPhone Plus (6+,8+) devices.

You can see the difference below.

iPhone 8+:-

iPhone 8:-

Here is my code

```<code>extension UIView {
    func addShadow() {
        layer.cornerRadius = 8
        layer.masksToBounds = true

        layer.shadowColor = UIColor.lightGray.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 1.0)
        layer.shadowRadius = 2.0
        layer.shadowOpacity = 0.5
        layer.masksToBounds = false

        layer.shadowPath = UIBezierPath(roundedRect: self.bounds,cornerRadius:8).cgPath
    }
}
</code>```

How I can fix this properly?

答:
I'm sharing my approach that worked for me. I have used @clemens extension which is:

```<code>extension UIView {
    func addShadow() {
        layer.cornerRadius = 8
        layer.shadowColor = UIColor.lightGray.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 1.0)
        layer.shadowRadius = 2.0
        layer.shadowOpacity = 0.5
        layer.masksToBounds = false

        updateShadow()
    }

    func updateShadow() {
        layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 8).cgPath
    }
}
</code>```

However, it didn't work until this:

```<code>override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // Async is the key in this situation :)
    DispatchQueue.main.async { [weak self] in
        self?.someButton.addShadowNice()
        self?.someButton.updateShadow()
    }
}
</code>```

Cheers.

Body:
I have a login screen as below. Around each text field I have added a view and for that view I want to display a drop shadow. I kind of achieved what I was trying but this thing is not working for iPhone Plus (6+,8+) devices.

You can see the difference below.

iPhone 8+:-

iPhone 8:-

Here is my code

extension UIView {
    func addShadow() {
        layer.cornerRadius = 8
        layer.masksToBounds = true

        layer.shadowColor = UIColor.lightGray.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 1.0)
        layer.shadowRadius = 2.0
        layer.shadowOpacity = 0.5
        layer.masksToBounds = false

        layer.shadowPath = UIBezierPath(roundedRect: self.bounds,cornerRadius:8).cgPath
    }
}

How I can fix this properly?

Body:
I'm sharing my approach that worked for me. I have used @clemens extension which is:

extension UIView {
    func addShadow() {
        layer.cornerRadius = 8
        layer.shadowColor = UIColor.lightGray.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 1.0)
        layer.shadowRadius = 2.0
        layer.shadowOpacity = 0.5
        layer.masksToBounds = false

        updateShadow()
    }

    func updateShadow() {
        layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 8).cgPath
    }
}

However, it didn't work until this:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // Async is the key in this situation :)
    DispatchQueue.main.async { [weak self] in
        self?.someButton.addShadowNice()
        self?.someButton.updateShadow()
    }
}

Cheers.


问:
JS: temporarily disable page rendering (possible?)
I'm tryin to sort a big html table using JS. It takes a lot of cpu% to rearrange all the rows of this table. I think the big part of this problem is: every time my script moves a pair of rows, the browser starts refreshing the table

So, I'm searching for any way to temporarily tell the browser something like "wait, I'm sorting this table, dont waste CPU for rendering until I'll finish, plz?"

Basically, I need something lke "Memo1.lines.beginupdate / Memo1.lines.endupdate" in delphi >.<

答:
alert(string) stops rendering, and not asyncronous calls, but not loading. You may prompt "too many cells to load, please wait" you may got the desired behavior.
note that, in order to work, string should be a non empty string after trim so a white space is not valid.</p>