问:
SQL Select row between two conditional rows
```<code>id  vehicle   speed
1   ABC-12     1.2
2   ABC-34     7.3
3   ABC-56     6.3
4   ABC-78     0
5   ABC-90     5.1
6   ABC-91     0
7   ABC-92     5.1
8   ABC-93     0
9   ABC-94     0
</code>```

I have a table with structure like this, I want to select all vehicles whose speed = 0 but vehicle before that && after that must have speed > 0

Like in this above example answer should be

```<code>id  vehicle   speed
4   ABC-78     0
6   ABC-91     0
</code>```

I am not sure it's possible or not

答:
Something like this might help</p>

```<code>WITH cte
AS
(
    SELECT id, vehicle, speed, lead(speed) OVER (ORDER BY id) AS ld, lag(speed) OVER (ORDER BY id) AS lg
    from yourTable
)

SELECT *
FROM cte
WHERE speed = 0 AND ld > 0 AND lg > 0
</code>```

Body:
id  vehicle   speed
1   ABC-12     1.2
2   ABC-34     7.3
3   ABC-56     6.3
4   ABC-78     0
5   ABC-90     5.1
6   ABC-91     0
7   ABC-92     5.1
8   ABC-93     0
9   ABC-94     0

I have a table with structure like this, I want to select all vehicles whose speed = 0 but vehicle before that && after that must have speed > 0

Like in this above example answer should be

id  vehicle   speed
4   ABC-78     0
6   ABC-91     0

I am not sure it's possible or not

Body:
Something like this might help

WITH cte
AS
(
    SELECT id, vehicle, speed, lead(speed) OVER (ORDER BY id) AS ld, lag(speed) OVER (ORDER BY id) AS lg
    from yourTable
)

SELECT *
FROM cte
WHERE speed = 0 AND ld > 0 AND lg > 0


来源: stackexchange

问:
React JS // Editing style of one component from another component
My goal is to create a basic app that allows me to change the style of one component with an action from another component.

Lets assume I have a <Btn/> component and a <Box/> component and when the button is clicked, I want to change the background color of the box. <Btn/> and <Box/> have the common ancestor of <App/> but are both at different levels in the component tree.

Btn.js

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

function Btn() {

  const handleClick = (e) => {
    //...
  }

  return (
    <button onClick={handleClick}>
      Click me
    </button>
  );
}

export default Btn
</code>```

Box.js

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

function Box() {
  return (
    <h1>
       Hello World!
    </h1>
  );
}

export default Box
</code>```

I do not want to use prop drilling (with style setting/getting functionality in the <App/> component) to achieve this. I have also deliberately left out component styling as I am open to whichever styling option is best to solve this problem.

