问:
Accessing a Private Constructor from Outside the Class in C#
If I define a class with a private default constructor and a public constructor that has parameters, how can I access the private constructor?

```<code>public class Bob
{
   public String Surname { get; set; }

   private Bob()
   { }

   public Bob(string surname)
   {
      Surname = surname;
   }
}
</code>```

I can access the private constructor via a static method on the class like this:

```<code>public static Bob GetBob()
{
   return new Bob();
}
</code>```

I thought that I could access the private constructor via an extension method, since (according to my understanding) extension methods are translated so that they appear to be static methods on the class, but I can't:

```<code>static class Fred
{
   public static Bob Bobby(this Bob bob)
   {
      return new Bob();
   }
}
</code>```

So, how can I access the private constructor?

Thank you

EDIT:

The reason that I wanted to do this was that I wanted to create tests for one of our business classes, but not allow a consumer of this class to be able to instantiate an object incorrectly. I'm testing it, so I know (I hope!) under what circumstances the tests will fail. I'm still a testing n00b right now so my idea may or may not have been the "wrong way" of doing things.

I've changed my testing strategy to just do things the way the a consumer of this class would, i.e. calling the public methods and if the public methods are OK, assuming that the private methods are OK. I would still prefer to test the private methods, but my boss is breathing down my neck on a deliverable :-(

答:
if a class has only private and no public constructors, it can only be only accessible from nested classes within this class. what is worthy taking into consideration is the fact that classes with private default constructor cannot be derived.
so it only makes sense to declare constructor or constructors as private (in a class which has no public instructors) when the instances from the class are aimed to be created only within nested classes inside this class. there is no other valid places for instancing this class.</p>

Body:
If I define a class with a private default constructor and a public constructor that has parameters, how can I access the private constructor?

public class Bob
{
   public String Surname { get; set; }

   private Bob()
   { }

   public Bob(string surname)
   {
      Surname = surname;
   }
}

I can access the private constructor via a static method on the class like this:

public static Bob GetBob()
{
   return new Bob();
}

I thought that I could access the private constructor via an extension method, since (according to my understanding) extension methods are translated so that they appear to be static methods on the class, but I can't:

static class Fred
{
   public static Bob Bobby(this Bob bob)
   {
      return new Bob();
   }
}

So, how can I access the private constructor?

Thank you

EDIT:

The reason that I wanted to do this was that I wanted to create tests for one of our business classes, but not allow a consumer of this class to be able to instantiate an object incorrectly. I'm testing it, so I know (I hope!) under what circumstances the tests will fail. I'm still a testing n00b right now so my idea may or may not have been the "wrong way" of doing things.

I've changed my testing strategy to just do things the way the a consumer of this class would, i.e. calling the public methods and if the public methods are OK, assuming that the private methods are OK. I would still prefer to test the private methods, but my boss is breathing down my neck on a deliverable :-(


来源: stackexchange

问:
RegEx for Javascript to allow only alphanumeric
I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just want one what would allow either and not require both.</p>

答:
I have string similar to Samsung Galaxy A10s 6.2-Inch (2GB,32GB ROM) Android 9.0, (13MP+2MP)+ 8MP Dual SIM 4000mAh 4G LTE Smartphone - Black (BF19)

Below is what i did:

```<code>string.replace(/[^a-zA-Z0-9 ,._-]/g, '').split(',').join('-').split(' ').join('-').toLowerCase()
</code>```

Notice i allowed ,._- then use split() and join() to replace , to - and space to - respectively.

I ended up getting something like this:
samsung-galaxy-a10s-6.2-inch-2gb-32gb-rom-android-9.0-13mp-2mp-8mp-dual-sim-4000mah-4g-lte-smartphone-black-bf19-20 which is what i wanted.

There might be a better solution but this is what i found working fine for me.

ContentLicense: CC BY-SA 3.0

Body:
I have string similar to Samsung Galaxy A10s 6.2-Inch (2GB,32GB ROM) Android 9.0, (13MP+2MP)+ 8MP Dual SIM 4000mAh 4G LTE Smartphone - Black (BF19)

Below is what i did:

string.replace(/[^a-zA-Z0-9 ,._-]/g, '').split(',').join('-').split(' ').join('-').toLowerCase()

Notice i allowed ,._- then use split() and join() to replace , to - and space to - respectively.

I ended up getting something like this:
samsung-galaxy-a10s-6.2-inch-2gb-32gb-rom-android-9.0-13mp-2mp-8mp-dual-sim-4000mah-4g-lte-smartphone-black-bf19-20 which is what i wanted.

There might be a better solution but this is what i found working fine for me.

ContentLicense: CC BY-SA 4.0


问:
Dynamic Feature Module with Flutter
I am a Native Android Developer and I was learning Dynamic Feature Module from here
But I also work with flutter. So, is this feature available in flutter?</p>

答: It is not but flutter now has ability to add flutter to existing android app which you can use for that case, I.e build all submodule in flutter and add or load them in a native app, I hope you got an idea.</p>

Title: Dynamic Feature Module with Flutter


问:
Why does JQuery function returns undefined in update panel
I have this jquery code that disables an export option in srss.

```

It should search and hide the PDF option. The issue is it works on most pages however it fails to alter the display options of reports that are within update panels. My guess is that the update panel is messing with the Jquery operations.

What are your recommendations. I cannot remove the update panels from the pages.

答:
When using an UpdatePanel, you need to rebind jQuery to DOM elements within the UpdatePanel because the original ones are lost due to the update.</p>

```<code><script type="text/javascript">
    $(document).ready(function () {
        hideOptions();
    });

    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_endRequest(function () {
        hideOptions();
    });

    function hideOptions() {
        var MHTMLid = $("a[onclick=\"$find('ctl00_ContentPlaceHolder1_ReportViewerControl1_ReportViewer1').exportReport('PDF');\"]").parent().parent().attr("id");
        $("#" + MHTMLid + " div:nth-child(4)").css('display', 'none');
        console.log(MHTMLid);
    }
</script>
</code>```

Body:
I have this jquery code that disables an export option in srss.

It should search and hide the PDF option. The issue is it works on most pages however it fails to alter the display options of reports that are within update panels. My guess is that the update panel is messing with the Jquery operations.

What are your recommendations. I cannot remove the update panels from the pages.

Body:
When using an UpdatePanel, you need to rebind jQuery to DOM elements within the UpdatePanel because the original ones are lost due to the update.

<script type="text/javascript">
    $(document).ready(function () {
        hideOptions();
    });

    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_endRequest(function () {
        hideOptions();
    });

    function hideOptions() {
        var MHTMLid = $("a[onclick=\"$find('ctl00_ContentPlaceHolder1_ReportViewerControl1_ReportViewer1').exportReport('PDF');\"]").parent().parent().attr("id");
        $("#" + MHTMLid + " div:nth-child(4)").css('display', 'none');
        console.log(MHTMLid);
    }
</script>


问:
SQL padding 0 to the left of a number in string
I am a beginner in SQL language and I am using postgre sql and doing little exercices to learn. I have a column of strings named acronym from a destination table:

```<code> DO1
 ES1
 ES2
 FR1
 FR10
 FR2
 FR3
 FR4
 FR5
 FR6
 FR7
 FR8
 FR9
 GP1
 GP2
 IN1
 IN2
 MU1
 RU1
 TR1
 UA1
</code>```

I would like to add a padding zero for acronym numbers that have only one digit, output:

```<code> DO01
 ES01
 ES02
 FR01
 FR02
 FR03
 FR04
 FR05
 FR06
 FR07
 FR08
 FR09
 FR10
 GP01
 GP02
 IN01
 IN02
 MU01
 RU01
 TR01
 UA01
</code>```

How can I get to the left of the first number in the string? There is some regex I think but I did not figure it out

答:
try with below:

to_char() function

```<code>select to_char(column1, 'fm000') as column2
from Test_table;
</code>```

fm "fill mode"prefix avoids leading spaces in the resulting var char.
000 it defines the number of digits you want to have.

Body:
I am a beginner in SQL language and I am using postgre sql and doing little exercices to learn. I have a column of strings named acronym from a destination table:

 DO1
 ES1
 ES2
 FR1
 FR10
 FR2
 FR3
 FR4
 FR5
 FR6
 FR7
 FR8
 FR9
 GP1
 GP2
 IN1
 IN2
 MU1
 RU1
 TR1
 UA1

I would like to add a padding zero for acronym numbers that have only one digit, output:

 DO01
 ES01
 ES02
 FR01
 FR02
 FR03
 FR04
 FR05
 FR06
 FR07
 FR08
 FR09
 FR10
 GP01
 GP02
 IN01
 IN02
 MU01
 RU01
 TR01
 UA01

How can I get to the left of the first number in the string? There is some regex I think but I did not figure it out

Body:
try with below:

to_char() function

select to_char(column1, 'fm000') as column2
from Test_table;

fm "fill mode"prefix avoids leading spaces in the resulting var char.
000 it defines the number of digits you want to have.


问:
prevention of additional eventListeners being added to a dom element
Is there any way to ensure that no more event listeners are added to a particular element(in js). Due to template I have chosen after certain actions there are some event handlers being added to a particular element which contain lines like e.preventDefault(); e.stopPropagation(); which hinders my work .Since I can't remove these lines is there any way with which I can prevent an eventHandler being attached to an element?

答:
This is hacky, but if you can run code before the bad event listener code runs, you can temporarily change addEventListener to a no-op, then change it back afterwards:

// Inject this first:
HTMLElement.prototype.addEventListener = () => {
  console.log('Refusing to add bad event listener');
  delete HTMLElement.prototype.addEventListener;
};

// Then the attachment of the bad listener will fail:
document.querySelector('#container').addEventListener('click', (e) => {
  console.log('Bad listener running');
  e.stopPropagation();
});

console.log('Bad code finished, now adding good event listeners again');
// And your other listeners that want to be able to see the event will succeed:
document.body.addEventListener('click', (e) => {
  console.log('Saw click on body');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">click me</div></code>```

