问:
Javascript querySelector Problem Inside While Loop
I am trying to attach a countdown script to looped, dynamic divs. The countdown shows outside of the loop without issue, but console log shows queryselector is null inside the loop. If anyone can help it would be appreciated</p>

```<code>var expiration = data[i]['expiration'];

function getTimeRemaining(expiration) {
  var t = Date.parse(expiration) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, expiration) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelectorAll('.days');
  var hoursSpan = clock.querySelectorAll('.hours');
  var minutesSpan = clock.querySelectorAll('.minutes');
  var secondsSpan = clock.querySelectorAll('.seconds');

  function updateClock() {
    var t = getTimeRemaining(expiration);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = t.hours;
    secondsSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

initializeClock('clockdiv', expiration);

if (email == "") {

  if (promoType == "Banner") {
    $('#load-container-expiring').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameExpiringButton + '</div></div>');
    $('#load-container-expiring').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="visitor-banner-click" src=' + theBanner + '></div></div>');
    -- >>> Issue Here-- - > $('#load-container-expiring').append('<div id="clockdiv"><span class="days"></span> Days <span class="hours"></span> Hours <span class="minutes"></span> Minutes <span class="seconds"></span> Seconds</div>');
  }
</code>```

答:
At the moment you call initializeClock('clockdiv', expiration), the div with id "clockdiv" does not exist yet. And so clock will be undefined, and
clock.querySelectorAll(...) will generate an exception.

Move that  initializeClock('clockdiv', expiration) below the code that adds that "clockdiv" element to the DOM.

Also fix the first secondsSpan.innerHTML = to be minutesSpan.innerHTML =

Body:
I am trying to attach a countdown script to looped, dynamic divs. The countdown shows outside of the loop without issue, but console log shows queryselector is null inside the loop. If anyone can help it would be appreciated

var expiration = data[i]['expiration'];

