问:
Syntax error when passing function with arguments to a function (python)
Learning decorators and I wanted to pass a function with arguments to a decorator function like shown below but I always get a syntax error. Please help!

```<code>def decorator(func(*args)):
    def wrapper():
        print('up')
        func(*args)
        print('down')
    return wrapper

@decorator
def func(n):
    print(n)

func('middle')
</code>```

Output:

```<code>File "<ipython-input-21-c2d727543f8e>", line 1
    def decorator(func(*args)):
                      ^
SyntaxError: invalid syntax
</code>```

答:
Your syntax is incorrect. To define a correct decorator and wrapper function, see what follows:

```<code>def decorator(func):       # assign the function you want to pass
    def wrapper(*args):    # assign the parameters you want to use for the function
        print('up')
        func(*args)
        print('down')
    return wrapper

@decorator
def func(n):               # The function you want to decorate
    print(n)

func('middle')
</code>```

Output:

```<code>up
middle
down
</code>```

Body:
Learning decorators and I wanted to pass a function with arguments to a decorator function like shown below but I always get a syntax error. Please help!

def decorator(func(*args)):
    def wrapper():
        print('up')
        func(*args)
        print('down')
    return wrapper

@decorator
def func(n):
    print(n)

func('middle')

Output:

File "<ipython-input-21-c2d727543f8e>", line 1
    def decorator(func(*args)):
                      ^
SyntaxError: invalid syntax

Body:
Your syntax is incorrect. To define a correct decorator and wrapper function, see what follows:

def decorator(func):       # assign the function you want to pass
    def wrapper(*args):    # assign the parameters you want to use for the function
        print('up')
        func(*args)
        print('down')
    return wrapper

@decorator
def func(n):               # The function you want to decorate
    print(n)

func('middle')

Output:

up
middle
down


来源: stackexchange

问:
Is there a mistake in FeathersJS generator?
When generating a service with feathersjs, the model file looks like this

```<code>import { Application } from '../declarations';

export default function (app: Application) {
  const modelName = 'comments';
  const mongooseClient = app.get('mongooseClient');
  const { Schema } = mongooseClient;
  const schema = new Schema({
    text: { type: String, required: true }
  }, {
    timestamps: true
  });

  // This is necessary to avoid model compilation errors in watch mode
  // see https://mongoosejs.com/docs/api/connection.html#connection_Connection-deleteModel
  if (mongooseClient.modelNames().includes(modelName)) {
    mongooseClient.deleteModel(modelName);
  }
  return mongooseClient.model(modelName, schema);
}
</code>```

The mongooseClient is of type Mongoose and the documentation says deleteModel is under the Connection.prototype.deleteModel()

Shouldn't the line say mongooseClient.connection.deleteModel(modelName); ??

答:
No it shouldn't

If you look at the file mongoose.js under root folder you can see 'mongooseClient' is setting after mongoose.connect :

const mongoose = require('mongoose');

    module.exports = function (app) {
      mongoose.connect(
        app.get('mongodb'),
        { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true }
      );
      mongoose.Promise = global.Promise;

      app.set('mongooseClient', mongoose);
    };
```

So it is part of Connection.prototype.

ContentLicense: CC BY-SA 4.0

Body:
When generating a service with feathersjs, the model file looks like this

import { Application } from '../declarations';

export default function (app: Application) {
  const modelName = 'comments';
  const mongooseClient = app.get('mongooseClient');
  const { Schema } = mongooseClient;
  const schema = new Schema({
    text: { type: String, required: true }
  }, {
    timestamps: true
  });

  // This is necessary to avoid model compilation errors in watch mode
  // see https://mongoosejs.com/docs/api/connection.html#connection_Connection-deleteModel
  if (mongooseClient.modelNames().includes(modelName)) {
    mongooseClient.deleteModel(modelName);
  }
  return mongooseClient.model(modelName, schema);
}

The mongooseClient is of type Mongoose and the documentation says deleteModel is under the Connection.prototype.deleteModel()

Shouldn't the line say mongooseClient.connection.deleteModel(modelName); ??

Body:
No it shouldn't

If you look at the file mongoose.js under root folder you can see 'mongooseClient' is setting after mongoose.connect :

const mongoose = require('mongoose');

    module.exports = function (app) {
      mongoose.connect(
        app.get('mongodb'),
        { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true }
      );
      mongoose.Promise = global.Promise;

      app.set('mongooseClient', mongoose);
    };

So it is part of Connection.prototype.


问:
three.js - Adjusting opacity of individual particles
I am trying to vary the opacity of particles as a function of their distance from a plane.

This issue describes my problem, and the answer a year ago was essentially "you can't". Opacity is apparently a parameter of a material, not an element, and hence individual particle opacity is not possible.

Has anything changed, is there any way I could achieve this? If individual particle colouring is possible, I imagine this isn't out of reach.

Cheers

答:
Not sure why, but proposed solution didn't work for me. I used somewhat tricky shading to make points round and blurry at edges. So the corners of points were supposed to be transparent, but they appeared black: http://jsfiddle.net/5kz64ero/1/

Relevant part of my fragment shader:

```<code>// Distance from 0.0 to 0.5 from the center of the point
float d = distance(gl_PointCoord, vec2(0.5, 0.5));

// Applying sigmoid to smoothen the edge
float opacity = 1.0 / (1.0 + exp(16.0 * (d - 0.25)));

gl_FragColor = vec4(opacity * vColor, opacity);
</code>```

I figured that traditionally this is solved by depth-sorting (with farthest points coming first), and I found some evidence that some older implementations of ParticleSystem in Three contained sortParticles attribute. But it's not there anymore. And in my case sorting would really involve redoing that every time camera position changes. Instead I set depthWrite: false and it seems to solve the issue.

The result: http://jsfiddle.net/5kz64ero/6/

ContentLicense: CC BY-SA 3.0

Body:
Not sure why, but proposed solution didn't work for me. I used somewhat tricky shading to make points round and blurry at edges. So the corners of points were supposed to be transparent, but they appeared black: http://jsfiddle.net/5kz64ero/1/

Relevant part of my fragment shader:

// Distance from 0.0 to 0.5 from the center of the point
float d = distance(gl_PointCoord, vec2(0.5, 0.5));

// Applying sigmoid to smoothen the edge
float opacity = 1.0 / (1.0 + exp(16.0 * (d - 0.25)));

gl_FragColor = vec4(opacity * vColor, opacity);

I figured that traditionally this is solved by depth-sorting (with farthest points coming first), and I found some evidence that some older implementations of ParticleSystem in Three contained sortParticles attribute. But it's not there anymore. And in my case sorting would really involve redoing that every time camera position changes. Instead I set depthWrite: false and it seems to solve the issue.

The result: http://jsfiddle.net/5kz64ero/6/


问:
Why is this for loop not logging sum?
I am trying to use this for loop within the function to get the sum of an array. However, when I call the function I receive NaN.</p>

```<code>tips = [1,2,3,4,5]
function sumTip (tips){
  for (i=0; i<tips.length; i++){
    var total = total + tips[i];
    console.log(total);
  }
}
sumTip();
</code>```

答:
Error 1 - Wrong syntax. It should be tips.length and not length.tips.

Error 2 - You haven't given the parameter to the function when you
are calling it. It should be sumTip(tips);

Error 3 - i is not declared in the loop.

Error 4 - For your logic to work, the total should be declared and initialised to zero outside the for loop and then used inside the loop.

You are doing - var total = total + tips[i]; when total hasn't been defined yet so the in the expression total + tips[i] evaluates to NaN and that's why you are getting Nan as output.

The following code should work after correcting the above mentioned errors -

```<code>tips = [1,2,3,4,5]
function sumTip (tips){
  var total = 0;
  for (var i=0; i<tips.length; i++){
    total = total + tips[i];
    console.log(total);
  }
}
sumTip(tips);
</code>```

Title: Why is this for loop not logging sum?

Body:
I am trying to use this for loop within the function to get the sum of an array. However, when I call the function I receive NaN.

tips = [1,2,3,4,5]
function sumTip (tips){
  for (i=0; i<tips.length; i++){
    var total = total + tips[i];
    console.log(total);
  }
}
sumTip();

Body:
Error 1 - Wrong syntax. It should be tips.length and not length.tips.

Error 2 - You haven't given the parameter to the function when you
are calling it. It should be sumTip(tips);

Error 3 - i is not declared in the loop.

Error 4 - For your logic to work, the total should be declared and initialised to zero outside the for loop and then used inside the loop.

You are doing - var total = total + tips[i]; when total hasn't been defined yet so the in the expression total + tips[i] evaluates to NaN and that's why you are getting Nan as output.

The following code should work after correcting the above mentioned errors -

tips = [1,2,3,4,5]
function sumTip (tips){
  var total = 0;
  for (var i=0; i<tips.length; i++){
    total = total + tips[i];
    console.log(total);
  }
}
sumTip(tips);


问:
Java - escape string to prevent SQL injection
I'm trying to put some anti sql injection in place in java and am finding it very difficult to work with the the "replaceAll" string function. Ultimately I need a function that will convert any existing \ to \\, any " to \", any ' to \', and any \n to \\n so that when the string is evaluated by MySQL SQL injections will be blocked.

I've jacked up some code I was working with and all the \\\\\\\\\\\ in the function are making my eyes go nuts. If anyone happens to have an example of this I would greatly appreciate it.

答:
If you are using PL/SQL you can also use DBMS_ASSERT
it can sanitize your input so you can use it without worrying about SQL injections.

see this answer for instance:
https://stackoverflow.com/a/21406499/1726419

ContentLicense: CC BY-SA 2.5


答:
Just a few changes: arguments for a function you need to provide as *args inside wrapper. And and another thing - remove *args from decorator(func(*args)). </p>

```<code>def decorator(func):
    def wrapper(*args):
        print('up')
        func(*args)
        print('down')
    return wrapper

@decorator
def func(n):
    print(n)

func('middle')
</code>```

Title: Syntax error when passing function with arguments to a function (python)

Body:
Just a few changes: arguments for a function you need to provide as *args inside wrapper. And and another thing - remove *args from decorator(func(*args)).

def decorator(func):
    def wrapper(*args):
        print('up')
        func(*args)
        print('down')
    return wrapper

@decorator
def func(n):
    print(n)

func('middle')


问:
Getting typeface and Windows name of font that is not installed
Can someone tell me how can I get the typeface name of a font? And how can I take the Windows name of the font having the typeface name?

Like "arialblackno1.ttf" that have typeface "arialblack".

but I am looking to get the typeface name of a font that isn't installed, it is just in a folder.

答:
You say in a comment that you need the name of a font that isn't installed in Windows.

There are two ways of doing this that I can think of:-

Use FreeType

Or, use GDI+, and PrivateFontCollection.AddFontFile()

Either way, you will need to find Delphi wrappers for these libraries. Google should help.

There seems to be a FreeType binding as part of AggPas. It's not something I've tried, though.


问:
PowerShell Question: script to move my video files from separate folders on my hard drive to a central folder
I have created a PowerShell script to move my video files from separate folders on my hard drive to a central folder. The script looks like this:

```<code>#location of starting directory
$_sourcePath ="C:\Movies\ -recurse"
#location where files will be copied to
$_destinationPath = "C:\New\"
#Array of extension that need to move from source path
$_FileType= @("*.*mp4")
</code>```

When the scrip runs, nothing happens. I get no errors, but I also don't  get an of the *.mp4 files moved.
what is wrong with this script?

答:
Try this</p>

```<code>$_sourcePath ="C:\Movies\"
$_destinationPath = "C:\New";

