问:
Problem accessing variable declared in one file in extension file
I  declared a variable in my ViewController.swift file like this:

```<code>struct serials{
    static var snToConnectTo2 = ""
}

class ViewController: UIViewController {
....
}
</code>```

I want to access this variable from my KeyboardViewController.swift file which belongs to an extension of my application that ViewController.swift controls.

I am trying to access the variable like this:

```<code>serials.snToConnectTo2
</code>```

When I try to compile my code I get the following error:

```<code>Use of unresolved identifier 'serials';
</code>```

How do you properly access variables from different files?

答:
it's not giving any error

```<code>import Foundation
import UIKit

class Sclass: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print("run1: \(serials.snToConnectTo2)")
        serials.snToConnectTo2 = "abc"
        print("run2: \(serials.snToConnectTo2)")

    }
}

struct serials{
static var snToConnectTo2 = ""
}
</code>```

output is

```<code>run1:
run2: abc
</code>```

If you are still facing any error ... please provide

```<code>class ViewController: UIViewController {
....
}
</code>```

Body:
I  declared a variable in my ViewController.swift file like this:

struct serials{
    static var snToConnectTo2 = ""
}

class ViewController: UIViewController {
....
}

I want to access this variable from my KeyboardViewController.swift file which belongs to an extension of my application that ViewController.swift controls.

I am trying to access the variable like this:

serials.snToConnectTo2

When I try to compile my code I get the following error:

Use of unresolved identifier 'serials';

How do you properly access variables from different files?

Body:
it's not giving any error

import Foundation
import UIKit

class Sclass: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print("run1: \(serials.snToConnectTo2)")
        serials.snToConnectTo2 = "abc"
        print("run2: \(serials.snToConnectTo2)")

    }
}

struct serials{
static var snToConnectTo2 = ""
}

output is

run1:
run2: abc

If you are still facing any error ... please provide

class ViewController: UIViewController {
....
}


来源: stackexchange

问:
If loop to choose which value to populate in textbox
I have a textbox Job in Form2, and I have multiple textboxes in Form1.

Lets say in form1 I have Textbox1 which is RollFromInventory, Textbox2 is RollFromMachine1, Texbox3 is RollFromMachine2 and so on, assume there are 4 other machines, so four other Textboxes.

When I want to populate the textbox Job in Form2, I want to write an If loop which should look for the textbox which has value populated in it, in form1 (there will be only one textbox which will have a value among all the available textboxes in form1), i.e. either RollFromInventory will have a value or RollFromMachine1 will have a value or RollFromMachine2..

I am unsure of the looping logic, so I cant really figure out how to go about it.

Currently the code I have written is mainly for populating concatenated values (I am not providing that code, because it will make the objective seem complicated).

答:
I wrote a code to achieve what I wanted:</p>

```<code>If Len(Me.InvPW.Value & "") > 0 Then
Forms![PrinterWaxLabel].JOB = Me.InvPW.Value

Me.JOB.SetFocus

Else

If Len(Me.FHPW & "") > 0 Then

Forms![PrinterWaxLabel].JOB = Me.FHPW.Value

Me.JOB.SetFocus

Else

If Len(Me.WxPW.Value & "") > 0 Then

Forms![PrinterWaxLabel].JOB = Me.WxPW.Value

Me.JOB.SetFocus

End If

End If

End If
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote a code to achieve what I wanted:

If Len(Me.InvPW.Value & "") > 0 Then
Forms![PrinterWaxLabel].JOB = Me.InvPW.Value

Me.JOB.SetFocus

Else

If Len(Me.FHPW & "") > 0 Then

Forms![PrinterWaxLabel].JOB = Me.FHPW.Value

Me.JOB.SetFocus

Else

If Len(Me.WxPW.Value & "") > 0 Then

Forms![PrinterWaxLabel].JOB = Me.WxPW.Value

Me.JOB.SetFocus

End If

End If

End If


问:
why the main method is printing nothing in the sub class?
"mysecondclass" which is a sub class of the super class "myfirstclass"
should inherit all the properties of the super class "myfirstclass"
and it's expected to output the value of x but instead it prints nothing

```<code>package myfirstproject;

public class myfirstclass {
    protected int x = 10;
    //getter
    public void getX() {
     System.out.println(x);
    }
    public static void main(String[] args) {
/* it asked me to define this main method here although it's useless in this situation
   */
    }
}
class mysecondclass extends myfirstclass {
    public static void main(String[] args) {
    mysecondclass mysecondobject = new mysecondclass();
    mysecondobject.getX(); //prints nothing
    }
}
</code>```

i am really newbie in java and i am actually still learning it's basics
also i do not know why it always asks me to add the main method in the super class although i have already declared one in the sub class (i heard one main method is enough for one java file)
any help is really appreciated , thanks in advance

答:
You have 2 ways to make your code running as you wish

1) create 2 java file. one is myfirstclass.java the second is mysecondclass.java. each hold their main class. Thus you can kick off any main method as you wish.

2) just keep these 2 class in the same java file. then when you running it, it will only run the main method in default in the public class.

Body:
"mysecondclass" which is a sub class of the super class "myfirstclass"
should inherit all the properties of the super class "myfirstclass"
and it's expected to output the value of x but instead it prints nothing

package myfirstproject;

public class myfirstclass {
    protected int x = 10;
    //getter
    public void getX() {
     System.out.println(x);
    }
    public static void main(String[] args) {
/* it asked me to define this main method here although it's useless in this situation
   */
    }
}
class mysecondclass extends myfirstclass {
    public static void main(String[] args) {
    mysecondclass mysecondobject = new mysecondclass();
    mysecondobject.getX(); //prints nothing
    }
}

i am really newbie in java and i am actually still learning it's basics
also i do not know why it always asks me to add the main method in the super class although i have already declared one in the sub class (i heard one main method is enough for one java file)
any help is really appreciated , thanks in advance


问:
How to check if attachment is new in Rails' ActiveStorage?
In my Rails 5.2.2 app I am using Active Storage to attach logos to profiles:

```<code>class Profile < ApplicationRecord

  has_many_attached :logos

end
</code>```

How can I test if a new logo has been attached to the profile on update?

Right now, I am checking for a logos parameter in my controller which works fine:

```<code>class ProfileController < ApplicationController

  def update
    if params[:profile][:logos].present?
      @profile.logo_active = true # This is the important attribute I need to set
    end
    if @profile.update(profile_params)
      flash[:success] = "Profile updated."
      redirect_to profile_path
    end
  end