What would be the best way to go about this? (I'm open to using Context, Redux or another library if it is appropriate.)

答:
The simplest way of doing this is with Context, as you're using function components not classes the documentation you'll need is useContext https://reactjs.org/docs/hooks-reference.html#usecontext. You still have to define the prop and "setter" function at the app level or at a component called at the app level, but with context you don't have to pass the props all the way down.

To take their example and adapt it to your use case would go something like this. (Working sample: https://codesandbox.io/s/stackoverflow-answer-7hryk)

const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

const ThemeContext = React.createContext(themes.light);

function App() {
  const [stateTheme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={{ theme: themes[stateTheme], setTheme: setStateTheme }}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar(props) {
  return (

      <ToggleButtons />
      <ThemedButton />

  );
}

function ToggleButtons() {
  const { setTheme } = useContext(ThemeContext);
  return (

      <button onClick={() => setTheme('light')}>Light Theme</button>
      <button onClick={() => setTheme('dark')}>Dark Theme</button>

  );
}

function ThemedButton() {
  const { theme } = useContext(ThemeContext);

  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
    </button>
  );
}
```

ContentLicense: CC BY-SA 4.0

Body:
My goal is to create a basic app that allows me to change the style of one component with an action from another component.

Lets assume I have a <Btn/> component and a <Box/> component and when the button is clicked, I want to change the background color of the box. <Btn/> and <Box/> have the common ancestor of <App/> but are both at different levels in the component tree.

Btn.js

import React from 'react'

function Btn() {

  const handleClick = (e) => {
    //...
  }

  return (
    <button onClick={handleClick}>
      Click me
    </button>
  );
}

export default Btn

Box.js

import React from 'react'

function Box() {
  return (

       Hello World!

  );
}

export default Box

I do not want to use prop drilling (with style setting/getting functionality in the <App/> component) to achieve this. I have also deliberately left out component styling as I am open to whichever styling option is best to solve this problem.

What would be the best way to go about this? (I'm open to using Context, Redux or another library if it is appropriate.)

Body:
The simplest way of doing this is with Context, as you're using function components not classes the documentation you'll need is useContext https://reactjs.org/docs/hooks-reference.html#usecontext. You still have to define the prop and "setter" function at the app level or at a component called at the app level, but with context you don't have to pass the props all the way down.

To take their example and adapt it to your use case would go something like this. (Working sample: https://codesandbox.io/s/stackoverflow-answer-7hryk)

const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee"
  },
  dark: {
    foreground: "#ffffff",
    background: "#222222"
  }
};

const ThemeContext = React.createContext(themes.light);

function App() {
  const [stateTheme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={{ theme: themes[stateTheme], setTheme: setStateTheme }}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar(props) {
  return (
    <div>
      <ToggleButtons />
      <ThemedButton />
    </div>
  );
}

function ToggleButtons() {
  const { setTheme } = useContext(ThemeContext);
  return (
    <div>
      <button onClick={() => setTheme('light')}>Light Theme</button>
      <button onClick={() => setTheme('dark')}>Dark Theme</button>
    </div>
  );
}

function ThemedButton() {
  const { theme } = useContext(ThemeContext);

  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!
    </button>
  );
}


问:
Repeated Step functions
I am trying to create a signal in matlab that will be a step function that is initially off then switches on and then off.  But, I need to repeat this signal for rest of my interval and would require to repeat this step function thirty or so times.

Instead of writing heaviside for each time it switches on and off.  I tried to put the hevistep function inside a for loop, but had little success.  I don't think the heaviestep function is designed for a for loop, what are some better methods of creating this signal.

```<code>y = 0
    for a = 1:2:10
        x = heaviside(t-a) - heaviside(t-(a+1));
        y = y + x
    end
</code>```

答:
To get a heavyside function you can do something like this, where t is your independent variable, period is your period, duty is your duty cycle (fraction of cycle you want high) and shift is to shift.

```<code>heavy =@(t, period, duty, shift) double( mod( t - shift , period ) < duty * period )
</code>```

Then you can do something like

```<code>t = linspace(0,10,1E4);
plot(t , heavy( t , pi , 0.25 , pi/3 ) )
</code>```

Title: Repeated Step functions

Body:
I am trying to create a signal in matlab that will be a step function that is initially off then switches on and then off.  But, I need to repeat this signal for rest of my interval and would require to repeat this step function thirty or so times.

Instead of writing heaviside for each time it switches on and off.  I tried to put the hevistep function inside a for loop, but had little success.  I don't think the heaviestep function is designed for a for loop, what are some better methods of creating this signal.

y = 0
    for a = 1:2:10
        x = heaviside(t-a) - heaviside(t-(a+1));
        y = y + x
    end

Body:
To get a heavyside function you can do something like this, where t is your independent variable, period is your period, duty is your duty cycle (fraction of cycle you want high) and shift is to shift.

heavy =@(t, period, duty, shift) double( mod( t - shift , period ) < duty * period )

Then you can do something like

t = linspace(0,10,1E4);
plot(t , heavy( t , pi , 0.25 , pi/3 ) )


问:
PHP: Count input type with value
Hi I want to count input type with value

<input type="text" name="a[]" value="Test1">
<input type="text" name="a[]" value="Test2">
<input type="text" name="a[]" value="">```
</div>
</div>
</p>

<p>PHP Code:</p>

```echo count($_POST['a']);
```

The output is 3. I want to get only the input type with value which is 2.

I want my output to be 2

Thank you

答:
This should work -

```<code>count(array_filter($_POST['a']))
</code>```

array_filter will remove the empty values from array.

array_filter()

Title: PHP: Count input type with value

Body:
Hi I want to count input type with value

<input type="text" name="a[]" value="Test1">
<input type="text" name="a[]" value="Test2">
<input type="text" name="a[]" value="">

PHP Code:

echo count($_POST['a']);

The output is 3. I want to get only the input type with value which is 2.

I want my output to be 2

Thank you

Body:
This should work -

count(array_filter($_POST['a']))

array_filter will remove the empty values from array.

array_filter()


问:
How to use IExceptionHandler in ASP.NET CORE MVC?
I'm having trouble using IExceptionHandler in my project.

Do I need to install any NuGet packages?

When I try to use, Visual Studio does not find the reference. He asks if I want to create an interface named IExceptionHandler.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EventMotors.Controllers
{
    public class ErrorController : Controller
    {
        private readonly IExceptionHandler _exceptionHandler;

        public ErrorController(IExceptionHandler exceptionHandler)
        {
            _exceptionHandler = exceptionHandler;
        }
    }
}
</code>```

答:
IExceptionHandler is not in asp.net core .  In error action , you can use IExceptionHandlerPathFeature to access the exception and the original request path in an error handler controller or page:

```<code>var exceptionHandlerPathFeature =
    HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
    ExceptionMessage = "File error thrown";
}
if (exceptionHandlerPathFeature?.Path == "/index")
{
    ExceptionMessage += " from home page";
}
</code>```

Please refer to document :

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1

Body:
I'm having trouble using IExceptionHandler in my project.

Do I need to install any NuGet packages?

When I try to use, Visual Studio does not find the reference. He asks if I want to create an interface named IExceptionHandler.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EventMotors.Controllers
{
    public class ErrorController : Controller
    {
        private readonly IExceptionHandler _exceptionHandler;

        public ErrorController(IExceptionHandler exceptionHandler)
        {
            _exceptionHandler = exceptionHandler;
        }
    }
}

Body:
IExceptionHandler is not in asp.net core .  In error action , you can use IExceptionHandlerPathFeature to access the exception and the original request path in an error handler controller or page:

var exceptionHandlerPathFeature =
    HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
    ExceptionMessage = "File error thrown";
}
if (exceptionHandlerPathFeature?.Path == "/index")
{
    ExceptionMessage += " from home page";
}

Please refer to document :

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-3.1


问:
Tensorflow 2 multiple simultaneous predictions
In Tensorflow 2 after loading saved model with
tf.saved_model.load(my_model) How can I run multiple predictions with same model( not Graph)?

I am using Pool class from multiprocessing package. Importing tensorflow and keras in helper method before loading model did not help:

```<code>import tensorflow as tf
import keras
tf.saved_model.load(my_model)
</code>```

Error code:

Can't pickle local object 'Loader._recreate_base_user_object.._UserObject'

答:
As was suggested in stackoverflow, passing multiple inputs in array (numpy or python doesn't matter) works better than for loop. Performance improvement was 25%.
Don't forget to set thread number:

```<code>tf.config.threading.set_intra_op_parallelism_threads(num_cores)
tf.config.threading.set_inter_op_parallelism_threads(num_cores)
</code>```

However should note that tensorflow would use number of thread times more memory.

Body:
In Tensorflow 2 after loading saved model with
tf.saved_model.load(my_model) How can I run multiple predictions with same model( not Graph)?

I am using Pool class from multiprocessing package. Importing tensorflow and keras in helper method before loading model did not help:

import tensorflow as tf
import keras
tf.saved_model.load(my_model)

Error code:

Can't pickle local object 'Loader._recreate_base_user_object.._UserObject'

Body:
As was suggested in stackoverflow, passing multiple inputs in array (numpy or python doesn't matter) works better than for loop. Performance improvement was 25%.
Don't forget to set thread number:

tf.config.threading.set_intra_op_parallelism_threads(num_cores)
tf.config.threading.set_inter_op_parallelism_threads(num_cores)

However should note that tensorflow would use number of thread times more memory.


问:
Image not fitting
I am trying to load an image as a background in pygame.  I have done this before, and followed the same process, but with my latest game it is showing up wonky and I'm not sure why...
My original image (below) is 1280x645 and I use this code to load/display it:

```<code>import pygame
pygame.init()

win = pygame.display.set_mode((1280,645))
bg = pygame.image.load('CheeseFarm_Background.png')

win.blit(bg, (0,0))
</code>```

But, when I run it, it looks like this:

Ideas what I am doing wrong?

答:
There's not really enough code to say what could be the problem.  The image in the post works fine for me.  Obviously your code has no event loop, so probably the window closes immediately.  I expect the code was omitted to make the question smaller.

The code below opens a window and displays the bitmap from the question correctly.

```<code>import pygame

### initialisation
pygame.init()
win = pygame.display.set_mode((1280,645))
bg = pygame.image.load('dairy_farm.png')

### Main Loop
clock = pygame.time.Clock()
done = False
while not done:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True
        elif ( event.type == pygame.MOUSEBUTTONUP ):
            # On mouse-click
            mouse = event.pos
            print( "Click at " + str( mouse ) )

    # Update the window, but not more than 60fps
    win.blit(bg, (0,0))
    pygame.display.flip()

    # Clamp FPS
    clock.tick_busy_loop(60)

pygame.quit()
</code>```

Title: Image not fitting

Body:
I am trying to load an image as a background in pygame.  I have done this before, and followed the same process, but with my latest game it is showing up wonky and I'm not sure why...
My original image (below) is 1280x645 and I use this code to load/display it:

import pygame
pygame.init()

win = pygame.display.set_mode((1280,645))
bg = pygame.image.load('CheeseFarm_Background.png')

win.blit(bg, (0,0))

But, when I run it, it looks like this:

Ideas what I am doing wrong?

Body:
There's not really enough code to say what could be the problem.  The image in the post works fine for me.  Obviously your code has no event loop, so probably the window closes immediately.  I expect the code was omitted to make the question smaller.

The code below opens a window and displays the bitmap from the question correctly.

import pygame

### initialisation
pygame.init()
win = pygame.display.set_mode((1280,645))
bg = pygame.image.load('dairy_farm.png')

### Main Loop
clock = pygame.time.Clock()
done = False
while not done:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True
        elif ( event.type == pygame.MOUSEBUTTONUP ):
            # On mouse-click
            mouse = event.pos
            print( "Click at " + str( mouse ) )

    # Update the window, but not more than 60fps
    win.blit(bg, (0,0))
    pygame.display.flip()

    # Clamp FPS
    clock.tick_busy_loop(60)

pygame.quit()


问:
How to mask string after first character
Let's say I have a string that consists of a person's name:

```<code>var name = "Jason, Bruno Mars";
</code>```

How do I mask the string with X for the name behind the comma and returns:

```<code>var name = "Jason, BXXXX MXXX";
</code>```

I have tried using the following methods but only front characters are masked:

```<code>string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}
</code>```

Anyone has a better idea of how can I achieve the same result in a more efficient way?

答:
```<code>private string MaskName(string name)
{
    var parts = name.Split(',');
    var subparts = parts[1].Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

    for (var i = 0; i < subparts.Length; i++)
    {
        var subpart = subparts[i];

        subparts[i] = subpart[0] + new string('X', subpart.Length - 1);
    }

    return parts[0] + ", " + string.Join(" ", subparts);
}
</code>```

Body:
Let's say I have a string that consists of a person's name:

var name = "Jason, Bruno Mars";

How do I mask the string with X for the name behind the comma and returns:

var name = "Jason, BXXXX MXXX";

I have tried using the following methods but only front characters are masked:

string first, second, output;
bool hasSpace, hasComma;
int int_LENGTH;
var name = "Jason, Bruno Mars";
hasComma = name.Contains(",");

if (hasComma == true)
{
    int_LENGTH = name.IndexOf(",");
    if (int_LENGTH > 0)
    {
        first = name.Substring(0, int_LENGTH);
    }

    second = string.Join(",", name.Split(" ").Skip(1));
    hasSpace = second.Contains(" ");

    if (hasSpace == true)
    {
        second = string.Concat(new string('X', 12), second.Substring(second.Length - 4));
        output = first + "," + second;
    }
}

Anyone has a better idea of how can I achieve the same result in a more efficient way?


问:
Compare Txt Files in Linux and Return Elements in File 1 for Elements in File 2
Here is the problem.

Host.txt file has only Hostnames as follows:

```
GVC-CH-ZRH-BRA-5H81-PELE
GVC-US-NYC-9TH-4C101-MEDROOM
GVC-US-NYC-9TH-4C101E-EXTRA
GVC-US-NYC-9TH-5E117-STUDIO54
```

2.HosandIp.txt has the Hostnames and Ip as follows (HostandIP has hostname,IP Address Note the Comma (,)):

```
GVC-CH-ZRH-BRA-5H81-PELE,170.16.75.101
GVC-US-NYC-9TH-4C101-MEDROOM,170.26.114.242
GVC-US-NYC-9TH-4C101E-EXTRA,170.26.108.224
GVC-US-NYC-9TH-5E117-STUDIO54,170.26.108.95
beta-gvc-personal-antoniop-526,170.26.107.180
beta-gvc-personal-antoniop-9100,170.26.106.206
beta-gvc-personal-antoniop-9100b,170.26.106.41
beta-gvc-personal-antoniop-office,170.26.107.192
```

I need to compare these two files and get only the IP Address in another text file called IPOnly.txt

IPOnly.txt has only the IP's common to both Host.txt and HostandIp.txt as follows:

```
170.16.75.101
170.26.114.242
170.26.108.224
170.26.108.95
```

It can be done in JAVA using HASH MAP. Is there a Linux Command to do this ? Please Help!

答:
```<code>awk -F, '
  NR == FNR {host[$1]++; next}
  ($1 in host) {print $2}
' Host.txt HostandIP.txt > IPOnly.txt
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is the problem.

Host.txt file has only Hostnames as follows:

GVC-CH-ZRH-BRA-5H81-PELE
GVC-US-NYC-9TH-4C101-MEDROOM
GVC-US-NYC-9TH-4C101E-EXTRA
GVC-US-NYC-9TH-5E117-STUDIO54

2.HosandIp.txt has the Hostnames and Ip as follows (HostandIP has hostname,IP Address Note the Comma (,)):

GVC-CH-ZRH-BRA-5H81-PELE,170.16.75.101
GVC-US-NYC-9TH-4C101-MEDROOM,170.26.114.242
GVC-US-NYC-9TH-4C101E-EXTRA,170.26.108.224
GVC-US-NYC-9TH-5E117-STUDIO54,170.26.108.95
beta-gvc-personal-antoniop-526,170.26.107.180
beta-gvc-personal-antoniop-9100,170.26.106.206
beta-gvc-personal-antoniop-9100b,170.26.106.41
beta-gvc-personal-antoniop-office,170.26.107.192

I need to compare these two files and get only the IP Address in another text file called IPOnly.txt

IPOnly.txt has only the IP's common to both Host.txt and HostandIp.txt as follows:

170.16.75.101
170.26.114.242
170.26.108.224
170.26.108.95

It can be done in JAVA using HASH MAP. Is there a Linux Command to do this ? Please Help!


问:
How do you call a content view function from an instantiated class in Swift?
Inside my ContentView, I instantiate a class I made called timer. When the timer's "timerText" hits "0:00", I want the timer to call a function in the ContentView to edit the view with information that is not accessible from the timer. However, I don't know how to call a function from the ContentView from inside this timer class. Is this even possible?

If this isn't possible, I could achieve the same goal by making a "timerText" variable in the ContentView that is always synced with the timer object's "timerText" variable. That way, when the ContentView's "timerText" is "0:00", I can just call the function like normal because I'm already "inside" the ContentView. However, I don't know how to have a variable synced together across two different classes. Is there a way to do this?

答:
If I understood correctly what you want to achieve, this solution will help you:

Use Combine and make your timerText @Published;

In ContentView use .onReceive func at any View and call your function, if needed.

Here is simple code example:

import SwiftUI
import Combine

final class SpecialTimer: ObservableObject {

    @Published var timerText = "0:01"

    func resetTimer() {
        timerText = "0:00"
    }

}

struct SpecialTimerView: View {

    @EnvironmentObject var timer: SpecialTimer
    @State private var didEditedSpecialInfo = false

    var body: some View {

        VStack {

            Text(timer.timerText)
                .onReceive(timer.$timerText) { timerText in
                    guard timerText == "0:00" else { return }
                    self.whenTimerResets()
            }

            Button(action: {self.timer.resetTimer()} ) {
                Text("reset timer!")
            }

            Text("timer did reset")
                .opacity(didEditedSpecialInfo ? 1 : 0)

        }

    }

    private func whenTimerResets() {
        print("edit the view with information that is not accessible from the timer")
        didEditedSpecialInfo = true

    }

}

struct SpecialTimerView_Previews: PreviewProvider {
    static var previews: some View {
        SpecialTimerView()
            .environmentObject(SpecialTimer())
    }
}

```


问:
autoResizeColumns Takes Too Long to Process
I spent a couple of hours trying to figure out why my script takes so long to process. I ended up realizing the culprit was autoResizeColumns(). The more rows on a sheet the longer it takes. It takes about a minute for about 6K rows. In my case I had to call it twice on two different sheets, both about 6K rows.

Is there really no other option? Doing this action manually on a sheet using the mouse takes significantly less time. So my question to you is what methods are you using to resize columns automatically?

答: Sheets api is usually faster and can be accessed from apps script through advanced Google services</p>


问:
Gradle sync failed with Android Studio 3.1: Uninitialized object exists on backward branch 70
After Updating Android Studio from 3.0 to 3.1 My project gradle syncing failed with the following error.  </p>

```<code>Gradle sync failed: Uninitialized object exists on backward branch 70 Exception Details: Location:
com/android/build/gradle/tasks/BuildArtifactReportTask.newArtifact(Lcom/android/build/api/artifact/BuildableArtifact;)
Lcom/android/build/gradle/tasks/BuildArtifactReportTask$BuildableArtifactData;
</code>```

答:
Android Studio:  3.5.3

gradle plugin:   3.5.3

gradle:          5.4.1

platform:        Mac OS Mojave 10.14.6 (18G103)

I had done this:Project Structure -> SDK Location -> Select "Use embedded JDK(recommended)"
but it still not working.

when I read this article,

you can add a property at gradle.properies:

org.gradle.java.home=(path to JDK home)

it works!

Body:
After Updating Android Studio from 3.0 to 3.1 My project gradle syncing failed with the following error.

Gradle sync failed: Uninitialized object exists on backward branch 70 Exception Details: Location:
com/android/build/gradle/tasks/BuildArtifactReportTask.newArtifact(Lcom/android/build/api/artifact/BuildableArtifact;)
Lcom/android/build/gradle/tasks/BuildArtifactReportTask$BuildableArtifactData;


问:
Post form not submitting inside while loop table php
I am trying to submit this form but it only submits the hidden input field. I can't understand why. It was working before. </p>

```<code>while ($row = mysqli_fetch_array($gettimesheets)) {
    $date = $row['Date'];
    $date = date('d-m-Y', strtotime($date));
    $teachername = $row['StaffName'];
    $teacherid = $row['StaffID'];
    $starttime = $row['StartTime'];
    $endtime = $row['EndTime'];
    $totalhours = $row['TotalHours'];
    $timesheetid = $row['id'];

    ?>
    <tr>
        <form action="edittimesheet.php" method="post">
            <td class="text-center"><?php echo $date; ?></td>
            <td><?php echo $teachername; ?></td>
            <td><?php echo $teacherid; ?></td>
            <td><input type="time" name="starttime" class="form-control" value="<?php echo $starttime; ?>"></td>
            <td><input type="time" name="endtime" class="form-control" value="<?php echo $endtime; ?>">
                <input type="text" name="timesheetid" value="<?php echo $timesheetid; ?>" hidden></td>
            <td class="text-right">
                <input type="submit" class="btn btn-success" value="Edit"/>
                <a href="deletetimesheet.php?id=<?php echo $timesheetid; ?>"
                   class="btn btn-simple btn-danger">Delete</a>
            </td>
        </form>
    </tr>

    <?php
}
</code>```

答:
It's odd but putting parts of a table inside a form is not a good idea. Actually browsers in such situation are confused! You can put your whole form inside a cell (td).

For more information Check this

Body:
I am trying to submit this form but it only submits the hidden input field. I can't understand why. It was working before.

while ($row = mysqli_fetch_array($gettimesheets)) {
    $date = $row['Date'];
    $date = date('d-m-Y', strtotime($date));
    $teachername = $row['StaffName'];
    $teacherid = $row['StaffID'];
    $starttime = $row['StartTime'];
    $endtime = $row['EndTime'];
    $totalhours = $row['TotalHours'];
    $timesheetid = $row['id'];

    ?>

        <form action="edittimesheet.php" method="post">
            <?php echo $date; ?>
            <?php echo $teachername; ?>
            <?php echo $teacherid; ?>
            <input type="time" name="starttime" class="form-control" value="<?php echo $starttime; ?>">
            <input type="time" name="endtime" class="form-control" value="<?php echo $endtime; ?>">
                <input type="text" name="timesheetid" value="<?php echo $timesheetid; ?>" hidden>

                <input type="submit" class="btn btn-success" value="Edit"/>
                <a href="deletetimesheet.php?id=<?php echo $timesheetid; ?>"
                   class="btn btn-simple btn-danger">Delete

        </form>

    <?php
}


问:
jQuery .attribute for p tags in HTML
I want to add an attribute of 'data-class' to every paragraph in an HTML element, the 'data-class' should be set to the value of the class. I have used .attr but not able to assign the same value.
There are currently 9 paragraphs on the page with a numbered class of

p1, p2, p3 etc...

How would I just set the data-class to the same p-tag as well?

I have jQuery like this so far:

```<code>$('p').attr('data-class', 'p'}
</code>```

答:
Try this</p>

```<code>var data_class = "value";

$("p").each(function(index) {
    $(this).setAttribute("data-class", data_class);
});
</code>```

Title: jQuery .attribute for p tags in HTML

Body:
I want to add an attribute of 'data-class' to every paragraph in an HTML element, the 'data-class' should be set to the value of the class. I have used .attr but not able to assign the same value.
There are currently 9 paragraphs on the page with a numbered class of

p1, p2, p3 etc...

How would I just set the data-class to the same p-tag as well?

I have jQuery like this so far:

$('p').attr('data-class', 'p'}

Body:
Try this

var data_class = "value";

$("p").each(function(index) {
    $(this).setAttribute("data-class", data_class);
});


问:
Password protect Open XML Wordprocessing Document
I need to add basic password protection to an Open XML Wordprocessing document. I can either use the COM interface, which is very slow when I have a large number of documents to process; or I can put the data directly in the docx file under <w:settings> <w:documentProtection> which is very fast. However, looking at the requirements to encrypt the password looks like it will take hours of programming. Does anyone have this algorithm already coded? I'm coding in C#.

答: I had something similar to @Brij and was hoping to get the algorithm for the password hash. I subsequently found some incomplete code on the MSDN forum, and also discovered that the Word 2007 password protection is very easily got around. So for now I'm just putting a random hash and salt in so no one, including me, knows the actual password. That's enough effort to prevent accidental changing; and given it's impossible to prevent intentional changing, I'm not going to make it any more secure.</p>

ContentLicense: CC BY-SA 2.5


问:
Is there a longitude or latitude function in HTML
I’m a beginner so the answer might be fairly obvious, see his creation on https://codpen.io/johan-tirholm/pen/JjoXJNg
I know it is not a problem with the website itself, and I don’t think there is a pre-existing longitude and latitude function. If that’s the case, I don’t know how to make those functions due to lack of experience. Thank you for your help.</p>

答:
@DecDDM

Please try this code,To use of longitude or latitude function in HTML

```<code><script>
var x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>
</code>```

I hope above code will be useful for you.

Thank you.

Body:
@DecDDM

Please try this code,To use of longitude or latitude function in HTML

<script>
var x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>

I hope above code will be useful for you.

Thank you.


问:
problem with date formate in motion chart in django
Using Google motion chart for generating graph in django. i came accross with date format issue while converting from django t0 JavaScript date form new Date(2011, 01, 01).

motion chart link :http://code.google.com/apis/chart/interactive/docs/gallery/motionchart.html

below is the code how did :

```<code>ml =[]
for i in data:
   year = m['month'].strftime('%Y')
   month = m['month'].strftime('%m')
   day = m['month'].strftime('%d')
   check = 'new Date(%s, %s, %s)' % (year, month, day)
   ml.append([str(m[selected_mode]),check, m['total']])
</code>```

ml returned a list

i have this output in hmtl :

```<code><script type="text/javascript">
      google.load('visualization', '1', {'packages':['motionchart']});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = new google.visualization.DataTable();

        data.addColumn('string', 'Mode');
        data.addColumn('date', 'Date');
        data.addColumn('number', 'Total');
        data.addRows([["sl", "new Date(2011, 01, 01)", 31], ["kl", "new Date(2011, 02, 01)", 13], ["ml", "new Date(2011, 01, 01)", 51], ["rl", "new Date(2011, 03, 01)", 30], ["ml", "new Date(2011, 02, 01)", 22], ["sl", "new Date(2011, 03, 01)", 30], ["kl", "new Date(2011, 03, 01)", 28], ["sl", "new Date(2011, 02, 01)", 24], ["rl", "new Date(2011, 01, 01)", 17], ["rl", "new Date(2011, 02, 01)", 4], ["kl", "new Date(2011, 01, 01)", 5], ["sl", "new Date(2011, 04, 01)", 1]]);
        var chart = new google.visualization.MotionChart(document.getElementById('chart_div'));
        chart.draw(data, {width: 600, height:300});
      }
    </script>