$_FileType= @("*.*mp4")

Get-ChildItem -recurse ($_sourcePath) -include ($_FileType) | move-Item -Destination ($_destinationPath)`
</code>```

Body:
I have created a PowerShell script to move my video files from separate folders on my hard drive to a central folder. The script looks like this:

#location of starting directory
$_sourcePath ="C:\Movies\ -recurse"
#location where files will be copied to
$_destinationPath = "C:\New\"
#Array of extension that need to move from source path
$_FileType= @("*.*mp4")

When the scrip runs, nothing happens. I get no errors, but I also don't  get an of the *.mp4 files moved.
what is wrong with this script?

Body:
Try this

$_sourcePath ="C:\Movies\"
$_destinationPath = "C:\New";

$_FileType= @("*.*mp4")

Get-ChildItem -recurse ($_sourcePath) -include ($_FileType) | move-Item -Destination ($_destinationPath)`


问:
HTML Resize content of iFrame
I'm currently using the prebuildt email form of sendgrid as an iFrame.

Everything is working as expected. The only problem I have is that on mobile devices the content of the iFrame is too big to get shown on the screen as you can see on the image:

So I tried to resize the content with the scale: 0.5, but it just make the whole iFrame smaller.

My current CSS-Code is the following:

```<code> .bg-modal {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    justify-content: center;
    align-items: center;
}

.modal-contents {
    height: 600px;
    width: 600px;
    background-color: white;
    text-align: center;
    position: relative;
    border-radius: 4px;
}

.iframeClass{
    width: 100%;
    height:100%;
    overflow:hidden;
}
</code>```

and my HTML is this:

```<code><div class="bg-modal">
<div class="modal-contents">
    <iframe scrolling="no" class="iframeClass" frameborder="0" src="https://..."></iframe>
</div>
</div>
</code>```

I don't want to show the scrollbars.

Does someone know a solution for this repsonsive problem?

答:
Your device is lower resolution than 600px so it will scroll sideways.

You could use max-width to sort it out.

The solution

```<code>.bg-modal {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    justify-content: center;
    align-items: center;
}

.modal-contents {
    height: 600px;
    width: 600px;
    max-width: 100%; /* This makes it so if the device is under 600px, it will resize to be the width of the screen and it will not overflow */
    background-color: white;
    text-align: center;
    position: relative;
    border-radius: 4px;
}

.iframeClass{
    width: 100%;
    height:100%;
    overflow:hidden;
}
</code>```

If you are still getting problems, try this:

```<code>body {
    overflow-x: hidden;
}
</code>```

Title: HTML Resize content of iFrame

Body:
I'm currently using the prebuildt email form of sendgrid as an iFrame.

Everything is working as expected. The only problem I have is that on mobile devices the content of the iFrame is too big to get shown on the screen as you can see on the image:

So I tried to resize the content with the scale: 0.5, but it just make the whole iFrame smaller.

My current CSS-Code is the following:

 .bg-modal {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    justify-content: center;
    align-items: center;
}

.modal-contents {
    height: 600px;
    width: 600px;
    background-color: white;
    text-align: center;
    position: relative;
    border-radius: 4px;
}

.iframeClass{
    width: 100%;
    height:100%;
    overflow:hidden;
}

and my HTML is this:

I don't want to show the scrollbars.

Does someone know a solution for this repsonsive problem?

Body:
Your device is lower resolution than 600px so it will scroll sideways.

You could use max-width to sort it out.

The solution

.bg-modal {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    justify-content: center;
    align-items: center;
}

.modal-contents {
    height: 600px;
    width: 600px;
    max-width: 100%; /* This makes it so if the device is under 600px, it will resize to be the width of the screen and it will not overflow */
    background-color: white;
    text-align: center;
    position: relative;
    border-radius: 4px;
}

.iframeClass{
    width: 100%;
    height:100%;
    overflow:hidden;
}

If you are still getting problems, try this:

body {
    overflow-x: hidden;
}


问:
What's more efficient for counting, Arrays or Hashmap(or Set)
Assume we're asked to count and print the occurrences of each character in a given String. For simplicity, the string has just lowercase letters. I wrote these 2 functions and I want to know which one is more efficient/preferable in Java.

Function 1:

```<code>private void countAndPrintArray1(String str){
        int[] a = new int[26];
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int index = c - 'a';
            a[index] = a[index] + 1;
        }

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int freq = a[c -'a'];
            System.out.println(c+" -> "+ freq);
        }
    }
</code>```

Function 2:

```<code>    private void countAndPrintArray2(String str){
        Map<Character, Integer> map = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int freq = map.getOrDefault(c, 0) + 1;
            map.put(c, freq);
        }

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int freq = map.get(c);
            System.out.println(c+" -> "+ freq);
        }
    }
</code>```

答:
Comparing the two approaches based on their performances, both of the algorithms run in O(n) time complexity where n is the size of the string provided. Also, the space complexity is O(1) in both cases.
Talking about the preference, it depends on the developer and the team which is developing the product. Though the HashMap approach seems to be more elite and clean (again developer opinion).</p>

Body:
Assume we're asked to count and print the occurrences of each character in a given String. For simplicity, the string has just lowercase letters. I wrote these 2 functions and I want to know which one is more efficient/preferable in Java.

Function 1:

private void countAndPrintArray1(String str){
        int[] a = new int[26];
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int index = c - 'a';
            a[index] = a[index] + 1;
        }

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int freq = a[c -'a'];
            System.out.println(c+" -> "+ freq);
        }
    }

Function 2:

    private void countAndPrintArray2(String str){
        Map<Character, Integer> map = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int freq = map.getOrDefault(c, 0) + 1;
            map.put(c, freq);
        }

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            int freq = map.get(c);
            System.out.println(c+" -> "+ freq);
        }
    }


问:
how to auto load mobile templates by agent in codeigniter?
```<code>dir:
</code>```

```
application
 -controllers
 -models
 -views
 -mobile_views