function getTimeRemaining(expiration) {
  var t = Date.parse(expiration) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, expiration) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelectorAll('.days');
  var hoursSpan = clock.querySelectorAll('.hours');
  var minutesSpan = clock.querySelectorAll('.minutes');
  var secondsSpan = clock.querySelectorAll('.seconds');

  function updateClock() {
    var t = getTimeRemaining(expiration);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = t.hours;
    secondsSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

initializeClock('clockdiv', expiration);

if (email == "") {

  if (promoType == "Banner") {
    $('#load-container-expiring').append('

' + promoNameExpiringButton + '

');
    $('#load-container-expiring').append('

');
    -- >>> Issue Here-- - > $('#load-container-expiring').append('
 Days  Hours  Minutes  Seconds
');
  }


来源: stackexchange

问:
Why is my script_loader_tag hook not actually changing the type of script?
I have a Wordpress plugin, that appears as a metabox on the edit post page I'm writing which is supposed to call scripts of both custom HTML elements AND modules. However, when I view source, the scripts that need to appear as type="module" only appear as type="text/javascript". My code is:

```<code>function meta_box_setup() {
    add_action( 'add_meta_boxes', __NAMESPACE__ . '\add_meta_box' );
    add_action( 'save_post', __NAMESPACE__ . '\save_meta_box_data', 10, 2 );

    wp_register_script('Module1','/wp-content/plugins/my-plugin/js/model/module1.js');
    wp_register_script('Module2','/wp-content/plugins/my-plugin/js/module2.js', array('Module1'));
    wp_register_script('Module3','/wp-content/plugins/my-plugin/js/Controller/module3.js', array('Module1','Module2'));
    add_action( 'admin_enqueue_scripts', function () {
        wp_enqueue_script('Module1');
        wp_enqueue_script('Module2');
        wp_enqueue_script('Module3');
    });
    add_filter('script_loader_tag',
        function ($tag, $handle, $src) {
            if (( 'Module3' !== $handle ) || ('Module1' !== $handle) || ('Module2' !== $handle)) {
                return $tag;
            }
            $tag = '<script type="module" src="' . $src . '"></script>';
            return $tag;
    }
    , 10, 3);

    add_action( 'admin_enqueue_scripts', function () {
        error_log("inside the scripts callback");
        wp_enqueue_script('Element1','/wp-content/plugins/my-plugin/js/element1.js');
        wp_enqueue_script('Element2','/wp-content/plugins/my-plugin/js/element2.js');
        wp_enqueue_script('Element3','/wp-content/plugins/my-plugin/js/element3.js');
        wp_enqueue_script('Element4','/wp-content/plugins/my-plugin/js/element4.js');
    });
}
</code>```

I tried to base my code off this but to no avail. How can I get the modules to show up as type='module'?

答:
Your boolean logic for returning early should either use &&, or it should continue to use || but use that to change the tag:

<?php
add_filter('script_loader_tag',
    function ($tag, $handle, $src) {
        if (('Module3' === $handle) || ('Module1' === $handle) || ('Module2' === $handle)) {
            $tag = '';
        }

        return $tag;
    }
    , 10, 3);
```

ContentLicense: CC BY-SA 4.0

Body:
I have a Wordpress plugin, that appears as a metabox on the edit post page I'm writing which is supposed to call scripts of both custom HTML elements AND modules. However, when I view source, the scripts that need to appear as type="module" only appear as type="text/javascript". My code is:

function meta_box_setup() {
    add_action( 'add_meta_boxes', __NAMESPACE__ . '\add_meta_box' );
    add_action( 'save_post', __NAMESPACE__ . '\save_meta_box_data', 10, 2 );

    wp_register_script('Module1','/wp-content/plugins/my-plugin/js/model/module1.js');
    wp_register_script('Module2','/wp-content/plugins/my-plugin/js/module2.js', array('Module1'));
    wp_register_script('Module3','/wp-content/plugins/my-plugin/js/Controller/module3.js', array('Module1','Module2'));
    add_action( 'admin_enqueue_scripts', function () {
        wp_enqueue_script('Module1');
        wp_enqueue_script('Module2');
        wp_enqueue_script('Module3');
    });
    add_filter('script_loader_tag',
        function ($tag, $handle, $src) {
            if (( 'Module3' !== $handle ) || ('Module1' !== $handle) || ('Module2' !== $handle)) {
                return $tag;
            }
            $tag = '';
            return $tag;
    }
    , 10, 3);

    add_action( 'admin_enqueue_scripts', function () {
        error_log("inside the scripts callback");
        wp_enqueue_script('Element1','/wp-content/plugins/my-plugin/js/element1.js');
        wp_enqueue_script('Element2','/wp-content/plugins/my-plugin/js/element2.js');
        wp_enqueue_script('Element3','/wp-content/plugins/my-plugin/js/element3.js');
        wp_enqueue_script('Element4','/wp-content/plugins/my-plugin/js/element4.js');
    });
}

I tried to base my code off this but to no avail. How can I get the modules to show up as type='module'?

Body:
Your boolean logic for returning early should either use &&, or it should continue to use || but use that to change the tag:

<?php
add_filter('script_loader_tag',
    function ($tag, $handle, $src) {
        if (('Module3' === $handle) || ('Module1' === $handle) || ('Module2' === $handle)) {
            $tag = '<script type="module" src="' . $src . '"></script>';
        }

        return $tag;
    }
    , 10, 3);


问:
Google spreadsheets, giving permission to user with google script
My goal:

Every time I create a new spreadsheet, it should automatically give permission to "TheEmailIwant@gmail.com" as an editor.

Research:

```<code>  function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  ss.addEditor('TheEmailIwant@gmail.com');
  }
</code>```

Issue:
Am actually using selenium automation to create the spreadsheet and gspread to read the values from it but the issue is gspread only reads spreadsheets shared with the service account...

I tried manually going to tools > script editor and run the program above, it worked.
but when a new spreadsheet is created and I ran the same program but it didn't work.

Conclusion:
Every time selenium creates a new spreadsheet it should automatically share it to the service account.

答:
If you create a follow up spreadsheet, and assuming that the files that you create are within a specific folder, the following code will help you to list the files (this is optional in the script but could be useful) and share them to the specified email at the same time. You can either run the script from the menu created (My Files) within the spreadsheet or set a trigger to run it automatically at a specific times/days:

So, you need:

To create a new spreadsheet for listing the files

Get the ID of this spreadsheet (  // https://drive.google.com/drive/folders/ID IS HERE
)

Get the ID of the folder containing the created spreadsheets (https://docs.google.com/spreadsheets/d/ID IS HERE/edit)

Set the email to share the files with

Run the script manually each time or set up a trigger to do it automatically

Code:

```<code>   // ---------- Menu ----------
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Files')
  .addItem('List & Add Permission', 'ListFilesandAddEditor')
  .addToUi();
}

function ListFilesandAddEditor() {

  var folder = DriveApp.getFolderById('FOLDER ID GOES HERE');
  var sheetId = "SPREADHSEET ID GOES HERE";
  var ss = SpreadsheetApp.openById(sheetId);

  // specify the sheet to write the DATA, here it's Sheet1

  var sheet = ss.getSheetByName("Sheet1");
  sheet.getRange("A2:B").clear();

  var output = [];
  var file;
  var name;
  var link;
  var fileId;
  var contents = folder.getFiles();
  while(contents.hasNext()) {
    file = contents.next();
    data = [
      name =  file.getName(),
      link =  file.getUrl(),
      fileId = file.getId(),
      DriveApp.getFileById(fileId).addEditor('mynamel@gmail.com'),
    ];

    output.push([name, link]);

    // write data to the sheet
    sheet.getRange(2, 1, output.length, output[0].length).setValues(output);
  }
};
</code>```

Body:
My goal:

Every time I create a new spreadsheet, it should automatically give permission to "TheEmailIwant@gmail.com" as an editor.

Research:

  function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  ss.addEditor('TheEmailIwant@gmail.com');
  }

Issue:
Am actually using selenium automation to create the spreadsheet and gspread to read the values from it but the issue is gspread only reads spreadsheets shared with the service account...

I tried manually going to tools > script editor and run the program above, it worked.
but when a new spreadsheet is created and I ran the same program but it didn't work.

Conclusion:
Every time selenium creates a new spreadsheet it should automatically share it to the service account.

Body:
If you create a follow up spreadsheet, and assuming that the files that you create are within a specific folder, the following code will help you to list the files (this is optional in the script but could be useful) and share them to the specified email at the same time. You can either run the script from the menu created (My Files) within the spreadsheet or set a trigger to run it automatically at a specific times/days:

So, you need:

To create a new spreadsheet for listing the files

Get the ID of this spreadsheet (  // https://drive.google.com/drive/folders/ID IS HERE
)

Get the ID of the folder containing the created spreadsheets (https://docs.google.com/spreadsheets/d/ID IS HERE/edit)

Set the email to share the files with

Run the script manually each time or set up a trigger to do it automatically

Code:

   // ---------- Menu ----------
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Files')
  .addItem('List & Add Permission', 'ListFilesandAddEditor')
  .addToUi();
}

function ListFilesandAddEditor() {

  var folder = DriveApp.getFolderById('FOLDER ID GOES HERE');
  var sheetId = "SPREADHSEET ID GOES HERE";
  var ss = SpreadsheetApp.openById(sheetId);

  // specify the sheet to write the DATA, here it's Sheet1

  var sheet = ss.getSheetByName("Sheet1");
  sheet.getRange("A2:B").clear();

  var output = [];
  var file;
  var name;
  var link;
  var fileId;
  var contents = folder.getFiles();
  while(contents.hasNext()) {
    file = contents.next();
    data = [
      name =  file.getName(),
      link =  file.getUrl(),
      fileId = file.getId(),
      DriveApp.getFileById(fileId).addEditor('mynamel@gmail.com'),
    ];

    output.push([name, link]);

    // write data to the sheet
    sheet.getRange(2, 1, output.length, output[0].length).setValues(output);
  }
};


问:
Comparing runtimes
I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.

1) Is it actually worth taking such things into account?

2) Assuming it is worth taking it into account, how do I do this?

I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.

答:
If your idea is to compare the languages, I'd say anything outside them is not relevant for comparison purposes.

Nonetheless you can use the time command to measure everything and can compare it with the timing within a script.

Like this:

```<code>$ time script.php
HI!

real    0m3.218s
user    0m0.080s
sys     0m0.064s
</code>```

It will give you clock time, user time (php interpreter) and sys time (OS time)

If you are thinking web, then it gets a lot harder because you would be mixing webserver overhead and that is not always easy to compare if, say, you are using WSGI v/s mod_php. Then you'd have to hook probes into the webserving parts of the chain as well

OwnerDisplayName: Teifion

ContentLicense: CC BY-SA 3.0

Title: Comparing runtimes

LastEditorDisplayName: hoyhoy

Body:
If your idea is to compare the languages, I'd say anything outside them is not relevant for comparison purposes.

Nonetheless you can use the time command to measure everything and can compare it with the timing within a script.

Like this:

$ time script.php
HI!

real    0m3.218s
user    0m0.080s
sys     0m0.064s

It will give you clock time, user time (php interpreter) and sys time (OS time)

If you are thinking web, then it gets a lot harder because you would be mixing webserver overhead and that is not always easy to compare if, say, you are using WSGI v/s mod_php. Then you'd have to hook probes into the webserving parts of the chain as well

OwnerDisplayName: Vinko Vrsalovic

ContentLicense: CC BY-SA 2.5


问:
Is it possible to generate random numbers through physical process simulation?
Is it possible to generate random numbers through physical process simulation?

If I simulate the physical roll of a dice (i.e. you picking it up, shaking it in your hand, releasing it onto the table and recording which side ends up "up"...) will that produce a "random" number or would I just have a complex simulation which really accomplishes nothing.

答:
First you need to define 'random'. You can generate trivially unpredictable numbers by using a strange set of calculations, sure. But you won't get useful randomness or an even distribution of numbers.

A physical simulation like you describe would actually require some sort of random number generator at some point in the calculation. Fortunately, random() is easy to use.

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: John Fricker


问:
How do I access my array from my table data source?
I am starting my first Cocoa Project. And I have a serious (for me) but maybe easy problem (for you) to solve and I need some direction where to start.

The short description: I have built a class "PortConnection.h" who writes all ports found by an external class (AMSerial.h) into an array when the function -listPorts is called. Here is the code for the PortConnection.h

```<code>#import <Cocoa/Cocoa.h>
#import "AMSerialPortList.h"
#import "AMSerialPortAdditions.h"
#import "AMSerialPort.h"

@interface PortConnection : NSObject {
@private
    AMSerialPort *port;
    NSMutableArray *portArray;
}

- (void)listDevices;

@property (nonatomic, retain) NSMutableArray *portArray;
@property (nonatomic, retain) AMSerialPort *port;

@end
</code>```

and following the PortConnection.m

```<code>#import "PortConnection.h"
#import "AMSerialPortList.h"
#import "AMSerialPortAdditions.h"
#import "AMSerialPort.h"

@implementation PortConnection
@synthesize portArray;
@synthesize port;

- (void)listDevices
{
    // get an port enumerator
    NSEnumerator *enumerator = [AMSerialPortList portEnumerator];
    AMSerialPort *aPort;

    while ((aPort = [enumerator nextObject]))
    {
        // Add Devices to Array
        [portArray addObject:[aPort bsdPath]];

    }
}
</code>```

So far it is perfectly working.
Now my questions

I have implemented an tableView in the GUI for display the results of the method called above. This file is called "PortTableViewController.h" and is the datasource for my TableView.

Here is the .h file

```<code>#import <Foundation/Foundation.h>
#import "PortConnection.h"

@interface PortTableViewController : NSObject <NSTableViewDataSource> {
@private
    IBOutlet NSTableView *portTableView;
}

@property (assign) IBOutlet NSTableView *portTableView;

@end
</code>```

and here is the .m file:

```<code>#import "PortTableViewController.h"
#import "PortConnection.h"

@implementation PortTableViewController
@synthesize portTableView;

#pragma mark -
#pragma mark TableView Delegates

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
    PortConnection *portConnection = [[PortConnection alloc] init];
    [portConnection listDevices];
    return [portConnection.portArray count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
        ??????? I DO NOT HAVE A CLUE HOW TO ACCESS THE ARRAY IN PORTCONNECTION.M CORRECTLY
}

@end
</code>```

QUESTIONS:

1) When having a look on the TableViewDataSourceDelegates how do I access the filled portArray in the PortConnection.m class correctly. It doesn't seem to work the way I do it.

2) Do I have to create an Object from Portconnection.h every time I want to retrieve Data from it in a tableviewdelegate method?

I am really thankful for every kind of help! I want to learn something.. and I really appreciate your support! Thanks.. for question in order to help me, don't hesitate. I really appreciate it....

Thanks
Sebastian

答:
You should only need a single PortConnection instance, but your table view controller will somehow need to know about it. It could be that the PortTableViewController creates and owns the PortConnection object, or it could be that some other object, like the app delegate or another controller creates it.

In the former case, it's trivial... the PortTableViewController creates the PortConnection instance, and therefore it has a reference to it and can access its portArray property at well.

In the latter case, things aren't much more complicated: the object that creates the PortController should give the PortTableViewController a pointer to the PortController. The PortTableViewController should then retain the PortController and stash the pointer in an instance variable so that it can access the portArray property as needed.

Body:
I am starting my first Cocoa Project. And I have a serious (for me) but maybe easy problem (for you) to solve and I need some direction where to start.

The short description: I have built a class "PortConnection.h" who writes all ports found by an external class (AMSerial.h) into an array when the function -listPorts is called. Here is the code for the PortConnection.h

#import <Cocoa/Cocoa.h>
#import "AMSerialPortList.h"
#import "AMSerialPortAdditions.h"
#import "AMSerialPort.h"

@interface PortConnection : NSObject {
@private
    AMSerialPort *port;
    NSMutableArray *portArray;
}

- (void)listDevices;

@property (nonatomic, retain) NSMutableArray *portArray;
@property (nonatomic, retain) AMSerialPort *port;

@end

and following the PortConnection.m

#import "PortConnection.h"
#import "AMSerialPortList.h"
#import "AMSerialPortAdditions.h"
#import "AMSerialPort.h"

@implementation PortConnection
@synthesize portArray;
@synthesize port;

- (void)listDevices
{
    // get an port enumerator
    NSEnumerator *enumerator = [AMSerialPortList portEnumerator];
    AMSerialPort *aPort;

    while ((aPort = [enumerator nextObject]))
    {
        // Add Devices to Array
        [portArray addObject:[aPort bsdPath]];

    }
}

So far it is perfectly working.
Now my questions

I have implemented an tableView in the GUI for display the results of the method called above. This file is called "PortTableViewController.h" and is the datasource for my TableView.

Here is the .h file

#import <Foundation/Foundation.h>
#import "PortConnection.h"

@interface PortTableViewController : NSObject <NSTableViewDataSource> {
@private
    IBOutlet NSTableView *portTableView;
}

@property (assign) IBOutlet NSTableView *portTableView;

@end

and here is the .m file:

#import "PortTableViewController.h"
#import "PortConnection.h"

@implementation PortTableViewController
@synthesize portTableView;

#pragma mark -
#pragma mark TableView Delegates

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
    PortConnection *portConnection = [[PortConnection alloc] init];
    [portConnection listDevices];
    return [portConnection.portArray count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
        ??????? I DO NOT HAVE A CLUE HOW TO ACCESS THE ARRAY IN PORTCONNECTION.M CORRECTLY
}

@end

QUESTIONS:

1) When having a look on the TableViewDataSourceDelegates how do I access the filled portArray in the PortConnection.m class correctly. It doesn't seem to work the way I do it.

2) Do I have to create an Object from Portconnection.h every time I want to retrieve Data from it in a tableviewdelegate method?

I am really thankful for every kind of help! I want to learn something.. and I really appreciate your support! Thanks.. for question in order to help me, don't hesitate. I really appreciate it....

Thanks
Sebastian


问:
Duplicate class com.google.common.util.concurrent.ListenableFuture found in modules guava-20.0.jar (com.google.guava:guava:20.0)
When I use implementation 'com.google.firebase:firebase-inappmessaging-display:17.2.0' in my app/build.gradle, I get this error:

Duplicate class com.google.common.util.concurrent.ListenableFuture found in modules guava-20.0.jar (com.google.guava:guava:20.0) and listenablefuture-1.0.jar (com.google.guava:listenablefuture:1.0)

Go to the documentation to learn how to Fix dependency resolution errors.
```

<p>What I also have in my <code>app/build.gradle</code> is this:</p>

```implementation 'com.google.android.gms:play-services-base:16.1.0'
implementation 'com.google.android.gms:play-services-analytics:16.0.8'
implementation 'com.google.android.gms:play-services-awareness:16.0.0'
implementation 'com.google.android.gms:play-services-cast:16.2.0'
implementation 'com.google.android.gms:play-services-gcm:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-iid:17.1.2'
implementation 'com.google.firebase:firebase-messaging:17.6.0'
implementation 'android.arch.work:work-runtime:1.0.1'
implementation 'com.android.support:multidex:1.0.3'
apply plugin: 'com.google.gms.google-services'
```

Maybe one of the libraries that I am using already includes support for the In-App Messaging dependency, and then it becomes redundant? Thank you.

答:
I encountered the same problem. I added the line below

```<code>implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'
</code>```

This works but I encountered another issue- Cannot fit requested classes in a single dex file (# methods: 89411 > 65536) To resolve this error make sure to enable multiDex as below

```<code>defaultConfig {
    applicationId "com.techweezy.smartsync"
    minSdkVersion 19
    targetSdkVersion 29
    versionCode 5
    versionName "1.4"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true //added this line
}
</code>```

Then finally add the below lines.

```<code>   implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'
    implementation 'androidx.multidex:multidex:2.0.1'
</code>```

Body:
When I use implementation 'com.google.firebase:firebase-inappmessaging-display:17.2.0' in my app/build.gradle, I get this error:

Duplicate class com.google.common.util.concurrent.ListenableFuture found in modules guava-20.0.jar (com.google.guava:guava:20.0) and listenablefuture-1.0.jar (com.google.guava:listenablefuture:1.0)

Go to the documentation to learn how to Fix dependency resolution errors.

What I also have in my app/build.gradle is this:

implementation 'com.google.android.gms:play-services-base:16.1.0'
implementation 'com.google.android.gms:play-services-analytics:16.0.8'
implementation 'com.google.android.gms:play-services-awareness:16.0.0'
implementation 'com.google.android.gms:play-services-cast:16.2.0'
implementation 'com.google.android.gms:play-services-gcm:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-iid:17.1.2'
implementation 'com.google.firebase:firebase-messaging:17.6.0'
implementation 'android.arch.work:work-runtime:1.0.1'
implementation 'com.android.support:multidex:1.0.3'
apply plugin: 'com.google.gms.google-services'

Maybe one of the libraries that I am using already includes support for the In-App Messaging dependency, and then it becomes redundant? Thank you.

Body:
I encountered the same problem. I added the line below

implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'

This works but I encountered another issue- Cannot fit requested classes in a single dex file (# methods: 89411 > 65536) To resolve this error make sure to enable multiDex as below

defaultConfig {
    applicationId "com.techweezy.smartsync"
    minSdkVersion 19
    targetSdkVersion 29
    versionCode 5
    versionName "1.4"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true //added this line
}

Then finally add the below lines.

   implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'
    implementation 'androidx.multidex:multidex:2.0.1'


问:
Sending data to Azure IoT hub using REST
I am trying to learn the Azure IoT hub, but I am unable to send data to my IoT hub using Postman.
I did the following:

Create Azure IoT hub

Create a device using Azure Portal CLI

Copied the text where it said "primary key" on the Device page

My request looks as follows:

POST https://myhub.azure-devices.net/devices/MyDevice/messages/events?api-version=2020-03-13

I have added the authorization header, which has the value:
SharedAccessSignature=SharedAccessSignature sr=myhub.azure-devices.net%2Fdevices%2FMyDevice&sig=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Where the key is the copied text from the "primary key" field from the device page.

Content-type is set to application/json. But the body is currently empty.

I am getting the following response:

"Message": "ErrorCode:ServerError;InternalServerError",

Note: Hub and device name are not the same as stated here.

答:
For a quick-start on this, we have 3 stages 1) SAS key generation from Visual Studio Code see below images(Or from CLI please see the answer posted by silent) 2) Use Postman 3) Monitor via VS code

Steps: VS Code

1) Install VS Code extension tools for Azure IoT & Connect your IoT Hub as per onscreen instructions

2) You can see the list of devices in VS code Explorer. Now right click the device (created in the portal) and select 'Generate SAS Token for the device', give the time in hours like 24 and hit enter.Copy the SAS key from output window fully (entire). Sample shown below.

