问:
How to remove authentication for introspection query in Graphql
so may be this is very basic question so please bear with me. Let me explain what I am doing and what I really need.

EXPLANATION

I have created a graphql server by using ApolloGraphql (apollo-server-express npm module).

Here is the code snippet to give you an idea.

api.js

```<code>import express from 'express'
import rootSchema from './root-schema'
.... // some extra code
app = express.router()
app.use(jwtaAuthenticator) // --> this code authenticates Authorization header
.... // some more middleware's added
const graphQLServer = new ApolloServer({
  schema: rootSchema, // --> this is root schema object
  context: context => context,
  introspection: true,
})
graphQLServer.applyMiddleware({ app, path: '/graphql' })
</code>```

server.js

```<code>import http from 'http'
import express from 'express'
import apiRouter from './api' // --> the above file
const app = express()
app.use([some middlewares])
app.use('/', apiRouter)
....
....
export async function init () {

try {
  const httpServer = http.createServer(app)
  httpServer
    .listen(PORT)
    .on('error', (err) => { setTimeout(() => process.exit(1), 5000) })
  } catch (err) {
    setTimeout(() => process.exit(1), 5000)
  }
  console.log('Server started --- ', PORT)
}
export default app
</code>```

index.js

```<code>require('babel-core')
require('babel-polyfill')
require = require('esm')(module/* , options */)
const server = require('./server.js') // --> the above file

server.init()
</code>```

PROBLEM STATEMENT

I am using node index.js to start the app. So, the app is expecting Authorization header (JWT token) to be present all the times, even for the introspection query. But this is not what I want, I want that introspection query will be resolvable even without the token. So that anyone can see the documentation.

Please shed some light and please guide what is the best approach to do so. Happy coding :)

答:
There's a ton of different ways to handle authorization in GraphQL, as illustrated in the docs:

Adding middleware for express (or some other framework like hapi or koa)

Checking for authorization inside individual resolvers

Checking for authorization inside your data models

Utilizing custom directives

Adding express middleware is great for preventing unauthorized access to your entire schema. If you want to allow unauthenticated access to some fields but not others, it's generally recommended you move your authorization logic from the framework layer to the GraphQL or data model layer using one of the methods above.

Body:
so may be this is very basic question so please bear with me. Let me explain what I am doing and what I really need.

EXPLANATION

I have created a graphql server by using ApolloGraphql (apollo-server-express npm module).

Here is the code snippet to give you an idea.

api.js

import express from 'express'
import rootSchema from './root-schema'
.... // some extra code
app = express.router()
app.use(jwtaAuthenticator) // --> this code authenticates Authorization header
.... // some more middleware's added
const graphQLServer = new ApolloServer({
  schema: rootSchema, // --> this is root schema object
  context: context => context,
  introspection: true,
})
graphQLServer.applyMiddleware({ app, path: '/graphql' })

server.js

import http from 'http'
import express from 'express'
import apiRouter from './api' // --> the above file
const app = express()
app.use([some middlewares])
app.use('/', apiRouter)
....
....
export async function init () {

try {
  const httpServer = http.createServer(app)
  httpServer
    .listen(PORT)
    .on('error', (err) => { setTimeout(() => process.exit(1), 5000) })
  } catch (err) {
    setTimeout(() => process.exit(1), 5000)
  }
  console.log('Server started --- ', PORT)
}
export default app

index.js

require('babel-core')
require('babel-polyfill')
require = require('esm')(module/* , options */)
const server = require('./server.js') // --> the above file

server.init()

PROBLEM STATEMENT

I am using node index.js to start the app. So, the app is expecting Authorization header (JWT token) to be present all the times, even for the introspection query. But this is not what I want, I want that introspection query will be resolvable even without the token. So that anyone can see the documentation.

Please shed some light and please guide what is the best approach to do so. Happy coding :)


来源: stackexchange