```

How do I auto load templates at mobile_views when I use $this->load->view and view by iphone or other mobile phone?

答:
to load views from another dir aside from "views", i found this forum topic to be helpful

http://codeigniter.com/forums/viewthread/132960/

```<code>function external_view($path, $view, $vars = array(), $return = FALSE)
    {
        $full_path = $path.$view.'.php';
        if (file_exists($full_path))
        {
            return $this->_ci_load(array('_ci_path' => $full_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
        }
        else
        {
            show_error('Unable to load the requested module template file: '.$view);
        }
    }
</code>```

and you can work the rest from the controller.

Body:
dir:

application
 -controllers
 -models
 -views
 -mobile_views

How do I auto load templates at mobile_views when I use $this->load->view and view by iphone or other mobile phone?

Body:
to load views from another dir aside from "views", i found this forum topic to be helpful

http://codeigniter.com/forums/viewthread/132960/

function external_view($path, $view, $vars = array(), $return = FALSE)
    {
        $full_path = $path.$view.'.php';
        if (file_exists($full_path))
        {
            return $this->_ci_load(array('_ci_path' => $full_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
        }
        else
        {
            show_error('Unable to load the requested module template file: '.$view);
        }
    }

and you can work the rest from the controller.


问:
Case Syntax - Subtraction of 2 values gives incorrect number
I am working on this assignment:

The code that I wrote based on this is:

```<code>SELECT Number1, Number2, MathOperation, Result = CASE
WHEN MathOperation = 'Addition' THEN Number1 + Number2
WHEN MathOperation = 'Substraction' THEN Number1 - Number2
WHEN MathOperation = 'Multiplication' THEN Number1 * Number2
ELSE Number1 / Number2
END
FROM @Math;
</code>```

The Subtraction Result (Second WHEN) is the same as the Division Result (ELSE), which is not correct.
I am not sure what I am doing incorrectly. Could you please help?

答:
It is giving the correct result.

Your query is not working properly/behaving differently and producing the wrong result, it might be because the data in the table Subtraction and the value in the case statement Substraction is different.

```<code>create table Math(id int identity(1, 1) primary key
, Number1 decimal(16, 2)
, Number2 decimal(16, 2)
, MathOperation NVARCHAR(100))

insert into Math values
  (128, 48, 'Addition')
, (128, 48, 'Substraction')
, (128, 48, 'Multiplication')
, (128, 48, 'Division')

SELECT Number1
    ,Number2
    ,MathOperation
    ,Result = CASE
        WHEN MathOperation = 'Addition'
            THEN Number1 + Number2
        WHEN MathOperation = 'Substraction'
            THEN Number1 - Number2
        WHEN MathOperation = 'Multiplication'
            THEN Number1 * Number2
        ELSE Number1 / Number2
        END
FROM Math
</code>```

db<>fiddle demo

Body:
I am working on this assignment:

The code that I wrote based on this is:

SELECT Number1, Number2, MathOperation, Result = CASE
WHEN MathOperation = 'Addition' THEN Number1 + Number2
WHEN MathOperation = 'Substraction' THEN Number1 - Number2
WHEN MathOperation = 'Multiplication' THEN Number1 * Number2
ELSE Number1 / Number2
END
FROM @Math;

The Subtraction Result (Second WHEN) is the same as the Division Result (ELSE), which is not correct.
I am not sure what I am doing incorrectly. Could you please help?

Body:
It is giving the correct result.

Your query is not working properly/behaving differently and producing the wrong result, it might be because the data in the table Subtraction and the value in the case statement Substraction is different.

create table Math(id int identity(1, 1) primary key
, Number1 decimal(16, 2)
, Number2 decimal(16, 2)
, MathOperation NVARCHAR(100))

insert into Math values
  (128, 48, 'Addition')
, (128, 48, 'Substraction')
, (128, 48, 'Multiplication')
, (128, 48, 'Division')

SELECT Number1
    ,Number2
    ,MathOperation
    ,Result = CASE
        WHEN MathOperation = 'Addition'
            THEN Number1 + Number2
        WHEN MathOperation = 'Substraction'
            THEN Number1 - Number2
        WHEN MathOperation = 'Multiplication'
            THEN Number1 * Number2
        ELSE Number1 / Number2
        END
FROM Math

db<>fiddle demo


问:
Node/Postgresql Error: connect ECONNREFUSED 127.0.0.1:5432 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
I've been running a Node server that connects to a Postgresql DB (via Knex). Everything was working absolutely fine and as intended until my laptop crashed. Since restarting, the DB connection will not work at all, and I get the following error:

```<code>Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
</code>```

Attempting a Postgresql connection via DBeaver also results in the same error. My server itself can start up absolutely fine. I only get the error when making an API call that tries to connect to the DB. My DB connection set up looks like this:

```<code>const db = knex({
  client: 'pg',
  connection: DATABASE_URL,
});
</code>```

Again, this was all working perfectly until my laptop crashed. I'm guessing something happened during that process, but I'm not sure what or how to fix it. Any ideas/advice would be appreciated!

Full npm log below:

```<code>0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '/Users/<name>/.nvm/versions/node/v12.16.2/bin/node',
1 verbose cli   '/Users/<name>/.nvm/versions/node/v12.16.2/bin/npm',
1 verbose cli   'run',
1 verbose cli   'dev'
1 verbose cli ]
2 info using npm@6.14.4
3 info using node@v12.16.2
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle express-boilerplate@1.0.0~predev: express-boilerplate@1.0.0
6 info lifecycle express-boilerplate@1.0.0~dev: express-boilerplate@1.0.0
7 verbose lifecycle express-boilerplate@1.0.0~dev: unsafe-perm in lifecycle true
8 verbose lifecycle express-boilerplate@1.0.0~dev: PATH:         /Users/<name>/.nvm/versions/node/v12.16.2/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/<name>/Desktop/BLOC/productify-server/node_modules/.bin:/Users/<name>/.nvm/versions/node/v12.16.2/bin:/Library/Frameworks/Python.framework/Versions/3.8/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Users/<name>/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/<name>/Downloads/apache-maven-3.6.1 :/usr/local/share/dotnet
9 verbose lifecycle express-boilerplate@1.0.0~dev: CWD: /Users/<name>/Desktop/BLOC/productify-server
10 silly lifecycle express-boilerplate@1.0.0~dev: Args: [ '-c', 'nodemon src/server.js' ]
11 silly lifecycle express-boilerplate@1.0.0~dev: Returned: code: 130  signal: null
12 info lifecycle express-boilerplate@1.0.0~dev: Failed to exec dev script
13 verbose stack Error: express-boilerplate@1.0.0 dev: `nodemon src/server.js`
13 verbose stack Exit status 130
13 verbose stack     at EventEmitter.<anonymous> (/Users/<name>/.nvm/versions/node/v12.16.2/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:310:20)
13 verbose stack     at ChildProcess.<anonymous> (/Users/<name>/.nvm/versions/node/v12.16.2/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:310:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid express-boilerplate@1.0.0
15 verbose cwd /Users/<name>/Desktop/BLOC/productify-server
16 verbose Darwin 19.4.0
17 verbose argv "/Users/<name>/.nvm/versions/node/v12.16.2/bin/node" "/Users/<name>/.nvm/versions/node/v12.16.2/bin/npm" "run" "dev"
18 verbose node v12.16.2
19 verbose npm  v6.14.4
20 error code ELIFECYCLE
21 error errno 130
22 error express-boilerplate@1.0.0 dev: `nodemon src/server.js`
22 error Exit status 130
23 error Failed at the express-boilerplate@1.0.0 dev script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 130, true ]
</code>```

答:
You are having a problem with your PostgreSQL in your Windows machine, try to restart your PostgreSQL server using the following command:

```<code>pg_ctl -D "C:\Program Files\PostgreSQL\9.6\data" restart
</code>```

If this does not solve your problem, try to look at the logs where the problem is.

The logs are available on the dir %PROGRAMFILES%\PostgreSQL\9.3\data\pg_log (adjusting for your PostgreSQL version and where you installed PostgreSQL if you didn't use the defaults).

Body:
I've been running a Node server that connects to a Postgresql DB (via Knex). Everything was working absolutely fine and as intended until my laptop crashed. Since restarting, the DB connection will not work at all, and I get the following error:

Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)

Attempting a Postgresql connection via DBeaver also results in the same error. My server itself can start up absolutely fine. I only get the error when making an API call that tries to connect to the DB. My DB connection set up looks like this:

const db = knex({
  client: 'pg',
  connection: DATABASE_URL,
});

Again, this was all working perfectly until my laptop crashed. I'm guessing something happened during that process, but I'm not sure what or how to fix it. Any ideas/advice would be appreciated!

Full npm log below:

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '/Users/<name>/.nvm/versions/node/v12.16.2/bin/node',
1 verbose cli   '/Users/<name>/.nvm/versions/node/v12.16.2/bin/npm',
1 verbose cli   'run',
1 verbose cli   'dev'
1 verbose cli ]
2 info using npm@6.14.4
3 info using node@v12.16.2
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle express-boilerplate@1.0.0~predev: express-boilerplate@1.0.0
6 info lifecycle express-boilerplate@1.0.0~dev: express-boilerplate@1.0.0
7 verbose lifecycle express-boilerplate@1.0.0~dev: unsafe-perm in lifecycle true
8 verbose lifecycle express-boilerplate@1.0.0~dev: PATH:         /Users/<name>/.nvm/versions/node/v12.16.2/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/<name>/Desktop/BLOC/productify-server/node_modules/.bin:/Users/<name>/.nvm/versions/node/v12.16.2/bin:/Library/Frameworks/Python.framework/Versions/3.8/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Users/<name>/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/<name>/Downloads/apache-maven-3.6.1 :/usr/local/share/dotnet
9 verbose lifecycle express-boilerplate@1.0.0~dev: CWD: /Users/<name>/Desktop/BLOC/productify-server
10 silly lifecycle express-boilerplate@1.0.0~dev: Args: [ '-c', 'nodemon src/server.js' ]
11 silly lifecycle express-boilerplate@1.0.0~dev: Returned: code: 130  signal: null
12 info lifecycle express-boilerplate@1.0.0~dev: Failed to exec dev script
13 verbose stack Error: express-boilerplate@1.0.0 dev: `nodemon src/server.js`
13 verbose stack Exit status 130
13 verbose stack     at EventEmitter.<anonymous> (/Users/<name>/.nvm/versions/node/v12.16.2/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:310:20)
13 verbose stack     at ChildProcess.<anonymous> (/Users/<name>/.nvm/versions/node/v12.16.2/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:310:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid express-boilerplate@1.0.0
15 verbose cwd /Users/<name>/Desktop/BLOC/productify-server
16 verbose Darwin 19.4.0
17 verbose argv "/Users/<name>/.nvm/versions/node/v12.16.2/bin/node" "/Users/<name>/.nvm/versions/node/v12.16.2/bin/npm" "run" "dev"
18 verbose node v12.16.2
19 verbose npm  v6.14.4
20 error code ELIFECYCLE
21 error errno 130
22 error express-boilerplate@1.0.0 dev: `nodemon src/server.js`
22 error Exit status 130
23 error Failed at the express-boilerplate@1.0.0 dev script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 130, true ]

Body:
You are having a problem with your PostgreSQL in your Windows machine, try to restart your PostgreSQL server using the following command:

pg_ctl -D "C:\Program Files\PostgreSQL\9.6\data" restart

If this does not solve your problem, try to look at the logs where the problem is.

The logs are available on the dir %PROGRAMFILES%\PostgreSQL\9.3\data\pg_log (adjusting for your PostgreSQL version and where you installed PostgreSQL if you didn't use the defaults).


问:
Lazy load images on Hugo
I am trying to lazy load images on my hugo website.

I downloaded the npm plugin lazyload by typing: npm i lazyload.

In my code if I follow the documentation, I just have to write:

When I am doing that, the image is not displaying anymore, I think it is because of the data-src.
But without the data-src I can't do a lazyload. So it is very confused.

答: Just using the tag loading=lazy will work in the newer versions of most modern browsers.

Title: Lazy load images on Hugo


问:
Using a for loop to create a new list
I have a list of strings and would like to use a for loop to change the strings and create a new list.

```<code>oldList = ['AAA','BBB','CCC']

for i in range(len(oldList)):

    newList = []
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)
</code>```

The list 'newList' should contain all the strings on the old list plus the amendments (i.e. ['a_AAA_z', 'a_BBB_z', 'a_CCC_z']). However, it only contains the last string (i.e. ['a_CCC_z']).

What am I missig here? Many thanks in advance.

答:
Declare the output list outside of the loop. It can be simplified, by the way:

```<code>newList = []
for ele in oldList:
    add1 = 'a_'
    add2 = '_z'
    newStr = add1 + ele + add2
    newList.append(newStr)
</code>```

Or we can simplify even further if we use a list comprehension and formatted strings, as suggested by @AnnZen

```<code>newList = [f"a_{ele}_z" for ele in oldList]
</code>```

Title: Using a for loop to create a new list

Body:
I have a list of strings and would like to use a for loop to change the strings and create a new list.

oldList = ['AAA','BBB','CCC']

for i in range(len(oldList)):

    newList = []
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)

The list 'newList' should contain all the strings on the old list plus the amendments (i.e. ['a_AAA_z', 'a_BBB_z', 'a_CCC_z']). However, it only contains the last string (i.e. ['a_CCC_z']).

What am I missig here? Many thanks in advance.

Body:
Declare the output list outside of the loop. It can be simplified, by the way:

newList = []
for ele in oldList:
    add1 = 'a_'
    add2 = '_z'
    newStr = add1 + ele + add2
    newList.append(newStr)

Or we can simplify even further if we use a list comprehension and formatted strings, as suggested by @AnnZen

newList = [f"a_{ele}_z" for ele in oldList]


问:
Python3 : EOF Error while taking input on GUVI
This is my code in python3:

```<code>import heapq

myQueue = []
n = raw_input()
try:
  num = int(n)
  if num<=100000 :
    arr = input().split()
  for i in range(num):
    heapq.heappush(myQueue, arr[i])
    print(myQueue[0])

except (NameError, ValueError):
  print("Wrong Input, N should be under 100000")

except IndexError:
  print("Inputs is less than actually required")

except EOFError:
  print ("Error: EOF or empty input!")