end
</code>```

Is there a way to do the same in the model, i.e. check if an attachment is actually new and then set the logo_active attribute depending on that?

I toyed around with Rails' new_record? method but to no avail.

答:
You can check if there is an attachment with

```<code>@profile.logos.attached?
</code>```

https://api.rubyonrails.org/classes/ActiveStorage/Attached/Many.html#method-i-attached-3F

Body:
In my Rails 5.2.2 app I am using Active Storage to attach logos to profiles:

class Profile < ApplicationRecord

  has_many_attached :logos

end

How can I test if a new logo has been attached to the profile on update?

Right now, I am checking for a logos parameter in my controller which works fine:

class ProfileController < ApplicationController

  def update
    if params[:profile][:logos].present?
      @profile.logo_active = true # This is the important attribute I need to set
    end
    if @profile.update(profile_params)
      flash[:success] = "Profile updated."
      redirect_to profile_path
    end
  end

end

Is there a way to do the same in the model, i.e. check if an attachment is actually new and then set the logo_active attribute depending on that?

I toyed around with Rails' new_record? method but to no avail.

Body:
You can check if there is an attachment with

@profile.logos.attached?

https://api.rubyonrails.org/classes/ActiveStorage/Attached/Many.html#method-i-attached-3F


问:
Comparing a datetime dataframe with a period dataframe
I have been stuck with a simple pandas dataframe problem and maybe someone faced this situation before...

Thank you in advance :)

Hi have two dataframes, df1 and df2:

df1

```<code>unique_id    timestamp
1            2019-01-21
2            2019-02-01
3            2019-04-05
4            2019-05-01
5            2019-05-12
...          ...
</code>```

df2

```<code>classification     from            to
A                  2019-01-05      2019-02-02
B                  2019-02-03      2019-02-28
C                  2019-03-01      2019-04-05
D                  2019-04-06      2019-05-03
E                  2019-05-04      2019-05-31
...                ...             ...
</code>```

My goal is to compare each timestamp in df1 with each from to date interval in df2 and be able to classify every unique_id of df1 with the correspondent classification of df2

I was trying something like this:

```<code>df1.loc[(df1['timestamp'] > df2['from]) & (df1['timestamp'] < df2['to']), 'class'] = df2['classification']´
</code>```

always get a ValueError: Can only compare identically-labeled Series objects despite both datetime dtypes are the exact same, datetime64[ns]...

Expected Output:

```<code>unique_id         timestamp        classification
1                 2019-01-21       A
2                 2019-02-01       A
3                 2019-04-05       C
4                 2019-05-01       D
5                 2019-05-12       E
...               ...              ...
</code>```

答:
try:

import numpy as np

now instead of

df1['timestamp'] > df2['from]

try:

np.greater(df1['timestamp'],df2['from])

looks like your are trying to get a true\false answer.

might want to take a look here: https://docs.scipy.org/doc/numpy/reference/routines.logic.html

Body:
I have been stuck with a simple pandas dataframe problem and maybe someone faced this situation before...

Thank you in advance :)

Hi have two dataframes, df1 and df2:

df1

unique_id    timestamp
1            2019-01-21
2            2019-02-01
3            2019-04-05
4            2019-05-01
5            2019-05-12
...          ...

df2

classification     from            to
A                  2019-01-05      2019-02-02
B                  2019-02-03      2019-02-28
C                  2019-03-01      2019-04-05
D                  2019-04-06      2019-05-03
E                  2019-05-04      2019-05-31
...                ...             ...

My goal is to compare each timestamp in df1 with each from to date interval in df2 and be able to classify every unique_id of df1 with the correspondent classification of df2

I was trying something like this:

df1.loc[(df1['timestamp'] > df2['from]) & (df1['timestamp'] < df2['to']), 'class'] = df2['classification']´

always get a ValueError: Can only compare identically-labeled Series objects despite both datetime dtypes are the exact same, datetime64[ns]...

Expected Output:

unique_id         timestamp        classification
1                 2019-01-21       A
2                 2019-02-01       A
3                 2019-04-05       C
4                 2019-05-01       D
5                 2019-05-12       E
...               ...              ...


问:
jQuery dilemma in loading different pages on one page
Hello i need some help to figure out what to do .

I am trying to create a page that has a list of events and each time I click one of the list's elements a different photo gallery should load. I did this by loading each gallery in a different iframe.

The problem is that right now the only thing it dose is loading the first galery and the other ones don't seem to manage loading any pictures (if I refresh each frame than they work fine)

What should i do?

This is the script I used in the webpage

You can find the page source here http://www.avantsolutions.ro/exp.txt

答:
You can use jQuery's load function to load a gallery via ajax.

$(selectorForYourGalleryDisplayDiv).load( url, [ data ], [ complete(responseText, textStatus, XMLHttpRequest) ] )

Load will take the result from url, if you need to pass it data it will use a HTTP POST, and replace the inner html of the wrapped set it is called on.

I don't know the internals of your architecture, but the main process is giving your galleries Ids, pass them to the server using the JSON format, your code will use that id to get what's needed for the gallery, render the html and return it.

load will drop that html into the elements that match selectorForYourGalleryDisplayDiv.

ContentLicense: CC BY-SA 3.0


问:
Java Get mac address of disconnected card
I want to get the MAC of the ethernet card (for product key)
I tried using this kind of solution and searched here, the problem is that when all the networking is disconnected (ethernet and wifi) it returns empty MAC adress.
I rather get the adress of the ethernet even if it's disconnected.

Thanks!!

```<code>   public static void main(String[] args)
    {
        InetAddress ip;
        try {
            ip = InetAddress.getLocalHost();

            System.out.println("The mac Address of this machine is :" + ip.getHostAddress());

            NetworkInterface network = NetworkInterface.getByInetAddress(ip);

            byte[] mac = network.getHardwareAddress();

            System.out.print("The mac address is : ");

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++){
                sb.append(String.format("%02X%s", mac[i],(i< mac.length - 1)?"-":""));
            }

            System.out.println(sb.toString());

        }
        catch (UnknownHostException e) {
            e.printStackTrace();
        }
        catch (SocketException e) {
            e.printStackTrace();
        }
    }
}
</code>```

答:
If you are looking to use some unique hardware identifier to validate a license then I recommend using OSHI (Operating System and Hardware Information) to get the hardware information you need.

The general principal would be encode the hardware identifier into the client license string then when the client runs it would decode that id from the license string and make sure that hardware is present to validate the license. Don't depend on indices because there's often no guarantee of hardware order, just iterate through the list of hardware in question and see if the one the key is bound to is present.

Note: When license validation is done locally it can always be cracked; The point is just to make it annoying to crack. If your license were just the plain MAC address by itself then it would be very easy for people to just look up their MAC and give themselves a valid license. Even if you encode/encrypt the MAC into the license, they could look at the decompiled code and find the how the decoding (and hence encoding) works so that they could encode their own valid license. You need to encrypt and obfuscate as much as possible to make it hard for people to generate their own licenses but in the end it only makes it more annoying to crack but not impossible.

Another option, aside from MAC address, is binding to a disk. Disk serial number is not as easy to change as MAC address. With this you could bind the license to a USB key which is kinda fun. The only thing to worry about is people changing out disks but if the software license is bound to the disk it's stored on then that's hardly a problem.

pom.xml

```<code>...
<dependencies>
    <dependency>
        <groupId>com.github.oshi</groupId>
        <artifactId>oshi-core</artifactId>
        <version>3.13.2</version>
    </dependency>
</dependencies>
...
</code>```

ClientLicense.java

```<code>import oshi.SystemInfo;
import oshi.hardware.HWDiskStore;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.NetworkIF;

/**
 * This class would be loaded with the client license and validate that the license is for the machine running this code.
 */
public class ClientLicense {
    final String clientLicenseString;

    public ClientLicense(String clientLicenseString) {
        this.clientLicenseString = clientLicenseString;
    }

    public final boolean validateByDisk() {
        int expectedModelSerialHash = decodeExpectedModelSerialHash(clientLicenseString);
        for (HWDiskStore disk : new SystemInfo().getHardware().getDiskStores()) {
            if (expectedModelSerialHash == Objects.hash(disk.getModel(), disk.getSerial())) {
                return true;
            }
        }
        return false;
    }

    public final boolean validateByMAC() {
        String expectedMac = decodeExpectedMac(clientLicenseString);
        for (NetworkIF netIF : new SystemInfo().getHardware().getNetworkIFs()) {
            if (expectedMac.equals(netIF.getMacaddr())) {
                return true;
            }
        }
        return false;
    }

    private int decodeExpectedModelSerialHash(String clientLicenseString) {
        // obfuscate license decoding, inverse of license encoding/encrypting
        return 0; // return the expected hash of model and serial
    }

    private String decodeExpectedMac(String clientLicenseString) {
        // obfuscate license decoding, inverse of license encoding/encrypting
        return ""; // return the expected MAC address
    }
}
</code>```

Alternatively, you can see a lot of the hardware information that you can get in this example file.

Additionally, see example classes at oshi-demo (as mentioned by Daniel Widdis); The ComputerID.java example contains the following method:

```<code>/**
 * Generates a Computer Identifier, which may be part of a strategy to
 * construct a licence key. (The identifier may not be unique as in one case
 * hashcode could be same for multiple values, and the result may differ
 * based on whether the program is running with sudo/root permission.) The
 * identifier string is based upon the processor serial number, vendor,
 * processor identifier, and total processor count.
 *
 * @return A string containing four hyphen-delimited fields representing the
 *         processor; the first 3 are 32-bit hexadecimal values and the last
 *         one is an integer value.
 */
public static String getComputerIdentifier() {
    SystemInfo systemInfo = new SystemInfo();
    OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
    HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
    CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();
    ComputerSystem computerSystem = hardwareAbstractionLayer.getComputerSystem();

    String vendor = operatingSystem.getManufacturer();
    String processorSerialNumber = computerSystem.getSerialNumber();
    String processorIdentifier = centralProcessor.getIdentifier();
    int processors = centralProcessor.getLogicalProcessorCount();

    String delimiter = "-";

    return String.format("%08x", vendor.hashCode()) + delimiter
            + String.format("%08x", processorSerialNumber.hashCode()) + delimiter
            + String.format("%08x", processorIdentifier.hashCode()) + delimiter + processors;
}
</code>```

Body:
I want to get the MAC of the ethernet card (for product key)
I tried using this kind of solution and searched here, the problem is that when all the networking is disconnected (ethernet and wifi) it returns empty MAC adress.
I rather get the adress of the ethernet even if it's disconnected.

Thanks!!

   public static void main(String[] args)
    {
        InetAddress ip;
        try {
            ip = InetAddress.getLocalHost();

            System.out.println("The mac Address of this machine is :" + ip.getHostAddress());

            NetworkInterface network = NetworkInterface.getByInetAddress(ip);

            byte[] mac = network.getHardwareAddress();

            System.out.print("The mac address is : ");

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++){
                sb.append(String.format("%02X%s", mac[i],(i< mac.length - 1)?"-":""));
            }

            System.out.println(sb.toString());

        }
        catch (UnknownHostException e) {
            e.printStackTrace();
        }
        catch (SocketException e) {
            e.printStackTrace();
        }
    }
}

Body:
If you are looking to use some unique hardware identifier to validate a license then I recommend using OSHI (Operating System and Hardware Information) to get the hardware information you need.

The general principal would be encode the hardware identifier into the client license string then when the client runs it would decode that id from the license string and make sure that hardware is present to validate the license. Don't depend on indices because there's often no guarantee of hardware order, just iterate through the list of hardware in question and see if the one the key is bound to is present.

Note: When license validation is done locally it can always be cracked; The point is just to make it annoying to crack. If your license were just the plain MAC address by itself then it would be very easy for people to just look up their MAC and give themselves a valid license. Even if you encode/encrypt the MAC into the license, they could look at the decompiled code and find the how the decoding (and hence encoding) works so that they could encode their own valid license. You need to encrypt and obfuscate as much as possible to make it hard for people to generate their own licenses but in the end it only makes it more annoying to crack but not impossible.

Another option, aside from MAC address, is binding to a disk. Disk serial number is not as easy to change as MAC address. With this you could bind the license to a USB key which is kinda fun. The only thing to worry about is people changing out disks but if the software license is bound to the disk it's stored on then that's hardly a problem.

pom.xml

...
<dependencies>
    <dependency>
        <groupId>com.github.oshi</groupId>
        <artifactId>oshi-core</artifactId>
        <version>3.13.2</version>
    </dependency>
</dependencies>
...

ClientLicense.java

import oshi.SystemInfo;
import oshi.hardware.HWDiskStore;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.NetworkIF;

/**
 * This class would be loaded with the client license and validate that the license is for the machine running this code.
 */
public class ClientLicense {
    final String clientLicenseString;

    public ClientLicense(String clientLicenseString) {
        this.clientLicenseString = clientLicenseString;
    }

    public final boolean validateByDisk() {
        int expectedModelSerialHash = decodeExpectedModelSerialHash(clientLicenseString);
        for (HWDiskStore disk : new SystemInfo().getHardware().getDiskStores()) {
            if (expectedModelSerialHash == Objects.hash(disk.getModel(), disk.getSerial())) {
                return true;
            }
        }
        return false;
    }

    public final boolean validateByMAC() {
        String expectedMac = decodeExpectedMac(clientLicenseString);
        for (NetworkIF netIF : new SystemInfo().getHardware().getNetworkIFs()) {
            if (expectedMac.equals(netIF.getMacaddr())) {
                return true;
            }
        }
        return false;
    }

    private int decodeExpectedModelSerialHash(String clientLicenseString) {
        // obfuscate license decoding, inverse of license encoding/encrypting
        return 0; // return the expected hash of model and serial
    }

    private String decodeExpectedMac(String clientLicenseString) {
        // obfuscate license decoding, inverse of license encoding/encrypting
        return ""; // return the expected MAC address
    }
}

Alternatively, you can see a lot of the hardware information that you can get in this example file.

Additionally, see example classes at oshi-demo (as mentioned by Daniel Widdis); The ComputerID.java example contains the following method:

/**
 * Generates a Computer Identifier, which may be part of a strategy to
 * construct a licence key. (The identifier may not be unique as in one case
 * hashcode could be same for multiple values, and the result may differ
 * based on whether the program is running with sudo/root permission.) The
 * identifier string is based upon the processor serial number, vendor,
 * processor identifier, and total processor count.
 *
 * @return A string containing four hyphen-delimited fields representing the
 *         processor; the first 3 are 32-bit hexadecimal values and the last
 *         one is an integer value.
 */
public static String getComputerIdentifier() {
    SystemInfo systemInfo = new SystemInfo();
    OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
    HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
    CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();
    ComputerSystem computerSystem = hardwareAbstractionLayer.getComputerSystem();

    String vendor = operatingSystem.getManufacturer();
    String processorSerialNumber = computerSystem.getSerialNumber();
    String processorIdentifier = centralProcessor.getIdentifier();
    int processors = centralProcessor.getLogicalProcessorCount();

    String delimiter = "-";

    return String.format("%08x", vendor.hashCode()) + delimiter
            + String.format("%08x", processorSerialNumber.hashCode()) + delimiter
            + String.format("%08x", processorIdentifier.hashCode()) + delimiter + processors;
}


问:
Distinguish between create and update event of Managed Objects
I'm using Apama in Cumulocity. Whenever a managed object (device) is created in Cumulocity, I would like to provide it with some initial parameters, here the required interval the device needs to report to Cumulocity before it's considered to be unavailable.

My problem is that in Apama I don't seem to have any way to distinguish between create and update events. So if I receive a managed object, add some parameters to it and send it back to the managed object channel, I end up in a loop.

I can of course do some check after the event has been received, but I would prefer to filter on only the create events of managed objects and don't perform any IF checks.

Is there any way I can filter on only create events? What is the difference between the CHANNEL and the UPDATE_CHANNEL? It doesn't seem to make a difference which one I use.

My current code looks as follows. What I want to achieve is avoid the IF statement and filter directly on create events in the listener.

```<code>monitor InitializeDevice {
    action onload() {

        monitor.subscribe(ManagedObject.CHANNEL);
        on all ManagedObject(type = "c8y_MQTTDevice") as mo {
            log "###Received managed object. Content is: " + mo.toString() at INFO;
            if (mo.params.hasKey("c8y_RequiredAvailability")) {
                //Assuming an interval has already been set, do nothing.
                log "###Received managed object with required availability fragment. Doing nothing." at INFO;
            }
            else {
                //Set the response interval on the managed object
                dictionary<string,any> params := mo.params;
                dictionary<string,any> paramssub := new dictionary<string,any>;
                paramssub.add("responseInterval",3);
                params.add("c8y_RequiredAvailability",paramssub);
                mo.params := params;
                log "###Added required interval to managed object. Content is: " + mo.toString() at INFO;
                send mo to ManagedObject.UPDATE_CHANNEL;
            }
        }
    }
}

</code>```

When I execute this monitor and create a new managed object, this is what is printed to the logs:

```<code>
2019-05-27 16:15:07.310 INFO  [12648] - InitializeDevice [6] ###Received managed object. Content is: com.apama.cumulocity.ManagedObject("5708279","c8y_MQTTDevice","some-device",[],[],[],[],[],[],{},{"c8y_IsDevice":any(dictionary<any,any>,{}),"owner":any(string,"some-owner")})
2019-05-27 16:15:07.310 INFO  [12648] - InitializeDevice [6] ###Added required interval to managed object. Content is: com.apama.cumulocity.ManagedObject("5708279","c8y_MQTTDevice","some-device",[],[],[],[],[],[],{},{"c8y_IsDevice":any(dictionary<any,any>,{}),"c8y_RequiredAvailability":any(dictionary<string,any>,{"responseInterval":any(integer,3)}),"owner":any(string,"some-owner")})
2019-05-27 16:15:07.310 INFO  [12648] - InitializeDevice [6] ###Received managed object. Content is: com.apama.cumulocity.ManagedObject("5708279","c8y_MQTTDevice","some-device",[],[],[],[],[],[],{},{"c8y_IsDevice":any(dictionary<any,any>,{}),"c8y_RequiredAvailability":any(dictionary<string,any>,{"responseInterval":any(integer,3)}),"owner":any(string,"some-owner")})
2019-05-27 16:15:07.310 INFO  [12648] - InitializeDevice [6] ###Received managed object with required availability fragment. Doing nothing.
2019-05-27 16:15:08.244 INFO  [7868] - InitializeDevice [6] ###Received managed object. Content is: com.apama.cumulocity.ManagedObject("5708279","c8y_MQTTDevice","some-device",[],[],[],[],[],[],{},{"c8y_Availability":any(dictionary<any,any>,{any(string,"lastMessage"):any(dictionary<any,any>,{any(string,"date"):any(integer,27),any(string,"day"):any(integer,1),any(string,"hours"):any(integer,16),any(string,"minutes"):any(integer,15),any(string,"month"):any(integer,4),any(string,"seconds"):any(integer,7),any(string,"time"):any(integer,1558966507220),any(string,"timezoneOffset"):any(integer,-120),any(string,"year"):any(integer,119)}),any(string,"status"):any(string,"AVAILABLE")}),"c8y_Connection":any(dictionary<any,any>,{any(string,"status"):any(string,"DISCONNECTED")}),"c8y_IsDevice":any(dictionary<any,any>,{}),"c8y_RequiredAvailability":any(dictionary<any,any>,{any(string,"responseInterval"):any(integer,3)}),"owner":any(string,"some-owner")})
2019-05-27 16:15:08.244 INFO  [7868] - InitializeDevice [6] ###Received managed object with required availability fragment. Doing nothing.
</code>```

Is there any way to filter directly on create events? Why do I received two print statements after the update?

Thanks
Mathias

答:
After some investigation it seems that there isn't any way to distinguish the Creation and Update messages. So the code you are using at the moment is probably the only way to do this.

Edited:

BUT The second part of the question:

Why do I received two print statements after the update?

c8y sends managed object to MO.CHANNEL -> Apama monitor
  monitor adds c8y_RequiredAvailability

monitor sends managed object with update to MO.UPDATE_CHANNEL -> c8y

c8y sends updated managed object containing c8y_RequiredAvailability -> Apama monitor

c8y sends managed object + c8y_Availability-> Apama monitor

so 3 is the confirmation of your update, and 4 is c8y asynchronously sending the final update with availability on the MO.CHANNEL

To be explicit - the MO.CHANNEL is where created and updated objects arrive into Apama. Sending on that channel shouldn't have an effect. The MO.UPDATE_CHANNEL is the request channel where you send updates to which may then trigger further messages on the MO.CHANNEL as c8y processes.

Body:
I'm using Apama in Cumulocity. Whenever a managed object (device) is created in Cumulocity, I would like to provide it with some initial parameters, here the required interval the device needs to report to Cumulocity before it's considered to be unavailable.

My problem is that in Apama I don't seem to have any way to distinguish between create and update events. So if I receive a managed object, add some parameters to it and send it back to the managed object channel, I end up in a loop.

I can of course do some check after the event has been received, but I would prefer to filter on only the create events of managed objects and don't perform any IF checks.

Is there any way I can filter on only create events? What is the difference between the CHANNEL and the UPDATE_CHANNEL? It doesn't seem to make a difference which one I use.

My current code looks as follows. What I want to achieve is avoid the IF statement and filter directly on create events in the listener.

monitor InitializeDevice {
    action onload() {

        monitor.subscribe(ManagedObject.CHANNEL);
        on all ManagedObject(type = "c8y_MQTTDevice") as mo {
            log "###Received managed object. Content is: " + mo.toString() at INFO;
            if (mo.params.hasKey("c8y_RequiredAvailability")) {
                //Assuming an interval has already been set, do nothing.
                log "###Received managed object with required availability fragment. Doing nothing." at INFO;
            }
            else {
                //Set the response interval on the managed object
                dictionary<string,any> params := mo.params;
                dictionary<string,any> paramssub := new dictionary<string,any>;
                paramssub.add("responseInterval",3);
                params.add("c8y_RequiredAvailability",paramssub);
                mo.params := params;
                log "###Added required interval to managed object. Content is: " + mo.toString() at INFO;
                send mo to ManagedObject.UPDATE_CHANNEL;
            }
        }
    }
}

When I execute this monitor and create a new managed object, this is what is printed to the logs:

2019-05-27 16:15:07.310 INFO  [12648] - InitializeDevice [6] ###Received managed object. Content is: com.apama.cumulocity.ManagedObject("5708279","c8y_MQTTDevice","some-device",[],[],[],[],[],[],{},{"c8y_IsDevice":any(dictionary<any,any>,{}),"owner":any(string,"some-owner")})
2019-05-27 16:15:07.310 INFO  [12648] - InitializeDevice [6] ###Added required interval to managed object. Content is: com.apama.cumulocity.ManagedObject("5708279","c8y_MQTTDevice","some-device",[],[],[],[],[],[],{},{"c8y_IsDevice":any(dictionary<any,any>,{}),"c8y_RequiredAvailability":any(dictionary<string,any>,{"responseInterval":any(integer,3)}),"owner":any(string,"some-owner")})
2019-05-27 16:15:07.310 INFO  [12648] - InitializeDevice [6] ###Received managed object. Content is: com.apama.cumulocity.ManagedObject("5708279","c8y_MQTTDevice","some-device",[],[],[],[],[],[],{},{"c8y_IsDevice":any(dictionary<any,any>,{}),"c8y_RequiredAvailability":any(dictionary<string,any>,{"responseInterval":any(integer,3)}),"owner":any(string,"some-owner")})
2019-05-27 16:15:07.310 INFO  [12648] - InitializeDevice [6] ###Received managed object with required availability fragment. Doing nothing.
2019-05-27 16:15:08.244 INFO  [7868] - InitializeDevice [6] ###Received managed object. Content is: com.apama.cumulocity.ManagedObject("5708279","c8y_MQTTDevice","some-device",[],[],[],[],[],[],{},{"c8y_Availability":any(dictionary<any,any>,{any(string,"lastMessage"):any(dictionary<any,any>,{any(string,"date"):any(integer,27),any(string,"day"):any(integer,1),any(string,"hours"):any(integer,16),any(string,"minutes"):any(integer,15),any(string,"month"):any(integer,4),any(string,"seconds"):any(integer,7),any(string,"time"):any(integer,1558966507220),any(string,"timezoneOffset"):any(integer,-120),any(string,"year"):any(integer,119)}),any(string,"status"):any(string,"AVAILABLE")}),"c8y_Connection":any(dictionary<any,any>,{any(string,"status"):any(string,"DISCONNECTED")}),"c8y_IsDevice":any(dictionary<any,any>,{}),"c8y_RequiredAvailability":any(dictionary<any,any>,{any(string,"responseInterval"):any(integer,3)}),"owner":any(string,"some-owner")})
2019-05-27 16:15:08.244 INFO  [7868] - InitializeDevice [6] ###Received managed object with required availability fragment. Doing nothing.

Is there any way to filter directly on create events? Why do I received two print statements after the update?

Thanks
Mathias


问:
My code wont render even after installing dependencies
Failed to compile.

./src/components/Teachers.js
Module not found: Can't resolve 'semantic-ui-react' in 'C:\Users\user\Documents\GitHub\Portfolio\Rework1\src\components'

I keep getting this error my code works but it looks like my dependencies are not loading correctly I ran some terminal commands that broke my code please help.

I have tried installing dependencies in Node_Modules folder

```<code>import React from 'react';
import TeacherList from '../data/teachers';
import {  Badge, CardHeader,CardImg, CardFooter, CardBody,
 CardText,CardColumns,CardTitle,CardSubtitle,Row,Col, } from 'reactstrap';
 import { Button, Header, Modal } from 'semantic-ui-react'

 import { Card, Icon, Image } from 'semantic-ui-react'

import Description from './Description'
const Teachers = () => {
  let teachers = TeacherList.map((teacher) => {
    return (

<img className="teacher-img" src={teacher.img_src} alt="teacher" />
  <b className="projectTitle">{teacher.name}</b>
            <hr className="divider2 my-4"/>

          <a className="link" href={teacher.code} target="_blank"  rel="noopener noreferrer"><b> Code </b></a>
  <a  className="link code" href={teacher.live} target="_blank"  rel="noopener noreferrer"><b> Live </b></a>
  <CardFooter>
         <Badge color="primary" pill>{teacher.javascript}</Badge>
         <Badge color="secondary" pill>{teacher.html5}</Badge>
         <Badge color="success" pill>{teacher.bootstrap}</Badge>
         <Badge color="info" pill>{teacher.css3}</Badge>
         <Badge color="light ">{teacher.jquery}</Badge>

         </CardFooter>
</Card> */}
<Card>
    <div className="container3">
    <Image src={teacher.img_src} wrapped ui={false} />
    <Card.Content>
      <Card.Header>Daniel</Card.Header>
      <Card.Meta>Joined in 2016</Card.Meta>
      <Card.Description>
        Daniel is a comedian living in Nashville.
      </Card.Description>
    </Card.Content>
    <Card.Content extra>
      <a>
        <Icon name='user' />
        10 Friends
      </a>
    </Card.Content>
    </div>

  </Card>

</div>

    );
  });

  return (
    <div className="main-content">
      <h2>Projects </h2>
      <ul className="group">
        {teachers}
      </ul>
    </div>
  );
}

