问:
jquery iframeFix implementation
I have a jquery-ui modal popup that contains an iframe.  It is called as so:

```<code>    $("#modalDiv").dialog({
        modal: true,
        autoOpen: false,
        height: '400',
        width: '400',
        position: ['150', '200'],
        draggable: true,
        resizable: false,
        title: 'Loading...'
    });

    $('#modalIFrame').attr('src', url);
    $('#modalDiv').dialog('open');
</code>```

The problem is that dragging the modal around is very sketchy.  I understand it's basically due to the iframe intercepting the drag event.  I'm trying to implement the "iframeFix" solution, but it doesn't seem to work. I am currently calling it from the popup as so:

```<code>    window.parent.$("#modalDiv").draggable("option", "iframeFix", true);
</code>```

I also tried it from the parent page in these two ways:

```<code>    $("#modalDiv").draggable("option", "iframeFix", true);
    $("#modalIFrame").draggable("option", "iframeFix", true);
</code>```

No luck.

答:
I am unsure as to how the iframeFix works, but here is the solution that I use at the moment. I added a bug report on the jQuery UI website and it seems that they are working on this for the next release of jQuery UI.

I notice that your dialog specifies that it is non-resizable, so the following should resolve your problem. If you required a resizable dialog then you would need to replace dialogdragstart with dialogdragstart dialogresizestart and likewise dialogdragstop with dialogdragstop dialogresizestop.

```<code>$("#modalDiv")
    .dialog({
        modal    : true,
        autoOpen : false,
        height   : 400,
        width    : 400,
        position : [ 150, 200 ],
        draggable: true,
        resizable: false,
        title    : 'Loading...'
    })
    .bind('dialogdragstart', function() {
        var overlay = $(this).find('.hidden-dialog-overlay');
        if (!overlay.length) {
            overlay = $('<div class="hidden-dialog-overlay" style="position:absolute;top:0;left:0;right:0;bottom:0;z-order:100000;"></div>');
            overlay.appendTo(this);
        }
        else
            overlay.show();
    })
    .bind('dialogdragstop', function() {
        $(this).find('.hidden-dialog-overlay').hide();
    });
</code>```

Title: jquery iframeFix implementation

Body:
I have a jquery-ui modal popup that contains an iframe.  It is called as so:

    $("#modalDiv").dialog({
        modal: true,
        autoOpen: false,
        height: '400',
        width: '400',
        position: ['150', '200'],
        draggable: true,
        resizable: false,
        title: 'Loading...'
    });

    $('#modalIFrame').attr('src', url);
    $('#modalDiv').dialog('open');

The problem is that dragging the modal around is very sketchy.  I understand it's basically due to the iframe intercepting the drag event.  I'm trying to implement the "iframeFix" solution, but it doesn't seem to work. I am currently calling it from the popup as so:

    window.parent.$("#modalDiv").draggable("option", "iframeFix", true);

I also tried it from the parent page in these two ways:

    $("#modalDiv").draggable("option", "iframeFix", true);
    $("#modalIFrame").draggable("option", "iframeFix", true);

No luck.

Body:
I am unsure as to how the iframeFix works, but here is the solution that I use at the moment. I added a bug report on the jQuery UI website and it seems that they are working on this for the next release of jQuery UI.

I notice that your dialog specifies that it is non-resizable, so the following should resolve your problem. If you required a resizable dialog then you would need to replace dialogdragstart with dialogdragstart dialogresizestart and likewise dialogdragstop with dialogdragstop dialogresizestop.

$("#modalDiv")
    .dialog({
        modal    : true,
        autoOpen : false,
        height   : 400,
        width    : 400,
        position : [ 150, 200 ],
        draggable: true,
        resizable: false,
        title    : 'Loading...'
    })
    .bind('dialogdragstart', function() {
        var overlay = $(this).find('.hidden-dialog-overlay');
        if (!overlay.length) {
            overlay = $('<div class="hidden-dialog-overlay" style="position:absolute;top:0;left:0;right:0;bottom:0;z-order:100000;"></div>');
            overlay.appendTo(this);
        }
        else
            overlay.show();
    })
    .bind('dialogdragstop', function() {
        $(this).find('.hidden-dialog-overlay').hide();
    });


来源: stackexchange

问:
how to use PATCH method with Jersey Invocation Builder?
```<code>WebTarget webTarget = httpClient.target(url);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON)
                .header(HttpUtils.AUTHORISATION_HEADER_NAME, "Bearer " + theAccessToken);
response = invocationBuilder.put(Entity.json(objectMapper.writeValueAsString(payload)));
</code>```

httpClient is of type javax.ws.rs.client.Client and gets injected.

invocatioBuilder implements javax.ws.rs.client.Invocation.Builder, but is defined in package org.glassfish.jersey.client

invocationBuilder.put, invocationBuilder.post, invocationBuilder.get all exist and work, but here is no invocationBuilder.patch - it's missing.

Any suggestions on how to patch?

==== UPDATE ====

After some googling, it seems that jersey client has no support for patch. As all our apps API calls are made using jersey client, this is a bit of a problem.  I assume Ill need to find an alternative library, method and code to call patch, but it needs to support OATH 2.0 also.  Any ideas if such a library exists, and, ideally has some examples?

FYI, using Java 1.8.0_131-b11

答:
I found @Paul Samsotha, @John Little Accepted Answer to be correct.

If you don't find javax.ws.rs.client.Client to be directly injectable, a Bean method similar to this (if you have a Bean that extends extends Consumer<ClientBuilder>) may further help to access it:

```<code>import java.util.function.Consumer;

import javax.ws.rs.client.ClientBuilder;

@Bean
public Consumer<ClientBuilder> patchOverrideEnhancer() {
    return (client) -> {
        client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
    };
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
WebTarget webTarget = httpClient.target(url);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON)
                .header(HttpUtils.AUTHORISATION_HEADER_NAME, "Bearer " + theAccessToken);
response = invocationBuilder.put(Entity.json(objectMapper.writeValueAsString(payload)));

httpClient is of type javax.ws.rs.client.Client and gets injected.

invocatioBuilder implements javax.ws.rs.client.Invocation.Builder, but is defined in package org.glassfish.jersey.client

invocationBuilder.put, invocationBuilder.post, invocationBuilder.get all exist and work, but here is no invocationBuilder.patch - it's missing.

Any suggestions on how to patch?

==== UPDATE ====

After some googling, it seems that jersey client has no support for patch. As all our apps API calls are made using jersey client, this is a bit of a problem.  I assume Ill need to find an alternative library, method and code to call patch, but it needs to support OATH 2.0 also.  Any ideas if such a library exists, and, ideally has some examples?

FYI, using Java 1.8.0_131-b11

Body:
I found @Paul Samsotha, @John Little Accepted Answer to be correct.

If you don't find javax.ws.rs.client.Client to be directly injectable, a Bean method similar to this (if you have a Bean that extends extends Consumer<ClientBuilder>) may further help to access it:

import java.util.function.Consumer;

import javax.ws.rs.client.ClientBuilder;

@Bean
public Consumer<ClientBuilder> patchOverrideEnhancer() {
    return (client) -> {
        client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
    };
}


问:
How do I add Linux capabilities SYS_NICE and DAC_READ_SEARCH to container in AWS Fargate?
I'm trying to setup a task definition in ECS Fargate for running Koha containers but Fargate won't accept

--cap-add=SYS_NICE --cap-add=DAC_READ_SEARCH

(or any other kernel capabilities except for SYS_PTRACE) in the task definition json file. I tried adding  "linuxParameters": {"capabilities": {  "add": [   "SYS_NICE", "DAC_READ_SEARCH"],to the task definition json file but Fargate simply deletes the code.
The mpm_itk module fails without this option (and my container throws an 500 error with the following warning/error in the logs

[mpm_itk:warn] [pid 17146] (itkmpm: pid=17146 uid=33, gid=33) itk_post_perdir_config(): setgid(1000): Operation not permitted

How do I work around this? Is there a way to pass on these capabilities after the container has started up? Any help will be appreciated, thanks!

答:
The container created by docker runc is bounded by capability flag i.e.

0x00000000a80425fb=cap_chown,cap_dac_override,cap_fowner,cap_fsetid,cap_kill,cap_setgid,cap_setuid,cap_setpcap,cap_net_bind_service,cap_net_raw,cap_sys_chroot,cap_mknod,cap_audit_write,cap_setfcap

The container can get the capabilities from this set only.


问:
How do I get QuickLook to show offline files?
Our iPad app can show Documents and save them offline when needed.
I've got a QLPreviewController subclass named DocumentViewController (named DVC from now on) for showing them.

Workflow of the app:
- The user clicks a name of a document and the DVC is pushed on to show the document.
- The DVC downloads the file offline and shows it when done.
  (So the HTTP URL is downloaded, stored offline, and an offline URL is returned)

The weird thing is, is that only PDF files are working with the offline URL, and the rest crashes.. (it works with online links though)

I did some tests and when I put file:// before the offline link the app does not crash but the DVC is ging me some information about the file (like that it is a excel 97-2004 document).

So some info is transferred, but I can't figure out what the problem is.

Here are some screenshots and after that some code.

code:
Note that Document is a model class with document properties like id, name, file type and url.

```<code>//DVC QLPreviewController dataSource method for returning url
- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger)index
{
    [SaveHelper saveDocumentFileAndPropertyWithDocument:document];

    //[SaveHelper getDocumentFileWithDocument:document]; without file://
    //if I return document.documentUrl it is working with all files except iworks files)
    return [SaveHelper getDocumentFileAsPathWithDocument:document]; //with file://
}

