问:
Filtering results in MySQL in join result
I am beginner programmer. I have small problem with my MySQL Queries.
This is my MySQL data: https://pastebin.com/69PcBSVH

I have this tables:

```<code>CREATE TABLE `dishes` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1',
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `dish_values` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `dishes_id` bigint(20) UNSIGNED NOT NULL,
  `food_ingredient_id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `quantity` decimal(9,2) NOT NULL DEFAULT '0.00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `food_ingredients` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(120) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `garbage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `energy_value` decimal(9,2) NOT NULL DEFAULT '0.00',
  `protein` decimal(9,2) NOT NULL DEFAULT '0.00',
  `fat` decimal(9,2) NOT NULL DEFAULT '0.00',
  `available_carbohydrates` decimal(9,2) NOT NULL DEFAULT '0.00',
  `roughage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `url_address` varchar(160) COLLATE utf8mb4_unicode_ci NOT NULL,
  `allergen` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen1` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen2` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen3` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `available_in_demo` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
</code>```

My base is a base of dishes and ingredients needed to prepare a dish.

I need to display all dishes that are not allergens (food_ingredients.allergen = 0).

```<code>Table dishes = given dishes
Table dish_values = ingredients that are assigned to a given dish
Food_ingredients table = ingredients of the dish.
</code>```

Dishes that are allergens have a value of 1 in the allergen column and those that are not allergens 0.

I make query to show my dish (without allergens):

```<code>SELECT
  dishes.id, dishes.company_id, dishes.name, dishes.description, dishes.enable
FROM `dishes`  join dish_values on dish_values.dishes_id = dishes.id
      join food_ingredients on food_ingredients.id = dish_values.food_ingredient_id
WHERE food_ingredients.allergen = 0
GROUP BY dishes.id
</code>```

But it's not working correct.

As a result, I have both dishes that contain allergens and those that do not have them.

How can I repair it?

答: As allergen is a char column, you need quotes around the 0. Alternatively, you can change the column to an int.</p>

Body:
I am beginner programmer. I have small problem with my MySQL Queries.
This is my MySQL data: https://pastebin.com/69PcBSVH

I have this tables:

CREATE TABLE `dishes` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1',
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `dish_values` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `dishes_id` bigint(20) UNSIGNED NOT NULL,
  `food_ingredient_id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `quantity` decimal(9,2) NOT NULL DEFAULT '0.00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `food_ingredients` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `company_id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(120) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `garbage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `energy_value` decimal(9,2) NOT NULL DEFAULT '0.00',
  `protein` decimal(9,2) NOT NULL DEFAULT '0.00',
  `fat` decimal(9,2) NOT NULL DEFAULT '0.00',
  `available_carbohydrates` decimal(9,2) NOT NULL DEFAULT '0.00',
  `roughage` decimal(9,2) NOT NULL DEFAULT '0.00',
  `description` longtext COLLATE utf8mb4_unicode_ci,
  `url_address` varchar(160) COLLATE utf8mb4_unicode_ci NOT NULL,
  `allergen` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen1` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen2` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `allergen3` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `available_in_demo` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0',
  `enable` char(1) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

My base is a base of dishes and ingredients needed to prepare a dish.

I need to display all dishes that are not allergens (food_ingredients.allergen = 0).

Table dishes = given dishes
Table dish_values = ingredients that are assigned to a given dish
Food_ingredients table = ingredients of the dish.

Dishes that are allergens have a value of 1 in the allergen column and those that are not allergens 0.

I make query to show my dish (without allergens):

SELECT
  dishes.id, dishes.company_id, dishes.name, dishes.description, dishes.enable
FROM `dishes`  join dish_values on dish_values.dishes_id = dishes.id
      join food_ingredients on food_ingredients.id = dish_values.food_ingredient_id
WHERE food_ingredients.allergen = 0
GROUP BY dishes.id

But it's not working correct.

As a result, I have both dishes that contain allergens and those that do not have them.

How can I repair it?


来源: stackexchange

问:
VueJS: $router.push not working with query parameters
In my NuxtJS(v. 2.10.2) application, I have a URL like below where pid is a post's id.

/post?pid=5e4844e34202d6075e593062

This URL works fine and loads the post as per the value passed to the pid query parameter. However, user can add new post by clicking Add Post button on the application bar that opens a dialog. Once the user clicks add, a request to back-end server is made to save the request. And once successful, user is redirected to the new post using vue router push like below

```<code>.then(data => {
  if (data) {
    this.$router.push({ path: `/post?pid=${data.id}` });
  }
})
</code>```

The problem is, user is not redirected to the new post, only the query parameter pid is updated. I suspect VueJS does not acknowledge this as a different URL and hence does nothing.

How to fix this?

Update: As an alternative tried the syntax below but getting the same behavior.

```<code>this.$router.push({ path: "post", query: { pid: data.id } });
</code>```

答:
Say you have a component post.vue which is mapped with /post URL.

Now if you redirect the user to /post?pid=13, the post.vue component won't mount again if it's already mounted ie. when you are already at /post or /post?pid=12.

[1] In this case, you can put a watch on the route to know if the route has been changed.

```<code>watch: {
 '$route.path': {
   handler (oldUrl, newUrl) {
     let PID = this.$route.query.pid
     // fetch data for this PID from the server.
     // ...
  }
 }
}
</code>```

OR

[2] If the component post.vue is mapped with some route say /post.

You can also use the lifecycle -> beforeRouteUpdate provided by vue-router

```<code>beforeRouteUpdate (to, from, next) {
  let PID = to.query.pid
  // fetch data for this PID from the server.
  // ...
  next()
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my NuxtJS(v. 2.10.2) application, I have a URL like below where pid is a post's id.

/post?pid=5e4844e34202d6075e593062

This URL works fine and loads the post as per the value passed to the pid query parameter. However, user can add new post by clicking Add Post button on the application bar that opens a dialog. Once the user clicks add, a request to back-end server is made to save the request. And once successful, user is redirected to the new post using vue router push like below

.then(data => {
  if (data) {
    this.$router.push({ path: `/post?pid=${data.id}` });
  }
})

The problem is, user is not redirected to the new post, only the query parameter pid is updated. I suspect VueJS does not acknowledge this as a different URL and hence does nothing.

How to fix this?

Update: As an alternative tried the syntax below but getting the same behavior.

this.$router.push({ path: "post", query: { pid: data.id } });

Body:
Say you have a component post.vue which is mapped with /post URL.

Now if you redirect the user to /post?pid=13, the post.vue component won't mount again if it's already mounted ie. when you are already at /post or /post?pid=12.

[1] In this case, you can put a watch on the route to know if the route has been changed.

watch: {
 '$route.path': {
   handler (oldUrl, newUrl) {
     let PID = this.$route.query.pid
     // fetch data for this PID from the server.
     // ...
  }
 }
}

OR

[2] If the component post.vue is mapped with some route say /post.

You can also use the lifecycle -> beforeRouteUpdate provided by vue-router

beforeRouteUpdate (to, from, next) {
  let PID = to.query.pid
  // fetch data for this PID from the server.
  // ...
  next()
}


问:
How to get a Discord Bot to return the formatted name of a Channel?
I'm attempting to create a Discord bot using Discord.py for a server I'm in, I'm trying to get the bot to mention (blue links) other channels in the server. I thought it would have been using something like discord.TextChannel.name, discord.TextChannel.mention. But neither of those work, they only return something along the lines of "<property object at 0x03CE8B68>".

Code:

```<code>import discord

from discord.ext import commands

bot = commands.Bot(command_prefix='$')
client = discord.Client()
token = <token>

@bot.command()
async def test(ctx, arg):
    await ctx.send(arg)

@bot.command()
async def mentionChan(ctx):
    await ctx.send(ctx.guild.get_channel('662129928463974411').mention)

client.run(token)
</code>```

答:
```<code>@botclient.command()
async def mentionChan(ctx):
    await ctx.send(ctx.guild.get_channel(CHANNEL_ID).mention)
</code>```

This will mention the channel with the given id. You can get the id of a channel by right clicking a channel and selecting "Copy ID". This is only possible after you have turned on developer mode at the appearance tab in User Settings.

ctx.guild.text_channels will give you a list of all the text channels in the server if you want to use that.

Body:
I'm attempting to create a Discord bot using Discord.py for a server I'm in, I'm trying to get the bot to mention (blue links) other channels in the server. I thought it would have been using something like discord.TextChannel.name, discord.TextChannel.mention. But neither of those work, they only return something along the lines of "<property object at 0x03CE8B68>".

Code:

import discord

from discord.ext import commands

bot = commands.Bot(command_prefix='$')
client = discord.Client()
token = <token>

@bot.command()
async def test(ctx, arg):
    await ctx.send(arg)

@bot.command()
async def mentionChan(ctx):
    await ctx.send(ctx.guild.get_channel('662129928463974411').mention)

client.run(token)

Body:
@botclient.command()
async def mentionChan(ctx):
    await ctx.send(ctx.guild.get_channel(CHANNEL_ID).mention)

This will mention the channel with the given id. You can get the id of a channel by right clicking a channel and selecting "Copy ID". This is only possible after you have turned on developer mode at the appearance tab in User Settings.

ctx.guild.text_channels will give you a list of all the text channels in the server if you want to use that.


问:
How do I print colored output with Python 3?
I have a simple print statement:

```<code>print('hello friends')
</code>```

I would like the output to be blue in the terminal. How can I accomplish this with Python3?

答:
Since Python is interpreted and run in C, it is possible to set colors without a module.

You can define a class for colors like this:

```<code>class color:
   PURPLE = '\033[1;35;48m'
   CYAN = '\033[1;36;48m'
   BOLD = '\033[1;37;48m'
   BLUE = '\033[1;34;48m'
   GREEN = '\033[1;32;48m'
   YELLOW = '\033[1;33;48m'
   RED = '\033[1;31;48m'
   BLACK = '\033[1;30;48m'
   UNDERLINE = '\033[4;37;48m'
   END = '\033[1;37;0m'
