问:
Multi-Media Book App for iPad - Obj-C or Corona Or Cocos2D?
I am planning to build a BOOK APP (with text, images, animation, sound etc) for iPad. I started learning Obj-C But I came to know about frameworks like Corona & Cocos2D and Corona boasts to be promising for my scenario. I have no working experience with any of these but am willing to learn. Which one is better to start with for building a multi-media book app? XCode & Obj-C OR Corona OR Cocos2D and how would would be the learning curve?</p>

答:
I can't speak for Corona, but Cocos2D is just an Obj-C library, so you'll still have to know a bit of Obj-C to get it going.

That said, I started with just Objective-C, then found Cocos2D which greatly improved my development speed, as all the groundwork is already implemented. Cocos2D has a much more managable learning curve than doing it all from scratch, and there are a number of great resources available (cocos2d forums, this blog, etc).

A quick Google search showed me that Corona has costs associated with it for distribution - cocos2d does not.


来源: stackexchange

问:
how to exit a loop with a keystroke
I have a script that searches for a running process (notepad) and it will stay runnning until notpad is no longer running:

```<code>:search
TASKLIST|FIND "notepad.exe" >nul 2>&1
IF %ERRORLEVEL% equ 0 (GOTO found)
timeout 3 > nul
GOTO search

:found
exit
</code>```

What i'd like to insert here is a prompt for keypress to exit this loop and jump to :foundIf no keypress is entered the file keep looking for notepad until it closes.

答:
I corrected your logic a bit (to match stay running until notepad is no longer running)

```<code>:search
TASKLIST|FIND "notepad.exe" >nul 2>&1
IF errorlevel 1 GOTO :cont
choice /c cn  /t 3 /d n /n /m "[C]ancel"
if errorlevel 2 goto :search
echo you cancelled.
goto :eof

:cont
echo Notepad has closed.
exit /b
</code>```

For an explanation of the choice command see choice /?

For an explanation of the changed if errorlevel syntax, see if /?

or - if you don't like the continuous [C]ancel - suppress the output of choice and print the hint before the loop:

```<code>echo [C]ancel
:search
TASKLIST|FIND "notepad.exe" >nul 2>&1
IF errorlevel 1 GOTO :cont
choice /c cn  /t 3 /d n >nul
if errorlevel 2 goto :search
echo you cancelled.
goto :eof

:cont
echo Notepad has closed.
exit /b
</code>```

ContentLicense: CC BY-SA 4.0

Title: how to exit a loop with a keystroke

Body:
I have a script that searches for a running process (notepad) and it will stay runnning until notpad is no longer running:

:search
TASKLIST|FIND "notepad.exe" >nul 2>&1
IF %ERRORLEVEL% equ 0 (GOTO found)
timeout 3 > nul
GOTO search

:found
exit

What i'd like to insert here is a prompt for keypress to exit this loop and jump to :foundIf no keypress is entered the file keep looking for notepad until it closes.

Body:
I corrected your logic a bit (to match stay running until notepad is no longer running)

:search
TASKLIST|FIND "notepad.exe" >nul 2>&1
IF errorlevel 1 GOTO :cont
choice /c cn  /t 3 /d n /n /m "[C]ancel"
if errorlevel 2 goto :search
echo you cancelled.
goto :eof

:cont
echo Notepad has closed.
exit /b

For an explanation of the choice command see choice /?

For an explanation of the changed if errorlevel syntax, see if /?

or - if you don't like the continuous [C]ancel - suppress the output of choice and print the hint before the loop:

echo [C]ancel
:search
TASKLIST|FIND "notepad.exe" >nul 2>&1
IF errorlevel 1 GOTO :cont
choice /c cn  /t 3 /d n >nul
if errorlevel 2 goto :search
echo you cancelled.
goto :eof

:cont
echo Notepad has closed.
exit /b


问:
Different behaviors between train_on_batch and gradientTape
I'm trying to train a simple keras model on some data using

approach 1

```<code>model.train_on_batch(x, y)
</code>```

and approach 2

```<code>with tf.GradientTape() as g:
    g.watch(model.variables)
    loss = my_loss(
        y_true=y,
        y_pred=model(x)
    )
    gradients = g.gradient(loss, model.variables)
    opt.apply_gradients(
              zip(gradients, model.variables)
    )
</code>```

Even if the optimizer (Adam with some fixed learning rate) and the loss are the same, I do not get the exact same behavior. Is is expected ? (aka train_on_batch doing some additional stuff)

答:
In approach 1, train_on_batch trains using a single batch only and once. Runs a single gradient update on a single batch of data. The idea of using train_on_batch is probably to do more things between each batch.

In approach 2, gradient update depends on the frequency of optimizer.apply_gradients(zip(grads, model.trainable_weights)) in the training loop.

As gradient update is happening differently in both the cases, there might be difference in the model behavior.

Hope this answers your question. Happy Learning.

Body:
I'm trying to train a simple keras model on some data using

approach 1

model.train_on_batch(x, y)

and approach 2

with tf.GradientTape() as g:
    g.watch(model.variables)
    loss = my_loss(
        y_true=y,
        y_pred=model(x)
    )
    gradients = g.gradient(loss, model.variables)
    opt.apply_gradients(
              zip(gradients, model.variables)
    )

Even if the optimizer (Adam with some fixed learning rate) and the loss are the same, I do not get the exact same behavior. Is is expected ? (aka train_on_batch doing some additional stuff)


问:
How to remove unnecessary space between Grid Rows of Material-UI?
I was trying to use material ui grid system but there is an awkward space occur when i use grid direction='row'.

```<code>const useStyles = makeStyles((theme) => ({
    gridHome: {
        minHeight: '100vh',
        border: '2px solid red'
    },
    gridContent: {
        width: '100%',
        border: '2px solid black',
        textAlign: 'center'
    },
    title: {
        fontFamily: 'Dancing Script,Sans Serif,cursive',
    }
 }));

const NewUser = () => {
    const classes = useStyles();
    return (
        <React.Fragment>
            <Grid container direction='row' justify='center' alignItems='flex-start' className=
            {classes.gridHome}>
                <Grid item xs={12} md={12} className={classes.gridContent}>
                    <Typography className={classes.title}>user</Typography>
                </Grid>
                <Grid item xs={12} md={12} className={classes.gridContent}>
                    <Typography className={classes.title}>Welcome User</Typography>
                </Grid>
            </Grid>
       </React.Fragment>
    );
}
</code>```

答:
minHeight: '100vh' is the issue, because this Grid component is container and having display flex and "Grid item" component is having column width to 12...so first grid component will occupy entire width and hence second will be rendered in next row but container is flex so height of container will be divided in half and new Grid Item will be rendered from there ... causing this akward spacing.

This issue is very similar to Material UI Grid List Rows with a big awkward gap

Body:
I was trying to use material ui grid system but there is an awkward space occur when i use grid direction='row'.

const useStyles = makeStyles((theme) => ({
    gridHome: {
        minHeight: '100vh',
        border: '2px solid red'
    },
    gridContent: {
        width: '100%',
        border: '2px solid black',
        textAlign: 'center'
    },
    title: {
        fontFamily: 'Dancing Script,Sans Serif,cursive',
    }
 }));

const NewUser = () => {
    const classes = useStyles();
    return (
        <React.Fragment>
            <Grid container direction='row' justify='center' alignItems='flex-start' className=
            {classes.gridHome}>
                <Grid item xs={12} md={12} className={classes.gridContent}>
                    <Typography className={classes.title}>user</Typography>
                </Grid>
                <Grid item xs={12} md={12} className={classes.gridContent}>
                    <Typography className={classes.title}>Welcome User</Typography>
                </Grid>
            </Grid>
       </React.Fragment>
    );
}


问:
Does using assembly compiled in older version of .NET framework affects whole performance?
Lets imagine that we have two assemblies:

Foo.Logic (compiled on .NET 2.0 framework)

Foo.Application (compiled on .NET 4.0 framework) that have reference and uses compiled Foo.Logic.

Does it have impact on Foo.Application performance (or have any other drawbacks)?

答:
Unless you use explicitly use SxS, your .NET 2 assembly will be loaded into the .NET 4 CLR. There shouldn't be any performance problems at all... the code which originally targeted .NET 2 will just run using the .NET 4 libraries and CLR, etc. And yes, you can use an assembly compiled with .NET 1.1 in a .NET 2 or higher app, too.

There is a problem if you try to load a mixed-mode assembly (some native code, some IL) in .NET 4, IIRC... but if it's "just" a .NET class library, you should be fine.

ContentLicense: CC BY-SA 3.0


问:
(javaScript: DOM) setAttribute index
I'm trying to add  an image inside  through javaScript DOM and just wondering why the first code works but second code doesn't work? Why does img need an index?

```<code>    var img = document.querySelectorAll("img");
    img[0].setAttribute("src", "images/image_1.jpg");
    img[0].setAttribute("style", "width:500px; height:200px;");
</code>```

```<code>    var img = document.querySelectorAll("img");
    img.setAttribute("src", "images/image_1.jpg");
    img.setAttribute("style", "width:500px; height:200px;");
</code>```

答:
Because document.querySelectorAll returns an element list.

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

FYI

If you use document.querySelector instead, you don't need to specify the index because it returns the first element within the document that matches the specified selector.

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Title: (javaScript: DOM) setAttribute index

Body:
I'm trying to add  an image inside  through javaScript DOM and just wondering why the first code works but second code doesn't work? Why does img need an index?

    var img = document.querySelectorAll("img");
    img[0].setAttribute("src", "images/image_1.jpg");
    img[0].setAttribute("style", "width:500px; height:200px;");

    var img = document.querySelectorAll("img");
    img.setAttribute("src", "images/image_1.jpg");
    img.setAttribute("style", "width:500px; height:200px;");


问:
How to create a new VM with a HDD os disk using Powershell
I want to choose HDD os disk for a new VM to be deployed. I have tried using "New-AzDisk" "Set-AzVMOSDisk" and "New-AzVM"  powershell commands but got an error :
 New-AzVM : Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorCode: InvalidParameter
ErrorMessage: Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorTarget: osDisk
StatusCode: 400
ReasonPhrase: Bad Request
OperationID : e7cac0e6-2ed8-4a61-a4ef-0bd04590b935
Au caractère Ligne:1 : 1
+ New-AzVM -ResourceGroupName $rg_name -Location $location -VM $vm_adfs ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError : (:) [New-AzVM], ComputeCloudException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.NewAzureVMCommand

my code is the following