//SaveHelper methods
+ (NSString *)documentFilePathWithDocument:(Document *)document
{
    return [[self documentFilePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%d.%@", DOCUMENT_FILE_PREFIX, document.documentId, document.documentType]];
}

+ (NSURL *)saveDocumentFileAndPropertyWithDocument:(Document *)document
{
    if([self saveDocumentPropertyWithDocument:document])
    {
        return [self saveDocumentFileWithDocument:document];
    }

    return nil;
}

+ (NSURL *)saveDocumentFileWithDocument:(Document *)document
{
    NSData *data = [NSData dataWithContentsOfURL:document.documentURL];

    NSString *fullPath = [self documentFilePathWithDocument:document];

   if([[NSKeyedArchiver archivedDataWithRootObject:data] writeToFile:fullPath atomically:YES])
   {
       return [NSURL fileURLWithPath:fullPath];
   }

    return nil;
}

+ (NSURL *)getDocumentFileWithDocument:(Document *)document
{
    return [NSURL fileURLWithPath:[self documentFilePathWithDocument:document]];
}

+ (NSURL *)getDocumentFileAsPathWithDocument:(Document *)document
{
    return [NSURL fileURLWithPath:[@"file://" stringByAppendingPathComponent:[[self getDocumentFileWithDocument:document] absoluteString]]];
}
</code>```

If more code needed, just say.

EDIT:

When logging the URL passed trough the 'getDocumentFileAsPathWithDocument' method:

```<code>url: file:/var/mobile/Applications/xx-xx/Documents/documentFiles/file_20.pdf
url: file:/var/mobile/Applications/xx-xx/Documents/documentFiles/file_80.docx
</code>```

Where the PDF file is working and the docx not

When I try to load an image(jpg) from local storage I get a black screen with this error message:

```<code>warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.5 (8L1)/Symbols/System/Library/Frameworks/QuickLook.framework/DisplayBundles/Image.qldisplay/Image (file not found).
warning: No copy of Image.qldisplay/Image found locally, reading from memory on remote device.  This may slow down the debug session.
</code>```

EDIT:

The webview does not work either with the local urls. PDF is fine but the office files gives an message "Unable to read Document, the file format is invalid". The iWorks documents give the same error as the quicklook. I think its somewhere at the save and load of the format, I savve them as a NSDATA but after that there is no hint for the iPad to see if it is for example a word document (only the extension).

答:
first of all, use this code to make sure your documents are there,because i think the error cause by your documents path. </p>

```<code>NSFileManager *fileManager=[NSFileManager defaultManager];

        if([fileManager fileExistsAtPath:fullPath]){
            NSLog(@"%@  exsit! ",fullPath);
        }else{
            NSLog(@"%@  not exsit! ",fullPath);

        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Our iPad app can show Documents and save them offline when needed.
I've got a QLPreviewController subclass named DocumentViewController (named DVC from now on) for showing them.

Workflow of the app:
- The user clicks a name of a document and the DVC is pushed on to show the document.
- The DVC downloads the file offline and shows it when done.
  (So the HTTP URL is downloaded, stored offline, and an offline URL is returned)

The weird thing is, is that only PDF files are working with the offline URL, and the rest crashes.. (it works with online links though)

I did some tests and when I put file:// before the offline link the app does not crash but the DVC is ging me some information about the file (like that it is a excel 97-2004 document).

So some info is transferred, but I can't figure out what the problem is.

Here are some screenshots and after that some code.

code:
Note that Document is a model class with document properties like id, name, file type and url.

//DVC QLPreviewController dataSource method for returning url
- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger)index
{
    [SaveHelper saveDocumentFileAndPropertyWithDocument:document];

    //[SaveHelper getDocumentFileWithDocument:document]; without file://
    //if I return document.documentUrl it is working with all files except iworks files)
    return [SaveHelper getDocumentFileAsPathWithDocument:document]; //with file://
}

//SaveHelper methods
+ (NSString *)documentFilePathWithDocument:(Document *)document
{
    return [[self documentFilePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%d.%@", DOCUMENT_FILE_PREFIX, document.documentId, document.documentType]];
}

+ (NSURL *)saveDocumentFileAndPropertyWithDocument:(Document *)document
{
    if([self saveDocumentPropertyWithDocument:document])
    {
        return [self saveDocumentFileWithDocument:document];
    }

    return nil;
}

+ (NSURL *)saveDocumentFileWithDocument:(Document *)document
{
    NSData *data = [NSData dataWithContentsOfURL:document.documentURL];

    NSString *fullPath = [self documentFilePathWithDocument:document];

   if([[NSKeyedArchiver archivedDataWithRootObject:data] writeToFile:fullPath atomically:YES])
   {
       return [NSURL fileURLWithPath:fullPath];
   }

    return nil;
}

+ (NSURL *)getDocumentFileWithDocument:(Document *)document
{
    return [NSURL fileURLWithPath:[self documentFilePathWithDocument:document]];
}

+ (NSURL *)getDocumentFileAsPathWithDocument:(Document *)document
{
    return [NSURL fileURLWithPath:[@"file://" stringByAppendingPathComponent:[[self getDocumentFileWithDocument:document] absoluteString]]];
}

If more code needed, just say.

EDIT:

When logging the URL passed trough the 'getDocumentFileAsPathWithDocument' method:

url: file:/var/mobile/Applications/xx-xx/Documents/documentFiles/file_20.pdf
url: file:/var/mobile/Applications/xx-xx/Documents/documentFiles/file_80.docx

Where the PDF file is working and the docx not

When I try to load an image(jpg) from local storage I get a black screen with this error message:

warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.5 (8L1)/Symbols/System/Library/Frameworks/QuickLook.framework/DisplayBundles/Image.qldisplay/Image (file not found).
warning: No copy of Image.qldisplay/Image found locally, reading from memory on remote device.  This may slow down the debug session.

EDIT:

The webview does not work either with the local urls. PDF is fine but the office files gives an message "Unable to read Document, the file format is invalid". The iWorks documents give the same error as the quicklook. I think its somewhere at the save and load of the format, I savve them as a NSDATA but after that there is no hint for the iPad to see if it is for example a word document (only the extension).

Body:
first of all, use this code to make sure your documents are there,because i think the error cause by your documents path.

NSFileManager *fileManager=[NSFileManager defaultManager];

        if([fileManager fileExistsAtPath:fullPath]){
            NSLog(@"%@  exsit! ",fullPath);
        }else{
            NSLog(@"%@  not exsit! ",fullPath);

        }


问:
Do global variables take longer fetch time?
The below code works fine for attached input.

```<code>public class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        return wordBreakMemo(s, new HashSet<>(wordDict), 0, new Boolean[s.length()]);
    }

    private boolean wordBreakMemo(String s, Set<String> wordDict, int start, Boolean[] memo) {
        if (start == s.length()) {
            return true;
        }
        if (memo[start] != null) {
            return memo[start];
        }
        for (int end = start + 1; end <= s.length(); end++) {
            if (wordDict.contains(s.substring(start, end)) && wordBreakMemo(s, wordDict, end, memo)) {
                return memo[start] = true;
            }
        }
        return memo[start] = false;
    }
}
</code>```

But when I change the local variables to global as below, my code take longer to execute, resulting in 'Time Limit Exceeded' on LeetCode.

```<code>class Solution {
    HashSet<String> set;
    String s;
    Boolean dp[];
    public boolean wordBreak(String s, List<String> wordDict) {

        set=new HashSet();
        set.addAll(wordDict);
        this.s=s;
        dp=new Boolean[s.length()];
        return wordMemo(0);
    }
    public boolean wordMemo(int start)
    {
        if(start==s.length())
            return true;

        if(dp[start]!=null)
            return dp[start];

        for(int i=start+1; i<=s.length(); i++)
        {
            if(set.contains(s.substring(start, i)) && wordMemo(i))
            {
                dp[start]=true;
                return true;
            }
        }
        return false;
    }
}
</code>```

Input:

```<code>"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
</code>```

Can someone please explain what is happening around here?

答:
Global variables don't have slower fetch times, no.

Whenever you get Time Limit Exceeded in a coding challenge you should assume you have a a flawed or buggy algorithm or data structure. It's never micro factors like fetch times or access modifiers or the language you've chosen. Even if you could speed up your program 10% with better memory access patterns or 100% by switching from Python to C, you're probably off by 10,000% or 10,000,000%, not 100%. That's how bad it can be when your program is accidentally O(n2) or O(2n) when the challenge designers expect O(n).

Here, the first program has:

```<code>return memo[start] = false;
</code>```

While the second one has just:

```<code>return false;
</code>```

It never memoizes false results. There are a lot more repeated computations, enough to kill the algorithm's Big-O time complexity.

Body:
The below code works fine for attached input.

public class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        return wordBreakMemo(s, new HashSet<>(wordDict), 0, new Boolean[s.length()]);
    }

    private boolean wordBreakMemo(String s, Set<String> wordDict, int start, Boolean[] memo) {
        if (start == s.length()) {
            return true;
        }
        if (memo[start] != null) {
            return memo[start];
        }
        for (int end = start + 1; end <= s.length(); end++) {
            if (wordDict.contains(s.substring(start, end)) && wordBreakMemo(s, wordDict, end, memo)) {
                return memo[start] = true;
            }
        }
        return memo[start] = false;
    }
}

But when I change the local variables to global as below, my code take longer to execute, resulting in 'Time Limit Exceeded' on LeetCode.

class Solution {
    HashSet<String> set;
    String s;
    Boolean dp[];
    public boolean wordBreak(String s, List<String> wordDict) {

        set=new HashSet();
        set.addAll(wordDict);
        this.s=s;
        dp=new Boolean[s.length()];
        return wordMemo(0);
    }
    public boolean wordMemo(int start)
    {
        if(start==s.length())
            return true;

        if(dp[start]!=null)
            return dp[start];

        for(int i=start+1; i<=s.length(); i++)
        {
            if(set.contains(s.substring(start, i)) && wordMemo(i))
            {
                dp[start]=true;
                return true;
            }
        }
        return false;
    }
}

Input:

"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]

Can someone please explain what is happening around here?

Body:
Global variables don't have slower fetch times, no.

Whenever you get Time Limit Exceeded in a coding challenge you should assume you have a a flawed or buggy algorithm or data structure. It's never micro factors like fetch times or access modifiers or the language you've chosen. Even if you could speed up your program 10% with better memory access patterns or 100% by switching from Python to C, you're probably off by 10,000% or 10,000,000%, not 100%. That's how bad it can be when your program is accidentally O(n2) or O(2n) when the challenge designers expect O(n).

Here, the first program has:

return memo[start] = false;

While the second one has just:

return false;

It never memoizes false results. There are a lot more repeated computations, enough to kill the algorithm's Big-O time complexity.


问:
Tags not rendering in React

const Albums = ({artist, album, textBarInput}) => {

    let indexOfTheArtist = takeTheIndexOfTheArtist(artist);   // -1 means not found    |    >= 0   means found and return his position
    let artistAlbums =  bands[indexOfTheArtist].albums

    for(let i = 0; i < artistAlbums.length; i+=1){
        return(
             <Record spotifyLink={artistAlbums[i].spotifyLink} imageLink={artistAlbums[i].imageLink} title={artistAlbums[i].title} releaseDate={artistAlbums[i].releaseDate}></Record>
                );
    }
}

const Record = ({spotifyLink, imageLink, title, releaseDate}) => {
    return(
            ,

{title}
,

Release Date: {releaseDate}

        );
}

export default Albums
```

Hi there,
I'm working on a personal project which is a music gallery using React. So I have two select options(one for artists and one for albums) and an input bar so that the user can type the artist that they want and get the albums of that band. I also have an array named bands in which each entrance is a dictionary with the artist name (artist) and also a dictionary with all of the albums of that band with data like release date, spotify link and an image source of the album cover. As you can see on my Albums component I receive as props the input from the user, but when I pass these values to the Record component the only thing that renders on the page is the release date paragraph. Am I missing something?

答:
i'm pretty sure that the problem is data not being updated correctly.
try adding a state that holds your current artist, and then for every record just pass the data from the state. something like this:

add a state in your main component:
const [currentArtist, setCurrentArtist] = useState({});

use the setCurrentArtist after choosing the right artist,

add record for each album like this:

{currentArtist.albums.map((album) => <Record {...album} />)}```
</div>
</div>
</p>
<p>make sure the artist object in the state has keys with the props names. it should look like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{ spotifyLink: '.../.../', imageLink: '.../.../', title: 'Song Title' ...}</code>```

by doing so, you can just spread the album item as a prop (example in code) and not needing to pass props one by one.

Title: Tags not rendering in React

Body:
const Albums = ({artist, album, textBarInput}) => {

    let indexOfTheArtist = takeTheIndexOfTheArtist(artist);   // -1 means not found    |    >= 0   means found and return his position
    let artistAlbums =  bands[indexOfTheArtist].albums

    for(let i = 0; i < artistAlbums.length; i+=1){
        return(
             <Record spotifyLink={artistAlbums[i].spotifyLink} imageLink={artistAlbums[i].imageLink} title={artistAlbums[i].title} releaseDate={artistAlbums[i].releaseDate}></Record>
                );
    }
}

const Record = ({spotifyLink, imageLink, title, releaseDate}) => {
    return(
            ,

{title}
,

Release Date: {releaseDate}

        );
}

export default Albums

Hi there,
I'm working on a personal project which is a music gallery using React. So I have two select options(one for artists and one for albums) and an input bar so that the user can type the artist that they want and get the albums of that band. I also have an array named bands in which each entrance is a dictionary with the artist name (artist) and also a dictionary with all of the albums of that band with data like release date, spotify link and an image source of the album cover. As you can see on my Albums component I receive as props the input from the user, but when I pass these values to the Record component the only thing that renders on the page is the release date paragraph. Am I missing something?

Body:
i'm pretty sure that the problem is data not being updated correctly.
try adding a state that holds your current artist, and then for every record just pass the data from the state. something like this:

add a state in your main component:
const [currentArtist, setCurrentArtist] = useState({});

use the setCurrentArtist after choosing the right artist,

add record for each album like this:

{currentArtist.albums.map((album) => <Record {...album} />)}

make sure the artist object in the state has keys with the props names. it should look like this:

{ spotifyLink: '.../.../', imageLink: '.../.../', title: 'Song Title' ...}

by doing so, you can just spread the album item as a prop (example in code) and not needing to pass props one by one.


问:
Is there a way to exclude fatal warnings from unit tests?
I would like to turn fatal warnings on for my project but exclude fatal warnings for for my unit tests. I am currently cross compiling to Scala 2.12 and 2.13 (also ignoring deprecation warnings) and these are my current compiler flags within build.sbt</p>
```<code>scalacOptions ++= Seq(
  "-language:_",
  "-target:11",
  "-encoding",
  "UTF-8",
  "-feature",
  "-Xfatal-warnings",
  "-language:existentials",
  "-language:higherKinds",
  "-language:implicitConversions",
  "-unchecked",
  "-Ywarn-dead-code",
  "-Ywarn-numeric-widen",
  "-Ywarn-value-discard"
) ++ (CrossVersion.binaryScalaVersion(scalaVersion.value) match {
  case "2.12" =>
    Seq(
      "-Xlint",
      "-Yno-adapted-args",
      "-Xfuture",
      "-Ypartial-unification"
    )
  case "2.13" =>
    Seq(
      "-Wconf:cat=deprecation:w,any:e", // exclude deprecations in fatal warnings
      "-Xlint:-byname-implicit" // needed for Doobie
    )
  case _ => Nil
})
</code>```

答:
All you need is:

Test / scalacOptions -= "-Xfatal-warnings"
```

Body:
I would like to turn fatal warnings on for my project but exclude fatal warnings for for my unit tests. I am currently cross compiling to Scala 2.12 and 2.13 (also ignoring deprecation warnings) and these are my current compiler flags within build.sbt

scalacOptions ++= Seq(
  "-language:_",
  "-target:11",
  "-encoding",
  "UTF-8",
  "-feature",
  "-Xfatal-warnings",
  "-language:existentials",
  "-language:higherKinds",
  "-language:implicitConversions",
  "-unchecked",
  "-Ywarn-dead-code",
  "-Ywarn-numeric-widen",
  "-Ywarn-value-discard"
) ++ (CrossVersion.binaryScalaVersion(scalaVersion.value) match {
  case "2.12" =>
    Seq(
      "-Xlint",
      "-Yno-adapted-args",
      "-Xfuture",
      "-Ypartial-unification"
    )
  case "2.13" =>
    Seq(
      "-Wconf:cat=deprecation:w,any:e", // exclude deprecations in fatal warnings
      "-Xlint:-byname-implicit" // needed for Doobie
    )
  case _ => Nil
})


问:
How can I ensure that newest version of Gradle resolve all dependencies
I need to update Gradle version in kotlin project. Have I any option to check if all dependencies support new version of Gradle or I need to check all dependencies release nots to make sure.
Actually for me it's not pretty clear how dependencies can't support new version of Gradle.
For instance:

答:
Have I any option to check if all dependencies support new version of Gradle

There two sets of dependencies:

Application dependencies -- https://docs.gradle.org/current/userguide/declaring_dependencies.html

Applications dependencies have no correlation with Gradle whatsoever. These are dependencies needed to build your application and has no impact on Gradle's build environment.

Build dependencies

https://docs.gradle.org/current/userguide/tutorial_using_tasks.html#sec:build_script_external_dependencies

https://docs.gradle.org/current/userguide/plugins.html

These dependencies, commonly Gradle plugins, do have an impact of your build. Whether or not a plugin supports a version of Gradle is only known by going to the source and checking release notes, if any. If it is not clear if a plugin supports a particular version of Gradle, then your only option is to upgrade your version of Gradle and see if anything breaks.


问:
C# Dependency Injection with DNN Version 9.9 in a Web Forms project
I am trying to get my hands around using Dependency Injection with DNN.  I looked at the DotNetNuke.Startup class and see the following:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<WebFormsModuleControlFactory>();
    services.AddSingleton<Html5ModuleControlFactory>();
    services.AddSingleton<ReflectedModuleControlFactory>();
    services.AddSingleton<IDnnContext, DotNetNukeContext>();
    services.AddScoped<IEventLogger, EventLogController>();
    services.AddScoped<IEventLogConfigService, EventLogController>();
    services.AddScoped<IEventLogService, EventLogController>();
    services.AddTransient((IServiceProvider x) => ServiceLocator<IPortalController, PortalController>.Instance);
    services.AddScoped<IHostSettingsService, HostController>();
    services.AddScoped<INavigationManager, NavigationManager>();
    services.AddScoped<ISerializationManager, SerializationManager>();
    services.AddScoped<IApplicationInfo, DotNetNuke.Application.Application>();
    services.AddScoped<IApplicationStatusInfo, ApplicationStatusInfo>();
    services.AddScoped<IPortalAliasService, PortalAliasController>();
}
</code>```

I have an understanding on how to wire up those services, but my confusion comes into play on how to register other dependencies that are not specific to DNN services for a Web Forms application (a new custom service).

Does anyone have any experience with this? In my Web Forms project, do I have to create a new Startup class that inherits the DNN Interface for Startup?  Any examples would be greatly appreciated.

答:
Utilizing Dependency Injection from WebForms with DNN is ever so slightly different, but this article provides the step-by-step instructions on using it in your project.

The short summary is you create your own registration class using IDnnStartup and then use the Service Locator to get the instance.

Body:
I am trying to get my hands around using Dependency Injection with DNN.  I looked at the DotNetNuke.Startup class and see the following:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<WebFormsModuleControlFactory>();
    services.AddSingleton<Html5ModuleControlFactory>();
    services.AddSingleton<ReflectedModuleControlFactory>();
    services.AddSingleton<IDnnContext, DotNetNukeContext>();
    services.AddScoped<IEventLogger, EventLogController>();
    services.AddScoped<IEventLogConfigService, EventLogController>();
    services.AddScoped<IEventLogService, EventLogController>();
    services.AddTransient((IServiceProvider x) => ServiceLocator<IPortalController, PortalController>.Instance);
    services.AddScoped<IHostSettingsService, HostController>();
    services.AddScoped<INavigationManager, NavigationManager>();
    services.AddScoped<ISerializationManager, SerializationManager>();
    services.AddScoped<IApplicationInfo, DotNetNuke.Application.Application>();
    services.AddScoped<IApplicationStatusInfo, ApplicationStatusInfo>();
    services.AddScoped<IPortalAliasService, PortalAliasController>();
}

I have an understanding on how to wire up those services, but my confusion comes into play on how to register other dependencies that are not specific to DNN services for a Web Forms application (a new custom service).

Does anyone have any experience with this? In my Web Forms project, do I have to create a new Startup class that inherits the DNN Interface for Startup?  Any examples would be greatly appreciated.


问:
NetBeans error: package org does not exist
I just installed Netbeans IDE. I am now unable to import any org.* libs and it just says package org does not exist.
Also, I imported jdic.jar into the project and even though the code completion suggestions show up as org.jdesktop.*, it shows the same error.

How do I fix this?

答: in my experience the problem was with a Jpanel with AbsoluteLayout, I put free-design and solved the problem</p>


问:
Why the local variable problem happens in python
I got this error

```<code>increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        value = x
        while n > 0 :
            value = h(value)
            n = n - 1

        return value
    return f

    a = make_repeater(increment,5)
    b = a(1)
</code>```

UnboundLocalError: local variable 'n' referenced before assignment

while when I write like this , it runs well

```<code>increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        i = n
        value = x
        while i > 0 :
            value = h(value)
            i = i - 1

        return value
    return f

    a = make_repeater(increment, 5)
    b = a(1)
</code>```

答:
Your function f is not getting n as an argument.

Instead, n is taken from the scope of make_repeater.

As a result, in first example you work with variable n that is defined when the function is created, but is not availiable when the function is called.

In your second example n is used only during creation of the function, but when it is called it just uses the variable i and value 5.

Body:
I got this error

increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        value = x
        while n > 0 :
            value = h(value)
            n = n - 1

        return value
    return f

    a = make_repeater(increment,5)
    b = a(1)

UnboundLocalError: local variable 'n' referenced before assignment

while when I write like this , it runs well

increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        i = n
        value = x
        while i > 0 :
            value = h(value)
            i = i - 1

        return value
    return f

    a = make_repeater(increment, 5)
    b = a(1)


问:
Excel move tab when you go to another tab
This one is hard to explain but I would like to move a summary tab to the left of the active tab. I attached a GIF on what I mean, as you can see the red tab moves to the left of the tab I click. Any idea on how this is done?

https://i.stack.imgur.com/AAtoZ.gif

答:
Insert this code in every sheet Code (except the "Roll-up" sheet)

```<code>Private Sub Worksheet_Activate()
    Dim ws As Worksheet
    Dim WsActive As Worksheet

    On Error GoTo Errorhandler

    Application.ScreenUpdating = False
    Set ws = ThisWorkbook.Worksheets("Roll-up")
    Set WsActive = ActiveSheet

    Application.EnableEvents = False
    ws.Move Before:=ActiveSheet
    WsActive.Activate
    Application.EnableEvents = True

    Exit Sub
Errorhandler:
    Application.EnableEvents = True

End Sub
</code>```

Save your workbook as .xlsm file

This is called Worksheet event. The macro gets triggered by activating the worksheet where the code lies.

We need to switch off these events before activating this sheet otherwise the macro will go in loops and in some cases Excel might crash.

After the sheet is activated you have to enable the events again (enableevents = true). Otherwise it will not work next time.

If there is an error the events need to get set to true in the errorhandler.
If the macro for some reasons (stopping it manually)  will not run the enableevents=true, then no events are possible, until Excel is closed and reopened or you run the code Application.EnableEvents = True somehow.

Body:
Insert this code in every sheet Code (except the "Roll-up" sheet)

Private Sub Worksheet_Activate()
    Dim ws As Worksheet
    Dim WsActive As Worksheet

    On Error GoTo Errorhandler

    Application.ScreenUpdating = False
    Set ws = ThisWorkbook.Worksheets("Roll-up")
    Set WsActive = ActiveSheet

    Application.EnableEvents = False
    ws.Move Before:=ActiveSheet
    WsActive.Activate
    Application.EnableEvents = True

    Exit Sub
Errorhandler:
    Application.EnableEvents = True

End Sub

Save your workbook as .xlsm file

This is called Worksheet event. The macro gets triggered by activating the worksheet where the code lies.

We need to switch off these events before activating this sheet otherwise the macro will go in loops and in some cases Excel might crash.

After the sheet is activated you have to enable the events again (enableevents = true). Otherwise it will not work next time.

If there is an error the events need to get set to true in the errorhandler.
If the macro for some reasons (stopping it manually)  will not run the enableevents=true, then no events are possible, until Excel is closed and reopened or you run the code Application.EnableEvents = True somehow.


问:
How to use fiftyone for exploring the instance segmentation of custom coco data?
How to use fiftyone for exploring the instance segmentation of custom coco data? It has documentation for coco dataset but I couldn't find any resource for custom coco dataset.

答: It can be done by using COCODetectionDatasetImporter Class and set label_types=["detections","segmentations"] for seeing mask annotated images


问:
How to pass html textbox value to a javascript function
I have a HTML textbox where user will input some string which i want to pass to a JavaScript function:

```<code><input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="<s:text name="button.search"/>" class="p-userButton"
 onClick="ADSEARCHGF.showTable('');"/>
</code>```

Please suggest how can i do it.

答:
Do this:

JS:

HTML:

```<code><input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="search" class="p-userButton" onClick="showTable(document.getElementById('ad_search_query').value);"/>
</code>```

See this Demo: http://jsfiddle.net/rathoreahsan/8ddbD/

Body:
I have a HTML textbox where user will input some string which i want to pass to a JavaScript function:

<input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="<s:text name="button.search"/>" class="p-userButton"
 onClick="ADSEARCHGF.showTable('');"/>

Please suggest how can i do it.

Body:
Do this:

JS:

<script>function showTable(val) {alert(val);} </script>

HTML:

<input type="text" id="ad_search_query" style="width:295px">&nbsp;
<input type="button" value="search" class="p-userButton" onClick="showTable(document.getElementById('ad_search_query').value);"/>

See this Demo: http://jsfiddle.net/rathoreahsan/8ddbD/


问:
How to immediately chunk or partition large data that would normally be read by sql into pandas?
High level idea:

I need to iterate over and perform fairly complex operations on a large dataset (240 million rows) that I have chunked into SQL calls that return ~20 million records each. I can successfully pull each chunk into pandas, but those dataframes are unwieldy and really need further chunking or partitioning further before I can operate on them. I unfortunately can not divide the ingestion calls any smaller (the SQL calls are against AWS S3 via Spectrum and would require many costly scans against a nonpartitioned column if so).

Using Python, how can I efficiently further chunk out these large datasets upon ingestion?

Specific details:

I have two primary columns to consider ID and Date. The already established chunks (of 20 million each) are for months in the Date column. Within each ingested chunk, the operations I need to perform look like:

Sort the data by Date

Iterate through each ID, get a new dataset filtered to that ID

For each row in each ID's dataset, do some stuff

Said stuff will allow me to create a new dataset with one row per ID

...then eventually concatenate the result of all of the months. To me, the inference then is that if I can immediately partition each ingested 20 million records by ID or sets of such, I'm golden, but I don't know how to reach that.

I could save each ID set as a separate csv, but then I'd need to iterate over the pandas dataframe (filtering and then saving), which isn't tenable. I've read about alternatives to scale out of pandas like dask, but it ?seems? like that doesn't really handle ingestion or setting up a big for loop as I need, but rather typical pandas-like data transformations. Having not worked with data such large sizes, I'm not sure what tools are available to approach a problem like this within a Python environment.

答:
You don't give a minimal reproducible example so I can't work with your specific data.
You can use generators, but chunks are easier and faster to implement so you are on the right track.

I usually chunk huge datasets like that:

    chunk_size = 10000
    for i in range(0, len(column), chunk_size):
        data_chunked = [j for j in column[i:i+chunk_size]] # or any other data manipulation
        entries_to_sql = [data_chunked, *other_entries] # if others are not chunked: other_entry[i:i+chunk_size]
        insert_many_entries_to_sql(entries_to_sql)
```


问:
Invalidation of the cache from L1 cache
Suppose that a cache line with variable X is simultaneously uploaded to L1d of CPU0 and L1d of CPU1. After changing the value of X from CPU0, when CPU1's L1d cache line is invalidated, Is it impossible for CPU1 to copy the variable X from CPU0's L1d cache if CPU0 has a cache line with X? And even if this is not the case, I want to know if there are cases where CPU0 brings in CPU1'</p>

答:
The case described is not allowed.  When a processor core executes a store to an address, the data is written to a "store buffer" for transfer to the cache at a later time.  Before transferring data from the store buffer, the cache requires Exclusive access to the line -- a state that can exist in only one cache at a time.

Three easy cases:

If the core's cache already has exclusive access (i.e., the line is in the Exclusive or Modifed states), then the store buffer can write the data to the cache at any time.

If the core's cache has a valid copy of the line without exclusive access (such as the "Shared" state), the presence of new data in the store buffer will cause the cache to generate an "upgrade" request for the line.  The upgrade to E or M state will not be granted until all other caches (or directories) acknowledge that they have invalidated any copies of that address.

If the core's cache does not have a valid copy of the line (either no address match or an address match in the Invalid state), the cache will issue a "Read With Intent To Modify" request.  This will result in the transfer of the current data for the cache line (whether in memory or from a modified copy in another core's cache) to the requesting core's cache, AND the invalidation of the cache line in every other cache in the system.