</code>```

When writing code, you can simply write:

print(color.BLUE + "hello friends" + color.END)

Note that the color you choose will have to be capitalized like your class definition, and that these are color choices that I personally find satisfying.  For a fuller array of color choices and, indeed, background choices as well, please see: https://gist.github.com/RabaDabaDoba/145049536f815903c79944599c6f952a.

This is code for C, but can easily be adapted to Python once you realize how the code is written.

Take BLUE for example, since that is what you are wanting to display.

```<code>BLUE = '033[1;37;48m'
</code>```

\033 tells Python to break and pay attention to the following formatting.

1 informs the code to be bold.  (I prefer 1 to 0 because it pops more.)

34 is the actual color code.  It chooses blue.

48m is the background color.  48m is the same shade as the console window, so it seems there is no background.

ContentLicense: CC BY-SA 3.0

Body:
I have a simple print statement:

print('hello friends')

I would like the output to be blue in the terminal. How can I accomplish this with Python3?

Body:
Since Python is interpreted and run in C, it is possible to set colors without a module.

You can define a class for colors like this:

class color:
   PURPLE = '\033[1;35;48m'
   CYAN = '\033[1;36;48m'
   BOLD = '\033[1;37;48m'
   BLUE = '\033[1;34;48m'
   GREEN = '\033[1;32;48m'
   YELLOW = '\033[1;33;48m'
   RED = '\033[1;31;48m'
   BLACK = '\033[1;30;48m'
   UNDERLINE = '\033[4;37;48m'
   END = '\033[1;37;0m'

When writing code, you can simply write:

print(color.BLUE + "hello friends" + color.END)

Note that the color you choose will have to be capitalized like your class definition, and that these are color choices that I personally find satisfying.  For a fuller array of color choices and, indeed, background choices as well, please see: https://gist.github.com/RabaDabaDoba/145049536f815903c79944599c6f952a.

This is code for C, but can easily be adapted to Python once you realize how the code is written.

Take BLUE for example, since that is what you are wanting to display.

BLUE = '033[1;37;48m'

\033 tells Python to break and pay attention to the following formatting.

1 informs the code to be bold.  (I prefer 1 to 0 because it pops more.)

34 is the actual color code.  It chooses blue.

48m is the background color.  48m is the same shade as the console window, so it seems there is no background.


问:
A function to check for hill or valley in a given list, without usage of Numpy or zip?

A list of numbers is identified as 'hill' if it has an ascending sequence followed by a descending sequence. Similarly, it'll be 'valley hill' if it consists of a descending sequence followed by an ascending one. Each of the sequences should be of length of at least two.

For example, a list [1,2,3,5,4] will be a hill or a list [5,4,1,2,3] will be a valley.

I'm trying to write a function, without the usage of either numpy arrays or zip function that returns a true if it identifies a hill or valley and false if it doesn't.

The code I've come up with is:

```<code>def hillovalley(n):
  if len(n)<=2:
    return False
  c = n[0]<n[1]
  x=0
  for i in range(len(n)-1):
    if c!=(n[i]<n[i+1]):
      c=n[i]<n[i+1]
      x=x+1
    if x==1:
      return True
    else:
      return False
</code>```

However, this code would fail if the input is something like [1,2,3,5,4,3,2,1] or [9,5,4,-1,-2,3,7].

Thank you for your help!

答:
```<code>def ascending(l):
    if len(l) <= 1:
        return(True)
    else:
        return(l[0] < l[1] and ascending(l[1:]))

def descending(l):
    if len(l) <= 1:
        return(True)
    else:
        return(l[0] > l[1] and descending(l[1:]))

def hill(l):
    for i in range(1,len(l)-1):
        if ascending(l[:i+1]) and descending(l[i:]):
            return(True)
    return(False)

def valley(l):
    for i in range(1,len(l)-1):
        if descending(l[:i+1]) and ascending(l[i:]):
            return(True)
    return(False)

def hillvalley(l):
    return(hill(l) or valley(l))
</code>```

Body:
A list of numbers is identified as 'hill' if it has an ascending sequence followed by a descending sequence. Similarly, it'll be 'valley hill' if it consists of a descending sequence followed by an ascending one. Each of the sequences should be of length of at least two.

For example, a list [1,2,3,5,4] will be a hill or a list [5,4,1,2,3] will be a valley.

I'm trying to write a function, without the usage of either numpy arrays or zip function that returns a true if it identifies a hill or valley and false if it doesn't.

The code I've come up with is:

def hillovalley(n):
  if len(n)<=2:
    return False
  c = n[0]<n[1]
  x=0
  for i in range(len(n)-1):
    if c!=(n[i]<n[i+1]):
      c=n[i]<n[i+1]
      x=x+1
    if x==1:
      return True
    else:
      return False

However, this code would fail if the input is something like [1,2,3,5,4,3,2,1] or [9,5,4,-1,-2,3,7].

Thank you for your help!


问:
How do I get the directory where a Bash script is located from within the script itself?
How do I get the path of the directory in which a Bash script is located, inside that script?

I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

```<code>$ ./application
</code>```

答:
```<code>#!/bin/sh
PRG="$0"

# need this for relative symlinks
while [ -h "$PRG" ] ; do
   PRG=`readlink "$PRG"`
done

scriptdir=`dirname "$PRG"`
</code>```

OwnerDisplayName: Jim Robert

Body:
How do I get the path of the directory in which a Bash script is located, inside that script?

I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

$ ./application

OwnerDisplayName: Monkeyboy

ContentLicense: CC BY-SA 2.5


问:
How do I call a function immediately upon an iPhone app resuming from a saved state?

User has my app open.

They hit the home button, resulting in my app closing and going into a "saved state".

Users uses his device for other things.

User opens up my app again, resuming from where he left off.

How, in my code, do I detect that the user has resumed from the saved state? Is there a specific iOS4 multitasking NSNotification that I can attach to?

答:
You can use the app delegate methods to get you up and running if the system terminates your app is while it is in the background.

If your app isn't terminated, then observing the UIApplicationDidEnterBackgroundNotification notification will be helpful.  It will allow you to do any viewController specific state saving and cleanup.  You can use this to do quick clean up.  i.e. freeze dry any lazily created instance variables in order to make your app as small as possible in terms of memory foot print while it is in the background state.

Registering for this notification allows you to restore state UIApplicationWillEnterForegroundNotification

Make sure you are careful to remove your object as an observer though.


答:
This is pretty similar to other answers, only hold two decimals.

let foo = [{
  a: 10,
  b: 10.10,
  c: 'dfdf',
  d: true
},
{
  a: 20,
  b: 20.20,
  c: 'dfdf',
  d: true
}]

function obj_avg(data) {
  let ret = data.reduce((acc, record) => {
    Object.keys(record).forEach(field => {
      if (typeof record[field] === 'number') {
        if (!acc[field]) {
          acc[field] = []
        }
        acc[field].push(record[field])
      }
    })
    return acc
  }, {})

  Object.keys(ret).forEach(key => {
    let avg = ret[key].reduce((acc, cur) => acc + cur, 0) / ret[key].length
    ret[key] = Math.round((avg + Number.EPSILON) * 100) / 100
  })
  return ret
}

console.log(obj_avg(foo))```

Title: How to get the average of the total values from json file using nodejs


问:
Newtonsoft JArray LINQ - Group By array with identical values
I'm new to LINQ and having a problem I can't seem to solve. I have a JSON array/object like this:

```<code>[
  {
    "items": [
      "pepperoni"
    ]
  },
  {
    "items": [
      "sausage"
    ]
  },
  {
    "items": [
      "sausage"
    ]
  },
  {
    "items": [
      "pepperoni",
      "mushrooms",
      "olives"
    ]
  },
  {
    "items": [
      "peppers",
      "spinach"
    ]
  },
  {
    "items": [
      "peppers",
      "spinach"
    ]
  },
  {
    "items": [
      "peppers",
      "spinach"
    ]
  }
]
</code>```

I need to GROUP BY the items combinations and produce results like this:

peppers,spinach - 3

sausage - 2

pepperoni - 1

pepperoni,mushrooms,olives - 1

