问:
Binding behavior changes depending on the invocation (shiny vs. non shiny)
Invocation of the following code has a different binding behavior depending if it's running under shiny or not. I can't justify it in any way.

```<code># app.R
source("b.R")
print("foo after source")
print(foo)
x()
print("setting foo in app.R")
foo <- c(1,2)
x()
</code>```

```<code># b.R
foo <- c("XXX")

x <- function() {
  print("inside function")
  print(foo)
}
</code>```

Result if I invoke it with Rscript:

```<code>whatever$ Rscript app.R
[1] "foo after source"
[1] "XXX"
[1] "inside function"
[1] "XXX"
[1] "setting foo in app.R"
[1] "inside function"
[1] 1 2
</code>```

Result if I invoke it under shiny

```<code>> shiny::runApp('whatever')
Loading required package: shiny
[1] "foo after source"
[1] "XXX"
[1] "inside function"
[1] "XXX"
[1] "setting foo in app.R"
[1] "inside function"
[1] "XXX"
</code>```

It's as if it does early binding for the function closure only when running under shiny.

答:
What's happening here is that when you run shiny::runApp(), shiny creates it's own environment to run all the shiny code in. (I think related to this). But when you call source() directly, no separate environment is created and everything goes straight to the global environment. You can see this if you add print(environment()) to your app.R file. You'll see when you source("app.R") this returns <environment: R_GlobalEnv> but when you call shiny::runApp() you'll see a different environment name.

So when you call source() in app.R, again it's loading all the content into the local environment by default. This creates foo<-"XXX" in the global environment and the environment for x() is set to the global environment. This is true for both invocations. But when you kick it off with shiny::runApp, that's no operating in the global environment so when you do foo <- c(1,2) you are not updating the global environment, but just the local shiny environment. The global foo still exists and thanks to lexical scoping, the global value is the one x will find.

A quick fix would be to use

```<code>source("b.R", local=TRUE)
</code>```

in app.R. This will load the values from b.R into the local environment rather than the global environment. This will work under both circumstances since calling source() directly on "app.R" will already run in the global environment so it won't work any differently.

Body:
Invocation of the following code has a different binding behavior depending if it's running under shiny or not. I can't justify it in any way.

# app.R
source("b.R")
print("foo after source")
print(foo)
x()
print("setting foo in app.R")
foo <- c(1,2)
x()

# b.R
foo <- c("XXX")

x <- function() {
  print("inside function")
  print(foo)
}

Result if I invoke it with Rscript:

whatever$ Rscript app.R
[1] "foo after source"
[1] "XXX"
[1] "inside function"
[1] "XXX"
[1] "setting foo in app.R"
[1] "inside function"
[1] 1 2

Result if I invoke it under shiny

> shiny::runApp('whatever')
Loading required package: shiny
[1] "foo after source"
[1] "XXX"
[1] "inside function"
[1] "XXX"
[1] "setting foo in app.R"
[1] "inside function"
[1] "XXX"

It's as if it does early binding for the function closure only when running under shiny.

Body:
What's happening here is that when you run shiny::runApp(), shiny creates it's own environment to run all the shiny code in. (I think related to this). But when you call source() directly, no separate environment is created and everything goes straight to the global environment. You can see this if you add print(environment()) to your app.R file. You'll see when you source("app.R") this returns <environment: R_GlobalEnv> but when you call shiny::runApp() you'll see a different environment name.

So when you call source() in app.R, again it's loading all the content into the local environment by default. This creates foo<-"XXX" in the global environment and the environment for x() is set to the global environment. This is true for both invocations. But when you kick it off with shiny::runApp, that's no operating in the global environment so when you do foo <- c(1,2) you are not updating the global environment, but just the local shiny environment. The global foo still exists and thanks to lexical scoping, the global value is the one x will find.

A quick fix would be to use

source("b.R", local=TRUE)

in app.R. This will load the values from b.R into the local environment rather than the global environment. This will work under both circumstances since calling source() directly on "app.R" will already run in the global environment so it won't work any differently.


来源: stackexchange

问:
Gzip compression through webpack not happening , what's missing
I have noticed compression difference between manual webpack configuration and create-react-app for same application/code base,create-react-app configuration compression apparently is gzip because of which final bundle size is way less than manual configuration of webpack ,

So I also tried using CompressionPlugin but it seems not working as expected, what could be missing from webpack configuration

const common = require("./webpack.common");
const path = require("path");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const merge = require("webpack-merge");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CompressionPlugin = require('compression-webpack-plugin');
const globImporter = require('node-sass-glob-importer');

module.exports = merge(common, {
    mode: "production",
    output: {
        filename: "[name].[contenthash].js",
        path: path.resolve(__dirname, "dist")
    },
    module: {
        rules: [
            {
                test: /\.(sa|sc|c)ss$/,
                use: [
                    { loader: MiniCssExtractPlugin.loader },
                    { loader: 'css-loader' },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: () => [require('autoprefixer')({
                                'overrideBrowserslist': ['> 1%', 'last 2 versions']
                            })],
                        }
                    },
                    {
                        loader: 'sass-loader', options: {
                            sassOptions: {
                                importer: globImporter()
                            }
                        }
                    }]
            }
        ]
    },
    plugins: [new MiniCssExtractPlugin({
        filename: "./src/css/[name].[contentHash].css"
    },
        new CompressionPlugin({
            algorithm: 'gzip'
        }),
    ), new CleanWebpackPlugin()
    ]

})```

答:
this code is the half way of the process. now you need to tell express to handle those gzip files. for this you need to install

```<code>npm i express-static-gzip
</code>```

then in your server.js

```<code>const expressStaticGzip = require("express-static-gzip");
server.use(expressStaticGzip("dist")); //make sure you use this middleware on top of the other middlewares otherwise it will not work.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
this code is the half way of the process. now you need to tell express to handle those gzip files. for this you need to install

npm i express-static-gzip

then in your server.js

const expressStaticGzip = require("express-static-gzip");
server.use(expressStaticGzip("dist")); //make sure you use this middleware on top of the other middlewares otherwise it will not work.


问:
My first Lisp macro; is it leaky?
I've been working through Practical Common Lisp and as an exercise decided to write a macro to determine if a number is a multiple of another number:

(defmacro multp (value factor)

   `(= (rem ,value ,factor)  0))

so that :
(multp 40 10)
evaluates to true whilst
(multp 40 13)
does not

The question is does this macro leak in some way?  Also is this "good" Lisp?  Is there already an existing function/macro that I could have used?

答:
Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here. Both value and factor are evaluated only once and in order, and rem doesn't have any side effects.

This is not good Lisp though, because there's no reason to use a macro in this case. A function

```<code>(defun multp (value factor)
  (zerop (rem value factor)))
</code>```

is identical for all practical purposes. (Note the use of zerop. I think it makes things clearer in this case, but in cases where you need to highlight, that the value you're testing might still be meaningful if it's something other then zero, (= ... 0) might be better)

OwnerDisplayName: Tom Martin

ContentLicense: CC BY-SA 2.5

Title: My first Lisp macro; is it leaky?

Body:
Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here. Both value and factor are evaluated only once and in order, and rem doesn't have any side effects.

This is not good Lisp though, because there's no reason to use a macro in this case. A function

(defun multp (value factor)
  (zerop (rem value factor)))

is identical for all practical purposes. (Note the use of zerop. I think it makes things clearer in this case, but in cases where you need to highlight, that the value you're testing might still be meaningful if it's something other then zero, (= ... 0) might be better)


问:
how to extract content from
 tag java
i have a serious problem.
i would like to extract the content from  tag such as:

```<code><div class="main-content">
    <div class="sub-content">Sub content here</div>
      Main content here </div>
</code>```

output i would expect is:

Sub content here
Main content here

i've tried using regex, but the result isn't so impressive.
By using:

```<code>Pattern.compile("<div>(\\S+)</div>");
</code>```

would return all the strings before the first <*/div> tag
so, could anyone help me pls?

答:
```<code><div class="main-content" id="mainCon">
    <div class="sub-content" id="subCon">Sub content here</div>
 Main content here </div>
</code>```

From this code if you want to get the result you have mentioned

Use document.getElementById("mainCon").innerHTML it will give Main content here along with sub div but you parse that thing.

And similarly for sub-div you can use the above code sniplet i.e. document.getElementById("subCon").innerHTML

ContentLicense: CC BY-SA 3.0

Title: how to extract content from <div> tag java

Body:
i have a serious problem.
i would like to extract the content from  tag such as:

Sub content here

      Main content here

output i would expect is:

Sub content here
Main content here

i've tried using regex, but the result isn't so impressive.
By using:

Pattern.compile("
(\\S+)
");

would return all the strings before the first <*/div> tag
so, could anyone help me pls?

Body:
<div class="main-content" id="mainCon">
    <div class="sub-content" id="subCon">Sub content here</div>
 Main content here </div>

From this code if you want to get the result you have mentioned

Use document.getElementById("mainCon").innerHTML it will give Main content here along with sub div but you parse that thing.

And similarly for sub-div you can use the above code sniplet i.e. document.getElementById("subCon").innerHTML


问:
Using argparse.subparser with boolean values
I've read through the Python argparse documentation several times and must be missing something huge.  I'm trying to add a makefile like syntax onto my cli tool, but despite the --help flag showing me the expected behavior the execution of it errors out:

test.py

import argparse
import os

def main():
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    make_subparser = subparsers.add_parser("make")
    make_subparser.add_argument("update", action="store_false", help="Runs all make targets")
    make_subparser.add_argument("clean", action="store_false", help="Cleans up everything done previously")

    args = parser.parse_args()

    if args.update:
        os.system("touch test.txt")

    elif args.clean:
        os.system("rm test.txt")

    else:
        print("Bad args, see: python test.py make --help.")

if __name__ == "__main__":
    main()
```

<p>Then in my terminal:</p>

<pre class="lang-sh prettyprint-override"><code>$> python test.py make --help
usage: test.py make [-h]

positional arguments:
  update      Runs all make targets

$> python test.py make update
usage: test.py [-h] {make} ...
test.py: error: unrecognized arguments: update
$> # this should make a file
$>
$> python test.py make clean
usage: test.py [-h] {make} ...
test.py: error: unrecognized arguments: clean
$> # this should delete the file

</code>```

This works fine if I swap out the action="store_false" for action="store_true", but there's a dozen make commands so I only want to run the one that the user adds in the cli, if they try to enter any more it should exit.

答:
Instead of separate boolean flags, use single argument target which allows a restricted set of values.

```<code>make_subparser.add_argument("target", choices=['update', 'clean'], help="Runs all make targets")

if args.target == "update":
    ...
elif args.target == "clean":
    ...
</code>```

No else is needed, because any attempt to pass something other than update or clean will cause an error in parse_args, before args.target ever gets set.

Body:
I've read through the Python argparse documentation several times and must be missing something huge.  I'm trying to add a makefile like syntax onto my cli tool, but despite the --help flag showing me the expected behavior the execution of it errors out:

test.py

import argparse
import os

def main():
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    make_subparser = subparsers.add_parser("make")
    make_subparser.add_argument("update", action="store_false", help="Runs all make targets")
    make_subparser.add_argument("clean", action="store_false", help="Cleans up everything done previously")

    args = parser.parse_args()

    if args.update:
        os.system("touch test.txt")

    elif args.clean:
        os.system("rm test.txt")

    else:
        print("Bad args, see: python test.py make --help.")

if __name__ == "__main__":
    main()

Then in my terminal:

$> python test.py make --help
usage: test.py make [-h]

positional arguments:
  update      Runs all make targets

$> python test.py make update
usage: test.py [-h] {make} ...
test.py: error: unrecognized arguments: update
$> # this should make a file
$>
$> python test.py make clean
usage: test.py [-h] {make} ...
test.py: error: unrecognized arguments: clean
$> # this should delete the file

This works fine if I swap out the action="store_false" for action="store_true", but there's a dozen make commands so I only want to run the one that the user adds in the cli, if they try to enter any more it should exit.

Body:
Instead of separate boolean flags, use single argument target which allows a restricted set of values.

make_subparser.add_argument("target", choices=['update', 'clean'], help="Runs all make targets")

if args.target == "update":
    ...
elif args.target == "clean":
    ...

No else is needed, because any attempt to pass something other than update or clean will cause an error in parse_args, before args.target ever gets set.


问:
Codewars Challenge - JavaScript - Find the first non-consecutive number in Array
Link to Codewars challenge

This is very basic, but for some reason, I can't figure out why I'm not able to return null when there are not any non-consecutive numbers in an array. My code works fine when the array is not totally consecutive:

function firstNonConsecutive(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i + 1] - arr[i] !== 1) {
      return arr[i + 1];
    }
  }
  return null;
}

console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));```
</div>
</div>
</p>

<p>But if the array <em>is</em> consecutive, i.e. like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function firstNonConsecutive(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i + 1] - arr[i] !== 1) {
      return arr[i + 1];
    }
  }
  return null;
}