SharedAccessSignature
  sr=deviothub.azure-devices.net%2Fdevices%2FNewDevice&sig=H3II%2FCa5Km5V2pieP5Ti1SI%3D&se=1590867649

Steps Postman

1) I hope you have already visited this document on Azure IoT Hub REST API
Replace the required sections with your IoT Hub values.

POST
  https://fully-qualified-iothubname.azure-devices.net/devices/{id}/messages/events?api-version=2020-03-13

2) Make sure to include the fully copied SAS token and use it in the header section of POST call

3) Body content : It depends on your use case.
 example 'raw'--JSON--> {"Temperature":54}

**You can see the accepted response from IoT Hub as '204 No Content'

Step Monitor the Telemetry the easy way

1) Open the VS Code editor and right click the particular device and slect 'Start Monitoring the in built events'

2) Send another telemetry from Postman and you can see the message arrived at IoT Hub and is visible on the VS code Monitoring screen.

Happy Azure IoT Learning


问:
sphinx_rtd_theme is no longer a hard dependency since version 1.4.0

C:\Users\Administrator\Desktop\item\code_serv\documents\api>make html
  Running Sphinx v1.6.2 loading pickled environment... failed:

Can't get attribute 'WarningStream' on <module 'sphinx.util.nodes' from 'c:\\users\\administrator\\appdata\\local\\programs\\python\\python36-32\\lib\\site-packages\\sphinx\\util\\nodes.py'>

Theme error:

sphinx_rtd_theme is no longer a hard dependency since version 1.4.0.
  Please install it manually.(pip install sphinx_rtd_theme)

How do I solve this?

答:
I found another issue, I had two installations of sphinx, one via pip and another one via brew. Deleting one (I chose to remove installation done via brew ) solved this issue.

```<code>brew remove sphinx-doc
</code>```

If it still doesnt work, try uninstalling and reinstalling

```<code>pip3  uninstall sphinx sphinx_rtd_theme
pip3  install sphinx sphinx_rtd_theme
</code>```

Body:
I found another issue, I had two installations of sphinx, one via pip and another one via brew. Deleting one (I chose to remove installation done via brew ) solved this issue.

brew remove sphinx-doc

If it still doesnt work, try uninstalling and reinstalling

pip3  uninstall sphinx sphinx_rtd_theme
pip3  install sphinx sphinx_rtd_theme


问:
Add Spacing between table rows
I developed a data grid but I'm having some problems with customizing it.

Is there a way to remove the header bottom border and add a space between each row in the table?

DEMO

code

```<code><dx-data-grid style="margin-top:50px" class="table" [dataSource]="datas"
    [showColumnLines]="false" [showRowLines]="false" [columnAutoWidth]="true" [allowColumnResizing]="true">
    <dxo-header-filter [visible]="true"></dxo-header-filter>
    <dxi-column dataField="ID" dataType="text" caption="ID"></dxi-column>
    <dxi-column dataField="Name" dataType="text" caption="Name"></dxi-column>
</dx-data-grid>
</code>```

答: You can use border-bottom: 4px solid #FFFFFF; at .dx-data-row to add space between the table rows

Title: Add Spacing between table rows

Body:
I developed a data grid but I'm having some problems with customizing it.

Is there a way to remove the header bottom border and add a space between each row in the table?

DEMO

code

<dx-data-grid style="margin-top:50px" class="table" [dataSource]="datas"
    [showColumnLines]="false" [showRowLines]="false" [columnAutoWidth]="true" [allowColumnResizing]="true">
    <dxo-header-filter [visible]="true"></dxo-header-filter>
    <dxi-column dataField="ID" dataType="text" caption="ID"></dxi-column>
    <dxi-column dataField="Name" dataType="text" caption="Name"></dxi-column>
</dx-data-grid>


问:
How to change the font color of few string in p tag for a dynamic string
I have a list which needs to displayed on a pop up. Suppose my list contains below information

row 1: Name mismatch error

row 2: Expecting numbers

Row 3: mandatory field

I want the row1, row 2 , row 3 to be in red and rest of the text in black

TS:

```<code> getMessages()
 {
  var msg :string[] = [];
  var separatedMsg:any[];
  msg = this.getErrorMessage(this.messages);
  var msgBody = document.getElementById("msgBody");
  msgBody.innerHTML="";
  for(var i=0;i<msg.length;i++)
   {
   separatedMsg=msg[i].split(":")
   var pElement:any = document.createElement("p");
   var emElement:any = document.createElement("em");
   emElement.innerHTML =separatedMsg[0];
   pElement.innerHTML =  emElement.innerHTML+separatedMsg[1]+'\n';
   emElement.style.color ="Red"
   pElement.style.color = "Black"
   msgBody.appendChild(pElement)
    }
 }
</code>```

with this I get all the text in black, my idea was to split the string at : and make first half as em tag and second half as P tag. I'm not sure how to append both this tag.
How do I achieve this ?

答:
a) Perhaps it's easier to set an innerHTML as string:

```<code>msgBody.innerHTML='<div class="msg-div">test<p class="msg-p">test2 <span class="msg-what-ever">word</span></p></div>';
</code>```

b) You can use classes instead of inline style. See inline-styles-vs-classes

```<code>.msg-div {color: green;}
.msg-p {color: red;}
.msg-what-ever {color: blue;}
</code>```

Body:
I have a list which needs to displayed on a pop up. Suppose my list contains below information

row 1: Name mismatch error

row 2: Expecting numbers

Row 3: mandatory field

I want the row1, row 2 , row 3 to be in red and rest of the text in black

TS:

 getMessages()
 {
  var msg :string[] = [];
  var separatedMsg:any[];
  msg = this.getErrorMessage(this.messages);
  var msgBody = document.getElementById("msgBody");
  msgBody.innerHTML="";
  for(var i=0;i<msg.length;i++)
   {
   separatedMsg=msg[i].split(":")
   var pElement:any = document.createElement("p");
   var emElement:any = document.createElement("em");
   emElement.innerHTML =separatedMsg[0];
   pElement.innerHTML =  emElement.innerHTML+separatedMsg[1]+'\n';
   emElement.style.color ="Red"
   pElement.style.color = "Black"
   msgBody.appendChild(pElement)
    }
 }