```<code>    $diskconfig = New-AzDiskConfig -Location $location -DiskSizeGB 127 -AccountType Standard_LRS -OsType Windows -CreateOption Empty
    $disk = New-AzDisk -ResourceGroupName $rg_name -DiskName $vm_name -Disk $diskconfig
    $vm = New-AzVMConfig -VMName $vm_name -VMSize "Standard_DS1_V2"
    $vm = Set-AzVMOSDisk -VM $vm_adfs -ManagedDiskId $disk_adfs.Id -CreateOption Attach -Windows
    $vm = Set-AzVMOperatingSystem -VM $vm -Windows -ComputerName $vm_name -Credential $vm_cred -ProvisionVMAgent -EnableAutoUpdate
    $vm = Add-AzVMNetworkInterface -VM $vm -Id $nic.Id
    $vm = Set-AzVMSourceImage -VM $vm_adfs -PublisherName 'MicrosoftWindowsServer' -Offer 'WindowsServer' -Skus '2016-Datacenter' -Version latest
    New-AzVM -ResourceGroupName $rg_name -Location $location -VM $vm -Verbose
</code>```

答:
It seems you want to create a VM with HDD os disk type from a VM image, but your code attempt to attach an existing os disk. I think it's the problem that caused the error. So the solution for you is that change the command:

```<code>$vm = Set-AzVMOSDisk -VM $vm_adfs -ManagedDiskId $disk_adfs.Id -CreateOption Attach -Windows
</code>```

into:

```<code>$vm = Set-AzVMOSDisk -VM $vm_adfs -StorageAccountType Standard_LRS -CreateOption Attach -Windows
</code>```

Or if you want to attach the existing OS disk to your new VM, then you just need to delete the command:

```<code>$vm = Set-AzVMSourceImage -VM $vm_adfs -PublisherName 'MicrosoftWindowsServer' -Offer 'WindowsServer' -Skus '2016-Datacenter' -Version latest
</code>```

You cannot create a new VM from the VM image while attaching another existing OS disk to it. These two means will conflict when you use both of them at one time.

Body:
I want to choose HDD os disk for a new VM to be deployed. I have tried using "New-AzDisk" "Set-AzVMOSDisk" and "New-AzVM"  powershell commands but got an error :
 New-AzVM : Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorCode: InvalidParameter
ErrorMessage: Cannot attach an existing OS disk if the VM is created from a platform, user or a shared gallery image.
ErrorTarget: osDisk
StatusCode: 400
ReasonPhrase: Bad Request
OperationID : e7cac0e6-2ed8-4a61-a4ef-0bd04590b935
Au caractère Ligne:1 : 1
+ New-AzVM -ResourceGroupName $rg_name -Location $location -VM $vm_adfs ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError : (:) [New-AzVM], ComputeCloudException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.NewAzureVMCommand

my code is the following

    $diskconfig = New-AzDiskConfig -Location $location -DiskSizeGB 127 -AccountType Standard_LRS -OsType Windows -CreateOption Empty
    $disk = New-AzDisk -ResourceGroupName $rg_name -DiskName $vm_name -Disk $diskconfig
    $vm = New-AzVMConfig -VMName $vm_name -VMSize "Standard_DS1_V2"
    $vm = Set-AzVMOSDisk -VM $vm_adfs -ManagedDiskId $disk_adfs.Id -CreateOption Attach -Windows
    $vm = Set-AzVMOperatingSystem -VM $vm -Windows -ComputerName $vm_name -Credential $vm_cred -ProvisionVMAgent -EnableAutoUpdate
    $vm = Add-AzVMNetworkInterface -VM $vm -Id $nic.Id
    $vm = Set-AzVMSourceImage -VM $vm_adfs -PublisherName 'MicrosoftWindowsServer' -Offer 'WindowsServer' -Skus '2016-Datacenter' -Version latest
    New-AzVM -ResourceGroupName $rg_name -Location $location -VM $vm -Verbose

Body:
It seems you want to create a VM with HDD os disk type from a VM image, but your code attempt to attach an existing os disk. I think it's the problem that caused the error. So the solution for you is that change the command:

$vm = Set-AzVMOSDisk -VM $vm_adfs -ManagedDiskId $disk_adfs.Id -CreateOption Attach -Windows

into:

$vm = Set-AzVMOSDisk -VM $vm_adfs -StorageAccountType Standard_LRS -CreateOption Attach -Windows

Or if you want to attach the existing OS disk to your new VM, then you just need to delete the command:

$vm = Set-AzVMSourceImage -VM $vm_adfs -PublisherName 'MicrosoftWindowsServer' -Offer 'WindowsServer' -Skus '2016-Datacenter' -Version latest

You cannot create a new VM from the VM image while attaching another existing OS disk to it. These two means will conflict when you use both of them at one time.


问:
SSL enabled Microservice architecture with Spring boot
My Setup

I have built my project using multiple spring boot applications as micro services. And there is another spring boot application called as api-gateway, which acts as a reverse-proxy for all other micro services. I am using ZuulProxy for this. Each micro service comes up with it's own tomcat with different ports and api-gateway routes the traffic across these. And micro services talk to each other over http.

I am spinning up the micro services and api-gatway as docker containers. This is my back-end setup.

I have a web client developed in html, angularjs and this is also running as docker container. This web application calls back-end APIs over http REST. This container is an apache container exposing 80 port.

So, when someone hits http://example.com it reaches web app container and loads the UI. This UI uses http://api-example.com/* for it's REST calls. So, in apache container(httpd.conf) I have added VirtualHosts like this.

```<code><VirtualHost *:80>
  ServerName example.com
  DocumentRoot "<path to my UI files>"
</VirtualHost>

<VirtualHost *:80>
  ServerName api-example.com
  ProxyPass / http://apigateway:8081/
  ProxyPassReverse / http://apigateway:8081/
</VirtualHost>
</code>```

Overview of my setup

Question

Everything is working as expected over http. But what is the right way to enable SSL for this setup.

What I tried

I bought a certificate and configure in web app container and UI is loading fine in the browser over https. Since, I was using http://api-example.com/* in UI for api calls, browser thrown me error saying non secure call in secure application. So, I have changed the api url to https in UI code. For that I have added a VirtualHost in httpd.conf like this

```<code><VirtualHost *:443>
  ServerName api-example.com
  ProxyPass / http://apigateway:8081/ timeout=600
  ProxyPassReverse / http://apigateway:8081/ timeout=600
</VirtualHost>
</code>```

This whole thing is deployed in a server. And I am able to access application over https from my browser.
But, it is not working from other's laptop. It is working sometimes and it is failing rest of the time, with a CORS error while UI accessing https://api-example.com/.

Complete error in the browser console :
Access to XMLHttpRequest at 'https://api-example.com/api/auth/login?' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

By the way, I also have below code to comply with CORS, in my api-gateway

```<code>    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedHeader("Access-Control-Allow-Origin");
        config.addExposedHeader("X-AuthToken");  //This is must for browser to read X-AuthToken header
        config.addExposedHeader("X-filename");  //This is must for browser to read X-filename header
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
</code>```

This looks very strange, because I am not getting this error in my browser. My colleagues have tried all other browsers and cleared the browser cache also.

So, I am suspecting the way I have done this architecture. Can someone please tell me what mistake I made or suggest a better way to setup something like this.

NOTE: I wanted to have all my services and web app in the same machine for now.

答:
Can you modify as below and see if it works? I suspect source.registerCorsConfiguration("/**", config); creating problem.

```<code>config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("*", config);
</code>```

Body:
My Setup

I have built my project using multiple spring boot applications as micro services. And there is another spring boot application called as api-gateway, which acts as a reverse-proxy for all other micro services. I am using ZuulProxy for this. Each micro service comes up with it's own tomcat with different ports and api-gateway routes the traffic across these. And micro services talk to each other over http.

I am spinning up the micro services and api-gatway as docker containers. This is my back-end setup.

I have a web client developed in html, angularjs and this is also running as docker container. This web application calls back-end APIs over http REST. This container is an apache container exposing 80 port.

So, when someone hits http://example.com it reaches web app container and loads the UI. This UI uses http://api-example.com/* for it's REST calls. So, in apache container(httpd.conf) I have added VirtualHosts like this.

<VirtualHost *:80>
  ServerName example.com
  DocumentRoot "<path to my UI files>"
</VirtualHost>

<VirtualHost *:80>
  ServerName api-example.com
  ProxyPass / http://apigateway:8081/
  ProxyPassReverse / http://apigateway:8081/
</VirtualHost>

Overview of my setup

Question

Everything is working as expected over http. But what is the right way to enable SSL for this setup.

What I tried

I bought a certificate and configure in web app container and UI is loading fine in the browser over https. Since, I was using http://api-example.com/* in UI for api calls, browser thrown me error saying non secure call in secure application. So, I have changed the api url to https in UI code. For that I have added a VirtualHost in httpd.conf like this

<VirtualHost *:443>
  ServerName api-example.com
  ProxyPass / http://apigateway:8081/ timeout=600
  ProxyPassReverse / http://apigateway:8081/ timeout=600
</VirtualHost>

This whole thing is deployed in a server. And I am able to access application over https from my browser.
But, it is not working from other's laptop. It is working sometimes and it is failing rest of the time, with a CORS error while UI accessing https://api-example.com/.

Complete error in the browser console :
Access to XMLHttpRequest at 'https://api-example.com/api/auth/login?' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

By the way, I also have below code to comply with CORS, in my api-gateway

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedHeader("Access-Control-Allow-Origin");
        config.addExposedHeader("X-AuthToken");  //This is must for browser to read X-AuthToken header
        config.addExposedHeader("X-filename");  //This is must for browser to read X-filename header
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

This looks very strange, because I am not getting this error in my browser. My colleagues have tried all other browsers and cleared the browser cache also.

So, I am suspecting the way I have done this architecture. Can someone please tell me what mistake I made or suggest a better way to setup something like this.

NOTE: I wanted to have all my services and web app in the same machine for now.

Body:
Can you modify as below and see if it works? I suspect source.registerCorsConfiguration("/**", config); creating problem.

config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("*", config);


问:
how to project fields using another field's value in mongo db?
I have a mongo document like this:

```<code>{"_id": {"$oid":"xx"} ,"start": "a", "elements": {"a":"large object", "b": "large object"}
</code>```