console.log(firstNonConsecutive([ 6, 7, 8, 9, 10, 11, 12 ]));</code>```

You can see that it returns undefined instead of null. Why isn't it returning null? The return is outside of the for-loop.

I tried to create an initial check to see if the array is not consecutive, like this:

function firstNonConsecutive(arr) {
  let newArr = [];
  for (let j = arr[0]; j < arr[arr.length - 1]; j++) {
    newArr.push(j);
  }
  //check if arr does not contain consecutive characters
  if (String(arr) !== String(newArr)) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i + 1] - arr[i] !== 1) {
        return arr[i + 1];
      }
    }
  }
  else {
    return null;
  }
}
console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));```

But it did not make a difference. Any ideas?

答:
You may try to Array.prototype.find() the gap:

```<code>const firstNonConsecutive = arr => arr.find((n,i,s) => i && n-s[i-1] > 1)
</code>```

So, it's modified version that'll pass arrays without gaps and arrays with negatives, would look like that:

const src1 = [1,2,3,4,6,7,8],
      src2 = [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ],
      src3 = [ -4, -3, -2, 0, 1, 3, 4, 5 ],
      firstNonConsecutive = arr => (
        gap = arr.find((n,i,s) => i && Math.max(n,s[i-1])-Math.min(n,s[i-1]) > 1),
        gap === undefined ? null : gap
      )

console.log(firstNonConsecutive(src1))
console.log(firstNonConsecutive(src2))
console.log(firstNonConsecutive(src3))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height:100%;}</code>```

While my answer may appear a bit overcomplicated due to Math.min()/Math.max() usage, it'll work for consecutive numbers listed in descending order just as well.

Body:
Link to Codewars challenge

This is very basic, but for some reason, I can't figure out why I'm not able to return null when there are not any non-consecutive numbers in an array. My code works fine when the array is not totally consecutive:

function firstNonConsecutive(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i + 1] - arr[i] !== 1) {
      return arr[i + 1];
    }
  }
  return null;
}

console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));

But if the array is consecutive, i.e. like this:

function firstNonConsecutive(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i + 1] - arr[i] !== 1) {
      return arr[i + 1];
    }
  }
  return null;
}

console.log(firstNonConsecutive([ 6, 7, 8, 9, 10, 11, 12 ]));

You can see that it returns undefined instead of null. Why isn't it returning null? The return is outside of the for-loop.

I tried to create an initial check to see if the array is not consecutive, like this:

function firstNonConsecutive(arr) {
  let newArr = [];
  for (let j = arr[0]; j < arr[arr.length - 1]; j++) {
    newArr.push(j);
  }
  //check if arr does not contain consecutive characters
  if (String(arr) !== String(newArr)) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i + 1] - arr[i] !== 1) {
        return arr[i + 1];
      }
    }
  }
  else {
    return null;
  }
}
console.log(firstNonConsecutive([ 0, 1, 2, 3, 4, 6, 7, 8, 9 ]));

But it did not make a difference. Any ideas?

Body:
You may try to Array.prototype.find() the gap:

const firstNonConsecutive = arr => arr.find((n,i,s) => i && n-s[i-1] > 1)

So, it's modified version that'll pass arrays without gaps and arrays with negatives, would look like that:

const src1 = [1,2,3,4,6,7,8],
      src2 = [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ],
      src3 = [ -4, -3, -2, 0, 1, 3, 4, 5 ],
      firstNonConsecutive = arr => (
        gap = arr.find((n,i,s) => i && Math.max(n,s[i-1])-Math.min(n,s[i-1]) > 1),
        gap === undefined ? null : gap
      )

console.log(firstNonConsecutive(src1))
console.log(firstNonConsecutive(src2))
console.log(firstNonConsecutive(src3))

.as-console-wrapper{min-height:100%;}

While my answer may appear a bit overcomplicated due to Math.min()/Math.max() usage, it'll work for consecutive numbers listed in descending order just as well.


问:
Function maybe written wrong, doesn't toggle image
This code is supposed to toggle between the "like" and "unlike" images, except it doesn't. Can anybody tell me what i wrote wrong. And yes i am new to javascript.</p>

```<code><script>
        function imgclick(){
        var like = "like.png",
            unlike = "unlike.png";
        var liked = document.getElemendById("liked");

        liked.src = (liked.src === unlike)? like : unlike;
        }
</script>
    <img src="unlike.png" id="liked" width="200" height="200" onclick="imgclick();">
</code>```

答:
You made a typo in the following line:

```<code>var liked = document.getElemendById("liked");
</code>```

You put getElemendById when it should be getElementById:

```<code>var liked = document.getElementById("liked");
</code>```

Body:
You made a typo in the following line:

var liked = document.getElemendById("liked");

You put getElemendById when it should be getElementById:

var liked = document.getElementById("liked");


问:
AWS S3 Bucket with Multiple Regions

I have an AWS S3 bucket which is set for the US Standard region but I want it to work in Singapore too. I have researched but could not find a way for the same bucket to work i multiple regions.

It would be great if someone could find a solution!

Thanks,

Maanit

答:
AWS Solutions has lanuched new solution to all replication across regions.

For example, you can create objects in Oregon, rename them in Singapore, and delete them in Dublin, and the changes are replicated to all other regions. This solution is designed for workloads that can tolerate lost events and variations in replication speed.
You can find more information here https://aws.amazon.com/solutions/multi-region-asynchronous-object-replication-solution/

Title: AWS S3 Bucket with Multiple Regions


问:
Django error Related Field got invalid lookup: icontains
Iam doing a Search in django using foreign key but it shows this error "Related Field got invalid lookup: icontains" i found similar cases here, but didnt work, i think the error is in the views.py in the queryset_list line..

models.py

```<code>class Anos_dos_manuais(models.Model):
    ano = models.CharField(max_length=200)
    publicado = models.BooleanField(default=True)

class Meta:
    verbose_name = 'Ano do manual'
    verbose_name_plural = 'Anos dos manuais'

def __str__(self):
    return self.ano

class Disciplina(models.Model):
    título = models.CharField(max_length=200)
    publicado = models.BooleanField(default=True)

class Meta:
    verbose_name = 'Disciplina'
    verbose_name_plural = 'Disciplinas'

def __str__(self):
    return self.título

class Manuais(models.Model):
    nome = models.CharField(max_length=200, null=True)
    título = models.ForeignKey(Disciplina, on_delete=models.DO_NOTHING)
    descrição = RichTextUploadingField(blank=False)
    ano = models.ForeignKey(Anos_dos_manuais, on_delete=models.DO_NOTHING ,max_length=20, null=True, blank=True)
    imagem = models.ImageField(upload_to='imagens/%Y/%m/%d/')
    manual_pdf = models.FileField(upload_to="manuais/%Y/%m/%d", null=True, blank=False)
    data_publicada = models.DateTimeField(default=datetime.now, blank=False, null=True)
    publicado = models.BooleanField(default=True)

class Meta:
    verbose_name = 'Manual'
    verbose_name_plural = 'Manuais'

def __str__(self):
    return self.nome
</code>```

When doing the search with the foreign and icontains it doesnt work, but with other fields it works
views.py

```<code>def search_manual(request):
    queryset_list = Manuais.objects.order_by('-data_publicada')
    disciplinas = Disciplina.objects.filter(publicado=True)
    anos = Anos_dos_manuais.objects.filter(publicado=True)

#keywords
if 'keywords' in request.GET:
    keywords = request.GET['keywords']
    if keywords:
        queryset_list = queryset_list.filter(título__icontains=keywords)

#Ano
if 'manual_ano' in request.GET:
    manual_ano = request.GET['manual_ano']
    if manual_ano:
        queryset_list = queryset_list.filter(ano__icontains=manual_ano)

#Disciplina
if 'manual_disciplina' in request.GET:
    manual_disciplina = request.GET['manual_disciplina']
    if manual_disciplina:
        queryset_list = queryset_list.filter(título__icontains=manual_disciplina)

context = {
    'anos': anos,
    'disciplinas': disciplinas,
    'manuais': queryset_list
}
return render(request, 'manuais/search.html', context)
</code>```

答:
Here titulo is a ForeignKey that refers to Desciplina. You likely want to filter on the titulo field of that Desciplina, so then you should add the lookup to that field, like:

```<code>queryset_list = queryset_list.filter(<b>título__titulo__icontains=keywords</b>)
# …
queryset_list = queryset_list.filter(<b>título__titulo__icontains=manual_disciplina</b>)
#                                            ^ field
#                                    ^ foreign key   ^ lookup</code>```

Body:
Iam doing a Search in django using foreign key but it shows this error "Related Field got invalid lookup: icontains" i found similar cases here, but didnt work, i think the error is in the views.py in the queryset_list line..

models.py

class Anos_dos_manuais(models.Model):
    ano = models.CharField(max_length=200)
    publicado = models.BooleanField(default=True)

class Meta:
    verbose_name = 'Ano do manual'
    verbose_name_plural = 'Anos dos manuais'

def __str__(self):
    return self.ano

class Disciplina(models.Model):
    título = models.CharField(max_length=200)
    publicado = models.BooleanField(default=True)