</code>```

I am trying to implement priority queue.
But I am facing this EOF Error while solving this problem on GUVI.

```<code>Output:
Error: EOF or empty input!
</code>```

The tried to catch the error using except EOFError, but that will just make my program run but does not solve input problem right.
I even tried to run this piece of code on Sublime text editor as well as Vs code,
where it runs just fine, Correct Output.
I don't understand, is there a problem in my code or That Online Platform.
I even tried to search the answer on their Q&A platform of GUVI, I found similar question but no one has answered it.
And this is not just for this piece of Code but I found the same error for many before.

Could ANYONE help me, Please!

Thanking you in advance.. :)

答:
EOF error occurs if the input is not provided.

In case of most of the online compilers you need to provide the inputs before running the code.

With that said, while your are trying to access the input via raw_input() there will be no input supplied resulting in the above error.

To avoid this, error supply inputs before running your code like below

Also, I can notice that you are using raw_input() and input(). Please note that raw_input() can be used if you are using Python 2 and input() if you are using python 3 correspondingly.

Body:
This is my code in python3:

import heapq

myQueue = []
n = raw_input()
try:
  num = int(n)
  if num<=100000 :
    arr = input().split()
  for i in range(num):
    heapq.heappush(myQueue, arr[i])
    print(myQueue[0])

except (NameError, ValueError):
  print("Wrong Input, N should be under 100000")

except IndexError:
  print("Inputs is less than actually required")

except EOFError:
  print ("Error: EOF or empty input!")

I am trying to implement priority queue.
But I am facing this EOF Error while solving this problem on GUVI.

Output:
Error: EOF or empty input!

The tried to catch the error using except EOFError, but that will just make my program run but does not solve input problem right.
I even tried to run this piece of code on Sublime text editor as well as Vs code,
where it runs just fine, Correct Output.
I don't understand, is there a problem in my code or That Online Platform.
I even tried to search the answer on their Q&A platform of GUVI, I found similar question but no one has answered it.
And this is not just for this piece of Code but I found the same error for many before.

Could ANYONE help me, Please!

Thanking you in advance.. :)


问:
Error when using Jax to generate Proxy web service client
I was wondering if i could get some help with the following issue.

I was trying to run the command below using jax to generate web service client  proxy:

```<code>wsimport http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL
</code>```

but i'm getting the following error:

```<code>Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Asher>wsimport http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL
parsing WSDL...

[WARNING] src-resolve.4.2: Error resolving component 's:schema'. It was detected that 's:schema' is in namespace 'http:/
/www.w3.org/2001/XMLSchema', but components from this namespace are not referenceable from schema document 'http://www.h
olidaywebservice.com/Holidays/HolidayService.asmx?WSDL#types?schema1'. If this is the incorrect namespace, perhaps the p
refix of 's:schema' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be ad
ded to 'http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL#types?schema1'.
  line 15 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL#types?schema1

[ERROR] undefined element declaration 's:schema'
  line 15 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

[ERROR] undefined element declaration 's:schema'
  line 36 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

[ERROR] undefined element declaration 's:schema'
  line 74 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

[ERROR] undefined element declaration 's:schema'
  line 97 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

[ERROR] undefined element declaration 's:schema'
  line 120 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

[ERROR] undefined element declaration 's:schema'
  line 131 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

C:\Users\Asher>
</code>```

First of all am i doing something incorrectly? And lastly if there's no way to generate a proxy client then is there any other way to access this webservice & it's methods in java.
I'm fairy new to java so any help would be greatly appreciated.

Thanks

答:
How did you create that WSDL? It seams that you refer some data types that are not exported in your WSDL.

EDIT

The wsdl refers to a schema named 's' but this can't be found, because its URL is

http://www.w3.org/2001/XMLSchema but should be

http://www.w3.org/2001/XMLSchema.xsd

after change that now it also complains about http://www.27seconds.com/Holidays/ that isn't pointing to a schema too. You need to fix all of them in your copy of the WSDL and then do the wsimport with it.

I also gone to www.holidaywebservice.com and found there's a second version at:
http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx?wsdl

Body:
I was wondering if i could get some help with the following issue.

I was trying to run the command below using jax to generate web service client  proxy:

wsimport http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

but i'm getting the following error:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Asher>wsimport http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL
parsing WSDL...

[WARNING] src-resolve.4.2: Error resolving component 's:schema'. It was detected that 's:schema' is in namespace 'http:/
/www.w3.org/2001/XMLSchema', but components from this namespace are not referenceable from schema document 'http://www.h
olidaywebservice.com/Holidays/HolidayService.asmx?WSDL#types?schema1'. If this is the incorrect namespace, perhaps the p
refix of 's:schema' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be ad
ded to 'http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL#types?schema1'.
  line 15 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL#types?schema1

[ERROR] undefined element declaration 's:schema'
  line 15 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

[ERROR] undefined element declaration 's:schema'
  line 36 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

[ERROR] undefined element declaration 's:schema'
  line 74 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

[ERROR] undefined element declaration 's:schema'
  line 97 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

[ERROR] undefined element declaration 's:schema'
  line 120 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

[ERROR] undefined element declaration 's:schema'
  line 131 of http://www.holidaywebservice.com/Holidays/HolidayService.asmx?WSDL

C:\Users\Asher>

First of all am i doing something incorrectly? And lastly if there's no way to generate a proxy client then is there any other way to access this webservice & it's methods in java.
I'm fairy new to java so any help would be greatly appreciated.

Thanks


问:
React Dropdown List - Selected Values Off By One
I have a dropdown list in React that is populating with data from my api, that works fine. Howver, when I select an option in the dropdown list, and i log the result, the result it logs always shows the item that's 1 place above the item I selected.  It also shows as blank the first time I select, but then every select after that, off by one.  Does anyone see what I'm missing?</p>

```<code>import React, { Component } from 'react';
import { Editor } from '@tinymce/tinymce-react';

class TinyEditor extends Component {
    constructor(props) {
        super(props);

        this.state = {
            content: '',
            policy: '',
            policies: []
         };

        this.selectPolicy = this.selectPolicy.bind(this);

    }

    componentDidMount() {
        console.log(`Component did mount`);
        fetch(`/api/policy/all`)
            .then(res => res.json())
            .then((result) => {
                console.log(result);
                this.setState({policies: result});
            });
    }

    selectPolicy(e) {
        this.setState({policy: e.target.value});
        console.log(this.state.policy);
    }

    render() {
                return (
            <div>
                <div className="container">

                    <select onChange={this.selectPolicy}
                            value={this.state.policy}>
                        <option default>Select Policy...</option>
                        { this.state.policies.map(item => (
                            <option key={item.policy}>{item.policy}</option>
                        ))}
                    </select>

                </div>
            </div>
        )
    }
}

export default TinyEditor;
</code>```

答:
Your console is getting rendered before completing a setSstate,
Try the following code

this.setState({policy: e.target.value}, ()=>console.log(this.state.policy)}

Here the console.log() will be called only after completing the setState.

Body:
I have a dropdown list in React that is populating with data from my api, that works fine. Howver, when I select an option in the dropdown list, and i log the result, the result it logs always shows the item that's 1 place above the item I selected.  It also shows as blank the first time I select, but then every select after that, off by one.  Does anyone see what I'm missing?

import React, { Component } from 'react';
import { Editor } from '@tinymce/tinymce-react';

class TinyEditor extends Component {
    constructor(props) {
        super(props);

        this.state = {
            content: '',
            policy: '',
            policies: []
         };

        this.selectPolicy = this.selectPolicy.bind(this);

    }

    componentDidMount() {
        console.log(`Component did mount`);
        fetch(`/api/policy/all`)
            .then(res => res.json())
            .then((result) => {
                console.log(result);
                this.setState({policies: result});
            });
    }

    selectPolicy(e) {
        this.setState({policy: e.target.value});
        console.log(this.state.policy);
    }

    render() {
                return (

                    <select onChange={this.selectPolicy}
                            value={this.state.policy}>
                        <option default>Select Policy...</option>
                        { this.state.policies.map(item => (
                            <option key={item.policy}>{item.policy}</option>
                        ))}
                    </select>

        )
    }
}

export default TinyEditor;


问:
How can I programmatically make a window fullscreen?
How can I programmatically make a window fullscreen?</p>

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    scene = new QNewScene(this);
    ui->graphicsView->setScene(scene);
    // here is some code that will make the window fullscreen

}
</code>```

答:
For example:

```<code>QTimer::singleShot(0, this, SLOT(showFullScreen()));
</code>```

method to make your window full screen:

```<code>QWidget::showFullScreen()
</code>```

check it here: https://doc.qt.io/qt-5/qwidget.html#showFullScreen

Body:
How can I programmatically make a window fullscreen?

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    scene = new QNewScene(this);
    ui->graphicsView->setScene(scene);
    // here is some code that will make the window fullscreen

}

Body:
For example:

QTimer::singleShot(0, this, SLOT(showFullScreen()));

method to make your window full screen:

QWidget::showFullScreen()

check it here: https://doc.qt.io/qt-5/qwidget.html#showFullScreen


问:
Does CDI with Spring DI annotation works when its from an external dependency?
I'm writing a code that needs to be compatible with both Quarkus and Spring DI.
I am using both DI and Spring Boot Properties extensions, the Spring Boot Extension. It works fine, apparently, but the injection of any other object from the external dependency that was annotated as a bean doesn't get injected anywhere. Quarkus doesn't seem to recognize it.

Is this some kind of limitation with the Spring DI Extention?
I already tried to use the quarkus.index-dependency property and also tried to include the dependency structured as a Quarkus Extention, but it didn't work.

EDIT 1:
As stated by @Kolossus, adding the beans.xml resolved the DI issue, but i'm having another error related to the properties class:

java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors

```<code>        [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: Found 3 deployment problems:
[1] Ambiguous dependencies for type com.properties.IntegrationProperties and qualifiers [@Default]
        - java member: com.authorization.AuthenticationService#<init>()
        - declared on CLASS bean [types=[com.authorization.AuthenticationService, java.lang.Object], qualifiers=[@Named(value = "authenticationService"), @Default, @Any], target=com.authorization.AuthenticationService]
        - available beans:
                - CLASS bean [types=[com.properties.IntegrationProperties, java.lang.Object], qualifiers=[@Default, @Any], target=com.properties.IntegrationProperties]
                - PRODUCER METHOD bean [types=[com.properties.IntegrationProperties, java.lang.Object], qualifiers=[@Default, @Any], target=com.properties.IntegrationProperties produceIntegrationProperties(org.eclipse.microprofile.config.Config), declaringBean=io.quarkus.arc.runtime.config.ConfigPropertiesProducer]
</code>```

Ambiguous dependencies in all the Injection Points for the properties class.

答:
Adding the beans.xml to the dependency solved my problem. The problem with the properties class was that the class was annotated like this:

@Configuration
@ConfigurationProperties(prefix = "some-prefix")
 public class IntegrationProperties

So Quarkus was creating 2 beans of the same type, one because of the @configuration and the other because of the @ConfigurationProperties.
I fixed it by adding @EnableConfigurationProperties(IntegrationProperties.class)
in another configuration class.

Body:
I'm writing a code that needs to be compatible with both Quarkus and Spring DI.
I am using both DI and Spring Boot Properties extensions, the Spring Boot Extension. It works fine, apparently, but the injection of any other object from the external dependency that was annotated as a bean doesn't get injected anywhere. Quarkus doesn't seem to recognize it.

Is this some kind of limitation with the Spring DI Extention?
I already tried to use the quarkus.index-dependency property and also tried to include the dependency structured as a Quarkus Extention, but it didn't work.