问:
Error: 0xC002F210 (can't import a database in my SQL Server)
I have SQL Server 2014 installed on my PC, working on a same project in my company, a worker send me a database to import.

I followed the steps described here, but I get this error :

Error 0xc002f210: Preparation SQL Task 1: Executing the query "CREATE TABLE [dbo].[~TMPCLP14521] (

  [Champ1] nvar..." failed with the following error: "Culture is not supported.

  Parameter name: culture

  3072 (0x0c00) is an invalid culture identifier.".

Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

What is wrong?

答:
Solved , after reading  this issue i found that in order to make the import work ,apparently ,the sqlserver and the system should have the same language format ;

My Sql Server is in french ,my windows was in english format changing it to french format in setting>region>region format solved my problem.

ContentLicense: CC BY-SA 4.0


问:
Linux alias question
I want to create an alias for this command "rmi" so that if I execute

```<code>rmi File.txt
</code>```

it will actually execute

```<code>ls * | grep -v File.txt | xargs rm -rf
</code>```

Basically I want to reorder arguments.

答:
thanks for clarifying this.  In tcsh it's easy:

```<code>alias rmi 'ls * | grep -v \! | xargs rm -rf'
</code>```

this should do it...

```<code>\!
</code>```

expands all arguments following "rmi"

you could also use "find" to do this..

```<code>find . -type f | grep -v \! | xargs rm -rf'
</code>```

... be careful with that axe! (rm -rf)

ContentLicense: CC BY-SA 3.0

Title: Linux alias question

Body:
I want to create an alias for this command "rmi" so that if I execute

rmi File.txt

it will actually execute

ls * | grep -v File.txt | xargs rm -rf

Basically I want to reorder arguments.

Body:
thanks for clarifying this.  In tcsh it's easy:

alias rmi 'ls * | grep -v \! | xargs rm -rf'

this should do it...

\!

expands all arguments following "rmi"

you could also use "find" to do this..

find . -type f | grep -v \! | xargs rm -rf'

... be careful with that axe! (rm -rf)


Title: Plotting a histogram using a range of values and their frequency as a dictionary

Body:
Assume that I have the following dictionary:

scenario_summary = {'Day1': {'22459-22585': 0.0, '22585-22711': 0.0, '22711-22837': 0.0, '22837-22963': 0.0, '22963-23089': 0.0, '23089-23215': 0.0, '23215-23341': 0.0, '23341-23467': 0.0, '23467-23593': 0.0, '23593-23719': 0.0, '23719-23845': 0.0, '23845-23971': 0.0, '23971-24097': 0.0, '24097-24223': 0.0, '24223-24349': 0.0, '24349-24475': 0.0, '24475-24601': 0.0, '24601-24727': 0.0, '24727-24853': 0.0, '24853-24979': 0.0, '24979-25105': 0.0, '25105-25231': 0.0, '25231-25357': 0.0, '25357-25483': 0.0, '25483-25609': 0.0, '25609-25735': 0.0, '25735-25861': 0.0, '25861-25987': 0.0, '25987-26113': 1.0, '26113-26239': 1.0, '26239-26365': 0.0, '26365-26491': 2.0, '26491-26617': 5.0, '26617-26743': 5.0, '26743-26869': 5.0, '26869-26995': 12.0, '26995-27121': 19.0, '27121-27247': 7.000000000000001, '27247-27373': 11.0, '27373-27499': 15.0, '27499-27625': 7.000000000000001, '27625-27751': 4.0, '27751-27877': 4.0, '27877-28003': 2.0, '28003-28129': 0.0, '28129-28255': 0.0, '28255-28381': 0.0, '28381-28507': 0.0, '28507-28633': 0.0, '28633-28759': 0.0, '28759-28885': 0.0, '28885-29011': 0.0, '29011-29137': 0.0, '29137-29263': 0.0, '29263-29389': 0.0, '29389-29515': 0.0, '29515-29641': 0.0, '29641-29767': 0.0, '29767-29893': 0.0, '29893-30019': 0.0, '30019-30145': 0.0, '30145-30271': 0.0, '30271-30397': 0.0, '30397-30523': 0.0, '30523-30649': 0.0, '30649-30775': 0.0, '30775-30901': 0.0, '30901-31027': 0.0, '31027-31153': 0.0, '31153-31279': 0.0, '31279-31405': 0.0, '31405-31531': 0.0, '31531-31657': 0.0, '31657-31783': 0.0, '31783-31909': 0.0, '31909-32035': 0.0, '32035-32161': 0.0, '32161-32287': 0.0, '32287-32413': 0.0, '32413-32539': 0.0, '32539-32665': 0.0, '32665-32791': 0.0, '32791-32917': 0.0, '32917-33043': 0.0, '33043-33169': 0.0, '33169-33295': 0.0, '33295-33421': 0.0, '33421-33547': 0.0, '33547-33673': 0.0, '33673-33799': 0.0, '33799-33925': 0.0, '33925-34051': 0.0, '34051-34177': 0.0, '34177-34303': 0.0, '34303-34429': 0.0, '34429-34555': 0.0, '34555-34681': 0.0, '34681-34807': 0.0}}

As you can see, the dictionary consists of a range of values in string and their frequency. I would like to plot this as a histogram, but I don't know how I would be able to transform the string into a form that pandas or plotly would understand. What would your approach be? Or is there an easier way to do it, instead of hardcoding things? Or, would another module be easier option in doing so?

Thanks!

Body:
A histogram is basically a simple bar chart, where each bar represents a bin (usually in the form of a range) and a frequency of the elements that fall into that bin.

This is exactly the data that you already have. So instead of computing values for a histogram (as it would be done with plt.hist), you can simply pass your data to plt.bar, as it is. The result would then be this:

The code with your data, as a MCVE :

import matplotlib.pyplot as plt

scenario_summary = { 'Day1': {
    '22459-22585': 0.0, '22585-22711': 0.0, '22711-22837': 0.0,
    '22837-22963': 0.0, '22963-23089': 0.0, '23089-23215': 0.0,
    '23215-23341': 0.0, '23341-23467': 0.0, '23467-23593': 0.0,
    '23593-23719': 0.0, '23719-23845': 0.0, '23845-23971': 0.0,
    '23971-24097': 0.0, '24097-24223': 0.0, '24223-24349': 0.0,
    '24349-24475': 0.0, '24475-24601': 0.0, '24601-24727': 0.0,
    '24727-24853': 0.0, '24853-24979': 0.0, '24979-25105': 0.0,
    '25105-25231': 0.0, '25231-25357': 0.0, '25357-25483': 0.0,
    '25483-25609': 0.0, '25609-25735': 0.0, '25735-25861': 0.0,
    '25861-25987': 0.0, '25987-26113': 1.0, '26113-26239': 1.0,
    '26239-26365': 0.0, '26365-26491': 2.0, '26491-26617': 5.0,
    '26617-26743': 5.0, '26743-26869': 5.0, '26869-26995': 12.0,
    '26995-27121': 19.0, '27121-27247': 7.0, '27247-27373': 11.0,
    '27373-27499': 15.0, '27499-27625': 7.0, '27625-27751': 4.0,
    '27751-27877': 4.0, '27877-28003': 2.0, '28003-28129': 0.0,
    '28129-28255': 0.0, '28255-28381': 0.0, '28381-28507': 0.0,
    '28507-28633': 0.0, '28633-28759': 0.0, '28759-28885': 0.0,
    '28885-29011': 0.0, '29011-29137': 0.0, '29137-29263': 0.0,
    '29263-29389': 0.0, '29389-29515': 0.0, '29515-29641': 0.0,
    '29641-29767': 0.0, '29767-29893': 0.0, '29893-30019': 0.0,
    '30019-30145': 0.0, '30145-30271': 0.0, '30271-30397': 0.0,
    '30397-30523': 0.0, '30523-30649': 0.0, '30649-30775': 0.0,
    '30775-30901': 0.0, '30901-31027': 0.0, '31027-31153': 0.0,
    '31153-31279': 0.0, '31279-31405': 0.0, '31405-31531': 0.0,
    '31531-31657': 0.0, '31657-31783': 0.0, '31783-31909': 0.0,
    '31909-32035': 0.0, '32035-32161': 0.0, '32161-32287': 0.0,
    '32287-32413': 0.0, '32413-32539': 0.0, '32539-32665': 0.0,
    '32665-32791': 0.0, '32791-32917': 0.0, '32917-33043': 0.0,
    '33043-33169': 0.0, '33169-33295': 0.0, '33295-33421': 0.0,
    '33421-33547': 0.0, '33547-33673': 0.0, '33673-33799': 0.0,
    '33799-33925': 0.0, '33925-34051': 0.0, '34051-34177': 0.0,
    '34177-34303': 0.0, '34303-34429': 0.0, '34429-34555': 0.0,
    '34555-34681': 0.0, '34681-34807': 0.0}}

data = scenario_summary['Day1']

x = range(len(data))
y = list(data.values())

plt.figure(figsize=(16, 9))
plt.bar(x, y)
plt.subplots_adjust(bottom=0.2)
plt.xticks(x, data.keys(), rotation='vertical')
plt.show()


问:
How to find the number of times a string occurs in a text file?
I'm trying to count the number of times a string occurs in a file of strings.

```<code>data=open('xyz.txt')
num=[]
    while 1:
        numrow=[]
        count=0
        x=data.readline()
        if x=='':
            break
        for line in data:
            if line==x:
                count+=1
        numrow.append(x)
        numrow.append(count)
        num.append(numrow)
    print(num)
</code>```

When I try the code above, I keep getting the wrong count. Also, I'm not able to get every string and the number of times it appears. Instead, I get the string in the first line with the wrong count.

Is there a way I can print all the distinct strings along with their corresponding counts?

答:
Here the code which might help you ...</p>

```<code>with open('xyz.txt') as f:
    k=f.read().split()
result={}
for element in k:
    if element not in result:
        result[element]=1
    else:
        result[element]+=1
print(result)
print(max(result)) #find max occurance string
</code>```

Body:
I'm trying to count the number of times a string occurs in a file of strings.

data=open('xyz.txt')
num=[]
    while 1:
        numrow=[]
        count=0
        x=data.readline()
        if x=='':
            break
        for line in data:
            if line==x:
                count+=1
        numrow.append(x)
        numrow.append(count)
        num.append(numrow)
    print(num)

When I try the code above, I keep getting the wrong count. Also, I'm not able to get every string and the number of times it appears. Instead, I get the string in the first line with the wrong count.

Is there a way I can print all the distinct strings along with their corresponding counts?

Body:
Here the code which might help you ...

with open('xyz.txt') as f:
    k=f.read().split()
result={}
for element in k:
    if element not in result:
        result[element]=1
    else:
        result[element]+=1
print(result)
print(max(result)) #find max occurance string


问:
Whether 'var' allocates new memory when re-accessed or overwrites it?
```<code>function Foo(){
  var someObj = {
    s: 'string'
  }

  console.log(someObj.s);
}

Foo(); // first call
Foo(); // second call
</code>```

Will the memory where the someObj points to are overwritten or will a new one be allocated? If new memory will be allocated, what happens with someObj created at first call, will garbage collector erase it? And should I make a definition of someObj outside the function to reduce the number of memory operations?

答:
A new someObj will be created on each call of Foo. You can check this by returning the object and seeing if the new one is equal:

function Foo(){
  var someObj = {
    s: 'string'
  };
  return someObj;
}
console.log(Foo() === Foo());```
</div>
</div>
</p>

<p>They're not the same - the location in memory that the first <code>someObj</code> points to is not the same as the location in memory that the second <code>someObj</code> points to. If you continually called <code>Foo</code> without leaving time for the GC to run, you would eventually run out of memory.</p>

<p>If the object is not returned, then after <code>Foo</code> runs, nothing else can reference the <code>someObj</code>, so it will be GC'd shortly.</p>

<p>If you want to prevent multiple <code>someObj</code>s from being created, yes, feel free to define <code>someObj</code> outside of <code>Foo</code>.</p>

<p>If you want <code>someObj</code> to only be referenceable inside of <code>Foo</code> while also creating only one such object, then turn <code>Foo</code> into an IIFE:</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>const Foo = (() => {
  var someObj = {
    s: 'string'
  };
  return () => {
    console.log(someObj.s);
  };
})();

Foo();</code>```

Body:
function Foo(){
  var someObj = {
    s: 'string'
  }

  console.log(someObj.s);
}

Foo(); // first call
Foo(); // second call

Will the memory where the someObj points to are overwritten or will a new one be allocated? If new memory will be allocated, what happens with someObj created at first call, will garbage collector erase it? And should I make a definition of someObj outside the function to reduce the number of memory operations?

Body:
A new someObj will be created on each call of Foo. You can check this by returning the object and seeing if the new one is equal:

function Foo(){
  var someObj = {
    s: 'string'
  };
  return someObj;
}
console.log(Foo() === Foo());

They're not the same - the location in memory that the first someObj points to is not the same as the location in memory that the second someObj points to. If you continually called Foo without leaving time for the GC to run, you would eventually run out of memory.

If the object is not returned, then after Foo runs, nothing else can reference the someObj, so it will be GC'd shortly.

If you want to prevent multiple someObjs from being created, yes, feel free to define someObj outside of Foo.

If you want someObj to only be referenceable inside of Foo while also creating only one such object, then turn Foo into an IIFE:

const Foo = (() => {
  var someObj = {
    s: 'string'
  };
  return () => {
    console.log(someObj.s);
  };
})();

Foo();


问:
Can Prometheus send its data to an external URL?
I'm working with Prometheus and I need to export data extracted from Prometheus server to an external URL (An expresse JS server hosted by me) every time the Prometheus gets data periodically.

I can send a GET request to Prometheus server from an external server and receive data. But what I need is to send a POST request to an external URL from Prometheus server every time Prometheus updates.

Is it possible?

答: It sounds like you want remote write, which will post data as it gets it in a compressed proto format over HTTP.</p>


问:
Proper formating of JSON using powershell
I have a following file in JSON format:

Before ConvertTo-JSON:

```<code>[
    {
        "Yura": {
            "Cashier": {
                "branch": "release/Retail-v4.0",
                "configuration": "RetailDemo Debug",
                "datetime_deployed": "Apr 18 2018 07:45:05",
                "deployed_by": "anonymous",
                "host": "cashier2-retail4.testing.aws.com",
                "job": "http://jenkins-testing.aws.com:8080/job/CashierDeployment",
                "lineserver": "",
                "messagebus": "",
                "product": "Cashier",
                "publish_profile": "cashier2.retail.dev.pubxml"
            },
            "ContentManager": {
                "branch": "release/Retail-v3.31.1",
                "configuration": "RetailDemo Debug",
                "datetime_deployed": "Jan 17 2018 11:59:24",
                "deployed_by": "anonymous",
                "host": "contentmanager2-retail3.testing.aws.com",
                "job": "http://jenkins-testing.aws.com:8080/job/ContentManagerDeployment",
                "lineserver": "",
                "messagebus": "",
                "product": "ContentManager",
                "publish_profile": "..\\ContentManager.PublishProfiles\\contentmanager2.retail5.dev.pubxml"
            }
        }
    }
]
</code>```

after using this code for manipulation with data:

```<code>$json = Get-Content 'D:\script\test.json'  -encoding utf8 | ConvertFrom-Json
$json.yura.ContentManager.branch = 'test'
</code>```

I save JSON into another file:

```<code>$json | convertto-json | set-content "D:\script\test1.json" -encoding utf8
</code>```

Problem is, that after saving file, format become broken:

```<code>{
    "Yura":  {
                 "Cashier":  {
                                 "branch":  "release/Retail-v4.0",
                                 "configuration":  "RetailDemo Debug",
                                 "datetime_deployed":  "Apr 18 2018 07:45:05",
                                 "deployed_by":  "anonymous",
                                 "host":  "cashier2-retail4.testing.aws.com",
                                 "job":  "http://jenkins-testing.aws.com:8080/job/CashierDeployment",
                                 "lineserver":  "",
                                 "messagebus":  "",
                                 "product":  "Cashier",
                                 "publish_profile":  "cashier2.retail.dev.pubxml"
                             },
                 "ContentManager":  {
                                        "branch":  "test",
                                        "configuration":  "RetailDemo Debug",
                                        "datetime_deployed":  "Jan 17 2018 11:59:24",
                                        "deployed_by":  "anonymous",
                                        "host":  "contentmanager2-retail3.testing.aws.com",
                                        "job":  "http://jenkins-testing.aws.com:8080/job/ContentManagerDeployment",
                                        "lineserver":  "",
                                        "messagebus":  "",
                                        "product":  "ContentManager",
                                        "publish_profile":  "..\\ContentManager.PublishProfiles\\contentmanager2.retail5.dev.pubxml"
                                    }
             }
}
</code>```

My question is - how to preserve source formatting in PowerShell?

答:
Since your original json contains an array with only one element, PowerShell will condense that to become just this one element. If in your output you want it to be an array again, use rokumaru's good answer.

However, PowerShell's ConvertTo-Json does not produce pretty formatted json and for that I have written a helper function some time ago:

```<code>function Format-Json {
    <#
    .SYNOPSIS
        Prettifies JSON output.
    .DESCRIPTION
        Reformats a JSON string so the output looks better than what ConvertTo-Json outputs.
    .PARAMETER Json
        Required: [string] The JSON text to prettify.
    .PARAMETER Minify
        Optional: Returns the json string compressed.
    .PARAMETER Indentation
        Optional: The number of spaces (1..1024) to use for indentation. Defaults to 4.
    .PARAMETER AsArray
        Optional: If set, the output will be in the form of a string array, otherwise a single string is output.
    .EXAMPLE
        $json | ConvertTo-Json  | Format-Json -Indentation 2
    #>
    [CmdletBinding(DefaultParameterSetName = 'Prettify')]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [string]$Json,

        [Parameter(ParameterSetName = 'Minify')]
        [switch]$Minify,

        [Parameter(ParameterSetName = 'Prettify')]
        [ValidateRange(1, 1024)]
        [int]$Indentation = 4,

        [Parameter(ParameterSetName = 'Prettify')]
        [switch]$AsArray
    )

    if ($PSCmdlet.ParameterSetName -eq 'Minify') {
        return ($Json | ConvertFrom-Json) | ConvertTo-Json -Depth 100 -Compress
    }

    # If the input JSON text has been created with ConvertTo-Json -Compress
    # then we first need to reconvert it without compression
    if ($Json -notmatch '\r?\n') {
        $Json = ($Json | ConvertFrom-Json) | ConvertTo-Json -Depth 100
    }

    $indent = 0
    $regexUnlessQuoted = '(?=([^"]*"[^"]*")*[^"]*$)'

    $result = $Json -split '\r?\n' |
        ForEach-Object {
            # If the line contains a ] or } character,
            # we need to decrement the indentation level unless it is inside quotes.
            if ($_ -match "[}\]]$regexUnlessQuoted") {
                $indent = [Math]::Max($indent - $Indentation, 0)
            }

            # Replace all colon-space combinations by ": " unless it is inside quotes.
            $line = (' ' * $indent) + ($_.TrimStart() -replace ":\s+$regexUnlessQuoted", ': ')

            # If the line contains a [ or { character,
            # we need to increment the indentation level unless it is inside quotes.
            if ($_ -match "[\{\[]$regexUnlessQuoted") {
                $indent += $Indentation
            }

            $line
        }

    if ($AsArray) { return $result }
    return $result -Join [Environment]::NewLine
}
</code>```

Use it like this:

```<code>$json = Get-Content 'D:\script\test.json' -Encoding UTF8 | ConvertFrom-Json
$json.yura.ContentManager.branch = 'test'

# recreate the object as array, and use the -Depth parameter (your json needs 3 minimum)
ConvertTo-Json @($json) -Depth 3 | Format-Json | Set-Content "D:\script\test1.json" -Encoding UTF8

# instead of using '@($json)' you can of course also recreate the array by adding the square brackets manually:
# '[{0}{1}{0}]' -f [Environment]::NewLine, ($json | ConvertTo-Json -Depth 3) |
#        Format-Json | Set-Content "D:\script\test1.json" -Encoding UTF8
</code>```

Body:
I have a following file in JSON format:

Before ConvertTo-JSON:

[
    {
        "Yura": {
            "Cashier": {
                "branch": "release/Retail-v4.0",
                "configuration": "RetailDemo Debug",
                "datetime_deployed": "Apr 18 2018 07:45:05",
                "deployed_by": "anonymous",
                "host": "cashier2-retail4.testing.aws.com",
                "job": "http://jenkins-testing.aws.com:8080/job/CashierDeployment",
                "lineserver": "",
                "messagebus": "",
                "product": "Cashier",
                "publish_profile": "cashier2.retail.dev.pubxml"
            },
            "ContentManager": {
                "branch": "release/Retail-v3.31.1",
                "configuration": "RetailDemo Debug",
                "datetime_deployed": "Jan 17 2018 11:59:24",
                "deployed_by": "anonymous",
                "host": "contentmanager2-retail3.testing.aws.com",
                "job": "http://jenkins-testing.aws.com:8080/job/ContentManagerDeployment",
                "lineserver": "",
                "messagebus": "",
                "product": "ContentManager",
                "publish_profile": "..\\ContentManager.PublishProfiles\\contentmanager2.retail5.dev.pubxml"
            }
        }
    }
]

after using this code for manipulation with data:

$json = Get-Content 'D:\script\test.json'  -encoding utf8 | ConvertFrom-Json
$json.yura.ContentManager.branch = 'test'

I save JSON into another file:

$json | convertto-json | set-content "D:\script\test1.json" -encoding utf8

Problem is, that after saving file, format become broken:

{
    "Yura":  {
                 "Cashier":  {
                                 "branch":  "release/Retail-v4.0",
                                 "configuration":  "RetailDemo Debug",
                                 "datetime_deployed":  "Apr 18 2018 07:45:05",
                                 "deployed_by":  "anonymous",
                                 "host":  "cashier2-retail4.testing.aws.com",
                                 "job":  "http://jenkins-testing.aws.com:8080/job/CashierDeployment",
                                 "lineserver":  "",
                                 "messagebus":  "",
                                 "product":  "Cashier",
                                 "publish_profile":  "cashier2.retail.dev.pubxml"
                             },
                 "ContentManager":  {
                                        "branch":  "test",
                                        "configuration":  "RetailDemo Debug",
                                        "datetime_deployed":  "Jan 17 2018 11:59:24",
                                        "deployed_by":  "anonymous",
                                        "host":  "contentmanager2-retail3.testing.aws.com",
                                        "job":  "http://jenkins-testing.aws.com:8080/job/ContentManagerDeployment",
                                        "lineserver":  "",
                                        "messagebus":  "",
                                        "product":  "ContentManager",
                                        "publish_profile":  "..\\ContentManager.PublishProfiles\\contentmanager2.retail5.dev.pubxml"
                                    }
             }
}

My question is - how to preserve source formatting in PowerShell?

Body:
Since your original json contains an array with only one element, PowerShell will condense that to become just this one element. If in your output you want it to be an array again, use rokumaru's good answer.

However, PowerShell's ConvertTo-Json does not produce pretty formatted json and for that I have written a helper function some time ago:

function Format-Json {
    <#
    .SYNOPSIS
        Prettifies JSON output.
    .DESCRIPTION
        Reformats a JSON string so the output looks better than what ConvertTo-Json outputs.
    .PARAMETER Json
        Required: [string] The JSON text to prettify.
    .PARAMETER Minify
        Optional: Returns the json string compressed.
    .PARAMETER Indentation
        Optional: The number of spaces (1..1024) to use for indentation. Defaults to 4.
    .PARAMETER AsArray
        Optional: If set, the output will be in the form of a string array, otherwise a single string is output.
    .EXAMPLE
        $json | ConvertTo-Json  | Format-Json -Indentation 2
    #>
    [CmdletBinding(DefaultParameterSetName = 'Prettify')]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [string]$Json,

        [Parameter(ParameterSetName = 'Minify')]
        [switch]$Minify,

        [Parameter(ParameterSetName = 'Prettify')]
        [ValidateRange(1, 1024)]
        [int]$Indentation = 4,

        [Parameter(ParameterSetName = 'Prettify')]
        [switch]$AsArray
    )

    if ($PSCmdlet.ParameterSetName -eq 'Minify') {
        return ($Json | ConvertFrom-Json) | ConvertTo-Json -Depth 100 -Compress
    }

    # If the input JSON text has been created with ConvertTo-Json -Compress
    # then we first need to reconvert it without compression
    if ($Json -notmatch '\r?\n') {
        $Json = ($Json | ConvertFrom-Json) | ConvertTo-Json -Depth 100
    }

    $indent = 0
    $regexUnlessQuoted = '(?=([^"]*"[^"]*")*[^"]*$)'

    $result = $Json -split '\r?\n' |
        ForEach-Object {
            # If the line contains a ] or } character,
            # we need to decrement the indentation level unless it is inside quotes.
            if ($_ -match "[}\]]$regexUnlessQuoted") {
                $indent = [Math]::Max($indent - $Indentation, 0)
            }

            # Replace all colon-space combinations by ": " unless it is inside quotes.
            $line = (' ' * $indent) + ($_.TrimStart() -replace ":\s+$regexUnlessQuoted", ': ')

            # If the line contains a [ or { character,
            # we need to increment the indentation level unless it is inside quotes.
            if ($_ -match "[\{\[]$regexUnlessQuoted") {
                $indent += $Indentation
            }

            $line
        }

    if ($AsArray) { return $result }
    return $result -Join [Environment]::NewLine
}