My expected query result is to project only the start element, in this case, it is {"elements.a:"large object"}. But with the value of "start" unknow before the query, I don't know how to write the query.

2 undesirable alternatives:

One way I could figure is to query start once with _id, and project for start to get "a", and another for elements.a。（

Another way is query all, and get the start element in code. But I don't want to query all at once for the document may be very large)

答:
You can make use of $objectToArray, $arrayToObject and $filter operators.

The below query will be helpful:

db.collection.aggregate([
  {
    $project: {
      elements: {
        $arrayToObject: {
          $filter: {
            input: {
              $objectToArray: "$elements"
            },
            as: "e",
            cond: {
              $eq: [
                "$$e.k",
                "$start"
              ]
            }
          }
        }
      }
    }
  }
])
```

<p>Output:</p>

```[
  {
    "_id": 1,
    "elements": {
      "a": "large object"
    }
  }
]
```

MongoPlayGroundLink

I hope, this is what you want.

Body:
I have a mongo document like this:

{"_id": {"$oid":"xx"} ,"start": "a", "elements": {"a":"large object", "b": "large object"}

My expected query result is to project only the start element, in this case, it is {"elements.a:"large object"}. But with the value of "start" unknow before the query, I don't know how to write the query.

2 undesirable alternatives:

One way I could figure is to query start once with _id, and project for start to get "a", and another for elements.a。（

Another way is query all, and get the start element in code. But I don't want to query all at once for the document may be very large)

Body:
You can make use of $objectToArray, $arrayToObject and $filter operators.

The below query will be helpful:

db.collection.aggregate([
  {
    $project: {
      elements: {
        $arrayToObject: {
          $filter: {
            input: {
              $objectToArray: "$elements"
            },
            as: "e",
            cond: {
              $eq: [
                "$$e.k",
                "$start"
              ]
            }
          }
        }
      }
    }
  }
])

Output:

[
  {
    "_id": 1,
    "elements": {
      "a": "large object"
    }
  }
]

MongoPlayGroundLink

I hope, this is what you want.


问:
Android - Generate CSV file from table values
I have a database containing one table, i want to generate CSV file with values of this table.

Actually, I want to email this CSV file as an attachment. I know about sending file as an attachment in email intent(ACTION_SEND), but I don't know the procedure of creating or the method by which i can create CSV formatted file.

Please give me suggestions or ideas.

答:
In case of using Kotlin, I recommend kotlin-csv library.

Just get the list of DB table objects, go through all of them and add the column values to CSV rows, one by one, like this:

```<code>csvWriter().open(csvFile) {
    // Header
    writeRow(listOf("[id]", "[name]", "[age]"))

    peopleList.forEachIndexed { index, person ->
        writeRow(listOf(index, person.fullName, person.age))
    }
}
</code>```

I explain the whole process of creating csv file here.

Body:
In case of using Kotlin, I recommend kotlin-csv library.

Just get the list of DB table objects, go through all of them and add the column values to CSV rows, one by one, like this:

csvWriter().open(csvFile) {
    // Header
    writeRow(listOf("[id]", "[name]", "[age]"))

    peopleList.forEachIndexed { index, person ->
        writeRow(listOf(index, person.fullName, person.age))
    }
}

I explain the whole process of creating csv file here.


问:
My C program's "for" loop is stalling after 3 iterations
I've made a simple C program for reversing practice - however, when I enter a name and password, it iterates thrice through the for loop then stops and has a spinning cursor, finally exiting with no output back to the CLI. I've made changes to my algorithm and ensured it's correct (the function x here is not the problem, as even when returning its static value this freezing occurs). Where in my program have I gone astray? (This is my first day of C, and IDEONE said I had a buffer overflow.)

Program:

```<code>#include <stdio.h>
#include <string.h>

int x(char* s, int c) {
    return 65;
}

int main(void) {

    char N[16] = ""; // Entered name
    char p[16] = ""; // Entered password
    char r[16] = ""; // Result of applying keygen `x` to `N` (`p` should be this to be correct)

    char n;
    printf("Enter name: ");
    scanf("%s", N);
    printf("Entered name\n");
    printf("Enter password: ");
    scanf("%s", p);
    printf("Entered password\n");

    int j;
    for (j = 0; j < strlen(N); j++) {
        printf("Iterating, iteration %d\n", j);
        if (N[j] == 0) {
            break;
        }
        n = x(N, j);
        strcat(r, &n);
    }
    if (strcmp(r, p) == 0) {
        printf("Correct!\n");
    }
    else {
        printf("Incorrect!\n");
    }
    return 0;
}
</code>```

CLI:

```<code>C:\MinGW\bin>gcc "\\Mac\Home\Desktop\My Crackme.c" -o "\\Mac\Home\Desktop\MyCrackme.exe"
C:\MinGW\bin>"\\Mac\Home\Desktop\MyCrackme.exe"

Enter name: Jack
Entered name
Enter password: Not Jack
Entered password
Iterating, iteration 0
Iterating, iteration 1
Iterating, iteration 2

C:\MinGW\bin>
</code>```

This appears to only happen when I compile with MinGW into an exe - compiling into a generic executable with gcc on my Mac produces a seemingly working program. However, I need an exe file. All help appreciated!

答:
The problem is with strcat(r, &n); because *n is not a null terminated string but a single char. strcat copies up until the first null it encounters, which it won't here. So your r will overflow, causing the abort.

Instead of strcat you must manually append the character, for example:

```<code>int len= strlen(r);
*(r+len  )= n;
*(r+len+1)= '\0';
</code>```

or (better):

```<code>int len= strlen(r);
if (len<sizeof(r)-1) {
    *(r+len  )= n;
    *(r+len+1)= '\0';
}
</code>```

Body:
I've made a simple C program for reversing practice - however, when I enter a name and password, it iterates thrice through the for loop then stops and has a spinning cursor, finally exiting with no output back to the CLI. I've made changes to my algorithm and ensured it's correct (the function x here is not the problem, as even when returning its static value this freezing occurs). Where in my program have I gone astray? (This is my first day of C, and IDEONE said I had a buffer overflow.)

Program:

#include <stdio.h>
#include <string.h>

int x(char* s, int c) {
    return 65;
}

int main(void) {

    char N[16] = ""; // Entered name
    char p[16] = ""; // Entered password
    char r[16] = ""; // Result of applying keygen `x` to `N` (`p` should be this to be correct)

    char n;
    printf("Enter name: ");
    scanf("%s", N);
    printf("Entered name\n");
    printf("Enter password: ");
    scanf("%s", p);
    printf("Entered password\n");

    int j;
    for (j = 0; j < strlen(N); j++) {
        printf("Iterating, iteration %d\n", j);
        if (N[j] == 0) {
            break;
        }
        n = x(N, j);
        strcat(r, &n);
    }
    if (strcmp(r, p) == 0) {
        printf("Correct!\n");
    }
    else {
        printf("Incorrect!\n");
    }
    return 0;
}

CLI:

C:\MinGW\bin>gcc "\\Mac\Home\Desktop\My Crackme.c" -o "\\Mac\Home\Desktop\MyCrackme.exe"
C:\MinGW\bin>"\\Mac\Home\Desktop\MyCrackme.exe"

Enter name: Jack
Entered name
Enter password: Not Jack
Entered password
Iterating, iteration 0
Iterating, iteration 1
Iterating, iteration 2

C:\MinGW\bin>

This appears to only happen when I compile with MinGW into an exe - compiling into a generic executable with gcc on my Mac produces a seemingly working program. However, I need an exe file. All help appreciated!

Body:
The problem is with strcat(r, &n); because *n is not a null terminated string but a single char. strcat copies up until the first null it encounters, which it won't here. So your r will overflow, causing the abort.

Instead of strcat you must manually append the character, for example:

int len= strlen(r);
*(r+len  )= n;
*(r+len+1)= '\0';

or (better):

int len= strlen(r);
if (len<sizeof(r)-1) {
    *(r+len  )= n;
    *(r+len+1)= '\0';
}


问:
Simple java lib for text templating?
I need to template some email texts. Nothing fancy, just replace something like @name@ with real value. No pictures, no fancy formatting etc.

What java lib could you recommend? The simplier the better.

答:
It very simple to do it yourself:

```<code>public class Substitution {

  public static void main(String[] args) throws Exception {
    String a = "aaaa@bbb@ccc";

    // This can be easiliy FileReader or any Reader
    Reader sr = new StringReader(a);

    // This can be any Writer (ie FileWriter)
    Writer wr = new StringWriter();

    for (;;) {
      int c = sr.read();
      if (c == -1) { //EOF
        break;
      }
      if (c == '@') {
        String var = readVariable(sr);
        String val = getValue(var);
        wr.append(val);
      }
      else {
        wr.write(c);
      }
    }
  }

  /**
   * This finds the value from Map, or somewhere
   */
  private static String getValue(String var)  {
    return null;
  }

  private static String readVariable(Reader sr)throws Exception {
    StringBuilder nameSB = new StringBuilder();
    for (;;) {
      int c = sr.read();
      if (c == -1) {
        throw new IllegalStateException("premature EOF.");
      }
      if (c == '@') {
        break;
      }
      nameSB.append((char)c);
    }
    return nameSB.toString();
  }
}
</code>```

You have to polish it a little bit, but that's all.

Title: Simple java lib for text templating?

Body:
It very simple to do it yourself:

public class Substitution {

  public static void main(String[] args) throws Exception {
    String a = "aaaa@bbb@ccc";

    // This can be easiliy FileReader or any Reader
    Reader sr = new StringReader(a);

    // This can be any Writer (ie FileWriter)
    Writer wr = new StringWriter();

    for (;;) {
      int c = sr.read();
      if (c == -1) { //EOF
        break;
      }
      if (c == '@') {
        String var = readVariable(sr);
        String val = getValue(var);
        wr.append(val);
      }
      else {
        wr.write(c);
      }
    }
  }

  /**
   * This finds the value from Map, or somewhere
   */
  private static String getValue(String var)  {
    return null;
  }

  private static String readVariable(Reader sr)throws Exception {
    StringBuilder nameSB = new StringBuilder();
    for (;;) {
      int c = sr.read();
      if (c == -1) {
        throw new IllegalStateException("premature EOF.");
      }
      if (c == '@') {
        break;
      }
      nameSB.append((char)c);
    }
    return nameSB.toString();
  }
}

You have to polish it a little bit, but that's all.


问:
Difference between std::fabs(a * b) and std::fabs(a) * std::fabs(b)
I am working on some numerical code and I was looking at the compiler output. One particular case struck me as odd:

In real numbers, it holds that abs(a) * abs(b) = abs(a * b). I would expect the same to hold in floating point numbers. However, the optimization is performed neither by clang nor by g++ and I wonder whether I am missing some subtle difference there. Both compilers do however realize that abs(abs(a) * abs(b)) = abs(a) * abs(b).

Here is the relevant piece of code:

```<code>#include<cmath>

double fabsprod1(double a, double b) {
    return std::fabs(a*b);
}
double fabsprod2(double a, double b) {
    return std::fabs(a) * std::fabs(b);
}
double fabsprod3(double a, double b) {
    return std::fabs(std::fabs(a) * std::fabs(b));
}
</code>```

And here is the confusing compiler output in godbolt with gcc-10.1 (current stable version as of writing this) and -O3: https://godbolt.org/z/ZEFPgF

Notably, even with -Ofast, which as far as I understand is more lenient with the transformations that are allowed, this optimization is not performed.

As was pointed out by @Scheff in the comments, double and float are not real numbers. But I also fail to see where corner cases with float types, such as getting Infinity or NaN as argument, could produce different outputs.

答:
Comparable problem with intregrals (int) :

```<code>#include<cmath>

int fabsprod1(int a, int b) {
    return std::abs(a*b);
}
int fabsprod2(int a, int b) {
    return std::abs(a) * std::abs(b);
}
int fabsprod3(int a, int b) {
    return std::abs(std::abs(a) * std::abs(b));
}
</code>```

Results in (using your options -O3 -std=c++2a -march=cannonlake):

```<code>fabsprod1(int, int):
        mov     eax, edi
        imul    eax, esi
        cdq
        xor     eax, edx
        sub     eax, edx
        ret
fabsprod2(int, int):
        mov     eax, edi
        cdq
        xor     eax, edx
        sub     eax, edx
        mov     edx, esi
        sar     edx, 31
        xor     esi, edx
        sub     esi, edx
        imul    eax, esi
        ret
fabsprod3(int, int):
        mov     eax, edi
        cdq
        xor     eax, edx
        sub     eax, edx
        mov     edx, esi
        sar     edx, 31
        xor     esi, edx
        sub     esi, edx
        imul    eax, esi
        ret
</code>```

https://godbolt.org/z/tf3nZN

This contradicts your statement about "real/floating point" numbers.

Overall you shouldn't expect the compiler to shortcut math problems for you. That being said some optimizations is made possible. Please provide documentation or a comparable example where you see the optimaztion.

Body:
I am working on some numerical code and I was looking at the compiler output. One particular case struck me as odd:

In real numbers, it holds that abs(a) * abs(b) = abs(a * b). I would expect the same to hold in floating point numbers. However, the optimization is performed neither by clang nor by g++ and I wonder whether I am missing some subtle difference there. Both compilers do however realize that abs(abs(a) * abs(b)) = abs(a) * abs(b).

Here is the relevant piece of code:

#include<cmath>

double fabsprod1(double a, double b) {
    return std::fabs(a*b);
}
double fabsprod2(double a, double b) {
    return std::fabs(a) * std::fabs(b);
}
double fabsprod3(double a, double b) {
    return std::fabs(std::fabs(a) * std::fabs(b));
}

And here is the confusing compiler output in godbolt with gcc-10.1 (current stable version as of writing this) and -O3: https://godbolt.org/z/ZEFPgF

Notably, even with -Ofast, which as far as I understand is more lenient with the transformations that are allowed, this optimization is not performed.

As was pointed out by @Scheff in the comments, double and float are not real numbers. But I also fail to see where corner cases with float types, such as getting Infinity or NaN as argument, could produce different outputs.

Body:
Comparable problem with intregrals (int) :

#include<cmath>

int fabsprod1(int a, int b) {
    return std::abs(a*b);
}
int fabsprod2(int a, int b) {
    return std::abs(a) * std::abs(b);
}
int fabsprod3(int a, int b) {
    return std::abs(std::abs(a) * std::abs(b));
}

Results in (using your options -O3 -std=c++2a -march=cannonlake):

fabsprod1(int, int):
        mov     eax, edi
        imul    eax, esi
        cdq
        xor     eax, edx
        sub     eax, edx
        ret
fabsprod2(int, int):
        mov     eax, edi
        cdq
        xor     eax, edx
        sub     eax, edx
        mov     edx, esi
        sar     edx, 31
        xor     esi, edx
        sub     esi, edx
        imul    eax, esi
        ret
fabsprod3(int, int):
        mov     eax, edi
        cdq
        xor     eax, edx
        sub     eax, edx
        mov     edx, esi
        sar     edx, 31
        xor     esi, edx
        sub     esi, edx
        imul    eax, esi
        ret

https://godbolt.org/z/tf3nZN

This contradicts your statement about "real/floating point" numbers.

Overall you shouldn't expect the compiler to shortcut math problems for you. That being said some optimizations is made possible. Please provide documentation or a comparable example where you see the optimaztion.


问:
How to Create MDI Child of different type with Generics?
I need to centralize the MDI Child Forms creation into a unique procedure in Delphi (VCL). The idea is to do some actions every time an MDI Child Form is created no matter its type, i.e., to add its caption name into a List to get access to that MDI child form. Like this:

```<code>   procedure TMainForm<T>.CreateMDIChild(const ACaption : String);
    var
      Child: T;
    begin
      { create a new MDI child window }
      Child := T.Create(Application);
      Child.Caption := ACaption;
      // add this child to the list of active MDI windows
      ...
    end;

   procedure TMainForm.Button1Click(Sender : TObject);
   begin
       CreateMDIChild<TMdiChild1>('Child type 1');
       CreateMDIChild<TMdiChild2>('Child type 2');
       ...
</code>```

But, I don't have experience with generics. Any help I'll appreciate it.
Thank you so much.

答:
You can define a class for generic creation of form (using generics) with a class constraint like this:

```<code>TGenericMDIForm <T:TForm> = class
  class procedure CreateMDIChild(const Name: string);
end;
</code>```

And with this implementation:

```<code>class procedure TGenericMDIForm<T>.CreateMDIChild(const Name: string);
var
  Child:TCustomForm;
begin
  Child := T.Create(Application);
  Child.Caption := Name + ' of ' + T.ClassName + ' class';
end;
</code>```

Now, you can use it for create MDIChil forms differents classes:

```<code>procedure TMainForm.Button1Click(Sender: TObject);
begin
   TGenericMDIForm<TMdiChild>.CreateMDIChild('Child type 1');
   TGenericMDIForm<TMdiChild2>.CreateMDIChild('Child type 2');
end;
</code>```

Using the class constraint with the generic TGenericMDIForm <T:TForm> = class, you can avoid someone try use something like this TGenericMDIForm<TMemo>.CreateMDIChild('Child type 1'); with a class that not is a TForm descendant.

Body:
I need to centralize the MDI Child Forms creation into a unique procedure in Delphi (VCL). The idea is to do some actions every time an MDI Child Form is created no matter its type, i.e., to add its caption name into a List to get access to that MDI child form. Like this:

   procedure TMainForm<T>.CreateMDIChild(const ACaption : String);
    var
      Child: T;
    begin
      { create a new MDI child window }
      Child := T.Create(Application);
      Child.Caption := ACaption;
      // add this child to the list of active MDI windows
      ...
    end;

   procedure TMainForm.Button1Click(Sender : TObject);
   begin
       CreateMDIChild<TMdiChild1>('Child type 1');
       CreateMDIChild<TMdiChild2>('Child type 2');
       ...

But, I don't have experience with generics. Any help I'll appreciate it.
Thank you so much.

Body:
You can define a class for generic creation of form (using generics) with a class constraint like this:

TGenericMDIForm <T:TForm> = class
  class procedure CreateMDIChild(const Name: string);
end;

And with this implementation:

class procedure TGenericMDIForm<T>.CreateMDIChild(const Name: string);
var
  Child:TCustomForm;
begin
  Child := T.Create(Application);
  Child.Caption := Name + ' of ' + T.ClassName + ' class';
end;

Now, you can use it for create MDIChil forms differents classes:

procedure TMainForm.Button1Click(Sender: TObject);
begin
   TGenericMDIForm<TMdiChild>.CreateMDIChild('Child type 1');
   TGenericMDIForm<TMdiChild2>.CreateMDIChild('Child type 2');
end;

Using the class constraint with the generic TGenericMDIForm <T:TForm> = class, you can avoid someone try use something like this TGenericMDIForm<TMemo>.CreateMDIChild('Child type 1'); with a class that not is a TForm descendant.


问:
Cache Http requests using only RxJS operators
I'm trying to achieve what is described here: https://www.prestonlamb.com/blog/rxjs-cache-and-refresh-in-angular

In other words, I want to cache an observable, during a given time (let's say 1minute). When a subscription is made after that given time, data should be retrieved again and cache again for 1 minute.

Example of the expected result:

```<code>T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => RETRIEVE data
T 01:15: Request (6) => data from cache
T 01:30: Request (7) => data from cache
T 02:30: Request (8) => RETRIEVE data
</code>```

The shareReplay operator is working fine to cache data for a given time, but I'm not able to re-launch it when that given time is elapsed.

Example using shareRelay(1, 1000) operator:

```<code>T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => no response
T 01:15: Request (6) => no response
T 01:30: Request (7) => no response
T 02:30: Request (8) => no response
</code>```

The link above try to change that behavior using first operator catching null results. Unfortunately, it's not working fine as data is not cached after the first time.

Here's what I've got using the article of the above link (following picture is describing the code used)

Result I've got:

```<code>T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => RETRIEVE data
T 01:15: Request (6) => RETRIEVE data
T 01:30: Request (7) => RETRIEVE data
T 02:30: Request (8) => RETRIEVE data
</code>```

I've also seen some example with the timer operator, but in that cases, data is retrieved every minute, even if there is no subscribtion on it. I do not want to refresh data every minute, I want to expire cache every minute. Unfortunately, I've lost the code with the timer operator, but the result was something like that:

Result with timer operator:

```<code>T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:00: NO REQUEST => RETRIEVE data
T 01:10: Request (5) => data from cache
T 01:15: Request (6) => data from cache
T 01:30: Request (7) => data from cache
T 02:00: NO REQUEST => RETRIEVE data
T 02:30: Request (8) => data from cache
</code>```

Anyone with a "pure" RxJS solution to do what I want?

答:
I would consider the following strategy.

First of all you create a function createCachedSource which returns an Observable with its cache implemented via shareReplay(1).

Then I would use this function to set a variable source$ which is the one that clients have to use to subscribe to get data.

Now the trick is to reset source$ at the desired interval, using again createCachedSource.

All these concepts in code look like this

```<code>// this function created an Observable cached via shareReplay(1)
const createCachedSource = () =>
  of(1).pipe(
    tap((d) => console.log(`Go out and fetch ${d}`)),
    shareReplay(1),
    tap((d) => console.log(`Return cached data ${d}`))
  );

// source$ is the Observable the clients must subscribe to
let source$ = createCachedSource();

// every 1 sec reset the cache by creating a new Observable and setting it as value of source$
interval(1000)
  .pipe(
    take(10),
    tap(() => (source$ = createCachedSource()))
  )
  .subscribe();

// here we simulate 30 subscriptions to source$, one every 300 mS
interval(300)
  .pipe(
    take(30),
    switchMap(() => source$)
  )
  .subscribe();
</code>```

Body:
I'm trying to achieve what is described here: https://www.prestonlamb.com/blog/rxjs-cache-and-refresh-in-angular

In other words, I want to cache an observable, during a given time (let's say 1minute). When a subscription is made after that given time, data should be retrieved again and cache again for 1 minute.

Example of the expected result:

T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => RETRIEVE data
T 01:15: Request (6) => data from cache
T 01:30: Request (7) => data from cache
T 02:30: Request (8) => RETRIEVE data

The shareReplay operator is working fine to cache data for a given time, but I'm not able to re-launch it when that given time is elapsed.

Example using shareRelay(1, 1000) operator:

T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => no response
T 01:15: Request (6) => no response
T 01:30: Request (7) => no response
T 02:30: Request (8) => no response

The link above try to change that behavior using first operator catching null results. Unfortunately, it's not working fine as data is not cached after the first time.

Here's what I've got using the article of the above link (following picture is describing the code used)

Result I've got:

T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => RETRIEVE data
T 01:15: Request (6) => RETRIEVE data
T 01:30: Request (7) => RETRIEVE data
T 02:30: Request (8) => RETRIEVE data

I've also seen some example with the timer operator, but in that cases, data is retrieved every minute, even if there is no subscribtion on it. I do not want to refresh data every minute, I want to expire cache every minute. Unfortunately, I've lost the code with the timer operator, but the result was something like that:

Result with timer operator:

T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:00: NO REQUEST => RETRIEVE data
T 01:10: Request (5) => data from cache
T 01:15: Request (6) => data from cache
T 01:30: Request (7) => data from cache
T 02:00: NO REQUEST => RETRIEVE data
T 02:30: Request (8) => data from cache

Anyone with a "pure" RxJS solution to do what I want?

Body:
I would consider the following strategy.

First of all you create a function createCachedSource which returns an Observable with its cache implemented via shareReplay(1).

Then I would use this function to set a variable source$ which is the one that clients have to use to subscribe to get data.

Now the trick is to reset source$ at the desired interval, using again createCachedSource.

All these concepts in code look like this

// this function created an Observable cached via shareReplay(1)
const createCachedSource = () =>
  of(1).pipe(
    tap((d) => console.log(`Go out and fetch ${d}`)),
    shareReplay(1),
    tap((d) => console.log(`Return cached data ${d}`))
  );

// source$ is the Observable the clients must subscribe to
let source$ = createCachedSource();

// every 1 sec reset the cache by creating a new Observable and setting it as value of source$
interval(1000)
  .pipe(
    take(10),
    tap(() => (source$ = createCachedSource()))
  )
  .subscribe();

// here we simulate 30 subscriptions to source$, one every 300 mS
interval(300)
  .pipe(
    take(30),
    switchMap(() => source$)
  )
  .subscribe();


问:
using jquery - 2 different links that open the same window but display the appropriate content?
I'm trying to work out how this can be achieved using jQuery, I have page 1 which has 2 links namely link 1 and link 2, what I want to achieve is when I click link 1 a new browser window is opened displaying the content for link 1 and when I click link 2 the same window is displayed but with the content for link 2.

Is this a matter of creating a page and hiding both sets of content then displaying the content when the appropriate link is clicked?

Has anyone any tutorials that are similar to this?

答:
The Javascript window object has a open(href, name, properties) function, and browsers will only open one window of a given name. Simply open the pages that link 1 and link 2 refer to in a new window with the same name, and you'll get the desired outcome.

So, as an example:

```<code><a href="#" onclick="window.open('page1.html', 'my_window', 'height=100,width=100');return false;">Link 1</a>
<a href="#" onclick="window.open('page2.html', 'my_window', 'height=100,width=100');return false;">Link 2</a>
</code>```

Body:
The Javascript window object has a open(href, name, properties) function, and browsers will only open one window of a given name. Simply open the pages that link 1 and link 2 refer to in a new window with the same name, and you'll get the desired outcome.

So, as an example:

<a href="#" onclick="window.open('page1.html', 'my_window', 'height=100,width=100');return false;">Link 1</a>
<a href="#" onclick="window.open('page2.html', 'my_window', 'height=100,width=100');return false;">Link 2</a>


问:
Java Class Path error in SAS
I am trying to call a java class object from a data step in SAS. The Java class file has been placed in the class path./dir/folder_location

The class path variable for SAS has been changed to the folder where the class files are stored. This has been verified from the SAS enterprise Guide where I am printing the class path to the logs

SYSGET("CLASSPATH") returns /dir/folder_location

When I run the following path to declare a java object in the class:

```<code>   data _null_;
   declare javaobj j ('Classname');
   run;
</code>```

This gives me an error that

ERROR: Could not find class 'ClassName' at line x column y. Please ensure that the CLASSPATH is correct.
ERROR: DATA STEP Component Object failure. Aborted during the EXECUTION phase.

Als when i get the java info by using the command

```<code>PROC javainfo CLASSPATHS;
run;
</code>```

This returns a different path. Is this different than the above class path?

Does anyone have thoughts on as to why this is happening and what the solution is?

Thanks in advance.

答:
SAS documentation is as crap as usual in this subject (either).
In client/server application the spawner omits the user's enviroment variables on the server.
Fortunately I found a very simple solution.
Try this:
options set=CLASSPATH "your classpaths here";</p>

Title: Java Class Path error in SAS

Body:
I am trying to call a java class object from a data step in SAS. The Java class file has been placed in the class path./dir/folder_location

The class path variable for SAS has been changed to the folder where the class files are stored. This has been verified from the SAS enterprise Guide where I am printing the class path to the logs

SYSGET("CLASSPATH") returns /dir/folder_location

When I run the following path to declare a java object in the class:

   data _null_;
   declare javaobj j ('Classname');
   run;

This gives me an error that

ERROR: Could not find class 'ClassName' at line x column y. Please ensure that the CLASSPATH is correct.
ERROR: DATA STEP Component Object failure. Aborted during the EXECUTION phase.

Als when i get the java info by using the command

PROC javainfo CLASSPATHS;
run;

This returns a different path. Is this different than the above class path?

Does anyone have thoughts on as to why this is happening and what the solution is?

Thanks in advance.


问:
Get device id in windows with c#
I have a problem getting the id of the Windows device. He returns it to me empty. I don't know why that inconvenience.
My code:

```<code>productIdEdit.Text = RegHelper.readStringValue(RegistryValues.productIdKey(), RegistryValues.productIdValue());
</code>```

With this line I call two classes with the values I need to search for.
RegHelper:

```<code>public static string readStringValue(string regKey, string regValue)
{
string result;
try
{
   result = (string)Registry.GetValue(regKey, regValue, "");
}
catch (Exception)
{
    result = "";
}
return result;
}
</code>```

RegistryValues:

```<code>public static string productIdKey()
{
    return "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
}

public static string productIdValue()
{
    return "ProductId";
}
</code>```

The program runs in administrator mode.

答:
Please try this:

```<code>        using Microsoft.Win32;

        public static string getDeviceId()
        {

        string ret = string.Empty;
        RegistryKey regKey = null;

        try
        {
            var regDefault = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false);
            ret = regDefault.GetValue("ProductId").ToString();

        }
        catch (Exception ex)
        {
            ret = string.Format("Your error message");
        }
        finally
        {
            if (regKey != null)
                regKey.Close();
        }

        return ret;

    }