</code>```

here "new Date(2011, 01, 01)" takes as string but it should be in new Date(2011, 01, 01) , can you please help me how to make it has new Date(2011, 01, 01)

"new Date(2011, 01, 01)" ==> new Date(2011, 01, 01)

Below is the template

```<code>    {% extends "newbase.html" %}
    {% block extra_js %}
   <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
          google.load('visualization', '1', {'packages':['motionchart']});
          google.setOnLoadCallback(drawChart);
          function drawChart() {
            var data = new google.visualization.DataTable();

            data.addColumn('string', 'Mode');
            data.addColumn('date', 'Date');
            data.addColumn('number', 'Total');
            data.addRows({{ m1|safe }});
            var chart = new google.visualization.MotionChart(document.getElementById('chart_div'));
            chart.draw(data, {width: 600, height:300});
          }
        </script>
    {% endblock %}
    {% block content %}
    <div id="chart_div" style="width: 600px; height: 300px;"></div>
    </center>
    {% endblock %}
</code>```

答:
```<code>dataTable.addRows( [
{% for d in data %}
["{{d.id}}","{{d.description|escapejs}}",new Date({{d.StartDate|date:"Y"}},{{dL.StartDate|date:"n"}}-1,{{d.StartDate|date:"j"}}),new Date()],
{% endfor %}
]);