export default Teachers;
</code>```

Package.Json

```<code>{
  "name": "course-directory",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "1.0.6"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^5.0.0",
    "semantic-ui": "^2.4.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
</code>```

答:
Maybe try this, it looks like you have quite a few syntax errors. I haven't run this, but it may help.</p>

```<code>const Teachers = () => {
  let teachers = TeacherList.map((teacher) => {
    return (
<div>
<img className="teacher-img" src={teacher.img_src} alt="teacher" />
<b className="projectTitle">{teacher.name}</b>
<hr className="divider2 my-4"/>

<a className="link" href={teacher.code} target="_blank"  rel="noopener noreferrer"><b> Code </b></a>
  <a  className="link code" href={teacher.live} target="_blank"  rel="noopener noreferrer"><b> Live </b></a>
  <CardFooter>
         <Badge color="primary" pill>{teacher.javascript}</Badge>
         <Badge color="secondary" pill>{teacher.html5}</Badge>
         <Badge color="success" pill>{teacher.bootstrap}</Badge>
         <Badge color="info" pill>{teacher.css3}</Badge>
         <Badge color="light ">{teacher.jquery}</Badge>
    </CardFooter>

<Card>
    <div className="container3">
    <Image src={teacher.img_src} wrapped ui={false} />
    <Card.Content>
      <Card.Header>Daniel</Card.Header>
      <Card.Meta>Joined in 2016</Card.Meta>
      <Card.Description>
        Daniel is a comedian living in Nashville.
      </Card.Description>
    </Card.Content>
    <Card.Content extra>
      <a>
        <Icon name='user' />
        10 Friends
      </a>
    </Card.Content>
    </div>

</Card>
</div>
    )}
    )

  return (
    <div className="main-content">
      <h2>Projects </h2>
      <ul className="group">
        {teachers}
      </ul>
    </div>
  );
}

export default Teachers;
</code>```

Body:
Failed to compile.

./src/components/Teachers.js
Module not found: Can't resolve 'semantic-ui-react' in 'C:\Users\user\Documents\GitHub\Portfolio\Rework1\src\components'

I keep getting this error my code works but it looks like my dependencies are not loading correctly I ran some terminal commands that broke my code please help.

I have tried installing dependencies in Node_Modules folder

import React from 'react';
import TeacherList from '../data/teachers';
import {  Badge, CardHeader,CardImg, CardFooter, CardBody,
 CardText,CardColumns,CardTitle,CardSubtitle,Row,Col, } from 'reactstrap';
 import { Button, Header, Modal } from 'semantic-ui-react'

 import { Card, Icon, Image } from 'semantic-ui-react'

import Description from './Description'
const Teachers = () => {
  let teachers = TeacherList.map((teacher) => {
    return (

  {teacher.name}

           Code
   Live
  <CardFooter>
         <Badge color="primary" pill>{teacher.javascript}</Badge>
         <Badge color="secondary" pill>{teacher.html5}</Badge>
         <Badge color="success" pill>{teacher.bootstrap}</Badge>
         <Badge color="info" pill>{teacher.css3}</Badge>
         <Badge color="light ">{teacher.jquery}</Badge>

         </CardFooter>
</Card> */}
<Card>

    <Image src={teacher.img_src} wrapped ui={false} />
    <Card.Content>
      <Card.Header>Daniel</Card.Header>
      <Card.Meta>Joined in 2016</Card.Meta>
      <Card.Description>
        Daniel is a comedian living in Nashville.
      </Card.Description>
    </Card.Content>
    <Card.Content extra>

        <Icon name='user' />
        10 Friends

    </Card.Content>

  </Card>

    );
  });

  return (

Projects

        {teachers}

  );
}

export default Teachers;

Package.Json

{
  "name": "course-directory",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "1.0.6"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^5.0.0",
    "semantic-ui": "^2.4.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Body:
Maybe try this, it looks like you have quite a few syntax errors. I haven't run this, but it may help.

const Teachers = () => {
  let teachers = TeacherList.map((teacher) => {
    return (
<div>
<img className="teacher-img" src={teacher.img_src} alt="teacher" />
<b className="projectTitle">{teacher.name}</b>
<hr className="divider2 my-4"/>

<a className="link" href={teacher.code} target="_blank"  rel="noopener noreferrer"><b> Code </b></a>
  <a  className="link code" href={teacher.live} target="_blank"  rel="noopener noreferrer"><b> Live </b></a>
  <CardFooter>
         <Badge color="primary" pill>{teacher.javascript}</Badge>
         <Badge color="secondary" pill>{teacher.html5}</Badge>
         <Badge color="success" pill>{teacher.bootstrap}</Badge>
         <Badge color="info" pill>{teacher.css3}</Badge>
         <Badge color="light ">{teacher.jquery}</Badge>
    </CardFooter>

<Card>
    <div className="container3">
    <Image src={teacher.img_src} wrapped ui={false} />
    <Card.Content>
      <Card.Header>Daniel</Card.Header>
      <Card.Meta>Joined in 2016</Card.Meta>
      <Card.Description>
        Daniel is a comedian living in Nashville.
      </Card.Description>
    </Card.Content>
    <Card.Content extra>
      <a>
        <Icon name='user' />
        10 Friends
      </a>
    </Card.Content>
    </div>

</Card>
</div>
    )}
    )

  return (
    <div className="main-content">
      <h2>Projects </h2>
      <ul className="group">
        {teachers}
      </ul>
    </div>
  );
}

export default Teachers;


问:
Failing to authenticate with MongoDB using node.js
I've been attempting to add authentication to my mongo database.

So following various tutorials and solving some problems (my server was 2.4 and needed to be upgraded), I was finally able to add a user

I run the server in one shell

```<code>mongod --dbpath ./
</code>```

then in another I run

```<code>mongo
use admin
db.createUser({
     user:"user",
     pwd:"pass",
     roles: [{role:"userAdminAnyDatabase", db:"admin"}]
})
</code>```

I get a success message, so then I quit out of both the server and the shell

In another shell I run

```<code>mongod --dbpath ./ --auth
</code>```

Then I run

```<code>node server.js
</code>```

Within the server.js file, there is the following code

```<code>mongodb.MongoClient.connect('mongodb://127.0.0.1:27017/db', function(err, db) {
    if(err) throw err;
    db.authenticate("user", "pass", function(err, res) {
        if(err) throw err;
        // code here
    });
});
</code>```

But this throws a mongo error, that authentication failed

Am I trying to authenticate incorrectly, or doing something else wrong? I'm not understanding my mistake.

Here is the error

```<code>C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\connection\base.js:245
    throw message;
          ^
MongoError: auth failed
    at Object.toError (C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\utils.js:110:11)
    at C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\db.js:1128:31
    at C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\db.js:1843:9
    at Server.Base._callHandler (C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\connection\base.js:445:41)
    at C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\connection\server.js:468:18
    at MongoReply.parseBody (C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\responses\mongo_reply.js:68:5)
    at null.<anonymous> (C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\connection\server.js:426:20)
    at EventEmitter.emit (events.js:95:17)
    at null.<anonymous> (C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:201:13)
    at EventEmitter.emit (events.js:98:17)
</code>```

答:
It fails when you pass in the db to connect to in the url. Looks like the authentication is done against the same db. Instead you should do:

```<code>    const client = await new Promise((res, rej) =>
      MongoClient.connect(
        K2_MONGODB_URL,
        {
          auth: {
            authdb: 'admin'
          },
          useNewUrlParser: true
        },
        (err, client) => (err ? rej(err) : res(client))
      )
    )
</code>```

where K2_MONGODB_URL=mongodb://user:password@localhost:27017

Body:
I've been attempting to add authentication to my mongo database.

So following various tutorials and solving some problems (my server was 2.4 and needed to be upgraded), I was finally able to add a user

I run the server in one shell

mongod --dbpath ./

then in another I run

mongo
use admin
db.createUser({
     user:"user",
     pwd:"pass",
     roles: [{role:"userAdminAnyDatabase", db:"admin"}]
})

I get a success message, so then I quit out of both the server and the shell

In another shell I run

mongod --dbpath ./ --auth

Then I run

node server.js

Within the server.js file, there is the following code

mongodb.MongoClient.connect('mongodb://127.0.0.1:27017/db', function(err, db) {
    if(err) throw err;
    db.authenticate("user", "pass", function(err, res) {
        if(err) throw err;
        // code here
    });
});

But this throws a mongo error, that authentication failed

Am I trying to authenticate incorrectly, or doing something else wrong? I'm not understanding my mistake.

Here is the error

C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\connection\base.js:245
    throw message;
          ^
MongoError: auth failed
    at Object.toError (C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\utils.js:110:11)
    at C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\db.js:1128:31
    at C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\db.js:1843:9
    at Server.Base._callHandler (C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\connection\base.js:445:41)
    at C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\connection\server.js:468:18
    at MongoReply.parseBody (C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\responses\mongo_reply.js:68:5)
    at null.<anonymous> (C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\connection\server.js:426:20)
    at EventEmitter.emit (events.js:95:17)
    at null.<anonymous> (C:\Users\Corey Byrne\Documents\DocuBuilder\Email Project\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:201:13)
    at EventEmitter.emit (events.js:98:17)

Body:
It fails when you pass in the db to connect to in the url. Looks like the authentication is done against the same db. Instead you should do:

    const client = await new Promise((res, rej) =>
      MongoClient.connect(
        K2_MONGODB_URL,
        {
          auth: {
            authdb: 'admin'
          },
          useNewUrlParser: true
        },
        (err, client) => (err ? rej(err) : res(client))
      )
    )

where K2_MONGODB_URL=mongodb://user:password@localhost:27017


问:
Tool tip for long texts in Hero Cards
I am using Bot Framework Webchat (React based). I use Card Actions (Hero Cards) to suggest a list of similar questions. Sometimes the text within the Hero Card might be too long. In that case the text gets truncated and replaced with three dots. Is it possible to have tool tip for the Hero Cards?

I looked into the HeroCard options in the code but didn't find anything relevant.

I have raised this on Github: https://github.com/microsoft/BotFramework-WebChat/issues/2032

Any help with this please?

答:
Web Chat utilizes the Adaptive Cards NPM package to render cards, and, unfortunately, Adaptive Cards does not support adding tooltip descriptions to elements in the card. There are, however, several issues open on GitHub regarding adding tooltip functionality, so hopefully, that feature will be available in Web Chat soon.

Even though Adaptive Cards doesn't support adding tooltips, you can create a custom attachment middleware for Web Chat and implement your own Hero Card renderer. The code snippet below shows a basic Hero Card renderer without any styling.

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

  const HeroCardAttachment = ({ buttons, images, title, store }) =>
    <div className='ac-container'>
      <div className='ac-container'>
        { images.map(({ url }, index) =>
          <window.React.Fragment key={ index }>
            <div>
              <img src= { url } />
            </div>
            <div style={{height: '8px'}}/>
          </window.React.Fragment>
        )}
        <div>{ title }</div>
      </div>
      <div />
      <div >
        { buttons.map(({ title, type, value }, index) => (
          <window.React.Fragment key={ index }>
            <button
              aria-label={ title }
              type='button'
              title={ title }
              onClick={ () => {
                switch (type) {
                  case 'openUrl':
                    window.open(value)
                    break;
                  case 'postBack':
                    store.dispatch({
                      type: 'WEB_CHAT/SEND_POST_BACK',
                      payload: { value }
                    });
                    break;
                  default:
                    store.dispatch({
                      type: 'WEB_CHAT/SEND_MESSAGE_BACK',
                      payload: { value, text: value, displayText: value }
                    });
                }
              }}
            >
              <div title={ title }>
                { title }
              </div>
            </button>
            <div />
          </window.React.Fragment>
        ))}
      </div>
    </div>;

  (async function () {

    const res = await fetch('/directline/token', { method: 'POST' });
    const { token } = await res.json();
    const { createStore, ReactWebChat } = window.WebChat;
    const store = createStore();

    const attachmentMiddleware = () => next => card => {
      switch (card.attachment.contentType) {
        case 'application/vnd.microsoft.card.hero':
          return <HeroCardAttachment {...card.attachment.content} store={ store }/>;
        default:
          return next(card);
      }
    };

    window.ReactDOM.render(
      <ReactWebChat
        attachmentMiddleware={ attachmentMiddleware }
        directLine={ window.WebChat.createDirectLine({ token }) }
        store={ store }
      />,
      document.getElementById('webchat')
    );

    store.dispatch({
      type: 'WEB_CHAT/SET_SEND_BOX',
      payload: { text: 'sample:github-repository' }
    });

    document.querySelector('#webchat > *').focus();
  })().catch(err => console.error(err));
</script>

</code>```

For more details regarding the attachment middleware, take a look at this sample.

Hope this helps.

Title: Tool tip for long texts in Hero Cards

Body:
Web Chat utilizes the Adaptive Cards NPM package to render cards, and, unfortunately, Adaptive Cards does not support adding tooltip descriptions to elements in the card. There are, however, several issues open on GitHub regarding adding tooltip functionality, so hopefully, that feature will be available in Web Chat soon.

Even though Adaptive Cards doesn't support adding tooltips, you can create a custom attachment middleware for Web Chat and implement your own Hero Card renderer. The code snippet below shows a basic Hero Card renderer without any styling.

<script type="text/babel">

  const HeroCardAttachment = ({ buttons, images, title, store }) =>
    <div className='ac-container'>
      <div className='ac-container'>
        { images.map(({ url }, index) =>
          <window.React.Fragment key={ index }>
            <div>
              <img src= { url } />
            </div>
            <div style={{height: '8px'}}/>
          </window.React.Fragment>
        )}
        <div>{ title }</div>
      </div>
      <div />
      <div >
        { buttons.map(({ title, type, value }, index) => (
          <window.React.Fragment key={ index }>
            <button
              aria-label={ title }
              type='button'
              title={ title }
              onClick={ () => {
                switch (type) {
                  case 'openUrl':
                    window.open(value)
                    break;
                  case 'postBack':
                    store.dispatch({
                      type: 'WEB_CHAT/SEND_POST_BACK',
                      payload: { value }
                    });
                    break;
                  default:
                    store.dispatch({
                      type: 'WEB_CHAT/SEND_MESSAGE_BACK',
                      payload: { value, text: value, displayText: value }
                    });
                }
              }}
            >
              <div title={ title }>
                { title }
              </div>
            </button>
            <div />
          </window.React.Fragment>
        ))}
      </div>
    </div>;

  (async function () {

    const res = await fetch('/directline/token', { method: 'POST' });
    const { token } = await res.json();
    const { createStore, ReactWebChat } = window.WebChat;
    const store = createStore();

    const attachmentMiddleware = () => next => card => {
      switch (card.attachment.contentType) {
        case 'application/vnd.microsoft.card.hero':
          return <HeroCardAttachment {...card.attachment.content} store={ store }/>;
        default:
          return next(card);
      }
    };

    window.ReactDOM.render(
      <ReactWebChat
        attachmentMiddleware={ attachmentMiddleware }
        directLine={ window.WebChat.createDirectLine({ token }) }
        store={ store }
      />,
      document.getElementById('webchat')
    );

    store.dispatch({
      type: 'WEB_CHAT/SET_SEND_BOX',
      payload: { text: 'sample:github-repository' }
    });

    document.querySelector('#webchat > *').focus();
  })().catch(err => console.error(err));
</script>

For more details regarding the attachment middleware, take a look at this sample.

Hope this helps.


问:
Counting number of days in transaction data but from 6AM to 6AM of next day in PySpark
I have transaction data but I need to calculate the number of visits based on countDistinct of dates. The problem is that I need to calculate it based on a timestamp of 6AM to 6AM, i.e. if the transaction happens on 04/07 between 12 AM and 6AM, it still should be counted as a single visit.

Is there any way I can achieve that?

```<code>CUSTOMER_ID   TRANSACTION_ID   TRANSACTION_DATETIME

     C1             T1           04/07/2019 22:20:00
     C1             T1           04/08/2019 1:00:00
     C1             T2           04/07/2019 17:10:00
     C1             T3           05/08/2019 12:00:00
</code>```

So as per the above, I need the visits for each customer_ID.

This is the code I have so far

```<code>testdfmod = df.groupBy("CUSTOMER_ID") \
                           .agg(F.max(F.col('TRANSACTION_DATETIME')).alias("TRANSACTION_DATETIME"), \
                    F.countDistinct(
                                    F.to_date(F.col('TRANSACTION_DATETIME')).alias('TRANSACTION_DATETIME').cast("date")) \
                           .alias("TOTAL_TRIPS"))
</code>```

Thank you so much for all the help.

Body:
I have transaction data but I need to calculate the number of visits based on countDistinct of dates. The problem is that I need to calculate it based on a timestamp of 6AM to 6AM, i.e. if the transaction happens on 04/07 between 12 AM and 6AM, it still should be counted as a single visit.

Is there any way I can achieve that?

CUSTOMER_ID   TRANSACTION_ID   TRANSACTION_DATETIME

     C1             T1           04/07/2019 22:20:00
     C1             T1           04/08/2019 1:00:00
     C1             T2           04/07/2019 17:10:00
     C1             T3           05/08/2019 12:00:00

So as per the above, I need the visits for each customer_ID.

This is the code I have so far

testdfmod = df.groupBy("CUSTOMER_ID") \
                           .agg(F.max(F.col('TRANSACTION_DATETIME')).alias("TRANSACTION_DATETIME"), \
                    F.countDistinct(
                                    F.to_date(F.col('TRANSACTION_DATETIME')).alias('TRANSACTION_DATETIME').cast("date")) \
                           .alias("TOTAL_TRIPS"))

Thank you so much for all the help.

Body:
IIUC, you can just add a new column with value equals to TRANSACTION_DATETIME minus 6 hours (6*3600 seconds):

from pyspark.sql import functions as F

df.withColumn('adjusted_trx_date', F.from_unixtime(F.unix_timestamp('TRANSACTION_DATETIME', format='MM/dd/yyyy HH:mm:ss')-6*3600, format='yyyy-MM-dd')).show()
#+-----------+--------------+--------------------+-----------------+
#|CUSTOMER_ID|TRANSACTION_ID|TRANSACTION_DATETIME|adjusted_trx_date|
#+-----------+--------------+--------------------+-----------------+
#|         C1|            T1| 04/07/2019 22:20:00|       2019-04-07|
#|         C1|            T1|  04/08/2019 1:00:00|       2019-04-07|
#|         C1|            T2| 04/07/2019 17:10:00|       2019-04-07|
#|         C1|            T3| 05/08/2019 12:00:00|       2019-05-08|
#+-----------+--------------+--------------------+-----------------+

Then you can do countDistinct() on the new column adjusted_trx_date with the code you had.


问:
How to insert txt data into mongodb using python
I need to  insert data from file.txt into new MongoDB database.collection using python.

.txt file contains data like:

```<code>a={
    "_id"          : "67a2c0e2e559fb56bf055502",
    "field1"       : "value1",
    "field2" : ["value21","value22"],
    "field3"  : {
                       "_id"  : "37a2c0e2e559fb56bf055502",
                       "subfield1" : "subvalue1"
                     }
};

b={
    "_id"          : "67a2c0e2e559fb56bf055503",
    "field1"       : "value1",
    "field2" : ["value21","value22"],
    "field3"  : {
                       "_id"  : "27a2c0e2e559fb56bf055503",
                       "subfield1" : "subvalue1"
                     }
};

c={....
};
</code>```

I want to insert all documents if we say a=doc1, b=doc2, C=doc3, d...
I tried to split them in a list using l=split(read,';') and add it to Mongo with insert_many but I get this error

```<code>TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
</code>```

is there any way to insert the data without creating json file?
Thanks

Code

def insert():
    client = pymongo.MongoClient(dbStringConnection)

    db = client[dbName]

    collectionR = db[dbCollection]

    list1 = []
    with open (file, 'r') as f:
        reader= f.read()
        #print (reader)
    f.close()
    reader= reader.replace('\n', '')
    reader= reader.replace('  ','')
    list1 = reader.split(';')
   # print(list1[0])

    list2={}

    for i in range(len(lista)-1):

        s=''
        t=list1[i][0:1]
        s=s+str(list1[i][2:len(list1[i])])
        list2[t]=s
    collectionR.insert_many(list2)

```

答:
Thanks a lot, I was able to insert the data in MongoDB

def insert():
    client = pymongo.MongoClient(dbStringConnection)

    db = client[dbName]

    collectionR = db[dbCollection]

    list1 = []
    with open (file, 'r') as f:
        reader= f.read()

    f.close()
    reader= reader.replace('\n', '')
    reader= reader.replace('  ','')
    list1 = reader.split(';')
    for i in range(len(list1)-1):
        my_dict={}
        my_dict=eval((list1[i][2:len(list1[i])]))
        collectionR.insert_one(my_dict)
```

Body:
I need to  insert data from file.txt into new MongoDB database.collection using python.

.txt file contains data like:

a={
    "_id"          : "67a2c0e2e559fb56bf055502",
    "field1"       : "value1",
    "field2" : ["value21","value22"],
    "field3"  : {
                       "_id"  : "37a2c0e2e559fb56bf055502",
                       "subfield1" : "subvalue1"
                     }
};

b={
    "_id"          : "67a2c0e2e559fb56bf055503",
    "field1"       : "value1",
    "field2" : ["value21","value22"],
    "field3"  : {
                       "_id"  : "27a2c0e2e559fb56bf055503",
                       "subfield1" : "subvalue1"
                     }
};

c={....
};

I want to insert all documents if we say a=doc1, b=doc2, C=doc3, d...
I tried to split them in a list using l=split(read,';') and add it to Mongo with insert_many but I get this error

TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

is there any way to insert the data without creating json file?
Thanks

Code

def insert():
    client = pymongo.MongoClient(dbStringConnection)

    db = client[dbName]

    collectionR = db[dbCollection]

    list1 = []
    with open (file, 'r') as f:
        reader= f.read()
        #print (reader)
    f.close()
    reader= reader.replace('\n', '')
    reader= reader.replace('  ','')
    list1 = reader.split(';')
   # print(list1[0])

    list2={}

    for i in range(len(lista)-1):

        s=''
        t=list1[i][0:1]
        s=s+str(list1[i][2:len(list1[i])])
        list2[t]=s
    collectionR.insert_many(list2)


问:
How to compile libdvdcss on Mac with Xcode?
I am wondering how to compile the source code of libdvdcss using Xcode on Mac OS X? The file bsdi_ioctl.c has include statements for /sys/dev/scsi/scsi.h and /sys/dev/scsi/scsi_ioctl.h.

What I did is run ./bootstrap and ./configure to generate the config.h first, but I still got the problem.

Can anyone shed some light on it?

答:
It is unusual that your Makefile will be trying to include those files as the autoconf file has an instruction to look for them before including them in your Makefile.  But whatever the reason, you have a couple options for compiling:

Edit src/Makefile.  Search for $(bsdi_sources) and delete all occurrences then re-make (do not reconfigure)

or Edit configure.ac.  Search for AM_CONDITIONAL(SYS_BSDI and replace with SYS_BSDI='0'.  Then re-run ./bootstrap & ./configure

or Run SYS_BSDI="0" ./configure (single command) to re-make without.


问:
In a string with just numbers and commas how do I convert that into a double
So I have a string with just numbers and commas. for example "1,233,323.32"(String) but I want to convert that to 1233323.32(double).</p>

答:
Use NumberFormatter:

```<code>let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let number = formatter.number(from: "1,233,323.32")
</code>```

Body:
Use NumberFormatter:

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let number = formatter.number(from: "1,233,323.32")


问:
How can I use mutliple url variables?
I will convert URL's like those

```<code>example.com/tasks.php?action=list
example.com/tasks.php?action=detail&id=48
example.com/tasks.php?action=add&name=Test
</code>```

into those

```<code>example.com/tasks/list
example.com/tasks/detail/48
example.com/tasks/add?name=Test
</code>```

So, I need two variables, but the second must be optional, the file extension must be hidden and I need to add get variables.

答:
Well, you can simply implement different rewriting rules for those three separate situations. That keeps the rules simple and clear, so easy to maintain:

```<code>RewriteEngine on
RewriteRule ^/?tasks/([^/]+)/?$ /tasks.php?action=$1 [END]
RewriteRule ^/?tasks/([^/]+)/(\d+)$ /tasks.php?action=$1&id=$2 [END]
RewriteRule ^/?tasks/([^/]+)/([^/]+)/([^/]+)/?$ /tasks.php?action=$1&$2=$3 [END]
</code>```

That will implement these rewritings:

/tasks/list => /tasks.php?action=list

/tasks/detail/48 => example.com/tasks.php?action=detail&id=48

/tasks/add/name/Test => example.com/tasks.php?action=add&name=Test

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

This rule will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

Title: How can I use mutliple url variables?

Body:
I will convert URL's like those

example.com/tasks.php?action=list
example.com/tasks.php?action=detail&id=48
example.com/tasks.php?action=add&name=Test

into those

example.com/tasks/list
example.com/tasks/detail/48
example.com/tasks/add?name=Test

So, I need two variables, but the second must be optional, the file extension must be hidden and I need to add get variables.

Body:
Well, you can simply implement different rewriting rules for those three separate situations. That keeps the rules simple and clear, so easy to maintain:

RewriteEngine on
RewriteRule ^/?tasks/([^/]+)/?$ /tasks.php?action=$1 [END]
RewriteRule ^/?tasks/([^/]+)/(\d+)$ /tasks.php?action=$1&id=$2 [END]
RewriteRule ^/?tasks/([^/]+)/([^/]+)/([^/]+)/?$ /tasks.php?action=$1&$2=$3 [END]

That will implement these rewritings:

/tasks/list => /tasks.php?action=list

/tasks/detail/48 => example.com/tasks.php?action=detail&id=48

/tasks/add/name/Test => example.com/tasks.php?action=add&name=Test

In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

This rule will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


问:
How can I use Python to stream multiple audio files simultaneously
I’m looking to stream multiple audio files in .wav format to a Raspberry Pi for synchronous playback. I’m looking to use Python as my language of choice and TCP sockets, although I understand UDP might be necessary for latency. Anyone who can point me in the right direction/give some input would be much appreciated!</p>

答:
Actually, there are many approaches to do such a thing. For example, you can write your own Python script and send audio frames on a socket. But if you just need to do a stream you can use high-level tools like FFmpeg. It will give you a bunch of solutions to stream your Audio and Video on the network with bare UDP or well-optimized protocols like RTP or RTSP.

For example, if you want to stream the ALSA device plughw:1,0 to your localhost, it would become something like this:

```<code>ffmpeg -ac 1 -f alsa -i hw:0,0 -acodec libmp3lame -ab 32k -ac 1 -re -f rtp rtp://localhost:1234
</code>```

Also, you can use other tools like Alsa recording app (arecord) and pipe its output to FFmpeg:

```<code>arecord -f cd -D plughw:1,0 | ffmpeg -i - -acodec libmp3lame -ab 32k -ac 1 -re -f rtp rtp://localhost:1234
</code>```

Then you can simply play it with ffplay:

```<code>ffplay rtp://localhost:1234
</code>```

You can find more info about FFmpeg's streaming feature in here.

Body:
Actually, there are many approaches to do such a thing. For example, you can write your own Python script and send audio frames on a socket. But if you just need to do a stream you can use high-level tools like FFmpeg. It will give you a bunch of solutions to stream your Audio and Video on the network with bare UDP or well-optimized protocols like RTP or RTSP.

For example, if you want to stream the ALSA device plughw:1,0 to your localhost, it would become something like this:

ffmpeg -ac 1 -f alsa -i hw:0,0 -acodec libmp3lame -ab 32k -ac 1 -re -f rtp rtp://localhost:1234

Also, you can use other tools like Alsa recording app (arecord) and pipe its output to FFmpeg:

arecord -f cd -D plughw:1,0 | ffmpeg -i - -acodec libmp3lame -ab 32k -ac 1 -re -f rtp rtp://localhost:1234

Then you can simply play it with ffplay:

ffplay rtp://localhost:1234

You can find more info about FFmpeg's streaming feature in here.


问:
Fetching more data from binance using python loop
I am trying to fetch more than 500 rows of historical data from Binance website but I want more than 500 rows, how do i loop through it and fetch more?

The code i tried:

```<code>candles= client.get_klines(symbol='ADABTC',interval=Client.KLINE_INTERVAL_1MINUTE)
    candles_data_frame=df(candles)
</code>```

This code fetches 500 rows but i would expect more than 10000 rows of historical data. Please let me know how should i get it.

Thanks

答:
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#klinecandlestick-data the API documentation specifie the limit max at 1000. So in your case you can't get more than 1000 rows</p>

```<code>candles = client.get_klines(
    symbol='ADABTC',
    interval=Client.KLINE_INTERVAL_1MINUTE,
    limit=1000)
candles_data_frame = df(candles)
</code>```

Body:
I am trying to fetch more than 500 rows of historical data from Binance website but I want more than 500 rows, how do i loop through it and fetch more?

The code i tried:

candles= client.get_klines(symbol='ADABTC',interval=Client.KLINE_INTERVAL_1MINUTE)
    candles_data_frame=df(candles)

This code fetches 500 rows but i would expect more than 10000 rows of historical data. Please let me know how should i get it.

Thanks

Body:
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#klinecandlestick-data the API documentation specifie the limit max at 1000. So in your case you can't get more than 1000 rows

candles = client.get_klines(
    symbol='ADABTC',
    interval=Client.KLINE_INTERVAL_1MINUTE,
    limit=1000)
candles_data_frame = df(candles)


问:
Mac App Store testing receipt validation (from receigen) "app is damaged and can't be opened."
I'm using Receigen (http://receigen.etiemble.com/) to do receipt validation for one of my MacOS apps. This has worked beautifully for several years, but something has changed. I haven't made an update to this app for a year or so and submitted a change but it was rejected because the receipt validation wasn't working.

When I try to test the receipts locally, it pops up the App Store login, I enter my email+password, and then I get the "app is damaged" message.

I used the Receigen Code Assistant to generate validation code (it generates receipt validation code and randomizes as much as it can so you can't just easily crack every app that uses receigen).

I'm using macOS 10.14.3 and Xcode 10.2.

This is the header from my receigen generated code:

```<code>//
// This code was generated by RECEIGEN 4.0.4 on 2019-04-08 15:54:01 and will use:
//
// Bundle Identifier            : com.inadaydevelopment.mac10biiFinancialCalculator
// Bundle Version               : 2.1.0
// Receipt Identifier           : com.inadaydevelopment.mac10biiFinancialCalculator
// Receipt Version              : 2.1.0
//
// Language                     : ObjC
// Platform                     : OSX
// Code Prefix                  : ReceiptValidation
// Success Behavior             : RunApplication
// Failure Behavior             : ExitWith173
//
// Certificate Name             : Apple Root CA
// Certificate Fingerprint      : 611E5B662C593A08FF58D14AE22452D198DF6C60
// Signer Certificate OID       : 1.2.840.113635.100.6.11.1
//
// OpenSSL Version              : 1.0
//
// This generated code has to be linked with OpenSSL libcrypto (either statically or dynamically)
// Refer to the website for more details and specific cases.
//
</code>```

I have verified that the Bundle Id and Version match what I have in XCode (the text field isn't long enough, but it DOES start with com.inaday...):

I looked through Receigen's diagnostic page to see the possible fixes for this, but nothing helped:

1) I looked/searched through my console for any "storeagent" entries and I never find any. Perhaps the Diagnostics page has info for an older version of macOS?

2) I did the "killall" and "rm -r" commands to fix any caching problems associated with the damaged message. I also rebooted several times.

3) I looked inside the app package and I didn't see any receipt.

4) I deleted the only other copy of the app that I know of (the one I've installed from the App Store) and tried everything again. Same problem.

5) Tried removing the Container. Same problem.