This is the Linq query I have (clearly doesn't work).

```<code>JArray jsonData= JsonConvert.DeserializeObject<JArray>(jsonString);

var queryResult =
from c in jsonData.Select(i => i["items"]).Values<string>()
group c by c
into g
orderby g.Count() descending
select new { Items = g.Key, Count = g.Count() };
</code>```

I find examples for every scenario except this one.

答:
You need to merge list items into string then Group items:

```<code>var queryResult = from c in jsonData.Select(i => String.Join(",", i["items"]).OrderBy(o => o))
                  group c by c
                  into g
                  orderby g.Count() descending
                  select new { Items = g.Key, Count = g.Count() };
</code>```

It will give you desired output:

```<code>peppers,spinach-3
sausage-2
pepperoni-1
pepperoni,mushrooms,olives-1
</code>```

Body:
I'm new to LINQ and having a problem I can't seem to solve. I have a JSON array/object like this:

[
  {
    "items": [
      "pepperoni"
    ]
  },
  {
    "items": [
      "sausage"
    ]
  },
  {
    "items": [
      "sausage"
    ]
  },
  {
    "items": [
      "pepperoni",
      "mushrooms",
      "olives"
    ]
  },
  {
    "items": [
      "peppers",
      "spinach"
    ]
  },
  {
    "items": [
      "peppers",
      "spinach"
    ]
  },
  {
    "items": [
      "peppers",
      "spinach"
    ]
  }
]

I need to GROUP BY the items combinations and produce results like this:

peppers,spinach - 3

sausage - 2

pepperoni - 1

pepperoni,mushrooms,olives - 1

This is the Linq query I have (clearly doesn't work).

JArray jsonData= JsonConvert.DeserializeObject<JArray>(jsonString);

var queryResult =
from c in jsonData.Select(i => i["items"]).Values<string>()
group c by c
into g
orderby g.Count() descending
select new { Items = g.Key, Count = g.Count() };

I find examples for every scenario except this one.

Body:
You need to merge list items into string then Group items:

var queryResult = from c in jsonData.Select(i => String.Join(",", i["items"]).OrderBy(o => o))
                  group c by c
                  into g
                  orderby g.Count() descending
                  select new { Items = g.Key, Count = g.Count() };

It will give you desired output:

peppers,spinach-3
sausage-2
pepperoni-1
pepperoni,mushrooms,olives-1


问:
REACT Jest - Test suite failed to run
I have created sample react project and added JEST, enzyme dependencies to test my component. But getting below error while running test suite:
ERROR:
 Cannot find module 'components/Add' from 'App.js'

```<code>However, Jest was able to find:
    'components/Add.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

However, Jest was able to find:
    './App.css'
    './App.js'
    './App.test.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

  1 | import React from 'react';
> 2 | import Add from 'components/Add';
    | ^
  3 |
  4 |
  5 | function App() {

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
  at Object.<anonymous> (src/App.js:2:1)
</code>```

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        4.035s
Ran all test suites.

Can anyone please help to resolve this issue, will be happy to share more details.

答:
Have you tried to use a relative import instead?

```<code>import Add from './components/Add';
</code>```

Let me know if it helps :)

Title: REACT Jest - Test suite failed to run

Body:
I have created sample react project and added JEST, enzyme dependencies to test my component. But getting below error while running test suite:
ERROR:
 Cannot find module 'components/Add' from 'App.js'

However, Jest was able to find:
    'components/Add.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

However, Jest was able to find:
    './App.css'
    './App.js'
    './App.test.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

  1 | import React from 'react';
> 2 | import Add from 'components/Add';
    | ^
  3 |
  4 |
  5 | function App() {

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
  at Object.<anonymous> (src/App.js:2:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        4.035s
Ran all test suites.

Can anyone please help to resolve this issue, will be happy to share more details.

Body:
Have you tried to use a relative import instead?

import Add from './components/Add';

Let me know if it helps :)


问:
How to insert index using if statement when using map function in react?
I am using redux and I am working on receiving data about membership information from action and processing it from components.

And try to process the data to a table.

I took data from user action and created a table through map functions... The incoming data contains

Data received as action ....

```<code>[{create_date : "2020-02-16T03:00:00Z", id:"test"},
{create_date : "2020-02-16T01:00:00Z", id:"test1"},
{create_date : "2020-02-14T03:00:00Z", id:"test2"},
{create_date : "2020-02-14T01:00:00Z", id:"test3"},
{create_date : "2020-02-14T00:00:01Z", id:"test4"},
{create_date : "2020-02-13T03:00:00Z", id:"test5"},
...]

</code>```

As you can see, only create_date id is included.

I would like to order them by date and number them in order by next day after day.

For example, would like to print like this.

```<code>index    create_date           id
2        2020-02-16T03:00:00Z  test
1        2020-02-16T01:00:00Z  test1

3        2020-02-14T03:00:00Z  test2
2        2020-02-14T01:00:00Z  test3
1        2020-02-14T00:00:01Z  test4

1        2020-02-13T03:00:00Z  test5
</code>```

How to insert index using if statement when using map function in react??

Mycode

```<code>    render() {
        const {user_list} = this.props;
        console.log(user_list);
        return (
            <div className="animated fadeIn">
                <Row>
                    <Col xl={12}>
                        <Card>
                            <CardHeader>
                                <i className="fa fa-align-justify"></i>userlist
                            </CardHeader>
                            <CardBody>
                                <Search searchUser={this.searchUser}/>
                                <Table responsive hover>
                                    <thead>
                                    <tr><th scope="col">Index</th>
                                        <th scope="col">create_time</th>
                                        <th scope="col">id/name</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {user_list.length > 0 && user_list.map((item, index) => (
                                        <tr key={item.id.toString()}>
                                            <td>{index}</td> //<<Does this change by date index.. if statement?
                                            <td className={'datetime'}>
                                                {item.hasOwnProperty('create_date') &&
                                                    <div>
                                                        {moment(item.create_date).format('YYYY-MM-DD')}<br/>
                                                        {moment(item.create_date).format('HH:mm')}
                                                    </div>
                                                }
                                            </td>
                                            <td scope="row">
                                                    {item.displayName}
                                            </td>

                                        </tr>
                                    ))}
                                    </tbody>
                                </Table>
                            </CardBody>
                        </Card>
                    </Col>
                </Row>

            </div>
        )
    }

....

</code>```

答:
Elaborate on comments of @James. I just changed a little bit.

You can group them first by date. And then flat it to a list you want. Plain javascirpt version:

```<code>let data = [{create_date : "2020-02-16T03:00:00Z", id:"test"},
{create_date : "2020-02-16T01:00:00Z", id:"test1"},
{create_date : "2020-02-14T03:00:00Z", id:"test2"},
{create_date : "2020-02-14T01:00:00Z", id:"test3"},
{create_date : "2020-02-14T00:00:01Z", id:"test4"},
{create_date : "2020-02-13T03:00:00Z", id:"test5"},
]

let groups = {}
for (let e of data.reverse()) {
  let date = e.create_date.slice(0, 10)
  if (groups[date]) {
    let group = groups[date];
    group.push({ index: group.length + 1, ...e });
  } else {
    groups[date] = [{ index: 1, ...e }]
  }
}

const dates = Object.keys(groups).reverse()
const flatten = []
for (let date of dates) {
  flatten.push(...(groups[date].reverse()))
}

console.log(flatten)

</code>```

flatten should be logged as:

```<code>[ { index: 2, create_date: '2020-02-16T03:00:00Z', id: 'test' },
  { index: 1, create_date: '2020-02-16T01:00:00Z', id: 'test1' },
  { index: 3, create_date: '2020-02-14T03:00:00Z', id: 'test2' },
  { index: 2, create_date: '2020-02-14T01:00:00Z', id: 'test3' },
  { index: 1, create_date: '2020-02-14T00:00:01Z', id: 'test4' },
  { index: 1, create_date: '2020-02-13T03:00:00Z', id: 'test5' } ]
</code>```

You should be able to render that directly in a map. Though I think it's better to store the flatten list as state or in redux store so that it won't do the transformation on every rerender.

Body:
I am using redux and I am working on receiving data about membership information from action and processing it from components.

And try to process the data to a table.

I took data from user action and created a table through map functions... The incoming data contains

Data received as action ....

[{create_date : "2020-02-16T03:00:00Z", id:"test"},
{create_date : "2020-02-16T01:00:00Z", id:"test1"},
{create_date : "2020-02-14T03:00:00Z", id:"test2"},
{create_date : "2020-02-14T01:00:00Z", id:"test3"},
{create_date : "2020-02-14T00:00:01Z", id:"test4"},
{create_date : "2020-02-13T03:00:00Z", id:"test5"},
...]

As you can see, only create_date id is included.

I would like to order them by date and number them in order by next day after day.

For example, would like to print like this.

index    create_date           id
2        2020-02-16T03:00:00Z  test
1        2020-02-16T01:00:00Z  test1

3        2020-02-14T03:00:00Z  test2
2        2020-02-14T01:00:00Z  test3
1        2020-02-14T00:00:01Z  test4

1        2020-02-13T03:00:00Z  test5

How to insert index using if statement when using map function in react??

Mycode

    render() {
        const {user_list} = this.props;
        console.log(user_list);
        return (

                <Row>
                    <Col xl={12}>
                        <Card>
                            <CardHeader>
                                userlist
                            </CardHeader>
                            <CardBody>
                                <Search searchUser={this.searchUser}/>

Index
                                        create_time
                                        id/name

                                    {user_list.length > 0 && user_list.map((item, index) => (

                                            {index}	 //<<Does this change by date index.. if statement?

                                                {item.hasOwnProperty('create_date') &&

                                                        {moment(item.create_date).format('YYYY-MM-DD')}

                                                        {moment(item.create_date).format('HH:mm')}

                                                }

                                                    {item.displayName}

                                    ))}

                            </CardBody>
                        </Card>
                    </Col>
                </Row>

        )
    }

....

Body:
Elaborate on comments of @James. I just changed a little bit.

You can group them first by date. And then flat it to a list you want. Plain javascirpt version:

let data = [{create_date : "2020-02-16T03:00:00Z", id:"test"},
{create_date : "2020-02-16T01:00:00Z", id:"test1"},
{create_date : "2020-02-14T03:00:00Z", id:"test2"},
{create_date : "2020-02-14T01:00:00Z", id:"test3"},
{create_date : "2020-02-14T00:00:01Z", id:"test4"},
{create_date : "2020-02-13T03:00:00Z", id:"test5"},
]

let groups = {}
for (let e of data.reverse()) {
  let date = e.create_date.slice(0, 10)
  if (groups[date]) {
    let group = groups[date];
    group.push({ index: group.length + 1, ...e });
  } else {
    groups[date] = [{ index: 1, ...e }]
  }
}

const dates = Object.keys(groups).reverse()
const flatten = []
for (let date of dates) {
  flatten.push(...(groups[date].reverse()))
}

console.log(flatten)

flatten should be logged as:

[ { index: 2, create_date: '2020-02-16T03:00:00Z', id: 'test' },
  { index: 1, create_date: '2020-02-16T01:00:00Z', id: 'test1' },
  { index: 3, create_date: '2020-02-14T03:00:00Z', id: 'test2' },
  { index: 2, create_date: '2020-02-14T01:00:00Z', id: 'test3' },
  { index: 1, create_date: '2020-02-14T00:00:01Z', id: 'test4' },
  { index: 1, create_date: '2020-02-13T03:00:00Z', id: 'test5' } ]

You should be able to render that directly in a map. Though I think it's better to store the flatten list as state or in redux store so that it won't do the transformation on every rerender.


问:
fetch data from mongoDB, setstate and pass props to child component is not working
beneath is my code

```<code>class Root extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentDidMount() {
    this.getDataFromDb();
  }

  getDataFromDb = () => {
    fetch('http://localhost:3001/getData')
      .then((data) => data.json())
      .then((res) => {
        if(res !== this.state.data) {
          this.setState({ data: res}, () => console.log(this.state.data));
        }
      });
  };

  render() {
    return(
      <div>
        <IRPage data={this.state.data}></IRPage>
      </div>
    )
  }
}

class IRPage extends Component {

  print = () => {
    console.log(this.props.data);
  }

  render() {
    return (
      <div className="container m-5">
        <button onClick={this.print}></button>
      </div>
    )
  }
}
</code>```

callback function of setstate in getDatafromDB in Root component work successfully,
but when it pass to child component IRPage, and click print button, result is undefined.
Thank you for helping

答:
You code seems to work as you intended it. </p>

<p>I tried to replicate what you wrote and it's working. checkout this jsfiddle </p>

```<code>class Root extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentDidMount() {
    this.getDataFromDb();
  }

  getDataFromDb = () => {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then((data) => data.json())
      .then((res) => {
        if(res !== this.state.data) {
          this.setState({ data: res}, () => console.log(this.state.data));
        }
      });
  };

  render() {
    return(
      <div>
        <IRPage data={this.state.data}></IRPage>
      </div>
    )
  }
}

// here I have added React to import Components from, because I don't know what import statement is
class IRPage extends React.Component {

  print = () => {
    console.log(this.props.data);
  }

  render() {
    return (
      <div className="container m-5">
        <button onClick={this.print}></button>
      </div>
    )
  }
}

ReactDOM.render(<Root />, document.querySelector("#app"))
</code>```

Body:
beneath is my code

class Root extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentDidMount() {
    this.getDataFromDb();
  }

  getDataFromDb = () => {
    fetch('http://localhost:3001/getData')
      .then((data) => data.json())
      .then((res) => {
        if(res !== this.state.data) {
          this.setState({ data: res}, () => console.log(this.state.data));
        }
      });
  };

  render() {
    return(

        <IRPage data={this.state.data}></IRPage>

    )
  }
}

class IRPage extends Component {

  print = () => {
    console.log(this.props.data);
  }

  render() {
    return (

        <button onClick={this.print}></button>

    )
  }
}

callback function of setstate in getDatafromDB in Root component work successfully,
but when it pass to child component IRPage, and click print button, result is undefined.
Thank you for helping

Body:
You code seems to work as you intended it.

I tried to replicate what you wrote and it's working. checkout this jsfiddle

class Root extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentDidMount() {
    this.getDataFromDb();
  }

  getDataFromDb = () => {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then((data) => data.json())
      .then((res) => {
        if(res !== this.state.data) {
          this.setState({ data: res}, () => console.log(this.state.data));
        }
      });
  };

  render() {
    return(
      <div>
        <IRPage data={this.state.data}></IRPage>
      </div>
    )
  }
}