Use it like this:

$json = Get-Content 'D:\script\test.json' -Encoding UTF8 | ConvertFrom-Json
$json.yura.ContentManager.branch = 'test'

# recreate the object as array, and use the -Depth parameter (your json needs 3 minimum)
ConvertTo-Json @($json) -Depth 3 | Format-Json | Set-Content "D:\script\test1.json" -Encoding UTF8

# instead of using '@($json)' you can of course also recreate the array by adding the square brackets manually:
# '[{0}{1}{0}]' -f [Environment]::NewLine, ($json | ConvertTo-Json -Depth 3) |
#        Format-Json | Set-Content "D:\script\test1.json" -Encoding UTF8


问:
Angular 7 Reactive Formarray cascading dropdown - How to load saved data back in UI form
I've followed the stackoverflow link cascading dropdown in reactive formarray

and achieved the desired result. On top of this, I want to load the saved data from DB back to UI when user tries to edit the options again. I've almost achieved that but issues with second dropdown. Need help on loading the wheres[] dynamically for each of the formarray rows. I'm saving the formarray json as such in DB and retrieving the same and iterating.

options: string - the name of the variable in DB where formarray is stored

```<code>private retrieveSavedControls(options: string): FormArray{
console.log(classes);
this.profileForm= this.fb.group({
  optionGroups: this.fb.array([])
})
const control = <FormArray>this.profileForm.controls['optionGroups'];

this.units = JSON.parse(options).optionGroups;
console.log('parsed json: ',this.units);
let index =0;
this.units.forEach(unit => {

  control.push(this.fb.group({
    selectInput: ['', Validators.required],
    whereInput: [[], Validators.required]
  }));
  // this part should've loaded the list for each of the 2nd dropdown but not loading.
  this.wheres[unit.selectInput] = this.getWhere().filter((item)=> item.selectid == unit.selectInput);

   (<FormArray>this.profileForm.controls['optionGroups']).controls[index]
    .patchValue({ selectInput: unit.selectInput, whereInput: unit.whereInput});
  index++
})
console.log('control: ',control)
return control;
</code>```

}

答: all. It was an issue from my code. The actual list was empty for some reason. It was fixed and it successfully loaded the selected values against each individual list.</p>

Body:
I've followed the stackoverflow link cascading dropdown in reactive formarray

and achieved the desired result. On top of this, I want to load the saved data from DB back to UI when user tries to edit the options again. I've almost achieved that but issues with second dropdown. Need help on loading the wheres[] dynamically for each of the formarray rows. I'm saving the formarray json as such in DB and retrieving the same and iterating.

options: string - the name of the variable in DB where formarray is stored