6) I tried "sudo pkill -f CommerceKit". Same problem.

This is what I found in my console:

ReceiptRefreshRequest: Error fetching receipt for
  /Users/kenny/Library/Developer/Xcode/DerivedData/10bii_Financial_Calculator-edfoaceclymbdsazqdpinclhsejp/Build/Products/Debug/10bii
  Financial Calculator.app - Error Domain=com.apple.commerce.server
  Code=500317 "(null)"

Here's the full section from the console:

```<code>default 11:52:42.776265 -0700   commerce    StoreSession: StatusCode: 200; <private>; Environment: SB; URL: https://p100-sandbox.itunes.apple.com/WebObjects/MZFinance.woa/wa/createAppReceipt
debug   11:52:42.776776 -0700   commerce    looked up value <private> for key PrimaryAccount:1 in CFPrefsPlistSource<0x7fe4eb803860> (Domain: com.apple.appstore.commerce, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No)
debug   11:52:42.776811 -0700   commerce    looked up value <private> for key KnownAccounts:1 in CFPrefsPlistSource<0x7fe4ea6058a0> (Domain: com.apple.commerce, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No)
debug   11:52:42.776909 -0700   commerce    Handling response <private> for URL <private>...
debug   11:52:42.776943 -0700   commerce    No handling for HTTP status code 200 in response for URL <private>
default 11:52:42.777268 -0700   storeuid    ReceiptRefreshRequest: Error fetching receipt for /Users/kenny/Library/Developer/Xcode/DerivedData/10bii_Financial_Calculator-edfoaceclymbdsazqdpinclhsejp/Build/Products/Debug/10bii Financial Calculator.app - Error Domain=com.apple.commerce.server Code=500317 "(null)"
debug   11:52:42.777338 -0700   storeuid    Bundle: <private>, key: APP_IS_DAMAGED_TITLE, value: , table: MacAppStore, localizationName: (null), result: APP_IS_DAMAGED_TITLE
debug   11:52:42.777400 -0700   storeuid    Bundle: <private>, key: APP_IS_DAMAGED_TITLE, value: , table: Localizable, localizationName: (null), result: “%@” is damaged and can’t be opened. Delete “%@” and download it again from the App Store.
debug   11:52:42.777427 -0700   storelegacy Bundle: <private>, key: com.apple.commerce.server, value: com.apple.commerce.server, table: Error, localizationName: (null), result: com.apple.commerce.server
debug   11:52:42.777496 -0700   storeuid    Resource lookup at <private>
    Request       : appStore type: icns
    Result        : file:///System/Library/PrivateFrameworks/CommerceKit.framework/Resources/appStore.icns
debug   11:52:42.777471 -0700   storelegacy Bundle: <private>, key: The operation couldn\U2019t be completed. (%@ error %ld.), value: The operation couldn\U2019t be completed. (%@ error %ld.), table: Error, localizationName: (null), result: The operation couldn’t be completed. (%1$@ error %2$ld.)
debug   11:52:42.777544 -0700   storeuid    Bundle: <private>, key: OK, value: , table: MacAppStore, localizationName: (null), result: OK
default 11:52:42.777540 -0700   storelegacy StoreLegacy: Failed to renew receipt for application at path /Users/kenny/Library/Developer/Xcode/DerivedData/10bii_Financial_Calculator-edfoaceclymbdsazqdpinclhsejp/Build/Products/Debug/10bii Financial Calculator.app : 'The operation couldn’t be completed. (com.apple.commerce.server error 500317.)'
</code>```