</code>```

Hope it helps :).

Title: Get device id in windows with c#

Body:
I have a problem getting the id of the Windows device. He returns it to me empty. I don't know why that inconvenience.
My code:

productIdEdit.Text = RegHelper.readStringValue(RegistryValues.productIdKey(), RegistryValues.productIdValue());

With this line I call two classes with the values I need to search for.
RegHelper:

public static string readStringValue(string regKey, string regValue)
{
string result;
try
{
   result = (string)Registry.GetValue(regKey, regValue, "");
}
catch (Exception)
{
    result = "";
}
return result;
}

RegistryValues:

public static string productIdKey()
{
    return "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
}

public static string productIdValue()
{
    return "ProductId";
}

The program runs in administrator mode.

Body:
Please try this:

        using Microsoft.Win32;

        public static string getDeviceId()
        {

        string ret = string.Empty;
        RegistryKey regKey = null;

        try
        {
            var regDefault = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false);
            ret = regDefault.GetValue("ProductId").ToString();

        }
        catch (Exception ex)
        {
            ret = string.Format("Your error message");
        }
        finally
        {
            if (regKey != null)
                regKey.Close();
        }

        return ret;

    }

Hope it helps :).


问:
Matlab or Octave plot auto-generated dates on x axis
I have a few hundred integer measurements. They are taken daily. I know the first measurement was taken on the 3/3/2019. I do not have any date explicitly related to each measurement.   I would like to plot these values on the y axis and the consecutive dates on the x axis.  I would also like to plot a subset of these measurements.For example, from 6/6/2019 until 11/11/2019, preferably by supplying only the initial start date and the two subset dates.</p>

答:
You can create a vector of date times and use it as the x-axis. Check out the Date and Time Arithmetic in MATLAB.

To create the time-vector, just add a duration (in hours) to your initial date

```<code>% number of samples/data/dates
NumSmpl = 100;
DateVec = datetime(2019,3,3,12,0,0) + duration((1:NumSmpl)*24,0,0).'; % I prefer to have vectors rather than arrays, which is why I transpose it here
</code>```

Now plot your data

```<code>% assuming this is your signal
Sig = 1:NumSmpl;