Google Chart takes only Date() Object. Hence implemented as above and it is working for me.
</code>```

Body:
Using Google motion chart for generating graph in django. i came accross with date format issue while converting from django t0 JavaScript date form new Date(2011, 01, 01).

motion chart link :http://code.google.com/apis/chart/interactive/docs/gallery/motionchart.html

below is the code how did :

ml =[]
for i in data:
   year = m['month'].strftime('%Y')
   month = m['month'].strftime('%m')
   day = m['month'].strftime('%d')
   check = 'new Date(%s, %s, %s)' % (year, month, day)
   ml.append([str(m[selected_mode]),check, m['total']])

ml returned a list

i have this output in hmtl :

here "new Date(2011, 01, 01)" takes as string but it should be in new Date(2011, 01, 01) , can you please help me how to make it has new Date(2011, 01, 01)

"new Date(2011, 01, 01)" ==> new Date(2011, 01, 01)

Below is the template

    {% extends "newbase.html" %}
    {% block extra_js %}

    {% endblock %}
    {% block content %}

    {% endblock %}


问:
Android application loses state after launching another intent
So I have the following:

A Common class that many of my Activities access in my android application, via setting the class in my manifest:

```<code><application android:name="com.dev.games.phraseparty.Common"... />
</code>```

Now, within this class I have several objects that are constructed to preserve application state and common services to perform applications that are constructed in the Common constructor

ie

```<code>GameStateVO gameState;

public Common()
{
    gameState = new GameStateVO();
}
</code>```

My problem is that my Activity has an Admob ad. When the user clicks on the ad, it calls the webbrowser intent to open the ad URL in a webbrowser.

Now, when I click back from the webbrowser launched by admob, it takes me back to the caling activity and the OnCreate method is called.

This activity then gets a null pointer exception because it will do something like:

```<code>public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Common common = this.getApplication();

//null pointer here since the game state VO is null since the Common has lost its state.
int score = common.getGameState().getScore();

}
</code>```

答: You might want to look into implementing the onSaveInstanceState method: this lets you store any relevant information before it gets killed off. See http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState%28android.os.Bundle%29 for the actual call you need to implement, and Saving Android Activity state using Save Instance State for a quite excellent example.

Body:
So I have the following:

A Common class that many of my Activities access in my android application, via setting the class in my manifest:

<application android:name="com.dev.games.phraseparty.Common"... />

Now, within this class I have several objects that are constructed to preserve application state and common services to perform applications that are constructed in the Common constructor

ie

GameStateVO gameState;

public Common()
{
    gameState = new GameStateVO();
}

My problem is that my Activity has an Admob ad. When the user clicks on the ad, it calls the webbrowser intent to open the ad URL in a webbrowser.

Now, when I click back from the webbrowser launched by admob, it takes me back to the caling activity and the OnCreate method is called.

This activity then gets a null pointer exception because it will do something like:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Common common = this.getApplication();

//null pointer here since the game state VO is null since the Common has lost its state.
int score = common.getGameState().getScore();

}


问:
Utility to convert List to Map
We can convert a list to map using the following

```<code>List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) {
  map.put(i.getKey(),i);
}
</code>```

Is there is a java or apache common utility which does in a single line? Some times the key should be sequential integer, sometimes the key is the value itself (taking care of uniqueness).

答:
You can use the toMap() collector with a stream:

```<code>Map<Key, Item> map = list.stream().collect(Collectors.toMap(Item::getKey, i -> i));
</code>```

Title: Utility to convert List to Map

Body:
We can convert a list to map using the following

List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) {
  map.put(i.getKey(),i);
}

Is there is a java or apache common utility which does in a single line? Some times the key should be sequential integer, sometimes the key is the value itself (taking care of uniqueness).

Body:
You can use the toMap() collector with a stream:

Map<Key, Item> map = list.stream().collect(Collectors.toMap(Item::getKey, i -> i));


问:
Android Docx4J Gradle: Duplicate class org.slf4j despite excluding it
I am trying to use the Docx4j library in order to read in the contents of MS Word files selected by the user (I am trying to install it through this example: https://github.com/plutext/Docx4j4Android4). However, I receive the following error when I read in a MS Word file (I didn't include all the errors, but the duplicate classes all belong to org.slf4j.*):

```<code>Duplicate class org.slf4j.ILoggerFactory found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
Duplicate class org.slf4j.IMarkerFactory found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
Duplicate class org.slf4j.Logger found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
........
</code>```

This seems strange, since in my build.gradle, I explicity exclude org.sl4j when implementing the docx4j library.

Below is my build.gradle code:

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        // Comment the following in order to see actual errors, not unhelpful "too many errors"!
//        preDexLibraries = false
        additionalParameters=['--core-library']
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module")
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'io.github.java-diff-utils:java-diff-utils:4.5'
    // For developers using AndroidX in their applications
    implementation 'pub.devrel:easypermissions:3.0.0'
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    //implementation files('libs/commons-text-1.2.jar')
    implementation files('libs/commons-lang3-3.7.jar')
    //Thanks for using https://jar-download.com
    implementation 'org.webjars.bowergithub.telecomsante:pdf-viewer:2.2.0'
    implementation 'com.tom_roush:pdfbox-android:1.8.10.1'
    //implementation files('libs/commons-logging-1.2.jar')
    implementation 'com.bskim:maxheightscrollview:1.0.0@aar'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    // Docx4j is the library used to read Word documents
    // https://mvnrepository.com/artifact/org.docx4j/docx4j
    implementation files('libs/commons-lang3-3.7.jar')
    implementation files('libs/commons-text-1.2.jar')

    //implementationtestCompile 'junit:junit:4.12'
    implementation 'javax.xml.bind:jaxb-api:2.2.12'
    implementation 'javax.xml.stream:stax-api:1.0-2'
    implementation 'com.fasterxml:aalto-xml:1.0.0'
    //compile 'org.codehaus.woodstox:stax2-api:4.0.0'
    implementation files('libs/awt-bastardised-17v8.jar')
    implementation files('libs/slf4j-android-1.6.1-RC1.jar')
    implementation files('libs/activation.jar')
    implementation files('libs/additionnal.jar')
    implementation files('libs/jaxb-core-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/jaxb-runtime-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/istack-commons-runtime-3.0.4-SNAPSHOT.jar')
    // with org.slf4j removed
    implementation('org.docx4j:docx4j:3.3.0') {
        ['org.apache.commons', 'commons-logging', 'org.sl4j'].each {
            exclude group: "$it"
        }
    }

}
</code>```

And below is a screenshot of the library jar files I have:

答:
Add the following lines in app's build.gradle</p>

```<code>configurations {
compile.exclude group: 'org.slf4j', module: 'slf4j-log4j12'
}

configurations.all {
    resolutionStrategy {
        force 'org.slf4j:slf4j-log4j12:1.7.25'
    }
}
</code>```

Body:
I am trying to use the Docx4j library in order to read in the contents of MS Word files selected by the user (I am trying to install it through this example: https://github.com/plutext/Docx4j4Android4). However, I receive the following error when I read in a MS Word file (I didn't include all the errors, but the duplicate classes all belong to org.slf4j.*):

Duplicate class org.slf4j.ILoggerFactory found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
Duplicate class org.slf4j.IMarkerFactory found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
Duplicate class org.slf4j.Logger found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
........

This seems strange, since in my build.gradle, I explicity exclude org.sl4j when implementing the docx4j library.

Below is my build.gradle code:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        // Comment the following in order to see actual errors, not unhelpful "too many errors"!
//        preDexLibraries = false
        additionalParameters=['--core-library']
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module")
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'io.github.java-diff-utils:java-diff-utils:4.5'
    // For developers using AndroidX in their applications
    implementation 'pub.devrel:easypermissions:3.0.0'
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    //implementation files('libs/commons-text-1.2.jar')
    implementation files('libs/commons-lang3-3.7.jar')
    //Thanks for using https://jar-download.com
    implementation 'org.webjars.bowergithub.telecomsante:pdf-viewer:2.2.0'
    implementation 'com.tom_roush:pdfbox-android:1.8.10.1'
    //implementation files('libs/commons-logging-1.2.jar')
    implementation 'com.bskim:maxheightscrollview:1.0.0@aar'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    // Docx4j is the library used to read Word documents
    // https://mvnrepository.com/artifact/org.docx4j/docx4j
    implementation files('libs/commons-lang3-3.7.jar')
    implementation files('libs/commons-text-1.2.jar')

    //implementationtestCompile 'junit:junit:4.12'
    implementation 'javax.xml.bind:jaxb-api:2.2.12'
    implementation 'javax.xml.stream:stax-api:1.0-2'
    implementation 'com.fasterxml:aalto-xml:1.0.0'
    //compile 'org.codehaus.woodstox:stax2-api:4.0.0'
    implementation files('libs/awt-bastardised-17v8.jar')
    implementation files('libs/slf4j-android-1.6.1-RC1.jar')
    implementation files('libs/activation.jar')
    implementation files('libs/additionnal.jar')
    implementation files('libs/jaxb-core-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/jaxb-runtime-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/istack-commons-runtime-3.0.4-SNAPSHOT.jar')
    // with org.slf4j removed
    implementation('org.docx4j:docx4j:3.3.0') {
        ['org.apache.commons', 'commons-logging', 'org.sl4j'].each {
            exclude group: "$it"
        }
    }

}

And below is a screenshot of the library jar files I have:

Body:
Add the following lines in app's build.gradle

configurations {
compile.exclude group: 'org.slf4j', module: 'slf4j-log4j12'
}

configurations.all {
    resolutionStrategy {
        force 'org.slf4j:slf4j-log4j12:1.7.25'
    }
}


问:
Angular 8: access the assets folder when running ng build --prod --base-href './project1'
My client want me to deploy multiple projects on the same ngnix server with the following configuration.

```<code>location /project1/ {
    alias /usr/local/var/www/project1/;
    try_files $uri$args $uri$args/ /project1/index.html;
}
</code>```

In the above configuration I could not access the assets folder as it's in the project1 folder and I try to access it from the root of the domain example src:

url('/assets/fonts/texta/Texta-Regular/Texta-Regular.eot')

When I change the path with src: url('./assets/fonts/texta/Texta-Regular/Texta-Regular.eot') I'm getting following problem when building the production build

ERROR in ./src/styles.scss Module build failed (from
  ./node_modules/mini-css-extract-plugin/dist/loader.js): ModuleError:
  Module Error (from ./node_modules/postcss-loader/src/index.js):
  (Emitted value instead of an instance of Error) CssSyntaxError:
  /Users/Desktop/personal/projects/example/src/styles.scss:10115:13:
  Can't resolve
  './assets/fonts/texta/Texta-Regular/Texta-Regular.eot%3F' in
  '/Users/Desktop/personal/projects/example/src'