A more elaborate method would be to examine the source of the passed function string to see if it contains preventDefault (or exactly matches what you want to not get attached).

An alternative which doesn't involve preventing the attachment of that listener is to add your own listeners in the capturing phase, before the event propagation gets stopped:

document.querySelector('#container').addEventListener('click', (e) => {
  console.log('Bad listener running');
  e.stopPropagation();
});

console.log('Bad code finished, now adding good event listeners again');
document.body.addEventListener('click', (e) => {
  console.log('Saw click on body');
}, true); // <---- pass 3rd parameter of true to listen in capturing phase```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">click me</div></code>```

Body:
This is hacky, but if you can run code before the bad event listener code runs, you can temporarily change addEventListener to a no-op, then change it back afterwards:

// Inject this first:
HTMLElement.prototype.addEventListener = () => {
  console.log('Refusing to add bad event listener');
  delete HTMLElement.prototype.addEventListener;
};

// Then the attachment of the bad listener will fail:
document.querySelector('#container').addEventListener('click', (e) => {
  console.log('Bad listener running');
  e.stopPropagation();
});

console.log('Bad code finished, now adding good event listeners again');
// And your other listeners that want to be able to see the event will succeed:
document.body.addEventListener('click', (e) => {
  console.log('Saw click on body');
});

<div id="container">click me</div>

A more elaborate method would be to examine the source of the passed function string to see if it contains preventDefault (or exactly matches what you want to not get attached).

An alternative which doesn't involve preventing the attachment of that listener is to add your own listeners in the capturing phase, before the event propagation gets stopped:

document.querySelector('#container').addEventListener('click', (e) => {
  console.log('Bad listener running');
  e.stopPropagation();
});

console.log('Bad code finished, now adding good event listeners again');
document.body.addEventListener('click', (e) => {
  console.log('Saw click on body');
}, true); // <---- pass 3rd parameter of true to listen in capturing phase

<div id="container">click me</div>


问:
Merge a collection using the same key values
I have two collections with data to combine:

```<code>//1
  [
     [
       "date" => "2019-02-15",
       "clicks" => 1,
     ],
   ]
//2
[
     [
       "date" => "2019-02-15",
       "users" => 1,
     ],
   ]
</code>```

it is necessary that the collection elements (arrays) that have the same values for a particular key are combined

Body:
I have two collections with data to combine:

//1
  [
     [
       "date" => "2019-02-15",
       "clicks" => 1,
     ],
   ]
//2
[
     [
       "date" => "2019-02-15",
       "users" => 1,
     ],
   ]

it is necessary that the collection elements (arrays) that have the same values for a particular key are combined

Body:
<?php

$c1 = collect([
    [
        "date" => "2019-02-15",
        "clicks" => 1,
    ],
    [
        "date" => "2019-02-16",
        "clicks" => 3,
    ],
]);

$c2 = collect([
    [
        "date" => "2019-02-15",
        "users" => 4,
    ],
    [
        "date" => "2019-02-16",
        "users" => 5,
    ],
]);

$c1->merge($c2)
    ->groupBy('date')
    ->map(function ($items) {
        return Arr::collapse($items);
    });


答:
You can use string functions like lpad(), substr(), left():

```<code>select
  concat(left(columnname, 2), lpad(substr(columnname, 3), 2, '0')) result
from tablename
</code>```

See the demo.

Results:

```<code>| result |
| ------ |
| DO01   |
| ES01   |
| ES02   |
| FR01   |
| FR10   |
| FR02   |
| FR03   |
| FR04   |
| FR05   |
| FR06   |
| FR07   |
| FR08   |
| FR09   |
| GP01   |
| GP02   |
| IN01   |
| IN02   |
| MU01   |
| RU01   |
| TR01   |
| UA01   |
</code>```

Title: SQL padding 0 to the left of a number in string

Body:
You can use string functions like lpad(), substr(), left():

select
  concat(left(columnname, 2), lpad(substr(columnname, 3), 2, '0')) result
from tablename

See the demo.

Results:

| result |
| ------ |
| DO01   |
| ES01   |
| ES02   |
| FR01   |
| FR10   |
| FR02   |
| FR03   |
| FR04   |
| FR05   |
| FR06   |
| FR07   |
| FR08   |
| FR09   |
| GP01   |
| GP02   |
| IN01   |
| IN02   |
| MU01   |
| RU01   |
| TR01   |
| UA01   |


问:
Ruby - when is block executed?
I understood how ruby's block works.

block_test.rb

```<code>def foo
  yield if block_given?
end

my_block = foo { puts "hello" }
</code>```

if I run, ruby block_test.rb. Of course it print 'hello' as you expected.

```<code>hello
</code>```

But my question is when did I execute ruby block?
I did not call foo method in anywhere.

I didn't write - foo() stuff like that.

```<code># I defined `foo` method here as [If a block has been given, execute it.] but did not call.
def foo
  yield if block_given?
end

# I also defined block of `foo` as [print 'hello'] and store into `my_block` variable.
# But I did not say execute `foo`. Did I?
my_block = foo { puts "hello" }
</code>```

So my assumption is..
When you declare block, It implicitly means that it will execute the method with the same name of the block

Please correct me If I am missing something.

答:
I didn't write - foo() stuff like that.

In Ruby, parentheses are optional when calling methods. You can call a method without parentheses. For example, puts is often called without parentheses like this:

```<code>puts "hello"
</code>```

You are calling your method here:

my_block = foo { puts "hello" }
#          ^^^
```

So my assumption is..
  When you declare block, It implicitly means that it will execute the method with the same name of the block

It is unclear what you are asking here. A block doesn't have a name, so "the method with the same name of the block" doesn't make sense. A block is a special argument to a method call. It cannot appear anywhere else except as the last argument of a method call. It cannot be assigned to a variable, it cannot be returned from a method, it cannot be given a name. It is not an object or a value.

Title: Ruby - when is block executed?

Body:
I understood how ruby's block works.

block_test.rb

def foo
  yield if block_given?
end

my_block = foo { puts "hello" }

if I run, ruby block_test.rb. Of course it print 'hello' as you expected.

hello

But my question is when did I execute ruby block?
I did not call foo method in anywhere.

I didn't write - foo() stuff like that.

# I defined `foo` method here as [If a block has been given, execute it.] but did not call.
def foo
  yield if block_given?
end

# I also defined block of `foo` as [print 'hello'] and store into `my_block` variable.
# But I did not say execute `foo`. Did I?
my_block = foo { puts "hello" }

So my assumption is..
When you declare block, It implicitly means that it will execute the method with the same name of the block

Please correct me If I am missing something.

Body:
I didn't write - foo() stuff like that.

In Ruby, parentheses are optional when calling methods. You can call a method without parentheses. For example, puts is often called without parentheses like this:

puts "hello"

You are calling your method here:

my_block = foo { puts "hello" }
#          ^^^

So my assumption is..
  When you declare block, It implicitly means that it will execute the method with the same name of the block

It is unclear what you are asking here. A block doesn't have a name, so "the method with the same name of the block" doesn't make sense. A block is a special argument to a method call. It cannot appear anywhere else except as the last argument of a method call. It cannot be assigned to a variable, it cannot be returned from a method, it cannot be given a name. It is not an object or a value.


问:
Which design pattern to use for a 2D iPhone game?
To give a little background about the game: falling items float from the top, and the objective is to flick/slide another object to hit them. If an item hits the ground, you lose a life, and gain points for hitting falling items.

Here is where I'm a little confused. In O'Reilly's iPhone game development. They state have the AppDelegate inherit a game state machine object, and have the main game loop in the App Delegate. Nothing about MVC.

I was going to use MVC. I have all the objects identified for the models, and was going to use one controller to update each model and their corresponding view. Then have a navigation controller in the App Delegate, and push certain controllers (Play, instructions, stats) from the home screen. Then have the game loop run in my gameViewController. I am using Chipmunk as a physics engine by the way.

This is my first game so I'm little confused. I would greatly appreciate any advice on how to proceed. I would like to get the object orientated design right from the start before jumping into code.

答:
Do you not consider that game state machine to be a kind of data model? I don't have the O'Reilly book you mention, but the description you give sounds to me very much like MVC.

The main point of MVC is to separate an application's content from the way that content is represented on the screen. The "model" in MVC doesn't have to consist of dumb data objects that you read from a file or a web server... it could just as easily be a simulation, a connection to another device, etc. The way I think of it is that the model is the part that you'd keep if you were going to throw out app's GUI and replace it with a script, a command line interface, or maybe a web service. A game state machine could certainly fit that description.

It's not uncommon in an iOS app to have the application delegate instantiate the model. You then have view controllers that know how to talk to the model and translate the data that it provides into something that can be displayed in the view(s). If some of the data that the model provides are graphic elements like textures or meshes, that's okay... those are the data that the game operates on, after all.


问:
How to include Enum in Dart class?
I have defined enum like:

```<code>enum Status {
 done,
 current,
 future
}
</code>```

I want to include this enum inside the class which is defined below.
Both the enum and class are in same file.

The enum is defined outside of the class because multiple classes should be able to use it.

When using the enum vscode is giving me an error Status not defined

```<code>class WeekDay extends StatelessWidget {
 final int day;
 final Status status;
 const WeekDay({this.day, this.status});

 @override
 Widget build(BuildContext context) {
  return Container();
 }
}
</code>```

How do we import Enum in class in Dart?

答:
Sorry, for the silly question.
It Was VSCODE problem,

The error was gone after restarting the vscode.

The above code works perfectly fine.

Title: How to include Enum in Dart class?

Body:
I have defined enum like:

enum Status {
 done,
 current,
 future
}

I want to include this enum inside the class which is defined below.
Both the enum and class are in same file.

The enum is defined outside of the class because multiple classes should be able to use it.

When using the enum vscode is giving me an error Status not defined

class WeekDay extends StatelessWidget {
 final int day;
 final Status status;
 const WeekDay({this.day, this.status});

 @override
 Widget build(BuildContext context) {
  return Container();
 }
}

How do we import Enum in class in Dart?


答: You need to import the files your are depending on like the following (if e.g. status and weekday are in the same folder):

Title: How to include Enum in Dart class?


问:
Handle concurrent async updates to local state
I have a series of asynchronous calls that read from a local state S, perform some computation based on its current value, and return a new, update value of the local state S'

All this happens at runtime, so I have very little control over the order of these operations. This is a simplified version of what I have.

type State = {
  state: number
}

let localState: State = {
  state: 1000
}

const promiseTimeout = (time: number, value: number) => () => new Promise(
    (resolve: (n: number) => void) => setTimeout(resolve, time, value + time)
  );

const post: (n: number, currentState: State) => Promise<void> = (n, c) => promiseTimeout(n, c.state)()
  .then(res => {
    localState.state = res
    console.log(localState)
  })

post(1000, localState); // localState at call time is 1000
post(3000, localState); // localState at call time is still 1000
// when both promises resolve, the final value of localState will be 4000 instead of 5000
```