class Meta:
    verbose_name = 'Disciplina'
    verbose_name_plural = 'Disciplinas'

def __str__(self):
    return self.título

class Manuais(models.Model):
    nome = models.CharField(max_length=200, null=True)
    título = models.ForeignKey(Disciplina, on_delete=models.DO_NOTHING)
    descrição = RichTextUploadingField(blank=False)
    ano = models.ForeignKey(Anos_dos_manuais, on_delete=models.DO_NOTHING ,max_length=20, null=True, blank=True)
    imagem = models.ImageField(upload_to='imagens/%Y/%m/%d/')
    manual_pdf = models.FileField(upload_to="manuais/%Y/%m/%d", null=True, blank=False)
    data_publicada = models.DateTimeField(default=datetime.now, blank=False, null=True)
    publicado = models.BooleanField(default=True)

class Meta:
    verbose_name = 'Manual'
    verbose_name_plural = 'Manuais'

def __str__(self):
    return self.nome

When doing the search with the foreign and icontains it doesnt work, but with other fields it works
views.py

def search_manual(request):
    queryset_list = Manuais.objects.order_by('-data_publicada')
    disciplinas = Disciplina.objects.filter(publicado=True)
    anos = Anos_dos_manuais.objects.filter(publicado=True)

#keywords
if 'keywords' in request.GET:
    keywords = request.GET['keywords']
    if keywords:
        queryset_list = queryset_list.filter(título__icontains=keywords)

#Ano
if 'manual_ano' in request.GET:
    manual_ano = request.GET['manual_ano']
    if manual_ano:
        queryset_list = queryset_list.filter(ano__icontains=manual_ano)

#Disciplina
if 'manual_disciplina' in request.GET:
    manual_disciplina = request.GET['manual_disciplina']
    if manual_disciplina:
        queryset_list = queryset_list.filter(título__icontains=manual_disciplina)

context = {
    'anos': anos,
    'disciplinas': disciplinas,
    'manuais': queryset_list
}
return render(request, 'manuais/search.html', context)

Body:
Here titulo is a ForeignKey that refers to Desciplina. You likely want to filter on the titulo field of that Desciplina, so then you should add the lookup to that field, like:

queryset_list = queryset_list.filter(título__titulo__icontains=keywords)
# …
queryset_list = queryset_list.filter(título__titulo__icontains=manual_disciplina)
#                                            ^ field
#                                    ^ foreign key   ^ lookup


问:
How to use GoMap in Cgo?
I'm trying to call Go from c++. My code operates on maps, and I can't seem to make maps work with cgo.

main.go:

package main

import (
    "C"
    "fmt"
)

func main() {}

//export PrintMap
func PrintMap(m map[string]string) {
    fmt.Println(m)
}
```

<p>Which "compiles" to <code>main.h</code>:</p>

<pre class="lang-c prettyprint-override"><code>typedef void *GoMap;

extern void PrintMap(GoMap p0);
</code>```

How can I successfully create a GoMap in my c++ code and pass it to the go code?

答:
You can't. In fact, you can't really do anything with this type with cgo due to the pointer-passing rules that allow cgo to work safely with Go's concurrency and garbage collector. Maps are on the list of types that "always include Go pointers", and therefore maps can't be passed as arguments to C functions, returned from Go functions that are called by C code, or stored by C.

It's hard to give a recommendation on what you should do without seeing more of what you're trying to accomplish, but the usual workaround for this is to have the Go code hold objects in a map, and pass the C code a key from that map (as e.g. a C string or int, which can be passed or stored freely) as a handle to the object contained within. C then does all of its interaction with the objects through Go functions, which can use the key to find the correct value in the map. A slice would work too.

Title: How to use GoMap in Cgo?

Body:
I'm trying to call Go from c++. My code operates on maps, and I can't seem to make maps work with cgo.

main.go:

package main

import (
    "C"
    "fmt"
)

func main() {}

//export PrintMap
func PrintMap(m map[string]string) {
    fmt.Println(m)
}

Which "compiles" to main.h:

typedef void *GoMap;

extern void PrintMap(GoMap p0);

How can I successfully create a GoMap in my c++ code and pass it to the go code?


问:
Mongoose won't populate an array or object
Im having an issue where i have a Fixtures schema like so:

```<code>const FixtureSchema = mongoose.Schema({
  home: {
    club: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'club'
    },
    score: {
      type: Number,
      default: 0
    },
    scorers: [
      {
        player: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'player'
        }
      }
    ]
  },
  away: {
    club: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'club'
    },
    score: {
      type: Number,
      default: 0
    },
    scorers: [
      {
        player: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'player'
        }
      }
    ]
  },
  match_num: {
    type: Number,
    required: true
  },
  date: {
    type: Date,
    default: Date.now()
  }
});

module.exports = Fixture = mongoose.model('fixture', FixtureSchema);
</code>```

Club schema:

```<code>const ClubSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
});

module.exports = Club = mongoose.model('club', ClubSchema);
</code>```

Player Schema:

```<code>const PlayerSchema = new mongoose.Schema({
  name: {
    type: String,
    require: true
  },
  club: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'club'
  },
  stats: {
    starts: {
      type: Number,
      default: 0
    },
    goals: {
      type: Number,
      default: 0
    },
    assists: {
      type: Number,
      default: 0
    },
    goal_streak: {
      type: Number,
      default: 0
    }
  }
});

module.exports = Player = mongoose.model('player', PlayerSchema);
</code>```

I make a request like this:

```<code>router.get('/', async (req, res) => {
  try {
    const fixture = await Fixture.find()
      .populate('player', ['name'])
      .populate('club', ['name']);
    res.json(fixture);
  } catch (err) {
    console.error(err.message);
  }
});
</code>```

Postman get request gives me:

```<code>[
    {
        "home": {
            "score": 1,
            "club": "5e3dfcffb52ec61c30fc44cd",
            "scorers": [
                {
                    "_id": "5e4aac5d81d92b368398bd4d",
                    "player": "5e3dfddd4884f51cb7ee61e9"
                }
            ]
        },
        "away": {
            "score": 0,
            "club": "5e3dfd18b52ec61c30fc44ce",
            "scorers": []
        },
        "date": "2020-02-17T15:07:57.229Z",
        "_id": "5e4aac5d81d92b368398bd4c",
        "match_num": 1,
        "__v": 0
    }
]
</code>```

Why is it not populating the name of the player or the club??? It works when it is not stored in an array or object.. Ive tried looking for advice on other topics but cant find anything relating to this..

Thanks for any replies and advice

答:
Turns out it was the same as the other questions!!! lol..

If i change :

```<code> .populate('club', ['name']);
</code>```

to

```<code>.populate('home.club', ['name']);
</code>```

and so on
it solves it...

Body:
Im having an issue where i have a Fixtures schema like so:

const FixtureSchema = mongoose.Schema({
  home: {
    club: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'club'
    },
    score: {
      type: Number,
      default: 0
    },
    scorers: [
      {
        player: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'player'
        }
      }
    ]
  },
  away: {
    club: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'club'
    },
    score: {
      type: Number,
      default: 0
    },
    scorers: [
      {
        player: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'player'
        }
      }
    ]
  },
  match_num: {
    type: Number,
    required: true
  },
  date: {
    type: Date,
    default: Date.now()
  }
});

module.exports = Fixture = mongoose.model('fixture', FixtureSchema);

Club schema:

const ClubSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
});

module.exports = Club = mongoose.model('club', ClubSchema);

Player Schema:

const PlayerSchema = new mongoose.Schema({
  name: {
    type: String,
    require: true
  },
  club: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'club'
  },
  stats: {
    starts: {
      type: Number,
      default: 0
    },
    goals: {
      type: Number,
      default: 0
    },
    assists: {
      type: Number,
      default: 0
    },
    goal_streak: {
      type: Number,
      default: 0
    }
  }
});

module.exports = Player = mongoose.model('player', PlayerSchema);

I make a request like this:

router.get('/', async (req, res) => {
  try {
    const fixture = await Fixture.find()
      .populate('player', ['name'])
      .populate('club', ['name']);
    res.json(fixture);
  } catch (err) {
    console.error(err.message);
  }
});

Postman get request gives me:

[
    {
        "home": {
            "score": 1,
            "club": "5e3dfcffb52ec61c30fc44cd",
            "scorers": [
                {
                    "_id": "5e4aac5d81d92b368398bd4d",
                    "player": "5e3dfddd4884f51cb7ee61e9"
                }
            ]
        },
        "away": {
            "score": 0,
            "club": "5e3dfd18b52ec61c30fc44ce",
            "scorers": []
        },
        "date": "2020-02-17T15:07:57.229Z",
        "_id": "5e4aac5d81d92b368398bd4c",
        "match_num": 1,
        "__v": 0
    }
]

Why is it not populating the name of the player or the club??? It works when it is not stored in an array or object.. Ive tried looking for advice on other topics but cant find anything relating to this..

Thanks for any replies and advice

Body:
Turns out it was the same as the other questions!!! lol..

If i change :

 .populate('club', ['name']);

to

.populate('home.club', ['name']);

and so on
it solves it...


问:
Traefik:v2 Windows Container Failed to retrieve information of the docker client and server host
I ran docker image traefik:v2.1.4-windowsservercore-1809 in Windows Server 2019 with 4GB memory (Amazon EC2 t2.medium instance) and got the following error.

$ docker run -p 8080:8080 -p 80:80 -v $PWD/traefikdata:C:/etc/traefik --entrypoint /traefik traefik:v2.1.4-windowsservercore-1809 --configfile=C:/etc/traefik/traefik.toml
time="2020-02-15T11:30:12Z" level=info msg="Configuration loaded from file: C:\etc\traefik\traefik.toml"
time="2020-02-15T11:30:12Z" level=error msg="Failed to retrieve information of the docker client and server host: error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.24/version: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running." providerName=docker
time="2020-02-15T11:30:12Z" level=error msg="Provider connection error error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.24/version: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running., retrying in 552.330144ms" providerName=docker

The traefik.toml is

```<code>[entryPoints]
  [entryPoints.web]
  address = ":80"

[api]
  insecure = true

[providers]
  [providers.docker]
  endpoint = "npipe:////./pipe/docker_engine"
</code>```

The traefik version is

```<code>Version:      2.1.4
Codename:     cantal
Go version:   go1.13.7
Built:        2020-02-06T17:12:23Z
OS/Arch:      windows/amd64
</code>```

The Docker daemon.json is

```<code>{
    "hosts":  [
                  "npipe://"
              ]
}
</code>```

Docker version 19.03.5, build 2ee0c57608

What is wrong with my configuration? Thanks for your help!

答:
I figured it out. I need to map named pipe. The following commnad works fine.
docker run -p 8080:8080 -p 80:80 -v $PWD/traefikdata:C:/etc/traefik --volume .\pipe\docker_engine:.\pipe\docker_engine --entrypoint /traefik traefik:v2.1.4-windowsservercore-1809
--configfile=C:/etc/traefik/traefik.toml</p>