with this I get all the text in black, my idea was to split the string at : and make first half as em tag and second half as P tag. I'm not sure how to append both this tag.
How do I achieve this ?

Body:
a) Perhaps it's easier to set an innerHTML as string:

msgBody.innerHTML='<div class="msg-div">test<p class="msg-p">test2 <span class="msg-what-ever">word</span></p></div>';

b) You can use classes instead of inline style. See inline-styles-vs-classes

.msg-div {color: green;}
.msg-p {color: red;}
.msg-what-ever {color: blue;}


问:
How can I split multiple columns of a df into multiple rows?
I have recently started learning python.
My df looks like:

```<code>**FRUITS**            **QUANTITY**        **MARKET_PRICE**             **SELLING_PRICE**
Apple                      5                    65                            50
Kiwi                       8                    80                            65
Orange                     6                    70                            55
Apple/Kiwi/Orange          9                65/80/70                       50/65/55
Apple                      4                    50                            40
Orange                     7                    65                            45
</code>```

i want to my df to look like:

```<code>**FRUITS**            **QUANTITY**        **MARKET_PRICE**             **SELLING_PRICE**
Apple                      5                    65                            50
Kiwi                       8                    80                            65
Orange                     6                    70                            55
Apple                      9                    65                            50
Kiwi                       9                    80                            65
Orange                     9                    70                            55
Apple                      4                    50                            40
Orange                     7                    65                            45
</code>```

how do i achieve this?

答:
```<code>#convert to lists
res = df.astype('str').to_numpy().tolist()

#split each entry using "/"
res1 = [[val.split("/") for val in ent]
        for ent in res]

#get the maximum length for each sublist
lengths = [max(len(v) for v in ent) for ent in res1]

#if the length of a value in a sublist is
#less than the maximum length,
# increase its length
res2 = [[v*length
         if len(v) < length else v
         for v in ent]
        for ent,length
        in zip(res1,lengths)
       ]

#zip through each sublist and chain the final outcome
final = chain.from_iterable(zip(*ent) for ent in res2)

#read back into dataframe
output = pd.DataFrame(final,columns=df.columns)
output

**FRUITS**  **QUANTITY**    **MARKET_PRICE**    **SELLING_PRICE**
0   Apple       5                 65                  50
1   Kiwi        8                 80                  65
2   Orange      6                 70                  55
3   Apple       9                 65                  50
4   Kiwi        9                 80                  65
5   Orange      9                 70                  55
6   Apple       4                 50                  40
7   Orange      7                 65                  45
</code>```

Body:
I have recently started learning python.
My df looks like:

**FRUITS**            **QUANTITY**        **MARKET_PRICE**             **SELLING_PRICE**
Apple                      5                    65                            50
Kiwi                       8                    80                            65
Orange                     6                    70                            55
Apple/Kiwi/Orange          9                65/80/70                       50/65/55
Apple                      4                    50                            40
Orange                     7                    65                            45

i want to my df to look like:

**FRUITS**            **QUANTITY**        **MARKET_PRICE**             **SELLING_PRICE**
Apple                      5                    65                            50
Kiwi                       8                    80                            65
Orange                     6                    70                            55
Apple                      9                    65                            50
Kiwi                       9                    80                            65
Orange                     9                    70                            55
Apple                      4                    50                            40
Orange                     7                    65                            45

how do i achieve this?


问:
Matching a file's string length with a file's integer
I've been working with file assignments and happend on a tricky problem where I need to read a file's numbers and match them by comparing the first integer to the second one, separated by a space. If the latter number is higher than the number of constituents in the former I'm supposed to print them out.

```<code>      Create(F, Out_File, File_Name);
      Put_Line(F, "23709 5");
      Put_Line(F, "001 4");
      Put_Line(F, "1 1");
      Put_Line(F, "10923487283462 14");
      Put_Line(F, "22 3");
</code>```

In the above scenario, which is the real problem, Id want to print lines

```<code>001 4
22 3
</code>```

because they mismatch.

Originally I planned to solve this by adding a Check variable that would be equal to 10 ** checksum (the latter integer above) -1. That would work unless it werent so that the fourth number is too big to be read and so I chose to go down the path of making the first integer a string and trying to match it's length with the checksum integer. Here's where I ran into problems. My way of naming the string stores numbers from previous lines and builds on them unfortunately. And because they build on each other my check variable doesnt work because its not matched to the actual length of the string but the combined length of the string and then some.

Here's my code:

```<code>with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;
with ada.float_text_IO; use ada.float_text_IO;

-----------------------------------------------------------------------
-- Im supposed to read the following file and detect
-- whether or not the integer in the file following immediately after
-- the space indicates how many integer places are found
-- in the integer infront of the space. If it mismatches
-- Im supposed to print it.
----------------------------------------------------------------------
procedure exercise2 is

   F: File_Type;
   File_Name: constant String := "BAD_DIGITS.TXT";
   Space : Character;
   Checksum: Integer;
   Name : String(1..20);
   L: Integer := 0;
   Ints : Integer;
   Char : Character;

   begin

      Create(F, Out_File, File_Name);
      Put_Line(F, "23709 5");
      Put_Line(F, "001 4");
      Put_Line(F, "1 1");
      Put_Line(F, "10923487283462 14");
      Put_Line(F, "22 3");

      Close(F);

      Open(F, In_File, File_Name);

      while not End_Of_File(F) loop
     while not End_Of_Line(F) loop
        loop
           Get(F, Char);
           L := L+1;
           if Char = ' ' then
          exit;
           else
          Name(L) := Char;
           end if;
        end loop;
        Get(F, Checksum);
        if L-1 > Checksum then
           Put(Name);
           Put(" ");
           Put(Checksum, Width =>0);
           New_Line;
           L := 0;
        end if;
     end loop;
     Skip_Line(F);
      end loop;

end exercise2;
</code>```

I've been sitting all day with this problem and I'm hoping someone comes along with some constructive feedback to free my mind.

答:
Be sure you zero your character counter before reading each line.
Only increment your character counter if the character is not a space.
Read the checksum value as an integer.</p>

```<code>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   F: File_Type;
   File_Name: constant String := "BAD_DIGITS.TXT";
   Space : constant Character :=  ' ';
   Checksum: Integer;
   Value : String(1..20);
   L: Integer := 0;
   Char : Character;
begin
   Create(F, Out_File, File_Name);
   Put_Line(F, "23709 5");
   Put_Line(F, "001 4");
   Put_Line(F, "1 1");
   Put_Line(F, "10923487283462 14");
   Put_Line(F, "22 3");

   Close(F);

   Open(F, In_File, File_Name);

   while not End_Of_File(F) loop
      L := 0;
      loop
         Get(File => F,
             Item => Char);
         if Char /= Space then
            L := L + 1;
            Value(L) := Char;
         else
            exit;
         end if;
      end loop;
      Get(F, Checksum);  -- Uses Ada.Integer_Text_Io
      if Checksum /= L then
         Put_Line(Value(1..L) & Checksum'Image);
      end if;

   end loop;
 end main;
</code>```

Body:
I've been working with file assignments and happend on a tricky problem where I need to read a file's numbers and match them by comparing the first integer to the second one, separated by a space. If the latter number is higher than the number of constituents in the former I'm supposed to print them out.

      Create(F, Out_File, File_Name);
      Put_Line(F, "23709 5");
      Put_Line(F, "001 4");
      Put_Line(F, "1 1");
      Put_Line(F, "10923487283462 14");
      Put_Line(F, "22 3");

In the above scenario, which is the real problem, Id want to print lines

001 4
22 3

because they mismatch.

Originally I planned to solve this by adding a Check variable that would be equal to 10 ** checksum (the latter integer above) -1. That would work unless it werent so that the fourth number is too big to be read and so I chose to go down the path of making the first integer a string and trying to match it's length with the checksum integer. Here's where I ran into problems. My way of naming the string stores numbers from previous lines and builds on them unfortunately. And because they build on each other my check variable doesnt work because its not matched to the actual length of the string but the combined length of the string and then some.

Here's my code:

with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;
with ada.float_text_IO; use ada.float_text_IO;

-----------------------------------------------------------------------
-- Im supposed to read the following file and detect
-- whether or not the integer in the file following immediately after
-- the space indicates how many integer places are found
-- in the integer infront of the space. If it mismatches
-- Im supposed to print it.
----------------------------------------------------------------------
procedure exercise2 is

   F: File_Type;
   File_Name: constant String := "BAD_DIGITS.TXT";
   Space : Character;
   Checksum: Integer;
   Name : String(1..20);
   L: Integer := 0;
   Ints : Integer;
   Char : Character;

   begin

      Create(F, Out_File, File_Name);
      Put_Line(F, "23709 5");
      Put_Line(F, "001 4");
      Put_Line(F, "1 1");
      Put_Line(F, "10923487283462 14");
      Put_Line(F, "22 3");

      Close(F);

      Open(F, In_File, File_Name);

      while not End_Of_File(F) loop
     while not End_Of_Line(F) loop
        loop
           Get(F, Char);
           L := L+1;
           if Char = ' ' then
          exit;
           else
          Name(L) := Char;
           end if;
        end loop;
        Get(F, Checksum);
        if L-1 > Checksum then
           Put(Name);
           Put(" ");
           Put(Checksum, Width =>0);
           New_Line;
           L := 0;
        end if;
     end loop;
     Skip_Line(F);
      end loop;

end exercise2;

I've been sitting all day with this problem and I'm hoping someone comes along with some constructive feedback to free my mind.

Body:
Be sure you zero your character counter before reading each line.
Only increment your character counter if the character is not a space.
Read the checksum value as an integer.

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   F: File_Type;
   File_Name: constant String := "BAD_DIGITS.TXT";
   Space : constant Character :=  ' ';
   Checksum: Integer;
   Value : String(1..20);
   L: Integer := 0;
   Char : Character;