EDIT 1:
As stated by @Kolossus, adding the beans.xml resolved the DI issue, but i'm having another error related to the properties class:

java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors

        [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: Found 3 deployment problems:
[1] Ambiguous dependencies for type com.properties.IntegrationProperties and qualifiers [@Default]
        - java member: com.authorization.AuthenticationService#<init>()
        - declared on CLASS bean [types=[com.authorization.AuthenticationService, java.lang.Object], qualifiers=[@Named(value = "authenticationService"), @Default, @Any], target=com.authorization.AuthenticationService]
        - available beans:
                - CLASS bean [types=[com.properties.IntegrationProperties, java.lang.Object], qualifiers=[@Default, @Any], target=com.properties.IntegrationProperties]
                - PRODUCER METHOD bean [types=[com.properties.IntegrationProperties, java.lang.Object], qualifiers=[@Default, @Any], target=com.properties.IntegrationProperties produceIntegrationProperties(org.eclipse.microprofile.config.Config), declaringBean=io.quarkus.arc.runtime.config.ConfigPropertiesProducer]

Ambiguous dependencies in all the Injection Points for the properties class.


问:
AWS Batch Job Stuck in Runnable State
I'm trying to run a 100 node AWS Batch job, when I set my computing environment to use only m4.xlarge and m5.xlarge instances everything works fine and my job is picked up and runs.

However, when I begin to include other instance types in my compute environment such as m5.2xlarge, the job is stuck in the runnable state indefinitely. The only variable I am changing in these updates is the instance types in the compute environment.

I'm not sure what is causing this job to not be picked up when I include other instance types in the computing environment. In the documentation for Compute Environment Parameters the only note is:

When you create a compute environment, the instance types that you select for the compute environment must share the same architecture. For example, you can't mix x86 and ARM instances in  the same compute environment.

The JobDefinition is multi-node:

Node 0

vCPUs: 1

Memory: 15360 MiB

Node 1:

vCPUs: 2

Memory: 15360 MiB

My computing environment max vCPUs is set to 10,000, is always in a VALID state and always ENABLED. Also my EC2 vCPU limit is 6,000. CloudWatch provides no logs because the job has not started, I'm not sure what else to try here. I am also not using the optimal setting for instance types because I ran into issues with not getting enough instances.

答:
I just resolved this issue, the problem is with the BEST_FIT strategy in Batch. The jobs that I'm submitting are not close enough to the instance type so they never get picked up.

I figured this out by modifying the job definition to use 8 vCPU and 30GB of memory and the job began with the m5.2xlarge instances.

I'm going to see if using the BEST_FIT_PROGRESSIVE strategy will resolve this issue and report back, although I doubt it will.

--

Update: I have spoken with AWS Support and got some more insight. The BEST_FIT_PROGRESSIVE allocation strategy has built-in protections for over-scaling so that customers do not accidentally launch thousands of instances. Although this has the side effect of what I am experiencing which leads to jobs failing to start.

The support engineers recommendation was to use a single instance type in the Compute Environment and the BEST_FIT allocation strategy. Since my jobs have different instance requirements I was able to successfully create three separate ComputeEnvironments targeting difference instances types (c5.large, c5.xlarge, m4.xlarge), submit jobs and have them run in the appropriate Compute Environment.

Title: AWS Batch Job Stuck in Runnable State


问:
Test void method behavior junit and mockito
Given this service I'd like to test that the role property of stuff object is properly set:

```<code>public void saveAStuffForAnEvent(Event whatever) {
    if (whatever == null){
        Stuff stuff = StuffBuilder().role(StuffRoles.DEFAULT).build();
        stuffRepository.save(stuff);
    } else {
        Stuff stuff = StuffBuilder().role(StuffRoles.OTHER).build();
        stuffRepository.save(stuff);
    }
}
</code>```

How can I test that stuff object is properly created with the DEFAULT role?

答:
Use captor.

In your test create field with @Captor annotation like:

```<code>@Mock
private StuffRepository stuffRepository;

@Captor
private ArgumentCaptor<Stuff> stuffCaptor;
</code>```

Then in test after:

```<code>// when
subject.saveAStuffForAnEvent(event);
// then
verify(stuffRepository).save(stuffCaptor.capture());
assertThat(stuffCaptor.getValue().getRole()).isEqualTo(StuffRoles.DEFAULT);
</code>```

Or if it's integration test then:

```<code>// when
subject.saveAStuffForAnEvent(event);
//then
assertThat(subject.findAll().get(0).getRole()).isEqualTo(StuffRoles.DEFAULT);
</code>```

Body:
Given this service I'd like to test that the role property of stuff object is properly set:

public void saveAStuffForAnEvent(Event whatever) {
    if (whatever == null){
        Stuff stuff = StuffBuilder().role(StuffRoles.DEFAULT).build();
        stuffRepository.save(stuff);
    } else {
        Stuff stuff = StuffBuilder().role(StuffRoles.OTHER).build();
        stuffRepository.save(stuff);
    }
}

How can I test that stuff object is properly created with the DEFAULT role?

Body:
Use captor.

In your test create field with @Captor annotation like:

@Mock
private StuffRepository stuffRepository;

@Captor
private ArgumentCaptor<Stuff> stuffCaptor;

Then in test after:

// when
subject.saveAStuffForAnEvent(event);
// then
verify(stuffRepository).save(stuffCaptor.capture());
assertThat(stuffCaptor.getValue().getRole()).isEqualTo(StuffRoles.DEFAULT);

Or if it's integration test then:

// when
subject.saveAStuffForAnEvent(event);
//then
assertThat(subject.findAll().get(0).getRole()).isEqualTo(StuffRoles.DEFAULT);


问:
Pods Plugin Display Custom Taxonomy with Magic Tags on Pods Template
So I am using the Pod Plugin for my WordPress Website. And I want to use magic tags to display a custom taxonomy of a pod.

Little background info:

I have 2 pods (Projects & Programmes)

I have field in Projects to Select a Programme (Each Project belongs to one Programmme)

In my Programme Pod, I have a custom taxonomy called 'colour'. (Basically i need this for my CSS)

So i am using a pod template to display my recent projects. but with that I want to assign a custom color line on the side when each project is posted. (see image below)

Design of the recent post display

So in my sass file i have ready the code like:

```<code>.green-bg{
  background-color: #659E80;
}

.mustard-bg{
  background-color: #E3A44C;
}

.blue-bg{
  background-color: #2B7BBF;
}
</code>```

i want taxonomy select to be display in the class of the div side-line. for example:

I want this to be dynamic and using magic tags like:

```<code><div class="side-line
[each colour]
{@programme.colour}
[\each]
bg"></div>
</code>```

This syntax is invalid. It is just a example of what I want to achieve.  Also another note is the template is Pod Referencing Project pod.

Pods Template for Recent Projects:

```<code>div class="recent-post-container">
    <div class="side-line"></div>
    <div class="post-group">
        <p class="recent-post-title">{@post_title}</p>
        <p class="recent-post-programme">{@programme}</p>
    </div>

</div>
</code>```

Please help! If you can solve this or find another way i can dynamically assign colors to the div based on the programme being displayed.

答: Update. I manually put in the colors as a field with a relationship as type. </p>

Body:
So I am using the Pod Plugin for my WordPress Website. And I want to use magic tags to display a custom taxonomy of a pod.

Little background info:

I have 2 pods (Projects & Programmes)

I have field in Projects to Select a Programme (Each Project belongs to one Programmme)

In my Programme Pod, I have a custom taxonomy called 'colour'. (Basically i need this for my CSS)

So i am using a pod template to display my recent projects. but with that I want to assign a custom color line on the side when each project is posted. (see image below)

Design of the recent post display

So in my sass file i have ready the code like:

.green-bg{
  background-color: #659E80;
}

.mustard-bg{
  background-color: #E3A44C;
}

.blue-bg{
  background-color: #2B7BBF;
}

i want taxonomy select to be display in the class of the div side-line. for example:

I want this to be dynamic and using magic tags like:

This syntax is invalid. It is just a example of what I want to achieve.  Also another note is the template is Pod Referencing Project pod.

Pods Template for Recent Projects:

div class="recent-post-container">

{@post_title}

{@programme}

Please help! If you can solve this or find another way i can dynamically assign colors to the div based on the programme being displayed.


答:
The declaration of list should be outside the loop</p>

```<code>oldList = ['AAA','BBB','CCC']
newList = []

for i in range(len(oldList)):
    # should not declare newList inside for loop
    #newList = []
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)
print(newList)
</code>```

Title: Using a for loop to create a new list

Body:
The declaration of list should be outside the loop

oldList = ['AAA','BBB','CCC']
newList = []

for i in range(len(oldList)):
    # should not declare newList inside for loop
    #newList = []
    add1 = 'a_'
    add2 = '_z'

    newStr = add1 + oldList[i] + add2

    newList.append(newStr)
print(newList)


问:
my service return anonymous type data in JSON format, how to use it in angular 9 application as a string[]
My service return data in JSON like

```<code>[
    {
        "txtUserRole": "FinAsst"
    },
    {
        "txtUserRole": "CSG"
    },
    {
        "txtUserRole": "PA"
    },
    {
        "txtUserRole": "ARTEAM"
    }
]
</code>```

now I want to add all this role in a string array.
so i wrote a code like

```<code>  ngOnInit(): void {
    this.generic.getUserRoles().toPromise().then(
      (jsonData) => {
        jsonData.forEach(element => {
          **// console.log(element['txtUserRole']);**
          this.roles.push(element['txtUserRole']);
        });
      }
    );
  }
</code>```

when i was logging with           console.log(element['txtUserRole']);

I am able to see that result as below in the console

```<code>FinAsst
CSG
PA
ARTEAM
</code>```

but when in HTML using interpolation nothing is displayed.

```<code> {{roles}}
</code>```

what is the reason and what code needs to be changes

答:
in the html you need to use a loop to display the data:

{{ role }}

```

<p>In case of a debug:</p>

<pre class="lang-html prettyprint-override"><code>{{ roles | json }}
</code>```

Body:
My service return data in JSON like

[
    {
        "txtUserRole": "FinAsst"
    },
    {
        "txtUserRole": "CSG"
    },
    {
        "txtUserRole": "PA"
    },
    {
        "txtUserRole": "ARTEAM"
    }
]

now I want to add all this role in a string array.
so i wrote a code like

  ngOnInit(): void {
    this.generic.getUserRoles().toPromise().then(
      (jsonData) => {
        jsonData.forEach(element => {
          **// console.log(element['txtUserRole']);**
          this.roles.push(element['txtUserRole']);
        });
      }
    );
  }

when i was logging with           console.log(element['txtUserRole']);

I am able to see that result as below in the console

FinAsst
CSG
PA
ARTEAM

but when in HTML using interpolation nothing is displayed.

 {{roles}}

what is the reason and what code needs to be changes

Body:
in the html you need to use a loop to display the data:

<div *ngFor="let role of roles">{{ role }}</div>

In case of a debug:

{{ roles | json }}


问:
Recursive function calls working behind the scenes
So I can't wrap my head around recursive function calls especially with this example:

```<code>int Addup(int n)
{
    //6
    if(n <= 1)
        return 1;
    else
        return n + Addup(n - 1);
    /*
    6 + 5 + 4 + 3 + 2 + 1
    */
}
</code>```

Now if for example we did Addup(6), how will that work, what will the program do at runtime? Will it chain all the evaluations after the n then sum them together. I really can't visualize it.

If someone could have a simple way of demonstrating what actually happens at runtime it would be really great.

Thanks in advance.

答:
The secret to understanding recursion is that recursive functions work exactly like non-recursive functions.

Your functions work exactly like these:

```<code>int Addup_1(int n)
{
    return 1;
}

int Addup_2(int n)
{
    if(n <= 1)
        return 1;
    else
        return n + Addup_1(n - 1);
}

int Addup_3(int n)
{
    if(n <= 1)
        return 1;
    else
        return n + Addup_2(n - 1);
}

int Addup_4(int n)
{
    if(n <= 1)
        return 1;
    else
        return n + Addup_3(n - 1);
}

int Addup_5(int n)
{
    if(n <= 1)
        return 1;
    else
        return n + Addup_4(n - 1);
}

int Addup_6(int n)
{
    if(n <= 1)
        return 1;
    else
        return n + Addup_5(n - 1);
}
</code>```

Body:
So I can't wrap my head around recursive function calls especially with this example:

int Addup(int n)
{
    //6
    if(n <= 1)
        return 1;
    else
        return n + Addup(n - 1);
    /*
    6 + 5 + 4 + 3 + 2 + 1
    */
}

Now if for example we did Addup(6), how will that work, what will the program do at runtime? Will it chain all the evaluations after the n then sum them together. I really can't visualize it.

If someone could have a simple way of demonstrating what actually happens at runtime it would be really great.

Thanks in advance.

Body:
The secret to understanding recursion is that recursive functions work exactly like non-recursive functions.

Your functions work exactly like these:

int Addup_1(int n)
{
    return 1;
}

int Addup_2(int n)
{
    if(n <= 1)
        return 1;
    else
        return n + Addup_1(n - 1);
}

int Addup_3(int n)
{
    if(n <= 1)
        return 1;
    else
        return n + Addup_2(n - 1);
}

int Addup_4(int n)
{
    if(n <= 1)
        return 1;
    else
        return n + Addup_3(n - 1);
}

int Addup_5(int n)
{
    if(n <= 1)
        return 1;
    else
        return n + Addup_4(n - 1);
}

int Addup_6(int n)
{
    if(n <= 1)
        return 1;
    else
        return n + Addup_5(n - 1);
}


问:
Calculate Median on Sql
I am very new to SQL. I am trying to use the code below and it keeps giving me the following error -

Msg The ORDER BY clause is invalid in
  views, inline functions, derived
  tables, subqueries, and common table
  expressions, unless TOP or FOR XML is
  also specified.

Incorrect syntax near '2'.

Please can someone help - where am I going wrong?

I am just trying to calculate median.

Could someone please suggest amendment to this code as I have picked up someone else's work.

Any help will be greatly appreciated.

```<code>SELECT
    TOP (100) PERCENT Name, Sales Median
FROM
    (SELECT
         a1.Name, a1.Sales, COUNT(a1.Sales) Rank
     FROM
         PSE.vw_EM_Data a1, PSE.vw_EM_Data a2
     WHERE
         a1.Sales < a2.Sales OR
         (a1.Sales = a2.Sales AND a1.Name <= a2.Name)
     GROUP BY
         a1.Name, a1.Sales
     ORDER BY
         a1.Sales DESC) a3
WHERE
    Rank = (SELECT (COUNT(*) + 1) DIV 2 FROM Total_Sales);
WHERE
    (Name LIKE 'John%')
    AND (DISPOSAL = '1')
    AND (DATE BETWEEN CONVERT(DATETIME, '2010-04-01 00:00:00', 102) AND CONVERT(DATETIME, '2011-03-30 00:00:00', 102))
</code>```

答:
You problem is from the order by with in the subselect a3

Why not rather have a look at using Ranking Functions (Transact-SQL)

Title: Calculate Median on Sql

Body:
I am very new to SQL. I am trying to use the code below and it keeps giving me the following error -

Msg The ORDER BY clause is invalid in
  views, inline functions, derived
  tables, subqueries, and common table
  expressions, unless TOP or FOR XML is
  also specified.

Incorrect syntax near '2'.

Please can someone help - where am I going wrong?

I am just trying to calculate median.

Could someone please suggest amendment to this code as I have picked up someone else's work.

Any help will be greatly appreciated.

SELECT
    TOP (100) PERCENT Name, Sales Median
FROM
    (SELECT
         a1.Name, a1.Sales, COUNT(a1.Sales) Rank
     FROM
         PSE.vw_EM_Data a1, PSE.vw_EM_Data a2
     WHERE
         a1.Sales < a2.Sales OR
         (a1.Sales = a2.Sales AND a1.Name <= a2.Name)
     GROUP BY
         a1.Name, a1.Sales
     ORDER BY
         a1.Sales DESC) a3
WHERE
    Rank = (SELECT (COUNT(*) + 1) DIV 2 FROM Total_Sales);
WHERE
    (Name LIKE 'John%')
    AND (DISPOSAL = '1')
    AND (DATE BETWEEN CONVERT(DATETIME, '2010-04-01 00:00:00', 102) AND CONVERT(DATETIME, '2011-03-30 00:00:00', 102))


问:
Angular 8 Jasmine and karma testing: mocked ngonit promise value is not rendered in the DOM
My mock data in a test will not display in the markup when running the test. No matter what i try (fakeasync, done, stubs) the content of the promise is not rendered in the markup after running the test.

Can anyone please tell me why this mocked promise data will not display in the dom. I have spent 2 days almost on this and it simply does not work no matter what i try. I'm using angular 8 and starting to think it's a bug in the framework.

I have the following markup:

```<code><div>
    <div class="pt-8">
        <!-- Displays -->
        <ul>
            <li *ngFor="let worker of workers">{{worker.getName()}}</li>
        </ul>

        <!-- DOES NOT DISPLAY -->
        <ol>
            <li *ngFor="let centre of centres">{{centre.name}}</li>
        </ol>
    </div>
</div>
</code>```

This is the class:

```<code>import { Component, OnInit, Input, Inject } from '@angular/core';
import { WorkcentersService } from 'app/services/workcenters.service';
import { Workcenter } from 'app/model/workcenter';
import { User } from 'app/model/user';

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
  workers: User[];
  centres: Workcenter[];

  constructor(private workcentersService: WorkcentersService) { }

  ngOnInit(): void {
    let user1 = new User(); user1.name = "worker 1"; user1.surname = "surname1";
    let user2 = new User(); user2.name = "worker 2"; user2.surname = "surname2";
    let user3 = new User(); user3.name = "worker 3"; user3.surname = "surname3";
    this.workers = [user1, user2, user3];
    this.workcentersService.getWorkcentersList().then(wc => this.centres = wc);
  }
}
</code>```

This is the test:

```<code>import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { WorkcentersService } from 'app/services/workcenters.service';
import { Workcenter } from 'app/model/workcenter';
import { TestComponent } from './test.component';

fdescribe('TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(async () => {
    const mockCentres = createMockCentres();
    const mockWorkcentersService = jasmine.createSpyObj(["getWorkcentersList"]);
    mockWorkcentersService.getWorkcentersList.and.returnValue(Promise.resolve(mockCentres));

    TestBed.configureTestingModule({
      declarations: [TestComponent],
      imports: [],
      providers: [
        { provide: WorkcentersService, useValue: mockWorkcentersService }
      ]
    });

    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    await fixture.whenStable();
    fixture.detectChanges();
  });

  // Passes
  it('should create', () => {
    expect(component).toBeTruthy();
  });

  // Passes
  it('should render users', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll("ul li");
    expect(displayedUsers.length).toEqual(3);
  });

  // Fails
  it('should render centres', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll("ol li");
    expect(displayedUsers.length).toEqual(2);
  });

  // Fails
  it('should display "hello"', fakeAsync(() => {
    fixture.detectChanges();
    tick();
    const displayedUsers = fixture.nativeElement.querySelectorAll("ol li");
    expect(displayedUsers.length).toEqual(2);
  }));

  function createMockCentres(): Workcenter[] {
    const mockCentre1 = new Workcenter();mockCentre1.id = 1;mockCentre1.name = "Test centre 1";
    const mockCentre2 = new Workcenter();mockCentre2.id = 2;mockCentre2.name = "Test centre 2";
    return [mockCentre1, mockCentre2];
  }
});
</code>```

答:
@Aakash Garg Ive accepted your answer as you got it right.

After spending (yet) more time on this I found that the fact we created spies differently didn't make any difference.

The key fact was you turned around
fixture.detectChanges();
await fixture.whenStable();
I had them the other way around.

Also you added a fixture.detectChanges() in the test itself which was also necessary. The additonal whenStable call didn't seem to make any difference.

In the end I used fixture.autoDetectChanges() which made it work without the fixture.whenStable call as below:

```<code>beforeEach(async () => {
    const mockCentres = createMockCentres();
    const workers = { workers: createMockWorkers(), companyId: 22 };
    const mockWorkcentersService = jasmine.createSpyObj(["getWorkcentersList"]);
    mockWorkcentersService.getWorkcentersList.and.returnValue(Promise.resolve(mockCentres));

    TestBed.configureTestingModule({
      declarations: [CentreAssociateComponent],
      imports: [],
      providers: [
        //WorkcentersService,
        { provide: WorkcentersService, useValue: mockWorkcentersService },
        { provide: MAT_DIALOG_DATA, useValue: workers },
        { provide: MatDialogRef, useValue: {} }
      ]
    });

    fixture = TestBed.createComponent(CentreAssociateComponent);
    fixture.autoDetectChanges();
    component = fixture.componentInstance;

    await fixture.whenStable();
  });

  it('should render centres', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll("ol li");
    expect(displayedUsers.length).toEqual(2);
  });
</code>```

Body:
My mock data in a test will not display in the markup when running the test. No matter what i try (fakeasync, done, stubs) the content of the promise is not rendered in the markup after running the test.

Can anyone please tell me why this mocked promise data will not display in the dom. I have spent 2 days almost on this and it simply does not work no matter what i try. I'm using angular 8 and starting to think it's a bug in the framework.

I have the following markup:

{{worker.getName()}}

{{centre.name}}

This is the class:

import { Component, OnInit, Input, Inject } from '@angular/core';
import { WorkcentersService } from 'app/services/workcenters.service';
import { Workcenter } from 'app/model/workcenter';
import { User } from 'app/model/user';

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
  workers: User[];
  centres: Workcenter[];

  constructor(private workcentersService: WorkcentersService) { }

  ngOnInit(): void {
    let user1 = new User(); user1.name = "worker 1"; user1.surname = "surname1";
    let user2 = new User(); user2.name = "worker 2"; user2.surname = "surname2";
    let user3 = new User(); user3.name = "worker 3"; user3.surname = "surname3";
    this.workers = [user1, user2, user3];
    this.workcentersService.getWorkcentersList().then(wc => this.centres = wc);
  }
}