private retrieveSavedControls(options: string): FormArray{
console.log(classes);
this.profileForm= this.fb.group({
  optionGroups: this.fb.array([])
})
const control = <FormArray>this.profileForm.controls['optionGroups'];

this.units = JSON.parse(options).optionGroups;
console.log('parsed json: ',this.units);
let index =0;
this.units.forEach(unit => {

  control.push(this.fb.group({
    selectInput: ['', Validators.required],
    whereInput: [[], Validators.required]
  }));
  // this part should've loaded the list for each of the 2nd dropdown but not loading.
  this.wheres[unit.selectInput] = this.getWhere().filter((item)=> item.selectid == unit.selectInput);

   (<FormArray>this.profileForm.controls['optionGroups']).controls[index]
    .patchValue({ selectInput: unit.selectInput, whereInput: unit.whereInput});
  index++
})
console.log('control: ',control)
return control;

}


问:
Program in Python to show letters guessed in a hangman game not working
I have to write a code in Python where it is about playing the game hangman. Currently my code cannot replace the "_" with the guessed letters properly, where it only replaces one and doesn't show all of the guessed letters.

My code is below:

```<code>import random

word = random.choice(["bread", "clouds", "plane"])

guess = 0
correct_guess = 0
play_again = True

print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')
hyphens = print('_ ' * (len(word)))

if status == 'No' 'no' 'N' 'n':
  exit()

while play_again is True:

  letter = input('Guess a letter: ')

  if letter in word:
    guess = guess + 1
    correct_guess = correct_guess + 1
    print('You guessed a letter correctly!')
    position = word.find(letter)
    print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
    if position == 0:
      print(letter, "_ _ _ _")
    if position == 1:
      print("_", letter, "_ _ _ ")
    if position == 2:
      print("_ _", letter, "_ _ ")
    if position == 3:
      print("_ _ _", letter, "_ ")
    if position == 4:
      print("_ _ _ _", letter)
  else:
    guess = guess + 1
    print("That letter isn't in the word. Guess Count:", guess)
  if guess == 10:
    print('Bad luck. You lost.')
    play = input('Do you want to play again? ')
    if play == 'No' 'no' 'N' 'n':
      exit()
  if correct_guess == 5:
    print('Congratulations! You have guessed the word! The word was', word + '.')
    play = input('Do you want to play again? ')
    if play == 'No' 'no' 'N' 'n':
      exit()
</code>```

Your help is very much appreciated. Also, I don't know a lot about programming and I am fairly new to it.

James

答:
you can't write expression like :

```<code>if status == 'No' 'no' 'N' 'n':
</code>```

the correct way is:

```<code>if play == 'No' or play == 'no' or play == 'N' or play == 'n':
</code>```

or:

```<code>if play in ['No' ,'no', 'N' ,'n']
</code>```

one solution:

```<code>import random

word = random.choice(["bread", "clouds", "plane"])

print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')

def play():
    if status == 'No' or status == 'no' or status == 'N' or status == 'n':
        print ("Goodbye")
        return # exit
    else:
        print('_ ' * (len(word))) # _ _ _ _ _

    guess = 0
    correct_guess = 0
    play_again = True

    pos_list = ['_' for x in range(len(word))] # define list where you will put your guessed letters ['_', '_', '_', '_', '_']
    while play_again is True:
      letter = input('Guess a letter: ')

      if letter in word:
        guess = guess + 1
        correct_guess = correct_guess + 1
        print('You guessed a letter correctly!')
        position = word.find(letter)
        print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
        pos_list[position] = letter # save letter at position # ['_', '_', '_', 'a', '_']
        print (' '.join(pos_list)) # _ _ _ a _

      else:
        guess = guess + 1
        print("That letter isn't in the word. Guess Count:", guess)
      if guess == 10:
        print('Bad luck. You lost.')
        play = input('Do you want to play again? ')
        if play == 'No' or play == 'no' or play == 'N' or play == 'n':
            print("Goodbye")
            return
        else:
             print('_ ' * (len(word)))
      if correct_guess == len(word):
        print('Congratulations! You have guessed the word! The word was', word + '.')
        play = input('Do you want to play again? ')
        if play == 'No' or play == 'no' or play == 'N' or play == 'n':
            print("Goodbye")
            return
        else:
            print('_ ' * (len(word)))

play()
</code>```

Body:
I have to write a code in Python where it is about playing the game hangman. Currently my code cannot replace the "_" with the guessed letters properly, where it only replaces one and doesn't show all of the guessed letters.

My code is below:

import random

word = random.choice(["bread", "clouds", "plane"])

guess = 0
correct_guess = 0
play_again = True

print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')
hyphens = print('_ ' * (len(word)))

if status == 'No' 'no' 'N' 'n':
  exit()

while play_again is True:

  letter = input('Guess a letter: ')

  if letter in word:
    guess = guess + 1
    correct_guess = correct_guess + 1
    print('You guessed a letter correctly!')
    position = word.find(letter)
    print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
    if position == 0:
      print(letter, "_ _ _ _")
    if position == 1:
      print("_", letter, "_ _ _ ")
    if position == 2:
      print("_ _", letter, "_ _ ")
    if position == 3:
      print("_ _ _", letter, "_ ")
    if position == 4:
      print("_ _ _ _", letter)
  else:
    guess = guess + 1
    print("That letter isn't in the word. Guess Count:", guess)
  if guess == 10:
    print('Bad luck. You lost.')
    play = input('Do you want to play again? ')
    if play == 'No' 'no' 'N' 'n':
      exit()
  if correct_guess == 5:
    print('Congratulations! You have guessed the word! The word was', word + '.')
    play = input('Do you want to play again? ')
    if play == 'No' 'no' 'N' 'n':
      exit()

Your help is very much appreciated. Also, I don't know a lot about programming and I am fairly new to it.

James

Body:
you can't write expression like :

if status == 'No' 'no' 'N' 'n':

the correct way is:

if play == 'No' or play == 'no' or play == 'N' or play == 'n':

or:

if play in ['No' ,'no', 'N' ,'n']

one solution:

import random

word = random.choice(["bread", "clouds", "plane"])

print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')

def play():
    if status == 'No' or status == 'no' or status == 'N' or status == 'n':
        print ("Goodbye")
        return # exit
    else:
        print('_ ' * (len(word))) # _ _ _ _ _

    guess = 0
    correct_guess = 0
    play_again = True

    pos_list = ['_' for x in range(len(word))] # define list where you will put your guessed letters ['_', '_', '_', '_', '_']
    while play_again is True:
      letter = input('Guess a letter: ')

      if letter in word:
        guess = guess + 1
        correct_guess = correct_guess + 1
        print('You guessed a letter correctly!')
        position = word.find(letter)
        print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
        pos_list[position] = letter # save letter at position # ['_', '_', '_', 'a', '_']
        print (' '.join(pos_list)) # _ _ _ a _

      else:
        guess = guess + 1
        print("That letter isn't in the word. Guess Count:", guess)
      if guess == 10:
        print('Bad luck. You lost.')
        play = input('Do you want to play again? ')
        if play == 'No' or play == 'no' or play == 'N' or play == 'n':
            print("Goodbye")
            return
        else:
             print('_ ' * (len(word)))
      if correct_guess == len(word):
        print('Congratulations! You have guessed the word! The word was', word + '.')
        play = input('Do you want to play again? ')
        if play == 'No' or play == 'no' or play == 'N' or play == 'n':
            print("Goodbye")
            return
        else:
            print('_ ' * (len(word)))

play()


问:
is static variables cause memory leak in android?
is there is any chance of memory leak in static variable like in class

```<code>public class Date extends LinearLayout{

private static String VALUE="20";
    }
</code>```

contexts , object references using static cause memory leak. But what about the constants variable declarations

答:
Your example will not cause a memory leak, but if you point to an activity or view context, it will.

So you can safely store any primitive static variable in your class.

Body:
is there is any chance of memory leak in static variable like in class

public class Date extends LinearLayout{

private static String VALUE="20";
    }

contexts , object references using static cause memory leak. But what about the constants variable declarations


问:
Visual Studio Code - Python - List Index Limit Max 300 - Debugger
I have a list contains several hundred entries. I think the total size of the list is 3.5 MB.

When debugging an issue I can't seem to view any entry passed 300 and I see this message 'Too large to show contents. Max items to show: 300'

Any ideas?

答:
You want to find a file named pydevd_resolver.py under your Visual Studio Code workspace directory
(you can find it with Bash this command: find / -name pydevd_resolver.py 2>/dev/null).

Open the file, and inside it look for a constant definition: MAX_ITEMS_TO_HANDLE = 300. You can change this number to whatever you like, but please note this will of course consume more resources, so be careful with this.

Just for the sake of completion, I paste the note provided above this definition in pydevd_resolver.py itself:

Note: 300 is already a lot to see in the outline (after that the user should really use the shell to get things) and this also means we'll pass less information to the client side (which makes debugging faster).


问:
How to get the nearest value to a request param in SQL?
I have a table (shop_staff_relationvm) that saves the relation between a staff and a shop.

It has 3 columns: id_shop, id_staff and change_date.

id_staff => staff foreign key

id_shop => shop foreign key