begin
   Create(F, Out_File, File_Name);
   Put_Line(F, "23709 5");
   Put_Line(F, "001 4");
   Put_Line(F, "1 1");
   Put_Line(F, "10923487283462 14");
   Put_Line(F, "22 3");

   Close(F);

   Open(F, In_File, File_Name);

   while not End_Of_File(F) loop
      L := 0;
      loop
         Get(File => F,
             Item => Char);
         if Char /= Space then
            L := L + 1;
            Value(L) := Char;
         else
            exit;
         end if;
      end loop;
      Get(F, Checksum);  -- Uses Ada.Integer_Text_Io
      if Checksum /= L then
         Put_Line(Value(1..L) & Checksum'Image);
      end if;

   end loop;
 end main;


问:
How to store cookies using HttpClient in C#?
I'm trying to transmit some data from my application to a specific web service using HttpClient. To do that I first have to login to the web service and receive the cookie (that's the authentication method used by the web service). I do it like that:

```<code>Uri uri = "login_uri";
CookieContainer CookieContainer_login = new CookieContainer();
HttpClientHandler ch = new HttpClientHandler
{
   AllowAutoRedirect = true,
   CookieContainer = CookieContainer_login,
   UseCookies = true
};
HttpClient client = new HttpClient(ch);
List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>
{
   new KeyValuePair<string, string>("user", "test"),
   new KeyValuePair<string, string>("password", "test"),
   new KeyValuePair<string, string>("loginSource", "0")
};
FormUrlEncodedContent content = new FormUrlEncodedContent(pairs);
System.Threading.Tasks.Task<HttpResponseMessage> response = client.PostAsync(uri, content);
</code>```

It works, I receive the message about successful login via Fiddler. Now in order to use the web service (another Uri), for example to send a POST request, I have to pass my cookies (received during login process) to that request. As I am storing the cookies in the CookieContainer called CookieContainer_login I thought, that I can simply use the same client and only change the Uri in the PostAsync method or create a new client with the same HttpClientHandler and CookieContainer. Unfortunately it didn't work. Actually, I found out, that my CookieContainer is empty, even after the login process.

I tried to recreate that with HttpWebRequest like that:

```<code>string url_login = "login_uri";
string logparam = "user=test&password=test&loginSource=0";
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(url_login);
loginRequest.ContentType = "application/x-www-form-urlencoded";
loginRequest.Accept = "text/xml";
loginRequest.Method = "POST";
loginRequest.CookieContainer = CookieContainer_login;

byte[] byteArray = Encoding.UTF8.GetBytes(logparam);

loginRequest.ContentLength = byteArray.Length;

Stream dataStream_login = loginRequest.GetRequestStream();
dataStream_login.Write(byteArray, 0, byteArray.Length);
</code>```

It works, I also receive the successful login message, but also when I check the CookieContainer count, it shows 3 cookies that are being stored after login. Now my question is why with HttpClient there are no cookies in CookieContainer, but with the HttpWebRequest there are? How to get the cookies with the HttpClient as well?

答:
Okay, I managed to solve my problem and hopefully my answer will be useful to someone with the similar issue. In my case the mistake was in the method PostAsync invocation. It's an asynchronous method so it needs an await operator that I was missing. The proper method invocation should look like this:

HttpResponseMessage response = new HttpResponseMessage();
response = await client.PostAsync(uri, content);

Now all the cookies are stored in my CookieContainer.

Body:
I'm trying to transmit some data from my application to a specific web service using HttpClient. To do that I first have to login to the web service and receive the cookie (that's the authentication method used by the web service). I do it like that:

Uri uri = "login_uri";
CookieContainer CookieContainer_login = new CookieContainer();
HttpClientHandler ch = new HttpClientHandler
{
   AllowAutoRedirect = true,
   CookieContainer = CookieContainer_login,
   UseCookies = true
};
HttpClient client = new HttpClient(ch);
List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>
{
   new KeyValuePair<string, string>("user", "test"),
   new KeyValuePair<string, string>("password", "test"),
   new KeyValuePair<string, string>("loginSource", "0")
};
FormUrlEncodedContent content = new FormUrlEncodedContent(pairs);
System.Threading.Tasks.Task<HttpResponseMessage> response = client.PostAsync(uri, content);

It works, I receive the message about successful login via Fiddler. Now in order to use the web service (another Uri), for example to send a POST request, I have to pass my cookies (received during login process) to that request. As I am storing the cookies in the CookieContainer called CookieContainer_login I thought, that I can simply use the same client and only change the Uri in the PostAsync method or create a new client with the same HttpClientHandler and CookieContainer. Unfortunately it didn't work. Actually, I found out, that my CookieContainer is empty, even after the login process.

I tried to recreate that with HttpWebRequest like that:

string url_login = "login_uri";
string logparam = "user=test&password=test&loginSource=0";
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(url_login);
loginRequest.ContentType = "application/x-www-form-urlencoded";
loginRequest.Accept = "text/xml";
loginRequest.Method = "POST";
loginRequest.CookieContainer = CookieContainer_login;

byte[] byteArray = Encoding.UTF8.GetBytes(logparam);

loginRequest.ContentLength = byteArray.Length;

Stream dataStream_login = loginRequest.GetRequestStream();
dataStream_login.Write(byteArray, 0, byteArray.Length);

It works, I also receive the successful login message, but also when I check the CookieContainer count, it shows 3 cookies that are being stored after login. Now my question is why with HttpClient there are no cookies in CookieContainer, but with the HttpWebRequest there are? How to get the cookies with the HttpClient as well?


问:
Issue using React Hooks
I am getting this error while attempting to use useState within react:

https://i.imgur.com/XLQ7oq7.png

I have:

Reinstalled all modules

Made sure they are all up to date

Checked that I dont have duplicate react

I have thoroughly gone through this website and nothing helps

答:
I'd recommend reading this documentation: https://reactjs.org/docs/hooks-intro.html

React hooks can only be used in a functional component and they should not be used in the return / render hook.

Try this:

```<code>function component() {
 const [gridMode, setGridMode] = useState(false);

 return() {
  <button onClick={()=> setGridMode(true)}>Change hook state!</button>
  //an example of how to manipulate your hook
 }
}
</code>```

Title: Issue using React Hooks

Body:
I'd recommend reading this documentation: https://reactjs.org/docs/hooks-intro.html

React hooks can only be used in a functional component and they should not be used in the return / render hook.

Try this:

function component() {
 const [gridMode, setGridMode] = useState(false);

 return() {
  <button onClick={()=> setGridMode(true)}>Change hook state!</button>
  //an example of how to manipulate your hook
 }
}


问:
Ulimits in Docker host vs container
I wasn't able to find straight answer, to this question, but here it is:

Let's say that I have a host which has max open files 1024:

```<code>[root@host]# ulimit -a
open files                      (-n) 1024
</code>```

and a docker container running in that host with:

```<code>[root@container]# ulimit -a
open files                      (-n) 1048576
</code>```

So will I have any problem in container if I try to open more than 1024 files? I think the real limit in this case for container will be 1024 files. What do you think?

答:
I needed a direct answer to the OP's question:

So will I have a problem in container if I try to open more then 1024 files?

No. In this case I've found that the host value has no effect inside of the container and the Docker container can specify its own ulimit values.

In other words, it is valid for your container to set a higher value than the host's default value. So the effective ulimit nofile value in the container is 1048576 and this will work fine.

Title: Ulimits in Docker host vs container

Body:
I wasn't able to find straight answer, to this question, but here it is:

Let's say that I have a host which has max open files 1024:

[root@host]# ulimit -a
open files                      (-n) 1024

and a docker container running in that host with:

[root@container]# ulimit -a
open files                      (-n) 1048576

So will I have any problem in container if I try to open more than 1024 files? I think the real limit in this case for container will be 1024 files. What do you think?


问:
How to properly filter an object that has an array of objects
I'm trying to filter an array to get only what I want and I have tried with filter and reduce, but I was not able to make it fully work. I'm trying to get only the objects that has "System.State" with an "oldValue" and a "newValue"

```<code>const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
  ]
}
</code>```

The problem is that value array contains several objects that may NOT have "System.State" and some that have "System.State" but only with "newValue", instead of "oldValue" and "newValue", so I'm receiving a lot of undefined errors and I really don't know how to treat these situations.

This is a example that dont have "System.State" and another one that have "System.State" but with "newValue" only:

```<code>const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
    {
      "id": 24,
      "fields": {
        "System.State": {
          "newValue": "New"
        }
      }
    },
    {
      "id": 25,
      "fields": {
        "System.AuthorizedDate": { // This is only an example of an object that does not have System.State
          "newValue": "2020-03-13T14:14:37.1Z"
        }
      }
    },
  ]
}
</code>```

I'm using TFS API if anyone wants to know. This is what I have tried using filter:

```<code>data.value.fields.filter(status => status.fields['System.State'].oldValue === 'Forecasted' && status.fields['System.State'] === 'Done')
</code>```

And this was using reducer:

```<code>  const filter = data.value.reduce((c, n) => {
    const HasNewAndOldValue = c.fields['System.State'].oldValue === 'Forecasted' && c.fields['System.State'].newValue === 'Done';
    if (c.fields['System.State'] && HasNewAndOldValue) {
      return c;
    }
    c.push(n);
  }, [])
  console.log(data.value.fields && filter);
</code>```

What I'm doing wrong? Btw, I'm using ['System.State'] because I can't access an object property that has a dot.

答:
Just filter the value property to include only the array elements that contain:

"fields": {
  "System.State": {
    "oldValue": "anything",
    "newValue:": "anything"
  }
}
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function filterData(data) {
  let filteredValue = data.value.filter(el => {
    return el.fields["System.State"] &&
      el.fields["System.State"].oldValue &&
      el.fields["System.State"].newValue;
  });
  return { value: filteredValue };
}

const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
    {
      "id": 24,
      "fields": {
        "System.State": {
          "newValue": "New"
        }
      }
    },
    {
      "id": 25,
      "fields": {
        "System.AuthorizedDate": {
        // This is only an example of an object that does not have System.State
          "newValue": "2020-03-13T14:14:37.1Z"
        }
      }
    },
  ]
}