答:
Found the answer here, replicated below in case the original goes away:
https://forums.developer.apple.com/thread/92419

The problem was that I was trying to login using my normal iTunes Account.

... the user must use a Sandbox Test User Apple ID, not their own Apple ID which was not clear to me at the time. Also, I have found that the user needs to log out of the Mac App Store with their own Apple ID in order to be able to even enter the Sandbox Test User Apple ID when requested.

However, the Sandbox Test User accounts are Country specific. So you need a Sandbox Test User per country. And right now, I have very similar error messages for a user in a new country. Am probably going to have to use another DTS request to figure it out.

Body:
I'm using Receigen (http://receigen.etiemble.com/) to do receipt validation for one of my MacOS apps. This has worked beautifully for several years, but something has changed. I haven't made an update to this app for a year or so and submitted a change but it was rejected because the receipt validation wasn't working.

When I try to test the receipts locally, it pops up the App Store login, I enter my email+password, and then I get the "app is damaged" message.

I used the Receigen Code Assistant to generate validation code (it generates receipt validation code and randomizes as much as it can so you can't just easily crack every app that uses receigen).

I'm using macOS 10.14.3 and Xcode 10.2.

This is the header from my receigen generated code:

//
// This code was generated by RECEIGEN 4.0.4 on 2019-04-08 15:54:01 and will use:
//
// Bundle Identifier            : com.inadaydevelopment.mac10biiFinancialCalculator
// Bundle Version               : 2.1.0
// Receipt Identifier           : com.inadaydevelopment.mac10biiFinancialCalculator
// Receipt Version              : 2.1.0
//
// Language                     : ObjC
// Platform                     : OSX
// Code Prefix                  : ReceiptValidation
// Success Behavior             : RunApplication
// Failure Behavior             : ExitWith173
//
// Certificate Name             : Apple Root CA
// Certificate Fingerprint      : 611E5B662C593A08FF58D14AE22452D198DF6C60
// Signer Certificate OID       : 1.2.840.113635.100.6.11.1
//
// OpenSSL Version              : 1.0
//
// This generated code has to be linked with OpenSSL libcrypto (either statically or dynamically)
// Refer to the website for more details and specific cases.
//

I have verified that the Bundle Id and Version match what I have in XCode (the text field isn't long enough, but it DOES start with com.inaday...):

I looked through Receigen's diagnostic page to see the possible fixes for this, but nothing helped:

1) I looked/searched through my console for any "storeagent" entries and I never find any. Perhaps the Diagnostics page has info for an older version of macOS?

2) I did the "killall" and "rm -r" commands to fix any caching problems associated with the damaged message. I also rebooted several times.