This is the test:

import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { WorkcentersService } from 'app/services/workcenters.service';
import { Workcenter } from 'app/model/workcenter';
import { TestComponent } from './test.component';

fdescribe('TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(async () => {
    const mockCentres = createMockCentres();
    const mockWorkcentersService = jasmine.createSpyObj(["getWorkcentersList"]);
    mockWorkcentersService.getWorkcentersList.and.returnValue(Promise.resolve(mockCentres));

    TestBed.configureTestingModule({
      declarations: [TestComponent],
      imports: [],
      providers: [
        { provide: WorkcentersService, useValue: mockWorkcentersService }
      ]
    });

    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    await fixture.whenStable();
    fixture.detectChanges();
  });

  // Passes
  it('should create', () => {
    expect(component).toBeTruthy();
  });

  // Passes
  it('should render users', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll("ul li");
    expect(displayedUsers.length).toEqual(3);
  });

  // Fails
  it('should render centres', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll("ol li");
    expect(displayedUsers.length).toEqual(2);
  });

  // Fails
  it('should display "hello"', fakeAsync(() => {
    fixture.detectChanges();
    tick();
    const displayedUsers = fixture.nativeElement.querySelectorAll("ol li");
    expect(displayedUsers.length).toEqual(2);
  }));

  function createMockCentres(): Workcenter[] {
    const mockCentre1 = new Workcenter();mockCentre1.id = 1;mockCentre1.name = "Test centre 1";
    const mockCentre2 = new Workcenter();mockCentre2.id = 2;mockCentre2.name = "Test centre 2";
    return [mockCentre1, mockCentre2];
  }
});