subplot(2,2,1:2) % activate first row
plot(DateVec,Sig)

subplot(2,2,3) % bottom left
plot(DateVec,Sig)
% set axes limits
xlim([DateVec(3),DateVec(10)])

subplot(2,2,4) % bottom right
% plot only a fraction of the data
lg = DateVec > datetime(2019,3,6) & DateVec < datetime(2019,3,13);
plot(DateVec(lg),Sig(lg))
</code>```

I used two different ways of showing a portion of the plot. One by using xlim and the other by using logical indexing.

Body:
You can create a vector of date times and use it as the x-axis. Check out the Date and Time Arithmetic in MATLAB.

To create the time-vector, just add a duration (in hours) to your initial date

% number of samples/data/dates
NumSmpl = 100;
DateVec = datetime(2019,3,3,12,0,0) + duration((1:NumSmpl)*24,0,0).'; % I prefer to have vectors rather than arrays, which is why I transpose it here

Now plot your data

% assuming this is your signal
Sig = 1:NumSmpl;

subplot(2,2,1:2) % activate first row
plot(DateVec,Sig)

subplot(2,2,3) % bottom left
plot(DateVec,Sig)
% set axes limits
xlim([DateVec(3),DateVec(10)])

subplot(2,2,4) % bottom right
% plot only a fraction of the data
lg = DateVec > datetime(2019,3,6) & DateVec < datetime(2019,3,13);
plot(DateVec(lg),Sig(lg))

I used two different ways of showing a portion of the plot. One by using xlim and the other by using logical indexing.


问:
simultaneous page load and ajax call
I have a web application with some pages take quite a long time to load because of what they have to do in code behind. I would like to show what is going on to the user by showing the different status of the process.

I was thinking about calling recursively (by ajax) a page which ready a value in the session. This value is set by the page that take time to load.
The problem is that the page called by ajax is not executed while the other page load is finished.
Is there some way to do that?

Thanks advance

答: The usual pattern here is to load an initial status page that triggers an AJAX call to retrieve the final version of the page, overwriting the original with the result of your AJAX call when it completes.</p>

Title: simultaneous page load and ajax call


问:
Runtimes supported by containerd apart from runC?
Does containerd support any other runtimes apart from runC?

Further, the containerd site says, "An industry-standard container runtime with an emphasis on simplicity, robustness and portability". Does this refer to any specific standard like the OCI or CRI.

答:
From: github.com/containerd/containerd

Runtime Requirements

Runtime requirements for containerd are very minimal. Most interactions with the Linux and Windows container feature sets are handled via runc and/or OS-specific libraries (e.g. hcsshim for Microsoft).

From: github.com/Microsoft/hcsshim

hcsshim

This package contains the Golang interface for using the Windows Host Compute Service (HCS) to launch and manage Windows Containers. It also contains other helpers and functions for managing Windows Containers such as the Golang interface for the Host Network Service (HNS).

Regarding the OCI part of your question:

OCI Runtime Specification

containerd fully supports the OCI runtime specification for running containers. We have built in functions to help you generate runtime specifications based on images as well as custom parameters.

You can specify options when creating a container about how to modify the specification.

```<code>redis, err := client.NewContainer(context, "redis-master", containerd.WithNewSpec(oci.WithImageConfig(image)))
</code>```

Body:
From: github.com/containerd/containerd

Runtime Requirements

Runtime requirements for containerd are very minimal. Most interactions with the Linux and Windows container feature sets are handled via runc and/or OS-specific libraries (e.g. hcsshim for Microsoft).

From: github.com/Microsoft/hcsshim

hcsshim

This package contains the Golang interface for using the Windows Host Compute Service (HCS) to launch and manage Windows Containers. It also contains other helpers and functions for managing Windows Containers such as the Golang interface for the Host Network Service (HNS).

Regarding the OCI part of your question:

OCI Runtime Specification

containerd fully supports the OCI runtime specification for running containers. We have built in functions to help you generate runtime specifications based on images as well as custom parameters.

You can specify options when creating a container about how to modify the specification.

redis, err := client.NewContainer(context, "redis-master", containerd.WithNewSpec(oci.WithImageConfig(image)))


问:
Why sticky navbar's content doesn't fit in it?
I have two styles for my navbar (.navbar and .navbar_fixed). And links in the navbar don't fit in it properly. I tried to remove padding and add left: 0; but it doesn't work. How can I fix that?

$(document).ready(function() {

    $(window).scroll(function () {
        if ($(window).scrollTop() > 280) {
            $('.navbar').addClass('navbar_fixed');
            $('.navbar_fixed').removeClass('navbar');
        }

        if ($(window).scrollTop() < 281) {
            $('.navbar_fixed').addClass('navbar');
            $('.navbar').removeClass('navbar_fixed');
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
 margin: 0;
 padding: 0;
}

body {
 font-family: 'Montserrat', sans-serif;
}

.global-padding {
 padding-right: 98px;
 padding-left: 98px;
}

.clearfix:after {
 display: table;
 clear: both;

 content: '';
}

.container {
 width: 100%;
 max-width: 1366px;
}

.navbar {
 padding-top: 63px;
}

.navbar_fixed {
 position: fixed;
 z-index: 100;
 top: 0;
 left: 0;

 width: 100%;
 height: 32px;
 padding: 23px 98px 0 98px;

 background-color: #ffffff;
 box-shadow: 0 0 7px 1px rgba(0, 0, 0, 0.25);
}

.navbar__menu {
 float: right;

 list-style: none;
}

.navbar__link-item {
 float: left;
}

.navbar__link {
 font-size: 14px;
 font-weight: 300;

 padding: 10px 13px;

 text-decoration: none;
 text-transform: uppercase;

 color: #8c8c8c;
}

.navbar__link:hover {
 color: #212121;
}

.navbar__link_active {
 font-weight: 700;

 letter-spacing: 1.4px;

 color: #212121;
 border-bottom: 3px solid #212121;
}</code>```

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;300;400;700&display=swap" rel="stylesheet">