<p>Playground link</p>

<p>This model is clearly broken, as both calls to <code>post</code> will read the same value of <code>localState</code>, while instead they should be performed sequentially.</p>

<p>If all calls were already determined at compile time, I could simply have something like</p>

<pre class="lang-js prettyprint-override"><code>post(1000, localState)
  .then(() => post(3000, localState)) // localState at call time is now 2000
</code>```

How would I go about solving this?

答:
I have no experience with TypeScript, so you'll have to do the conversion yourself.

You could considder adding a queue method to your state, which takes a callback. If the callback returns an promise it will wait for it to finish. If not the next item in the queue is immediately executed.

function createQueue() {
  var promise = Promise.resolve();
  return function (fn) {
    promise = promise.then(() => fn(this));
    return promise;
  };
}

const localState = { state: 1000, queue: createQueue() };

const timeout = (...args) => new Promise(resolve => setTimeout(resolve, ...args));
const promiseTimeout = (time, value) => timeout(time, value + time);

const post = (time, state) => state.queue(() => {
  return promiseTimeout(time, state.state).then(result => {
    state.state = result;
    console.log(state.state);
  });
});

post(1000, localState).then(() => console.log("post 1000 complete"));
post(3000, localState).then(() => console.log("post 3000 complete"));```

Body:
I have a series of asynchronous calls that read from a local state S, perform some computation based on its current value, and return a new, update value of the local state S'

All this happens at runtime, so I have very little control over the order of these operations. This is a simplified version of what I have.

type State = {
  state: number
}

let localState: State = {
  state: 1000
}

const promiseTimeout = (time: number, value: number) => () => new Promise(
    (resolve: (n: number) => void) => setTimeout(resolve, time, value + time)
  );

const post: (n: number, currentState: State) => Promise<void> = (n, c) => promiseTimeout(n, c.state)()
  .then(res => {
    localState.state = res
    console.log(localState)
  })

post(1000, localState); // localState at call time is 1000
post(3000, localState); // localState at call time is still 1000
// when both promises resolve, the final value of localState will be 4000 instead of 5000

<a href="https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=23&pc=1#code/C4TwDgpgBAysCGxoF4oG8BQUoGcFIC4oA7AVwFsAjCAJwwF8MMAbCYKZgewGN5m5EEIgKRRUmbHkFEAjAAYFDJt07E8UMDU7kAljggAVHeQidS7VAApgxoSQrUaAGigA3PqTtkqtAJRiAPihLf2Qg4ggAdygABS1dfUssbGCaCBxOZlc7S2Iib0dQoNdOHQATItw2IxMzYEs0jKyIFxsTF3dmTygAaig2iF9k3wBuJgwVNXYwTjwiXPyHWhduUho04mARO23KuO09CAAeEvKgq2IVys0D-RrTc1yVgDopJF8Q5OfgAAsIYga6UC6GS2C4vH4+AgryhYigjVBUEmTWhXAA5pZwXxdsl6EMMDM8JZ5AoXFjIYJRgTZvUAMwKORknjYqFUjBAA" rel="nofollow noreferrer">Playground link

This model is clearly broken, as both calls to post will read the same value of localState, while instead they should be performed sequentially.

If all calls were already determined at compile time, I could simply have something like

post(1000, localState)
  .then(() => post(3000, localState)) // localState at call time is now 2000

How would I go about solving this?


问:
GCP Connection Failed - SSH - We are unable to connect to the VM on port 22
Since I received a email warning letter from google says "Action required: Critical problem with My First Project" saying my server has some abnormal outgoing activity , I tried to implemented ufw in my debian server.

For my ufw setting, I've done the following:

```<code>sudo ufw default deny incoming
sudo ufw default deny outgoing
sudo ufw allow ssh
sudo ufw allow 22
sudo ufw allow http
sudo ufw allow https
</code>```

After I restart my server , I can't connect to my server with the error "Connection Failed: We are unable to connect to the VM on port 22. Learn more about possible causes of this issue."

I followed the following instruction https://cloud.google.com/compute/docs/troubleshooting/troubleshooting-ssh but it still not working:

I tried gcloud to create default-allow-ssh
my firewall-rules list picture

I tried to use serial console to login but I haven't set password to my root account so I can't login.

I tried to add "/usr/sbin/ufw disable" to startup-script in Custom metadata and restart server many times but it seems the command is not executed so still not working
my gcp startup-script picture

答:
I found the correct answer in this website.
https://www.jhanley.com/google-cloud-recovering-from-ufw-lockout/

Method 2 in the website solves this problem

Body:
Since I received a email warning letter from google says "Action required: Critical problem with My First Project" saying my server has some abnormal outgoing activity , I tried to implemented ufw in my debian server.

For my ufw setting, I've done the following:

sudo ufw default deny incoming
sudo ufw default deny outgoing
sudo ufw allow ssh
sudo ufw allow 22
sudo ufw allow http
sudo ufw allow https

After I restart my server , I can't connect to my server with the error "Connection Failed: We are unable to connect to the VM on port 22. Learn more about possible causes of this issue."

I followed the following instruction https://cloud.google.com/compute/docs/troubleshooting/troubleshooting-ssh but it still not working:

I tried gcloud to create default-allow-ssh
my firewall-rules list picture

I tried to use serial console to login but I haven't set password to my root account so I can't login.

I tried to add "/usr/sbin/ufw disable" to startup-script in Custom metadata and restart server many times but it seems the command is not executed so still not working
my gcp startup-script picture


问:
Async / Await cause a loop
I try to use the Async / Await instead of .then() with a promise.
With the .then() Method my code works fine...

When i change it to Async / Await then i got a loop

Antother Question: How can i disable the Promise  in my console.log()?

Thank you .........

```<code>ASCBY1
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
state:2
</code>```

**This is working fine **

  private innerLoop(i,ifArray,counter,cb){
    let tempMod = new Module(null, ifArray[i].id,ifArray[i].type);
    /*FALLS CHCEK BY MODULE*/

    if(ifArray[i].timerID === 0){ //WENN ein Timer ausgeführt iwrd, dann gibt es kein Modul bzw. kein DevType, er muss aber dennoch durch alle Schleifen (ifArray) laufen. Ohne der && this.mod.... würde er bei switch case ein Fehler ausspucken weil es den DevType nicht gibt.
      if(!(this.mod === undefined)){
      //  var tempMod = new Module(ifArray[i].id,ifArray[i].type);
        setTimeout(()=>console.log(tempMod.getState()),1000);
        switch (this.mod.modulesRecievedData.DevType){
           case 0x0b:{
             if(this.mod.checkMultiSwitch(ifArray[i])){
               counter++;
             }
             break;
           }
           case 0x02:{
              console.log("ASCBY1");

              tempMod.getState().then((state)=>{
                if(state == 2) counter++;

                console.log("state:"+state);

                if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
                  this.innerLoop(i,ifArray,counter,cb);
                }else{
                  cb(counter);
                }
              });

              break;
           }
        }
        i++;
      }
    }else if(ifArray[i].timerID > 0){  /*FALLS CHECK BY TIMER*/
      var timerOnState = time[ifArray[i].timerID].timerOnState;
      if(timerOnState == true){
        counter++;
      }
      i++;
      if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
        this.innerLoop(i,ifArray,counter,cb);
      }else{
         console.log("counter3 "+counter);
        cb(counter);
      }
    }
  }```
</div>
</div>
</p>

<p><strong>This cause a look</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>private async innerLoop(i,ifArray,counter,cb){
    let tempMod = new Module(null, ifArray[i].id,ifArray[i].type);
    /*FALLS CHCEK BY MODULE*/

    if(ifArray[i].timerID === 0){ //WENN ein Timer ausgeführt iwrd, dann gibt es kein Modul bzw. kein DevType, er muss aber dennoch durch alle Schleifen (ifArray) laufen. Ohne der && this.mod.... würde er bei switch case ein Fehler ausspucken weil es den DevType nicht gibt.
      if(!(this.mod === undefined)){
      //  var tempMod = new Module(ifArray[i].id,ifArray[i].type);
        setTimeout(()=>console.log(tempMod.getState()),1000);
        switch (this.mod.modulesRecievedData.DevType){
           case 0x0b:{
             if(this.mod.checkMultiSwitch(ifArray[i])){
               counter++;
             }
             break;
           }
           case 0x02:{
              console.log("ASCBY1");
              ///////////////////////////////////
              //////HERE IS THE CHANGE///////////
              ///////////////////////////////////
              let state = await tempMod.getState();

              if(state == 2) counter++;

              console.log("state:"+state);

              if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
                this.innerLoop(i,ifArray,counter,cb);
              }else{
                cb(counter);
              }
              break;
           }
        }
        i++;
      }
    }else if(ifArray[i].timerID > 0){  /*FALLS CHECK BY TIMER*/
      var timerOnState = time[ifArray[i].timerID].timerOnState;
      if(timerOnState == true){
        counter++;
      }
      i++;
      if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
        this.innerLoop(i,ifArray,counter,cb);
      }else{
         console.log("counter3 "+counter);
        cb(counter);
      }
    }
  }</code>```