答:
You can't use absolute paths starting from "/" so you have 2 options:

1- Using relative paths (with "../" to go back up the hierarchy). This one is a bit messy but easy to do.

2- Define your assets folder in the compilerOptions of your tsconfig.json as follows:

```<code>"compilerOptions": {
"baseUrl": ".",
"paths": {
  "@assets/*": ["./src/assets/*"],
}
}
</code>```

Then you can use "@assets/" in your Url. Take note of the baseUrl and assets url and change it accordingly based on your project structure.

Hope this helps.

Body:
My client want me to deploy multiple projects on the same ngnix server with the following configuration.

location /project1/ {
    alias /usr/local/var/www/project1/;
    try_files $uri$args $uri$args/ /project1/index.html;
}

In the above configuration I could not access the assets folder as it's in the project1 folder and I try to access it from the root of the domain example src:

url('/assets/fonts/texta/Texta-Regular/Texta-Regular.eot')

When I change the path with src: url('./assets/fonts/texta/Texta-Regular/Texta-Regular.eot') I'm getting following problem when building the production build

ERROR in ./src/styles.scss Module build failed (from
  ./node_modules/mini-css-extract-plugin/dist/loader.js): ModuleError:
  Module Error (from ./node_modules/postcss-loader/src/index.js):
  (Emitted value instead of an instance of Error) CssSyntaxError:
  /Users/Desktop/personal/projects/example/src/styles.scss:10115:13:
  Can't resolve
  './assets/fonts/texta/Texta-Regular/Texta-Regular.eot%3F' in
  '/Users/Desktop/personal/projects/example/src'

Body:
You can't use absolute paths starting from "/" so you have 2 options:

1- Using relative paths (with "../" to go back up the hierarchy). This one is a bit messy but easy to do.

2- Define your assets folder in the compilerOptions of your tsconfig.json as follows:

"compilerOptions": {
"baseUrl": ".",
"paths": {
  "@assets/*": ["./src/assets/*"],
}
}

Then you can use "@assets/" in your Url. Take note of the baseUrl and assets url and change it accordingly based on your project structure.

Hope this helps.


问:
How to handle state using Redux with periodical updates and React Hooks?

My Use Case

I am just starting with React (Native) with Hooks and Redux and have some issues understanding some parts of the state update concept for my use case. I am currently working on a React Native App that should update data every full minute. So if the user enters the app at say 11h:31m:27s,

the initial state should be shown, then

a setTimeout handles the first update with the offset to reach the full minute (in this case 33s to reach 11h:32m:00s)

a setInterval handles the minutely update of the data from now on.

My Issue

Currently, with the below code the console.log("Reducer Fires!") inside the reducers.js file is fired increasingly more with every new minute (e.g. only once in the first minute, then two times in the second minute and so on). So I feel that I am still doing something wrong with how I handle the state of my data together with the setInterval() and setTimeout() logic. Could somebody review my code below and point me to the errors I am doing?

My Code (so far)

some dummy data:

```<code>export const DATA = [
    {"id": 1, "myAttr": 0},
    {"id": 2, "myAttr": 4},
    {"id": 3, "myAttr": 8},
    {"id": 4, "myAttr": 12},
]
</code>```

the App.js file with the redux store:

```<code>import React from 'react';
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";
import { View } from 'react-native';

// Components
import MyComponent from "./components/MyComponent";
import dataReducer from "./store/reducers";

//Create Redux store
const rootReducer = combineReducers({
  mydata: dataReducer
});

const store = createStore(rootReducer);

export default function App() {

  return (
    <Provider store={store} >
      <View>
        <MyComponent />
      </View>
    </Provider>
  );
}
</code>```

the actions.js file storing my Redux action:

```<code>//Action to update the data
export const UPDATE_DATA = "UPDATE_DATA";

export const updateData = () => {
    return { type: UPDATE_DATA }
}
</code>```

the reducers.js file to store the reducers:

```<code>import { DATA } from "../data/data";
import { UPDATE_DATA } from "./actions";

// Initial state when app launches
const initState = {
    data: DATA
}

const dataReducer = (state = initState, action) => {
    switch (action.type) {
        case UPDATE_DATA:
            //Update an attribute in each object of the data array

            const updatedData = state.data.map((i) => {
                const newMyAttr = i.myAttr + 1;
                return { ...i, myAttr: newMyAttr }
            }
            )

            console.log("Reducer Fires!");
            return { ...state, data: updatedData }

        default:
            return state;
    }
};

export default dataReducer;
</code>```

the component where I am trying to update the state:

```<code>import React, { useEffect, useCallback } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Text, View } from 'react-native';

const MyComponent = (props) => {
    const myData = useSelector(state => state.mydata.data);

    let start = new Date();
    const fullMinuteOffset = (60 - start.getSeconds()) * 1000;

    const dispatch = useDispatch();

    const saveData = useCallback(() => {
        dispatch(updateData())
    }, [dispatch]);

    useEffect(() => {
        const timer = setTimeout(() => {
            saveData()
            const interval = setInterval(() => {
                saveData()
            }, 60000)

            return () => clearInterval(interval);
        }, fullMinuteOffset);

        return () => clearTimeout(timer);
    }, [saveData, fullMinuteOffset]);

    return(
        <View>
            <Text>{myData[0].myAttr}</Text>
        </View>
    );
};

export default MyComponent;

</code>```

答: What happens if you change the useEffect dependencies to just this: [saveTime, fullMinuteOffset] -> to this []. It seems like everytime that component updates that useEffect call might be registering more intervals

Body:
My Use Case

I am just starting with React (Native) with Hooks and Redux and have some issues understanding some parts of the state update concept for my use case. I am currently working on a React Native App that should update data every full minute. So if the user enters the app at say 11h:31m:27s,

the initial state should be shown, then

a setTimeout handles the first update with the offset to reach the full minute (in this case 33s to reach 11h:32m:00s)

a setInterval handles the minutely update of the data from now on.

My Issue

Currently, with the below code the console.log("Reducer Fires!") inside the reducers.js file is fired increasingly more with every new minute (e.g. only once in the first minute, then two times in the second minute and so on). So I feel that I am still doing something wrong with how I handle the state of my data together with the setInterval() and setTimeout() logic. Could somebody review my code below and point me to the errors I am doing?

My Code (so far)

some dummy data:

export const DATA = [
    {"id": 1, "myAttr": 0},
    {"id": 2, "myAttr": 4},
    {"id": 3, "myAttr": 8},
    {"id": 4, "myAttr": 12},
]

the App.js file with the redux store:

import React from 'react';
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";
import { View } from 'react-native';

// Components
import MyComponent from "./components/MyComponent";
import dataReducer from "./store/reducers";

//Create Redux store
const rootReducer = combineReducers({
  mydata: dataReducer
});

const store = createStore(rootReducer);

export default function App() {

  return (
    <Provider store={store} >
      <View>
        <MyComponent />
      </View>
    </Provider>
  );
}

the actions.js file storing my Redux action:

//Action to update the data
export const UPDATE_DATA = "UPDATE_DATA";

export const updateData = () => {
    return { type: UPDATE_DATA }
}

the reducers.js file to store the reducers:

import { DATA } from "../data/data";
import { UPDATE_DATA } from "./actions";

// Initial state when app launches
const initState = {
    data: DATA
}

const dataReducer = (state = initState, action) => {
    switch (action.type) {
        case UPDATE_DATA:
            //Update an attribute in each object of the data array

            const updatedData = state.data.map((i) => {
                const newMyAttr = i.myAttr + 1;
                return { ...i, myAttr: newMyAttr }
            }
            )

            console.log("Reducer Fires!");
            return { ...state, data: updatedData }

        default:
            return state;
    }
};

export default dataReducer;

the component where I am trying to update the state:

import React, { useEffect, useCallback } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Text, View } from 'react-native';

const MyComponent = (props) => {
    const myData = useSelector(state => state.mydata.data);

    let start = new Date();
    const fullMinuteOffset = (60 - start.getSeconds()) * 1000;

    const dispatch = useDispatch();

    const saveData = useCallback(() => {
        dispatch(updateData())
    }, [dispatch]);

    useEffect(() => {
        const timer = setTimeout(() => {
            saveData()
            const interval = setInterval(() => {
                saveData()
            }, 60000)

            return () => clearInterval(interval);
        }, fullMinuteOffset);

        return () => clearTimeout(timer);
    }, [saveData, fullMinuteOffset]);

    return(
        <View>
            <Text>{myData[0].myAttr}</Text>
        </View>
    );
};

export default MyComponent;


问:
Deleting data that all users use but only for one user in Cloud Firestore
I am trying to structure my data such that when someone adds a new product to the database, all users receive the new product in their list and therefore the new product appears on their screen.
But if a user decides to delete that product, they can delete it but only for themselves. Is there a Cloud Firestore sorting/ordering/filtering that I should be using to accomplish this?

I thought I could use something like the following:

```<code>final theProduct = Provider.of<Products>(context);

products = await firestore.collection('products').getDocuments()

for (product in products.documents) {
await firestore.collection('products').add({
'nameOfProduct': theProduct.nameOfProduct
});
}
</code>```

But I get a document property error.

Maybe I need to go in one more collection and then try something? But I also need to be able to retrieve the data back using the userID of the signed in user..

Any hints/helpful links would be greatly appreciated.

So I think what I want to do is iterate through all documents within a collection and then document().collection('').add() something to each of their collection. Hopefully that sheds some more light on my problem.

答:
Question : a user decides to delete that product, they can delete it but only for themselves

Answer: U can create list in user profile section where u can have all the product document ids & u can use that document id to fetch particular product details & when user click on delete button u can remove that particular document id from there collection

Im not sure what r u doing with sample code over there.

If u want to add data to database then use :

```<code>await Firestore().collection('Products').add({
  'nameOfProduct': theProduct.nameOfProduct,
});
</code>```

this will generate document random id for your product.

To get data from particular id use :

```<code>DocumentSnapshot documentSnapshot = await Firestore().collection('Products').document('document').get();
</code>```

then u can use that document snapshot to get data for particular key e.g.

```<code>documentSnapshot.data['Product Name']
</code>```

Body:
I am trying to structure my data such that when someone adds a new product to the database, all users receive the new product in their list and therefore the new product appears on their screen.
But if a user decides to delete that product, they can delete it but only for themselves. Is there a Cloud Firestore sorting/ordering/filtering that I should be using to accomplish this?

I thought I could use something like the following:

final theProduct = Provider.of<Products>(context);

products = await firestore.collection('products').getDocuments()

for (product in products.documents) {
await firestore.collection('products').add({
'nameOfProduct': theProduct.nameOfProduct
});
}

But I get a document property error.

Maybe I need to go in one more collection and then try something? But I also need to be able to retrieve the data back using the userID of the signed in user..

Any hints/helpful links would be greatly appreciated.

So I think what I want to do is iterate through all documents within a collection and then document().collection('').add() something to each of their collection. Hopefully that sheds some more light on my problem.

Body:
Question : a user decides to delete that product, they can delete it but only for themselves

Answer: U can create list in user profile section where u can have all the product document ids & u can use that document id to fetch particular product details & when user click on delete button u can remove that particular document id from there collection

Im not sure what r u doing with sample code over there.

If u want to add data to database then use :

await Firestore().collection('Products').add({
  'nameOfProduct': theProduct.nameOfProduct,
});

this will generate document random id for your product.

To get data from particular id use :

DocumentSnapshot documentSnapshot = await Firestore().collection('Products').document('document').get();

then u can use that document snapshot to get data for particular key e.g.

documentSnapshot.data['Product Name']


问:
SQL Select where values in List<string>
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

```<code>Select * from Table where RecordID in (RecordIDList)
</code>```

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

答: If you use dynamic SQL, you can send the content of the parentheses as a literal comma-separated list. Otherwise you can use an XML variable for sending multiple values. See http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm</p>

OwnerDisplayName: JoelHess

Title: SQL Select where values in List<string>

Body:
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

Select * from Table where RecordID in (RecordIDList)

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

LastEditorDisplayName: Andrew Hare

OwnerDisplayName: Manu


问:
An exception has been thrown during the rendering of a template ("Asset manifest file "../manifest.json" does not exist.")
I cloned a Symfony 4 web application (which work on the server) to a fresh installed VM, but after installing all the packages, I get this error message :

An exception has been thrown during the rendering of a template
  ("Asset manifest file
  "/var/www/html/kyc/htdocs/public/build/manifest.json" does not
  exist.").

I tried this solution without success :

Symfony Error: "An exception has been thrown during the rendering of a template"

Any idea ?

Thank you.

答:
if you have something like this <link href="{{ asset('css/mystyle.css') }}" rel="stylesheet"/> then remove the asset() method and leave the contents exposed like this <link href="{{ 'css/mystyle.css' }}" rel="stylesheet"/>

I assume you're using webpack to manage your web assets


问:
How to access XML file from Azure Data Lake Gen2 and transform it into data-frame in Azure Databricks?
we need to access the XML file located in Azure Data Lake Gen2 and Transform it into a dataframe as shown below.

Sample XML data:

```<code><SOAP-ENV:Envelope
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

<SOAP-ENV:Body>
           <ns2:getProjectsResponse
               xmlns:ns2="http://www.logic8.com/eq/webservices/generated">
               <ns2:Project>
                   <ns2:fileName>P10001</ns2:fileName>
                   <ns2:alias>project1</ns2:alias>
               </ns2:Project>
               <ns2:Project>
                   <ns2:fileName>P10002</ns2:fileName>
                   <ns2:alias>project2</ns2:alias>
               </ns2:Project>
       <ns2:Project>
                   <ns2:fileName>P10003</ns2:fileName>
                   <ns2:alias>project3</ns2:alias>
               </ns2:Project>
           </ns2:getProjectsResponse>
       </SOAP-ENV:Body>
   </SOAP-ENV:Envelope>
</code>```

Expected Dataframe output:

Can anyone help me on this.

答:
Firstly, you need to learn read data from Azure Data Lake Gen2 to Azure databricks.

There are many tutorials you can learn from:

Databricks: Importing data from a Blob storage. This blogpost is about importing data from a Blob storage to Azure databricks.

Databricks Azure Blob Storage: This article explains how to
access Azure Blob storage by mounting storage using DBFS or directly
using APIs.

Secondly, about the xml data type, you need to use the use the databricks spark-xml library which @Axel R has provided in comment.

Import the spark-xml library into your workspace
https://docs.databricks.com/user-guide/libraries.html#create-a-library
(search spark-xml in the maven/spark package section and import it)

Attach the library to your cluster
https://docs.databricks.com/user-guide/libraries.html#attach-a-library-to-a-cluster

Use the following code in your notebook to read the xml file, where
"note" is the root of the xml file.

xmldata = spark.read.format('xml').option("rootTag","note").load('dbfs:/mnt/mydatafolder/xmls/note.xml')

Please reference：How can I read a XML file Azure Databricks Spark.

Combine these documents, I think you can figure out you problem. I don't know much about Azure databricks, I'm sorry that I can't test for you.

Hope this helps.

Body:
we need to access the XML file located in Azure Data Lake Gen2 and Transform it into a dataframe as shown below.

Sample XML data:

<SOAP-ENV:Envelope
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

<SOAP-ENV:Body>
           <ns2:getProjectsResponse
               xmlns:ns2="http://www.logic8.com/eq/webservices/generated">
               <ns2:Project>
                   <ns2:fileName>P10001</ns2:fileName>
                   <ns2:alias>project1</ns2:alias>
               </ns2:Project>
               <ns2:Project>
                   <ns2:fileName>P10002</ns2:fileName>
                   <ns2:alias>project2</ns2:alias>
               </ns2:Project>
       <ns2:Project>
                   <ns2:fileName>P10003</ns2:fileName>
                   <ns2:alias>project3</ns2:alias>
               </ns2:Project>
           </ns2:getProjectsResponse>
       </SOAP-ENV:Body>
   </SOAP-ENV:Envelope>

Expected Dataframe output:

Can anyone help me on this.


问:
Hibernate field naming issue with Spring Boot (naming strategy)
Note that this code does work with plain Spring but not with Spring Boot(v1.3.3), is there something i'm missing because this is imported from a spring app that works. The code below is from the spring boot app

```<code>@Entity
@Table(name="project")
public class Project implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private int id;

    @Column(name="teamId")
    private int teamId;

    //private String Rentabiliteit;

    @Column
    //@Index(name="IProject_status",columnNames="Status")
    private String status;

    @Column
    //@Index(name="IProject_naam",columnNames="Naam")
    private String naam;
    //public Prototype m_Prototype;
    //public Team m_Team;

}
</code>```

SQL

```<code>CREATE TABLE IF NOT EXISTS `project` (
`id` int(11) NOT NULL,
`teamId` int(11) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`naam` varchar(255) DEFAULT NULL
 ) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1;
</code>```

ERROR

```<code>Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
 Unknown column 'project0_.team_id' in 'field list'
</code>```

Edited: Application.yml

```<code>spring:

mvc:
  view:
    prefix: /WEB-INF/jsp/
    suffix: .jsp

datasource:
    url: jdbc:mysql://localhost:3306/oxyplast
    username: oxyplastuser
    password: oxyplastuserpw

jpa:
  properties:
    hibernate:
      current_session_context_class: org.springframework.orm.hibernate4.SpringSessionContext
      namingStrategy: org.hibernate.cfg.DefaultNamingStrategy
</code>```

答:
application.properties

```<code>spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultComponentSafeNamingStrategy
</code>```

the above properties work for me.
hibernate 4.3.11.Final
spring boot 1.4.2.RELEASE

Body:
Note that this code does work with plain Spring but not with Spring Boot(v1.3.3), is there something i'm missing because this is imported from a spring app that works. The code below is from the spring boot app

@Entity
@Table(name="project")
public class Project implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private int id;

    @Column(name="teamId")
    private int teamId;

    //private String Rentabiliteit;

    @Column
    //@Index(name="IProject_status",columnNames="Status")
    private String status;

    @Column
    //@Index(name="IProject_naam",columnNames="Naam")
    private String naam;
    //public Prototype m_Prototype;
    //public Team m_Team;

}

SQL

CREATE TABLE IF NOT EXISTS `project` (
`id` int(11) NOT NULL,
`teamId` int(11) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`naam` varchar(255) DEFAULT NULL
 ) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1;

ERROR

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
 Unknown column 'project0_.team_id' in 'field list'

Edited: Application.yml

spring:

mvc:
  view:
    prefix: /WEB-INF/jsp/
    suffix: .jsp

datasource:
    url: jdbc:mysql://localhost:3306/oxyplast
    username: oxyplastuser
    password: oxyplastuserpw

jpa:
  properties:
    hibernate:
      current_session_context_class: org.springframework.orm.hibernate4.SpringSessionContext
      namingStrategy: org.hibernate.cfg.DefaultNamingStrategy

Body:
application.properties

spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultComponentSafeNamingStrategy

the above properties work for me.
hibernate 4.3.11.Final
spring boot 1.4.2.RELEASE


问:
Why does the output differ when input "i" instead of "j" as the key in HashMap?
I am using 2 for loops as below to get the sum of the numbers in an int[]. getTotal() is suppose to give the sum of the values in array which are below 100. The sum is calculated by adding the values one by one until it exceeds hundred. When it exceeds hundred it starts again with the next value and adds one by one like before.

```<code>private static HashMap<Integer,Integer> getTotal(){
    int total = 0;
    HashMap<Integer,Integer> finalTotal = new HashMap<Integer, Integer>();
    for (int i = 0; i < array.length; i++) {
        total += array.get(i);
        for (int j = i+1; j < array.length; j++) {
            if(total>100){
                finalTotal.put(j,total - array.get(j));
                total = 0;
            }
            else if(total<100){
                total += array.get(j);
            }
        }
    }
    return finalTotal;
}
</code>```

When printing the result in the hash-map it gives 2 different maps of answers when I use i and j for as the key. Isn't it suppose to give the same values and just different keys as answers? Not only the value the amount length of the hashmap also changes.

It would be great if you could point out any mistakes and explain why this happens.

答:
Modifying your code, for smaller numbers for examples sake