let filtData = filterData(data);
document.getElementById('results').innerHTML =
  JSON.stringify(filtData, null, 2);</code>```

Filtered data:

```</code>```

Body:
I'm trying to filter an array to get only what I want and I have tried with filter and reduce, but I was not able to make it fully work. I'm trying to get only the objects that has "System.State" with an "oldValue" and a "newValue"

const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
  ]
}

The problem is that value array contains several objects that may NOT have "System.State" and some that have "System.State" but only with "newValue", instead of "oldValue" and "newValue", so I'm receiving a lot of undefined errors and I really don't know how to treat these situations.

This is a example that dont have "System.State" and another one that have "System.State" but with "newValue" only:

const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
    {
      "id": 24,
      "fields": {
        "System.State": {
          "newValue": "New"
        }
      }
    },
    {
      "id": 25,
      "fields": {
        "System.AuthorizedDate": { // This is only an example of an object that does not have System.State
          "newValue": "2020-03-13T14:14:37.1Z"
        }
      }
    },
  ]
}

I'm using TFS API if anyone wants to know. This is what I have tried using filter:

data.value.fields.filter(status => status.fields['System.State'].oldValue === 'Forecasted' && status.fields['System.State'] === 'Done')

And this was using reducer:

  const filter = data.value.reduce((c, n) => {
    const HasNewAndOldValue = c.fields['System.State'].oldValue === 'Forecasted' && c.fields['System.State'].newValue === 'Done';
    if (c.fields['System.State'] && HasNewAndOldValue) {
      return c;
    }
    c.push(n);
  }, [])
  console.log(data.value.fields && filter);

What I'm doing wrong? Btw, I'm using ['System.State'] because I can't access an object property that has a dot.

Body:
Just filter the value property to include only the array elements that contain:

"fields": {
  "System.State": {
    "oldValue": "anything",
    "newValue:": "anything"
  }
}

function filterData(data) {
  let filteredValue = data.value.filter(el => {
    return el.fields["System.State"] &&
      el.fields["System.State"].oldValue &&
      el.fields["System.State"].newValue;
  });
  return { value: filteredValue };
}

const data = {
  "value": [
    {
      "id": 23,
      "fields": {
        "System.State": {
          "oldValue": "Forecasted",
          "newValue": "Done"
        }
      }
    },
    {
      "id": 24,
      "fields": {
        "System.State": {
          "newValue": "New"
        }
      }
    },
    {
      "id": 25,
      "fields": {
        "System.AuthorizedDate": {
        // This is only an example of an object that does not have System.State
          "newValue": "2020-03-13T14:14:37.1Z"
        }
      }
    },
  ]
}

let filtData = filterData(data);
document.getElementById('results').innerHTML =
  JSON.stringify(filtData, null, 2);

Filtered data:<br/>
<pre id="results"></pre>


问:
Control - M | Mass update 'Active Environment Retention' from Forever to 1 day
Problem is with Control-M Version 9,

Multiple occasions I've tried to mass update the retention of jobs with control-m's mass update tool, i can use this for almost anything else however with this particular feature i can't get it working.

Does anyone know of any guides? I've looked round and have not been able to find people using it to amend environment retention only other things, which I've also been able to do in the past.

I've had a good play, and am now at my witts end, any help would be greatly appreciated.

Thanks all,

Jack

答: Assuming that you are doing the mass update in the Active Environment (AJF) then you could try using the ctmpsm command.


问:
R warning: " 'package:stats' may not be available when loading"
I've been working with the arules package and RODBC package for a few days now in RStudio. I saved the workspace image multiple times in the meantime. But today I wanted to save my workspace image again and now I get this warning:

Warning message:
  In save(list = ls(envir = .GlobalEnv, all.names = TRUE), file = outfile,  :
    'package:stats' may not be available when loading

I only used arules and RODBC functions and str_split_fixed from stringr and some standard stuff like data.frame.

I didn't even use the stats package at all. When reloading the workspace image, it doesn't seem affected by it. But the warning is bothering me anyway, especially since stats is supposed to be a standard package of R, how can it be unavailable... How can I resolve this warning?

答:
This is now an official rstudio bug.

In my case (the repro in the bug) the root cause was that one of the objects I was trying to save referenced an rstudio-internal function (this isn’t very exotic. A plain options call returns a list that does that). RStudio functions live in tools:rstudio namespace, which inherits the stats package among others - hence the warning.

It is currently planned to be fixed as part of v1.4.


问:
Assign a property value outside of the static resource file
I don't know if I've phrased the question correctly, but here is my problem.
I have 3 buttons on the screen. Each button uses the same MyButtonStyle from the static resources file. All 3 buttons behave in the same manner, but I want each one's border to have a different CornerRadius property. Since the Button itself doesn't have a CornerRadius property, I cannot use TemplateBinding as I did for Background and Brushes. I could extend the base style to create 3 separate ones, but I wanted to try doing it this way.

Here is my code:

```<code><Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border Name="border"
                        BorderThickness="2"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        Background="{TemplateBinding Background}"
                        CornerRadius = something >

                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</code>```

So the question is, what exactly should I put as the value of CornerRadius, in order to be able to modify it separately for each object, from code or the Window XAML file?

I was aiming for something like this, although I'm not sure if it's doable:

```<code><Button x:Name="Button1"
        Width="240"
        Height="150"
        Style="{StaticResource MyButtonStyle}"
        BoundNameForCornerRadius="10"/>
</code>```

答:
If you are not using the property Tag for other purposes, you may find your way with a simple solution by binding CornerRadius in the style to the Tag property of the button:

```<code>        <Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Name="border"
                            BorderThickness="2"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            Background="{TemplateBinding Background}"
                            CornerRadius = "{Binding Path=Tag,
    RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}}" >

                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</code>```
```<code>        <Button x:Name="Button1"
                    Width="240"
                    Height="150"
                    Style="{StaticResource MyButtonStyle}"
                    Tag="10"/>   <!-- set CornerRadius to 10-->

        <Button x:Name="Button2"
                    Width="240"
                    Height="150"
                    Style="{StaticResource MyButtonStyle}"
                    Tag="30"/> <!-- set CornerRadius to 30 -->
</code>```

I admit that this solution is not helping to make the code/style more clear/readable but it is easy and makes the job done.

Body:
If you are not using the property Tag for other purposes, you may find your way with a simple solution by binding CornerRadius in the style to the Tag property of the button:

        <Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Name="border"
                            BorderThickness="2"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            Background="{TemplateBinding Background}"
                            CornerRadius = "{Binding Path=Tag,
    RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}}" >

                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <Button x:Name="Button1"
                    Width="240"
                    Height="150"
                    Style="{StaticResource MyButtonStyle}"
                    Tag="10"/>   <!-- set CornerRadius to 10-->

        <Button x:Name="Button2"
                    Width="240"
                    Height="150"
                    Style="{StaticResource MyButtonStyle}"
                    Tag="30"/> <!-- set CornerRadius to 30 -->

I admit that this solution is not helping to make the code/style more clear/readable but it is easy and makes the job done.


问:
Check if file has changed using HTML5 File API
Okay, so I have a program which outputs some specific data to a tab separated variable file.

I had been using Excel to open and view the file contents, however I found excel's insistence on locking every file it opens to be incredibly annoying as my program would crash if I left the file open in Excel... but I would really like the data to neatly update after each run of the program, so I don't have to close and re-open the file all the time.

So, I decided it would be easiest to use Javascript to parse the file and display it in a html table, and it was. I knocked something together in no time. Now my program doesn't crash if I leave the file on display, however, it still doesn't update... and I have to open the newly generated file each time.

So, I was wondering if there was a mechanism by which my Javascript could be somehow notified of a change to the file by another process? I know this is unlikely, but I would like to avoid simply polling the file for obvious reasons.

I am very familiar with JS, but HTML5 and the new APIs are all new to me.

答:
There is two solutions to this problem, and <input type="file"> is not one of them. according to the spec, it creates a "snapshot" of the file.

Native File System

This api is experimental and requires flags to be enabled in blink (aka chromium browsers). The idea is that you get a file handle and when you need the file then you call the async "getFile" function to retrieve the actual file.

This feature is a "power feature" and require your site to be secure, and it can't work in sandboxed iframes.

So without testing here is some "code in the dark":

```<code>// triggerd on click
async function pickFile () {
  const handle = showOpenFilePicker()
  let lastModificationTime = 0

  async function compare () {
    const file = await handle.getFile()
    if (file.lastModified > lastModificationTime) {
      lastModificationTime = +file.lastModified
      console.log(await file.text())
    }
  }

  setInterval(compare, 1000)
}
</code>```

Get Entry from Drag and drop

Similar to the native file system you can also retrieve a file handle and do the same thing, but this feature works in all browsers today. but this code snippet don't work in stackoverflow since it use some sandboxing do making it incompatible, so here is a fiddle with few comments

```<code>function drop(event) {
  event.stopPropagation();
  event.preventDefault();

  // get the file as an fileEntry (aka file handle)
  const fileEntry = event.dataTransfer.items[0].webkitGetAsEntry()
  let lastModificationTime = 0

  async function read (file) {
    // use the new async read method on blobs.
    console.log(await file.text())
  }

  function compare (meta) {
    if (meta.modificationTime > lastModificationTime) {
      lastModificationTime = meta.modificationTime
      fileEntry.file(read)
    }
  }

  setInterval(fileEntry.getMetadata.bind(fileEntry, compare), 1000)
}
</code>```

Edit: there is now also a way to get drag and dropped files as a FileSystemFileHandle that is much nicer to work with

elem.addEventListener('dragover', evt => {
  // Prevent navigation.
  evt.preventDefault()
})
elem.addEventListener('drop', async evt => {
  // Prevent navigation.
  evt.preventDefault()

  // Process all of the items.
  for (const item of evt.dataTransfer.items) {
    // kind will be 'file' for file/directory entries.
    if (item.kind === 'file') {
      const entry = await item.getAsFileSystemHandle();
      if (entry.kind === 'file') {
        // use same solution as the first Native File System solution
      }
    }
  }
})
```

Body:
There is two solutions to this problem, and <input type="file"> is not one of them. according to the spec, it creates a "snapshot" of the file.

Native File System

This api is experimental and requires flags to be enabled in blink (aka chromium browsers). The idea is that you get a file handle and when you need the file then you call the async "getFile" function to retrieve the actual file.

This feature is a "power feature" and require your site to be secure, and it can't work in sandboxed iframes.

So without testing here is some "code in the dark":

// triggerd on click
async function pickFile () {
  const handle = showOpenFilePicker()
  let lastModificationTime = 0

  async function compare () {
    const file = await handle.getFile()
    if (file.lastModified > lastModificationTime) {
      lastModificationTime = +file.lastModified
      console.log(await file.text())
    }
  }

  setInterval(compare, 1000)
}