Module class

 getState(){
  let promise = new Promise((resolve)=>{
   this.db.getStateOfModule(this._id,this._type,
    (data)=>{this._state = data[0].state; resolve(data[0].state);}
   );
  });

  return promise;
 }```

答:
Module.getState returns a promise.

The line setTimeout(()=>console.log(tempMod.getState()),1000);
is waiting 1000ms, then console logging the result of tempMod.getState(), which is an unresolved promise.

If you do not want to be getting Promise { <pending> } in the console. You can change it to

setTimeout(() => tempMod.getState().then((result) => {
  console.log(result)
}), 1000);
```

As for the looping issue. When you are using .then(). The rest of the code after the .then() will immediately run. In particular the i++. Only the code that is inside the then callback will be delayed.

When you changed this to await. the entire function will stop executing until the promise resolves. That means the i++ will not be executed.

I am assuming ifArray.length is 1 and i starts at 0. So when you get to if(i < ifArray.length){ This will be true when using await (as i++ did not execute) which will cause innerLoop to be called again.
The same thing will keep happening as i++ will never be executed.

Title: Async / Await cause a loop

Body:
I try to use the Async / Await instead of .then() with a promise.
With the .then() Method my code works fine...

When i change it to Async / Await then i got a loop

Antother Question: How can i disable the Promise  in my console.log()?

Thank you .........

ASCBY1
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
state:2

**This is working fine **

  private innerLoop(i,ifArray,counter,cb){
    let tempMod = new Module(null, ifArray[i].id,ifArray[i].type);
    /*FALLS CHCEK BY MODULE*/

    if(ifArray[i].timerID === 0){ //WENN ein Timer ausgeführt iwrd, dann gibt es kein Modul bzw. kein DevType, er muss aber dennoch durch alle Schleifen (ifArray) laufen. Ohne der && this.mod.... würde er bei switch case ein Fehler ausspucken weil es den DevType nicht gibt.
      if(!(this.mod === undefined)){
      //  var tempMod = new Module(ifArray[i].id,ifArray[i].type);
        setTimeout(()=>console.log(tempMod.getState()),1000);
        switch (this.mod.modulesRecievedData.DevType){
           case 0x0b:{
             if(this.mod.checkMultiSwitch(ifArray[i])){
               counter++;
             }
             break;
           }
           case 0x02:{
              console.log("ASCBY1");

              tempMod.getState().then((state)=>{
                if(state == 2) counter++;

                console.log("state:"+state);

                if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
                  this.innerLoop(i,ifArray,counter,cb);
                }else{
                  cb(counter);
                }
              });

              break;
           }
        }
        i++;
      }
    }else if(ifArray[i].timerID > 0){  /*FALLS CHECK BY TIMER*/
      var timerOnState = time[ifArray[i].timerID].timerOnState;
      if(timerOnState == true){
        counter++;
      }
      i++;
      if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
        this.innerLoop(i,ifArray,counter,cb);
      }else{
         console.log("counter3 "+counter);
        cb(counter);
      }
    }
  }

This cause a look

private async innerLoop(i,ifArray,counter,cb){
    let tempMod = new Module(null, ifArray[i].id,ifArray[i].type);
    /*FALLS CHCEK BY MODULE*/

    if(ifArray[i].timerID === 0){ //WENN ein Timer ausgeführt iwrd, dann gibt es kein Modul bzw. kein DevType, er muss aber dennoch durch alle Schleifen (ifArray) laufen. Ohne der && this.mod.... würde er bei switch case ein Fehler ausspucken weil es den DevType nicht gibt.
      if(!(this.mod === undefined)){
      //  var tempMod = new Module(ifArray[i].id,ifArray[i].type);
        setTimeout(()=>console.log(tempMod.getState()),1000);
        switch (this.mod.modulesRecievedData.DevType){
           case 0x0b:{
             if(this.mod.checkMultiSwitch(ifArray[i])){
               counter++;
             }
             break;
           }
           case 0x02:{
              console.log("ASCBY1");
              ///////////////////////////////////
              //////HERE IS THE CHANGE///////////
              ///////////////////////////////////
              let state = await tempMod.getState();

              if(state == 2) counter++;

              console.log("state:"+state);

              if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
                this.innerLoop(i,ifArray,counter,cb);
              }else{
                cb(counter);
              }
              break;
           }
        }
        i++;
      }
    }else if(ifArray[i].timerID > 0){  /*FALLS CHECK BY TIMER*/
      var timerOnState = time[ifArray[i].timerID].timerOnState;
      if(timerOnState == true){
        counter++;
      }
      i++;
      if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
        this.innerLoop(i,ifArray,counter,cb);
      }else{
         console.log("counter3 "+counter);
        cb(counter);
      }
    }
  }

Module class

 getState(){
  let promise = new Promise((resolve)=>{
   this.db.getStateOfModule(this._id,this._type,
    (data)=>{this._state = data[0].state; resolve(data[0].state);}
   );
  });

  return promise;
 }

Body:
Module.getState returns a promise.

The line setTimeout(()=>console.log(tempMod.getState()),1000);
is waiting 1000ms, then console logging the result of tempMod.getState(), which is an unresolved promise.

If you do not want to be getting Promise { <pending> } in the console. You can change it to

setTimeout(() => tempMod.getState().then((result) => {
  console.log(result)
}), 1000);

As for the looping issue. When you are using .then(). The rest of the code after the .then() will immediately run. In particular the i++. Only the code that is inside the then callback will be delayed.

When you changed this to await. the entire function will stop executing until the promise resolves. That means the i++ will not be executed.

I am assuming ifArray.length is 1 and i starts at 0. So when you get to if(i < ifArray.length){ This will be true when using await (as i++ did not execute) which will cause innerLoop to be called again.
The same thing will keep happening as i++ will never be executed.


问:
How to determine MySQL / MariaDB version for Maven dependency?
I'm writing a simple Maven project to access my MySQL / MariaDB database. In order to download the proper database connector jar file, I'm adding the following Maven dependency:

```<code><dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    <scope>provided</scope>
</dependency>
</code>```

I've got that 5.1.47 version above "by chance", based on a previous project which already worked on my computer.

However, when I type mysql -V (capital V) on terminal to check my MySQL/MariaDB version, I get the following:

```<code>>mysql -V
mysql  Ver 15.1 Distrib 10.4.6-MariaDB, for Win64 (AMD64), source revision b8e655ce029a1f182602c9f12c3cc5931226eec2
</code>```

But that 10.4.6 version doesn't mean much to me in terms of determining a proper version to set up my Maven dependency.

What's the procedure to determine MySQL version for Maven dependency based on my local MySQL / MariaDB server?

答:
What's the procedure to determine MySQL version for Maven dependency
  based on my local MySQL / MariaDB server?

You cannot .They are different things. The one specified in maven is the client version while one the you checked with mysql -V is the server version. The JDBC client version does not needed to be exactly matched with the server version.

Instead , the thing that you need to ensure is that the server support client version that you used.

From the official docs,  5.1.47 should support MySQL 5.61, 5.71, 8.0. And from the compatibility matrix of MariaDB  , MariaDB 10.4.6 is comparability with MySQL 5.6 and 5.7 , which mean the JDBC client version that you are using should have no problem. But if it is possible , you can update the client to version 8.0 series , which is the official recommendation and should also work with your existing MariaDB version.

Body:
I'm writing a simple Maven project to access my MySQL / MariaDB database. In order to download the proper database connector jar file, I'm adding the following Maven dependency:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    <scope>provided</scope>
</dependency>

I've got that 5.1.47 version above "by chance", based on a previous project which already worked on my computer.

However, when I type mysql -V (capital V) on terminal to check my MySQL/MariaDB version, I get the following:

>mysql -V
mysql  Ver 15.1 Distrib 10.4.6-MariaDB, for Win64 (AMD64), source revision b8e655ce029a1f182602c9f12c3cc5931226eec2

But that 10.4.6 version doesn't mean much to me in terms of determining a proper version to set up my Maven dependency.

What's the procedure to determine MySQL version for Maven dependency based on my local MySQL / MariaDB server?


问:
use multiple go routines for different operations on mysql
I have a piece of Go code with 3 different functions, insertIntoMysql, updateRowMysql and deleteRowmysql. I check for operation type and run one of these functions as needed.

I want to convert my normal functions into go routines to be able to handle more operations.

But here is the issue:

If I convert into goroutines, I will lose the sequence of operations.

For example, the insert operations are much more frequent than the delete operations and insert operations are being queued in the insert channel while the delete channel is empty it is possible for my code to try to delete a row before it gets inserted (e.g. a row is inserted and the deleted 1 sec later).

Any ideas on how to make sure the sequence of my operations on mysql is the same as the received operations.

here is the code:

```<code>
    go insertIntoMysql(insertChan, fields, db, config.DestinationTable)
    go updatefieldMysql(updateChan, fields, db, config.DestinationTable)
    go deleteFromMysql(deleteChan, fields, db, config.DestinationTable)

    for !opsDone {
        select {
        case op, open := <-mysqlChan:
            if !open {
                opsDone = true
                break
            }

            switch op.Operation {
            case "i":
                //fmt.Println("got insert operation")
                insertChan <- op
                break
            case "u":
                fmt.Println("got update operation")
                updateChan <- op
                break
            case "d":
                fmt.Println("got delete operation")
                deleteChan <- op
                break
            case "c":
                fmt.Println("got command operation")
                //no logic yet
                break
            }

            break
        }
    }
    close(done)
    close(insertChan)
    close(deleteChan)
    close(updateChan)

}
</code>```

答:
As far as I understand the problem, the following can be done as a resolution :

Call Insert, Delete or Update as go routines and they will run concurrently and performing all these operations.

Ensure you have row-level locking in your MySQL DB (I am sure InnoDb provides that)

For your delete and update operations, have an isExist check to check if the row you are updating/deleting exists before deleting and updating the row, this allows for some level of control.

You can implement a retry mechanism in your channel (with jitter preferably) to ensure that even if Delete Operation goes before insert operation, it will fail the exist check and then can be retried(after a second or 0.5 second or some config) and this will ensure insert record is already performed before delete or update operation is retried.

Hope this helps.

Body:
I have a piece of Go code with 3 different functions, insertIntoMysql, updateRowMysql and deleteRowmysql. I check for operation type and run one of these functions as needed.

I want to convert my normal functions into go routines to be able to handle more operations.

But here is the issue:

If I convert into goroutines, I will lose the sequence of operations.

For example, the insert operations are much more frequent than the delete operations and insert operations are being queued in the insert channel while the delete channel is empty it is possible for my code to try to delete a row before it gets inserted (e.g. a row is inserted and the deleted 1 sec later).

Any ideas on how to make sure the sequence of my operations on mysql is the same as the received operations.

here is the code:

    go insertIntoMysql(insertChan, fields, db, config.DestinationTable)
    go updatefieldMysql(updateChan, fields, db, config.DestinationTable)
    go deleteFromMysql(deleteChan, fields, db, config.DestinationTable)

    for !opsDone {
        select {
        case op, open := <-mysqlChan:
            if !open {
                opsDone = true
                break
            }

            switch op.Operation {
            case "i":
                //fmt.Println("got insert operation")
                insertChan <- op
                break
            case "u":
                fmt.Println("got update operation")
                updateChan <- op
                break
            case "d":
                fmt.Println("got delete operation")
                deleteChan <- op
                break
            case "c":
                fmt.Println("got command operation")
                //no logic yet
                break
            }

            break
        }
    }
    close(done)
    close(insertChan)
    close(deleteChan)
    close(updateChan)

}