Body:
@Aakash Garg Ive accepted your answer as you got it right.

After spending (yet) more time on this I found that the fact we created spies differently didn't make any difference.

The key fact was you turned around
fixture.detectChanges();
await fixture.whenStable();
I had them the other way around.

Also you added a fixture.detectChanges() in the test itself which was also necessary. The additonal whenStable call didn't seem to make any difference.

In the end I used fixture.autoDetectChanges() which made it work without the fixture.whenStable call as below:

beforeEach(async () => {
    const mockCentres = createMockCentres();
    const workers = { workers: createMockWorkers(), companyId: 22 };
    const mockWorkcentersService = jasmine.createSpyObj(["getWorkcentersList"]);
    mockWorkcentersService.getWorkcentersList.and.returnValue(Promise.resolve(mockCentres));

    TestBed.configureTestingModule({
      declarations: [CentreAssociateComponent],
      imports: [],
      providers: [
        //WorkcentersService,
        { provide: WorkcentersService, useValue: mockWorkcentersService },
        { provide: MAT_DIALOG_DATA, useValue: workers },
        { provide: MatDialogRef, useValue: {} }
      ]
    });

    fixture = TestBed.createComponent(CentreAssociateComponent);
    fixture.autoDetectChanges();
    component = fixture.componentInstance;

    await fixture.whenStable();
  });

  it('should render centres', async () => {
    const displayedUsers = fixture.nativeElement.querySelectorAll("ol li");
    expect(displayedUsers.length).toEqual(2);
  });


问:
How to Commit/Rollback stored procedure based on return value in Snowflake?
I have a javascript stored procedure that return boolean. I want to be able to call this stored procedure inside a transaction and test the return value before committing the transaction.

BEGIN;
SET result = CALL my_stored_proc();

IF $result = true
COMMIT;
ELSE
ROLLBACK;```
</div>
</div>
</p>

<p>The stored procedure will return false if there is an exception or if there is some missing values based on business logic.</p>

<p>How do I achieve this in Snowflake?</p>

<hr>

<p>EDIT:
I tried the following and it did not work. The transaction remains open and the statements executed inside the stored proc are not rolled back until an explicit ROLLBACK statement is issued. </p>

```USE COMMON;

CREATE TABLE LOG
(
LOG_ID INT IDENTITY(1, 1) NOT NULL CONSTRAINT PK_LOG_ID PRIMARY KEY,
LOG_LEVEL VARCHAR (50) NOT NULL,
LOGGER VARCHAR (500) NOT NULL,
MESSAGE VARCHAR NOT NULL,
EXCEPTION VARCHAR NULL,
APPLICATION_NAME VARCHAR(500) NOT NULL,
LOGGED_ON DATETIME DEFAULT TO_TIMESTAMP_NTZ(CURRENT_TIMESTAMP()) NOT NULL,
LOGGED_BY VARCHAR(200) DEFAULT CURRENT_USER() NOT NULL
);

CREATE OR REPLACE PROCEDURE TEST_TRANSACTION()
RETURNS VARCHAR
LANGUAGE javascript
EXECUTE AS CALLER
AS
$$
snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This is a test transaction.', '', 'DATA LOADER');
`});
snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This message should not be in the logs.', '', 'DATA LOADER');
`});

throw 'Test error'
$$
;
-- Run the next 3 lines as a batch
BEGIN;
CALL COMMON.TEST_TRANSACTION(); -- This Fails
COMMIT; -- Commit is NOT executed

SELECT * FROM COMMON.LOG WHERE LOGGER = 'TEST_TRANSACTION'; -- The insert is successful & the transaction is still OPEN
```

How do I rollback the statements executed inside the stored procedure?

答:
I recommend reading through this document as it offers several examples and methods to do what you are asking.

https://docs.snowflake.com/en/sql-reference/stored-procedures-usage.html#transaction-management

Body:
I have a javascript stored procedure that return boolean. I want to be able to call this stored procedure inside a transaction and test the return value before committing the transaction.

BEGIN;
SET result = CALL my_stored_proc();

IF $result = true
COMMIT;
ELSE
ROLLBACK;

The stored procedure will return false if there is an exception or if there is some missing values based on business logic.

How do I achieve this in Snowflake?

EDIT:
I tried the following and it did not work. The transaction remains open and the statements executed inside the stored proc are not rolled back until an explicit ROLLBACK statement is issued.

USE COMMON;

CREATE TABLE LOG
(
LOG_ID INT IDENTITY(1, 1) NOT NULL CONSTRAINT PK_LOG_ID PRIMARY KEY,
LOG_LEVEL VARCHAR (50) NOT NULL,
LOGGER VARCHAR (500) NOT NULL,
MESSAGE VARCHAR NOT NULL,
EXCEPTION VARCHAR NULL,
APPLICATION_NAME VARCHAR(500) NOT NULL,
LOGGED_ON DATETIME DEFAULT TO_TIMESTAMP_NTZ(CURRENT_TIMESTAMP()) NOT NULL,
LOGGED_BY VARCHAR(200) DEFAULT CURRENT_USER() NOT NULL
);

CREATE OR REPLACE PROCEDURE TEST_TRANSACTION()
RETURNS VARCHAR
LANGUAGE javascript
EXECUTE AS CALLER
AS
$$
snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This is a test transaction.', '', 'DATA LOADER');
`});
snowflake.execute({sqlText:`
INSERT
            INTO
                COMMON.LOG (LOG_LEVEL, LOGGER, MESSAGE, EXCEPTION, APPLICATION_NAME)
            VALUES ('DEBUG', 'TEST_TRANSACTION', 'This message should not be in the logs.', '', 'DATA LOADER');
`});

throw 'Test error'
$$
;
-- Run the next 3 lines as a batch
BEGIN;
CALL COMMON.TEST_TRANSACTION(); -- This Fails
COMMIT; -- Commit is NOT executed

SELECT * FROM COMMON.LOG WHERE LOGGER = 'TEST_TRANSACTION'; -- The insert is successful & the transaction is still OPEN

How do I rollback the statements executed inside the stored procedure?


问:
try/except issue statement in python 3
Hello I am new to Python and learning basics. I am curious to understand try/except statements in Python and I want to ask whether I should keep as little as possible in try block/portion as mentioned below (Please refer Following Code Working Properly) or try to keep as much in try block/portion (Please refer Following Code Not Working Properly When I Enter Any String but it works when I enter float/integer).

So, these are the two scenarios almost the same but the other code (in which I am keeping minimum code) is giving me an error when I enter a string.

Why is that doing it? What should I do in that case if I want to keep as little as possible in try/except blocks? Any leads would be highly appreciated. What's the alternate correct solution of my second code in which I am keeping minimum lines of code?  - What adjustment I am supposed to make in it to work for me? Please help.

```<code>NameError: name 'fahr' is not defined
</code>```

```<code>***# Following Code Working Properly:***
inp = input('Enter Fahrenheit Temperature:')
try:
    fahr = float(inp)
    cel = (fahr - 32.0) * 5.0 / 9.0
    print(cel)
except:
    print('Please enter a number')
</code>```

```<code>***# Following Code Not Working Properly:***
inp = input('Enter Fahrenheit Temperature:')

try:
    fahr = float(inp)
except:
    print('Please enter a number')

fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
</code>```

答:
Your problem is quite simple: try: except: is not a loop.

```<code>try:
    fahr = float(inp)
except:
    print('Please enter a number')
</code>```

Here, you try to set fahr, and if you fail, you print 'Please enter a number' and your program continues.

But it failed to set fahr! So on the next line, when you try to use fahr to run calculation, it does not exist. Hence, NameError: name 'fahr' is not defined.

Why does this work:

```<code>inp = input('Enter Fahrenheit Temperature:')
try:
    fahr = float(inp)
    cel = (fahr - 32.0) * 5.0 / 9.0
    print(cel)
except:
    print('Please enter a number')
</code>```

Here, you try to set fahr, you run your calculation, you print. But if any of these steps fail, you print your error and continue.

See the difference ? I hope it helps.

Title: try/except issue statement in python 3

Body:
Hello I am new to Python and learning basics. I am curious to understand try/except statements in Python and I want to ask whether I should keep as little as possible in try block/portion as mentioned below (Please refer Following Code Working Properly) or try to keep as much in try block/portion (Please refer Following Code Not Working Properly When I Enter Any String but it works when I enter float/integer).

So, these are the two scenarios almost the same but the other code (in which I am keeping minimum code) is giving me an error when I enter a string.

Why is that doing it? What should I do in that case if I want to keep as little as possible in try/except blocks? Any leads would be highly appreciated. What's the alternate correct solution of my second code in which I am keeping minimum lines of code?  - What adjustment I am supposed to make in it to work for me? Please help.