3) I looked inside the app package and I didn't see any receipt.

4) I deleted the only other copy of the app that I know of (the one I've installed from the App Store) and tried everything again. Same problem.

5) Tried removing the Container. Same problem.

6) I tried "sudo pkill -f CommerceKit". Same problem.

This is what I found in my console:

ReceiptRefreshRequest: Error fetching receipt for
  /Users/kenny/Library/Developer/Xcode/DerivedData/10bii_Financial_Calculator-edfoaceclymbdsazqdpinclhsejp/Build/Products/Debug/10bii
  Financial Calculator.app - Error Domain=com.apple.commerce.server
  Code=500317 "(null)"

Here's the full section from the console:

default 11:52:42.776265 -0700   commerce    StoreSession: StatusCode: 200; <private>; Environment: SB; URL: https://p100-sandbox.itunes.apple.com/WebObjects/MZFinance.woa/wa/createAppReceipt
debug   11:52:42.776776 -0700   commerce    looked up value <private> for key PrimaryAccount:1 in CFPrefsPlistSource<0x7fe4eb803860> (Domain: com.apple.appstore.commerce, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No)
debug   11:52:42.776811 -0700   commerce    looked up value <private> for key KnownAccounts:1 in CFPrefsPlistSource<0x7fe4ea6058a0> (Domain: com.apple.commerce, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No)
debug   11:52:42.776909 -0700   commerce    Handling response <private> for URL <private>...
debug   11:52:42.776943 -0700   commerce    No handling for HTTP status code 200 in response for URL <private>
default 11:52:42.777268 -0700   storeuid    ReceiptRefreshRequest: Error fetching receipt for /Users/kenny/Library/Developer/Xcode/DerivedData/10bii_Financial_Calculator-edfoaceclymbdsazqdpinclhsejp/Build/Products/Debug/10bii Financial Calculator.app - Error Domain=com.apple.commerce.server Code=500317 "(null)"
debug   11:52:42.777338 -0700   storeuid    Bundle: <private>, key: APP_IS_DAMAGED_TITLE, value: , table: MacAppStore, localizationName: (null), result: APP_IS_DAMAGED_TITLE
debug   11:52:42.777400 -0700   storeuid    Bundle: <private>, key: APP_IS_DAMAGED_TITLE, value: , table: Localizable, localizationName: (null), result: “%@” is damaged and can’t be opened. Delete “%@” and download it again from the App Store.
debug   11:52:42.777427 -0700   storelegacy Bundle: <private>, key: com.apple.commerce.server, value: com.apple.commerce.server, table: Error, localizationName: (null), result: com.apple.commerce.server
debug   11:52:42.777496 -0700   storeuid    Resource lookup at <private>
    Request       : appStore type: icns
    Result        : file:///System/Library/PrivateFrameworks/CommerceKit.framework/Resources/appStore.icns