问:
No next button when importing Maven projects in IntelliJ
I am trying to follow a tutorial on spring boot, first step is to import a maven project in intelliJ, generated by spring initializer, but when I try to do so, I have no next button in the import window, only "finish". And when I click on finish, it does not seem to detect packages. Any idea ?

答:
You may check with these guidelines.

Just type mvn install in the terminal.

or

Settings --> Build,Execution,Deployment --> Maven --> importing

Check the import Maven projects automatically

which will enable imports automatically.


问:
Hiding element space without height constraint

This is a reuseable tableview cell. I want to hide 3. UILabel from the top, both the element and its space when it has no data.

I can't create a height constraint of it because I need to use it multiline depends on the text.

```<code>if release.post.isEmpty {

    cell.label3.isHidden = true

} else {

    cell.label3.isHidden = false

}
</code>```

So how can I hide its space without a height constraint?

答: You can use the stack view and then hide the required objects i.e label or image. Remember to give the proper constraints to the stack view and select the required properties.</p>

Body:
This is a reuseable tableview cell. I want to hide 3. UILabel from the top, both the element and its space when it has no data.

I can't create a height constraint of it because I need to use it multiline depends on the text.

if release.post.isEmpty {

    cell.label3.isHidden = true

} else {

    cell.label3.isHidden = false

}

So how can I hide its space without a height constraint?


答:
How would the one that calls delete know about the row in the first place? From a SQL perspective: if it is not committed, it does not exist. Something calls your code to insert. Your code should return only after the transaction is completed. At which point the caller could start select, update or delete.

For example, in a web server: Only the client that called insert knows of the existence to the record initially. Other clients will only learn of its existence after running select. That select will only return the new record if it was committed in the transaction that inserted it. Now they might decide to upsert or delete.

Many SQL databases take care of proper row locking, which will ensure data integrity during concurrent access. So if you use Go routines to write to the same record, they will become sequential (in any given order) on the DB side. Concurrent reads could still happen.

Please note that net/http already runs a Go routine for every request. And so do most other server front-ends for Go. If you are writing something different altogether, like a custom TCP listener, you could initiate your own Go routine for each request.

Title: use multiple go routines for different operations on mysql


问:
Is this add or subtraction?
I am really confused by this. For example var a = +"3" -"2" is this subtraction or adding? To me this is adding negative value on to number 3.  Can someone please clarify this for me, my brain is starting to hurt.

答:
Subtraction

The first '+' is a unary operator, while '-' is a binary operator.
Therefore the operation is subtraction.

var a = +"3" -"2"
console.log(a)```

Title: Is this add or subtraction?


答:
Taking into consideration operator precedence, the first + (called "unary plus", precedence 17) is turning the "3" string into a number, after which the - (precedence 14) converts the expressions on either side to numbers and subtraction occurs:

```<code>var a = +"3" -"2"
// equivalent to:
var a = (+"3") -"2"
var a = (3) -"2"
// Subtraction casts both sides to numbers before it occurs
// Left side is already a number
var a = 3 -2
var a = 1
</code>```

Title: Is this add or subtraction?

Body: I am really confused by this. For example var a = +"3" -"2" is this subtraction or adding? To me this is adding negative value on to number 3.  Can someone please clarify this for me, my brain is starting to hurt.

Body:
Taking into consideration operator precedence, the first + (called "unary plus", precedence 17) is turning the "3" string into a number, after which the - (precedence 14) converts the expressions on either side to numbers and subtraction occurs:

var a = +"3" -"2"
// equivalent to:
var a = (+"3") -"2"
var a = (3) -"2"
// Subtraction casts both sides to numbers before it occurs
// Left side is already a number
var a = 3 -2
var a = 1


问:
Anti-aliasing in R graphics under Windows (as per Mac)
is there a way to plot anti-aliased graphics from the Windows version of R? As you can see from the two versions below the Mac version of R prints graphics anti aliased....

....whereas while the Windows version anti-aliases text, it does not anti-alias the actual graphic, as can be seen from the riser points, and the grid:

Here is the code by the way:

```<code>library(scatterplot3d)
attach(mtcars)
s3d <-scatterplot3d(wt,disp,mpg, pch=16, highlight.3d=TRUE,
  type="h", main="3D Scatterplot")
fit <- lm(mpg ~ wt+disp)
s3d$plane3d(fit)
</code>```

I need the highest quality possible, for web page publication. I am running Windows 7 and pulling data from RBloomberg, which only works under Windows.

答:
This is likely to depend on details of the rendering engine on each platform, which could be hard to modify. My suggestions (untested, for lack of time and access to Windows):

install the cairoDevice package and use Cairo_png().  According to the documentation:

```<code> This functions the same as any other R graphics device. You may
 use the conventional plot commands and expect essentially the same
 output, except that everything is anti-aliased (similar to other
 vector-based devices like Quartz). Alpha-blending is supported, as
 is enhanced interactivity via ‘getGraphicsEvent’. The device
 should work the same across all supported platforms (Mac, Windows,
 and Linux).
</code>```

Render the PNG at a much higher resolution (or output data from R as PDF) and use ImageMagick (convert) or some other tool to get the  anti-aliased version you need.

Body:
is there a way to plot anti-aliased graphics from the Windows version of R? As you can see from the two versions below the Mac version of R prints graphics anti aliased....

....whereas while the Windows version anti-aliases text, it does not anti-alias the actual graphic, as can be seen from the riser points, and the grid:

Here is the code by the way:

library(scatterplot3d)
attach(mtcars)
s3d <-scatterplot3d(wt,disp,mpg, pch=16, highlight.3d=TRUE,
  type="h", main="3D Scatterplot")
fit <- lm(mpg ~ wt+disp)
s3d$plane3d(fit)

I need the highest quality possible, for web page publication. I am running Windows 7 and pulling data from RBloomberg, which only works under Windows.

Body:
This is likely to depend on details of the rendering engine on each platform, which could be hard to modify. My suggestions (untested, for lack of time and access to Windows):

install the cairoDevice package and use Cairo_png().  According to the documentation:

 This functions the same as any other R graphics device. You may
 use the conventional plot commands and expect essentially the same
 output, except that everything is anti-aliased (similar to other
 vector-based devices like Quartz). Alpha-blending is supported, as
 is enhanced interactivity via ‘getGraphicsEvent’. The device
 should work the same across all supported platforms (Mac, Windows,
 and Linux).

Render the PNG at a much higher resolution (or output data from R as PDF) and use ImageMagick (convert) or some other tool to get the  anti-aliased version you need.


问:
Reset Redux state to undefined or initial state except one state
I have a redux store where I have defined all the application using combineReducers. What I want to achieve is this, I want to reset all of the state to undefined except one state when the user logout.
example below works fine but what if I have more than 8 states, I will end up having long code. Is there way where I can simplify this, perhaps to loop through the appReducers?: </p>

```<code>const appReducer = combineReducers({
        num1,
        num2,
        num3,
        num4,
        ...createForms({})
    });