// here I have added React to import Components from, because I don't know what import statement is
class IRPage extends React.Component {

  print = () => {
    console.log(this.props.data);
  }

  render() {
    return (
      <div className="container m-5">
        <button onClick={this.print}></button>
      </div>
    )
  }
}

ReactDOM.render(<Root />, document.querySelector("#app"))


问:
Unable to schedule a TimerTask a long time in advance
Heavily edited/updated:
I am trying to schedule a task a long time in advance. I believe it is doing something to the process because it thinks it is not going to do anything else.
I should have used HOUR_OF_DAY for 24 hour time instead of hour, but still doesn't work correctly.
New code:

public class OtherMainClass {
    private static Timer timer;
    private static Calendar cal;

    public static void main(String[] args) throws InterruptedException {
        cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        cal.set(Calendar.HOUR_OF_DAY, 8);
        cal.set(Calendar.MINUTE, 0);
        System.out.println("Changed to: " + cal.getTime());
        timer = new Timer();
        System.out.println("current time is: " + Calendar.getInstance().getTime());
        System.out.println("Scheduled for: " + cal.getTime());
        timer.schedule(new MyTimerTask(), cal.getTime());
        timer.schedule(new MyTimerCheckTask(), 0, 1000*60*10);
    }

    public static class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            System.out.println("in run at: " + Calendar.getInstance().getTime());
        }
    }

    public static class MyTimerCheckTask extends TimerTask {

        @Override
        public void run() {
            System.out.println("cal at: " + Calendar.getInstance().getTime() + " is: " + OtherMainClass.cal.getTime());
        }
    }
}
```

<p>Commandline output (following "is:" is the calendar object passed into the schedule.):</p>

```Changed to: Fri Feb 14 08:00:41 GMT 2020
current time is: Thu Feb 13 23:25:41 GMT 2020
Scheduled for: Fri Feb 14 08:00:41 GMT 2020
cal at: Thu Feb 13 23:25:41 GMT 2020 is: Fri Feb 14 08:00:41 GMT 2020
cal at: Thu Feb 13 23:35:41 GMT 2020 is: Fri Feb 14 08:00:41 GMT 2020
cal at: Thu Feb 13 23:45:41 GMT 2020 is: Fri Feb 14 08:00:41 GMT 2020
cal at: Thu Feb 13 23:55:41 GMT 2020 is: Fri Feb 14 08:00:41 GMT 2020
cal at: Fri Feb 14 09:39:27 GMT 2020 is: Fri Feb 14 08:00:41 GMT 2020
in run at: Fri Feb 14 09:39:27 GMT 2020
```

<p>Note the very interesting run at the end, as well as the other task running. I clicked on commandline, which turned it into select mode, then control-c to exit that, then a few seconds later, it did both Tasks. (It should have run long before I clicked on commandline.
Java version from <code>java -version</code></p>

```openjdk version "1.8.0_242"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_242-b08)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.242-b08, mixed mode)
```

OS: Windows 10

答:
I ran a test stating Friday around 11:30. I changed the windows sleep settings set to 1 hour (Start -> Settings -> System  -> Power & sleep). Since Friday 8:00 had passed, I changed the day to Saturday. I also changed the repeated interval to every half hour 3*1000*60*10, since I wanted to limit the lines of output. I ran the code in 5 different Command Prompts and started them at around 11:30 Friday:

No QuickEdit Mode. The program was running and I had to Crtl-c to stop it. No printout to the screen after sleep initiated. (Admittedly I didn't wait to see if it would print the 8 o'clock message after some time, because it seemed pointless.)

QuickEdit Mode. Did not click inside the screen. Same as 1.

QuickEdit Mode. Clicked inside the screen and immediately cancelled with Ctrl^c. The prompt top bar changed to "Select Command Prompt.." and went back to "Command Prompt..". Same as 1.

QuickEdit Mode. Clicked inside the screen and highlighted some test. The prompt top bar changed to "Select Command Prompt". There was absolutely no printout after that until I pressed Ctrl^c and the printouts were as if I had just started the program and it just printed the below. However I did not just exit the program, and it resumes the 30 min interval printout, as you can see from the below:

QuickEdit Mode. Clicked inside the screen (that's all). The prompt top bar changed to "Select Command Prompt". Same as 4.

This is the result of 4 and 5, that only started printing after i exited "Select Command Prompt"-mode at 9:43 on Saturday:

```<code>Changed to: Sat Feb 15 08:00:16 CET 2020
current time is: Sat Feb 15 09:49:13 CET 2020
Scheduled for: Sat Feb 15 08:00:16 CET 2020
in run at: Sat Feb 15 09:49:13 CET 2020
cal at: Sat Feb 15 09:49:13 CET 2020 is: Sat Feb 15 08:00:16 CET 2020
cal at: Sat Feb 15 10:19:13 CET 2020 is: Sat Feb 15 08:00:16 CET 2020
cal at: Sat Feb 15 10:49:13 CET 2020 is: Sat Feb 15 08:00:16 CET 2020
cal at: Sat Feb 15 11:19:13 CET 2020 is: Sat Feb 15 08:00:16 CET 2020
...
</code>```

I ran another test with the windows sleep setting set to "Never". Since Saturday 8:00 had passed, I changed the day to Sunday. I again ran the code in 5 different Command Prompts and started them at around 15:30 Saturday:

No QuickEdit Mode. Worked without issues. See below.

QuickEdit Mode. Did not click inside the screen. Same as 1.

QuickEdit Mode. Clicked inside the screen and immediately cancelled with Ctrl^c. The prompt top bar changed to "Select Command Prompt.." and went back to "Command Prompt..". Same as 1.

QuickEdit Mode. Clicked inside the screen and highlighted some test. The prompt top bar changed to "Select Command Prompt". There was absolutely no printout after that. Until I pressed Ctrl^c and the printout was identical to the test above.

QuickEdit Mode. Clicked inside the screen (that's all). The prompt top bar changed to "Select Command Prompt". There was absolutely no printout after that.

Result:

```<code>Changed to: Sun Feb 16 08:00:31 CET 2020
current time is: Sat Feb 15 15:35:31 CET 2020
Scheduled for: Sun Feb 16 08:00:31 CET 2020
cal at: Sat Feb 15 15:35:31 CET 2020 is: Sun Feb 16 08:00:31 CET 2020
cal at: Sat Feb 15 16:05:31 CET 2020 is: Sun Feb 16 08:00:31 CET 2020
..snip..
cal at: Sun Feb 16 07:05:31 CET 2020 is: Sun Feb 16 08:00:31 CET 2020
cal at: Sun Feb 16 07:35:31 CET 2020 is: Sun Feb 16 08:00:31 CET 2020
in run at: Sun Feb 16 08:00:31 CET 2020
cal at: Sun Feb 16 08:05:31 CET 2020 is: Sun Feb 16 08:00:31 CET 2020
</code>```

The answer by Shaun Rowan to Why is my command prompt freezing on Windows 10? you provided mentions:

whenever you click on a command window in windows 10, it immediately halts the application process when it attempts to write to the console

So it doesn't seem to be a bug in the Command Prompt either, rather it's a feature.

As per Will my Window 10 apps continue to update or download on sleep or hibernation mode? by A. User:

Sleep is a power-saving state that allows a computer to quickly resume full-power operation (typically within several seconds) when you want to start working again. Putting your computer into the sleep state is like pausing a DVD player—the computer immediately stops what it’s doing and is ready to start again when you want to resume working.

If you're very interested in Windows sleep modes TechRepublic has an article on Investigating Sleep states in Windows 10 describes the 6 stages of sleep, from when the (processor clocks are stopped) -> (the processor shuts off to save power) -> (other chips on the motherboard may shut off)

Conclusion:

If you want your java program to keep executing, ensure your Command Prompt window is not in "Select Command Prompt.."-mode and also ensure that your computer does not enter sleep mode, as either of these will halt execution of the program.

Body:
Heavily edited/updated:
I am trying to schedule a task a long time in advance. I believe it is doing something to the process because it thinks it is not going to do anything else.
I should have used HOUR_OF_DAY for 24 hour time instead of hour, but still doesn't work correctly.
New code:

public class OtherMainClass {
    private static Timer timer;
    private static Calendar cal;

    public static void main(String[] args) throws InterruptedException {
        cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
        cal.set(Calendar.HOUR_OF_DAY, 8);
        cal.set(Calendar.MINUTE, 0);
        System.out.println("Changed to: " + cal.getTime());
        timer = new Timer();
        System.out.println("current time is: " + Calendar.getInstance().getTime());
        System.out.println("Scheduled for: " + cal.getTime());
        timer.schedule(new MyTimerTask(), cal.getTime());
        timer.schedule(new MyTimerCheckTask(), 0, 1000*60*10);
    }

    public static class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            System.out.println("in run at: " + Calendar.getInstance().getTime());
        }
    }

    public static class MyTimerCheckTask extends TimerTask {

        @Override
        public void run() {
            System.out.println("cal at: " + Calendar.getInstance().getTime() + " is: " + OtherMainClass.cal.getTime());
        }
    }
}

Commandline output (following "is:" is the calendar object passed into the schedule.):

Changed to: Fri Feb 14 08:00:41 GMT 2020
current time is: Thu Feb 13 23:25:41 GMT 2020
Scheduled for: Fri Feb 14 08:00:41 GMT 2020
cal at: Thu Feb 13 23:25:41 GMT 2020 is: Fri Feb 14 08:00:41 GMT 2020
cal at: Thu Feb 13 23:35:41 GMT 2020 is: Fri Feb 14 08:00:41 GMT 2020
cal at: Thu Feb 13 23:45:41 GMT 2020 is: Fri Feb 14 08:00:41 GMT 2020
cal at: Thu Feb 13 23:55:41 GMT 2020 is: Fri Feb 14 08:00:41 GMT 2020
cal at: Fri Feb 14 09:39:27 GMT 2020 is: Fri Feb 14 08:00:41 GMT 2020
in run at: Fri Feb 14 09:39:27 GMT 2020

Note the very interesting run at the end, as well as the other task running. I clicked on commandline, which turned it into select mode, then control-c to exit that, then a few seconds later, it did both Tasks. (It should have run long before I clicked on commandline.
Java version from java -version

openjdk version "1.8.0_242"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_242-b08)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.242-b08, mixed mode)

OS: Windows 10

Body:
I ran a test stating Friday around 11:30. I changed the windows sleep settings set to 1 hour (Start -> Settings -> System  -> Power & sleep). Since Friday 8:00 had passed, I changed the day to Saturday. I also changed the repeated interval to every half hour 3*1000*60*10, since I wanted to limit the lines of output. I ran the code in 5 different Command Prompts and started them at around 11:30 Friday:

No QuickEdit Mode. The program was running and I had to Crtl-c to stop it. No printout to the screen after sleep initiated. (Admittedly I didn't wait to see if it would print the 8 o'clock message after some time, because it seemed pointless.)

QuickEdit Mode. Did not click inside the screen. Same as 1.

QuickEdit Mode. Clicked inside the screen and immediately cancelled with Ctrl^c. The prompt top bar changed to "Select Command Prompt.." and went back to "Command Prompt..". Same as 1.

QuickEdit Mode. Clicked inside the screen and highlighted some test. The prompt top bar changed to "Select Command Prompt". There was absolutely no printout after that until I pressed Ctrl^c and the printouts were as if I had just started the program and it just printed the below. However I did not just exit the program, and it resumes the 30 min interval printout, as you can see from the below:

QuickEdit Mode. Clicked inside the screen (that's all). The prompt top bar changed to "Select Command Prompt". Same as 4.

This is the result of 4 and 5, that only started printing after i exited "Select Command Prompt"-mode at 9:43 on Saturday:

Changed to: Sat Feb 15 08:00:16 CET 2020
current time is: Sat Feb 15 09:49:13 CET 2020
Scheduled for: Sat Feb 15 08:00:16 CET 2020
in run at: Sat Feb 15 09:49:13 CET 2020
cal at: Sat Feb 15 09:49:13 CET 2020 is: Sat Feb 15 08:00:16 CET 2020
cal at: Sat Feb 15 10:19:13 CET 2020 is: Sat Feb 15 08:00:16 CET 2020
cal at: Sat Feb 15 10:49:13 CET 2020 is: Sat Feb 15 08:00:16 CET 2020
cal at: Sat Feb 15 11:19:13 CET 2020 is: Sat Feb 15 08:00:16 CET 2020
...

I ran another test with the windows sleep setting set to "Never". Since Saturday 8:00 had passed, I changed the day to Sunday. I again ran the code in 5 different Command Prompts and started them at around 15:30 Saturday:

No QuickEdit Mode. Worked without issues. See below.

QuickEdit Mode. Did not click inside the screen. Same as 1.

QuickEdit Mode. Clicked inside the screen and immediately cancelled with Ctrl^c. The prompt top bar changed to "Select Command Prompt.." and went back to "Command Prompt..". Same as 1.

QuickEdit Mode. Clicked inside the screen and highlighted some test. The prompt top bar changed to "Select Command Prompt". There was absolutely no printout after that. Until I pressed Ctrl^c and the printout was identical to the test above.

QuickEdit Mode. Clicked inside the screen (that's all). The prompt top bar changed to "Select Command Prompt". There was absolutely no printout after that.

Result:

Changed to: Sun Feb 16 08:00:31 CET 2020
current time is: Sat Feb 15 15:35:31 CET 2020
Scheduled for: Sun Feb 16 08:00:31 CET 2020
cal at: Sat Feb 15 15:35:31 CET 2020 is: Sun Feb 16 08:00:31 CET 2020
cal at: Sat Feb 15 16:05:31 CET 2020 is: Sun Feb 16 08:00:31 CET 2020
..snip..
cal at: Sun Feb 16 07:05:31 CET 2020 is: Sun Feb 16 08:00:31 CET 2020
cal at: Sun Feb 16 07:35:31 CET 2020 is: Sun Feb 16 08:00:31 CET 2020
in run at: Sun Feb 16 08:00:31 CET 2020
cal at: Sun Feb 16 08:05:31 CET 2020 is: Sun Feb 16 08:00:31 CET 2020

The answer by Shaun Rowan to Why is my command prompt freezing on Windows 10? you provided mentions:

whenever you click on a command window in windows 10, it immediately halts the application process when it attempts to write to the console

So it doesn't seem to be a bug in the Command Prompt either, rather it's a feature.

As per Will my Window 10 apps continue to update or download on sleep or hibernation mode? by A. User:

Sleep is a power-saving state that allows a computer to quickly resume full-power operation (typically within several seconds) when you want to start working again. Putting your computer into the sleep state is like pausing a DVD player—the computer immediately stops what it’s doing and is ready to start again when you want to resume working.

If you're very interested in Windows sleep modes TechRepublic has an article on Investigating Sleep states in Windows 10 describes the 6 stages of sleep, from when the (processor clocks are stopped) -> (the processor shuts off to save power) -> (other chips on the motherboard may shut off)

Conclusion:

If you want your java program to keep executing, ensure your Command Prompt window is not in "Select Command Prompt.."-mode and also ensure that your computer does not enter sleep mode, as either of these will halt execution of the program.


问:
javascript cannot find a method which exists
I have a pretty simple function declared in my JavaScript file, which is just supposed to return whether or not the validation has begun:

```<code>window.Validator = function(){
    this._started = false;
    this.started = function(){
        return this._started;
    };
}