Body:
I ran docker image traefik:v2.1.4-windowsservercore-1809 in Windows Server 2019 with 4GB memory (Amazon EC2 t2.medium instance) and got the following error.

$ docker run -p 8080:8080 -p 80:80 -v $PWD/traefikdata:C:/etc/traefik --entrypoint /traefik traefik:v2.1.4-windowsservercore-1809 --configfile=C:/etc/traefik/traefik.toml
time="2020-02-15T11:30:12Z" level=info msg="Configuration loaded from file: C:\etc\traefik\traefik.toml"
time="2020-02-15T11:30:12Z" level=error msg="Failed to retrieve information of the docker client and server host: error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.24/version: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running." providerName=docker
time="2020-02-15T11:30:12Z" level=error msg="Provider connection error error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.24/version: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running., retrying in 552.330144ms" providerName=docker

The traefik.toml is

[entryPoints]
  [entryPoints.web]
  address = ":80"

[api]
  insecure = true

[providers]
  [providers.docker]
  endpoint = "npipe:////./pipe/docker_engine"

The traefik version is

Version:      2.1.4
Codename:     cantal
Go version:   go1.13.7
Built:        2020-02-06T17:12:23Z
OS/Arch:      windows/amd64

The Docker daemon.json is

{
    "hosts":  [
                  "npipe://"
              ]
}

Docker version 19.03.5, build 2ee0c57608

What is wrong with my configuration? Thanks for your help!


问:
How to get value input form from FormGroup
Good day, guys I'd like to find the solution to solve my problem. I have a FormGroup like this :

```<code>  profileForm  = new FormGroup({
    username   : new FormControl(),
    firstname  : new FormControl(),
    lastname   : new FormControl(),
    email      : new FormControl(),
    password   : new FormControl(),
  });
</code>```

And I'd like to get the value by using :

```<code>const user = {
  firstname : this.profileForm.get('firstname').value,
  lastname  : this.profileForm.get('lastname').value,
  username  : this.profileForm.get('username').value,
  email     : this.profileForm.get('email').value,
  password  : this.profileForm.get('password').value
}
console.log(user)
</code>```

But I got null value for each input form. But the value exists in the HTML form input :

```<code><input name="username" matInput placeholder="Username" formControlName="username" [readonly]="true" value="{{details?.data.username}}" >
</code>```

Help me to fix this, thank you.

答:
Your mistake is that you access the Formgroup (which is basically an object which contains all formControls), which don't contain the value. You should be access controls of the Form group.
An example:</p>

```<code>this.profileForm.controls.username.value
</code>```

Body:
Good day, guys I'd like to find the solution to solve my problem. I have a FormGroup like this :

  profileForm  = new FormGroup({
    username   : new FormControl(),
    firstname  : new FormControl(),
    lastname   : new FormControl(),
    email      : new FormControl(),
    password   : new FormControl(),
  });

And I'd like to get the value by using :

const user = {
  firstname : this.profileForm.get('firstname').value,
  lastname  : this.profileForm.get('lastname').value,
  username  : this.profileForm.get('username').value,
  email     : this.profileForm.get('email').value,
  password  : this.profileForm.get('password').value
}
console.log(user)

But I got null value for each input form. But the value exists in the HTML form input :

<input name="username" matInput placeholder="Username" formControlName="username" [readonly]="true" value="{{details?.data.username}}" >

Help me to fix this, thank you.

Body:
Your mistake is that you access the Formgroup (which is basically an object which contains all formControls), which don't contain the value. You should be access controls of the Form group.
An example:

this.profileForm.controls.username.value


问:
Should I use Static class for Database connectivity in C#.net?
I have a class which contain all the database connection activities. What i want to know is should i make this class as static then i can call anywhere without creating it.
but the application runs in different pcs in same network in same time.

OR ELSE

should i create a normal class that can be use in other classes by inheriting it?

答: don't use static class you can make your connection string static,because when multiple users are accessing static class can make problem</p>


问:
Java maximum memory on Windows XP
I've always been able to allocate 1400 megabytes for Java SE running on 32-bit Windows XP (Java 1.4, 1.5 and 1.6).

```<code>java -Xmx1400m ...
</code>```

Today I tried the same option on a new Windows XP machine using Java 1.5_16 and 1.6.0_07 and got the error:

```<code>Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
</code>```

Through trial and error it seems 1200 megabytes is the most I can allocate on this machine.

Any ideas why one machine would allow 1400 and another only 1200?

Edit: The machine has 4GB of RAM with about 3.5GB that Windows can recognize.

答:
**There are numerous ways to change heap size like,

file->setting->build, exceution, deployment->compiler  here you will find heap size

file->setting->build, exceution, deployment->compiler->andriod here also you will find heap size. You can refer this for andriod project if you facing same issue.

What worked for me was

Set proper appropriate JAVA_HOME path incase you java got updated.

create new system variable computer->properties->advanced setting->create new system variable

name: _JAVA_OPTION value: -Xmx750m

FYI:
you can find default VMoption in Intellij
help->edit custom VM option , In this file you see min and max size of heap.**

OwnerDisplayName: Steve Kuo

Title: Java maximum memory on Windows XP

Body:
I've always been able to allocate 1400 megabytes for Java SE running on 32-bit Windows XP (Java 1.4, 1.5 and 1.6).

java -Xmx1400m ...

Today I tried the same option on a new Windows XP machine using Java 1.5_16 and 1.6.0_07 and got the error:

Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

Through trial and error it seems 1200 megabytes is the most I can allocate on this machine.

Any ideas why one machine would allow 1400 and another only 1200?

Edit: The machine has 4GB of RAM with about 3.5GB that Windows can recognize.

LastEditorDisplayName: Steve Kuo


问:
Tidy or unnest S4 BFBayesFactor object
I want to run several nested t.test and ttestBF (using tidyr::nest()) but I can't manage to either tidy or to unnest the S4: BFBayesFactor object that comes out the ttestBF function.

Example data:

```<code>set.seed(354654)
d = tibble(value = rnorm(100),
           category = sample(1:5, replace = TRUE, 100),
           group = sample(c('A', 'B'), replace = TRUE, 100)) %>%
  arrange(category)
</code>```

I run this piece of code for the t.test and it works just fine:

```<code>library('tidyverse')
library('broom')

d %>%
  group_by(category, group) %>%
  nest() %>%
  spread(key = group, value = data) %>%
  mutate(
    t_test = map2(A, B, ~{t.test(.x$value, .y$value) %>% tidy()}),
    A = map(A, nrow),
    B = map(B, nrow)
  ) %>%
  unnest()
</code>```

However, if I try this:

```<code>d %>%
  group_by(category, group) %>%
  nest() %>%
  spread(key = group, value = data) %>%
  mutate(
    t_test_bf = map2(A, B, ~{ttestBF(.x$value, .y$value, nullInterval = c(0, Inf)) %>% tidy() }),
    A = map(A, nrow),
    B = map(B, nrow)
  ) %>%
  unnest()
</code>```

I get: Error: No tidy method for objects of class BFBayesFactor. If I remove the tidy() call, so:

```<code>t_test_bf = map2(A, B, ~{ttestBF(.x$value, .y$value, nullInterval = c(0, Inf)) })
</code>```

I still get the following error:

Error: All nested columns must have the same number of elements.

Any idea on how to unnest the ttestBF output?

Title: Tidy or unnest S4 BFBayesFactor object

Body:
I want to run several nested t.test and ttestBF (using tidyr::nest()) but I can't manage to either tidy or to unnest the S4: BFBayesFactor object that comes out the ttestBF function.

Example data:

set.seed(354654)
d = tibble(value = rnorm(100),
           category = sample(1:5, replace = TRUE, 100),
           group = sample(c('A', 'B'), replace = TRUE, 100)) %>%
  arrange(category)

I run this piece of code for the t.test and it works just fine:

library('tidyverse')
library('broom')

d %>%
  group_by(category, group) %>%
  nest() %>%
  spread(key = group, value = data) %>%
  mutate(
    t_test = map2(A, B, ~{t.test(.x$value, .y$value) %>% tidy()}),
    A = map(A, nrow),
    B = map(B, nrow)
  ) %>%
  unnest()

However, if I try this:

d %>%
  group_by(category, group) %>%
  nest() %>%
  spread(key = group, value = data) %>%
  mutate(
    t_test_bf = map2(A, B, ~{ttestBF(.x$value, .y$value, nullInterval = c(0, Inf)) %>% tidy() }),
    A = map(A, nrow),
    B = map(B, nrow)
  ) %>%
  unnest()

I get: Error: No tidy method for objects of class BFBayesFactor. If I remove the tidy() call, so:

t_test_bf = map2(A, B, ~{ttestBF(.x$value, .y$value, nullInterval = c(0, Inf)) })

I still get the following error:

Error: All nested columns must have the same number of elements.

Any idea on how to unnest the ttestBF output?

Body:
You could pull the data frame out of each object's bayesFactor S4 slot using the @ notation for S4 objects:

d %>%
  group_by(category, group) %>%
  nest() %>%
  spread(key = group, value = data) %>%
  mutate(
    t_test_bf = map2(A, B, ~{ttestBF(.x$value, .y$value,
                                     nullInterval = c(0, Inf))@bayesFactor}[,-3]),
    A = map(A, nrow),
    B = map(B, nrow)
  ) %>%
  unnest()
#> # A tibble: 10 x 6
#> # Groups:   category [5]
#>    category     A     B     bf        error code
#>       <int> <int> <int>  <dbl>        <dbl> <fct>
#>  1        1    10    10 -1.04  0.0000592    159448f630f7
#>  2        1    10    10 -0.797 0.0000000429 1594124c5471
#>  3        2     7     6 -0.519 0.000000105  15946a5667c9
#>  4        2     7     6 -1.01  0.000141     15946b70910
#>  5        3     8     9 -1.32  0.00000260   15944c833396
#>  6        3     8     9 -0.214 0.000000168  159433103012
#>  7        4    15    11 -0.709 0.0000450    15942a13701
#>  8        4    15    11 -1.26  0.000123     15947c9d5ed8
#>  9        5    11    13 -1.11  0.000122     15945bcc7d07
#> 10        5    11    13 -0.850 0.00000969   1594311d17e2


问:
Remove ObjectId from mongodb document serialized to JSON in C#
I'm having a bit of an issue here. I am getting all my products from a mongodb collection with this function:

```<code>public async Task<string> getAllProducts()
        {
            List<string> all = new List<string>();

            var document = await getCollection("produits").Find(new BsonDocument()).ToCursorAsync();
            foreach (var doc in document.ToEnumerable())
            {
                var res = doc.ToJson();
                all.Add(res);
            }
            return JsonConvert.SerializeObject(all);
        }
</code>```

and it returns a JSON that looks like this to my react front end.

```<code>{ "_id" : ObjectId("5e49bdf5f040e808847a17d7"),
"email" : "example@gmail.com",
"quantite" : 1,
"matricule" : 1}
</code>```

problem is i cant parse this in my javascript because of this : ObjectId("5e49bdf5f040e808847a17d7")