const rootReducer = (state, action) => {
if (action.type === 'LOGOUT') {
    delete state.num1;
    delete state.num2;
    delete state.num3;
}

return appReducer(state, action) // this will always return num4 state.
}
</code>```

答:
Every time you modify a state in redux, it will return new state object,
So if you want to clear out all the state then simply

```<code>if (action.type === 'RESET') {
  return undefined
}
</code>```

If you want to persist only state with key 'persist'

you can simply return

```<code>if (action.type === 'LOGOUT') {
  return { num4: state.num4 }
}
</code>```

Body:
I have a redux store where I have defined all the application using combineReducers. What I want to achieve is this, I want to reset all of the state to undefined except one state when the user logout.
example below works fine but what if I have more than 8 states, I will end up having long code. Is there way where I can simplify this, perhaps to loop through the appReducers?:

const appReducer = combineReducers({
        num1,
        num2,
        num3,
        num4,
        ...createForms({})
    });
const rootReducer = (state, action) => {
if (action.type === 'LOGOUT') {
    delete state.num1;
    delete state.num2;
    delete state.num3;
}

return appReducer(state, action) // this will always return num4 state.
}

Body:
Every time you modify a state in redux, it will return new state object,
So if you want to clear out all the state then simply

if (action.type === 'RESET') {
  return undefined
}

If you want to persist only state with key 'persist'

you can simply return

if (action.type === 'LOGOUT') {
  return { num4: state.num4 }
}


答:
The + for +"3" is an Unary plus (MDN: Arithmetic operators):

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.

So  +"3" converts the string 3 to the number 3, resulting in 3-"2".

The - in 3 - "2"  is not a unary operator, because it has a value on its left sides, so it is a subtraction

In 3+-"2" the - would be a unary operator,  converting the "2" to a negative number.

Title: Is this add or subtraction?


问:
Remove elements of 2d array whose 1st column values are duplicates (Swift)
This query is a small twist on a commonly asked question.

The goal is to filter a 2d array to remove duplicate element pairs whose first-column values are duplicates. For example:

```<code>[[1, 1, 1,  2, 2,  3, 3, 3, 3], [0.1, 0.15, 0.2,  0.05, 0.1,  0.2, 0.25, 0.3, 0.35]]
     ->    [[1, 2, 3],[0.2, 0.1, 0.35]]
</code>```

Since the second-column values vary, there is obviously some discretion that needs to be applied when filtering: here, the last value of the set of duplicates is chosen.

One of the myriad answers to this related question -- a functional programming solution by Tim MB -- can be adapted to the task:

```<code>// Use FP-style filtering to eliminate repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = rawArray
    .transpose
    .enumerated()
    .filter{ (rawArray[0]).lastIndex(of: $0.1[0]) == $0.0 }
    .map{ $0.1 }
    .transpose
</code>```

However, this solution is rather slow, which is unfortunate because it's elegant.

A faster solution that keeps the FP spirit is to use dictionary hashing:

```<code>// Use array -> dict -> array trick to remove repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = Array( Array(
    rawArray
        .transpose
        .reduce(into: [:], { dict, elements in
            dict[elements[0], default:(0,0)] = elements[1]
        } )
        .map{ ($0.key, $0.value) } )
    .sorted{ $0.0 < $1.0 }
    .map{ [$0.0, $0.1] }
    .transpose) as! Array2D
</code>```

My questions are:

Is this dictionary trick a good idea? Given that it uses floats as keys?

Why is the FP solution slow?  Can it be speeded up?

Are there better alternatives?

答:
Note on terminology: I'll use a to refer to your array, length to refer to its count (a.count), and width to refer to its elements widths (a[0].count).

There are a few things here that are each pretty brutal on your performance.

Transposing

Firstly, each array transposition is O(width * height). Depending on the implementation, it could also be particularly rough on your cache. And you do it twice. Thus, it's an important goal to avoid transposition is possible.

In your case, since you have vectors with only two elements, you can use zip to iterate your two column vectors in tandem. The result a sequence that does so lazily, so no copying happens, and no extra memory or time is used.

Deduplication

The implementation of deduplication that you stumbled on (.filter{ (rawArray[0]).lastIndex(of: $0.1[0]) == $0.0 }) is hot garbage. It's also O(width * height). It's actually worse than approaches that use Array.contains to maintain an array of "already seen" elements. When contains is looking for an element, it can bail-early when it finds a match. lastIndex(of:) always has to go through the entire array, never early-returning because there could always be a later instance of the sought-after element.

Where possible, use an implementation that takes advantage of the Hashability of your elements. Using a Set to track the "already seen" elements allows you to do O(1) contains checks, over array's O(count). I strongly recommend Cœur's implementation.

There's only one catch: that implementation only keeps the first elements, not the last. Luckily enough, that's really easy to fix: just reverse the elements, unique them (keeping the firsts of the reversed elemtents is like keeping the lasts of the original elements), and reverse them back.

My solution:

```<code>extension Sequence {
    /// Returns an array containing, in order, the first instances of
    /// elements of the sequence that compare equally for the keyPath.
    func unique<T: Hashable>(for keyPath: KeyPath<Element, T>) -> [Element] {
        var unique = Set<T>()
        return filter { unique.insert($0[keyPath: keyPath]).inserted }
    }
}

let points = zip(array[0], array[1])
let pointsUniquedByXs = points.reversed() // O(1) for collections
            .unqiue() // O(count)
            .reversed() // O(1) until you need to materalize as a reversed collection
</code>```

Body:
This query is a small twist on a commonly asked question.

The goal is to filter a 2d array to remove duplicate element pairs whose first-column values are duplicates. For example:

[[1, 1, 1,  2, 2,  3, 3, 3, 3], [0.1, 0.15, 0.2,  0.05, 0.1,  0.2, 0.25, 0.3, 0.35]]
     ->    [[1, 2, 3],[0.2, 0.1, 0.35]]

Since the second-column values vary, there is obviously some discretion that needs to be applied when filtering: here, the last value of the set of duplicates is chosen.

One of the myriad answers to this related question -- a functional programming solution by Tim MB -- can be adapted to the task:

// Use FP-style filtering to eliminate repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = rawArray
    .transpose
    .enumerated()
    .filter{ (rawArray[0]).lastIndex(of: $0.1[0]) == $0.0 }
    .map{ $0.1 }
    .transpose

However, this solution is rather slow, which is unfortunate because it's elegant.

A faster solution that keeps the FP spirit is to use dictionary hashing:

// Use array -> dict -> array trick to remove repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = Array( Array(
    rawArray
        .transpose
        .reduce(into: [:], { dict, elements in
            dict[elements[0], default:(0,0)] = elements[1]
        } )
        .map{ ($0.key, $0.value) } )
    .sorted{ $0.0 < $1.0 }
    .map{ [$0.0, $0.1] }
    .transpose) as! Array2D

My questions are:

Is this dictionary trick a good idea? Given that it uses floats as keys?

Why is the FP solution slow?  Can it be speeded up?

Are there better alternatives?

Body:
Note on terminology: I'll use a to refer to your array, length to refer to its count (a.count), and width to refer to its elements widths (a[0].count).

There are a few things here that are each pretty brutal on your performance.

Transposing

Firstly, each array transposition is O(width * height). Depending on the implementation, it could also be particularly rough on your cache. And you do it twice. Thus, it's an important goal to avoid transposition is possible.

In your case, since you have vectors with only two elements, you can use zip to iterate your two column vectors in tandem. The result a sequence that does so lazily, so no copying happens, and no extra memory or time is used.

Deduplication

The implementation of deduplication that you stumbled on (.filter{ (rawArray[0]).lastIndex(of: $0.1[0]) == $0.0 }) is hot garbage. It's also O(width * height). It's actually worse than approaches that use Array.contains to maintain an array of "already seen" elements. When contains is looking for an element, it can bail-early when it finds a match. lastIndex(of:) always has to go through the entire array, never early-returning because there could always be a later instance of the sought-after element.

Where possible, use an implementation that takes advantage of the Hashability of your elements. Using a Set to track the "already seen" elements allows you to do O(1) contains checks, over array's O(count). I strongly recommend Cœur's implementation.

There's only one catch: that implementation only keeps the first elements, not the last. Luckily enough, that's really easy to fix: just reverse the elements, unique them (keeping the firsts of the reversed elemtents is like keeping the lasts of the original elements), and reverse them back.

My solution:

extension Sequence {
    /// Returns an array containing, in order, the first instances of
    /// elements of the sequence that compare equally for the keyPath.
    func unique<T: Hashable>(for keyPath: KeyPath<Element, T>) -> [Element] {
        var unique = Set<T>()
        return filter { unique.insert($0[keyPath: keyPath]).inserted }
    }
}

let points = zip(array[0], array[1])
let pointsUniquedByXs = points.reversed() // O(1) for collections
            .unqiue() // O(count)
            .reversed() // O(1) until you need to materalize as a reversed collection


问:
Customize Xamarin.Forms.Datepicker to pick and visualize multiple Dates
i'm kinda new to the whole wpf/xamarin UI thing and want to start my first mobile app.
So, like the title contains already the topic of this question, i would like to use the standard Xamarin.Forms Datepicker to let the user pick multiple Dates.

I guess it will be pretty easy to submit on the Event for picking a date and put this into an array for the selected Dates.

But how can i visualize all the selected Dates in the Datepicker Dialog? Is there any possability to do this with this Control?

Thanks :)

答: So you want display multiple dates that you previously selected? I dont think that is possible with a Xamarin date picker. The Xamarin date picker only contains one date at a time  as seen in the docs. You could make your custom datePicker but you would have to do that for every platform. The way I would do it is update a another display property every time you select a date via a date picker. Something like a clickable label or something similar.</p>


问:
How to convert a string of date and time in words to numbers?
I have the following string: January 1, 2020 /  12:04 AM / a month ago. How do I convert this into 1/1/2020 0:04:00? The code should ignore the a month ago. How do I do this?

答:
using strptime you can do it and below is the sample,i was using in my code

```<code>datetime.datetime.strptime(
...     "April 18, 2019, 09:09:09", "%B %d, %Y, %H:%M:%S"
</code>```

Body:
using strptime you can do it and below is the sample,i was using in my code

datetime.datetime.strptime(
...     "April 18, 2019, 09:09:09", "%B %d, %Y, %H:%M:%S"


问:
Spring Boot w/ JSP - Not finding CSS files
This is a spring boot app using jsp
I've tried many solutions, but I can't seem to get CSS integrated with my JSP files. My JSP files are under /WEB-INF/jsp and my css files are in /resources/static/css.

^ The first one doesn't work, but the second one with the link works.

Application.properties file:

```<code>#
# MVC Properties
#
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
server.servlet.context-path=/tfhk
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
</code>```

Project structure:
link to project structure

答:
Try this in your view:

```<code><link href="/css/main.css" rel="stylesheet">
</code>```

Also somewhere in your config do this (in spring security context if using it):

```<code>private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
        "classpath:/META-INF/resources/", "classpath:/resources/",
        "classpath:/static/", "classpath:/public/"
};

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**")
            .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}