HOME

PRODUCTS

HISTORY

SHOWROOM

CONTACT

            Lorem ipsum dolor sit amet consectetur adipisicing elit. Vero, ad tempore eaque autem at veritatis, modi a tenetur eius rem fugiat sunt esse! Placeat tempore quae quia eius alias! Ea officia modi cum sint pariatur architecto vero corrupti autem ex ratione asperiores commodi dolore fugiat, enim blanditiis quas accusamus sunt aperiam praesentium, accusantium excepturi? Ea, labore? Explicabo neque atque eveniet totam aperiam repellendus minima quia amet exercitationem laborum, quo tempore facilis dolores magni tenetur. Fuga nobis sit neque alias eos minima. Maiores quisquam soluta iure corrupti minima, ut enim error, ab nihil consectetur cupiditate, quod magni consequatur adipisci repudiandae architecto culpa suscipit! A minus omnis molestiae aut. Nam fugiat at, est voluptatem minus sint dolor commodi odio aperiam necessitatibus voluptatum ipsam nesciunt explicabo consequuntur nostrum hic, vitae eius blanditiis. Rem exercitationem, iure eligendi ullam accusamus, tempore impedit dignissimos perferendis quam iusto nulla molestias eos aliquam. Dolorum nisi atque nam! Iste vitae perferendis magni quos omnis impedit alias tenetur sed dolorem cupiditate totam sit nobis debitis blanditiis, cum ipsa, in earum ipsam. Asperiores atque molestiae fuga, quos tenetur repellat exercitationem magnam, voluptatibus aperiam dolore quisquam doloremque ratione perspiciatis autem in porro accusamus error accusantium iusto? Excepturi, pariatur repudiandae natus sed in totam voluptatibus laboriosam sint rerum nobis iusto quibusdam, perspiciatis alias ducimus quae dolorem eius, labore non ipsa quas. Tempore quis, beatae consequuntur explicabo asperiores eaque nisi ratione amet aliquid nesciunt atque? Enim laboriosam minima vero mollitia, quaerat porro facere laborum culpa molestiae perferendis? Quibusdam aut itaque, explicabo molestiae reprehenderit minima, et, soluta repellendus ipsam odio rem. Neque, dicta at voluptatum excepturi officiis vitae? Quidem debitis id sit amet recusandae facere rerum optio exercitationem necessitatibus cupiditate, illum magni ex reprehenderit fugiat culpa numquam maiores iste laudantium quasi ab neque! Quaerat consequuntur ipsa saepe quas perferendis consequatur neque rem pariatur corporis quia, enim eos dolorem reiciendis incidunt, ad architecto labore dignissimos adipisci sit in omnis cupiditate fuga? Blanditiis, maxime veniam quae ipsum labore ipsa quo necessitatibus, nostrum, magni omnis quidem voluptatum? Facilis vel reiciendis veniam consequatur dolorum minus! Blanditiis perferendis eveniet facilis. Assumenda corrupti libero eaque laborum labore expedita ab aperiam, neque fugiat id nesciunt dolore cupiditate reprehenderit, dignissimos distinctio ipsam. Minus sit, explicabo quae quos aliquam doloremque expedita consequuntur repellendus vel dicta? Dolorem aliquid placeat distinctio aperiam a aspernatur, ipsam quam minus doloribus, ad exercitationem quae? Ea iusto minus numquam fugiat inventore aspernatur perferendis temporibus pariatur nostrum cum eligendi, ab ratione modi similique quae rerum quasi tenetur dolor iure ut nemo molestias eveniet. Architecto soluta consequuntur optio quod, quos qui accusantium sit deserunt. Deleniti rerum explicabo sed. Voluptatibus, enim sit voluptas itaque quidem reiciendis asperiores quasi ipsum cumque consequuntur totam culpa suscipit natus repudiandae doloribus quas exercitationem veritatis sequi neque possimus qui voluptatum, nulla consectetur vel. Soluta reprehenderit perspiciatis debitis laboriosam, porro, possimus quis dolorem velit aperiam a aliquid blanditiis enim culpa dicta harum. Laborum reprehenderit enim est, eius laudantium quas ad molestias, quaerat debitis ullam quidem. Ut pariatur necessitatibus itaque at excepturi? Ratione, officiis amet repellat delectus recusandae eligendi quasi quidem esse similique quod at eum, placeat iure dignissimos magni modi debitis, nulla iusto facilis obcaecati ut. Sunt, delectus cumque aperiam exercitationem aut similique illum consectetur nostrum iusto iure aliquid impedit aspernatur dolore commodi. Asperiores saepe tempora architecto. Delectus dolorem distinctio obcaecati rerum eos eum fugiat ducimus, dignissimos, aperiam cupiditate non vel rem facere culpa eius doloribus laborum unde quod quos quae porro dolore natus. Et sed alias consectetur? Illo voluptatem possimus asperiores excepturi sed culpa dolore vitae est, esse laboriosam qui! Corporis, cupiditate ad tempore illo esse deleniti assumenda dignissimos mollitia eum odit dolores nostrum a odio maiores aperiam? Quisquam debitis perspiciatis expedita veritatis earum nemo modi eaque dolores nulla sapiente aperiam, assumenda magni quaerat iure nostrum cumque, repudiandae deleniti voluptatibus laborum! Perspiciatis quisquam aliquid nulla debitis doloremque, mollitia cumque ad totam quae suscipit, dolorum ratione perferendis consectetur magnam maxime facilis molestias quo impedit at asperiores, blanditiis et necessitatibus iure itaque. Ratione minus vero corporis mollitia velit ipsa quibusdam provident modi fugit suscipit, dolorem tempore? Recusandae ullam sit aspernatur sequi unde quas enim animi repellat perferendis rem nam praesentium, aperiam dicta eos temporibus quae! Laudantium placeat quibusdam consequuntur incidunt dolorem quia quos nulla sed aliquid accusantium quaerat consectetur obcaecati fugiat earum, laboriosam, inventore aspernatur amet at assumenda. Est dolore beatae non neque, ipsa ullam, perspiciatis laudantium ratione reiciendis vitae nobis veniam deleniti aliquam sapiente distinctio, voluptate enim praesentium fugiat libero repellat omnis ipsum. Veniam deserunt, ea in placeat distinctio facilis adipisci recusandae tempora iusto nisi excepturi sunt quae reprehenderit, tenetur enim, necessitatibus omnis et quisquam voluptate quia ipsum incidunt. Nisi sit ex mollitia aperiam nesciunt doloribus laborum rerum, dolorum deleniti asperiores ducimus maiores ea enim similique quas sunt? Sit fugit quibusdam adipisci culpa dolorum perferendis doloribus quo, placeat laboriosam expedita voluptatem totam dignissimos aspernatur aut soluta laborum! Repudiandae consequatur deleniti deserunt tempora error eveniet doloribus obcaecati, mollitia veritatis labore minima eum nihil ratione voluptate sit magni, voluptas quo exercitationem quia natus dolor. Cumque vitae ullam tempore hic fugiat esse a consequuntur libero asperiores minima cum earum repellat, ab, enim aliquam commodi saepe dolore nihil similique itaque laboriosam iure praesentium obcaecati! Eius, sed. In ipsam doloremque illum vel, sequi cupiditate, blanditiis dolores nihil aliquam veritatis facilis a impedit fugit cum, dolorum deleniti suscipit non velit laudantium ipsa maiores inventore nostrum animi? Error iusto, officiis saepe laborum nam repellat dolore aperiam ab deserunt distinctio quis amet vero, numquam obcaecati impedit quidem tempora corporis doloremque accusamus. Unde eveniet dolor quia maiores dolorem dicta. Veritatis nemo quos cum expedita doloribus, dolor recusandae soluta error, accusamus dolorum quis illo laudantium voluptatem aut repellendus optio, libero numquam eligendi enim totam distinctio. Sequi autem expedita eligendi vitae et quia dolorum adipisci. Expedita dolor tenetur, ipsa repellendus harum tempora aliquid delectus beatae quis ex cum sit sapiente hic deleniti incidunt ipsam repellat vitae. Porro distinctio, voluptatum rerum eius et corrupti fuga sapiente quia suscipit temporibus, nihil velit similique voluptatibus harum molestiae. Nemo, omnis quis facere ab nulla fuga tempore doloribus officia vitae commodi dolor, placeat voluptate beatae?