```<code>//*******************************************************************
// Welcome to CompileJava!
// If you experience any issues, please contact us ('More Info')  -->
//*******************************************************************

import java.lang.Math; // headers MUST be above the first class
import java.util.HashMap;

// one class needs to have a main() method
public class HelloWorld
{
  public static int[] array = {1,2,3,4,5,6,7,8,9,10};
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {

    System.out.println(getTotal());
  }

  private static HashMap<Integer,Integer> getTotal(){
    int total = 0;
    HashMap<Integer,Integer> finalTotal = new HashMap<Integer, Integer>();
    for (int i = 0; i < array.length; i++) {
        total += array[i];
        System.out.println("");
        System.out.println("//i = " + i + "; arr[i] = " + array[i]);
        System.out.println("total += " + array[i] + "; // total = " + total);
        for (int j = i+1; j < array.length; j++) {
            System.out.println("    //j = " + j + "; arr[j] = " + array[j]);
            if(total>5){
                finalTotal.put(j,total - array[j]);
                System.out.println("    finalTotal += (" + j+", "+total + "-" + array[j]+")");
                total = 0;
            }
            else if(total<5){
                total += array[j];
                System.out.println("    total += " + array[j]+"; //total = "+total);
            }
        }
    }
    return finalTotal;
  }
}
</code>```

Stepping through your code, and recording the results gives

```<code>//i = 0; arr[i] = 1
total += 1; // total = 1
    //j = 1; arr[j] = 2
    total += 2; //total = 3
    //j = 2; arr[j] = 3
    total += 3; //total = 6
    //j = 3; arr[j] = 4
    finalTotal += (3, 6-4)
    //j = 4; arr[j] = 5
    total += 5; //total = 5
    //j = 5; arr[j] = 6
    //j = 6; arr[j] = 7
    //j = 7; arr[j] = 8
    //j = 8; arr[j] = 9
    //j = 9; arr[j] = 10

//i = 1; arr[i] = 2
total += 2; // total = 7
    //j = 2; arr[j] = 3
    finalTotal += (2, 7-3)
    //j = 3; arr[j] = 4
    total += 4; //total = 4
    //j = 4; arr[j] = 5
    total += 5; //total = 9
    //j = 5; arr[j] = 6
    finalTotal += (5, 9-6)
    //j = 6; arr[j] = 7
    total += 7; //total = 7
    //j = 7; arr[j] = 8
    finalTotal += (7, 7-8)
    //j = 8; arr[j] = 9
    total += 9; //total = 9
    //j = 9; arr[j] = 10
    finalTotal += (9, 9-10)

//i = 2; arr[i] = 3
total += 3; // total = 3
    //j = 3; arr[j] = 4
    total += 4; //total = 7
    //j = 4; arr[j] = 5
    finalTotal += (4, 7-5)
    //j = 5; arr[j] = 6
    total += 6; //total = 6
    //j = 6; arr[j] = 7
    finalTotal += (6, 6-7)
    //j = 7; arr[j] = 8
    total += 8; //total = 8
    //j = 8; arr[j] = 9
    finalTotal += (8, 8-9)
    //j = 9; arr[j] = 10
    total += 10; //total = 10

//i = 3; arr[i] = 4
total += 4; // total = 14
    //j = 4; arr[j] = 5
    finalTotal += (4, 14-5)
    //j = 5; arr[j] = 6
    total += 6; //total = 6
    //j = 6; arr[j] = 7
    finalTotal += (6, 6-7)
    //j = 7; arr[j] = 8
    total += 8; //total = 8
    //j = 8; arr[j] = 9
    finalTotal += (8, 8-9)
    //j = 9; arr[j] = 10
    total += 10; //total = 10

//i = 4; arr[i] = 5
total += 5; // total = 15
    //j = 5; arr[j] = 6
    finalTotal += (5, 15-6)
    //j = 6; arr[j] = 7
    total += 7; //total = 7
    //j = 7; arr[j] = 8
    finalTotal += (7, 7-8)
    //j = 8; arr[j] = 9
    total += 9; //total = 9
    //j = 9; arr[j] = 10
    finalTotal += (9, 9-10)

//i = 5; arr[i] = 6
total += 6; // total = 6
    //j = 6; arr[j] = 7
    finalTotal += (6, 6-7)
    //j = 7; arr[j] = 8
    total += 8; //total = 8
    //j = 8; arr[j] = 9
    finalTotal += (8, 8-9)
    //j = 9; arr[j] = 10
    total += 10; //total = 10

//i = 6; arr[i] = 7
total += 7; // total = 17
    //j = 7; arr[j] = 8
    finalTotal += (7, 17-8)
    //j = 8; arr[j] = 9
    total += 9; //total = 9
    //j = 9; arr[j] = 10
    finalTotal += (9, 9-10)

//i = 7; arr[i] = 8
total += 8; // total = 8
    //j = 8; arr[j] = 9
    finalTotal += (8, 8-9)
    //j = 9; arr[j] = 10
    total += 10; //total = 10

//i = 8; arr[i] = 9
total += 9; // total = 19
    //j = 9; arr[j] = 10
    finalTotal += (9, 19-10)

//i = 9; arr[i] = 10
total += 10; // total = 10
{2=4, 3=2, 4=9, 5=9, 6=-1, 7=9, 8=-1, 9=9}
</code>```

This is only a few steps in, and it really doesn't seem like it does anything like you asked. I recommend looking up how to use a debugger, and step through your code.

Notice that j is not the same thing as arr[j]

Notice that loops within loops, still loop, and take care of the start positions of the loop.

Hashmaps will update their value, should you insert a duplicate, given your code (note that you don't handle the case where total==5/100, loop enough times and it's bound to happen) and you will get differing values.

Start on smaller problems / inputs that you are able to debug , and work your way up.

Body:
I am using 2 for loops as below to get the sum of the numbers in an int[]. getTotal() is suppose to give the sum of the values in array which are below 100. The sum is calculated by adding the values one by one until it exceeds hundred. When it exceeds hundred it starts again with the next value and adds one by one like before.

private static HashMap<Integer,Integer> getTotal(){
    int total = 0;
    HashMap<Integer,Integer> finalTotal = new HashMap<Integer, Integer>();
    for (int i = 0; i < array.length; i++) {
        total += array.get(i);
        for (int j = i+1; j < array.length; j++) {
            if(total>100){
                finalTotal.put(j,total - array.get(j));
                total = 0;
            }
            else if(total<100){
                total += array.get(j);
            }
        }
    }
    return finalTotal;
}

When printing the result in the hash-map it gives 2 different maps of answers when I use i and j for as the key. Isn't it suppose to give the same values and just different keys as answers? Not only the value the amount length of the hashmap also changes.

It would be great if you could point out any mistakes and explain why this happens.

Body:
Modifying your code, for smaller numbers for examples sake

//*******************************************************************
// Welcome to CompileJava!
// If you experience any issues, please contact us ('More Info')  -->
//*******************************************************************

import java.lang.Math; // headers MUST be above the first class
import java.util.HashMap;

// one class needs to have a main() method
public class HelloWorld
{
  public static int[] array = {1,2,3,4,5,6,7,8,9,10};
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {

    System.out.println(getTotal());
  }

  private static HashMap<Integer,Integer> getTotal(){
    int total = 0;
    HashMap<Integer,Integer> finalTotal = new HashMap<Integer, Integer>();
    for (int i = 0; i < array.length; i++) {
        total += array[i];
        System.out.println("");
        System.out.println("//i = " + i + "; arr[i] = " + array[i]);
        System.out.println("total += " + array[i] + "; // total = " + total);
        for (int j = i+1; j < array.length; j++) {
            System.out.println("    //j = " + j + "; arr[j] = " + array[j]);
            if(total>5){
                finalTotal.put(j,total - array[j]);
                System.out.println("    finalTotal += (" + j+", "+total + "-" + array[j]+")");
                total = 0;
            }
            else if(total<5){
                total += array[j];
                System.out.println("    total += " + array[j]+"; //total = "+total);
            }
        }
    }
    return finalTotal;
  }
}

Stepping through your code, and recording the results gives

//i = 0; arr[i] = 1
total += 1; // total = 1
    //j = 1; arr[j] = 2
    total += 2; //total = 3
    //j = 2; arr[j] = 3
    total += 3; //total = 6
    //j = 3; arr[j] = 4
    finalTotal += (3, 6-4)
    //j = 4; arr[j] = 5
    total += 5; //total = 5
    //j = 5; arr[j] = 6
    //j = 6; arr[j] = 7
    //j = 7; arr[j] = 8
    //j = 8; arr[j] = 9
    //j = 9; arr[j] = 10

//i = 1; arr[i] = 2
total += 2; // total = 7
    //j = 2; arr[j] = 3
    finalTotal += (2, 7-3)
    //j = 3; arr[j] = 4
    total += 4; //total = 4
    //j = 4; arr[j] = 5
    total += 5; //total = 9
    //j = 5; arr[j] = 6
    finalTotal += (5, 9-6)
    //j = 6; arr[j] = 7
    total += 7; //total = 7
    //j = 7; arr[j] = 8
    finalTotal += (7, 7-8)
    //j = 8; arr[j] = 9
    total += 9; //total = 9
    //j = 9; arr[j] = 10
    finalTotal += (9, 9-10)

//i = 2; arr[i] = 3
total += 3; // total = 3
    //j = 3; arr[j] = 4
    total += 4; //total = 7
    //j = 4; arr[j] = 5
    finalTotal += (4, 7-5)
    //j = 5; arr[j] = 6
    total += 6; //total = 6
    //j = 6; arr[j] = 7
    finalTotal += (6, 6-7)
    //j = 7; arr[j] = 8
    total += 8; //total = 8
    //j = 8; arr[j] = 9
    finalTotal += (8, 8-9)
    //j = 9; arr[j] = 10
    total += 10; //total = 10

//i = 3; arr[i] = 4
total += 4; // total = 14
    //j = 4; arr[j] = 5
    finalTotal += (4, 14-5)
    //j = 5; arr[j] = 6
    total += 6; //total = 6
    //j = 6; arr[j] = 7
    finalTotal += (6, 6-7)
    //j = 7; arr[j] = 8
    total += 8; //total = 8
    //j = 8; arr[j] = 9
    finalTotal += (8, 8-9)
    //j = 9; arr[j] = 10
    total += 10; //total = 10

//i = 4; arr[i] = 5
total += 5; // total = 15
    //j = 5; arr[j] = 6
    finalTotal += (5, 15-6)
    //j = 6; arr[j] = 7
    total += 7; //total = 7
    //j = 7; arr[j] = 8
    finalTotal += (7, 7-8)
    //j = 8; arr[j] = 9
    total += 9; //total = 9
    //j = 9; arr[j] = 10
    finalTotal += (9, 9-10)

//i = 5; arr[i] = 6
total += 6; // total = 6
    //j = 6; arr[j] = 7
    finalTotal += (6, 6-7)
    //j = 7; arr[j] = 8
    total += 8; //total = 8
    //j = 8; arr[j] = 9
    finalTotal += (8, 8-9)
    //j = 9; arr[j] = 10
    total += 10; //total = 10