</code>```

Body:
This is a spring boot app using jsp
I've tried many solutions, but I can't seem to get CSS integrated with my JSP files. My JSP files are under /WEB-INF/jsp and my css files are in /resources/static/css.

^ The first one doesn't work, but the second one with the link works.

Application.properties file:

#
# MVC Properties
#
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
server.servlet.context-path=/tfhk
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

Project structure:
link to project structure

Body:
Try this in your view:

<link href="/css/main.css" rel="stylesheet">

Also somewhere in your config do this (in spring security context if using it):

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
        "classpath:/META-INF/resources/", "classpath:/resources/",
        "classpath:/static/", "classpath:/public/"
};

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**")
            .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}


问:
JSX array.map undefined boolean data
i tried to display & map my objects in a table row, but my boolean datas will return as undefined and i can't even convert them into strings, whats the solution?

Look at user.isenable and user.isonline in mapping ...

this is what i tried ...

```<code>import { component, Fragment } from 'react'

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

    this.state = {
      users: []
    };
  }
  componentDidMount() {
    const url = "http://localhost:4000/api/user";
    // AXIOS REQUEST
    axios.get(url).then(res => {
      this.setState({ users: res.data });
      console.log(this.state.users);
    });
  }

  render() {
    const users = this.state;
    console.log(this.state.users.isenbale);
    return (
      <table id="users">
        <tr>
          <th>is Enable</th>
          <th>is Online</th>
        </tr>

        {this.state.users.map(user => {
          return (
            <tr key={user.nationalcode}>
              <td>{user.isEnable.toString()}</td>
              <td>{user.isOnline.toString()}</td>
            </tr>
          );
        })}
      </table>
    );
  }
}
</code>```

console logs of res.data & this.state.users are the same.

(5) [{…}, {…}, {…}, {…}, {…}]
0: {nationalcode: 134556778, stockcode: "md3456", firstname: "ali", lastname: "khodabakhashi", isenable: true, …}
1: {nationalcode: 1334853905, stockcode: "md4f5789", firstname: "saeed", lastname: "mohammad", isenable: true, …}
2: {nationalcode: 11313, stockcode: "31313", firstname: "1313", lastname: "1313", isenable: null, …}
3: {nationalcode: 4151515, stockcode: "151", firstname: "5131", lastname: "3114", isenable: null, …}
4: {nationalcode: 123456789, stockcode: "3131", firstname: "31", lastname: "3131", isenable: null, …}
length: 5
__proto__: Array(0)
```

答:
In the data, you're receiving isenable is all lowercase but in the code, you're using it as isEnable, javascript variable names are case sensitive so the engine treat them as two different things.

Change the code to user.isenable and it should work

Title: JSX array.map undefined boolean data

Body:
i tried to display & map my objects in a table row, but my boolean datas will return as undefined and i can't even convert them into strings, whats the solution?

Look at user.isenable and user.isonline in mapping ...

this is what i tried ...

import { component, Fragment } from 'react'

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

    this.state = {
      users: []
    };
  }
  componentDidMount() {
    const url = "http://localhost:4000/api/user";
    // AXIOS REQUEST
    axios.get(url).then(res => {
      this.setState({ users: res.data });
      console.log(this.state.users);
    });
  }

  render() {
    const users = this.state;
    console.log(this.state.users.isenbale);
    return (

          is Enable
          is Online

        {this.state.users.map(user => {
          return (

              {user.isEnable.toString()}
              {user.isOnline.toString()}

          );
        })}

    );
  }
}

console logs of res.data & this.state.users are the same.

(5) [{…}, {…}, {…}, {…}, {…}]
0: {nationalcode: 134556778, stockcode: "md3456", firstname: "ali", lastname: "khodabakhashi", isenable: true, …}
1: {nationalcode: 1334853905, stockcode: "md4f5789", firstname: "saeed", lastname: "mohammad", isenable: true, …}
2: {nationalcode: 11313, stockcode: "31313", firstname: "1313", lastname: "1313", isenable: null, …}
3: {nationalcode: 4151515, stockcode: "151", firstname: "5131", lastname: "3114", isenable: null, …}
4: {nationalcode: 123456789, stockcode: "3131", firstname: "31", lastname: "3131", isenable: null, …}
length: 5
__proto__: Array(0)


问:
how to use a struct field with a double pointer variable (without a support variable)?
I have this struct in c

```<code>struct node{
    int info;
    struct node* link;
};
</code>```

this procedure:

```<code>void example(struct node** head){
    struct node* tmp;
    tmp=*head;
    tmp->info=0;
    *head=tmp;
}
</code>```

and call the procedure in the main with

```<code>example(&head);
</code>```

so to modify head->info I need a support variable,there is another way without a support variable?

答:
Use this:

```<code>void example(struct node** head){
    (*head)->info=100;
}
</code>```

It'll do the same as your example function.
By dereferencing struct node** we get struct node*, then we can simply access it's member by using -> arrow operator.

Body:
I have this struct in c

struct node{
    int info;
    struct node* link;
};

this procedure:

void example(struct node** head){
    struct node* tmp;
    tmp=*head;
    tmp->info=0;
    *head=tmp;
}

and call the procedure in the main with

example(&head);

so to modify head->info I need a support variable,there is another way without a support variable?

Body:
Use this:

void example(struct node** head){
    (*head)->info=100;
}

It'll do the same as your example function.
By dereferencing struct node** we get struct node*, then we can simply access it's member by using -> arrow operator.


问:
Check, if list is a sublist of another list
I'd like to write a function that checks if one list is a sublist of another list. I wrote this, but it is not working, but I need something like this, I guess. Thanks for help.</p>

```<code>subList :: Eq a => [a] -> [a] -> Bool
subList _ []    = False
subList [] _    = True
subList (x:xs) (y:ys) =
     x == y    = subList xs ys
     otherwise = subList (x:xs) ys
</code>```

答:
You could use the function intersect like this:

intersect [list1] [list2] == [list1]

```<code>*Test> intersect [] [] == []
True
*Test> intersect [1] [] == [1]
False
*Test> intersect [2,4,6,4] [9,5,4,2,6,3,3] == [2,4,6,4]
True
*Test> intersect [1,2,3] [3,2,5,4] == [1,2,3]
False

</code>```

You will have to import Data.List for this.

Body:
I'd like to write a function that checks if one list is a sublist of another list. I wrote this, but it is not working, but I need something like this, I guess. Thanks for help.

subList :: Eq a => [a] -> [a] -> Bool
subList _ []    = False
subList [] _    = True
subList (x:xs) (y:ys) =
     x == y    = subList xs ys
     otherwise = subList (x:xs) ys

Body:
You could use the function intersect like this:

intersect [list1] [list2] == [list1]

*Test> intersect [] [] == []
True
*Test> intersect [1] [] == [1]
False
*Test> intersect [2,4,6,4] [9,5,4,2,6,3,3] == [2,4,6,4]
True
*Test> intersect [1,2,3] [3,2,5,4] == [1,2,3]
False

You will have to import Data.List for this.


问:
Uncaught Error: Unexpected directive 'NavComponent' imported by the module 'AppModule'. Please add a @NgModule annotation
I've a custom component (nav) inside.

When I use it , webpack compilation ends successfully but chrome throws the following error:

Uncaught Error: Unexpected directive 'NavComponent' imported by the module 'AppModule'. Please add a @NgModule annotation.

Here is my AppModule:

>

```<code> import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { NavComponent } from './nav/nav.component';

@NgModule({
  declarations: [AppComponent ],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, NavComponent],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
</code>```

答:
If your NavComponent is a @Component or a @Directive, you need to add it into the declarations, instead of imports

```<code>...
declarations: [ AppComponent, NavComponent ],
...
</code>```

Body:
I've a custom component (nav) inside.

When I use it , webpack compilation ends successfully but chrome throws the following error:

Uncaught Error: Unexpected directive 'NavComponent' imported by the module 'AppModule'. Please add a @NgModule annotation.

Here is my AppModule:

>

 import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { NavComponent } from './nav/nav.component';