```

答:
Try adding margin-right to your navbar_menu</p>

```<code>.navbar_fixed .navbar__menu {
    float: right;
    list-style: none;
    margin-right: 10%;
}
</code>```

Body:
I have two styles for my navbar (.navbar and .navbar_fixed). And links in the navbar don't fit in it properly. I tried to remove padding and add left: 0; but it doesn't work. How can I fix that?

$(document).ready(function() {

    $(window).scroll(function () {
        if ($(window).scrollTop() > 280) {
            $('.navbar').addClass('navbar_fixed');
            $('.navbar_fixed').removeClass('navbar');
        }

        if ($(window).scrollTop() < 281) {
            $('.navbar_fixed').addClass('navbar');
            $('.navbar').removeClass('navbar_fixed');
        }
    });
});

* {
 margin: 0;
 padding: 0;
}

body {
 font-family: 'Montserrat', sans-serif;
}

.global-padding {
 padding-right: 98px;
 padding-left: 98px;
}

.clearfix:after {
 display: table;
 clear: both;

 content: '';
}

.container {
 width: 100%;
 max-width: 1366px;
}

.navbar {
 padding-top: 63px;
}

.navbar_fixed {
 position: fixed;
 z-index: 100;
 top: 0;
 left: 0;

 width: 100%;
 height: 32px;
 padding: 23px 98px 0 98px;

 background-color: #ffffff;
 box-shadow: 0 0 7px 1px rgba(0, 0, 0, 0.25);
}

.navbar__menu {
 float: right;

 list-style: none;
}

.navbar__link-item {
 float: left;
}

.navbar__link {
 font-size: 14px;
 font-weight: 300;

 padding: 10px 13px;

 text-decoration: none;
 text-transform: uppercase;

 color: #8c8c8c;
}

.navbar__link:hover {
 color: #212121;
}

.navbar__link_active {
 font-weight: 700;

 letter-spacing: 1.4px;

 color: #212121;
 border-bottom: 3px solid #212121;
}

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;300;400;700&display=swap" rel="stylesheet">

HOME

PRODUCTS

HISTORY

SHOWROOM

CONTACT

            Lorem ipsum dolor sit amet consectetur adipisicing elit. Vero, ad tempore eaque autem at veritatis, modi a tenetur eius rem fugiat sunt esse! Placeat tempore quae quia eius alias! Ea officia modi cum sint pariatur architecto vero corrupti autem ex ratione asperiores commodi dolore fugiat, enim blanditiis quas accusamus sunt aperiam praesentium, accusantium excepturi? Ea, labore? Explicabo neque atque eveniet totam aperiam repellendus minima quia amet exercitationem laborum, quo tempore facilis dolores magni tenetur. Fuga nobis sit neque alias eos minima. Maiores quisquam soluta iure corrupti minima, ut enim error, ab nihil consectetur cupiditate, quod magni consequatur adipisci repudiandae architecto culpa suscipit! A minus omnis molestiae aut. Nam fugiat at, est voluptatem minus sint dolor commodi odio aperiam necessitatibus voluptatum ipsam nesciunt explicabo consequuntur nostrum hic, vitae eius blanditiis. Rem exercitationem, iure eligendi ullam accusamus, tempore impedit dignissimos perferendis quam iusto nulla molestias eos aliquam. Dolorum nisi atque nam! Iste vitae perferendis magni quos omnis impedit alias tenetur sed dolorem cupiditate totam sit nobis debitis blanditiis, cum ipsa, in earum ipsam. Asperiores atque molestiae fuga, quos tenetur repellat exercitationem magnam, voluptatibus aperiam dolore quisquam doloremque ratione perspiciatis autem in porro accusamus error accusantium iusto? Excepturi, pariatur repudiandae natus sed in totam voluptatibus laboriosam sint rerum nobis iusto quibusdam, perspiciatis alias ducimus quae dolorem eius, labore non ipsa quas. Tempore quis, beatae consequuntur explicabo asperiores eaque nisi ratione amet aliquid nesciunt atque? Enim laboriosam minima vero mollitia, quaerat porro facere laborum culpa molestiae perferendis? Quibusdam aut itaque, explicabo molestiae reprehenderit minima, et, soluta repellendus ipsam odio rem. Neque, dicta at voluptatum excepturi officiis vitae? Quidem debitis id sit amet recusandae facere rerum optio exercitationem necessitatibus cupiditate, illum magni ex reprehenderit fugiat culpa numquam maiores iste laudantium quasi ab neque! Quaerat consequuntur ipsa saepe quas perferendis consequatur neque rem pariatur corporis quia, enim eos dolorem reiciendis incidunt, ad architecto labore dignissimos adipisci sit in omnis cupiditate fuga? Blanditiis, maxime veniam quae ipsum labore ipsa quo necessitatibus, nostrum, magni omnis quidem voluptatum? Facilis vel reiciendis veniam consequatur dolorum minus! Blanditiis perferendis eveniet facilis. Assumenda corrupti libero eaque laborum labore expedita ab aperiam, neque fugiat id nesciunt dolore cupiditate reprehenderit, dignissimos distinctio ipsam. Minus sit, explicabo quae quos aliquam doloremque expedita consequuntur repellendus vel dicta? Dolorem aliquid placeat distinctio aperiam a aspernatur, ipsam quam minus doloribus, ad exercitationem quae? Ea iusto minus numquam fugiat inventore aspernatur perferendis temporibus pariatur nostrum cum eligendi, ab ratione modi similique quae rerum quasi tenetur dolor iure ut nemo molestias eveniet. Architecto soluta consequuntur optio quod, quos qui accusantium sit deserunt. Deleniti rerum explicabo sed. Voluptatibus, enim sit voluptas itaque quidem reiciendis asperiores quasi ipsum cumque consequuntur totam culpa suscipit natus repudiandae doloribus quas exercitationem veritatis sequi neque possimus qui voluptatum, nulla consectetur vel. Soluta reprehenderit perspiciatis debitis laboriosam, porro, possimus quis dolorem velit aperiam a aliquid blanditiis enim culpa dicta harum. Laborum reprehenderit enim est, eius laudantium quas ad molestias, quaerat debitis ullam quidem. Ut pariatur necessitatibus itaque at excepturi? Ratione, officiis amet repellat delectus recusandae eligendi quasi quidem esse similique quod at eum, placeat iure dignissimos magni modi debitis, nulla iusto facilis obcaecati ut. Sunt, delectus cumque aperiam exercitationem aut similique illum consectetur nostrum iusto iure aliquid impedit aspernatur dolore commodi. Asperiores saepe tempora architecto. Delectus dolorem distinctio obcaecati rerum eos eum fugiat ducimus, dignissimos, aperiam cupiditate non vel rem facere culpa eius doloribus laborum unde quod quos quae porro dolore natus. Et sed alias consectetur? Illo voluptatem possimus asperiores excepturi sed culpa dolore vitae est, esse laboriosam qui! Corporis, cupiditate ad tempore illo esse deleniti assumenda dignissimos mollitia eum odit dolores nostrum a odio maiores aperiam? Quisquam debitis perspiciatis expedita veritatis earum nemo modi eaque dolores nulla sapiente aperiam, assumenda magni quaerat iure nostrum cumque, repudiandae deleniti voluptatibus laborum! Perspiciatis quisquam aliquid nulla debitis doloremque, mollitia cumque ad totam quae suscipit, dolorum ratione perferendis consectetur magnam maxime facilis molestias quo impedit at asperiores, blanditiis et necessitatibus iure itaque. Ratione minus vero corporis mollitia velit ipsa quibusdam provident modi fugit suscipit, dolorem tempore? Recusandae ullam sit aspernatur sequi unde quas enim animi repellat perferendis rem nam praesentium, aperiam dicta eos temporibus quae! Laudantium placeat quibusdam consequuntur incidunt dolorem quia quos nulla sed aliquid accusantium quaerat consectetur obcaecati fugiat earum, laboriosam, inventore aspernatur amet at assumenda. Est dolore beatae non neque, ipsa ullam, perspiciatis laudantium ratione reiciendis vitae nobis veniam deleniti aliquam sapiente distinctio, voluptate enim praesentium fugiat libero repellat omnis ipsum. Veniam deserunt, ea in placeat distinctio facilis adipisci recusandae tempora iusto nisi excepturi sunt quae reprehenderit, tenetur enim, necessitatibus omnis et quisquam voluptate quia ipsum incidunt. Nisi sit ex mollitia aperiam nesciunt doloribus laborum rerum, dolorum deleniti asperiores ducimus maiores ea enim similique quas sunt? Sit fugit quibusdam adipisci culpa dolorum perferendis doloribus quo, placeat laboriosam expedita voluptatem totam dignissimos aspernatur aut soluta laborum! Repudiandae consequatur deleniti deserunt tempora error eveniet doloribus obcaecati, mollitia veritatis labore minima eum nihil ratione voluptate sit magni, voluptas quo exercitationem quia natus dolor. Cumque vitae ullam tempore hic fugiat esse a consequuntur libero asperiores minima cum earum repellat, ab, enim aliquam commodi saepe dolore nihil similique itaque laboriosam iure praesentium obcaecati! Eius, sed. In ipsam doloremque illum vel, sequi cupiditate, blanditiis dolores nihil aliquam veritatis facilis a impedit fugit cum, dolorum deleniti suscipit non velit laudantium ipsa maiores inventore nostrum animi? Error iusto, officiis saepe laborum nam repellat dolore aperiam ab deserunt distinctio quis amet vero, numquam obcaecati impedit quidem tempora corporis doloremque accusamus. Unde eveniet dolor quia maiores dolorem dicta. Veritatis nemo quos cum expedita doloribus, dolor recusandae soluta error, accusamus dolorum quis illo laudantium voluptatem aut repellendus optio, libero numquam eligendi enim totam distinctio. Sequi autem expedita eligendi vitae et quia dolorum adipisci. Expedita dolor tenetur, ipsa repellendus harum tempora aliquid delectus beatae quis ex cum sit sapiente hic deleniti incidunt ipsam repellat vitae. Porro distinctio, voluptatum rerum eius et corrupti fuga sapiente quia suscipit temporibus, nihil velit similique voluptatibus harum molestiae. Nemo, omnis quis facere ab nulla fuga tempore doloribus officia vitae commodi dolor, placeat voluptate beatae?

Body:
Try adding margin-right to your navbar_menu

.navbar_fixed .navbar__menu {
    float: right;
    list-style: none;
    margin-right: 10%;
}


问:
Task run by all ec2 instances
I have a python scripts that send mail to users, I want to run this scripts by all instances which is in running state at a particular interval of time(decided by task scheduler of instances).

I have not to use AWS Lambda.
Is there any way by which i can do it? Can i use AWS image?

答:
It appears that you wish to run a script on multiple Amazon EC2 instances at a particular time.

There are basically two ways to do this:

Using cron on each instance

Each Amazon EC2 instance can trigger its own script. On Linux, you would use cron. On Windows you would define a Schedule Task.

Running commands using AWS Systems Manager Run Command

If you wish to externally trigger a command on multiple Amazon EC2 instances, you can use the AWS Systems Manager Run Command. You will first define the commands to be run, and then nominate the instances on which to run the command. The Run Command will manage the process of running the script, gather the results, retry failures and report the results.

The benefit of using the Run Command is that you can centrally manage the process. It is very easy to edit the script and run it when desired. In contrast, if using cron you would need to update the script on every instance.

Title: Task run by all ec2 instances


问:
Can't get OpenLayers 3 map to display in Bootstrap modal
It looks like there is a weird bug when trying to display an ol3 map within a modal. The map is in the modal but it doesn't display. Resizing the window manually forces it display however. Here's a link to try and see what I mean. Click on the settings pulldown within each map. Click on 'Get Feature Info'. This will toggle the modal with a map in it (but not displaying). Resize your window. Voila!

I tried many ways to use javascript and jQuery to trigger a resize event along the lines of:

```<code>$('#featinfo').on('shown.bs.modal', function () {
ol.Map.event.trigger(map5, "resize"); //borrowed from google.maps.event. How to do this in ol3?
});
</code>```

Help?

答:
In an AngularJS application i had the same problem.

I resolved it by adding a little timout on $onInit()

```<code>constructor(private $log: ILogService, private $window: any, private $timeout: ITimeoutService) {
}