NameError: name 'fahr' is not defined

***# Following Code Working Properly:***
inp = input('Enter Fahrenheit Temperature:')
try:
    fahr = float(inp)
    cel = (fahr - 32.0) * 5.0 / 9.0
    print(cel)
except:
    print('Please enter a number')

***# Following Code Not Working Properly:***
inp = input('Enter Fahrenheit Temperature:')

try:
    fahr = float(inp)
except:
    print('Please enter a number')

fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)

Body:
Your problem is quite simple: try: except: is not a loop.

try:
    fahr = float(inp)
except:
    print('Please enter a number')

Here, you try to set fahr, and if you fail, you print 'Please enter a number' and your program continues.

But it failed to set fahr! So on the next line, when you try to use fahr to run calculation, it does not exist. Hence, NameError: name 'fahr' is not defined.

Why does this work:

inp = input('Enter Fahrenheit Temperature:')
try:
    fahr = float(inp)
    cel = (fahr - 32.0) * 5.0 / 9.0
    print(cel)
except:
    print('Please enter a number')

Here, you try to set fahr, you run your calculation, you print. But if any of these steps fail, you print your error and continue.

See the difference ? I hope it helps.


问:
Can't i use the variable in a formula?
I'm coding a math model using gurobiy, but an error occurs.

the error is 'Var' object cannot be interpreted as an integer.

i tried to solve it using search, but I don't have enough information.

spi: required space of block i

cft: area of factory f at t time

s_Time : Start time

p_Time : processing time

c_Time : completion time,

t: time

f: factory

i: block

yif : If blcok i is assgined at factory f  1 otherwise 0

Space must be available for the time the block is assembled before the block can be allocated to the factory.

```<code>for i in range(num_Block+1):
    s_Time[i] =m.addVar(lb=0,vtype=GRB.INTEGER,name='s_time'+str(i))
    c_Time[i] =m.addVar(lb=0,vtype=GRB.INTEGER,name='c_time'+str(i))

for i in range(1,num_Block+1):
    m.addConstr(s_Time[i]+p_Time[i]==c_Time[i])

# This part occurs error because of s_Time[i],c_Time[1]
m.addConstrs(sp[i]*y[i,f] <=c[f,t] for f in range(1,num_Factory+1) for i in range(1,num_Block+1) for t in range(s_Time[i],c_Time[i]))
</code>```

Is there another way to express  constraints? or How can i solve it

答: Gurobi is for linear (and quadratic) models. You cannot use a variable as a limit for indexing (that would make the model nonlinear). In general, such constructs are reformulated using binary variables or indicator constraints. You may want to discuss this with your teacher/supervisor. </p>

Title: Can't i use the variable in a formula?

Body:
I'm coding a math model using gurobiy, but an error occurs.

the error is 'Var' object cannot be interpreted as an integer.

i tried to solve it using search, but I don't have enough information.

spi: required space of block i

cft: area of factory f at t time

s_Time : Start time

p_Time : processing time

c_Time : completion time,

t: time

f: factory

i: block

yif : If blcok i is assgined at factory f  1 otherwise 0

Space must be available for the time the block is assembled before the block can be allocated to the factory.

for i in range(num_Block+1):
    s_Time[i] =m.addVar(lb=0,vtype=GRB.INTEGER,name='s_time'+str(i))
    c_Time[i] =m.addVar(lb=0,vtype=GRB.INTEGER,name='c_time'+str(i))

for i in range(1,num_Block+1):
    m.addConstr(s_Time[i]+p_Time[i]==c_Time[i])

# This part occurs error because of s_Time[i],c_Time[1]
m.addConstrs(sp[i]*y[i,f] <=c[f,t] for f in range(1,num_Factory+1) for i in range(1,num_Block+1) for t in range(s_Time[i],c_Time[i]))

Is there another way to express  constraints? or How can i solve it


问:
How to compare "4A4B4C" (string shows hex value) actual string is "JKL"
I am getting a string "4A4B4C4D4E4F".. it is equal to a string ("JKLMNO")

How can I check this type of string in c++.. (one string shows the hexadecimal representation of another)

hexadecimal value of

```<code>J=4A, K=4B, L=4C
</code>```

答:
Alternatively this can be done using C++ strings and features rather than C-style strings:</p>

```<code>#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <iomanip>
#include <string>

bool compareAscii(const std::string& string, const std::string& asciistr) {
   std::ostringstream result;
   result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
   // We copy the contents of string, using the range from the beginning to the end.
   // By copying it to an ostream iterator it gets written to the ostringstream,
   // but crucially we treat it as an unsigned int when we write it, which causes
   // the chars to get printed as their numerical values instead.
   std::copy(string.begin(), string.end(), std::ostream_iterator<unsigned int>(result));
   return result.str() == asciistr;
}

namespace {
   const std::string test="JKLMNO";
   const std::string value="4A4B4C4D4E4F";
}

int main() {
   std::cout << "compareAscii(\"" << test << "\", \"" << value << "\") returned " << compareAscii(test, value) << std::endl;
   return 0;
}
</code>```

Body:
I am getting a string "4A4B4C4D4E4F".. it is equal to a string ("JKLMNO")

How can I check this type of string in c++.. (one string shows the hexadecimal representation of another)

hexadecimal value of

J=4A, K=4B, L=4C

Body:
Alternatively this can be done using C++ strings and features rather than C-style strings:

#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <iomanip>
#include <string>

bool compareAscii(const std::string& string, const std::string& asciistr) {
   std::ostringstream result;
   result << std::setw(2) << std::setfill('0') << std::hex << std::uppercase;
   // We copy the contents of string, using the range from the beginning to the end.
   // By copying it to an ostream iterator it gets written to the ostringstream,
   // but crucially we treat it as an unsigned int when we write it, which causes
   // the chars to get printed as their numerical values instead.
   std::copy(string.begin(), string.end(), std::ostream_iterator<unsigned int>(result));
   return result.str() == asciistr;
}

namespace {
   const std::string test="JKLMNO";
   const std::string value="4A4B4C4D4E4F";
}

int main() {
   std::cout << "compareAscii(\"" << test << "\", \"" << value << "\") returned " << compareAscii(test, value) << std::endl;
   return 0;
}


问:
Cannot get refresh token for Chrome Web Store API to publish Chrome extension
I'm trying to upload and publish my Chrome Extension using Chrome Web Store API in Azure DevOps. I've been referencing the official Google guide but the problem is that it looks like it's outdated now. I'm failing at the step

To create the client ID and client secret, click on Create New Client ID, select Installed Application, and Other under Installed application type.

When I do this, I don't see option for "Other" in Application Type dropdown.

I've tried the following:

Choosing Web Application as Application Type

With this I'm not able to get an access code with this link:

https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.googleapis.com/auth/chromewebstore&client_id=$CLIENT_ID&redirect_uri=urn:ietf:wg:oauth:2.0:oob

it's resulting in "Error 400: redirect_uri_mismatch". If I add an authorized redirect URI in my Client ID settings, like 'localhost', and replace 'urn:ietf:wg:oauth:2.0:oob' in URL above with it, I'm able to invoke authorization process and get the code from URL. But when I try to make a curl request to https://accounts.google.com/o/oauth2/token to get the refresh token I don't receive a refresh token, I only get this:

```<code>{
  "access_token": "",
  "expires_in": 3599,
  "scope": "https://www.googleapis.com/auth/chromewebstore",
  "token_type": "Bearer"
}
</code>```

Choosing Chrome App as Application Type

Pretty much the same happens here as in previous attempt, except I don't have to substitute the redirect URI in request for access code, but I also don't have Client Secret for this application type, so I just omit it. Anyways, it results in the same response that doesn't have refresh token.

When I enable Chrome Web Store API in dev console and try to create new credentials, it suggests to create API key instead of Cliend ID. But it doesn't look like this API can actually work with this key, I've tried sending it as query param, as a header, and I always get 401 result with "Login Required" message. But when I try to send a request with (invalid) token in a header I get meaningful response (smth like Invalid Credentials).

Apparently I do need to have access token to work with Chrome Web Store API but without refresh token I need to manually authorize my permissions and that's not acceptable because I need to use in my CI/CD pipeline. It looks like Google removed the option to just generate this info for such application types.

So, the question is, how can I get the refresh token to actually be able to continuously deploy the chrome extension?

答:
Ok, so the trick here was to add two params to the request that you use to get the access code (not token):

&access_type=offline&approval_prompt=force

And so the link should be:

https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.googleapis.com/auth/chromewebstore&client_id=$CLIENT_ID&redirect_uri=urn:ietf:wg:oauth:2.0:oob&access_type=offline&approval_prompt=force

And Google should do better job in updating their docs.

Body:
I'm trying to upload and publish my Chrome Extension using Chrome Web Store API in Azure DevOps. I've been referencing the official Google guide but the problem is that it looks like it's outdated now. I'm failing at the step

To create the client ID and client secret, click on Create New Client ID, select Installed Application, and Other under Installed application type.

When I do this, I don't see option for "Other" in Application Type dropdown.

I've tried the following:

Choosing Web Application as Application Type

With this I'm not able to get an access code with this link:

https://accounts.google.com/o/oauth2/auth?response_type=code&scope=https://www.googleapis.com/auth/chromewebstore&client_id=$CLIENT_ID&redirect_uri=urn:ietf:wg:oauth:2.0:oob

it's resulting in "Error 400: redirect_uri_mismatch". If I add an authorized redirect URI in my Client ID settings, like 'localhost', and replace 'urn:ietf:wg:oauth:2.0:oob' in URL above with it, I'm able to invoke authorization process and get the code from URL. But when I try to make a curl request to https://accounts.google.com/o/oauth2/token to get the refresh token I don't receive a refresh token, I only get this:

{
  "access_token": "",
  "expires_in": 3599,
  "scope": "https://www.googleapis.com/auth/chromewebstore",
  "token_type": "Bearer"
}

Choosing Chrome App as Application Type

Pretty much the same happens here as in previous attempt, except I don't have to substitute the redirect URI in request for access code, but I also don't have Client Secret for this application type, so I just omit it. Anyways, it results in the same response that doesn't have refresh token.

When I enable Chrome Web Store API in dev console and try to create new credentials, it suggests to create API key instead of Cliend ID. But it doesn't look like this API can actually work with this key, I've tried sending it as query param, as a header, and I always get 401 result with "Login Required" message. But when I try to send a request with (invalid) token in a header I get meaningful response (smth like Invalid Credentials).

Apparently I do need to have access token to work with Chrome Web Store API but without refresh token I need to manually authorize my permissions and that's not acceptable because I need to use in my CI/CD pipeline. It looks like Google removed the option to just generate this info for such application types.

So, the question is, how can I get the refresh token to actually be able to continuously deploy the chrome extension?