Validator.started();
</code>```

However, when I call Validator.started(), even though it's literally directly after the declaration, it will throw the error:

Uncaught TypeError: Validator.started is not a function

Really scratching my head with this one and have no idea why it isn't working.

答:
this is a context. Or simply, it is an object which is on the left of dot. For example:

```<code>let v = new Validator();
v.started(); // v will be 'this' in your method
</code>```

Your code:

```<code>Validator.started();
</code>```

It means, that started() is a static method of Validator (method of exactly function Validator()). You have to write code as I write above. Or:

```<code>window.Validator = function() {};
Validator._started = false;
Validator.started = function() {
    return this._started;
};
console.log(Validator.started());
</code>```

Here _started is a static property and started() is a static method of Validator().

Body:
I have a pretty simple function declared in my JavaScript file, which is just supposed to return whether or not the validation has begun:

window.Validator = function(){
    this._started = false;
    this.started = function(){
        return this._started;
    };
}

Validator.started();

However, when I call Validator.started(), even though it's literally directly after the declaration, it will throw the error:

Uncaught TypeError: Validator.started is not a function

Really scratching my head with this one and have no idea why it isn't working.

Body:
this is a context. Or simply, it is an object which is on the left of dot. For example:

let v = new Validator();
v.started(); // v will be 'this' in your method

Your code:

Validator.started();

It means, that started() is a static method of Validator (method of exactly function Validator()). You have to write code as I write above. Or:

window.Validator = function() {};
Validator._started = false;
Validator.started = function() {
    return this._started;
};
console.log(Validator.started());

Here _started is a static property and started() is a static method of Validator().


问:
How does C compute sin() and other math functions?
I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of sin() and other math functions... they always seem to be referencing something else.

Can anyone help me find them?  I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm somewhere, right?

I'm aware of several ways that functions can be calculated, and have written my own routines to compute functions using taylor series for fun.  I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not).

答:
The essence of how it does this lies in this excerpt from Applied Numerical Analysis by Gerald Wheatley:

When your software program asks the computer to get a value of
   or , have you wondered how it can get the
  values if the most powerful functions it can compute are polynomials?
  It doesnt look these up in tables and interpolate! Rather, the
  computer approximates every function other than polynomials from some
  polynomial that is tailored to give the values very accurately.

A few points to mention on the above is that some algorithms do infact interpolate from a table, albeit only for the first few iterations. Also note how it mentions that computers utilise approximating polynomials without specifying which type of approximating polynomial. As others in the thread have pointed out, Chebyshev polynomials are more efficient than Taylor polynomials in this case.


问:
Can somebody explain what makes this code?
I've hot React component which returns input tag. Can you please explain what is going on at the eighth line ref={element => element && (element.onChange = onChange)}? I

```<code>import React from 'react';

export default function MyInput({
    onChange,
    ...rest
}) {
    return (
        <input
            {...rest}
            ref={element => element && (element.onChange = onChange)}
        />
    );
}
</code>```

答:
Refs are used to access DOM elements

The value of ref differs depending on the type of node:

When the ref attribute is used on an HTML element, the ref created
in the constructor with React.createRef() receives the underlying
DOM element as its current property.

When the ref attribute is used on a custom class component, the ref
object receives the mounted instance of the component as its
current.

They are used in cases where we want to change the value of a child component, without making use of props and all. But in your case, i think you have no need to use ref because you simply wants to assign onChange that you received from props.

Body:
I've hot React component which returns input tag. Can you please explain what is going on at the eighth line ref={element => element && (element.onChange = onChange)}? I

import React from 'react';

export default function MyInput({
    onChange,
    ...rest
}) {
    return (
        <input
            {...rest}
            ref={element => element && (element.onChange = onChange)}
        />
    );
}


问:
What's best (fastest) way to get DOM elements in specific area
I want to get all DOM elements within a selector area (created when press and drag left mouse, like photoshop, illustrator, figma selector). as the following img:

All elements are absolute position with left, top, width, height attributes. And the selector given a rectangle with left, top, bottom, right, width, height. And please note that we have alot of elements (e.g: 10,000 DOM elements), so if we loop through all 10,000 elements to check if it with in selector area, that's not good idea.

I've tried 2 solutions:

Using intersection-observer to observer visible elements on screen first, then we only need to check in these elements.

Cache all elements with 4 objects:

byTops: store all elements with order top ascending

byBottoms: store all elements with order bottom ascending

byLefts: store all elements with order left ascending

byRights: store all elements with order top ascending

And when we check, it maybe faster

And this is DEMO for solution 1: Demo for solution 1

Does anyone have a better solution for this scene? Please help me!

thanks you very much!

答:
If you know the minimum size of each element they can select, you could potentially use document.elementFromPoint to get the elements selected.

What I mean is, say they drew a selection, and each thing they can select is at least 40px x 60px.  You could then do something like:

```<code>let {top, left, right, bottom} = rectangleCoords;
const selectedElements = new Set();
for (let x = left; x <= right; x += 40) {
    for (let y = top; y <= bottom; y+= 60) {
        const el = document.elementFromPoint(x, y).closest('.thing-you-want');
        if (el) {
            selectedElements.add(el);
        }
    }
}
</code>```

Body:
If you know the minimum size of each element they can select, you could potentially use document.elementFromPoint to get the elements selected.

What I mean is, say they drew a selection, and each thing they can select is at least 40px x 60px.  You could then do something like:

let {top, left, right, bottom} = rectangleCoords;
const selectedElements = new Set();
for (let x = left; x <= right; x += 40) {
    for (let y = top; y <= bottom; y+= 60) {
        const el = document.elementFromPoint(x, y).closest('.thing-you-want');
        if (el) {
            selectedElements.add(el);
        }
    }
}


问:
Map twice the PySpark RDD to group by different keys
I have the following RDD:

```<code>timeRange = (access_logs
              .map(lambda log: (log.date_time, 1))
              .reduceByKey(lambda a, b : a + b)
              .map(lambda s: s)
              .take(2000))