debug   11:52:42.777471 -0700   storelegacy Bundle: <private>, key: The operation couldn\U2019t be completed. (%@ error %ld.), value: The operation couldn\U2019t be completed. (%@ error %ld.), table: Error, localizationName: (null), result: The operation couldn’t be completed. (%1$@ error %2$ld.)
debug   11:52:42.777544 -0700   storeuid    Bundle: <private>, key: OK, value: , table: MacAppStore, localizationName: (null), result: OK
default 11:52:42.777540 -0700   storelegacy StoreLegacy: Failed to renew receipt for application at path /Users/kenny/Library/Developer/Xcode/DerivedData/10bii_Financial_Calculator-edfoaceclymbdsazqdpinclhsejp/Build/Products/Debug/10bii Financial Calculator.app : 'The operation couldn’t be completed. (com.apple.commerce.server error 500317.)'


问:
How is this animation implemented
Can you take a look at JWT and suggest what library was used to create the animation of DIV transition from one place to another?
Also, any suggestions about the overall algorithm used to load the RSS and the construct columns/rows out of it?

Thank you.

答:
Take a look at what seems to be their "main" js file: http://www.jwt.com/js/compiled.js, and you can see that they're using a pretty huge variety of plugins, along with some self-composed stuff, probably for the feed and special case handling of data.

EDIT: the jQuery masonry plugin handles repositioning divs, while quicksand can handle filtering with animations. These are just examples of plugins that does those kinds of things, there might be other plugins as well.

Title: How is this animation implemented