If two cores execute store instructions "at the same time", the details of the implementation will result in one of two the cores obtaining exclusive access.  The other core will have its request "rejected" (NACK'd), and it will retry the request until the first core+cache has completed its upgrade of the cache line state and update of the data.  This mechanism forces all stores to a single address to be processed sequentially, even if they are issued concurrently.

In general it is not possible for a user to reliably make something happen "at the same time" in two cores (or to detect whether it happened at the same time), but the implementations have to account for it by the serialization process described above.

Title: Invalidation of the cache from L1 cache


问:
Terraform create multiple ec2 instances in multiple subnets
I am trying to create multiple ec2 instances with access to multiple subnets.

I've found questions and answers on doing these things individually, but not combined.

First, I create a private and a public subnet, then I setup a local to store the IDs once they are created:

```<code>locals {
  subnets =  [ aws_subnet.public_subnet.id, aws_subnet.private_subnet.id ]
}
</code>```

Next, I can create a variable number of servers in the private_subnet using for_each and the below:

```<code>servers = [ "s1", "s2" ]
resource "aws_instance" "system" {
  for_each                    = var.servers
  ami                         = var.aws_ami
  instance_type               = var.instance_type
  #subnet_id                  = aws_subnet.private_subnet.id
  count = 2
  subnet_id                   = element(local.subs, count.index)
}
</code>```

What I want to have, is that the server can access both subnets (it doesn't exist as far as I can tell, but the equivalent of subnet_ids = [aws_subnet.public_subnet.id, aws_subnet.private_subnet.id]).

I found a nice answer which works for a specific instance by creating two NICs (Terraform one EC2 instance with two subnets), however I need to do this var.servers times so it's difficult to hardcode the var.servers * 2 NICs with my current aws_instance setup (and I trip up when combining for_each and count).

Can someone please point me in the right direction?

答:
For those looking to have a similar setup there are a few steps (assuming subnets and route tables already exist):

Create a machine on a single subnet

Create an additional network interface

Attach the network interface to the 'other' subnet (for the existing machine)

Create a variable for machines to create:

```<code>domains = [
  "asd.com",
  "asd2.com"
]
</code>```

Create the machines on a single subnet:

```<code>resource "aws_instance" "domain" {
  for_each                    = var.domains
  ami                         = var.aws_ami
  subnet_id                   = aws_subnet.public_subnet.id
  associate_public_ip_address = true
  tags = {
    Name           = "Instance - ${each.key}"
  }
}
</code>```

Create the additional interfaces for the 'other' subnet:

```<code>resource "aws_network_interface" "nics" {
  for_each          = var.domains
  subnet_id         = aws_subnet.private_subnet.id
  tags = {
    Name           = "NIC - ${each.key}"
  }
}
</code>```

Attach the network interfaces to the 'other' subnet (for the existing machine):

```<code>resource "aws_network_interface_attachment" "attach_nics" {
  for_each              = var.domains
  instance_id           = aws_instance.domain[each.key].id
  network_interface_id  = aws_network_interface.nics[each.key].id
  device_index          = 1 # public_subnet = 0
}
</code>```

The 'trick' here (that I didn't know) is understanding that you can access data from created resources based on their names in the existing script (which is used in the aws_network_interface_attachment component).

Body:
I am trying to create multiple ec2 instances with access to multiple subnets.

I've found questions and answers on doing these things individually, but not combined.

First, I create a private and a public subnet, then I setup a local to store the IDs once they are created:

locals {
  subnets =  [ aws_subnet.public_subnet.id, aws_subnet.private_subnet.id ]
}

Next, I can create a variable number of servers in the private_subnet using for_each and the below:

servers = [ "s1", "s2" ]
resource "aws_instance" "system" {
  for_each                    = var.servers
  ami                         = var.aws_ami
  instance_type               = var.instance_type
  #subnet_id                  = aws_subnet.private_subnet.id
  count = 2
  subnet_id                   = element(local.subs, count.index)
}

What I want to have, is that the server can access both subnets (it doesn't exist as far as I can tell, but the equivalent of subnet_ids = [aws_subnet.public_subnet.id, aws_subnet.private_subnet.id]).

I found a nice answer which works for a specific instance by creating two NICs (Terraform one EC2 instance with two subnets), however I need to do this var.servers times so it's difficult to hardcode the var.servers * 2 NICs with my current aws_instance setup (and I trip up when combining for_each and count).

Can someone please point me in the right direction?

Body:
For those looking to have a similar setup there are a few steps (assuming subnets and route tables already exist):

Create a machine on a single subnet

Create an additional network interface

Attach the network interface to the 'other' subnet (for the existing machine)

Create a variable for machines to create:

domains = [
  "asd.com",
  "asd2.com"
]

Create the machines on a single subnet:

resource "aws_instance" "domain" {
  for_each                    = var.domains
  ami                         = var.aws_ami
  subnet_id                   = aws_subnet.public_subnet.id
  associate_public_ip_address = true
  tags = {
    Name           = "Instance - ${each.key}"
  }
}

Create the additional interfaces for the 'other' subnet:

resource "aws_network_interface" "nics" {
  for_each          = var.domains
  subnet_id         = aws_subnet.private_subnet.id
  tags = {
    Name           = "NIC - ${each.key}"
  }
}

Attach the network interfaces to the 'other' subnet (for the existing machine):

resource "aws_network_interface_attachment" "attach_nics" {
  for_each              = var.domains
  instance_id           = aws_instance.domain[each.key].id
  network_interface_id  = aws_network_interface.nics[each.key].id
  device_index          = 1 # public_subnet = 0
}

The 'trick' here (that I didn't know) is understanding that you can access data from created resources based on their names in the existing script (which is used in the aws_network_interface_attachment component).


问:
SAM Local: Can you use a CloudFormation file directly instead of SAM Template?
I am trying to use a compiled CloudFormation file directly with SAM Local. I cannot find a way to do this, has anyone achieved this successfully?</p>

答:
Well, assuming you want to test locally a lambda you're provisionin, you can use this command:

sam local invoke -t path-to-compiled-stack-sam-template.yaml
```

By default, sam local invoke tries to locate a template file built using the sam build command, located in the .aws-sam subfolder, and named template.yaml or template.yml. If it doens't succeed, it will look for a template.yaml in your current directory.

This should work.

Please let us know if you're case is any more specific than this.

Reference: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-invoke.html

Body:
Well, assuming you want to test locally a lambda you're provisionin, you can use this command:

sam local invoke -t path-to-compiled-stack-sam-template.yaml

By default, sam local invoke tries to locate a template file built using the sam build command, located in the .aws-sam subfolder, and named template.yaml or template.yml. If it doens't succeed, it will look for a template.yaml in your current directory.

This should work.

Please let us know if you're case is any more specific than this.

Reference: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-invoke.html


问:
Logstash 8.0.0 triggers "insecure dependency" alerts, how do you fix it?
We're trying to build a Docker container that contains Logstash-8.0.0 (the latest version, came out yesterday), such that it can be scanned with Trivy and not have any "HIGH" or "CRITICAL" severity alerts.

It's proving very hard to do, as we're not proficient with Java, Ruby, or JRuby.

If we have a Dockerfile that has the Elastic repository in it:

```<code>$ cat /etc/apt/sources.list.d/elastic-8.x.list

deb https://artifacts.elastic.co/packages/8.x/apt stable main
</code>```

And we install logstash:

```<code>$ sudo apt-get update
$ sudo apt-get install logstash
</code>```

Then install and run trivy:

```<code>$ curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b .
$ sudo trivy fs -s HIGH,CRITICAL /
</code>```

We get one critical and two high severity alerts, concerning ruby gems listed in /usr/share/logstash/Gemfile.lock:

```<code>usr/share/logstash/Gemfile.lock (bundler)
=========================================
Total: 3 (HIGH: 2, CRITICAL: 1)

+----------+------------------+----------+-------------------+---------------+---------------------------------------+
| LIBRARY  | VULNERABILITY ID | SEVERITY | INSTALLED VERSION | FIXED VERSION |                 TITLE                 |
+----------+------------------+----------+-------------------+---------------+---------------------------------------+
| json     | CVE-2020-10663   | HIGH     | 1.8.6-java        | >= 2.3.0      | rubygem-json: Unsafe object           |
|          |                  |          |                   |               | creation vulnerability in JSON        |
|          |                  |          |                   |               | -->avd.aquasec.com/nvd/cve-2020-10663 |
+----------+------------------+----------+-------------------+               +---------------------------------------+
| kramdown | CVE-2020-14001   | CRITICAL | 1.14.0            |               | rubygem-kramdown: processing template |
|          |                  |          |                   |               | options inside documents allows       |
|          |                  |          |                   |               | unintended read access or embedded... |
|          |                  |          |                   |               | -->avd.aquasec.com/nvd/cve-2020-14001 |
+----------+------------------+----------+-------------------+---------------+---------------------------------------+
| nokogiri | CVE-2021-41098   | HIGH     | 1.12.5-java       | >= 1.12.5     | rubygem-nokogiri: XEE on JRuby        |
|          |                  |          |                   |               | -->avd.aquasec.com/nvd/cve-2021-41098 |
+----------+------------------+----------+-------------------+---------------+---------------------------------------+

</code>```

By changing the path to include the appropriate(?) directories, we can run ruby, jruby, gem and bundle:

```<code>$ export PATH=/usr/share/logstash/bin:/usr/share/logstash/vendor/jruby/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:.
</code>```

But we're a bit at a loss as to what to try next.  So far, it looks like editing /usr/share/logstash/Gemfile to have the right versions of json and nokogiri and commenting out the gems that are marked :development and then run bundle install; bundle update is the way to go:

```<code>diff --git a/Gemfile b/Gemfile
index 6e90ef4..1054cb3 100644
--- a/Gemfile
+++ b/Gemfile
@@ -6,7 +6,8 @@ gem "logstash-core", :path => "./logstash-core"
 gem "logstash-core-plugin-api", :path => "./logstash-core-plugin-api"
 gem "atomic", "~> 1"
 gem "builder", "~> 3"
-gem "json", "~> 1"
+gem "json", "~> 2.3.0"
+gem "nokogiri", "1.12.5"
 gem "paquet", "~> 0.2"
 gem "pleaserun", "~>0.0.28"
 gem "rake", "~> 12"
@@ -18,15 +19,6 @@ gem "gems", "~> 1", :group => :build
 gem "octokit", "~> 4", :group => :build
 gem "rubyzip", "~> 1", :group => :build
 gem "stud", "~> 0.0.22", :group => :build
-# gem "belzebuth", :group => :development
-# gem "benchmark-ips", :group => :development
-# # # gem "ci_reporter_rspec", "~> 1", :group => :development
-# gem "flores", "~> 0.0.6", :group => :development
-# gem "json-schema", "~> 2", :group => :development
-# gem "logstash-devutils", "~> 1", :group => :development
-# gem "rack-test", :require => "rack/test", :group => :development
-# gem "rspec", "~> 3.5", :group => :development
-# gem "webmock", "~> 3", :group => :development
 gem "logstash-codec-avro"
 gem "logstash-codec-cef"
 gem "logstash-codec-collectd"
</code>```

But it seems that the Gemfile.lock file was created by bundler 2.3.6, which is not installed.  When we installed bundler 2.3.6, it complained about an unexpected error with openssl.  So, upgraded to bundler 2.3.7 (also released yesterday!), and it succeeded with bundle install.  But now logstash won't run:

```<code>[FATAL] 2022-02-10 18:12:40.504 [main] Logstash - Logstash stopped
processing because of an error: (GemNotFound) Could not find
 logstash-filter-elasticsearch-3.11.1,
 logstash-filter-http-1.3.0,
 logstash-filter-kv-4.6.0,
 logstash-input-beats-6.2.6-java,
 logstash-input-dead_letter_queue-1.1.10,
 logstash-input-http_poller-5.2.0,
 logstash-input-sqs-3.2.0,
 logstash-input-tcp-6.2.7-java,
 logstash-integration-elastic_enterprise_search-2.2.1,
 logstash-integration-
 kafka-10.10.0-java,
 logstash-output-http-5.4.0,
 logstash-output-tcp-6.0.1,
 puma-5.6.1-java,
 jruby-openssl-0.12.1-java,
 i18n-1.9.1,
 elasticsearch-7.17.0,
 logstash-mixin-http_client-7.1.0,
 json-2.6.1-java,
 redis-4.6.0,
 logstash-mixin-aws-5.0.0,
 elastic-enterprise-search-7.16.0,
 sequel-5.53.0,
 elasticsearch-api-7.17.0,
 elasticsearch-transport-7.17.0
in any of the sources
</code>```

Edit: Figured it out!
This makes logstash find the updated ruby gems:

```<code># cd /usr/share/logstash/vendor/jruby/lib/ruby/gems/shared
# tar c . | ( cd /usr/share/logstash/vendor/bundle/jruby/2.5.0; tar x )
</code>```

This makes trivy stop complaining about snakeyaml-1.23 while letting logstash keep working:

```<code># rm /usr/share/logstash/logstash-core/lib/jars/snakeyaml-1.23.jar
# cp /usr/share/logstash/vendor/jruby/lib/ruby/stdlib/org/yaml/snakeyaml/1.26/snakeyaml-1.26.jar /usr/share/logstash/logstash-core/lib/jars
</code>```

This cleans up the other trivy jar alerts:

```<code># rm -rf ~/.m2    # Delete maven cache
</code>```

Cheers!

答:
It was long and involved, but updating to logstash-8.0.0 allowed bundler-2.3.7 to work, and then copying the gems from one directory to another let logstash actually find the gems.

Details added to question.

Cheers!

Body:
We're trying to build a Docker container that contains Logstash-8.0.0 (the latest version, came out yesterday), such that it can be scanned with Trivy and not have any "HIGH" or "CRITICAL" severity alerts.

It's proving very hard to do, as we're not proficient with Java, Ruby, or JRuby.

If we have a Dockerfile that has the Elastic repository in it:

$ cat /etc/apt/sources.list.d/elastic-8.x.list

deb https://artifacts.elastic.co/packages/8.x/apt stable main

And we install logstash:

$ sudo apt-get update
$ sudo apt-get install logstash

Then install and run trivy:

$ curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b .
$ sudo trivy fs -s HIGH,CRITICAL /

We get one critical and two high severity alerts, concerning ruby gems listed in /usr/share/logstash/Gemfile.lock:

usr/share/logstash/Gemfile.lock (bundler)
=========================================
Total: 3 (HIGH: 2, CRITICAL: 1)

+----------+------------------+----------+-------------------+---------------+---------------------------------------+
| LIBRARY  | VULNERABILITY ID | SEVERITY | INSTALLED VERSION | FIXED VERSION |                 TITLE                 |
+----------+------------------+----------+-------------------+---------------+---------------------------------------+
| json     | CVE-2020-10663   | HIGH     | 1.8.6-java        | >= 2.3.0      | rubygem-json: Unsafe object           |
|          |                  |          |                   |               | creation vulnerability in JSON        |
|          |                  |          |                   |               | -->avd.aquasec.com/nvd/cve-2020-10663 |
+----------+------------------+----------+-------------------+               +---------------------------------------+
| kramdown | CVE-2020-14001   | CRITICAL | 1.14.0            |               | rubygem-kramdown: processing template |
|          |                  |          |                   |               | options inside documents allows       |
|          |                  |          |                   |               | unintended read access or embedded... |
|          |                  |          |                   |               | -->avd.aquasec.com/nvd/cve-2020-14001 |
+----------+------------------+----------+-------------------+---------------+---------------------------------------+
| nokogiri | CVE-2021-41098   | HIGH     | 1.12.5-java       | >= 1.12.5     | rubygem-nokogiri: XEE on JRuby        |
|          |                  |          |                   |               | -->avd.aquasec.com/nvd/cve-2021-41098 |
+----------+------------------+----------+-------------------+---------------+---------------------------------------+

By changing the path to include the appropriate(?) directories, we can run ruby, jruby, gem and bundle:

$ export PATH=/usr/share/logstash/bin:/usr/share/logstash/vendor/jruby/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:.

But we're a bit at a loss as to what to try next.  So far, it looks like editing /usr/share/logstash/Gemfile to have the right versions of json and nokogiri and commenting out the gems that are marked :development and then run bundle install; bundle update is the way to go:

diff --git a/Gemfile b/Gemfile
index 6e90ef4..1054cb3 100644
--- a/Gemfile
+++ b/Gemfile
@@ -6,7 +6,8 @@ gem "logstash-core", :path => "./logstash-core"
 gem "logstash-core-plugin-api", :path => "./logstash-core-plugin-api"
 gem "atomic", "~> 1"
 gem "builder", "~> 3"
-gem "json", "~> 1"
+gem "json", "~> 2.3.0"
+gem "nokogiri", "1.12.5"
 gem "paquet", "~> 0.2"
 gem "pleaserun", "~>0.0.28"
 gem "rake", "~> 12"
@@ -18,15 +19,6 @@ gem "gems", "~> 1", :group => :build
 gem "octokit", "~> 4", :group => :build
 gem "rubyzip", "~> 1", :group => :build
 gem "stud", "~> 0.0.22", :group => :build
-# gem "belzebuth", :group => :development
-# gem "benchmark-ips", :group => :development
-# # # gem "ci_reporter_rspec", "~> 1", :group => :development
-# gem "flores", "~> 0.0.6", :group => :development
-# gem "json-schema", "~> 2", :group => :development
-# gem "logstash-devutils", "~> 1", :group => :development
-# gem "rack-test", :require => "rack/test", :group => :development
-# gem "rspec", "~> 3.5", :group => :development
-# gem "webmock", "~> 3", :group => :development
 gem "logstash-codec-avro"
 gem "logstash-codec-cef"
 gem "logstash-codec-collectd"

But it seems that the Gemfile.lock file was created by bundler 2.3.6, which is not installed.  When we installed bundler 2.3.6, it complained about an unexpected error with openssl.  So, upgraded to bundler 2.3.7 (also released yesterday!), and it succeeded with bundle install.  But now logstash won't run:

[FATAL] 2022-02-10 18:12:40.504 [main] Logstash - Logstash stopped
processing because of an error: (GemNotFound) Could not find
 logstash-filter-elasticsearch-3.11.1,
 logstash-filter-http-1.3.0,
 logstash-filter-kv-4.6.0,
 logstash-input-beats-6.2.6-java,
 logstash-input-dead_letter_queue-1.1.10,
 logstash-input-http_poller-5.2.0,
 logstash-input-sqs-3.2.0,
 logstash-input-tcp-6.2.7-java,
 logstash-integration-elastic_enterprise_search-2.2.1,
 logstash-integration-
 kafka-10.10.0-java,
 logstash-output-http-5.4.0,
 logstash-output-tcp-6.0.1,
 puma-5.6.1-java,
 jruby-openssl-0.12.1-java,
 i18n-1.9.1,
 elasticsearch-7.17.0,
 logstash-mixin-http_client-7.1.0,
 json-2.6.1-java,
 redis-4.6.0,
 logstash-mixin-aws-5.0.0,
 elastic-enterprise-search-7.16.0,
 sequel-5.53.0,
 elasticsearch-api-7.17.0,
 elasticsearch-transport-7.17.0
in any of the sources

Edit: Figured it out!
This makes logstash find the updated ruby gems:

# cd /usr/share/logstash/vendor/jruby/lib/ruby/gems/shared
# tar c . | ( cd /usr/share/logstash/vendor/bundle/jruby/2.5.0; tar x )

This makes trivy stop complaining about snakeyaml-1.23 while letting logstash keep working:

# rm /usr/share/logstash/logstash-core/lib/jars/snakeyaml-1.23.jar
# cp /usr/share/logstash/vendor/jruby/lib/ruby/stdlib/org/yaml/snakeyaml/1.26/snakeyaml-1.26.jar /usr/share/logstash/logstash-core/lib/jars

This cleans up the other trivy jar alerts:

# rm -rf ~/.m2    # Delete maven cache

Cheers!


问:
Read folder created on local machine by using Math.random() method in Node js / JavaScript
I am trying to read a JSON File which is in folder within a folder and in another folder and this file is created on my local machine while performing some task but the problem is every time folder name get change as folder name is generated by Math.random() method but with prefix of _createdFolder_ so its look like this _createdFolder_012 in place of 012 it can be 454 or 782 or any number as it is generate by Math.random() method if the folder name is fixed I can easily read the file but file name get changed and its been hard to read

and I want to read a json file which is path look like this

folderPath

```<code>_createdFolder_563/data/systemCode/access.json
</code>```

as I want to read and fetch json file which is created on my local machine while performing some task but if the folder name is fixed I can easily read it but due to Math.random() its hard to read a file

```<code>fs.readFile("_createdFolder_501/data/systemCode/access.json", function(err, data) {
    if (err) throw err;

    const JsonData = JSON.parse(data);

    console.log(JsonData);
});
</code>```

is there any possible way I can read the folder which is created by Math.random()

答:
Yes.

Meet FS.readdir(path). It lists the contents of a directory.

You will need to invoke that, giving it the path to the folder that contains the randomly-named folder. That will give you a list of all the files and folders.

Then you need to search that list for an item whose name matches that pattern. Then you have the name you need, and you can do the rest of your logic.

Body:
I am trying to read a JSON File which is in folder within a folder and in another folder and this file is created on my local machine while performing some task but the problem is every time folder name get change as folder name is generated by Math.random() method but with prefix of _createdFolder_ so its look like this _createdFolder_012 in place of 012 it can be 454 or 782 or any number as it is generate by Math.random() method if the folder name is fixed I can easily read the file but file name get changed and its been hard to read

and I want to read a json file which is path look like this

folderPath

_createdFolder_563/data/systemCode/access.json

as I want to read and fetch json file which is created on my local machine while performing some task but if the folder name is fixed I can easily read it but due to Math.random() its hard to read a file

fs.readFile("_createdFolder_501/data/systemCode/access.json", function(err, data) {
    if (err) throw err;

    const JsonData = JSON.parse(data);

    console.log(JsonData);
});

is there any possible way I can read the folder which is created by Math.random()


问:
Can't post videos to Tiktok using the Web Video Kit API
I am trying to upload a video to Tiktok using this endpoint:

https://open-api.tiktok.com/share/video/upload/

Following the official docs:
https://developers.tiktok.com/doc/web-video-kit-with-web

(After successfully authenticating with Tiktok and getting an access token using the Login Kit API).
I am getting a response that suggests success (with error_code=0 and a non-empty share_id), however nothing gets uploaded and my Tiktok app's callback url does not seem to be getting triggered with any status update.

I've tried hitting the API from several different environments - a Node.js runtime (using Axios), a cURL request from 2 different machines (all getting the result described above) and also from my frontend code using Fetch (this one got me a CORS error). Code snippets below.

Will appreciate any help since I'm out of ideas as for what to try next. Also if there are any other docs or online resources besides the one I linked to that might be helpful, any links to such will be great.

Note: I made sure my test videos are satisfying the constraints mentioned in the docs.

My Node.js code:

```<code>    const url = `https://open-api.tiktok.com/share/video/upload?open_id=${openId}&access_token=${accessToken}`;
const data = new FormData();
data.append('video', fs.createReadStream(path.join(os.tmpdir(), 'test.mp4')));
await axios.post(url, data, {
  headers: data.getHeaders()
});
</code>```

cURL request:

```<code>curl --location --request POST 'https://open-api.tiktok.com/share/video/upload?open_id=<open_id>&access_token=<access_token>' --form 'video=@"/path/to/video.mp4"'
</code>```

Response payload (for both cURL and Node.JS requests):

```<code>{"data":{"err_code":0,"error_code":0,"share_id":"video.7031619168818448385.CGdXCmaC"},"extra":{"error_detail":"","logid":"2021111721133201024513311411A971D3"}}
</code>```

Frontend code (Fetch, getting a 307 response with the same Tiktok URL (/share/video/upload...) in the Location header - resulting in CORS error):

```<code>const formData = new FormData();
formData.append('video', selectedFile);

const requestOptions = {
  method: 'POST',
  body: formData,
  redirect: 'follow'
};

const URL = `https://open-api.tiktok.com/share/video/upload?access_token=${accessToken}&open_id=${openId}`;

fetch(URL, requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log('error', error));
</code>```

答: In case you get "Something went wrong, try again later". It is probably your region issue. You will need to try a vpn and try again.</p>

Body:
I am trying to upload a video to Tiktok using this endpoint:

https://open-api.tiktok.com/share/video/upload/

Following the official docs:
https://developers.tiktok.com/doc/web-video-kit-with-web

(After successfully authenticating with Tiktok and getting an access token using the Login Kit API).
I am getting a response that suggests success (with error_code=0 and a non-empty share_id), however nothing gets uploaded and my Tiktok app's callback url does not seem to be getting triggered with any status update.

I've tried hitting the API from several different environments - a Node.js runtime (using Axios), a cURL request from 2 different machines (all getting the result described above) and also from my frontend code using Fetch (this one got me a CORS error). Code snippets below.

Will appreciate any help since I'm out of ideas as for what to try next. Also if there are any other docs or online resources besides the one I linked to that might be helpful, any links to such will be great.

Note: I made sure my test videos are satisfying the constraints mentioned in the docs.

My Node.js code:

    const url = `https://open-api.tiktok.com/share/video/upload?open_id=${openId}&access_token=${accessToken}`;
const data = new FormData();
data.append('video', fs.createReadStream(path.join(os.tmpdir(), 'test.mp4')));
await axios.post(url, data, {
  headers: data.getHeaders()
});

cURL request:

curl --location --request POST 'https://open-api.tiktok.com/share/video/upload?open_id=<open_id>&access_token=<access_token>' --form 'video=@"/path/to/video.mp4"'

Response payload (for both cURL and Node.JS requests):

{"data":{"err_code":0,"error_code":0,"share_id":"video.7031619168818448385.CGdXCmaC"},"extra":{"error_detail":"","logid":"2021111721133201024513311411A971D3"}}

Frontend code (Fetch, getting a 307 response with the same Tiktok URL (/share/video/upload...) in the Location header - resulting in CORS error):

const formData = new FormData();
formData.append('video', selectedFile);

const requestOptions = {
  method: 'POST',
  body: formData,
  redirect: 'follow'
};

const URL = `https://open-api.tiktok.com/share/video/upload?access_token=${accessToken}&open_id=${openId}`;

fetch(URL, requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log('error', error));


问:
Library function not working: Uncaught at saveData
So, I got to build a script that asks the user for some information using google apps script. Those codes must be in a specific spreadsheet (1st URL), so does the HTML form that will be loaded by a modal dialog.

Even though the code is written in the spreadsheet SCRIPTS, that project is loaded as a library on the project from spreadsheet workbook, and that's the spreadsheet that will create a menu that will load the code from SCRIPTS.

The final goal is: the user opens workbook, runs the item from MyMenu > Form, a modal/form is opened; the user writes his info and hits submit. After that, the function saveData from SCRIPTS, which will write the informations in the spreadsheet requests.

Obs.: since saveData needs to call 2 methods hosted in the SCRIPTS project, it also needs to be hosted in the same project.

SCRIPTS: https://docs.google.com/spreadsheets/d/1Dkntw25H41JTk0R3Rm9fgiwt_RrAee9zYEz1Wy8DomI/edit?usp=sharing
requests: https://docs.google.com/spreadsheets/d/1o8JbVelmSNoGn6sn7laatBam_2WTtToB_nlZMTFY_Rg/edit?usp=sharing
workbook: https://docs.google.com/spreadsheets/d/17plSc9-kPj6XMBENBLJEE6sc01i82xfhGGPQ1UmOXjE/edit?usp=sharing

The problem here is that on the spreadsheets I shared above, everything works flawlessly, but on the original spreadsheets I need to work on (there are sensitive data from my job there, I can't share the url), when I click on the button submit, I only get this error on the console and nothing works:

PS.: Although I can't share my job's spreadsheet, all the code, from the one in the workbook to the one in the scripts spreadsheet are exactly the same as I wrote for my job, using different spreadsheets just like I said here, and still I get the error below:

Some code that might be helpful for you:

Project: workbook

// Code.gs

function onOpen() {
  SpreadsheetApp.getUi().createMenu('MyMenu').addItem('Form', 'closeKits').addToUi();
}
```
<pre class="lang-js prettyprint-override"><code>// CloseKits.gs

function closeKits() {
  scripts.showForm();
}

function callLibraryFunction(data){
  scripts.saveData(data);
}
</code>```

appsscript.json

{
  "timeZone": "America/New_York",
  "dependencies": {
    "libraries": [
      {
        "userSymbol": "scripts",
        "version": "0",
        "libraryId": "1AhbUglj05OrQuaZFqQcL_0UB7MCGope2YpVnE7eOGYjdxiXug0DiDA1i",
        "developmentMode": true
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}
```
<p><strong>Project SCRIPTS:</strong></p>
<pre class="lang-html prettyprint-override"><code><!-- Form.html -->
<!DOCTYPE html>
  <html>
    <head>
      <!--Import Google Icon Font-->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <!--Import materialize.css-->
      <!-- Compiled and minified CSS -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>

    <body>

      <div class="container">
        <form class="col s12">
          <div class="row">
            <label for="requestedBy">Requested By</label>
            <input id="requestedBy" type="text" placeholder="John Doe" class="validate">
          </div>

          <div class="row">
            <label for="dueDate">Due Date</label>
            <input id="dueDate" class="datepicker">
          </div>

          <div class="row">
            <label for="comments">Comments</label>
            <textarea id="comments" placeholder="Please ignore lines X, Y and Z..." class="materialize-textarea"></textarea>
          </div>

          <div class="row">
            <button class="btn waves-effect waves-light" id="btn">
              Submit
            </button>
          </div>
        </form>
      </div>

      <!-- Compiled and minified JavaScript -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
      <script>
        var options = {
          autoClose: true,
          format: 'mm/dd/yyyy',
          defaultDate: new Date(),
          setDefaultDate: true,
          showClearBtn: true
        };

        document.addEventListener('DOMContentLoaded', function() {
          var elements = document.querySelectorAll('.datepicker');
          var instances = M.Datepicker.init(elements, options);
        });

        document.getElementById('btn').addEventListener('click', getData);

        function getData() {
          var requestedBy = document.getElementById('requestedBy').value;
          var dueDate = document.getElementById('dueDate').value;
          var comments = document.getElementById('comments').value;

          var data = {
            requestedBy: requestedBy,
            dueDate: dueDate,
            comments: comments
          };

          google.script.run.callLibraryFunction(data);
        }
      </script>
    </body>
  </html>
</code>```

Here I had to use that callLibraryFunction present in the Code.gs from workbook in order to call the library function saveData, since that last method is not visible to the HTML client running on workbook.

// SaveData.gs

function saveData(data) {
  const iasRequestsSpreadsheet = SpreadsheetApp.openById('1o8JbVelmSNoGn6sn7laatBam_2WTtToB_nlZMTFY_Rg');
  const sheet = iasRequestsSpreadsheet.getSheetByName('page1');

  const line = getFirstEmptyRow(sheet);

  // requested by
  sheet.getRange(line, 2).setValue(data.requestedBy);

  // due date
  sheet.getRange(line, 6).setValue(data.dueDate);

  // comments
  sheet.getRange(line, 9).setValue(data.comments);
}
```
<pre class="lang-js prettyprint-override"><code>// ShowForm.gs

function showForm() {
  const form = HtmlService.createTemplateFromFile('Form').evaluate().setHeight(480);
  SpreadsheetApp.getUi().showModalDialog(form, 'Form');
}
</code>```

// GetFirstEmptyRow.gs

function getFirstEmptyRow(sheet) {
  const column = sheet.getDataRange();
  const values = column.getValues();

  let row = 0;

  for (row; row<values.length; row++) {
    if (!values[row].join("")) {
      break;
    }
  }

  return (row+1);
}
```

Please feel free to ask any other information in order to solve this, and also access those spreadsheets and run once the onOpen from workbook, so it requests the required permissions to you.

EDIT:
As asked, after clicking submit, on the spreadsheet workbook I get only this in the logs:

答: Well, apparently it was something with the browser... On my job notebook it worked using the edge, and for my colleagues it worked both on chrome and edge. But I still don't know what is the incompatibility here.</p>

Body:
So, I got to build a script that asks the user for some information using google apps script. Those codes must be in a specific spreadsheet (1st URL), so does the HTML form that will be loaded by a modal dialog.

Even though the code is written in the spreadsheet SCRIPTS, that project is loaded as a library on the project from spreadsheet workbook, and that's the spreadsheet that will create a menu that will load the code from SCRIPTS.

The final goal is: the user opens workbook, runs the item from MyMenu > Form, a modal/form is opened; the user writes his info and hits submit. After that, the function saveData from SCRIPTS, which will write the informations in the spreadsheet requests.

Obs.: since saveData needs to call 2 methods hosted in the SCRIPTS project, it also needs to be hosted in the same project.

SCRIPTS: https://docs.google.com/spreadsheets/d/1Dkntw25H41JTk0R3Rm9fgiwt_RrAee9zYEz1Wy8DomI/edit?usp=sharing
requests: https://docs.google.com/spreadsheets/d/1o8JbVelmSNoGn6sn7laatBam_2WTtToB_nlZMTFY_Rg/edit?usp=sharing
workbook: https://docs.google.com/spreadsheets/d/17plSc9-kPj6XMBENBLJEE6sc01i82xfhGGPQ1UmOXjE/edit?usp=sharing

The problem here is that on the spreadsheets I shared above, everything works flawlessly, but on the original spreadsheets I need to work on (there are sensitive data from my job there, I can't share the url), when I click on the button submit, I only get this error on the console and nothing works:

PS.: Although I can't share my job's spreadsheet, all the code, from the one in the workbook to the one in the scripts spreadsheet are exactly the same as I wrote for my job, using different spreadsheets just like I said here, and still I get the error below:

Some code that might be helpful for you:

Project: workbook

// Code.gs

function onOpen() {
  SpreadsheetApp.getUi().createMenu('MyMenu').addItem('Form', 'closeKits').addToUi();
}

// CloseKits.gs

function closeKits() {
  scripts.showForm();
}

function callLibraryFunction(data){
  scripts.saveData(data);
}

appsscript.json

{
  "timeZone": "America/New_York",
  "dependencies": {
    "libraries": [
      {
        "userSymbol": "scripts",
        "version": "0",
        "libraryId": "1AhbUglj05OrQuaZFqQcL_0UB7MCGope2YpVnE7eOGYjdxiXug0DiDA1i",
        "developmentMode": true
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}

Project SCRIPTS:

<!DOCTYPE html>

      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

        <form class="col s12">

            Requested By
            <input id="requestedBy" type="text" placeholder="John Doe" class="validate">

            Due Date
            <input id="dueDate" class="datepicker">

            Comments
            <textarea id="comments" placeholder="Please ignore lines X, Y and Z..." class="materialize-textarea"></textarea>

            <button class="btn waves-effect waves-light" id="btn">
              Submit
            </button>

        </form>

Here I had to use that callLibraryFunction present in the Code.gs from workbook in order to call the library function saveData, since that last method is not visible to the HTML client running on workbook.

// SaveData.gs

function saveData(data) {
  const iasRequestsSpreadsheet = SpreadsheetApp.openById('1o8JbVelmSNoGn6sn7laatBam_2WTtToB_nlZMTFY_Rg');
  const sheet = iasRequestsSpreadsheet.getSheetByName('page1');

  const line = getFirstEmptyRow(sheet);

  // requested by
  sheet.getRange(line, 2).setValue(data.requestedBy);

  // due date
  sheet.getRange(line, 6).setValue(data.dueDate);

  // comments
  sheet.getRange(line, 9).setValue(data.comments);
}

// ShowForm.gs

function showForm() {
  const form = HtmlService.createTemplateFromFile('Form').evaluate().setHeight(480);
  SpreadsheetApp.getUi().showModalDialog(form, 'Form');
}

// GetFirstEmptyRow.gs

function getFirstEmptyRow(sheet) {
  const column = sheet.getDataRange();
  const values = column.getValues();

  let row = 0;

  for (row; row<values.length; row++) {
    if (!values[row].join("")) {
      break;
    }
  }

  return (row+1);
}

Please feel free to ask any other information in order to solve this, and also access those spreadsheets and run once the onOpen from workbook, so it requests the required permissions to you.

EDIT:
As asked, after clicking submit, on the spreadsheet workbook I get only this in the logs:


问:
React hooks: setState() with string that contains html?
I'm trying to setState from a json file value that contains html. So something like:</p>
```<code>...
const quote = [quote, setQuote] = useState('');

const quotes = [
    { quote: "Some text." },
    { quote: 'Some text with <span class="red">HTML</span>.' },
  ];
  const handleClick = () => {
    setQuote(quotes[1].quote);
  };
...
return (
  <div>{quote}</div> // right now it's printing the html as text.
);
</code>```

答:
Insert raw HTML using dangerouslySetInnerHTML:

```<code>return (
  <div dangerouslySetInnerHTML={{__html: quote }}></div>
);
</code>```

Body:
I'm trying to setState from a json file value that contains html. So something like:

...
const quote = [quote, setQuote] = useState('');

const quotes = [
    { quote: "Some text." },
    { quote: 'Some text with HTML.' },
  ];
  const handleClick = () => {
    setQuote(quotes[1].quote);
  };
...
return (

{quote}
 // right now it's printing the html as text.
);

Body:
Insert raw HTML using dangerouslySetInnerHTML:

return (
  <div dangerouslySetInnerHTML={{__html: quote }}></div>
);


问:
ViewPager in a NestedScrollView
I need to create an interface like Google Newsstand which is a sort of ViewPager (horizontal scroll) over a collapsing header (vertical scroll). One of my requirements is to use the new Design Support Library presented at the Google IO 2015.
(http://android-developers.blogspot.ca/2015/05/android-design-support-library.html)

Based on the sample created by Chris Banes (https://github.com/chrisbanes/cheesesquare) I've reach the point that I'm able to do the collapsing behaviour but with a basic LinearLayout (without horizontal scroll).

I tried to replace the LinearLayout by a ViewPager and I got a blank screen. I played with: width, weight and all kind of view groups but.... still a blank screen. It seems that ViewPager and NestedScrollView don't like each other.

I tried a workaround by using an HorizontalScrollView: it works but I loose the benefit of the PagerTitleStrip feature and the focus on a single panel (I can stop the horizontally between 2 panels).

Now I have no more ideas, if anyone can lead me to a solution...

Thanks

Here is my latest layout file :

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/header_height"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <include
                layout="@layout/part_header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/activity_main_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/activity_main_nestedscrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v4.view.ViewPager
            android:id="@+id/activity_main_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#FFA0"/>

    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
</code>```

答:
I tried many ways but not worked.
I referred to this and my problem was solved.</p>

Title: ViewPager in a NestedScrollView

Body:
I need to create an interface like Google Newsstand which is a sort of ViewPager (horizontal scroll) over a collapsing header (vertical scroll). One of my requirements is to use the new Design Support Library presented at the Google IO 2015.
(http://android-developers.blogspot.ca/2015/05/android-design-support-library.html)

Based on the sample created by Chris Banes (https://github.com/chrisbanes/cheesesquare) I've reach the point that I'm able to do the collapsing behaviour but with a basic LinearLayout (without horizontal scroll).

I tried to replace the LinearLayout by a ViewPager and I got a blank screen. I played with: width, weight and all kind of view groups but.... still a blank screen. It seems that ViewPager and NestedScrollView don't like each other.

I tried a workaround by using an HorizontalScrollView: it works but I loose the benefit of the PagerTitleStrip feature and the focus on a single panel (I can stop the horizontally between 2 panels).

Now I have no more ideas, if anyone can lead me to a solution...

Thanks

Here is my latest layout file :

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/header_height"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <include
                layout="@layout/part_header"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/activity_main_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/activity_main_nestedscrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v4.view.ViewPager
            android:id="@+id/activity_main_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#FFA0"/>

    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>


问:
best practice using web api with graphql
a little bit naive question but right now I want to create a web api to be more flexible I just read about gqphql , is it a good practice to accept a query string and return a string containing the result </p>

<p>any example using web api and graphql , I know I can secure  queries with something like jws but am speaking about the idea and best practice </p>

答:
I wrote a "Database to GraphQL generator" that like Michael Ingmar Staib suggested uses HotChocolate and has all the best practices in-built! IT saves so much time for large databases and you can make mock tables that represent service calls.

Check it out here: https://github.com/MeaningOfLights/dB2GraphQL.Net

See the projects it generates and the demo databases it comes with, this is what it does:

db2GraphQL.Net

Body:
a little bit naive question but right now I want to create a web api to be more flexible I just read about gqphql , is it a good practice to accept a query string and return a string containing the result

any example using web api and graphql , I know I can secure  queries with something like jws but am speaking about the idea and best practice


答:
Injecting html from text is always a risk, but I think this should work:</p>
```<code>import { useRef } from 'react';

...
const quoteRef = useRef(null);

const quotes = [
    { quote: "Some text." },
    { quote: 'Some text with <span class="red">HTML</span>.' },
  ];
  const handleClick = () => {
    if(!quoteRef.current) return; //Just in case the element got deleted
    quoteRef.current.innerHTML = quotes[1].quote;
  };
...
return (
  <div ref={quoteRef}>{quote}</div> // right now it's printing the html as text.
);
</code>```

Title: React hooks: setState() with string that contains html?

Body:
Injecting html from text is always a risk, but I think this should work:

import { useRef } from 'react';

...
const quoteRef = useRef(null);

const quotes = [
    { quote: "Some text." },
    { quote: 'Some text with <span class="red">HTML</span>.' },
  ];
  const handleClick = () => {
    if(!quoteRef.current) return; //Just in case the element got deleted
    quoteRef.current.innerHTML = quotes[1].quote;
  };
...
return (
  <div ref={quoteRef}>{quote}</div> // right now it's printing the html as text.
);


问:
How to get last week date range based on current date in sql?
I have this code in crystal reports that gives me last week date range based on the current date.

First day of the week:

```<code>If DayOfWeek(currentdate) = 2 Then
currentdate
Else If DayOfWeek(currentdate) = 3 Then
dateadd ("d",-1,currentdate)
Else If DayOfWeek(currentdate) = 4 Then
dateadd ("d",-2,currentdate)
Else If DayOfWeek(currentdate) = 5 Then
dateadd ("d",-3,currentdate)
Else If DayOfWeek(currentdate) = 6 Then
dateadd ("d",-4,currentdate)
Else If DayOfWeek(currentdate) = 7 Then
dateadd ("d",-5,currentdate)
Else If DayOfWeek(currentdate) = 1 Then
dateadd ("d",-6,currentdate)
</code>```

Last day of week:

```<code>If DayOfWeek(currentdate) = 2 Then
dateadd ("d",+6,currentdate)
Else If DayOfWeek(currentdate) = 3 Then
dateadd ("d",+5,currentdate)
Else If DayOfWeek(currentdate) = 4 Then
dateadd ("d",+4,currentdate)
Else If DayOfWeek(currentdate) = 5 Then
dateadd ("d",+3,currentdate)
Else If DayOfWeek(currentdate) = 6 Then
dateadd ("d",+2,currentdate)
Else If DayOfWeek(currentdate) = 7 Then
dateadd ("d",+1,currentdate)
Else If DayOfWeek(currentdate) = 1 then currentdate
</code>```

How can I do the same in SQL using 2 variables to storage Monday(startdate) and Sunday(enddate)?

I found this select datepart(dw,getdate()) --6 in this site, but I do not know how to use it.

答:
A shortened version concise syntax

last week, in my vision is the prev adjacent week, so if Im doing report during the week days, I want to receive dates of previous adjacent week Monday to Sunday.

prev Monday is DATE_ADD(CURDATE(), INTERVAL -(5 + dayofweek(CURDATE())) DAY)

prev Sunday is DATE_ADD(CURDATE(), INTERVAL -(dayofweek(CURDATE()) - 1) DAY)

then to take the report from the table need just to integrate those two in SELECT statement

select * from XXX where DateCol between DATE_ADD(CURDATE(), INTERVAL -(5 + dayofweek(CURDATE())) DAY) and DATE_ADD(CURDATE(), INTERVAL -(dayofweek(CURDATE()) - 1) DAY) order by DateCol

Body:
I have this code in crystal reports that gives me last week date range based on the current date.

First day of the week:

If DayOfWeek(currentdate) = 2 Then
currentdate
Else If DayOfWeek(currentdate) = 3 Then
dateadd ("d",-1,currentdate)
Else If DayOfWeek(currentdate) = 4 Then
dateadd ("d",-2,currentdate)
Else If DayOfWeek(currentdate) = 5 Then
dateadd ("d",-3,currentdate)
Else If DayOfWeek(currentdate) = 6 Then
dateadd ("d",-4,currentdate)
Else If DayOfWeek(currentdate) = 7 Then
dateadd ("d",-5,currentdate)
Else If DayOfWeek(currentdate) = 1 Then
dateadd ("d",-6,currentdate)

Last day of week:

If DayOfWeek(currentdate) = 2 Then
dateadd ("d",+6,currentdate)
Else If DayOfWeek(currentdate) = 3 Then
dateadd ("d",+5,currentdate)
Else If DayOfWeek(currentdate) = 4 Then
dateadd ("d",+4,currentdate)
Else If DayOfWeek(currentdate) = 5 Then
dateadd ("d",+3,currentdate)
Else If DayOfWeek(currentdate) = 6 Then
dateadd ("d",+2,currentdate)
Else If DayOfWeek(currentdate) = 7 Then
dateadd ("d",+1,currentdate)
Else If DayOfWeek(currentdate) = 1 then currentdate

How can I do the same in SQL using 2 variables to storage Monday(startdate) and Sunday(enddate)?

I found this select datepart(dw,getdate()) --6 in this site, but I do not know how to use it.