print("IpAddresses by time range: {}".format(timeRange))
</code>```

and my schema looks like:

```<code>def parse_apache_log_line(logline):
    match = re.search(APACHE_ACCESS_LOG_PATTERN, logline)
    if match is None:
        raise Exception("Invalid logline: %s" % logline)
    return Row(
        ip_address    = match.group(1),
        client_identd = match.group(2),
        user_id       = match.group(3),
        date_time     = match.group(4),
        method        = match.group(5),
        endpoint      = match.group(6),
        protocol      = match.group(7),
        response_code = int(match.group(8)),
        content_size  = int(match.group(9))
    )
</code>```

a sample log file:

```<code>129.192.176.24 - - [25/May/2015:23:11:16 +0000] "GET / HTTP/1.0" 200 3557 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; snprtz|S26320700000083|2600#Service Pack 1#2#5#154321|isdn)"
</code>```

I want to group and display by timestamp, then by the IP address and its count, within the timestamp.
Right now I'm able to map over the IP address and get something like ('25/May/2015:23:11:15 +0000', 1995), but I was looking for something like:
('25/May/2015:23:11:15 +0000', ('1.2.3.4', 20)).

答:
You can simply reduce by the key (date_time, ip_address) in the first step then group by date_time.

Try this:

```<code>timeRange = (access_logs
             .map(lambda log: ((log.date_time, log.ip_address), 1))
             .reduceByKey(lambda a, b: a + b)
             .map(lambda x: (x[0][0], (x[0][1], x[1]))) # <=> (date_time, (ip_address, count))
             .groupByKey()
             .map(lambda x: (x[0], list(x[1]))) # this final step to get list as groupBy gives ResultIterable object
            )
</code>```

Body:
I have the following RDD:

timeRange = (access_logs
              .map(lambda log: (log.date_time, 1))
              .reduceByKey(lambda a, b : a + b)
              .map(lambda s: s)
              .take(2000))

print("IpAddresses by time range: {}".format(timeRange))

and my schema looks like:

def parse_apache_log_line(logline):
    match = re.search(APACHE_ACCESS_LOG_PATTERN, logline)
    if match is None:
        raise Exception("Invalid logline: %s" % logline)
    return Row(
        ip_address    = match.group(1),
        client_identd = match.group(2),
        user_id       = match.group(3),
        date_time     = match.group(4),
        method        = match.group(5),
        endpoint      = match.group(6),
        protocol      = match.group(7),
        response_code = int(match.group(8)),
        content_size  = int(match.group(9))
    )

a sample log file:

129.192.176.24 - - [25/May/2015:23:11:16 +0000] "GET / HTTP/1.0" 200 3557 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; snprtz|S26320700000083|2600#Service Pack 1#2#5#154321|isdn)"

I want to group and display by timestamp, then by the IP address and its count, within the timestamp.
Right now I'm able to map over the IP address and get something like ('25/May/2015:23:11:15 +0000', 1995), but I was looking for something like:
('25/May/2015:23:11:15 +0000', ('1.2.3.4', 20)).

Body:
You can simply reduce by the key (date_time, ip_address) in the first step then group by date_time.

Try this:

timeRange = (access_logs
             .map(lambda log: ((log.date_time, log.ip_address), 1))
             .reduceByKey(lambda a, b: a + b)
             .map(lambda x: (x[0][0], (x[0][1], x[1]))) # <=> (date_time, (ip_address, count))
             .groupByKey()
             .map(lambda x: (x[0], list(x[1]))) # this final step to get list as groupBy gives ResultIterable object
            )


问:
Java IF-ELSE IF-ELSE skipping the if and else if check and prints out else statement automatically
Java 11.6 In this BMI calculator that will take in Person's weight, height and calculate the BMI. The BMI is calculated properly however in the classify BMI method the program skips the if and else if check and just prints out the else statement which is "obese" for every test. Is the loop implemented incorrectly? or the value of BMI is not initiating in the loop. When I print out the BMI, I do see that for every test the BMI does change so that is not a problem.

The PersonWeight.java class

```<code>import java.time.Year;

public class PersonWeight {

    private double height;
    private double weight;

    public PersonWeight() {

        height = 0;
        weight = 0;

    }

    public PersonWeight(double h, double w) {

        height = h;
        weight = w;

    }

    public void setHeight(double h) {
        this.height = h;
    }

    public double getHeight() {
        return height;
    }

    public void setWeight(double w) {
        this.weight = w;
    }

    public double getWeight() {
        return weight;
    }

    public double ComputeBMI() {

        double bmi = ((weight)/(height*height));
        return bmi;
    }

}
</code>```

The test class that has the main method

```<code>import java.util.Scanner;
public class TestPersonWeight {

    public static void classifyBMI() {
        PersonWeight PersonWeight = new PersonWeight();
        double bmi = PersonWeight.ComputeBMI();

        if(bmi<18.5) {
            System.out.printf("Underweight");

        }else if (bmi >= 18.5 && bmi<25) {
            System.out.printf("Normal Weight");
        }else if (bmi >=25 && bmi<30) {
            System.out.printf("Overweight");
        }else  {
            System.out.printf("Obese");

        }
    }

        public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        TestPersonWeight TestPersonWeight = new TestPersonWeight();
        PersonWeight PersonWeight = new PersonWeight()
        System.out.printf("Enter person's Height in Meters: ");
        double h = input.nextDouble();
        PersonWeight.setHeight(h);

        System.out.printf("Enter person's Weight in Kilograms: ");
        double w = input.nextDouble();
        PersonWeight.setWeight(w);

        PersonWeight.ComputeBMI();
        System.out.printf("%n Height: " + PersonWeight.getHeight());
        System.out.printf("%n Weight: " + PersonWeight.getWeight());
        System.out.printf("%n BMI: " + PersonWeight.ComputeBMI());
        classifyBMI();

    }
}
</code>```

答:
Your classifyBMI() method creates a new PersonWeight where the height and weight remain 0.0, so you are dividing 0.0 by 0.0, which results in NaN. Hence, none of the comparisons evaluates to true, and you end up with the else clause being executed.

You should change that method to be an instance method (i.e. not static), and call it for the PersonWeight instance that you create in your main method.

Or, as an alternative, keep that method static, but pass to it the previously calculated bmi value.

i.e. in your main write:

```<code>double bmi = PersonWeight.ComputeBMI();
System.out.printf("%n Height: " + PersonWeight.getHeight());
System.out.printf("%n Weight: " + PersonWeight.getWeight());
System.out.printf("%n BMI: " + bmi);
classifyBMI(bmi);
</code>```

and classifyBMI will become:

```<code>public static void classifyBMI (double bmi) {
    if(bmi < 18.5) {
        System.out.printf("Underweight");
    } else if (bmi >= 18.5 && bmi < 25) {
        System.out.printf("Normal Weight");
    } else if (bmi >= 25 && bmi < 30) {
        System.out.printf("Overweight");
    } else {
        System.out.printf("Obese");
    }
}
</code>```

P.S. using the same identifier - PersonWeight - for both your class name and the variable name is a bad practice. Use personWeight for the variable.

Body:
Java 11.6 In this BMI calculator that will take in Person's weight, height and calculate the BMI. The BMI is calculated properly however in the classify BMI method the program skips the if and else if check and just prints out the else statement which is "obese" for every test. Is the loop implemented incorrectly? or the value of BMI is not initiating in the loop. When I print out the BMI, I do see that for every test the BMI does change so that is not a problem.

The PersonWeight.java class

import java.time.Year;

public class PersonWeight {

    private double height;
    private double weight;

    public PersonWeight() {

        height = 0;
        weight = 0;

    }

    public PersonWeight(double h, double w) {

        height = h;
        weight = w;

    }

    public void setHeight(double h) {
        this.height = h;
    }

    public double getHeight() {
        return height;
    }

    public void setWeight(double w) {
        this.weight = w;
    }

    public double getWeight() {
        return weight;
    }

    public double ComputeBMI() {

        double bmi = ((weight)/(height*height));
        return bmi;
    }

}

The test class that has the main method

import java.util.Scanner;
public class TestPersonWeight {

    public static void classifyBMI() {
        PersonWeight PersonWeight = new PersonWeight();
        double bmi = PersonWeight.ComputeBMI();

        if(bmi<18.5) {
            System.out.printf("Underweight");

        }else if (bmi >= 18.5 && bmi<25) {
            System.out.printf("Normal Weight");
        }else if (bmi >=25 && bmi<30) {
            System.out.printf("Overweight");
        }else  {
            System.out.printf("Obese");

        }
    }

        public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        TestPersonWeight TestPersonWeight = new TestPersonWeight();
        PersonWeight PersonWeight = new PersonWeight()
        System.out.printf("Enter person's Height in Meters: ");
        double h = input.nextDouble();
        PersonWeight.setHeight(h);

        System.out.printf("Enter person's Weight in Kilograms: ");
        double w = input.nextDouble();
        PersonWeight.setWeight(w);

        PersonWeight.ComputeBMI();
        System.out.printf("%n Height: " + PersonWeight.getHeight());
        System.out.printf("%n Weight: " + PersonWeight.getWeight());
        System.out.printf("%n BMI: " + PersonWeight.ComputeBMI());
        classifyBMI();

    }
}

Body:
Your classifyBMI() method creates a new PersonWeight where the height and weight remain 0.0, so you are dividing 0.0 by 0.0, which results in NaN. Hence, none of the comparisons evaluates to true, and you end up with the else clause being executed.

You should change that method to be an instance method (i.e. not static), and call it for the PersonWeight instance that you create in your main method.

Or, as an alternative, keep that method static, but pass to it the previously calculated bmi value.

i.e. in your main write:

double bmi = PersonWeight.ComputeBMI();
System.out.printf("%n Height: " + PersonWeight.getHeight());
System.out.printf("%n Weight: " + PersonWeight.getWeight());
System.out.printf("%n BMI: " + bmi);
classifyBMI(bmi);

and classifyBMI will become:

public static void classifyBMI (double bmi) {
    if(bmi < 18.5) {
        System.out.printf("Underweight");
    } else if (bmi >= 18.5 && bmi < 25) {
        System.out.printf("Normal Weight");
    } else if (bmi >= 25 && bmi < 30) {
        System.out.printf("Overweight");
    } else {
        System.out.printf("Obese");
    }
}

P.S. using the same identifier - PersonWeight - for both your class name and the variable name is a bad practice. Use personWeight for the variable.


问:
How to train a model given in keras.applications from scratch by randomly initialising weights?
Documentation referred.

My understanding is that keras models have weights pre-trained with imagenet dataset. For learning purposes I want to train from scratch with weights randomly initialized.

First I load the model from keras. Here I didn't include weights='imagenet' argument I saw in some examples. If I don't include this argument, does that mean the model weights are randomly initialized?

```<code>import os, sys
from keras.utils.vis_utils import plot_model
from keras.applications import VGG16
from keras.layers import Input