Of course I could do some string magic before I parse it, but id rather it be corrected on the server side. So is there a way I can get rid of this problem and get a result like this?

```<code>{ "_id" : "5e49bdf5f040e808847a17d7",
    "email" : "example@gmail.com",
    "quantite" : 1,
    "matricule" : 1}
</code>```

答:
give this a try. it will serialize string ids without objectid stuff.

    public static async Task<string> getAllProducts()
    {
        var collection = db.GetCollection<object>("produits");

        var all = new List<object>();

        using (var cursor = await collection.FindAsync("{}"))
        {
            while (await cursor.MoveNextAsync())
            {
                foreach (var doc in cursor.Current.ToArray())
                {
                    all.Add(doc);
                }
            }
        }

        return Newtonsoft.Json.JsonConvert.SerializeObject(all);
    }
```

Body:
I'm having a bit of an issue here. I am getting all my products from a mongodb collection with this function:

public async Task<string> getAllProducts()
        {
            List<string> all = new List<string>();

            var document = await getCollection("produits").Find(new BsonDocument()).ToCursorAsync();
            foreach (var doc in document.ToEnumerable())
            {
                var res = doc.ToJson();
                all.Add(res);
            }
            return JsonConvert.SerializeObject(all);
        }

and it returns a JSON that looks like this to my react front end.

{ "_id" : ObjectId("5e49bdf5f040e808847a17d7"),
"email" : "example@gmail.com",
"quantite" : 1,
"matricule" : 1}

problem is i cant parse this in my javascript because of this : ObjectId("5e49bdf5f040e808847a17d7")

Of course I could do some string magic before I parse it, but id rather it be corrected on the server side. So is there a way I can get rid of this problem and get a result like this?

{ "_id" : "5e49bdf5f040e808847a17d7",
    "email" : "example@gmail.com",
    "quantite" : 1,
    "matricule" : 1}


问:
Artifacts between pipeline tasks in Gitlab
I use the Gitlab CE edition and I setup my classic build pipeline (build, test, deploy). The build step creates an application of around 1GB (500 MB as zipped artifact). The artifact is uploaded to the server and the next gitlab runner downloads it again to test it. Is there a way to set an “affinity” for a gitlab runner, so exactly the machine which just built the binary can continue using the binaries to test it?

One option would be to merge the build and test step into a single one, but I am looking for alternatives. Thank you!

答:
Had exactly the same issue using cmake, and had to combine the build and test step into one to save time from zipping and unzipping large build directories.

There is an open issue on using sticky runners, where one pipeline will always use the same runner and save the workspace between jobs, however that is a while away from being completed it seems.


问:
perl - matching greater than charater in regex
```<code>$string1="<a href='/channels/folder1'>Alpha-Seeking";
$string2="<a href='/channels/folder2'>No Underlying Index ,";
</code>```

I need to extract "Alpha-Seeking" and "No Underlying Index ," from the above 2 strings.
Basically, need everything from ('>) to the last character of the string.

Tried two ways,

1) The standard intuitive

```<code>($string1=~ /\'>(.*?)/) {print "got $1";}
</code>```

but this does not seem to work on '>' symbol.

2) Also tried

```<code>if ($string1=~ /(?=>)(.*?)/) {print "got $1";}
</code>```

based on inputs from Greater than and less than symbol in regular expressions, but it is not working.

Any inputs will be useful.

PS: Also, if the answer can include matching the "less than" symbo ("<"), that will be great!

Thanks

答:
Do not parse HTML with a regex. Regexes are very bad at parsing complex, balanced text like HTML.

For example:

```<code><tag>
  outer
  <tag>
    middle
    <tag>inner</tag>
    middle
  </tag>
  outer
</tag>
</code>```

Instead, use an HTML parser and search tools such as XPath.

Here is a demonstration using XML::LibXML.

```<code>use strict;
use warnings;
use v5.10;

use XML::LibXML;

my $html = q{
<html>
<body>
    <a href='/channels/folder1'>Alpha-Seeking</a>
    <a href='/channels/folder2'>No Underlying Index</a>
</body>
</html>
};

# Parse the HTML
my $dom = XML::LibXML->load_html(string => $html);

# Find all links.
for my $node ($dom->findnodes('//a')) {
    # Print their text.
    say $node->textContent;
}
</code>```

Body:
$string1="Alpha-Seeking";
$string2="No Underlying Index ,";

I need to extract "Alpha-Seeking" and "No Underlying Index ," from the above 2 strings.
Basically, need everything from ('>) to the last character of the string.

Tried two ways,

1) The standard intuitive

($string1=~ /\'>(.*?)/) {print "got $1";}

but this does not seem to work on '>' symbol.

2) Also tried

if ($string1=~ /(?=>)(.*?)/) {print "got $1";}

based on inputs from Greater than and less than symbol in regular expressions, but it is not working.

Any inputs will be useful.

PS: Also, if the answer can include matching the "less than" symbo ("<"), that will be great!

Thanks

Body:
Do not parse HTML with a regex. Regexes are very bad at parsing complex, balanced text like HTML.

For example:

<tag>
  outer
  <tag>
    middle
    <tag>inner</tag>
    middle
  </tag>
  outer
</tag>

Instead, use an HTML parser and search tools such as XPath.

Here is a demonstration using XML::LibXML.

use strict;
use warnings;
use v5.10;

use XML::LibXML;

my $html = q{
<html>
<body>
    <a href='/channels/folder1'>Alpha-Seeking</a>
    <a href='/channels/folder2'>No Underlying Index</a>
</body>
</html>
};

# Parse the HTML
my $dom = XML::LibXML->load_html(string => $html);

# Find all links.
for my $node ($dom->findnodes('//a')) {
    # Print their text.
    say $node->textContent;
}


问:
Parent-child relation between two objects causes JSON StackOverflowError
I am trying to achieve a parent-child relation between some objects and I ran into a bit of trouble.

In my case, I am trying to store objects within other objects (e.g. container stores multiple items or other containers with items). The tricky part is that every object in the storage should be able to tell what it's outermost parent object is. While this seems to work in my in-memory database (using h2 at the moment), trying to get a JSON representation of all my storage items gives this (I return a List<StorageUnit> ):

Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]->com.warehousing.storage.FixedContentsCase["contents"]->java.util.ArrayList[0]->com.warehousing.storage.FixedContentsCase["contents"]->...

Here are the classes:

StorageUnit

```<code>@Entity
@Inheritance
public abstract class StorageUnit {

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Long id;
   @ManyToOne
   private Location location;
   protected Long parentContainerId;
   // <getters & setters>
   public abstract List<StorageUnit> getContents();
}
</code>```

FixedContentCase

```<code>
@Entity
public class FixedContentsCase extends StorageUnit {
    @OneToMany
    private List<Item> items;

    public FixedContentsCase() {
        super();
        items = new ArrayList<>();
    }
    // <getters & setters>
    @Override
    public List<StorageUnit> getContents() {
        // Return the case itself and its contents
        List<StorageUnit> contents = new ArrayList<>(Arrays.asList(this));
        for (StorageUnit item : items)
            contents.addAll(item.getContents());
        return contents;
    }
}
</code>```

Item

```<code>@Entity
public class Item extends StorageUnit {

    private String description;

    public Item() {
        super();
        this.description = "";
    }
    // <getters & setters>
    @Override
    public List<StorageUnit> getContents() {
        return Arrays.asList(this);
    }
}
</code>```

I have tried to annotate the StorageUnit class with @JsonIgnoreProperties("parentContainerId") but it didn't work. Annotating parentContainerId with  @JsonIgnore didn't help either. I also tried annotating the getters instead of the attributes themselves (as per following). Is there a way to work around this or is some kind of design change necessary? Thanks!

答:
Your problem is that you add the storage unit itself to its list of contents, leading to infinite recursion if you traverse the tree downwards. The solution: Use a reference and only serialize the object once, using @JsonIdentityInfo and @JsonIdentityReference:

```<code>public class MyTest {

    @Test
    public void myTest() throws JsonProcessingException {
        final FixedContentsCase fcc = new FixedContentsCase();
        fcc.setId(Long.valueOf(1));
        final Item item = new Item();
        item.setId(Long.valueOf(2));
        item.setDescription("item 1");
        fcc.getItems().add(item);
        final ObjectMapper om = new ObjectMapper();
        System.out.println(om.writeValueAsString(fcc));
    }
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = false)
class Item extends StorageUnit {

    ...
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = false)
class FixedContentsCase extends StorageUnit {

    ...
}

abstract class StorageUnit {

    ...
}
</code>```

Body:
I am trying to achieve a parent-child relation between some objects and I ran into a bit of trouble.

In my case, I am trying to store objects within other objects (e.g. container stores multiple items or other containers with items). The tricky part is that every object in the storage should be able to tell what it's outermost parent object is. While this seems to work in my in-memory database (using h2 at the moment), trying to get a JSON representation of all my storage items gives this (I return a List<StorageUnit> ):

Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]->com.warehousing.storage.FixedContentsCase["contents"]->java.util.ArrayList[0]->com.warehousing.storage.FixedContentsCase["contents"]->...

Here are the classes:

StorageUnit

@Entity
@Inheritance
public abstract class StorageUnit {

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Long id;
   @ManyToOne
   private Location location;
   protected Long parentContainerId;
   // <getters & setters>
   public abstract List<StorageUnit> getContents();
}

FixedContentCase

@Entity
public class FixedContentsCase extends StorageUnit {
    @OneToMany
    private List<Item> items;

    public FixedContentsCase() {
        super();
        items = new ArrayList<>();
    }
    // <getters & setters>
    @Override
    public List<StorageUnit> getContents() {
        // Return the case itself and its contents
        List<StorageUnit> contents = new ArrayList<>(Arrays.asList(this));
        for (StorageUnit item : items)
            contents.addAll(item.getContents());
        return contents;
    }
}

Item

@Entity
public class Item extends StorageUnit {

    private String description;

    public Item() {
        super();
        this.description = "";
    }
    // <getters & setters>
    @Override
    public List<StorageUnit> getContents() {
        return Arrays.asList(this);
    }
}

I have tried to annotate the StorageUnit class with @JsonIgnoreProperties("parentContainerId") but it didn't work. Annotating parentContainerId with  @JsonIgnore didn't help either. I also tried annotating the getters instead of the attributes themselves (as per following). Is there a way to work around this or is some kind of design change necessary? Thanks!

Body:
Your problem is that you add the storage unit itself to its list of contents, leading to infinite recursion if you traverse the tree downwards. The solution: Use a reference and only serialize the object once, using @JsonIdentityInfo and @JsonIdentityReference:

public class MyTest {

    @Test
    public void myTest() throws JsonProcessingException {
        final FixedContentsCase fcc = new FixedContentsCase();
        fcc.setId(Long.valueOf(1));
        final Item item = new Item();
        item.setId(Long.valueOf(2));
        item.setDescription("item 1");
        fcc.getItems().add(item);
        final ObjectMapper om = new ObjectMapper();
        System.out.println(om.writeValueAsString(fcc));
    }
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = false)
class Item extends StorageUnit {

    ...
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = false)
class FixedContentsCase extends StorageUnit {

    ...
}

abstract class StorageUnit {

    ...
}


问:
string split into lines php by pattern
I have a string like this:

```<code>1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps
</code>```

I want to split the string into two strings like this:

```<code>192.168.122.1 0.89 Bps
192.168.122.10 0.25 Bps
</code>```

Title: string split into lines php by pattern

Body:
I have a string like this:

1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps

I want to split the string into two strings like this:

192.168.122.1 0.89 Bps
192.168.122.10 0.25 Bps

Body:
preg_split example:

$str = "1. 192.168.122.1 0.89 Bps 2. 192.168.122.10 0.25 Bps";

$split = preg_split("~\s?\d\.\s~", $str, -1, PREG_SPLIT_NO_EMPTY);

/*
Array
(
    [0] => 192.168.122.1 0.89 Bps
    [1] => 192.168.122.10 0.25 Bps
)
*/


问:
How to get type from *types.Named
I'm trying to find function calls of funcs that have context.Context as first parameter.

I've been able to do what's shown below but I'm stuck at getting the underlying type from *types.Named. How can I do this?

package main

import (
    "bytes"
    "context"
    "fmt"
    "go/ast"
    "go/printer"
    "go/token"
    "go/types"

    "golang.org/x/tools/go/analysis"
    "golang.org/x/tools/go/analysis/singlechecker"
)

var Analyzer = &analysis.Analyzer{
    Name: "addlint",
    Doc:  "reports integer additions",
    Run:  run,
}

func main() {
    singlechecker.Main(Analyzer)
}

func funcHasContextContextAsFirstParam(pass *analysis.Pass, expr ast.Expr) bool {
    t := pass.TypesInfo.TypeOf(expr)
    if t == nil {
        return false
    }

    bt, ok := t.Underlying().(*types.Signature)
    if !ok {
        return false
    }

    fmt.Printf("signature: %+v - %T\n", bt, bt)

    params := bt.Params()
    for i := 0; i < params.Len(); i++ {
        v := params.At(i)
        fmt.Printf("Type :  %T\n", v.Type())

        if named, ok := v.Type().(*types.Named); ok {
            // fmt.Printf("named : %v - %T\n", named.Obj(), named.Obj())
            fmt.Printf("named : %T\n", named)
            fmt.Printf("named.Obj() : %T\n", named.Obj())

            typ := named.Underlying()
            fmt.Printf("typ:  %T\n", typ.Underlying())

            if _, ok = typ.(context.Context); ok {
                fmt.Printf("context.Context type!\n")
            }
        }
    }
    return true
}

func run(pass *analysis.Pass) (interface{}, error) {
    for _, file := range pass.Files {
        ast.Inspect(file, func(n ast.Node) bool {
            be, ok := n.(*ast.CallExpr)
            if !ok {
                return true
            }

            fmt.Printf("call expression %+v\n", be)
            funcHasContextContextAsFirstParam(pass, be.Fun)

            return true
        })
    }

    return nil, nil
}
```

<p>That's the output I'm getting:</p>

```call expression &{Fun:foo Lparen:6160580 Args:[c 0xc0003c5780 0xc0003c57c0] Ellipsis:0 Rparen:6160596}
signature: func(ctx context.Context, n int, str string) - *types.Signature
Type :  *types.Named
named : *types.Named
named.Obj() : *types.TypeName
typ:  *types.Interface
```

答:
I've ended up with something like this:

func funcHasContextContextAsFirstParam(pass *analysis.Pass, expr ast.Expr) bool {
    t := pass.TypesInfo.TypeOf(expr)
    if t == nil {
        return false
    }

    bt, ok := t.Underlying().(*types.Signature)
    if !ok {
        return false
    }

    params := bt.Params()

    if params.Len() < 1 {
        return false
    }

    param := params.At(0)
    named, ok := param.Type().(*types.Named)
    if !ok {
        return false
    }

    namedObj := named.Obj()
    if namedObj.Name() != "Context" || namedObj.Pkg().Name() != "context" {
        return false
    }

    return true
}
```

Title: How to get type from *types.Named

Body:
I'm trying to find function calls of funcs that have context.Context as first parameter.

I've been able to do what's shown below but I'm stuck at getting the underlying type from *types.Named. How can I do this?

package main

import (
    "bytes"
    "context"
    "fmt"
    "go/ast"
    "go/printer"
    "go/token"
    "go/types"

    "golang.org/x/tools/go/analysis"
    "golang.org/x/tools/go/analysis/singlechecker"
)

var Analyzer = &analysis.Analyzer{
    Name: "addlint",
    Doc:  "reports integer additions",
    Run:  run,
}

func main() {
    singlechecker.Main(Analyzer)
}

func funcHasContextContextAsFirstParam(pass *analysis.Pass, expr ast.Expr) bool {
    t := pass.TypesInfo.TypeOf(expr)
    if t == nil {
        return false
    }

    bt, ok := t.Underlying().(*types.Signature)
    if !ok {
        return false
    }

    fmt.Printf("signature: %+v - %T\n", bt, bt)

    params := bt.Params()
    for i := 0; i < params.Len(); i++ {
        v := params.At(i)
        fmt.Printf("Type :  %T\n", v.Type())

        if named, ok := v.Type().(*types.Named); ok {
            // fmt.Printf("named : %v - %T\n", named.Obj(), named.Obj())
            fmt.Printf("named : %T\n", named)
            fmt.Printf("named.Obj() : %T\n", named.Obj())

            typ := named.Underlying()
            fmt.Printf("typ:  %T\n", typ.Underlying())

            if _, ok = typ.(context.Context); ok {
                fmt.Printf("context.Context type!\n")
            }
        }
    }
    return true
}

func run(pass *analysis.Pass) (interface{}, error) {
    for _, file := range pass.Files {
        ast.Inspect(file, func(n ast.Node) bool {
            be, ok := n.(*ast.CallExpr)
            if !ok {
                return true
            }

            fmt.Printf("call expression %+v\n", be)
            funcHasContextContextAsFirstParam(pass, be.Fun)

            return true
        })
    }

    return nil, nil
}

That's the output I'm getting:

call expression &{Fun:foo Lparen:6160580 Args:[c 0xc0003c5780 0xc0003c57c0] Ellipsis:0 Rparen:6160596}
signature: func(ctx context.Context, n int, str string) - *types.Signature
Type :  *types.Named
named : *types.Named
named.Obj() : *types.TypeName
typ:  *types.Interface


问:
Antenna House Invalid property value: column-width="proportional-column-width(4%)"
I'm get the following warning from antenna house.

```<code>AHFCmd :WARNING: Error Level : 2
AHFCmd :WARNING: Error Code  : 10761 (2A09)
AHFCmd :WARNING: Invalid property value: column-width="proportional-column-width(4%)".
</code>```

from the code

```<code>  <fo:table-column column-number="1" column-width="proportional-column-width(4%)"/>
</code>```

The website seems to suggest that proportional-column-width is supported

Regards
Conteh

答:
proportional-column-width(4) would work. proportional-column-width(4%) will not.

If you want the column to be 4% of the available width, use column-width="4%" (see https://www.w3.org/TR/xsl11/#column-width).

I think that you are the first person that I have seen try to use a percentage rather than a number with proportional-column-width(), and you have just blown my mind.

A strict reading of the XSL 1.1 definition of 'numeric' and of the proportional-column-width() function prototype in the XSL 1.1 Recommendation (https://www.w3.org/TR/xsl11/#d0e5961):

numeric proportional-column-width(numeric)

would indicate that a percentage is a valid value because a percentage is a relative numeric. Mind blown. Presumably every proportional-column-width() within the same table would need to be a relative numeric value so that they can all be added together. However, that could lead to nonsensical definitions such as:

```<code><fo:table layout="fixed" width="100%">
  <fo:table-column column=width="proportional-column-width(4%)" />
  <fo:table-column column=width="proportional-column-width(4%)" />
  <fo:table-body>...</fo:table-body>
</fo:table>
</code>```

where the two '4%' columns each take 50% of the width.

Fortunately for my sanity, the definition of proportional-column-width() includes:

The difference between the table-width and the sum of the column widths is the available proportional width. One unit of proportional measure is the available proportional width divided by the sum of the proportional factors.

If the proportional widths were all relative numerics (which are really lengths), then dividing the available proportional width by a length would yield a unit-less number. A unit-less number wouldn't work as the result of proportional-column-width(), so you're back to needing proportional-column-width() values being only numbers so that the function can return widths.

Body:
I'm get the following warning from antenna house.

AHFCmd :WARNING: Error Level : 2
AHFCmd :WARNING: Error Code  : 10761 (2A09)
AHFCmd :WARNING: Invalid property value: column-width="proportional-column-width(4%)".

from the code

  <fo:table-column column-number="1" column-width="proportional-column-width(4%)"/>

The website seems to suggest that proportional-column-width is supported

Regards
Conteh

Body:
proportional-column-width(4) would work. proportional-column-width(4%) will not.

If you want the column to be 4% of the available width, use column-width="4%" (see https://www.w3.org/TR/xsl11/#column-width).

I think that you are the first person that I have seen try to use a percentage rather than a number with proportional-column-width(), and you have just blown my mind.

A strict reading of the XSL 1.1 definition of 'numeric' and of the proportional-column-width() function prototype in the XSL 1.1 Recommendation (https://www.w3.org/TR/xsl11/#d0e5961):

numeric proportional-column-width(numeric)

would indicate that a percentage is a valid value because a percentage is a relative numeric. Mind blown. Presumably every proportional-column-width() within the same table would need to be a relative numeric value so that they can all be added together. However, that could lead to nonsensical definitions such as:

<fo:table layout="fixed" width="100%">
  <fo:table-column column=width="proportional-column-width(4%)" />
  <fo:table-column column=width="proportional-column-width(4%)" />
  <fo:table-body>...</fo:table-body>
</fo:table>

where the two '4%' columns each take 50% of the width.

Fortunately for my sanity, the definition of proportional-column-width() includes:

The difference between the table-width and the sum of the column widths is the available proportional width. One unit of proportional measure is the available proportional width divided by the sum of the proportional factors.

If the proportional widths were all relative numerics (which are really lengths), then dividing the available proportional width by a length would yield a unit-less number. A unit-less number wouldn't work as the result of proportional-column-width(), so you're back to needing proportional-column-width() values being only numbers so that the function can return widths.


问:
HEREMaps with SwiftUI crashes with EXC_BAD_INSTRUCTION upon instantiation
I'm attempting to use HEREMaps with SwiftUI via UIViewRepresentable and I'm getting the following crash when instantiating NMAMapView. Using HEREMaps version 3.13.3 pod.

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

```<code>import SwiftUI
import NMAKit

struct MapView: UIViewRepresentable {

    func makeUIView(context: Context) -> NMAMapView {
        let mapView = NMAMapView()
        return mapView
    }

    func updateUIView(_ uiView: NMAMapView, context: Context) {

    }
}

struct ContentView: View {
    var body: some View {
        MapView()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

Also, no luck with adding NSLocationWhenInUseUsageDescription to my Inof.plist

答:
This is HERE SDK issue. Unfortunately no workarounds found yet.

Fix will be included in next HERE SDK Release(3.15), which is planned on April 1, 2020.

Thanks for reporting!

Body:
I'm attempting to use HEREMaps with SwiftUI via UIViewRepresentable and I'm getting the following crash when instantiating NMAMapView. Using HEREMaps version 3.13.3 pod.

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

import SwiftUI
import NMAKit

struct MapView: UIViewRepresentable {

    func makeUIView(context: Context) -> NMAMapView {
        let mapView = NMAMapView()
        return mapView
    }

    func updateUIView(_ uiView: NMAMapView, context: Context) {

    }
}

struct ContentView: View {
    var body: some View {
        MapView()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Also, no luck with adding NSLocationWhenInUseUsageDescription to my Inof.plist


问:
How can I adjust the cross tab order using a formula in Crystal Reports
I am trying to organize my cross tab labels in a specified order. The table shows students that have left the school by grade level and year. Grade level is dependant on an if - then formula because the database does not have the grade that students left the school. The grade level is calculated by subtracting the withdrawal year from their grad year and then applying a text string based on the result.

When I try to adjust to a specific order there is no option to select the individual groupings as my formula is not available in the common tab. The labels in the column are accurate but just out of order.

Any help would be greatly appreciated. I am fairly new to Crystal reports. Perhaps I am not understanding how a cross tab works or perhaps there are problems with my formula.

current view of order

Cross tab expert view

答: Easiest solution is to change the formula that generates the labels so they sort alphabetically as you wish. You can pad the numbers with a zero so that '1' becomes '01' or prepend the text with a counter (01., 02., etc.).</p>


问:
Picking order details from database in an interval
I want to pull orders that have been placed in between (last 5 mins - last 10 mins). For that I am running a query:

```<code>$query="SELECT * FROM orders where `orderStatus`='PARTIAL' and `timeCreated` >= date_sub(now(),interval 10 minute)";
</code>```

However, this query is picking data from between (last 0 mins - last 10 mins).

Can you please help what should I try?

答:
Just add another filtering condition:

```<code>SELECT *
FROM orders
WHERE
    orderStatus = 'PARTIAL'
    AND timeCreated >= date_sub(now(), interval 10 minute)
    AND timeCreated <  date_sub(now(), interval 5 minute);
</code>```

Assuming that you are using MySQL (the syntax of your existing query suggests it), you can also phrase the query using the following date arithmetics, which I find more straight-forward:

```<code>SELECT *
FROM orders
WHERE
    orderStatus = 'PARTIAL'
    AND timeCreated >= now() - interval 10 minute
    AND timeCreated < now() - interval 5 minute
</code>```

Body:
I want to pull orders that have been placed in between (last 5 mins - last 10 mins). For that I am running a query:

$query="SELECT * FROM orders where `orderStatus`='PARTIAL' and `timeCreated` >= date_sub(now(),interval 10 minute)";

However, this query is picking data from between (last 0 mins - last 10 mins).

Can you please help what should I try?

Body:
Just add another filtering condition:

SELECT *
FROM orders
WHERE
    orderStatus = 'PARTIAL'
    AND timeCreated >= date_sub(now(), interval 10 minute)
    AND timeCreated <  date_sub(now(), interval 5 minute);

Assuming that you are using MySQL (the syntax of your existing query suggests it), you can also phrase the query using the following date arithmetics, which I find more straight-forward:

SELECT *
FROM orders
WHERE
    orderStatus = 'PARTIAL'
    AND timeCreated >= now() - interval 10 minute
    AND timeCreated < now() - interval 5 minute


问:
In a vectorized way in numpy: Cutting out chunks of data (of different sizes) conditionally dependent on whats inside the chunk
I have a vector of integers (a 1D numpy array) that looks like:

8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1
```

<p>(In a vectorized way,) I want to filter out all of the data between 8's that contain at least one 99 value.  </p>

<p>So in this example, the data I want to cut out is listed in bold:</p>

```8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1```

<p>(i.e., it's data that's inbetween the 8's that contains at least one 99)</p>

<p>So if I made a boolean mask to crop out this data it would look like:</p>

```Data: 8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1
Mask: T, T, T, T, F,  F, F, F, F, F, T, T, T, T, F,  F,  F, T, T, T```

<p>And data after cropping look like:</p>

<pre class="lang-none prettyprint-override"><code>Data(Mask) = 8, 1, 1, 2, 8, 2, 2, 2, 8, 1, 1
</code>```

I can come up with vectorized code that can do this if there is a guaranteed equal spacing between the 8's. Here's that code:

```<code>inputRaw = np.array([8, 2, 3, 2, 99, 2, 8, 2, 3, 2, 2, 2, 8, 2, 3, 3, 3, 3])
inputPartitioned = np.reshape(inputRaw, (3, 6))
# reshaping it into an array of the form: np.array([[8, 2, 3, 2, 99, 2], [8, 2, 3, 2, 2, 2], [8, 2, 3, 3, 3, 3]])
selectedSections = np.logical_not(np.any(inputPartitioned>8, axis=1))
outputPartitioned = inputPartitioned[selectedSections]
outputFlattened = outputPartitioned.flatten()
</code>```

One extra thing that I need is a mask or index that tells me (in the original indices) the data that was cropped. (I need this because I have a second array I want to keep track of that has shared indices with the first array). I can code this mask (assumming equal spacing between the 8's) like so:

```<code>inputIndex = np.arange(inputRaw.size)
inputIndexPartitioned =  np.reshape(inputIndex, (3, 6))
outputPartitionedIndex = inputIndexPartitioned[selectedSections]
outputFlattenedIndex = outputPartitionedIndex.flatten()
</code>```

But I'm not sure how to do this in a vectorized way in the case where there's unequal spacing between the 8's.

Any ideas? These arrays are very long, so solutions that work fast for large arrays are helpful. Also, I'm fairly confident that these "99's" will always immediately after an 8, so maybe that might be helpful information in making the algorithm.

答:
This should do the trick (I've avoided the "fairly confident" part, so it will run even if 99 is not immediately after an 8).</p>

```<code>import numpy as np

in_arr = np.array([8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1])

mask_8 = in_arr == 8
mask_8_cumsum = np.cumsum(mask_8)
print(mask_8_cumsum)
>>> [1 1 1 1 2 2 2 2 2 2 3 3 3 3 4 4 4 5 5 5]

unique_inds = np.unique(mask_8_cumsum[in_arr == 99])
print(unique_inds)
>>> [2 4]

final_mask = ~np.isin(mask_8_cumsum, unique_inds)
final_data = in_arr[final_mask]
print(final_mask)
>>> [ True  True  True  True False False False False False False  True  True
  True  True False False False  True  True  True]

print(final_data)
>>> [8 1 1 2 8 2 2 2 8 1 1]
</code>```

Body:
I have a vector of integers (a 1D numpy array) that looks like:

8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1

(In a vectorized way,) I want to filter out all of the data between 8's that contain at least one 99 value.

So in this example, the data I want to cut out is listed in bold:

8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1

(i.e., it's data that's inbetween the 8's that contains at least one 99)

So if I made a boolean mask to crop out this data it would look like:

Data: 8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1
Mask: T, T, T, T, F,  F, F, F, F, F, T, T, T, T, F,  F,  F, T, T, T

And data after cropping look like:

Data(Mask) = 8, 1, 1, 2, 8, 2, 2, 2, 8, 1, 1

I can come up with vectorized code that can do this if there is a guaranteed equal spacing between the 8's. Here's that code:

inputRaw = np.array([8, 2, 3, 2, 99, 2, 8, 2, 3, 2, 2, 2, 8, 2, 3, 3, 3, 3])
inputPartitioned = np.reshape(inputRaw, (3, 6))
# reshaping it into an array of the form: np.array([[8, 2, 3, 2, 99, 2], [8, 2, 3, 2, 2, 2], [8, 2, 3, 3, 3, 3]])
selectedSections = np.logical_not(np.any(inputPartitioned>8, axis=1))
outputPartitioned = inputPartitioned[selectedSections]
outputFlattened = outputPartitioned.flatten()

One extra thing that I need is a mask or index that tells me (in the original indices) the data that was cropped. (I need this because I have a second array I want to keep track of that has shared indices with the first array). I can code this mask (assumming equal spacing between the 8's) like so:

inputIndex = np.arange(inputRaw.size)
inputIndexPartitioned =  np.reshape(inputIndex, (3, 6))
outputPartitionedIndex = inputIndexPartitioned[selectedSections]
outputFlattenedIndex = outputPartitionedIndex.flatten()

But I'm not sure how to do this in a vectorized way in the case where there's unequal spacing between the 8's.

Any ideas? These arrays are very long, so solutions that work fast for large arrays are helpful. Also, I'm fairly confident that these "99's" will always immediately after an 8, so maybe that might be helpful information in making the algorithm.

Body:
This should do the trick (I've avoided the "fairly confident" part, so it will run even if 99 is not immediately after an 8).

import numpy as np

in_arr = np.array([8, 1, 1, 2, 8, 99, 1, 2, 1, 2, 8, 2, 2, 2, 8, 99, 99, 8, 1, 1])

mask_8 = in_arr == 8
mask_8_cumsum = np.cumsum(mask_8)
print(mask_8_cumsum)
>>> [1 1 1 1 2 2 2 2 2 2 3 3 3 3 4 4 4 5 5 5]

unique_inds = np.unique(mask_8_cumsum[in_arr == 99])
print(unique_inds)
>>> [2 4]

final_mask = ~np.isin(mask_8_cumsum, unique_inds)
final_data = in_arr[final_mask]
print(final_mask)
>>> [ True  True  True  True False False False False False False  True  True
  True  True False False False  True  True  True]

print(final_data)
>>> [8 1 1 2 8 2 2 2 8 1 1]


问:
How to remove unnecessary numbers in DateTime
So, when I print DateTime.now() value, it shows those unnecessary numbers(on the screen the numbers are 323884). Is there any possibility on removing those numbers?
enter image description here</p>

答:
You need to use the DateFormat class.

First import intl package:

```<code>import 'dart:intl';
</code>```

The use it like this:

```<code>print(DateFormat.yMd().format(new DateTime.now()));
</code>```

You can use any format you'd like. See the docs for more formats

Body:
You need to use the DateFormat class.

First import intl package:

import 'dart:intl';

The use it like this:

print(DateFormat.yMd().format(new DateTime.now()));

You can use any format you'd like. See the docs for more formats


问:
Jobs status: Failed. But no errors
In the Dataflow UI the Job status is Failed. The Job Logs is empty, the Worker Logs is empty and the Job Error Reporting is empty. StackDriver is completely empty.

How to find out what went wrong?

答:
If the job was marked as failed, it means that Dataflow does received it. Please double check the existence of the logs by following the troubleshooting steps. In addition, I recommend paying attention in the Job Graph to see where exactly the job failed and review the details of a specific step.

If the link above confirms that there are not logs, you should check that ingestion Stackdriver logs was not stopped. To verify if logs are ingested in Stackdriver, you can access Logging Viewer directly and search for Dataflow logs and the failed job id.

Finally, if steps above don't help, I strongly recommend filing a support ticked to GCP for further assistance on your specific job.

Title: Jobs status: Failed. But no errors


问:
Is there a safe, ergonomic way to change a phantom type in a complex struct?
Suppose we define a generic struct, with many fields, representing a type-safe state machine using a phantom type:

struct Foo<State> {
    a: A,
    b: B,
    c: C,
    //...
    state: PhantomData<State>,
}
```

<p>We can then write a type-safe state transition:</p>

```impl Foo<SourceState> {
    fn transition(self, extra: X) -> Foo<DestinationState> {
        let Foo {a, b, c, state: _} = self;
        // do lots of stuff
        Foo { a, b, c, state: PhantomData }
    }
}
```

But we need to awkwardly unpack every field and re-pack in in a different structure.

We could also use mem::transmute, although my understanding is that different monomorphizations of the same struct are not guaranteed to have the same memory layout.

I hoped that Foo { state: PhantomData, ..self } would work; alas, it fails to compile.

Is there any canonical, ergonomic, safe way to write this ?

答:
There is no way to do that in a straight forward manner, because they are 2 different types: that's the whole point of your code, actually. To simplify it, I'd do that in 2 steps, with a generic transition being the 2nd one:

```<code>use core::marker::PhantomData;

struct Foo<State> {
    a: i32,
    b: i32,
    c: i32,
    //...
    state: PhantomData<State>,
}

struct SourceState;
struct DestinationState;

impl<Src> Foo<Src> {
    fn transition<Dest>(self) -> Foo<Dest> {
        let Foo {a, b, c, state: _} = self;

        Foo { a, b, c, state: PhantomData }
    }
}

impl Foo<SourceState> {
    fn to_destination_state(mut self, extra: ()) -> Foo<DestinationState> {
        // Do whatever you want with self

        self.transition()
    }
}
</code>```

Alternatively, you can abstract the fact that you have a state:

```<code>mod stateful {
    use core::marker::PhantomData;

    pub struct Stateful<T, State> {
        pub data: T,
        state: PhantomData<State>,
    }

    impl<T, SrcState> Stateful<T, SrcState> {
        pub fn transform<DestState>(self) -> Stateful<T, DestState> {
            let Stateful { data, state: _ } = self;

            Stateful {
                data,
                state: Default::default(),
            }
        }
    }
}

struct Data {
    a: i32,
    b: i32,
    c: i32,
}

struct SourceState;
struct DestinationState;

type Foo<State> = stateful::Stateful<Data, State>;

impl Foo<SourceState> {
    fn to_destination_state(mut self, extra: ()) -> Foo<DestinationState> {
        // Do whatever you want with self.data

        self.transform()
    }
}
</code>```

Body:
Suppose we define a generic struct, with many fields, representing a type-safe state machine using a phantom type:

struct Foo<State> {
    a: A,
    b: B,
    c: C,
    //...
    state: PhantomData<State>,
}

We can then write a type-safe state transition:

impl Foo<SourceState> {
    fn transition(self, extra: X) -> Foo<DestinationState> {
        let Foo {a, b, c, state: _} = self;
        // do lots of stuff
        Foo { a, b, c, state: PhantomData }
    }
}

But we need to awkwardly unpack every field and re-pack in in a different structure.

We could also use mem::transmute, although my understanding is that different monomorphizations of the same struct are not guaranteed to have the same memory layout.

I hoped that Foo { state: PhantomData, ..self } would work; alas, it fails to compile.

Is there any canonical, ergonomic, safe way to write this ?

Body:
There is no way to do that in a straight forward manner, because they are 2 different types: that's the whole point of your code, actually. To simplify it, I'd do that in 2 steps, with a generic transition being the 2nd one:

use core::marker::PhantomData;

struct Foo<State> {
    a: i32,
    b: i32,
    c: i32,
    //...
    state: PhantomData<State>,
}

struct SourceState;
struct DestinationState;

impl<Src> Foo<Src> {
    fn transition<Dest>(self) -> Foo<Dest> {
        let Foo {a, b, c, state: _} = self;

        Foo { a, b, c, state: PhantomData }
    }
}

impl Foo<SourceState> {
    fn to_destination_state(mut self, extra: ()) -> Foo<DestinationState> {
        // Do whatever you want with self

        self.transition()
    }
}

Alternatively, you can abstract the fact that you have a state:

mod stateful {
    use core::marker::PhantomData;

    pub struct Stateful<T, State> {
        pub data: T,
        state: PhantomData<State>,
    }

    impl<T, SrcState> Stateful<T, SrcState> {
        pub fn transform<DestState>(self) -> Stateful<T, DestState> {
            let Stateful { data, state: _ } = self;

            Stateful {
                data,
                state: Default::default(),
            }
        }
    }
}

struct Data {
    a: i32,
    b: i32,
    c: i32,
}

struct SourceState;
struct DestinationState;

type Foo<State> = stateful::Stateful<Data, State>;

impl Foo<SourceState> {
    fn to_destination_state(mut self, extra: ()) -> Foo<DestinationState> {
        // Do whatever you want with self.data

        self.transform()
    }
}


问:
$this->session->set_userdata() not working in codeigniter
The application has been working perfectly for over two years, only for me not to be able to log into the web app. I discovered that $this->session->set_userdata() is not working.
I input my credentials and i get redirected back to the login page. I tried to used an statement on the set_userdata() and found out that it is not working. My code is shown below </p>

```<code>/* Autoload.php*/
$autoload['libraries'] = array('database', 'email', 'session');
</code>```

```<code>/* Config.php */
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = BASEPATH.'sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

/* Login Controller */
public function verify_login(){
        $this->load->library('session');
        $pass = $this->input->post('password');
        $username = $this->input->post('username');
        $action = 'Login';
        if($this->admodel->Check_Login_In_DB($username,$pass)){
            $sess_array = array();
            $sess_array = array(
            'uid' =>  $this->admodel->getUidByUsername($username),
            'username' => $username
       );
       $this->session->set_userdata($sess_array);
       $this->admodel->insertLog($action,$this->admodel->getUidByUsername($username));
       redirect(base_url(), 'refresh');
        }else{
        $this->session->set_flashdata('msg','<div style="color:#b94a48;
        background-color:#f2dede;border-color:#eed3d7;height:auto;padding:5px;border-radius:3px;margin-bottom:7px;
        clear:both">The Email and Password Combination is not found in the database,Check Properly and try again !!!</div>');
            redirect(base_url().'login','refresh');
        }

    }

/* Homepage */
public function index(){

        if(!$this->session->userdata('uid')){

            $this->session->set_flashdata('msg','<div style="color: #b94a48;background-color:

            #f2dede;border-color: #eed3d7;height:auto;padding:5px;border-radius:3px;clear:both;margin-bottom:10px">

            You need to signin to continue !!!</div>');

            redirect(base_url().'login','refresh');

        }
</code>```

答:
Please change the session syntax like that.

```<code>$this->session->set_userdata('user_session',$sess_array);
</code>```

It will work.

Body:
The application has been working perfectly for over two years, only for me not to be able to log into the web app. I discovered that $this->session->set_userdata() is not working.
I input my credentials and i get redirected back to the login page. I tried to used an statement on the set_userdata() and found out that it is not working. My code is shown below

/* Autoload.php*/
$autoload['libraries'] = array('database', 'email', 'session');

/* Config.php */
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = BASEPATH.'sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

/* Login Controller */
public function verify_login(){
        $this->load->library('session');
        $pass = $this->input->post('password');
        $username = $this->input->post('username');
        $action = 'Login';
        if($this->admodel->Check_Login_In_DB($username,$pass)){
            $sess_array = array();
            $sess_array = array(
            'uid' =>  $this->admodel->getUidByUsername($username),
            'username' => $username
       );
       $this->session->set_userdata($sess_array);
       $this->admodel->insertLog($action,$this->admodel->getUidByUsername($username));
       redirect(base_url(), 'refresh');
        }else{
        $this->session->set_flashdata('msg','
The Email and Password Combination is not found in the database,Check Properly and try again !!!
');
            redirect(base_url().'login','refresh');
        }

    }

/* Homepage */
public function index(){

        if(!$this->session->userdata('uid')){

            $this->session->set_flashdata('msg','

            You need to signin to continue !!!
');

            redirect(base_url().'login','refresh');

        }

Body:
Please change the session syntax like that.

$this->session->set_userdata('user_session',$sess_array);

It will work.


问:
Strategy to refactor when too many dependencies injected into service or controller
I have an ASP.NET MVC 1 application that uses NHibernate and Castle Windsor for IoC. The controllers have service classes injected, and these service classes handle all the logic and actions required by the app. The service classes have repositories injected. Each repository handles a single object. Objects are mapped to DB table via NH. I have tried to keep a one to one relationship between services and controllers, but some services are used in more than one controller.

The problem is that some services now have dependencies on 10-15 repositories. The system has an invoicing component for example, where certain actions depend on users, customers, work orders, work order line items, invoices, invoice line items, taxes, etc.

What strategies do people used to refactor effectively when it comes to dependency overload? I'm thinking of splitting one service into many services and to remove the 1-to-1 attempt between services and controllers. But then dependencies at the controller level will increase. Splitting one controller into many controllers is possible with the prior suggestion, but I don't believe that's done unless you break views into partial views? I realize this is a broad question, but I'm more looking for guidance than exact answers. Feel free to provide links to articles or examples of similar refactoring.

答:
Your repository approach is flawed. Instead of having a repository for each and every entity type in your application, you should focus on your root entities. Pick a few entities that are the top level entities in your application and build your repositories around them. E.G. work order line items likely don't need their own repository, as they can't exist on their own without a work order.

Another thing you've likely created in your design is a very anemic domain layer. So your entities are pretty much just POCO objects, while all of the business logic is contained in your service layer. Consider moving some or most of that logic into the domain.


问:
invalid literal for int() with base 10 : '(1,2,3,4,5,6,7)'
```<code>tuple1 = int(input())
list1 = list()
for i in tuple1:
    if tuple1[i-1] % 2 == 0:
        list1.append(tuple1[i-1])
tuple2 = tuple(list1)
print(tuple2)
</code>```

I'm getting error as

invalid literal for int() with base 10 : '(1,2,3,4,5,6,7)'

答:
use range() in input()

```<code>tuple1 = range(int(input()))
</code>```

You can't make iteration in a number, when you use the range() method, you can iterate over it.

Body:
tuple1 = int(input())
list1 = list()
for i in tuple1:
    if tuple1[i-1] % 2 == 0:
        list1.append(tuple1[i-1])
tuple2 = tuple(list1)
print(tuple2)

I'm getting error as

invalid literal for int() with base 10 : '(1,2,3,4,5,6,7)'

Body:
use range() in input()

tuple1 = range(int(input()))

You can't make iteration in a number, when you use the range() method, you can iterate over it.