//i = 6; arr[i] = 7
total += 7; // total = 17
    //j = 7; arr[j] = 8
    finalTotal += (7, 17-8)
    //j = 8; arr[j] = 9
    total += 9; //total = 9
    //j = 9; arr[j] = 10
    finalTotal += (9, 9-10)

//i = 7; arr[i] = 8
total += 8; // total = 8
    //j = 8; arr[j] = 9
    finalTotal += (8, 8-9)
    //j = 9; arr[j] = 10
    total += 10; //total = 10

//i = 8; arr[i] = 9
total += 9; // total = 19
    //j = 9; arr[j] = 10
    finalTotal += (9, 19-10)

//i = 9; arr[i] = 10
total += 10; // total = 10
{2=4, 3=2, 4=9, 5=9, 6=-1, 7=9, 8=-1, 9=9}

This is only a few steps in, and it really doesn't seem like it does anything like you asked. I recommend looking up how to use a debugger, and step through your code.

Notice that j is not the same thing as arr[j]

Notice that loops within loops, still loop, and take care of the start positions of the loop.

Hashmaps will update their value, should you insert a duplicate, given your code (note that you don't handle the case where total==5/100, loop enough times and it's bound to happen) and you will get differing values.

Start on smaller problems / inputs that you are able to debug , and work your way up.


问:
Gradle sync failed: Uninitialized object exists on backward branch 70
My android app failed to sync gradle with the following error in build log:

```<code>Uninitialized object exists on backward branch 70
Exception Details:
  Location:
    com/android/build/gradle/tasks/BuildArtifactReportTask.newArtifact(Lcom/android/build/api/artifact/BuildableArtifact;)Lcom/android/build/gradle/tasks/BuildArtifactReportTask$BuildableArtifactData; @119: goto
  Reason:
    Error exists in the bytecode
  Bytecode:
    0000000: bb00 f459 2bb9 0139 0100 c000 6b2b b901
    0000010: 3d01 0001 b901 4302 0059 1301 45b8 0148
    0000020: c000 374d 3a0d 3a0c 3a0b 2c4e bb00 6859
    0000030: 2c10 0ab8 003d b700 69c0 006b 3a04 2db9
    0000040: 0054 0100 3a05 1905 b900 5a01 0099 002d
    0000050: 1905 b900 5e01 003a 0619 0419 06c0 014a
    0000060: 3a07 3a0e 1907 b901 4d01 003a 0f19 0e19
    0000070: 0fb9 0075 0200 57a7 ffcf 1904 c000 773a
    0000080: 0e19 0b19 0c19 0d19 0eb7 0150 b0
  Stackmap Table:
    full_frame(@70,{Object[#2],Object[#109],Object[#55],Object[#55],Object[#107],Object[#86],Top,Top,Top,Top,Top,Uninitialized[#0],Uninitialized[#0],Object[#107]},{})
    same_frame(@122)
</code>```

Here is my build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.3'

    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 111
        versionName "1.1.1"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(":adjust")
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.facebook.android:facebook-android-sdk:4.+'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.google.code.gson:gson:2.3.1'
    compile 'com.google.firebase:firebase-core:11.0.1'
    compile 'com.google.firebase:firebase-messaging:11.0.1'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

I'm happy to provide more information if you need.

答:
Android Studio: 3.5.3

gradle plugin: 3.5.3

gradle: 5.4.1

platform: Mac OS Mojave 10.14.6 (18G103)

I had done this:Project Structure -> SDK Location -> Select "Use embedded JDK(recommended)" but it still not working.

when I read this article,

you can add a property at gradle.properies:

org.gradle.java.home=(path to JDK home)

it works!

Body:
My android app failed to sync gradle with the following error in build log:

Uninitialized object exists on backward branch 70
Exception Details:
  Location:
    com/android/build/gradle/tasks/BuildArtifactReportTask.newArtifact(Lcom/android/build/api/artifact/BuildableArtifact;)Lcom/android/build/gradle/tasks/BuildArtifactReportTask$BuildableArtifactData; @119: goto
  Reason:
    Error exists in the bytecode
  Bytecode:
    0000000: bb00 f459 2bb9 0139 0100 c000 6b2b b901
    0000010: 3d01 0001 b901 4302 0059 1301 45b8 0148
    0000020: c000 374d 3a0d 3a0c 3a0b 2c4e bb00 6859
    0000030: 2c10 0ab8 003d b700 69c0 006b 3a04 2db9
    0000040: 0054 0100 3a05 1905 b900 5a01 0099 002d
    0000050: 1905 b900 5e01 003a 0619 0419 06c0 014a
    0000060: 3a07 3a0e 1907 b901 4d01 003a 0f19 0e19
    0000070: 0fb9 0075 0200 57a7 ffcf 1904 c000 773a
    0000080: 0e19 0b19 0c19 0d19 0eb7 0150 b0
  Stackmap Table:
    full_frame(@70,{Object[#2],Object[#109],Object[#55],Object[#55],Object[#107],Object[#86],Top,Top,Top,Top,Top,Uninitialized[#0],Uninitialized[#0],Object[#107]},{})
    same_frame(@122)

Here is my build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.3'

    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 111
        versionName "1.1.1"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(":adjust")
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.facebook.android:facebook-android-sdk:4.+'
    compile 'com.squareup.okhttp:okhttp:2.0.0'
    compile 'com.google.code.gson:gson:2.3.1'
    compile 'com.google.firebase:firebase-core:11.0.1'
    compile 'com.google.firebase:firebase-messaging:11.0.1'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

I'm happy to provide more information if you need.


问:
Deploy GCP Cloud function with local dependencies
I have been trying to deploy a Cloud Function with some private dependencies (pyodbc) as I couldn't get it working thru requirements.txt. Please note, I don't want to use Docker here. So all I have built here is below files,

```<code>1. main.py
2. process.py ( this one use pyodbc to connect to teradata)
3. libs (folder)
   3.1 pyodbc-4.0.30.dist-info (package)
   3.2 pyodbc (python extension module)
   3.3 __init.py__ ( this is to make this folder as module)
4.requirements.txt
</code>```

I also updated process.py file to import pyodbc module as below,

```<code>import libs.pyodbc
</code>```

Please note: I used GCP docs to install the pyodbc package and put in libs using https://cloud.google.com/functions/docs/writing/specifying-dependencies-python
On top this, I am also requirements.txt to import as default.

But I am still getting module error as below.

```<code>Error message: Code in file main.py can't be loaded.
Did you list all required modules in requirements.txt?
Detailed stack trace: Traceback (most recent call last):
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 305, in check_or_load_user_function
    _function_handler.load_user_function()
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 184, in load_user_function
    spec.loader.exec_module(main)
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/user_code/main.py", line 9, in <module>
    from process import process
  File "/user_code/process.py", line 6, in <module>
    import libs.pyodbc
ModuleNotFoundError: No module named 'libs.pyodbc'
</code>```

Any leads or help from here is really appreciated. All I am trying to achieve here is, Read CSV files from GCP bucket and process it thru dataframe which loads into teradata and generate output file back into another GCP bucket. I am trying to achieve all with Cloud Functions only. Thank you

答:
The pyodbc project might be a bit of a special case here, because:

The project requires some platform-specific code;

They haven't published source distributions for their latest release (only built distributions).

Here's what I did to get this to work. Starting with an empty libs directory, first download the latest available source distribution:

$ pip download pyodbc --no-binary :all:
```

<p>Make a directory for the module:</p>

<pre class="lang-none prettyprint-override"><code>$ mkdir libs/pyodbc
</code>```

Untar the source distribution into the module:

$ tar xf pyodbc-4.0.28.tar.gz -C libs/pyodbc
```

<p>Then, in the function you can do:</p>

<pre class="lang-py prettyprint-override"><code>import libs.pyodbc
</code>```

Body:
I have been trying to deploy a Cloud Function with some private dependencies (pyodbc) as I couldn't get it working thru requirements.txt. Please note, I don't want to use Docker here. So all I have built here is below files,

1. main.py
2. process.py ( this one use pyodbc to connect to teradata)
3. libs (folder)
   3.1 pyodbc-4.0.30.dist-info (package)
   3.2 pyodbc (python extension module)
   3.3 __init.py__ ( this is to make this folder as module)
4.requirements.txt

I also updated process.py file to import pyodbc module as below,

import libs.pyodbc

Please note: I used GCP docs to install the pyodbc package and put in libs using https://cloud.google.com/functions/docs/writing/specifying-dependencies-python
On top this, I am also requirements.txt to import as default.

But I am still getting module error as below.

Error message: Code in file main.py can't be loaded.
Did you list all required modules in requirements.txt?
Detailed stack trace: Traceback (most recent call last):
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 305, in check_or_load_user_function
    _function_handler.load_user_function()
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 184, in load_user_function
    spec.loader.exec_module(main)
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/user_code/main.py", line 9, in <module>
    from process import process
  File "/user_code/process.py", line 6, in <module>
    import libs.pyodbc
ModuleNotFoundError: No module named 'libs.pyodbc'

Any leads or help from here is really appreciated. All I am trying to achieve here is, Read CSV files from GCP bucket and process it thru dataframe which loads into teradata and generate output file back into another GCP bucket. I am trying to achieve all with Cloud Functions only. Thank you

Body:
The pyodbc project might be a bit of a special case here, because:

The project requires some platform-specific code;

They haven't published source distributions for their latest release (only built distributions).

Here's what I did to get this to work. Starting with an empty libs directory, first download the latest available source distribution:

$ pip download pyodbc --no-binary :all:

Make a directory for the module:

$ mkdir libs/pyodbc

Untar the source distribution into the module:

$ tar xf pyodbc-4.0.28.tar.gz -C libs/pyodbc

Then, in the function you can do:

import libs.pyodbc


问:
Why haven't we designed a computer to directly execute high level programming?
I always thought that computers nowadays are already programmed to directly execute high-level programming, but apparently not. Is there any specific reason why we haven't done that yet? Any cons of high-level programming.</p>

答:
This calls for speculation and over simplification, so that is what I will do

What you describe is an interpreted language, and the question is why are we not running hardware interpreters?

The rational is simply it is more cost efficient (both calculated in both silcon area and in Watt / useful work) to make a hardware architecture suitable for implementation in silicon and then create an advanced optimizing compiler which translates to this architecture than create the same logic in silicon to interpret the high level code.

Another argument not to do it is security, hardware development cycles are long and it isn't even possible to release an updated version of the processor after massproduction, interpreters are notorious for being vulnerable with security problems on malformed inputs .