from keras.optimizers import SGD

base_model = VGG16(, include_top=False, input_tensor=Input(shape = (224,224,3)))

base_model.summary()
plot_model(base_model, to_file=model_diagram_path, show_shapes=True)
</code>```

Next I added back the output layers to the model. I replicated the same structure given in the original VGG16 model.

```<code>from keras.layers.core import Flatten
from keras.layers.core import Dense
from keras.utils.vis_utils import plot_model
from keras.models import Model

# Create head part
head_model = base_model.output

head_model = Flatten(name='flatten')(head_model)
head_model = Dense(4096,activation='relu')(head_model)
head_model = Dense(4096,activation='relu')(head_model)
head_model = Dense(len(class_names),activation='softmax')(head_model)

# Attach head to model
model = Model(inputs=base_model.input, outputs = head_model)

model_diagram_path = 'vgg16-output-modified.png'
plot_model(model, to_file=model_diagram_path, show_shapes=True)
</code>```

Does this approach allows me to train a model from scratch? If not what is the correct approach?

答:
To perform training from scratch you should pass None for the weights argument.

base_model = VGG16(weights=None, include_top=False, input_tensor=Input(shape = (224,224,3)))
```

<p>After calling the above line you should see that the download has <strong>not</strong> started.</p>

<p>According to their Github Source the default argument for <code>weights</code> is <code>'imagenet'</code> so skipping this argument and calling your model via</p>

<pre class="lang-py prettyprint-override"><code>base_model = VGG16(include_top=False, input_tensor=Input(shape = (224,224,3)))
</code>```

will still download and load the Imagenet weights.

Body:
Documentation referred.

My understanding is that keras models have weights pre-trained with imagenet dataset. For learning purposes I want to train from scratch with weights randomly initialized.

First I load the model from keras. Here I didn't include weights='imagenet' argument I saw in some examples. If I don't include this argument, does that mean the model weights are randomly initialized?

import os, sys
from keras.utils.vis_utils import plot_model
from keras.applications import VGG16
from keras.layers import Input

from keras.optimizers import SGD

base_model = VGG16(, include_top=False, input_tensor=Input(shape = (224,224,3)))

base_model.summary()
plot_model(base_model, to_file=model_diagram_path, show_shapes=True)

Next I added back the output layers to the model. I replicated the same structure given in the original VGG16 model.

from keras.layers.core import Flatten
from keras.layers.core import Dense
from keras.utils.vis_utils import plot_model
from keras.models import Model

# Create head part
head_model = base_model.output

head_model = Flatten(name='flatten')(head_model)
head_model = Dense(4096,activation='relu')(head_model)
head_model = Dense(4096,activation='relu')(head_model)
head_model = Dense(len(class_names),activation='softmax')(head_model)

# Attach head to model
model = Model(inputs=base_model.input, outputs = head_model)

model_diagram_path = 'vgg16-output-modified.png'
plot_model(model, to_file=model_diagram_path, show_shapes=True)

Does this approach allows me to train a model from scratch? If not what is the correct approach?

Body:
To perform training from scratch you should pass None for the weights argument.

base_model = VGG16(weights=None, include_top=False, input_tensor=Input(shape = (224,224,3)))

After calling the above line you should see that the download has not started.

According to their Github Source the default argument for weights is 'imagenet' so skipping this argument and calling your model via

base_model = VGG16(include_top=False, input_tensor=Input(shape = (224,224,3)))

will still download and load the Imagenet weights.


问:
Can someone show me how to create this very simple makefile?
This is in C, am running UNIX through Putty and want to create a Makefile.

So I have a program that is in only one file "recommender.c" and i need to make a makefile that creates an executable file called recommender using the all function. The part i don't know how to do is that i compile recommender.c using the line gcc recommender.c -std=gnu99
I don't know how to make sure it does the -std=gun99 part too. please help? :)

答:
```<code>CFLAGS=-std=gnu99 -Wall -Wextra -O3

all: recommender

recommender: recommender.o
</code>```

Note that the file extension must be .c if it has the extension .cpp it will need the CXXFLAGS instead of CFLAGS

Some explanation:

The make file is dependency based as you can see you can set your variables on top of the make file. Then when the make program is invoked it will search for a Makefile in the current directory.

Since the default action is all it will search for the all rule.
When it found the all rule it will check which dependencies are needed in this case the recommender rule / file so it starts searching the rules again and it finds out it needs the recommender.o rule / file but it won't find any, now here is where the magic happens.

make is smart enough to know that an .o (object) file is made from an .c or .cpp (source) file so now it will start searching for the source file in the current directory. This he does by replacing the .o with an .c if it finds the file it will compile it with the gcc compiler if it where to find an .cpp file it will compile it with the g++ compiler.

So now we know this we can simply add multiple source files to the project by adding more object file as dependencies.

Now you don't really need to create an object file first since you compile from one source file you can also remove the recommender: recommender.o rule and make will try to create the recommender application by compiling recommender.c or .cpp

Body:
CFLAGS=-std=gnu99 -Wall -Wextra -O3

all: recommender

recommender: recommender.o

Note that the file extension must be .c if it has the extension .cpp it will need the CXXFLAGS instead of CFLAGS

Some explanation:

The make file is dependency based as you can see you can set your variables on top of the make file. Then when the make program is invoked it will search for a Makefile in the current directory.

Since the default action is all it will search for the all rule.
When it found the all rule it will check which dependencies are needed in this case the recommender rule / file so it starts searching the rules again and it finds out it needs the recommender.o rule / file but it won't find any, now here is where the magic happens.

make is smart enough to know that an .o (object) file is made from an .c or .cpp (source) file so now it will start searching for the source file in the current directory. This he does by replacing the .o with an .c if it finds the file it will compile it with the gcc compiler if it where to find an .cpp file it will compile it with the g++ compiler.

So now we know this we can simply add multiple source files to the project by adding more object file as dependencies.

Now you don't really need to create an object file first since you compile from one source file you can also remove the recommender: recommender.o rule and make will try to create the recommender application by compiling recommender.c or .cpp


问:
Python - nested loop vs 'in' operator resulting in almost double runtime
I come from a C++/Java background and have done a simple implementation of the 'TwoNumberSum' algorithm
 below. I first implemented it in a more C/Java way using the conventional nested loop then using the 'in' operator. I was expecting both to execute in similar time as 'in' should ideally also iterate through the list which should result in a nested loop and thus somewhere similar execution time but to my surprise the first algorithm takes double the time of the second.
Can someone explain what is causing such huge gap in runtime?

I am getting below results on executing the snippet.

Execution Time of Algo 1: 1.023191

Execution Time of Algo 2: 0.46218059999999994

```<code>from timeit import timeit

# First Algorithm using simple lists/arrays
code1 = """
def TwoNumberSum(list, sum):

    for i in range(0, len(list)-1):
        for j in range(i+1, len(list)):
            if list[i] + list[j] == sum:
                return [list[i], list[j]]
    return []

TwoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)
"""
# Second Algorith similar to first using 'in' operator
code2 = """
def TwoNumberSum(list, sum):

    for i in range(0, len(list)-1):
        if sum-list[i] in list[i+1:-1]:
            return [list[i], sum-list[i]]
    return []

TwoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)
"""

print(f"Execution Time of Algo 1: {timeit(code1, number=100000)}")
print(f"Execution Time of Algo 2: {timeit(code2, number=100000)}")
</code>```

答:
Python is an interpreted language, and for loops in it are notoriously slow.  You probably expect that in is implemented as a for loop, and it is, but it's implemented natively (typically in C), not in Python.  There are a lot of functions like that in Python, otherwise the whole language would be impractically slow (at least on the most common interpreter implementation, which is CPython).

If you care about performance in Python, you'll need to do everything you can to avoid Python loops that are executed many times.  This is a big part of why NumPy exists and is written largely in C (because operating on vectors and arrays takes forever if you use for loops).

You can also write your own Python modules in C (or C++, or other languages which can expose C callable functions), and this is very useful if you need to accelerate custom loops.

Added to address comments from user "Heap Overflow":

If the input list is long, you want an linear time solution.  Here is one:

```<code>def TwoNumberSum(nums, target):
    seen = set()
    for num in nums:
        complement = target - num
        if complement in seen:
            return num, complement
        seen.add(num)