Get Entry from Drag and drop

Similar to the native file system you can also retrieve a file handle and do the same thing, but this feature works in all browsers today. but this code snippet don't work in stackoverflow since it use some sandboxing do making it incompatible, so here is a fiddle with few comments

function drop(event) {
  event.stopPropagation();
  event.preventDefault();

  // get the file as an fileEntry (aka file handle)
  const fileEntry = event.dataTransfer.items[0].webkitGetAsEntry()
  let lastModificationTime = 0

  async function read (file) {
    // use the new async read method on blobs.
    console.log(await file.text())
  }

  function compare (meta) {
    if (meta.modificationTime > lastModificationTime) {
      lastModificationTime = meta.modificationTime
      fileEntry.file(read)
    }
  }

  setInterval(fileEntry.getMetadata.bind(fileEntry, compare), 1000)
}

Edit: there is now also a way to get drag and dropped files as a FileSystemFileHandle that is much nicer to work with

elem.addEventListener('dragover', evt => {
  // Prevent navigation.
  evt.preventDefault()
})
elem.addEventListener('drop', async evt => {
  // Prevent navigation.
  evt.preventDefault()

  // Process all of the items.
  for (const item of evt.dataTransfer.items) {
    // kind will be 'file' for file/directory entries.
    if (item.kind === 'file') {
      const entry = await item.getAsFileSystemHandle();
      if (entry.kind === 'file') {
        // use same solution as the first Native File System solution
      }
    }
  }
})


问:
Setting values with Vuex
I'm currently trying to learn Vuex.

I want so the the number-value increases each time you click on the element using a mutation(changeNumber).

```<code>let state = {
  counter: 0,
  someOtherValue: 'Text'
}

let changeNumber = {
  increment(state) {
    state.counter += 1
  }
}

let store = new Vuex.Store({
  changeNumber,
  state
})

Vue.component('counter-button', {
  computed: {
    counter() {
      return this.$store.state.counter
    }
  },
  template: `<input :value="$store.state.counter" @click="$store.commit('increment')" type="button">`
})

Vue.component('some-component', {
  computed: {
    someOtherValue() {
      return this.$store.state.someOtherValue
    }
  },
  template: '<div>{{ someOtherValue }}</div>'
})

new Vue({
  el: '#app',
  store,
  template: '<some-component></some-component>',

})
</code>```

My code is corrected by a bot, and I get returned two errors. What's wrong with my code?

```<code>Err) clicking on the paragraph causes the number value to change
Err) triggering the changeNumber mutation causes the number value to change
</code>```

答:
You should pass the mutations to the store under the key mutations instead of changeNumber. Note that in your code changeNumber is not the mutation, increment is the actual mutation.

```<code>let mutations = {
  increment(state) {
    state.counter += 1
  }
}

let store = new Vuex.Store({
  mutations,
  state
})
</code>```

Title: Setting values with Vuex

Body:
I'm currently trying to learn Vuex.

I want so the the number-value increases each time you click on the element using a mutation(changeNumber).

let state = {
  counter: 0,
  someOtherValue: 'Text'
}

let changeNumber = {
  increment(state) {
    state.counter += 1
  }
}

let store = new Vuex.Store({
  changeNumber,
  state
})

Vue.component('counter-button', {
  computed: {
    counter() {
      return this.$store.state.counter
    }
  },
  template: `<input :value="$store.state.counter" @click="$store.commit('increment')" type="button">`
})

Vue.component('some-component', {
  computed: {
    someOtherValue() {
      return this.$store.state.someOtherValue
    }
  },
  template: '
{{ someOtherValue }}
'
})

new Vue({
  el: '#app',
  store,
  template: '<some-component></some-component>',

})

My code is corrected by a bot, and I get returned two errors. What's wrong with my code?

Err) clicking on the paragraph causes the number value to change
Err) triggering the changeNumber mutation causes the number value to change

Body:
You should pass the mutations to the store under the key mutations instead of changeNumber. Note that in your code changeNumber is not the mutation, increment is the actual mutation.

let mutations = {
  increment(state) {
    state.counter += 1
  }
}

let store = new Vuex.Store({
  mutations,
  state
})


问:
iPhone - encoding and decoding a NSValue
So I read here on SO that I can encode a CGLayerRef to a NSValue using

```<code>NSValue *myCopy = [[NSValue alloc] initWithBytes:&myLayer objCType:@encode(CGLayerRef)];
</code>```

but how do I recreate the CGLayerRef from myCopy?

thanks

答:
This should work:</p>

```<code>CGLayerRef giveMeBackTheLayer;
[myCopy getValue:&giveMeBackTheLayer];
</code>```

Body:
So I read here on SO that I can encode a CGLayerRef to a NSValue using

NSValue *myCopy = [[NSValue alloc] initWithBytes:&myLayer objCType:@encode(CGLayerRef)];

but how do I recreate the CGLayerRef from myCopy?

thanks

Body:
This should work:

CGLayerRef giveMeBackTheLayer;
[myCopy getValue:&giveMeBackTheLayer];


问:
Cannot display image in laravel
I've tried displaying an image with laravel using a Query-- The images are stored in the storage directory and a symlink with "public" has already been established.

I have tried using:
src="{{storage_path('app/public/'.$post->post_image)}}"

src="{{ asset('storage/'.$post->post_image) }}"

src="{{$post->post_image}}"

Testing, I discovered I could use a static path in order to succesfully display the imaage like so:

src="{{ asset('storage/images/image_name.jpeg')}}"

However, this is not what I'm looking for.

The query {{$post->post_image}} returns the following:

127.0.0.1:8000/images/image_name.jpeg

EDIT: If I go edit the database and add "storage/" before the url of the image, then I can use src="{{asset($post->post_image)}}" to display it.

As mentioned before, I already tried src="{{asset('storage/' . $post->post_image)}} without altering the database.

答:
You must save the relative path of the image, after this, you can access as follows:

```<code>src="{{ asset('storage/'. $post->post_image )}}"
</code>```

for more info: docs

Title: Cannot display image in laravel

Body:
You must save the relative path of the image, after this, you can access as follows:

src="{{ asset('storage/'. $post->post_image )}}"

for more info: docs


问:
How do I answer this question correctly using SQL
"The second report presents a complete list of students with the subjects each has undertaken, their result for that subject, and their average mark for the units taken.

The columns required are as follows:

```<code>student ID,
forename,
surname,
subject ID,
result
</code>```

After each student display, the report should also display the average mark obtained by each student for their program.

An overall average mark should be displayed at the end of the report."

I am very new to SQL so any help on the syntax for this question would be greatly appreciated.

At the moment I have gotten as far as displaying all the columns with all the student details using:

```<code>select student.student_ID
     , student.forename
     , student.surname
     , result.subject_ID
     , result.result
  from student
     , result;
</code>```

But it gives me all the results as the same for whatever reason

As I said i'm not very handy with sql so even just a pseudo-syntaz would be great explaining what I have to do to get this done would be great.

It should be simple for someone with basic sql knowledge i'd imagine.

Thanks in advance

Connor

UPDATE: progress pic

However when adding group by. i seem to get the results for only one class? Do I need to group by something else?
One class pic

Thanks guys i've been on discord severs looking for help for hours and this is defo helping me a lot more. cheers

UPDATE2:

I now get this by adding ROLLUP, its looking good but I don't think these averages correspond to each individual student

Sorry for being so bad at this...
 I'm dumb the 4th row down for each student is the average..it is correct...but is it supposed to display like this?

答:
You haven't specified any relationship between the rows of student and result in your query. So it simply returns every combination of rows in the tables -- this is called a cross product or cross join.

You need to indicate how the rows should be paired up so each student is only shown with their own results, not those of other students. You do this with a JOIN with ON condition.

```<code>SELECT student.student_ID, student.forename, student.surname, result.subject_ID, result.result
FROM student
JOIN result ON student.student_ID = result.student_ID
</code>```

To get the average for each student, you need to use GROUP BY student.student_ID along with the aggregation function AVG().

```<code>SELECT student.student_ID, student.forename, student.surname, AVG(result.result) AS avg_result
FROM student
JOIN result ON student.student_ID = result.student_ID
GROUP BY student.student_ID
</code>```

To get an overall average, you leave out the grouping. In this case you don't even need to join with the student table.

```<code>SELECT AVG(result) AS avg_result
FROM result
</code>```

You can get all the results in a single query by using the WITH ROLLUP option.

```<code>SELECT student.student_ID, student.forename, student.surname, AVG(result.result) AS avg_result
FROM student
JOIN result ON student.student_ID = result.student_ID
GROUP BY student.student_ID, result.subject_ID WITH ROLLUP
</code>```

The average per student will have subject_ID = NULL, the overall average will have student_ID = NULL.

Body:
"The second report presents a complete list of students with the subjects each has undertaken, their result for that subject, and their average mark for the units taken.

The columns required are as follows:

student ID,
forename,
surname,
subject ID,
result

After each student display, the report should also display the average mark obtained by each student for their program.

An overall average mark should be displayed at the end of the report."

I am very new to SQL so any help on the syntax for this question would be greatly appreciated.

At the moment I have gotten as far as displaying all the columns with all the student details using:

select student.student_ID
     , student.forename
     , student.surname
     , result.subject_ID
     , result.result
  from student
     , result;

But it gives me all the results as the same for whatever reason

As I said i'm not very handy with sql so even just a pseudo-syntaz would be great explaining what I have to do to get this done would be great.

It should be simple for someone with basic sql knowledge i'd imagine.

Thanks in advance

Connor

UPDATE: progress pic

However when adding group by. i seem to get the results for only one class? Do I need to group by something else?
One class pic

Thanks guys i've been on discord severs looking for help for hours and this is defo helping me a lot more. cheers

UPDATE2:

I now get this by adding ROLLUP, its looking good but I don't think these averages correspond to each individual student

Sorry for being so bad at this...
 I'm dumb the 4th row down for each student is the average..it is correct...but is it supposed to display like this?

Body:
You haven't specified any relationship between the rows of student and result in your query. So it simply returns every combination of rows in the tables -- this is called a cross product or cross join.

You need to indicate how the rows should be paired up so each student is only shown with their own results, not those of other students. You do this with a JOIN with ON condition.