@NgModule({
  declarations: [AppComponent ],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, NavComponent],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Body:
If your NavComponent is a @Component or a @Directive, you need to add it into the declarations, instead of imports

...
declarations: [ AppComponent, NavComponent ],
...


问:
SQL Update with AVG of Joined Tables
I'm trying to update the supplier lead time in a table by calculating the difference between date of order and stock receipt date....

```<code>UPDATE cr_accs
SET    cr_accs.leadtime = Avg(Datediff(day, purchord_hdr.orderdate,
                                     stock_trans.transdate))
FROM   stock_items
       INNER JOIN stock_trans
               ON stock_trans.stockcode = stock_items.stockcode
       INNER JOIN purchord_hdr
               ON purchord_hdr.seqno = stock_trans.ref1
WHERE   cr_accs.accno = purchord_hdr.accno
       AND stock_trans.location = 1
       AND stock_trans.ref2 = 'RECEIPT'
       AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
       AND stock_items.isactive = 'Y'
       AND stock_items.bincode NOT IN ( 'OIO', 'CON' )
</code>```

However I'm getting an error

An aggregate may not appear in the set list of an UPDATE statement

I've seen other solutions where you would change the query to:

```<code>UPDATE cr_accs
SET    cr_accs.leadtime = h.calc_lead_time
FROM   (SELECT AVG(DATEDIFF(day, purchord_hdr.orderdate, stock_trans.transdate)) AS calc_lead_time
        FROM stock_items
       INNER JOIN stock_trans
               ON stock_trans.stockcode = stock_items.stockcode
       INNER JOIN purchord_hdr
               ON purchord_hdr.seqno = stock_trans.ref1
       INNER JOIN cr_accs
               ON cr_accs.accno = purchord_hdr.accno
WHERE   cr_accs.accno = purchord_hdr.accno
       AND stock_trans.location = 1
       AND stock_trans.ref2 = 'RECEIPT'
       AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
       AND stock_items.isactive = 'Y'
       AND stock_items.bincode NOT IN ( 'OIO', 'CON' ) ) h
</code>```

However this is not the solution for me as it doesn't define that the lead time is unique to each supplier...
It may be helpful to point out that each supplier is identified by cr_accs.accno

Any ideas please?

答:
You can also do what you want using a correlated subquery, which might be what you were trying to do:

```<code>UPDATE cr_accs
    SET cr_accs.leadtime =
         (SELECT AVG(DATEDIFF(day, p.orderdate, st.transdate)) AS calc_lead_time
          FROM stock_items si JOIN
               stock_trans st
               ON st.stockcode = si.stockcode JOIN
               purchord_hdr p
               ON p.seqno = st.ref1
          WHERE cr_accs.accno = p.accno  AND
                st.location = 1 AND
                st.ref2 = 'RECEIPT' AND
                p.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()), -730) AND
                si.isactive = 'Y' AND
                si.bincode NOT IN ( 'OIO', 'CON' )
         );
</code>```

I introduced table aliases so the query is easier to write and to read.

SQL Server also gives you the ability to express this using APPLY:

```<code>UPDATE a
    SET a.leadtime = p.calc_lead_time
    FROM cr_accs a CROSS APPLY
         (SELECT AVG(DATEDIFF(day, p.orderdate, st.transdate)) AS calc_lead_time
          FROM stock_items si JOIN
               stock_trans st
               ON st.stockcode = si.stockcode JOIN
               purchord_hdr p
               ON p.seqno = st.ref1
          WHERE a.accno = p.accno  AND
                st.location = 1 AND
                st.ref2 = 'RECEIPT' AND
                p.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()), -730) AND
                si.isactive = 'Y' AND
                si.bincode NOT IN ( 'OIO', 'CON' )
         ) p;
</code>```

Title: SQL Update with AVG of Joined Tables

Body:
I'm trying to update the supplier lead time in a table by calculating the difference between date of order and stock receipt date....

UPDATE cr_accs
SET    cr_accs.leadtime = Avg(Datediff(day, purchord_hdr.orderdate,
                                     stock_trans.transdate))
FROM   stock_items
       INNER JOIN stock_trans
               ON stock_trans.stockcode = stock_items.stockcode
       INNER JOIN purchord_hdr
               ON purchord_hdr.seqno = stock_trans.ref1
WHERE   cr_accs.accno = purchord_hdr.accno
       AND stock_trans.location = 1
       AND stock_trans.ref2 = 'RECEIPT'
       AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
       AND stock_items.isactive = 'Y'
       AND stock_items.bincode NOT IN ( 'OIO', 'CON' )

However I'm getting an error

An aggregate may not appear in the set list of an UPDATE statement

I've seen other solutions where you would change the query to:

UPDATE cr_accs
SET    cr_accs.leadtime = h.calc_lead_time
FROM   (SELECT AVG(DATEDIFF(day, purchord_hdr.orderdate, stock_trans.transdate)) AS calc_lead_time
        FROM stock_items
       INNER JOIN stock_trans
               ON stock_trans.stockcode = stock_items.stockcode
       INNER JOIN purchord_hdr
               ON purchord_hdr.seqno = stock_trans.ref1
       INNER JOIN cr_accs
               ON cr_accs.accno = purchord_hdr.accno
WHERE   cr_accs.accno = purchord_hdr.accno
       AND stock_trans.location = 1
       AND stock_trans.ref2 = 'RECEIPT'
       AND purchord_hdr.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()),-730)
       AND stock_items.isactive = 'Y'
       AND stock_items.bincode NOT IN ( 'OIO', 'CON' ) ) h

However this is not the solution for me as it doesn't define that the lead time is unique to each supplier...
It may be helpful to point out that each supplier is identified by cr_accs.accno

Any ideas please?

Body:
You can also do what you want using a correlated subquery, which might be what you were trying to do:

UPDATE cr_accs
    SET cr_accs.leadtime =
         (SELECT AVG(DATEDIFF(day, p.orderdate, st.transdate)) AS calc_lead_time
          FROM stock_items si JOIN
               stock_trans st
               ON st.stockcode = si.stockcode JOIN
               purchord_hdr p
               ON p.seqno = st.ref1
          WHERE cr_accs.accno = p.accno  AND
                st.location = 1 AND
                st.ref2 = 'RECEIPT' AND
                p.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()), -730) AND
                si.isactive = 'Y' AND
                si.bincode NOT IN ( 'OIO', 'CON' )
         );

I introduced table aliases so the query is easier to write and to read.

SQL Server also gives you the ability to express this using APPLY:

UPDATE a
    SET a.leadtime = p.calc_lead_time
    FROM cr_accs a CROSS APPLY
         (SELECT AVG(DATEDIFF(day, p.orderdate, st.transdate)) AS calc_lead_time
          FROM stock_items si JOIN
               stock_trans st
               ON st.stockcode = si.stockcode JOIN
               purchord_hdr p
               ON p.seqno = st.ref1
          WHERE a.accno = p.accno  AND
                st.location = 1 AND
                st.ref2 = 'RECEIPT' AND
                p.orderdate >= Dateadd(day, Datediff(day, 0, Getdate()), -730) AND
                si.isactive = 'Y' AND
                si.bincode NOT IN ( 'OIO', 'CON' )
         ) p;


问:
Common layouts, different resources
I need your suggestion for my application. I have written an application two month ago, and now have been asked to write similar application. I've got an idea to change only resources. I'd like to change my application to use different resources but common layouts.

Have you any ideas how to use different resources without replaceing them and renaming as thay are used in application.

答: Check your old project as a Android library (in project properties in eclipse), create new project, copy manifest to the new project, add old project as a Android library, put new/modified resources to the new. Resources will be overriden.</p>

Title: Common layouts, different resources


问:
Read extra javascript code from file on the fly
I'm looking to create an app in nodejs that is extensible with a separate javascript file.
The idea is that I create an app that has a GUI in which you can type commands but the commands are defined in a separate file not contained in the source structure so that a user can create their own commands, making it essentially extensible. For anyone who used it, this is the same as the Ubiquity addon for firefox from back in 2008.

I have done this already in java using Rhino but Rhino can't handle async calls and I want the commands to be able to call APIs.

My question is if within a node js app, you can have a line that does something to the effect of

```<code>let externalObject = read(file.js);    // contains the definition for SomeObject;
let foo = new externalObject.SomeObject();
foo.someFunctionFromFileJs();
</code>```

答:
You can use require() inside a loader function and load your extension. However this would have to be on the server side. The function could be triggered by some API endpoint, would load the module on the server, and perhaps other end points would allow for interaction with it.

index.js

//...

const loadExtension = ()=>{
  const extension = require('./extension');
  return extension;
}

myExtension = loadExtension();

console.log(myExtension.add(2, 5)); //output: 7
console.log(myExtension.multiply(2, 5)); //output: 10
```

<p>extension.js</p>

<pre class="lang-js prettyprint-override"><code>const add = (a, b) => a+b;
const multiply = (a, b) => a*b;

module.exports = {add, multiply}
</code>```

Body:
I'm looking to create an app in nodejs that is extensible with a separate javascript file.
The idea is that I create an app that has a GUI in which you can type commands but the commands are defined in a separate file not contained in the source structure so that a user can create their own commands, making it essentially extensible. For anyone who used it, this is the same as the Ubiquity addon for firefox from back in 2008.

I have done this already in java using Rhino but Rhino can't handle async calls and I want the commands to be able to call APIs.

My question is if within a node js app, you can have a line that does something to the effect of

let externalObject = read(file.js);    // contains the definition for SomeObject;
let foo = new externalObject.SomeObject();
foo.someFunctionFromFileJs();

Body:
You can use require() inside a loader function and load your extension. However this would have to be on the server side. The function could be triggered by some API endpoint, would load the module on the server, and perhaps other end points would allow for interaction with it.

index.js

//...

const loadExtension = ()=>{
  const extension = require('./extension');
  return extension;
}

myExtension = loadExtension();

console.log(myExtension.add(2, 5)); //output: 7
console.log(myExtension.multiply(2, 5)); //output: 10

extension.js

const add = (a, b) => a+b;
const multiply = (a, b) => a*b;

module.exports = {add, multiply}


问:
how to get total count of 2nd/3rd inner list of object using Linq or lambda expression in c#
I have a class structure like this

```<code>class ABC
{
    public List<A> LA { get; set; }
}
class A
{
    public List<B> LB { get; set; }
}

class B
{
    public List<C> LC { get; set; }
}

class C
{
    public int x { get; set; }
    public int y { get; set; }
    public int z { get; set; }
}
</code>```

Here, as you can see that class "abc" can have multiple objects/elements of class "A" and each element of class "A" can have multiple elements of class "B" and each element of class "B" can have multiple elements of class "C". Now I want to calculate total No of elements of class "C" and store that total count in a int type variable by using Linq or lambda expression and without foreach loop.

答: abc.LA.SelectMany(la => la.LB).SelectMany(lb => lb.LC).Count();</p>

Body:
I have a class structure like this

class ABC
{
    public List LA { get; set; }
}
class A
{
    public List LB { get; set; }
}

class B
{
    public List<C> LC { get; set; }
}

class C
{
    public int x { get; set; }
    public int y { get; set; }
    public int z { get; set; }
}

Here, as you can see that class "abc" can have multiple objects/elements of class "A" and each element of class "A" can have multiple elements of class "B" and each element of class "B" can have multiple elements of class "C". Now I want to calculate total No of elements of class "C" and store that total count in a int type variable by using Linq or lambda expression and without foreach loop.