$onInit() {

    // we need a timout here to load map after the modal!
    this.$timeout(() => {
        this.initMyMap();
    });

}
</code>```

Body:
It looks like there is a weird bug when trying to display an ol3 map within a modal. The map is in the modal but it doesn't display. Resizing the window manually forces it display however. Here's a link to try and see what I mean. Click on the settings pulldown within each map. Click on 'Get Feature Info'. This will toggle the modal with a map in it (but not displaying). Resize your window. Voila!

I tried many ways to use javascript and jQuery to trigger a resize event along the lines of:

$('#featinfo').on('shown.bs.modal', function () {
ol.Map.event.trigger(map5, "resize"); //borrowed from google.maps.event. How to do this in ol3?
});

Help?

Body:
In an AngularJS application i had the same problem.

I resolved it by adding a little timout on $onInit()

constructor(private $log: ILogService, private $window: any, private $timeout: ITimeoutService) {
}

$onInit() {

    // we need a timout here to load map after the modal!
    this.$timeout(() => {
        this.initMyMap();
    });

}


问:
How to make FomrGroup readonly in Angular8 without the disabled() function?
A FormGroup is either filled directly from UrlQuery Parameters or by user input. When the UrlQuery Parameters are provided, the FormGroup should be readonly. I saw the disable() function, but this is not working for me because the values of the FormGroup are not submitted. Any suggestions?

答:
use add the readonly property to the input tag:

<input controlName="Example" readonly></input>

resource:
- https://www.w3schools.com/TAGS/att_input_readonly.asp


问:
Spring Boot Rest API Returns Empty JSON Used with Lombok
I have Spring Boot Application with Web, JPA, H2, Web, Lombok dependency.
I have entities as follows

```<code>@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Getter
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer pageCount;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

}
</code>```

```<code>@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Getter
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String firstName;

    @Column
    private String lastName;

}
</code>```

I am getting following JSON in repose for the /books REST endpoint

```<code>[
    {},
    {}
]
</code>```

If I add getters and setters to entity it works fine. How can I get the actual values in response without adding getters setters as I am using @Data annotation

答:
need to add Lombok plugin in maven or gradle file link How to configure Lombok with maven-compiler-plugin?.
If you are  using IDE then need to install Lombok plugin link https://www.baeldung.com/lombok-ide</p>

Body:
I have Spring Boot Application with Web, JPA, H2, Web, Lombok dependency.
I have entities as follows

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Getter
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer pageCount;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

}

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@Getter
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String firstName;

    @Column
    private String lastName;

}

I am getting following JSON in repose for the /books REST endpoint

[
    {},
    {}
]

If I add getters and setters to entity it works fine. How can I get the actual values in response without adding getters setters as I am using @Data annotation


问:
How to compile LuaJit MSVC with DLUAJIT_ENABLE_LUA52COMPAT x86?
I am able to successfully build/compile LuaJit in static mode by doing msvcbuild.bat static. Though at the bottom of LuaJit Extensions it says if I use DLUAJIT_ENABLE_LUA52COMPAT option while building I will be able to use Lua5.2 components. Yet I don't see anywhere in the msvcbuild.bat file where I could add this on. If anyone has any information it would be greatly appreciated.</p>

答:
The DLUAJIT_ENABLE_LUA52COMPAT option is in the src/Makefile.

If you want to build Luajit use DLUAJIT_ENABLE_LUA52COMPAT option, you should modify the Makefile and rebuild by make.


问:
Typescript paths not resolved
I've been trying to get path resolving working in my project, but I can't find a way to make it work.
My project is an electron project that uses electron webpack.

My folder structure looks like this:

I would like to register paths for @main and @render for ./src/main and ./src/renderer
My tsconfig.json looks like this at the moment:

```<code>{
  "compilerOptions": {
    "target": "es2017",
    "module": "esnext",
    "moduleResolution": "node",
    "noUnusedLocals": true,
    "noImplicitReturns": true,
    "inlineSources": true,
    "inlineSourceMap": true,
    "experimentalDecorators": true,
    "newLine": "lf",
    "noEmitOnError": true,
    "jsx": "react",
    "esModuleInterop": true,
    "lib": ["es2015", "es2016", "DOM"],
    "typeRoots" : ["./node_modules/@types"],
    "baseUrl": "./src",
    "paths": {
      "@main/*" : ["main/*"],
      "@render/*" : ["renderer/*"]
    },
   "allowSyntheticDefaultImports": true,
   "resolveJsonModule": true
  }
}
</code>```

Yet VS Code warns me, that it can't find the module. The line looks like this:

```<code>import { Api } from '@render/api'
</code>```

How can I solve this?

答: You need to restart the IDE and TS service. When you change the config TS has to be restarted to detect new changes. </p>

Title: Typescript paths not resolved

Body:
I've been trying to get path resolving working in my project, but I can't find a way to make it work.
My project is an electron project that uses electron webpack.

My folder structure looks like this:

I would like to register paths for @main and @render for ./src/main and ./src/renderer
My tsconfig.json looks like this at the moment:

{
  "compilerOptions": {
    "target": "es2017",
    "module": "esnext",
    "moduleResolution": "node",
    "noUnusedLocals": true,
    "noImplicitReturns": true,
    "inlineSources": true,
    "inlineSourceMap": true,
    "experimentalDecorators": true,
    "newLine": "lf",
    "noEmitOnError": true,
    "jsx": "react",
    "esModuleInterop": true,
    "lib": ["es2015", "es2016", "DOM"],
    "typeRoots" : ["./node_modules/@types"],
    "baseUrl": "./src",
    "paths": {
      "@main/*" : ["main/*"],
      "@render/*" : ["renderer/*"]
    },
   "allowSyntheticDefaultImports": true,
   "resolveJsonModule": true
  }
}

Yet VS Code warns me, that it can't find the module. The line looks like this:

import { Api } from '@render/api'

How can I solve this?


问:
Is this correct way dependency injection in Angular?
So I am new to Angular, I have been reading around the subject of dependency injection.

I added this function into my app but keep getting a eslint error :

You should use the function syntax for DI

I can not see anything wrong with what I have declared. Can anyone help?

```<code>angular.module('tools').config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
        $routeProvider.otherwise({ redirectTo : '/404' });
        $locationProvider.html5Mode(true)
    }
]);
</code>```

the exact message I get is
" 1:1  error  You should use the function syntax for DI  angular/di"

答:
Instead of disabling the linting, you could also actually move it to a function.

If you are using something like ngInject, you could do:

```<code>angular.module('tools').config(myRoutConfig);

/** @ngInject */
function myRoutConfig($routeProvider, $locationProvider) {
    $routeProvider.otherwise({ redirectTo : '/404' });
    $locationProvider.html5Mode(true)
}

</code>```

Hope this helps someone!

Body:
So I am new to Angular, I have been reading around the subject of dependency injection.

I added this function into my app but keep getting a eslint error :

You should use the function syntax for DI

I can not see anything wrong with what I have declared. Can anyone help?

angular.module('tools').config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
        $routeProvider.otherwise({ redirectTo : '/404' });
        $locationProvider.html5Mode(true)
    }
]);

the exact message I get is
" 1:1  error  You should use the function syntax for DI  angular/di"

Body:
Instead of disabling the linting, you could also actually move it to a function.

If you are using something like ngInject, you could do:

angular.module('tools').config(myRoutConfig);

/** @ngInject */
function myRoutConfig($routeProvider, $locationProvider) {
    $routeProvider.otherwise({ redirectTo : '/404' });
    $locationProvider.html5Mode(true)
}

Hope this helps someone!