</code>```

This is actually slower for the short example lists given in the question, but will be faster for longer lists.  But it still contains a for loop in Python, which means it won't be blazing fast.  An easy way to fix that is to use Numba, which automatically translates a subset of Python to machine code:

```<code>import numba
TwoNumbaSum = numba.njit(TwoNumberSum)
</code>```

Numba expects NumPy arrays rather than lists, so call it like this:

```<code>TwoNumbaSum(np.asarray([3, 5, -4, 8, 11, 1, -1, 6]), 10)
</code>```

That's it, now you have a linear time solution with no for loops in Python, and you didn't have to write C or C++ code (which would run just as fast but require more effort to develop).

Body:
I come from a C++/Java background and have done a simple implementation of the 'TwoNumberSum' algorithm
 below. I first implemented it in a more C/Java way using the conventional nested loop then using the 'in' operator. I was expecting both to execute in similar time as 'in' should ideally also iterate through the list which should result in a nested loop and thus somewhere similar execution time but to my surprise the first algorithm takes double the time of the second.
Can someone explain what is causing such huge gap in runtime?

I am getting below results on executing the snippet.

Execution Time of Algo 1: 1.023191

Execution Time of Algo 2: 0.46218059999999994

from timeit import timeit

# First Algorithm using simple lists/arrays
code1 = """
def TwoNumberSum(list, sum):

    for i in range(0, len(list)-1):
        for j in range(i+1, len(list)):
            if list[i] + list[j] == sum:
                return [list[i], list[j]]
    return []

TwoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)
"""
# Second Algorith similar to first using 'in' operator
code2 = """
def TwoNumberSum(list, sum):

    for i in range(0, len(list)-1):
        if sum-list[i] in list[i+1:-1]:
            return [list[i], sum-list[i]]
    return []

TwoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)
"""

print(f"Execution Time of Algo 1: {timeit(code1, number=100000)}")
print(f"Execution Time of Algo 2: {timeit(code2, number=100000)}")

Body:
Python is an interpreted language, and for loops in it are notoriously slow.  You probably expect that in is implemented as a for loop, and it is, but it's implemented natively (typically in C), not in Python.  There are a lot of functions like that in Python, otherwise the whole language would be impractically slow (at least on the most common interpreter implementation, which is CPython).

If you care about performance in Python, you'll need to do everything you can to avoid Python loops that are executed many times.  This is a big part of why NumPy exists and is written largely in C (because operating on vectors and arrays takes forever if you use for loops).

You can also write your own Python modules in C (or C++, or other languages which can expose C callable functions), and this is very useful if you need to accelerate custom loops.

Added to address comments from user "Heap Overflow":

If the input list is long, you want an linear time solution.  Here is one:

def TwoNumberSum(nums, target):
    seen = set()
    for num in nums:
        complement = target - num
        if complement in seen:
            return num, complement
        seen.add(num)

This is actually slower for the short example lists given in the question, but will be faster for longer lists.  But it still contains a for loop in Python, which means it won't be blazing fast.  An easy way to fix that is to use Numba, which automatically translates a subset of Python to machine code:

import numba
TwoNumbaSum = numba.njit(TwoNumberSum)

Numba expects NumPy arrays rather than lists, so call it like this:

TwoNumbaSum(np.asarray([3, 5, -4, 8, 11, 1, -1, 6]), 10)

That's it, now you have a linear time solution with no for loops in Python, and you didn't have to write C or C++ code (which would run just as fast but require more effort to develop).


问:
How can I change an exist list, to a new list? || android - firebase realtime database
I want to change the exist “categories” list, to a new list.

I know that my problem is in the “setPriority()”, but I don’t find the right method.

My Database Structure:

My code:

```<code>private void updateData() {
            database = FirebaseDatabase.getInstance();
            mDatabaseRef = database.getReference();

            mDatabaseRef
                    .child("users")
                    .child(Login.userId)
                    .child("categories")
                    .setValue(categories)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {

                            if (task.isSuccessful()) {

                                //Update success
                            } else {

                                //Update fail
                            }
                        }
                    });
        }
</code>```

Thank you.

答:
No need to query to database to update list. You can simply call setValue to over write the existing list with new one. Check below:

```<code>database = FirebaseDatabase.getInstance();
mDatabaseRef = database.getReference();

mDatabaseRef
    .child("users")
    .child(Login.userId)
    .child("categories")
    .setValue(categories)
    .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {

            if (task.isSuccessful()) {

                //Update success
            } else {

                //Update fail
            }
        }
    });
</code>```

Body:
I want to change the exist “categories” list, to a new list.

I know that my problem is in the “setPriority()”, but I don’t find the right method.

My Database Structure:

My code:

private void updateData() {
            database = FirebaseDatabase.getInstance();
            mDatabaseRef = database.getReference();

            mDatabaseRef
                    .child("users")
                    .child(Login.userId)
                    .child("categories")
                    .setValue(categories)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {

                            if (task.isSuccessful()) {

                                //Update success
                            } else {

                                //Update fail
                            }
                        }
                    });
        }

Thank you.

Body:
No need to query to database to update list. You can simply call setValue to over write the existing list with new one. Check below:

database = FirebaseDatabase.getInstance();
mDatabaseRef = database.getReference();

mDatabaseRef
    .child("users")
    .child(Login.userId)
    .child("categories")
    .setValue(categories)
    .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {

            if (task.isSuccessful()) {

                //Update success
            } else {

                //Update fail
            }
        }
    });


问:
why Runtime.getRuntime().exec(startupOracle); does not fully execute command
I'm beginner at java and have some issues trying to startup oracle with java code. I've read several topics about this theme but none of them worked for me. Here is my code:

```<code>try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String host = "jdbc:oracle:thin:@localhost:1521:orcl";
            String uName = "username";
            String uPass = "password";

            con = DriverManager.getConnection(host, uName, uPass);

    }catch (Exception err){

        }
        if (con == null){
       String[] startupOracle = new String[]{"cmd ", " /c start cmd /K " + "\"" + " chcp 1251 "
         + " &C:\\app\\Raph\\product\\12.1.0\\dbhome_1\\bin\\sqlplus.exe " + "username/password"
            + "&startup" };

       Process pr = Runtime.getRuntime().exec(startupOracle);
        }
</code>```

I have two issues:

The Runtime.getRuntime().exec(startupOracle); execute till the point of login me in and stops execution immediately after I'm logged in thereby leaving line 15 ("&startup") not executed.

I'm unable to connect to oracle using "CONNECT / AS SYSDBA" as my username. I guess this is due to the empty space and "/" character in the username because when I use "system" as my username I get connected. I don't know how to solve the issue of empty space and "/" in the former username.

答:
Javadoc of exec(String[] cmdarray) says:

Parameters:

  cmdarray - array containing the command to call and its arguments.

Its "arguments" (plural), which means if you want to execute command foo.exe bar abc, then you need to pass { "foo.exe", "bar", "abc" }, not { "foo.exe", "bar abc" }.

For your code that means:

```<code>String[] startupOracle = new String[] {
        "cmd",
        "/c",
        "start",
        "cmd",
        "/K",
        "\"chcp 1251" +
          " & " +
          "C:\\app\\Raph\\product\\12.1.0\\dbhome_1\\bin\\sqlplus.exe username/password &startup\""
};
</code>```

Or something like that, though I think you have some problems with the &'s.

Body:
I'm beginner at java and have some issues trying to startup oracle with java code. I've read several topics about this theme but none of them worked for me. Here is my code:

try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String host = "jdbc:oracle:thin:@localhost:1521:orcl";
            String uName = "username";
            String uPass = "password";

            con = DriverManager.getConnection(host, uName, uPass);

    }catch (Exception err){

        }
        if (con == null){
       String[] startupOracle = new String[]{"cmd ", " /c start cmd /K " + "\"" + " chcp 1251 "
         + " &C:\\app\\Raph\\product\\12.1.0\\dbhome_1\\bin\\sqlplus.exe " + "username/password"
            + "&startup" };

       Process pr = Runtime.getRuntime().exec(startupOracle);
        }

I have two issues:

The Runtime.getRuntime().exec(startupOracle); execute till the point of login me in and stops execution immediately after I'm logged in thereby leaving line 15 ("&startup") not executed.

I'm unable to connect to oracle using "CONNECT / AS SYSDBA" as my username. I guess this is due to the empty space and "/" character in the username because when I use "system" as my username I get connected. I don't know how to solve the issue of empty space and "/" in the former username.

Body:
Javadoc of exec(String[] cmdarray) says:

Parameters:

  cmdarray - array containing the command to call and its arguments.

Its "arguments" (plural), which means if you want to execute command foo.exe bar abc, then you need to pass { "foo.exe", "bar", "abc" }, not { "foo.exe", "bar abc" }.

For your code that means:

String[] startupOracle = new String[] {
        "cmd",
        "/c",
        "start",
        "cmd",
        "/K",
        "\"chcp 1251" +
          " & " +
          "C:\\app\\Raph\\product\\12.1.0\\dbhome_1\\bin\\sqlplus.exe username/password &startup\""
};

Or something like that, though I think you have some problems with the &'s.


问:
Receiving Cannot GET/ Error NodeJS and Express
I'm learning how to use NodeJS and Express, and I'm having trouble loading pages using express. I'm able to load static pages (index.html works fine), but having trouble with anything dynamic; in this case, I keep receiving the error "Cannot GET /store.html". Would someone be able to explain what is happening?

server.js

app.set('view engine', 'ejs')
app.use(express.static('public'))

app.get('/store', function(req, res) {
    res.render('store.ejs', {
        FOO: foo
    })
})
```

<p><strong>file structure</strong></p>

```server.js
public
    index.html
views
    store.ejs
```

答: You should be using /store to access the store.ejs template not /store.html </p>

Body:
I'm learning how to use NodeJS and Express, and I'm having trouble loading pages using express. I'm able to load static pages (index.html works fine), but having trouble with anything dynamic; in this case, I keep receiving the error "Cannot GET /store.html". Would someone be able to explain what is happening?

server.js

app.set('view engine', 'ejs')
app.use(express.static('public'))

app.get('/store', function(req, res) {
    res.render('store.ejs', {
        FOO: foo
    })
})

file structure

server.js
public
    index.html
views
    store.ejs


问:
What is the easiest and least boring way to learn CakePHP?
I am trying to actually learn CakePHP and be able to make a simple website with it, but the shere size of the documentation and people telling me I should have read at least 100 pages, has kept me away from CakePHP after having worked with it for a month.

I just get a little bored when I have to read a full manual page with references, half of the used terms I have not yet known before, so it's not very effective.

I have successfully completed the blog-tutorial and read about the MVC model, I am however not ready to make a simple website. Half the time of my first attempt I ended up copy-pasting and using trial and error.

答:
I think that diving in and building an actual website is the best way to learn.
Choose something that really interests you and this will give you the motivation to search through the manual when you want to learn how to do something.

I would learn how to bake an application using the "bake" command in the console:

Code Generation with Bake

Start Cakephp – How to use shell/console/bake

Cake will generate all the code for your site - and it's a great starting point for developing a site further.

Studying other people's code can also be helpful.  Two places to look:

The Bakery, Everything CakePHP

http://thechaw.com/projects