change_date ==> whenever a new staff-shop relation is created I save the setting date (a staff's shop may change multiple times)

The 3 abov columns represent an embeddable primary key for shop_staff_relationvm table.

In the query, I have 2 request params: idShop and a date.

I am trying to get the list of staffs that belong to a specific shop (idShop) in a specific month (requestMonth).

So I need to get the list of staffs when the requestMonth is between the first date of the relation between the staff and shop and the last date of the relation.

This is an example:

```<code>STAFF     | SHOP     | CHANGE DATE
----------+----------+-------------
Staff A   | Shop 1   | 10-01-2019
Staff A   | Shop 2   | 10-03-2019
Staff A   | Shop 3   | 10-05-2019
</code>```

Assuming we have requestMonth = 02-2019

Then : shop 1 will have Staff A , shop 2 will have no staffs and shop 3 will have no staffs

Assuming we have requestMonth = 03-2019

Then : shop 1 will have no staffs , shop 2 will have Staff A and shop 3 will have no staffs

Assuming we have requestMonth = 06-2019

Then : shop 1 will have no staffs , shop 2 will have no staffs and shop 3 will have Staff A

This is the formula I came up with:

```<code>first date of relation <= requestMonth <= first date of next relation
</code>```

I do not have a problem getting the first date of the relation, but I have a problem in getting the first date of the next relation (which I concluded to be the next nearest value to the first date of the relation).

PS: I am using JPA native query

I have tried using an order by (change_date - first date of relation) to get the first nearest value to the first date of relation. but It always got me the maximum value (In the example I stated above, it always gets me the 05-2019 month)

I also tried using LEAD to get the next nearest value. However, using the example above:

For requestMonth = 02-2019 :
  the LEAD was equal to 03-2019 => correct

For requestMonth = 03-2019 :
  the LEAD was equal to 01-2019 => wrong => It should be 05-2019

This the whole query:

```<code>SELECT s.* FROM staffvm s INNER JOIN shop_staff_relationvm ss ON ss.id_staff = s.id_staff WHERE ss.id_shop = 2 and
(CASE WHEN ((SELECT MAX(to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff) > to_date('2019-02-16', 'yyyy-MM')
and (SELECT MIN(to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff) <= to_date('2019-02-16', 'yyyy-MM') )
THEN
((SELECT ((LEAD (to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) OVER (ORDER BY ss.id_staff DESC)) > to_date('2019-02-16', 'yyyy-MM') )
FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff and ss.id_shop !=2 LIMIT 1)
and
(SELECT (MIN(to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) <= to_date('2019-02-16', 'yyyy-MM'))
FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff and ss.id_shop = 2) )
ELSE
(SELECT (to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM') <= to_date('2019-02-16', 'yyyy-MM'))
 FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff and ss.id_shop = 2 )
END);
</code>```

The part of query I have problem with :

```<code>((SELECT ((LEAD (to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) OVER (ORDER BY ss.id_staff DESC)) > to_date('2019-02-16', 'yyyy-MM') )
FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff and ss.id_shop !=2 LIMIT 1)
and
(SELECT (MIN(to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) <= to_date('2019-02-16', 'yyyy-MM'))
FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff and ss.id_shop = 2))
</code>```

答:
If you want to get the staff on a particular date, you can use distinct on.

```<code>select distinct on (ss.id_staff) ss.*
from shop_staff_relationvm ss
where ss.change_date <= '2019-02-01'::date
order by ss.id_staff, ss.change_date desc;
</code>```

With an index on shop_staff_relationvm(id_staff, change_date), this is probably the best performing of possible solutions.

To determine who is at a particular shop, use a subquery:

```<code>select s.*
from (select distinct on (ss.id_staff) ss.*
      from shop_staff_relationvm ss
      where ss.change_date <= '2019-02-01'::date
      order by ss.id_staff, ss.change_date desc
     ) s
where s.shop_id = 2;
</code>```

Body:
I have a table (shop_staff_relationvm) that saves the relation between a staff and a shop.

It has 3 columns: id_shop, id_staff and change_date.

id_staff => staff foreign key

id_shop => shop foreign key

change_date ==> whenever a new staff-shop relation is created I save the setting date (a staff's shop may change multiple times)

The 3 abov columns represent an embeddable primary key for shop_staff_relationvm table.

In the query, I have 2 request params: idShop and a date.

I am trying to get the list of staffs that belong to a specific shop (idShop) in a specific month (requestMonth).

So I need to get the list of staffs when the requestMonth is between the first date of the relation between the staff and shop and the last date of the relation.

This is an example:

STAFF     | SHOP     | CHANGE DATE
----------+----------+-------------
Staff A   | Shop 1   | 10-01-2019
Staff A   | Shop 2   | 10-03-2019
Staff A   | Shop 3   | 10-05-2019

Assuming we have requestMonth = 02-2019

Then : shop 1 will have Staff A , shop 2 will have no staffs and shop 3 will have no staffs

Assuming we have requestMonth = 03-2019

Then : shop 1 will have no staffs , shop 2 will have Staff A and shop 3 will have no staffs

Assuming we have requestMonth = 06-2019

Then : shop 1 will have no staffs , shop 2 will have no staffs and shop 3 will have Staff A

This is the formula I came up with:

first date of relation <= requestMonth <= first date of next relation

I do not have a problem getting the first date of the relation, but I have a problem in getting the first date of the next relation (which I concluded to be the next nearest value to the first date of the relation).

PS: I am using JPA native query

I have tried using an order by (change_date - first date of relation) to get the first nearest value to the first date of relation. but It always got me the maximum value (In the example I stated above, it always gets me the 05-2019 month)

I also tried using LEAD to get the next nearest value. However, using the example above:

For requestMonth = 02-2019 :
  the LEAD was equal to 03-2019 => correct

For requestMonth = 03-2019 :
  the LEAD was equal to 01-2019 => wrong => It should be 05-2019

This the whole query:

SELECT s.* FROM staffvm s INNER JOIN shop_staff_relationvm ss ON ss.id_staff = s.id_staff WHERE ss.id_shop = 2 and
(CASE WHEN ((SELECT MAX(to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff) > to_date('2019-02-16', 'yyyy-MM')
and (SELECT MIN(to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff) <= to_date('2019-02-16', 'yyyy-MM') )
THEN
((SELECT ((LEAD (to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) OVER (ORDER BY ss.id_staff DESC)) > to_date('2019-02-16', 'yyyy-MM') )
FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff and ss.id_shop !=2 LIMIT 1)
and
(SELECT (MIN(to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) <= to_date('2019-02-16', 'yyyy-MM'))
FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff and ss.id_shop = 2) )
ELSE
(SELECT (to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM') <= to_date('2019-02-16', 'yyyy-MM'))
 FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff and ss.id_shop = 2 )
END);

The part of query I have problem with :

((SELECT ((LEAD (to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) OVER (ORDER BY ss.id_staff DESC)) > to_date('2019-02-16', 'yyyy-MM') )
FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff and ss.id_shop !=2 LIMIT 1)
and
(SELECT (MIN(to_date(to_char(ss.change_date, 'yyyy-MM'), 'yyyy-MM')) <= to_date('2019-02-16', 'yyyy-MM'))
FROM shop_staff_relationvm ss WHERE ss.id_staff = s.id_staff and ss.id_shop = 2))

Body:
If you want to get the staff on a particular date, you can use distinct on.

select distinct on (ss.id_staff) ss.*
from shop_staff_relationvm ss
where ss.change_date <= '2019-02-01'::date
order by ss.id_staff, ss.change_date desc;

With an index on shop_staff_relationvm(id_staff, change_date), this is probably the best performing of possible solutions.

To determine who is at a particular shop, use a subquery:

select s.*
from (select distinct on (ss.id_staff) ss.*
      from shop_staff_relationvm ss
      where ss.change_date <= '2019-02-01'::date
      order by ss.id_staff, ss.change_date desc
     ) s
where s.shop_id = 2;


问:
How to get image file from local directory by gatsby-transformer-asciidoc?
I use gatsby-transformer-asciidoc and write image::<some-name>[] in .adoc. But I haven't could get images.

Dirctory structure

```<code>---images
 |  |-cheetah.png
 |-posts
 |  |-test.adoc
 |-src
 |-gatsby-config.js
 |-gatsby-node.js
 :
</code>```

gatsby-config.js plugin

```<code>plugins: [
  {
    resolve: `gatsby-transformer-asciidoc`,
    options: {
      attributes: {
        imagesdir: `/images`,
      },
    },
  },
]
</code>```

test.adoc

```<code> :
image::cheetah.png[]
 :
</code>```

But I haven't get the image.

And I test an another plugin strucure.

gatsby-config.js

```<code>plugins: [
  {
    resolve: `gatsby-transformer-asciidoc`,
    options: {
      attributes: {
        imagesdir: `${__dirname}/images`,
      },
    },
  },
]
</code>```

But I could not.

Please save me!

答:
Here's one solution, maybe not the better one but it works for me.

You can put your images in a static/images folder at the root of your project, that way, you can use the default imagesdir attribute and it will work.

Meaning your directory structure would be

```<code> |-static
 |  |-images
 |    |-cheetah.png
 |-posts
 |  |-test.adoc
 |-src
 |-gatsby-config.js
 |-gatsby-node.js
 :
</code>```

and your config

```<code>plugins: [
  {
    resolve: `gatsby-transformer-asciidoc`,
    options: {
      attributes: {},
    },
  },
]
</code>```

Body:
I use gatsby-transformer-asciidoc and write image::<some-name>[] in .adoc. But I haven't could get images.

Dirctory structure

---images
 |  |-cheetah.png
 |-posts
 |  |-test.adoc
 |-src
 |-gatsby-config.js
 |-gatsby-node.js
 :

gatsby-config.js plugin

plugins: [
  {
    resolve: `gatsby-transformer-asciidoc`,
    options: {
      attributes: {
        imagesdir: `/images`,
      },
    },
  },
]

test.adoc

 :
image::cheetah.png[]
 :

But I haven't get the image.

And I test an another plugin strucure.

gatsby-config.js

plugins: [
  {
    resolve: `gatsby-transformer-asciidoc`,
    options: {
      attributes: {
        imagesdir: `${__dirname}/images`,
      },
    },
  },
]

But I could not.

Please save me!

Body:
Here's one solution, maybe not the better one but it works for me.

You can put your images in a static/images folder at the root of your project, that way, you can use the default imagesdir attribute and it will work.

Meaning your directory structure would be

 |-static
 |  |-images
 |    |-cheetah.png
 |-posts
 |  |-test.adoc
 |-src
 |-gatsby-config.js
 |-gatsby-node.js
 :

and your config

plugins: [
  {
    resolve: `gatsby-transformer-asciidoc`,
    options: {
      attributes: {},
    },
  },
]


问:
Is it possible to define a mysqli_connect object as a constant
I'm simply trying to make my life easier. My issue, and i know ways around it, is that I can't directly access my mysqli_connect object from a function, the function has to be handed the object as an argument.

```<code>define_constant( MYSQLI , mysqli_connect( "localhost","my_user","my_password","my_db" ) );
</code>```

Currently done similar to:

$link = mysqli_connect("localhost","my_user","my_password","my_db");

function doSqlStuff( $link ){
    //Run my sql statments here using the link passed through the fuction
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";

    if ($link->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "
" . $link->error;
    }
}
doSqlStuff( $link );
```

<p>How I would prefer to call as a easier way</p>

<pre class="lang-php prettyprint-override"><code>define_constant( MYSQLI , mysqli_connect("localhost","my_user","my_password","my_db") );

function doSqlStuff(){
    //Run my sql statments here using the link as a constant
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";

    if (MYSQLI->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . MYSQLI->error;
    }
}
doSqlStuff();

</code>```

My general feeling is that this is a bad idea. However it would make my life easier, and I can't think of a reason not to do this.

Could this work, or is there something similar that might do the trick to access the mysqli connection without having to pass the object each time.

答:
Actually you can not use constant to store non-static data. But you can create singleton-type class to access your connection link.</p>

```<code><?php

class Connection
{
    private static $link;

    static public function link() {
        if (self::$link === null) {
            self::$link = mysqli_connect( "localhost","my_user","my_password","my_db" );
        }

        return self::$link;
    }
}

function doSqlStuff(){
    //Run my sql statments here using the link as a constant
    $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";

    if (Connection::link()->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . Connection::link()->error;
    }
}
</code>```

Body:
I'm simply trying to make my life easier. My issue, and i know ways around it, is that I can't directly access my mysqli_connect object from a function, the function has to be handed the object as an argument.

define_constant( MYSQLI , mysqli_connect( "localhost","my_user","my_password","my_db" ) );

Currently done similar to:

$link = mysqli_connect("localhost","my_user","my_password","my_db");

function doSqlStuff( $link ){
    //Run my sql statments here using the link passed through the fuction
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";

    if ($link->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "
" . $link->error;
    }
}
doSqlStuff( $link );

How I would prefer to call as a easier way

define_constant( MYSQLI , mysqli_connect("localhost","my_user","my_password","my_db") );

function doSqlStuff(){
    //Run my sql statments here using the link as a constant
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";

    if (MYSQLI->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "
" . MYSQLI->error;
    }
}
doSqlStuff();

My general feeling is that this is a bad idea. However it would make my life easier, and I can't think of a reason not to do this.

Could this work, or is there something similar that might do the trick to access the mysqli connection without having to pass the object each time.

Body:
Actually you can not use constant to store non-static data. But you can create singleton-type class to access your connection link.

<?php

class Connection
{
    private static $link;

    static public function link() {
        if (self::$link === null) {
            self::$link = mysqli_connect( "localhost","my_user","my_password","my_db" );
        }

        return self::$link;
    }
}

function doSqlStuff(){
    //Run my sql statments here using the link as a constant
    $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";

    if (Connection::link()->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . Connection::link()->error;
    }
}


问:
What is the best method to save Objects local data in Firemonkey mobile app?
In my app I got JSON response from RESTServer. Then I convert them into Data Objects, store them in TObjectList and then bind the list to TListBindSourceAdapter for display.

I would like to save the TObjectList data to local storage. My question is: what is the best method to save it?

I tried to create a SQLite DB, I could save records into SQLite DB but it required to convert my TObjectList into DB records manually in code, and when I retrieve I need to convert it back to data object. It involves more development effort.

Or should I use SaveState? I could save local data as string using SaveState. I could try to use TJson.ObjectToJson to convert Data Object into JSON and save it. To do this, I could save the TObjectList into Array, store it into a data object and do convert to JSON. when retrieve I could convert back using TJson.JsonToObject.

Or is there any better method to do so? Is there a common method to save local data in Firemonkey? Is there something similar to State Management in Angular?

答:
At last, I used SaveState to save my data to local. Since I tried and found using SaveState is much faster to develop and easier to develop.

The disadvantage of using saveState instead of saving into a local DB is, SaveState only happens when the application form closed, or in a mobile app, when the app deactivated. If the app in mobile app been killed directly instead of deactivating, the SaveState is not called and data may lose. Conversely, saving into local DB can be called manually anytime.


问:
Enable Trendline drawing button in MT4 via MQL4
I'm MQL developer. It's some days that I want to enable/disable some features of Metatrader4 using some keys. Specifically I want to Enable/Disable "TrendLine Drawing", "vertical line drawing" and "horizontal line drawing" buttons but I didn't find related info on the web. As I know we can do similar task by importing User32.dll and using
PostMessageA(int hWnd, uint Msg, int wParam, int lParam) function.

Can you help me which parameters will work for me?

答: MT4 doesn't support enabling / disabling buttons on the tool bar. The best you you might be able to do is remove / restore the group of buttons from the toolbar. I will investigate this further in case you are unaware how to go about doing it.</p>


问:
PHP: are switch-case statements with strings inefficient?
In my PHP layer I'm receiving error codes as strings ("NOT_FOUND", "EXPIRED", etc). It's a small list of possible strings, perhaps a dozen. </p>

<p>What's the most efficient way of dealing with these? Using switch-case against string constants stored in a class, or should I parse them to numbers (or something) first? Or is PHP smart enough so it doesn't really matter? </p>

答:
You might want to consider using constants? Let's say you have a class Error and define all error codes there like this:

```<code>class Error {
   const NOT_FOUND = 0;
   const EXPIRED = 1;
   // and so forth
}
</code>```

And then you can use them in your code by accessing them like Error::NOT_FOUND and a switch statement wouldn't need to compare strings but has plain ints without downgrading readability.

Body:
In my PHP layer I'm receiving error codes as strings ("NOT_FOUND", "EXPIRED", etc). It's a small list of possible strings, perhaps a dozen.

What's the most efficient way of dealing with these? Using switch-case against string constants stored in a class, or should I parse them to numbers (or something) first? Or is PHP smart enough so it doesn't really matter?

Body:
You might want to consider using constants? Let's say you have a class Error and define all error codes there like this:

class Error {
   const NOT_FOUND = 0;
   const EXPIRED = 1;
   // and so forth
}

And then you can use them in your code by accessing them like Error::NOT_FOUND and a switch statement wouldn't need to compare strings but has plain ints without downgrading readability.


问:
Unable to send parcelable arraylist to service class
I am trying to pass a parcelable arraylist to service which contains image urls. For some reason all data types are passing to service but not parcelable arraylist. An error in logcat is coming as

E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! .

Following is my code for imageurl Arraylist model.

```<code>public class ImagesUrl implements Parcelable {

    private int id;
    private String filename;
    private String imageurl ;

    public ImagesUrl(Integer id , String imageurl , String filename) {
        this.id = id;
        this.filename = filename;
        this.imageurl = imageurl ;
    }

    public static final Parcelable.Creator<ImagesUrl> CREATOR = new Parcelable.Creator<ImagesUrl>() {
        public ImagesUrl createFromParcel(Parcel in) {
            return new ImagesUrl(in.readInt(),in.readString(), in.readString());
        }

        public ImagesUrl[] newArray(int size) {
            return new ImagesUrl[size];
        }
    };

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getImageurl() {
        return imageurl;
    }

    public void setImageurl(String imageurl) {
        this.imageurl = imageurl;
    }

    public static Creator<ImagesUrl> getCREATOR() {
        return CREATOR;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(filename);
        dest.writeString(imageurl);
    }

    private void readFromParcel(Parcel in) {
        id = in.readInt();
        filename = in.readString();
        imageurl = in.readString();
    }

}
</code>```

Here is code to start service:

```<code> Intent i= new Intent(SyncActivity.this,ImageDownloadService.class);
    Bundle b=new Bundle();
    b.putParcelableArrayList("imageurls", imagesUrlArrayList);
    b.putInt("int",12);
    i.putExtras(b);
    startService(i);
</code>```

Folowing is code for Service class:

```<code>public class ImageDownloadService extends Service {

    private ArrayList<ImagesUrl> imagesUrlArrayList = new ArrayList<>();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {

        Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();

    }
    @Override
    public void onStart(Intent intent, int startid) {

        if(intent != null && intent.getParcelableArrayListExtra("imageurls") != null){
            imagesUrlArrayList = intent.getParcelableArrayListExtra("imageurls");
        }
        int val = intent.getIntExtra("int",0);
        Log.d(TAG, "onStart: "+(String.valueOf(imagesUrlArrayList.size())));
        Log.d(TAG, "onStart: "+(String.valueOf(imagesUrlArrayList.size())));
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
    }

    class GetImages extends AsyncTask<String, String, String> {

        private Integer current;
        String jsonStr;

        @Override
        protected String doInBackground(String... args) {

            try {
                Log.d(TAG, "doInBackground: "+String.valueOf(imagesUrlArrayList.size()));
                for (int i = 0; i < imagesUrlArrayList.size(); i++) {
                    downloadimage(imagesUrlArrayList.get(i).getImageurl(),imagesUrlArrayList.get(i).getFilename());
                }
                return "Images downloaded successfully. Please refresh your screen";

            } catch (Exception er) {
                Log.d(TAG, er.getMessage());
                appendLog(TAG+" GetCategories "+ er.getMessage());
                return er.getMessage();
            }

        }

        protected void onPostExecute(String file_url) {
          //  Toast.makeText(mContext, file_url, Toast.LENGTH_LONG).show();

        }
    }
    private  void  downloadimage(String URL ,String filename){

        try {
            URL url = new URL(URL);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.connect();

            /*Context wrapper = new ContextWrapper(mContext);*/
            /*File internalStorage = wrapper.getDir("freshImages",MODE_PRIVATE);*/
            String root = Environment.getExternalStorageDirectory().toString();
            File internalStorage = new File(root + "/fresh/freshImages");

            if (!internalStorage.exists()) {
                internalStorage.mkdirs();
            }

            File file = new File(internalStorage, filename);

            InputStream inputStream = new BufferedInputStream(url.openStream() , 40 );

            // Bitmap bm = BitmapFactory.decodeStream(inputStream);

            OutputStream fileOutput = new FileOutputStream(file);

            Bitmap bmp =createScaledBitmapFromStream(inputStream,100,100);

            bmp.compress(Bitmap.CompressFormat.PNG, 90, fileOutput);
            inputStream.close();
            fileOutput.close();
            /*OutputStream fileOutput = new FileOutputStream(file);

            byte[] buffer = new byte[8192];
            int bufferLength = 0;

            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                fileOutput.write(buffer, 0, bufferLength);
            }
            fileOutput.close();*/
            //    Toast.makeText(getApplicationContext(), "image downloased", Toast.LENGTH_SHORT).show();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected Bitmap createScaledBitmapFromStream( InputStream s, int minimumDesiredBitmapWidth, int minimumDesiredBitmapHeight ) {

        final BufferedInputStream is = new BufferedInputStream(s, 32*1024);
        try {
            final BitmapFactory.Options decodeBitmapOptions = new BitmapFactory.Options();
            // For further memory savings, you may want to consider using this option
            // decodeBitmapOptions.inPreferredConfig = Config.RGB_565; // Uses 2-bytes instead of default 4 per pixel

            if( minimumDesiredBitmapWidth >0 && minimumDesiredBitmapHeight >0 ) {
                final BitmapFactory.Options decodeBoundsOptions = new BitmapFactory.Options();
                decodeBoundsOptions.inJustDecodeBounds = true;
                is.mark(32*1024); // 32k is probably overkill, but 8k is insufficient for some jpgs
                BitmapFactory.decodeStream(is,null,decodeBoundsOptions);
                is.reset();

                final int originalWidth = decodeBoundsOptions.outWidth;
                final int originalHeight = decodeBoundsOptions.outHeight;

                // inSampleSize prefers multiples of 2, but we prefer to prioritize memory savings
                decodeBitmapOptions.inSampleSize= Math.max(1,Math.min(originalWidth / minimumDesiredBitmapWidth, originalHeight / minimumDesiredBitmapHeight));

            }

            return BitmapFactory.decodeStream(is,null,decodeBitmapOptions);

        } catch( IOException e ) {
            throw new RuntimeException(e); // this shouldn't happen
        } finally {
            try {
                is.close();
            } catch( IOException ignored ) {}
        }

    }

}
</code>```

I  will call GetImages asyntask if i get pacelable arraylist right in service class.

答: My arraylist was having 5000 urls which can not be sent via intent. I made a util class to pass and receive array between activities. </p>

Body:
I am trying to pass a parcelable arraylist to service which contains image urls. For some reason all data types are passing to service but not parcelable arraylist. An error in logcat is coming as

E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! .

Following is my code for imageurl Arraylist model.

public class ImagesUrl implements Parcelable {

    private int id;
    private String filename;
    private String imageurl ;

    public ImagesUrl(Integer id , String imageurl , String filename) {
        this.id = id;
        this.filename = filename;
        this.imageurl = imageurl ;
    }

    public static final Parcelable.Creator<ImagesUrl> CREATOR = new Parcelable.Creator<ImagesUrl>() {
        public ImagesUrl createFromParcel(Parcel in) {
            return new ImagesUrl(in.readInt(),in.readString(), in.readString());
        }

        public ImagesUrl[] newArray(int size) {
            return new ImagesUrl[size];
        }
    };

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getImageurl() {
        return imageurl;
    }

    public void setImageurl(String imageurl) {
        this.imageurl = imageurl;
    }

    public static Creator<ImagesUrl> getCREATOR() {
        return CREATOR;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(filename);
        dest.writeString(imageurl);
    }

    private void readFromParcel(Parcel in) {
        id = in.readInt();
        filename = in.readString();
        imageurl = in.readString();
    }

}

Here is code to start service:

 Intent i= new Intent(SyncActivity.this,ImageDownloadService.class);
    Bundle b=new Bundle();
    b.putParcelableArrayList("imageurls", imagesUrlArrayList);
    b.putInt("int",12);
    i.putExtras(b);
    startService(i);

Folowing is code for Service class:

public class ImageDownloadService extends Service {

    private ArrayList<ImagesUrl> imagesUrlArrayList = new ArrayList<>();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {

        Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();

    }
    @Override
    public void onStart(Intent intent, int startid) {

        if(intent != null && intent.getParcelableArrayListExtra("imageurls") != null){
            imagesUrlArrayList = intent.getParcelableArrayListExtra("imageurls");
        }
        int val = intent.getIntExtra("int",0);
        Log.d(TAG, "onStart: "+(String.valueOf(imagesUrlArrayList.size())));
        Log.d(TAG, "onStart: "+(String.valueOf(imagesUrlArrayList.size())));
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
    }

    class GetImages extends AsyncTask<String, String, String> {

        private Integer current;
        String jsonStr;

        @Override
        protected String doInBackground(String... args) {

            try {
                Log.d(TAG, "doInBackground: "+String.valueOf(imagesUrlArrayList.size()));
                for (int i = 0; i < imagesUrlArrayList.size(); i++) {
                    downloadimage(imagesUrlArrayList.get(i).getImageurl(),imagesUrlArrayList.get(i).getFilename());
                }
                return "Images downloaded successfully. Please refresh your screen";

            } catch (Exception er) {
                Log.d(TAG, er.getMessage());
                appendLog(TAG+" GetCategories "+ er.getMessage());
                return er.getMessage();
            }

        }

        protected void onPostExecute(String file_url) {
          //  Toast.makeText(mContext, file_url, Toast.LENGTH_LONG).show();

        }
    }
    private  void  downloadimage(String URL ,String filename){

        try {
            URL url = new URL(URL);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.connect();

            /*Context wrapper = new ContextWrapper(mContext);*/
            /*File internalStorage = wrapper.getDir("freshImages",MODE_PRIVATE);*/
            String root = Environment.getExternalStorageDirectory().toString();
            File internalStorage = new File(root + "/fresh/freshImages");

            if (!internalStorage.exists()) {
                internalStorage.mkdirs();
            }

            File file = new File(internalStorage, filename);

            InputStream inputStream = new BufferedInputStream(url.openStream() , 40 );

            // Bitmap bm = BitmapFactory.decodeStream(inputStream);

            OutputStream fileOutput = new FileOutputStream(file);

            Bitmap bmp =createScaledBitmapFromStream(inputStream,100,100);

            bmp.compress(Bitmap.CompressFormat.PNG, 90, fileOutput);
            inputStream.close();
            fileOutput.close();
            /*OutputStream fileOutput = new FileOutputStream(file);

            byte[] buffer = new byte[8192];
            int bufferLength = 0;

            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                fileOutput.write(buffer, 0, bufferLength);
            }
            fileOutput.close();*/
            //    Toast.makeText(getApplicationContext(), "image downloased", Toast.LENGTH_SHORT).show();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected Bitmap createScaledBitmapFromStream( InputStream s, int minimumDesiredBitmapWidth, int minimumDesiredBitmapHeight ) {

        final BufferedInputStream is = new BufferedInputStream(s, 32*1024);
        try {
            final BitmapFactory.Options decodeBitmapOptions = new BitmapFactory.Options();
            // For further memory savings, you may want to consider using this option
            // decodeBitmapOptions.inPreferredConfig = Config.RGB_565; // Uses 2-bytes instead of default 4 per pixel

            if( minimumDesiredBitmapWidth >0 && minimumDesiredBitmapHeight >0 ) {
                final BitmapFactory.Options decodeBoundsOptions = new BitmapFactory.Options();
                decodeBoundsOptions.inJustDecodeBounds = true;
                is.mark(32*1024); // 32k is probably overkill, but 8k is insufficient for some jpgs
                BitmapFactory.decodeStream(is,null,decodeBoundsOptions);
                is.reset();

                final int originalWidth = decodeBoundsOptions.outWidth;
                final int originalHeight = decodeBoundsOptions.outHeight;

                // inSampleSize prefers multiples of 2, but we prefer to prioritize memory savings
                decodeBitmapOptions.inSampleSize= Math.max(1,Math.min(originalWidth / minimumDesiredBitmapWidth, originalHeight / minimumDesiredBitmapHeight));

            }

            return BitmapFactory.decodeStream(is,null,decodeBitmapOptions);

        } catch( IOException e ) {
            throw new RuntimeException(e); // this shouldn't happen
        } finally {
            try {
                is.close();
            } catch( IOException ignored ) {}
        }

    }

}

I  will call GetImages asyntask if i get pacelable arraylist right in service class.


问:
Remove duplicate values on each string in R
i have a dataframe with two columns:

```<code> VAR1.                     VAR2.

  A.              102 million; 102 million

  B.      0.1 million; 2 million; 0.1 million; 2 million
</code>```

I want to remove duplicate values of VAR2. for each row, obtaining

```<code> VAR1.           VAR2.

  A.          102 million

  B.     0.1 million; 2 million
</code>```

How can I do?

thank you for your suggestions.

答:
Using base R, we can split the string on ";" and paste unique entries for VAR2

```<code>sapply(strsplit(df$VAR2, ";"), function(x) paste(unique(x), collapse = ";"))
#[1] "102 million"           "0.1 million;2 million"
</code>```

Using dplyr and tidyr we can use separate_rows to bring VAR2 into different rows and then paste only unique entries per group.

```<code>library(dplyr)
library(tidyr)

df %>%
 separate_rows(VAR2, sep = ";") %>%
 group_by(VAR1) %>%
 summarise(VAR2 = paste(unique(VAR2), collapse = ";"))

#  VAR1  VAR2
#  <fct> <chr>
#1 A     102 million
#2 B     0.1 million;2 million
</code>```

Body:
i have a dataframe with two columns:

 VAR1.                     VAR2.

  A.              102 million; 102 million

  B.      0.1 million; 2 million; 0.1 million; 2 million

I want to remove duplicate values of VAR2. for each row, obtaining

 VAR1.           VAR2.

  A.          102 million

  B.     0.1 million; 2 million

How can I do?

thank you for your suggestions.

Body:
Using base R, we can split the string on ";" and paste unique entries for VAR2

sapply(strsplit(df$VAR2, ";"), function(x) paste(unique(x), collapse = ";"))
#[1] "102 million"           "0.1 million;2 million"

Using dplyr and tidyr we can use separate_rows to bring VAR2 into different rows and then paste only unique entries per group.

library(dplyr)
library(tidyr)

df %>%
 separate_rows(VAR2, sep = ";") %>%
 group_by(VAR1) %>%
 summarise(VAR2 = paste(unique(VAR2), collapse = ";"))

#  VAR1  VAR2
#  <fct> <chr>
#1 A     102 million
#2 B     0.1 million;2 million


问:
How do I forward requests from a client to a Windows Service running on Windows Server
I have an Angular application deployed to/via IIS. This app is sending requests to REST endpoints exposed by a Spring Boot application which I am running as a Windows Service (The Spring Boot application is accessing a MongoDB but this should not be relevant, I think). The exposed REST interface is accessable via port 8080 on the servers localhost.
The Angular app is accessible as it should be but there seems to be a problem when the web app tries to access the Spring Application's REST interfaces. More specific: The client seems to be receiving HTML documents when he should be receiving JSON files.

I am new to working with IIS so beginner errors are not unlikely. I'm happy to share more information if needed!

答:
Edit: I read again the question, and understood something wrong:

Looks like you were sending requests to your Angular server. For development you should use the embedded web server (https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-web-servers.html) in order to ease your server configuration steps. And from within the windows server, send request to localhost:springboot_port.

Once you want your service to be available for an external client, and to keep your service available/awake (something similar to systemd in Linux), you could try this: https://www.baeldung.com/spring-boot-app-as-a-service


问:
node | MySQL multiple WHERE with AND clause
I am trying to do a statement in node using mysql package. I am trying to select from a table WHERE with a AND clause such as WHERE id = 1 AND course = 1 so far I've got as far as being able to SELECT but I'm getting an error, I can see the error though and it's that there is no AND when I am binding the id.

This is my current code.

```<code>let sql = 'SELECT * FROM users WHERE ?';

let values = {
    id: 1,
    course: 1
}

database.query(sql, values, (err, result) => {

}
</code>```

This is the error I am getting...

SELECT * FROM users WHERE id = 1, course = 1

The query once it has been through node is missing the AND

Any help would be appreciated.

答:
I am defining a generic way of reforming a simple sql into parameterized query.

Let's say the given sql is:

```<code>var sql = "SELECT LK_USER_ID, LK_USER_STATUS, LK_USER_CONATCT_OFF FROM lk_users WHERE LK_USER_FNAME = 'test' AND LK_USER_LOGIN = 'debsnew' ORDER BY LK_USER_ID DESC LIMIT 1, 5";
</code>```

Now the parameterized query string version of the above query is:

```<code>var sql = 'SELECT ?? FROM ?? WHERE LK_USER_FNAME = ? AND LK_USER_LOGIN = ? ORDER BY ?? DESC LIMIT ?,?';
var columns = ['LK_USER_ID', 'LK_USER_STATUS', 'LK_USER_CONATCT_OFF'];
var tbl = TABLE_PREFIX +'user';
var query = mysql.conn.query(sql, [columns, tbl, 'test', 'debsnew', 'LK_USER_ID',  0, 5], (err, results, fileds) => {
    console.log(results);
    res.json({'status': 1, 'data': results});
});
</code>```

You can console log the generated sql as:

```<code>console.log(query.sql);
</code>```

In your case the sql is:

```<code>let sql = 'SELECT * FROM users WHERE id = 1 AND course = 1';
</code>```

The reformed parameterized query version is:

```<code>var sql = 'SELECT * FROM ?? WHERE id = ? AND course = ?';
var tbl = 'users';
var query = mysql.conn.query(sql, [tbl, 1, 1], (err, results, fileds) => {
    console.log(results);
    res.json({'status': 1, 'data': results});
});
</code>```

You can match the generated sql with the original one through

```<code>console.log(query.sql);
</code>```

Body:
I am trying to do a statement in node using mysql package. I am trying to select from a table WHERE with a AND clause such as WHERE id = 1 AND course = 1 so far I've got as far as being able to SELECT but I'm getting an error, I can see the error though and it's that there is no AND when I am binding the id.

This is my current code.

let sql = 'SELECT * FROM users WHERE ?';

let values = {
    id: 1,
    course: 1
}

database.query(sql, values, (err, result) => {

}

This is the error I am getting...

SELECT * FROM users WHERE id = 1, course = 1

The query once it has been through node is missing the AND

Any help would be appreciated.

Body:
I am defining a generic way of reforming a simple sql into parameterized query.

Let's say the given sql is:

var sql = "SELECT LK_USER_ID, LK_USER_STATUS, LK_USER_CONATCT_OFF FROM lk_users WHERE LK_USER_FNAME = 'test' AND LK_USER_LOGIN = 'debsnew' ORDER BY LK_USER_ID DESC LIMIT 1, 5";

Now the parameterized query string version of the above query is:

var sql = 'SELECT ?? FROM ?? WHERE LK_USER_FNAME = ? AND LK_USER_LOGIN = ? ORDER BY ?? DESC LIMIT ?,?';
var columns = ['LK_USER_ID', 'LK_USER_STATUS', 'LK_USER_CONATCT_OFF'];
var tbl = TABLE_PREFIX +'user';
var query = mysql.conn.query(sql, [columns, tbl, 'test', 'debsnew', 'LK_USER_ID',  0, 5], (err, results, fileds) => {
    console.log(results);
    res.json({'status': 1, 'data': results});
});

You can console log the generated sql as:

console.log(query.sql);

In your case the sql is:

let sql = 'SELECT * FROM users WHERE id = 1 AND course = 1';

The reformed parameterized query version is:

var sql = 'SELECT * FROM ?? WHERE id = ? AND course = ?';
var tbl = 'users';
var query = mysql.conn.query(sql, [tbl, 1, 1], (err, results, fileds) => {
    console.log(results);
    res.json({'status': 1, 'data': results});
});

You can match the generated sql with the original one through

console.log(query.sql);


问:
Error on install angular cli 7 on mac osx Mojave
I'm having error on install angular@cli on Mac Osx Mojave 10.14.5 with node version 10.15.3 and npm 6.9.0

I've also tried to remove and reinstall node and npm, and follow this article Error installing angular/cli on macOS mojave - node-pre-gyp

```<code>npm install -g @angular/cli
sudo npm install -g @angular/cli

npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/@angular/cli
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/@angular/cli/node_modules
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/@angular
npm ERR! path /usr/local/lib/node_modules/@angular/cli
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules/@angular/cli'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules/@angular/cli']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules/@angular/cli\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules/@angular/cli' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/fabiodigiuseppe/.npm/_logs/2019-05-26T15_39_28_869Z-debug.log
</code>```

答:
For everyone who find this problem during installation, i've resolved by install angular/cli with this:

sudo npm install -g @angular/cli --unsafe-perm

Body:
I'm having error on install angular@cli on Mac Osx Mojave 10.14.5 with node version 10.15.3 and npm 6.9.0

I've also tried to remove and reinstall node and npm, and follow this article Error installing angular/cli on macOS mojave - node-pre-gyp

npm install -g @angular/cli
sudo npm install -g @angular/cli

npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/@angular/cli
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/@angular/cli/node_modules
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/@angular
npm ERR! path /usr/local/lib/node_modules/@angular/cli
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules/@angular/cli'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules/@angular/cli']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules/@angular/cli\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules/@angular/cli' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/fabiodigiuseppe/.npm/_logs/2019-05-26T15_39_28_869Z-debug.log


问:
plsql works in Sql Developer, but not in a liquibase change ORA-06550 PLS-00103
I have the following code that has no issue running in SQL Developer, but when I put inside a liquibase change and run it I get an error.

```<code>DECLARE
  seqval NUMBER;
BEGIN
  SELECT MAX(id) + 1 INTO seqval FROM T_SLS_ITEMS;
  execute immediate('CREATE SEQUENCE SEQ_SLS_ITEMS MINVALUE '||seqval||'');
END;
</code>```

and the changeset for it:

```<code>     <changeSet author="Cristian Marian (cmarian)" id="2019-05-24-171101 Fix Items sequence - creting">
        <sql>
          DECLARE
            seqval NUMBER;
          BEGIN
            SELECT MAX(id) + 1 INTO seqval FROM T_SLS_ITEMS;
            execute immediate('CREATE SEQUENCE SEQ_SLS_ITEMS MINVALUE '||seqval||'');
          END;
        </sql>
    </changeSet>
</code>```

The error looks like this:

```<code>Reason: liquibase.exception.DatabaseException: ORA-06550: line 2, column 27:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:

   := . ( @ % ; not null range default character
 [Failed SQL: DECLARE
              seqval NUMBER] (Liquibase Update failed.)
</code>```

答:
Liquibase will try to split up the "script" inside the <sql> tag by the default statement delimiter which is ;. For a PL/SQL block this is obviously wrong, as the whole block needs to be treated as single statement.

To achieve that, use splitStatements attribute in the <sql> tag:

```<code><sql splitStatements="false">
  DECLARE
   ....
  END;
</sql>
</code>```

Body:
I have the following code that has no issue running in SQL Developer, but when I put inside a liquibase change and run it I get an error.

DECLARE
  seqval NUMBER;
BEGIN
  SELECT MAX(id) + 1 INTO seqval FROM T_SLS_ITEMS;
  execute immediate('CREATE SEQUENCE SEQ_SLS_ITEMS MINVALUE '||seqval||'');
END;

and the changeset for it:

     <changeSet author="Cristian Marian (cmarian)" id="2019-05-24-171101 Fix Items sequence - creting">
        <sql>
          DECLARE
            seqval NUMBER;
          BEGIN
            SELECT MAX(id) + 1 INTO seqval FROM T_SLS_ITEMS;
            execute immediate('CREATE SEQUENCE SEQ_SLS_ITEMS MINVALUE '||seqval||'');
          END;
        </sql>
    </changeSet>

The error looks like this:

Reason: liquibase.exception.DatabaseException: ORA-06550: line 2, column 27:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:

   := . ( @ % ; not null range default character
 [Failed SQL: DECLARE
              seqval NUMBER] (Liquibase Update failed.)

Body:
Liquibase will try to split up the "script" inside the <sql> tag by the default statement delimiter which is ;. For a PL/SQL block this is obviously wrong, as the whole block needs to be treated as single statement.

To achieve that, use splitStatements attribute in the <sql> tag:

<sql splitStatements="false">
  DECLARE
   ....
  END;
</sql>


问:
Selenium Firefox loads the profile but the web driver part isn't working anymore
```<code>        FirefoxOptions options3 = new FirefoxOptions();
        options3.setHeadless(false);
        options3.addArguments("profile","C:\\Users\\Administrator\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\i8k6kx4s.default");
        WebDriver driver3 = new FirefoxDriver(options3);false);
        Thread.sleep(1000);
        driver3.get("https://ramdonwebsit.com");
</code>```

It opens the profile but does not go to the website. I am trying to load a specific profile that has saved cache data and passwords in it, so I can just go to the website straight and avoid a login issue that has captchas.

答:
Try below -</p>

```<code>ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("Your_Profile");
WebDriver driver = new FirefoxDriver(myprofile);
Thread.sleep(1000);
driver.get("https://ramdonwebsit.com");
</code>```

Body:
        FirefoxOptions options3 = new FirefoxOptions();
        options3.setHeadless(false);
        options3.addArguments("profile","C:\\Users\\Administrator\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\i8k6kx4s.default");
        WebDriver driver3 = new FirefoxDriver(options3);false);
        Thread.sleep(1000);
        driver3.get("https://ramdonwebsit.com");

It opens the profile but does not go to the website. I am trying to load a specific profile that has saved cache data and passwords in it, so I can just go to the website straight and avoid a login issue that has captchas.

Body:
Try below -

ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("Your_Profile");
WebDriver driver = new FirefoxDriver(myprofile);
Thread.sleep(1000);
driver.get("https://ramdonwebsit.com");


问:
Pylint "unresolved import" error in Visual Studio Code
I am using the following setup

macOS v10.14 (Mojave)

Python 3.7.1

Visual Studio Code 1.30

Pylint 2.2.2

Django 2.1.4

I want to use linting to make my life a bit easier in Visual Studio Code. However, for every import I have states "unresolved import". Even on default Django imports (i.e. from django.db import models).

I presume it is because it is not seeing the virtual environment Python files.

Everything works just fine, but it's starting to get annoying.

The interpreter choices I have are all system versions of Python. It does not seem to see my virtual environment Python at all (it is not in the same directory as my workspace, so that part makes sense).

If I set up the python.PythonPath in the settings.json file, it just ignores it and does not list my virtual environment path as an option. I also tried setting it up in my global Python settings, but it also does not show up.

Is there a quick fix to get it working?

答:
When I do > reload window that fixes it.

Reference: Python unresolved import issue #3840, dkavraal's comment


问:
How to change selected value of JQuery-select2 dropdown by option list Index number using JQuery
Iam using dropdown box which is implemented using JQuery-select2 version 3.5.

I want to set the 2'nd item selected from the list like  $("#fieldId").prop("selectedIndex",1) using JQuery.

Is it possible?

Thanks in advance

答:
```<code>$('#selectId').find('option').each(function(index,element){
    if(element.value.toLowerCase().trim() == 'VAL_TO_MATCH'){
         $("#selectId").prop('selectedIndex', index).change();
    }
});
</code>```