SELECT student.student_ID, student.forename, student.surname, result.subject_ID, result.result
FROM student
JOIN result ON student.student_ID = result.student_ID

To get the average for each student, you need to use GROUP BY student.student_ID along with the aggregation function AVG().

SELECT student.student_ID, student.forename, student.surname, AVG(result.result) AS avg_result
FROM student
JOIN result ON student.student_ID = result.student_ID
GROUP BY student.student_ID

To get an overall average, you leave out the grouping. In this case you don't even need to join with the student table.

SELECT AVG(result) AS avg_result
FROM result

You can get all the results in a single query by using the WITH ROLLUP option.

SELECT student.student_ID, student.forename, student.surname, AVG(result.result) AS avg_result
FROM student
JOIN result ON student.student_ID = result.student_ID
GROUP BY student.student_ID, result.subject_ID WITH ROLLUP

The average per student will have subject_ID = NULL, the overall average will have student_ID = NULL.


问:
How to access resources from another proyect
I have two resource files called String.arg.resx and String.en.rex in a proyect called Common

Then I Have a class called LocalizationService in my Service proyect, the code is as follows:

```<code>public class LocalizationService
{
    private ResourceManager resourceManager;
    private CultureInfo cultureInfo;

    public LocalizationService()
    {
        SetDefaultCultureAndResource();
    }

    private void SetDefaultCultureAndResource()
    {
        cultureInfo = CultureInfo.CreateSpecificCulture("en");
        resourceManager = new ResourceManager("Common.Resources.String", Assembly.GetAssembly(typeof(Common.Resources));
    }

    public void ChangeLanguage(Languages languages)
    {
        switch (languages)
        {
            case Languages.Español:
                cultureInfo = CultureInfo.CreateSpecificCulture("es");
                resourceManager = new ResourceManager("Common.Resources.String", typeof(LocalizationService).Assembly);
                break;
            case Languages.English:
                cultureInfo = CultureInfo.CreateSpecificCulture("en");
                break;
            default:
                cultureInfo = CultureInfo.CreateSpecificCulture("en");
                break;
        }
    }

    public string GetString(string value)
    {
        return resourceManager.GetString(value, cultureInfo);
    }

}
</code>```

But the line resourceManager = new ResourceManager("Common.Resources.String", Assembly.GetAssembly(typeof(Common.Resources)); is not working, because I dont see Common.Resources.

Which Method of the Assembly class I should be using?

答: Ok... It seems I found the answer, I just put a Class that is inside the assembly where the Resource files are.</p>

Body:
I have two resource files called String.arg.resx and String.en.rex in a proyect called Common

Then I Have a class called LocalizationService in my Service proyect, the code is as follows:

public class LocalizationService
{
    private ResourceManager resourceManager;
    private CultureInfo cultureInfo;

    public LocalizationService()
    {
        SetDefaultCultureAndResource();
    }

    private void SetDefaultCultureAndResource()
    {
        cultureInfo = CultureInfo.CreateSpecificCulture("en");
        resourceManager = new ResourceManager("Common.Resources.String", Assembly.GetAssembly(typeof(Common.Resources));
    }

    public void ChangeLanguage(Languages languages)
    {
        switch (languages)
        {
            case Languages.Español:
                cultureInfo = CultureInfo.CreateSpecificCulture("es");
                resourceManager = new ResourceManager("Common.Resources.String", typeof(LocalizationService).Assembly);
                break;
            case Languages.English:
                cultureInfo = CultureInfo.CreateSpecificCulture("en");
                break;
            default:
                cultureInfo = CultureInfo.CreateSpecificCulture("en");
                break;
        }
    }

    public string GetString(string value)
    {
        return resourceManager.GetString(value, cultureInfo);
    }

}

But the line resourceManager = new ResourceManager("Common.Resources.String", Assembly.GetAssembly(typeof(Common.Resources)); is not working, because I dont see Common.Resources.

Which Method of the Assembly class I should be using?


问:
Which file is an anonymous memory mapping mapped to in linux?
My question is, when we create an anonymous memory mapping, what is the file that is being mapped into the address space of the process. I know that an anonymous mapping is guaranteed to be filled with zeros. Is it then the /dev/zero file? From what I understand, Inter Process Communication is not possible until there is some file that is being mapped inside the participating processes' address spaces ... be it a file in tmpfs or in the normal file system. I am new to Inter Process Communication, if you find any flaw in my understanding, please rectify.

答:
From man mmap:

MAP_ANONYMOUS

The mapping is not backed by any file; [...]

It just allocates and initializes the memory. Before calling mmap, you would get a protection violation (SIGSEGV) trying to access the memory since the virtual memory wasn't mapped to real memory. (Well, that's what happens in system with virtual memory.)


问:
If else, then redirect
I am trying to make a password login page but when you get the password correct, it just alerts the person that it is correct. But I want it to alert and to redirect to another page. For example, google.com. Here is my code, any help would be appreciated.

```<code>// Function to check Whether both passwords
// are same or not.
function checkPassword(form) {
    password = form.pass.value;
    correct = "admin";

    // If password not entered
    if (password == '')
        alert("Please enter Password");

    // If confirm password not entered
    else if (correct == '')
        alert("Please enter confirm password");

    // If Not same return False.
    else if (password != correct) {
        alert("\nPassword is incorrect. Please try again...")
        return false;
    }

    // If same return True.
    else {
        alert("Password is correct, press okay to continue.")
        return true;
    }
}
</code>```

I am very new to coding and got this off of a YouTube Video so I literally don't know anything about JavaScript but I do know about HTML and CSS.

答:
Use the window.location.href to point to the url you want to proceed to. I have modified your example to redirect to www.google.com if the password is right

// Function to check Whether both passwords
// are same or not.
function checkPassword(form) {
  password = form.pass.value;
  correct = "admin";

  // If password not entered
  if (password == '')
    alert("Please enter Password");

  // If confirm password not entered
  else if (correct == '')
    alert("Please enter confirm password");

  // If Not same return False.
  else if (password != correct) {
    alert("\nPassword is incorrect. Please try again...")
    return false;
  }

  // If same return True.
  else {
    alert("Password is correct, press okay to continue.")
    window.location.href = 'https://www.google.com'
  }
}```

Title: If else, then redirect

Body:
I am trying to make a password login page but when you get the password correct, it just alerts the person that it is correct. But I want it to alert and to redirect to another page. For example, google.com. Here is my code, any help would be appreciated.

// Function to check Whether both passwords
// are same or not.
function checkPassword(form) {
    password = form.pass.value;
    correct = "admin";

    // If password not entered
    if (password == '')
        alert("Please enter Password");

    // If confirm password not entered
    else if (correct == '')
        alert("Please enter confirm password");

    // If Not same return False.
    else if (password != correct) {
        alert("\nPassword is incorrect. Please try again...")
        return false;
    }

    // If same return True.
    else {
        alert("Password is correct, press okay to continue.")
        return true;
    }
}

I am very new to coding and got this off of a YouTube Video so I literally don't know anything about JavaScript but I do know about HTML and CSS.


问:
How can I outline the whole container when search bar is pressed?
How can I outline the whole container(search button and search bar) when search bar is pressed?

.container {
  display: flex;
  flex-direction: row;
  border: 1px solid gray;
  width: 22%;
  height: 42px;
}

.container:focus {
  outline-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <form>
    <center>
        <input type="text" class="sea" placeholder="Search supplies...">
        <button class="toc"></button>
    </center>
    </form>
</div></code>```

答:
May be this will help you out

    document.querySelector(".sea").addEventListener('click',function(){
        document.querySelector(".center").classList.add("active");
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   .container {
      display:flex;
      flex-direction:row;
      border:1px solid gray;
      width: 22%;
      height: 42px;
    }

    .container:focus {
      outline-color: green;
    }
    form{
      padding:2px;
      height:50px;
      }
      .active{
      border:1px solid black;
      }</code>```

        <form>
        <input type = "text" class = "sea" placeholder = "Search supplies..."><button class = "toc"></button>
        </form>

```

Body:
How can I outline the whole container(search button and search bar) when search bar is pressed?

.container {
  display: flex;
  flex-direction: row;
  border: 1px solid gray;
  width: 22%;
  height: 42px;
}

.container:focus {
  outline-color: green;
}

    <form>

        <input type="text" class="sea" placeholder="Search supplies...">
        <button class="toc"></button>

    </form>

Body:
May be this will help you out

    document.querySelector(".sea").addEventListener('click',function(){
        document.querySelector(".center").classList.add("active");
    });

   .container {
      display:flex;
      flex-direction:row;
      border:1px solid gray;
      width: 22%;
      height: 42px;
    }

    .container:focus {
      outline-color: green;
    }
    form{
      padding:2px;
      height:50px;
      }
      .active{
      border:1px solid black;
      }

    <div class = "container">
        <form>
        <center class="center"><input type = "text" class = "sea" placeholder = "Search supplies..."><button class = "toc"></button></center>
        </form>
    </div>


问:
How can I get a modified copy of a immutable object?
How can I get a modified copy of a immutable object?

I.e. how could some_magical_method look like in this snipped?

import attr

@attr.s(frozen=True, slots=True)
class Config:
    param1: int = attr.ib()
    param2: str = attr.ib()

my_base_config = Config(param1=1, param2="2")
my_derived_config = my_base_config.some_magical_method(param2="two")

print(my_derived_config.param1) # output: 1
print(my_derived_config.param2) # output: two
```

Background: I want to use immutable objects for my configuration. But I also want to avoid code duplication when dealing with very similar configurations, e.g. for unit tests

答:
attrs has a function specifically for you: https://www.attrs.org/en/stable/api.html#attr.evolve

Since it takes the instance as a first arguments you can use it to define a method too:

@attr.s
class C:
    some_magical_method = attr.evolve
```

Body:
How can I get a modified copy of a immutable object?

I.e. how could some_magical_method look like in this snipped?

import attr

@attr.s(frozen=True, slots=True)
class Config:
    param1: int = attr.ib()
    param2: str = attr.ib()

my_base_config = Config(param1=1, param2="2")
my_derived_config = my_base_config.some_magical_method(param2="two")

print(my_derived_config.param1) # output: 1
print(my_derived_config.param2) # output: two

Background: I want to use immutable objects for my configuration. But I also want to avoid code duplication when dealing with very similar configurations, e.g. for unit tests