问:
React-Native setTimeout function triggered after clearTimeout is called
In my react-native app, I am building a component that has a 'heads up display' with some controls, that only appears after touching the view. Then, one second after the last interaction of the user, I want those buttons to disappear again for a cleaner look.

I am using setTimeout for this. Whenever the user interacts with my component, I trigger a function. In this function, I set a timeout for 1 second, and then clear the navigation buttons when it triggers. I also check if another timer was already set (I store them in state), and cancel it because I want to make sure that only the latest timeout function gets triggered.

This is the code:

```<code>const [timer, setTimer] = useState<number>(null)

const handleControlsInteraction = useCallback(() => {
    // If the user interacted with the controls, we need to make them disappear 1 second after the latest interaction

    // If a timer was already set by a previous interaction, we want to cancel it,
    // because because the controls should disappear 1 second after the latest interaction
    if (timer != null) {
        console.log('Cancelling timeout: ', timer)
        clearTimeout(timer)
    }

    // now we set a new timer for 1 second
    let timeout = setTimeout(() => {
        // When the function of the timer triggers, we need to hide the controls, clear the timeout and remove the timout from our local state
        console.log('Hiding buttons for timeout: ', timeout)
        setDisplayButtons(false)
        clearTimeout(timer)
        setTimer(null)
    }, 1000);
    console.log('Setting new timeout: ', timeout)

    setTimer(timeout)
}, [timer])
</code>```

When I run this, And I tap my control twice (half a second apart), I notice that my first timer gets cancelled as expected, but it's function still gets triggered after that. This causes my controls to get hidden when the user is still interacting with them, rather than 1 second after the latest interaction.

What I'm trying to achieve seems like a pretty basic thing to do. However, I've been puzzling with this for a while now.

How can I resolve this? Any guidance would be highly appreciated.

答:
When your component changes the state and rerender, a new  timeout instance recreates and results in unexpected behavior.

The solution is to keep track of the original timeout instance for each component rerender cycle.

React provide useRef hook to persist value for each component render cycle.

```<code>let timerRef = React.useRef(null);

useEffect(() => {
  // Clear the interval when the component unmounts
  return () => clearTimeout(timerRef.current);
}, []);

const handleControlsInteraction = () => {

  if (timerRef.current != null) {
    clearTimout(timerRef.current)
  }

  // now we set a new timer for 1 second
  timerRef.current = setTimeout(() => {
    setDisplayButtons(false);
  }, 1000);
};

</code>```

Body:
In my react-native app, I am building a component that has a 'heads up display' with some controls, that only appears after touching the view. Then, one second after the last interaction of the user, I want those buttons to disappear again for a cleaner look.

I am using setTimeout for this. Whenever the user interacts with my component, I trigger a function. In this function, I set a timeout for 1 second, and then clear the navigation buttons when it triggers. I also check if another timer was already set (I store them in state), and cancel it because I want to make sure that only the latest timeout function gets triggered.

This is the code:

const [timer, setTimer] = useState<number>(null)

const handleControlsInteraction = useCallback(() => {
    // If the user interacted with the controls, we need to make them disappear 1 second after the latest interaction

    // If a timer was already set by a previous interaction, we want to cancel it,
    // because because the controls should disappear 1 second after the latest interaction
    if (timer != null) {
        console.log('Cancelling timeout: ', timer)
        clearTimeout(timer)
    }

    // now we set a new timer for 1 second
    let timeout = setTimeout(() => {
        // When the function of the timer triggers, we need to hide the controls, clear the timeout and remove the timout from our local state
        console.log('Hiding buttons for timeout: ', timeout)
        setDisplayButtons(false)
        clearTimeout(timer)
        setTimer(null)
    }, 1000);
    console.log('Setting new timeout: ', timeout)

    setTimer(timeout)
}, [timer])

When I run this, And I tap my control twice (half a second apart), I notice that my first timer gets cancelled as expected, but it's function still gets triggered after that. This causes my controls to get hidden when the user is still interacting with them, rather than 1 second after the latest interaction.

What I'm trying to achieve seems like a pretty basic thing to do. However, I've been puzzling with this for a while now.

How can I resolve this? Any guidance would be highly appreciated.

Body:
When your component changes the state and rerender, a new  timeout instance recreates and results in unexpected behavior.

The solution is to keep track of the original timeout instance for each component rerender cycle.

React provide useRef hook to persist value for each component render cycle.

let timerRef = React.useRef(null);

useEffect(() => {
  // Clear the interval when the component unmounts
  return () => clearTimeout(timerRef.current);
}, []);

const handleControlsInteraction = () => {

  if (timerRef.current != null) {
    clearTimout(timerRef.current)
  }

  // now we set a new timer for 1 second
  timerRef.current = setTimeout(() => {
    setDisplayButtons(false);
  }, 1000);
};


来源: stackexchange

问:
Control to display float array (f.e. Waveformdata, FFT-data etc)
I'm processing audio and I'd like to display several stages in my processing loop.

So I have for example some float arrays representing waveforms, FFT-data, PowerSpectrum-data, and some other stuff. All float[].

I'd like to display these float[] buffers using a single control that should probably have only a y-axis scale property.

Does anybody know if something like that is available somewhere for WPF ?
I'm not looking for complete charting libraries, I'd like to have something as simple as possible that does the job.

答: I would suggest the WPF WriteableBitmapEx project http://writeablebitmapex.codeplex.com/ which allows you quick ways of drawing over an image.</p>

ContentLicense: CC BY-SA 3.0


问:
Looking for a way to split cells in excel based the last five numbers in a cell
I am looking for a way to fix a mixed data set representing addresses in Excel.

Here is an example dataset.

```<code>Kirchgasse 2389179 Beimerstetten
</code>```

All this should result in three datasets.

```<code>A1 = Kirchgasse 2389179 Beimerstetten
A2 = Kirchgasse 23
A3 = 89179
A4 = Beimerstetten
</code>```

Pattern is, that A3 is always the last 5 numbers in the dataset.

I am totally lost here, as Excel is usually not my weapon of choice.

ContentLicense: CC BY-SA 4.0

Body:
I am looking for a way to fix a mixed data set representing addresses in Excel.

Here is an example dataset.

Kirchgasse 2389179 Beimerstetten

All this should result in three datasets.

A1 = Kirchgasse 2389179 Beimerstetten
A2 = Kirchgasse 23
A3 = 89179
A4 = Beimerstetten

Pattern is, that A3 is always the last 5 numbers in the dataset.

I am totally lost here, as Excel is usually not my weapon of choice.

Body:
In A2, formula copied down :

=TRIM(SUBSTITUTE(MID(SUBSTITUTE(" "&REPLACE(REPLACE(A$1,AGGREGATE(14,6,FIND(ROW($1:$10)-1,A$1,COLUMN(A:Z)),1)-4,0," "),FIND(" ",A$1),1,"@")," ",REPT(" ",50)),ROW($A1)*50,50),"@"," "))


问:
Is Angular adding margin/padding to my component?
I'm facing a little problem.. I'm trying to build some kind of "Matrix" to build a snake game in angular, and for some reason, there is a margin / padding I can not remove. Here is my code:

    <ng-container *ngFor="let box of row.boxes>
      <snake-box [box]="box"></snake-box>
    </ng-container>

```
<pre class="lang-html prettyprint-override"><code><!-- box.component.html -->
<div class="box"></div>
</code>```

Both using the same style file:

```<code>// styles.scss

.row {
  margin: 0px;
  padding: 0px;
}

.box {
  display: inline-block;
  background-color: blue;

  width: 30px;
  height: 30px;

  border: 1px solid black;
}

</code>```

so, why is there a space between rows??? I think that it doesn't make sense, but I'm sure I'm missing something. I'll left some screenshots:

In this screenshot you can check that the "snake-box" component is adding some kind of margin.

In this other screenshot you can see that the div actually doesn't have margin/padding.

Is angular adding margin to my component? If yes, how can I remove it?

答:
The answer to you problem is CSS FLEX.
It would work with these styles:

```<code>// styles.scss

.row {
  display: flex;
  flex-direction: row;
}

.box {
  background-color: blue;

  width: 30px;
  height: 30px;

  border: 1px solid black;
}
</code>```

If you want more information about flexbox, here is an interesting link https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Body:
I'm facing a little problem.. I'm trying to build some kind of "Matrix" to build a snake game in angular, and for some reason, there is a margin / padding I can not remove. Here is my code:

    <ng-container *ngFor="let box of row.boxes>
      <snake-box [box]="box"></snake-box>
    </ng-container>

Both using the same style file:

// styles.scss

.row {
  margin: 0px;
  padding: 0px;
}

.box {
  display: inline-block;
  background-color: blue;

  width: 30px;
  height: 30px;

  border: 1px solid black;
}

so, why is there a space between rows??? I think that it doesn't make sense, but I'm sure I'm missing something. I'll left some screenshots:

In this screenshot you can check that the "snake-box" component is adding some kind of margin.

In this other screenshot you can see that the div actually doesn't have margin/padding.

Is angular adding margin to my component? If yes, how can I remove it?

Body:
The answer to you problem is CSS FLEX.
It would work with these styles:

// styles.scss

.row {
  display: flex;
  flex-direction: row;
}

.box {
  background-color: blue;

  width: 30px;
  height: 30px;

  border: 1px solid black;
}

If you want more information about flexbox, here is an interesting link https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
arthas ognl map return null
this is a map return

```<code>@LinkedHashMap[
    @String[6]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@50d60a4a],
    @String[7]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@4a5f4b44],
    @String[8]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@2d8b8b8e],
    @String[9]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@5990bae5],
    @String[10]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@39747fc7],
    @String[11]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@94106c6],
]
</code>```

but i use 'get(6)' return null. 'get(@String[6])' is a Exception.

this is my line.

```<code>ognl @com.elex.billion.icefire.game.Application@getBean(@com.elex.billion.icefire.game.biz.manager.MissionManager@class).getPlayerChapterMission(100000000000031L).getChapterId2Info().get(6)
</code>```

How can i get value with a key? thanks.

Title: arthas ognl map return null

Body:
this is a map return

@LinkedHashMap[
    @String[6]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@50d60a4a],
    @String[7]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@4a5f4b44],
    @String[8]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@2d8b8b8e],
    @String[9]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@5990bae5],
    @String[10]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@39747fc7],
    @String[11]:@ChapterInfo[com.elex.billion.icefire.game.biz.model.mission.chapterMission.ChapterInfo@94106c6],
]

but i use 'get(6)' return null. 'get(@String[6])' is a Exception.

this is my line.

ognl @com.elex.billion.icefire.game.Application@getBean(@com.elex.billion.icefire.game.biz.manager.MissionManager@class).getPlayerChapterMission(100000000000031L).getChapterId2Info().get(6)

How can i get value with a key? thanks.

Body: ognl @com.elex.billion.icefire.game.Application@getBean(@com.elex.billion.icefire.game.biz.manager.MissionManager@class).getPlayerChapterMission(100000000000031L).getChapterId2Info().get(\"6\")


问:
using an href in react doens't direct to the wanted page, and i get an error when i try to use <link>
The following code shows up in the browser, but it just refreshes to the same page when clicked:

```<code><Button className="login-btn" variant="outline-dark" href="Login.jsx">Sign in</Button>
</code>```

or:

```<code><a href="Login.jsx">Sign in</a>
</code>```

I try using <link>, and I get the following error:

```<code>The above error occurred in the <Link> component:
    at LinkWithRef (http://localhost:3000/static/js/bundle.js:43308:5)
    at div
    at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
</code>```

It also gives me an error about useHref(), which I'm not using..

答:
The reason it refreshes on clicking the button is that you are passing Login.jsx as the href attribute which expects a URL/route defined in your application and I am assuming you are passing the same Login.jsx as the value for to attribute to the Link tag and because of that the error is occurring. If you want to redirect to the Login page on clicking Sign in then you can use it like this -

```<code><a href="/login">Sign in</a>
</code>```

Body:
The following code shows up in the browser, but it just refreshes to the same page when clicked:

<Button className="login-btn" variant="outline-dark" href="Login.jsx">Sign in</Button>

or:

Sign in

I try using <link>, and I get the following error:

The above error occurred in the <Link> component:
    at LinkWithRef (http://localhost:3000/static/js/bundle.js:43308:5)
    at div
    at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

It also gives me an error about useHref(), which I'm not using..

Body:
The reason it refreshes on clicking the button is that you are passing Login.jsx as the href attribute which expects a URL/route defined in your application and I am assuming you are passing the same Login.jsx as the value for to attribute to the Link tag and because of that the error is occurring. If you want to redirect to the Login page on clicking Sign in then you can use it like this -

<a href="/login">Sign in</a>


问:
React and uploady with custom function that sends a form after showFileUpload
I have a form that have an onSubmit, in that callback I have a uploady.showFileUpload(), but the code after uploady.showFileUpload() is executed.

Now the question is how can I wait for uploady, and then execute the rest of the code?

```<code>  const handleSubmit2 = useCallback((e)=> {
  uploady.showFileUpload(); //(HERE SHOULD WAIT FOR IT TO FINISH FILE SELECT)
  //OTHER CODE
});
</code>```

答:
This codesandbox should be helpful in the case of using Uploady with a form:
https://codesandbox.io/s/react-uploady-inside-form-ys1wx

The idea is that you show the file selection prompt separately from submitting the form:

import React, { useState, useCallback, useMemo, forwardRef } from "react";
import Uploady, {
  useUploadyContext
} from "@rpldy/uploady";
import { asUploadButton } from "@rpldy/upload-button";

const MyUploadField = asUploadButton(
  forwardRef(({ onChange, ...props }, ref) => {

    return (

      Select file

    );
  })
);

const MyForm = () => {
  const [fields, setFields] = useState({});
  const [fileName, setFileName] = useState(null);
  const uploadyContext = useUploadyContext();

  const onSubmit = useCallback(() => {
    uploadyContext.processPending({ params: fields });
  }, [fields, uploadyContext]);

  const onFieldChange = useCallback(
    (e) => {
      setFields({
        ...fields,
        [e.currentTarget.id]: e.currentTarget.value
      });
    },
    [fields, setFields]
  );

  return (
    <form>
      <MyUploadField autoUpload={false} />
      <input
        onChange={onFieldChange}
        id="field-name"
        type="text"
        placeholder="your name"
      />
      <SubmitButton
        id="form-submit"
        type="button"
        onClick={onSubmit}
      >
        Submit Form
      </SubmitButton>
    </form>
  );
};

<Uploady
        clearPendingOnAdd
        destination={{ url: "[upload-url]" }}
        multiple={false}
      >
        <MyForm />
      </Uploady>```

Selection is achieved by using the asUploadButton HOC. You can of course do so yourself as you did with uploady.showFileUpload();.

Then, the submit button uses uploady's processPending method to start uploading.

Body:
I have a form that have an onSubmit, in that callback I have a uploady.showFileUpload(), but the code after uploady.showFileUpload() is executed.

Now the question is how can I wait for uploady, and then execute the rest of the code?

  const handleSubmit2 = useCallback((e)=> {
  uploady.showFileUpload(); //(HERE SHOULD WAIT FOR IT TO FINISH FILE SELECT)
  //OTHER CODE
});

Body:
This codesandbox should be helpful in the case of using Uploady with a form:
https://codesandbox.io/s/react-uploady-inside-form-ys1wx

The idea is that you show the file selection prompt separately from submitting the form:

import React, { useState, useCallback, useMemo, forwardRef } from "react";
import Uploady, {
  useUploadyContext
} from "@rpldy/uploady";
import { asUploadButton } from "@rpldy/upload-button";

const MyUploadField = asUploadButton(
  forwardRef(({ onChange, ...props }, ref) => {

    return (
      <div {...props} ref={ref} id="form-upload-button" title={text}>
      Select file
      </div>
    );
  })
);

const MyForm = () => {
  const [fields, setFields] = useState({});
  const [fileName, setFileName] = useState(null);
  const uploadyContext = useUploadyContext();

  const onSubmit = useCallback(() => {
    uploadyContext.processPending({ params: fields });
  }, [fields, uploadyContext]);

  const onFieldChange = useCallback(
    (e) => {
      setFields({
        ...fields,
        [e.currentTarget.id]: e.currentTarget.value
      });
    },
    [fields, setFields]
  );

  return (
    <form>
      <MyUploadField autoUpload={false} />
      <input
        onChange={onFieldChange}
        id="field-name"
        type="text"
        placeholder="your name"
      />
      <SubmitButton
        id="form-submit"
        type="button"
        onClick={onSubmit}
      >
        Submit Form
      </SubmitButton>
    </form>
  );
};

<Uploady
        clearPendingOnAdd
        destination={{ url: "[upload-url]" }}
        multiple={false}
      >
        <MyForm />
      </Uploady>

Selection is achieved by using the asUploadButton HOC. You can of course do so yourself as you did with uploady.showFileUpload();.

Then, the submit button uses uploady's processPending method to start uploading.


问:
How Ruby GC count allocated RegularExpression
Today i learned about Ruby Garbage Collection, and do some test

def count_allocated_objects
  before = GC.stat(:total_allocated_objects)

  yield

  after = GC.stat(:total_allocated_objects)

  after - before
end

count_allocated_objects {
  s = "this is a string"
  r = /[a-z]/
} # => 1, so only the string `s` be counted

count_allocated_objects {
  s = "this is a string"
  s.gsub(/[a-z]/, "")
} # => 6, in this case, is the regex `/[a-z]/` counted ?
```

As you can see, it looks like the regex /[a-z]/ is not counted by the GC.
is it the Ruby's rule or the GC's stat total_allocated_objects rule ?

答:
Turn out the Regex is considered as frozen object (similar to the frozen String) and the GC will not count those frozen objects, so the Regex will not be counted. (regardless which Ruby version, at least so far)

count_allocated_objects {
  s1 = "this is a string"
  s2 = "another string"
  r = /[a-z]/
} # ruby 2.6.5 => 2, ruby 3.0.0 => 2, ruby 3.1.0 => 3
```
<p>although <code>ruby 3.1.0</code> return 3, but if i remove <code>r</code> from the above code, it still return 3</p>
<pre class="lang-rb prettyprint-override"><code>count_allocated_objects {
  s1 = "this is a string"
  s2 = "another string"
} # ruby 2.6.5 => 2, ruby 3.0.0 => 2, ruby 3.1.0 => 3
</code>```

test with a frozen String

count_allocated_objects {
  s1 = "this is a string"
  s2 = "another string".freeze
} # ruby 2.6.5 => 1, ruby 3.0.0 => 1, ruby 3.1.0 => 2
```
<p>For sure i checked a frozen String and Regexp in <code>heap dump</code></p>
<pre class="lang-rb prettyprint-override"><code>require 'objspace'
ObjectSpace.trace_object_allocations_start

s1 = "this is a string"
s2 = "another string".freeze
r = /[a-z]/

p r.frozen? # true
p ObjectSpace.dump(r) # "{..\"type\":\"REGEXP\", ... \"frozen\":true ...
p ObjectSpace.dump(s2) # "{..\"type\":\"STRING\", ... \"frozen\":true ...
p ObjectSpace.dump(s1) # didn't contain \"frozen\"
</code>```

Body:
Today i learned about Ruby Garbage Collection, and do some test

def count_allocated_objects
  before = GC.stat(:total_allocated_objects)

  yield

  after = GC.stat(:total_allocated_objects)

  after - before
end

count_allocated_objects {
  s = "this is a string"
  r = /[a-z]/
} # => 1, so only the string `s` be counted

count_allocated_objects {
  s = "this is a string"
  s.gsub(/[a-z]/, "")
} # => 6, in this case, is the regex `/[a-z]/` counted ?

As you can see, it looks like the regex /[a-z]/ is not counted by the GC.
is it the Ruby's rule or the GC's stat total_allocated_objects rule ?

Body:
Turn out the Regex is considered as frozen object (similar to the frozen String) and the GC will not count those frozen objects, so the Regex will not be counted. (regardless which Ruby version, at least so far)

count_allocated_objects {
  s1 = "this is a string"
  s2 = "another string"
  r = /[a-z]/
} # ruby 2.6.5 => 2, ruby 3.0.0 => 2, ruby 3.1.0 => 3

although ruby 3.1.0 return 3, but if i remove r from the above code, it still return 3

count_allocated_objects {
  s1 = "this is a string"
  s2 = "another string"
} # ruby 2.6.5 => 2, ruby 3.0.0 => 2, ruby 3.1.0 => 3

test with a frozen String

count_allocated_objects {
  s1 = "this is a string"
  s2 = "another string".freeze
} # ruby 2.6.5 => 1, ruby 3.0.0 => 1, ruby 3.1.0 => 2

For sure i checked a frozen String and Regexp in heap dump

require 'objspace'
ObjectSpace.trace_object_allocations_start

s1 = "this is a string"
s2 = "another string".freeze
r = /[a-z]/

p r.frozen? # true
p ObjectSpace.dump(r) # "{..\"type\":\"REGEXP\", ... \"frozen\":true ...
p ObjectSpace.dump(s2) # "{..\"type\":\"STRING\", ... \"frozen\":true ...
p ObjectSpace.dump(s1) # didn't contain \"frozen\"


问:
Does a Lua Table / Array Beautifier exist?
Considering all the json, xml formatters/beautifies out there, I’ve been unable to find one for Lua tables/arrays ?

The nuance here is that the output to beautify,  is from what i believe is a widely used table/array dump function - see below..

```<code>function dump(o)
    if type(o) == 'table' then
        local s = '{ '
        for k,v in pairs(o) do
            if type(k) ~= 'number' then
                k = '"'..k..'"'
            end
            s = s .. '['..k..'] = ' .. dump(v) .. ','
        end
        return s .. '} '
    else
        return tostring(o)
    end
end
</code>```

What I’m thinking is something like this.

A table dumped looks like this.

```<code>{[1] = ,[2] = { ["attr"] = { [1] = code,[2] = remaining,[3] = resetdate,["remaining"] = 990,["resetdate"] = 1638614242,["code"] = 200,} ,["tag"] = success,} ,[3] = ,["attr"] = { } ,["tag"] = prowl,}
</code>```

I’d love a beautifier that could present it like this..

```<code>{
[1] = ,
[2] = {
    ["attr"] = {
    [1] = code,
    [2] = remaining,
    [3] = resetdate,
    ["remaining"] = 990,
    ["resetdate"] = 1638614242,
    ["code"] = 200,
    } ,
    ["tag"] = success,
    } ,
[3] = ,
    ["attr"] = { } ,
    ["tag"] = prowl,
}
</code>```

答:
An example of such processing, you can correct the little things yourself:

```<code>function dump(o,level)
    level = level or 1
    if type(o) == 'table' then
        local s = {}
        s[1] = '{ '
        for k,v in pairs(o) do
            if type(k) ~= 'number' then
                k = '"'..k..'"'
            end
            s[#s+1] = string.rep('\t',level).. '['..k..'] = ' .. dump(v, level+1) .. ','
        end
        s[#s+1] = string.rep('\t',level) .. '} '
        return table.concat(s , "\n")
    else
        return tostring(o or 'nil')
    end
end
local t = {[1] = nil,[2] = { ["attr"] = { [1] = code,[2] = remaining,[3] = resetdate,["remaining"] = 990,["resetdate"] = 1638614242,["code"] = 200,} ,["tag"] = success,} ,[3] = nil,["attr"] = { } ,["tag"] = prowl,}

print (dump(t))
</code>```

result:

```<code>{
    ["attr"] = {
        } ,
    [2] = {
        ["attr"] = {
            ["remaining"] = 990,
            ["code"] = 200,
            ["resetdate"] = 1638614242,
            } ,
        } ,
    }
</code>```

you should also be aware that empty initialization values (like [3] =,) will throw an error, and generally zero data (like [3] = resetdate ) will be discarded in the dump, because assigning nil means deleting the table element.

Body:
Considering all the json, xml formatters/beautifies out there, I’ve been unable to find one for Lua tables/arrays ?

The nuance here is that the output to beautify,  is from what i believe is a widely used table/array dump function - see below..

function dump(o)
    if type(o) == 'table' then
        local s = '{ '
        for k,v in pairs(o) do
            if type(k) ~= 'number' then
                k = '"'..k..'"'
            end
            s = s .. '['..k..'] = ' .. dump(v) .. ','
        end
        return s .. '} '
    else
        return tostring(o)
    end
end

What I’m thinking is something like this.

A table dumped looks like this.

{[1] = ,[2] = { ["attr"] = { [1] = code,[2] = remaining,[3] = resetdate,["remaining"] = 990,["resetdate"] = 1638614242,["code"] = 200,} ,["tag"] = success,} ,[3] = ,["attr"] = { } ,["tag"] = prowl,}

I’d love a beautifier that could present it like this..

{
[1] = ,
[2] = {
    ["attr"] = {
    [1] = code,
    [2] = remaining,
    [3] = resetdate,
    ["remaining"] = 990,
    ["resetdate"] = 1638614242,
    ["code"] = 200,
    } ,
    ["tag"] = success,
    } ,
[3] = ,
    ["attr"] = { } ,
    ["tag"] = prowl,
}

Body:
An example of such processing, you can correct the little things yourself:

function dump(o,level)
    level = level or 1
    if type(o) == 'table' then
        local s = {}
        s[1] = '{ '
        for k,v in pairs(o) do
            if type(k) ~= 'number' then
                k = '"'..k..'"'
            end
            s[#s+1] = string.rep('\t',level).. '['..k..'] = ' .. dump(v, level+1) .. ','
        end
        s[#s+1] = string.rep('\t',level) .. '} '
        return table.concat(s , "\n")
    else
        return tostring(o or 'nil')
    end
end
local t = {[1] = nil,[2] = { ["attr"] = { [1] = code,[2] = remaining,[3] = resetdate,["remaining"] = 990,["resetdate"] = 1638614242,["code"] = 200,} ,["tag"] = success,} ,[3] = nil,["attr"] = { } ,["tag"] = prowl,}

print (dump(t))

result:

{
    ["attr"] = {
        } ,
    [2] = {
        ["attr"] = {
            ["remaining"] = 990,
            ["code"] = 200,
            ["resetdate"] = 1638614242,
            } ,
        } ,
    }

you should also be aware that empty initialization values (like [3] =,) will throw an error, and generally zero data (like [3] = resetdate ) will be discarded in the dump, because assigning nil means deleting the table element.


问:
Tkinter label overlap
for one of my first little projects I coded a fitnesscalculator last evening. Which has 3 functionalities at the start: Calculating the 1RM, BMI and FFMI. I'm running into the problem of overlapping labels when I first calculate the 1RM and then the FFMI. I have already googled and looked for similar threads but I couldn't find an answer to my solutions as my Gui is and its functionalities are based around a combobox. Please excuse the rather messy code, but I have already tried several methods to deal with this problem

```<code>from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk

root = Tk()
root.geometry("400x400")
root.title("Fitness Calculator")

#dropdown

Options = ["1RM Calculator", "BMI Calculator", "FFMI Calculator"]

#functions

def picker(input):
    global calculate_button
    global bf_box
    global bf_label
    global result_label
    global result2_label
    global result3_label
    calculate_button.destroy()
    result_label.pack_forget()
    result2_label.destroy()
    result3_label.destroy()
    bf_label.destroy()
    bf_box.destroy()
    selected = drop.get() #holt sich wert vom dropdown

    ####################RM CALCULATOR####################
    if selected == Options[0]:
        #labels
        weight_label = Label(root,text="Enter your training weight here: ", padx=10, pady=10)
        weight_label.grid(row=2, column=0, sticky=W)

        reps_label = Label(root,text="Enter your repetitions here: ", padx=10)
        reps_label.grid(row=3, column=0, sticky=W)
        def calculate():
            weight = int(weight_box.get())
            reps = int(reps_box.get())
            one_rm = round(weight*(36/(37-reps)), 2)
            #Result
            result_label = Label(root, text="Your 1RM is: " + str(one_rm) + " kg")
            result_label.grid(row=4)
            weight_box.delete(0,END)
            reps_box.delete(0,END)

        #Entryfields

        weight_box = Entry(root)
        weight_box.grid(row=2, column=1)

        reps_box = Entry(root)
        reps_box.grid(row=3, column=1)

        #Calculate button

        calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
        calculate_button.grid(row=4,column=1,pady=10)

    ####################BMI CALC####################
    if selected == Options[1]:
        #LABELS
        weight_label = Label(root,text="Enter your weight in kg here: ", padx=10, pady=10)
        weight_label.grid(row=2, column=0, sticky=W)

        height_label = Label(root,text="Enter your height in cm here: ", padx=10)
        height_label.grid(row=3, column=0, sticky=W)
        #ENTRY BOXES
        weight_box = Entry(root)
        weight_box.grid(row=2, column=1)

        height_box = Entry(root)
        height_box.grid(row=3, column=1)

        def calculate():
            weight = float(weight_box.get())
            height = float(height_box.get())/100
            bmi = round(weight/(height**2),0)
            #Result
            result_label = Label(root, text="Your BMI is: " + str(bmi))
            result_label.grid(row=4)
            weight_box.delete(0,END)
            height_box.delete(0,END)
        #Calculate button

        calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
        calculate_button.grid(row=4,column=1,pady=10)

    ####################FFMI####################
    if selected == Options[2]:
        calculate_button.destroy()
      #LABELS
        weight_label = Label(root,text="Enter your weight in kg here: ", padx=10,pady=5)
        weight_label.grid(row=2, column=0, sticky=W)
        height_label = Label(root,text="Enter your height in cm here: ", padx=10,pady=5)
        height_label.grid(row=3, column=0, sticky=W)
        bf_label = Label(root,text="Enter your estimated bodyfat % here: ", padx=10,pady=5)
        bf_label.grid(row=4, column=0, sticky=W)
        #ENTRY BOXES
        weight_box = Entry(root)
        weight_box.grid(row=2, column=1)
        height_box = Entry(root)
        height_box.grid(row=3, column=1)
        bf_box = Entry(root)
        bf_box.grid(row=4, column=1)
        def calculate():
            weight = float(weight_box.get())
            height = float(height_box.get())/100
            bf = float(bf_box.get())
            total_bf = weight*(bf)
            lean_weight = weight*(1-(bf/100))
            ffmi = round((lean_weight/height**2),2)
            adjusted_ffmi = ffmi + 6.1 * (1.8 - height)
            #Result
            result_label = Label(root, text="Lean Mass: " + str(lean_weight) + " kg")
            result_label.grid(row=6, sticky=W, padx=5)
            result_label2 = Label(root, text="FFMI: " + str(ffmi))
            result_label2.grid(row=7, sticky=W, padx=5)
            result_label3 = Label(root, text="adjusted-FFMI: " + str(adjusted_ffmi))
            result_label3.grid(row=8,sticky=W, padx=5)
            weight_box.delete(0,END)
            height_box.delete(0,END)
            bf_box.delete(0,END)
        #Calculate button
        calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
        calculate_button.grid(row=5,column=1,pady=10)

calculate_button = Button(root,text="Calculate", width=16 )
calculate_button.grid(row=4,column=1,pady=10)
calculate_button.destroy()

#Dropdownbox

drop = ttk.Combobox(root, value=Options, state="readonly")
drop.current(0)
drop.grid(row=0)
drop.bind("<<ComboboxSelected>>", picker)

result_label = Label(root,text="test")
result_label.grid(row=4)

result2_label = Label(root,text="")
result2_label.grid(row=4)

result3_label = Label(root,text="")
result3_label.grid(row=4)

bf_label = Label(root)
bf_box = Entry(root)

picker(drop.current(0))
root.mainloop()

</code>```

Here a Screenshot of the problem I'm referencing to:

答:
You keep creating a new Label with name result_label in your calculate methods.
This piles the labels on top of each other, since the result_label.destroy() does not remove them from the grid.

Instead of destroying them, keep just one instance (which you already defined global) and then configure them with the new text:

result_label.config(text="Your BMI is: " + str(bmi))
```

Title: Tkinter label overlap

Body:
for one of my first little projects I coded a fitnesscalculator last evening. Which has 3 functionalities at the start: Calculating the 1RM, BMI and FFMI. I'm running into the problem of overlapping labels when I first calculate the 1RM and then the FFMI. I have already googled and looked for similar threads but I couldn't find an answer to my solutions as my Gui is and its functionalities are based around a combobox. Please excuse the rather messy code, but I have already tried several methods to deal with this problem

from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk

root = Tk()
root.geometry("400x400")
root.title("Fitness Calculator")

#dropdown

Options = ["1RM Calculator", "BMI Calculator", "FFMI Calculator"]

#functions

def picker(input):
    global calculate_button
    global bf_box
    global bf_label
    global result_label
    global result2_label
    global result3_label
    calculate_button.destroy()
    result_label.pack_forget()
    result2_label.destroy()
    result3_label.destroy()
    bf_label.destroy()
    bf_box.destroy()
    selected = drop.get() #holt sich wert vom dropdown

    ####################RM CALCULATOR####################
    if selected == Options[0]:
        #labels
        weight_label = Label(root,text="Enter your training weight here: ", padx=10, pady=10)
        weight_label.grid(row=2, column=0, sticky=W)

        reps_label = Label(root,text="Enter your repetitions here: ", padx=10)
        reps_label.grid(row=3, column=0, sticky=W)
        def calculate():
            weight = int(weight_box.get())
            reps = int(reps_box.get())
            one_rm = round(weight*(36/(37-reps)), 2)
            #Result
            result_label = Label(root, text="Your 1RM is: " + str(one_rm) + " kg")
            result_label.grid(row=4)
            weight_box.delete(0,END)
            reps_box.delete(0,END)

        #Entryfields

        weight_box = Entry(root)
        weight_box.grid(row=2, column=1)

        reps_box = Entry(root)
        reps_box.grid(row=3, column=1)

        #Calculate button

        calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
        calculate_button.grid(row=4,column=1,pady=10)

    ####################BMI CALC####################
    if selected == Options[1]:
        #LABELS
        weight_label = Label(root,text="Enter your weight in kg here: ", padx=10, pady=10)
        weight_label.grid(row=2, column=0, sticky=W)

        height_label = Label(root,text="Enter your height in cm here: ", padx=10)
        height_label.grid(row=3, column=0, sticky=W)
        #ENTRY BOXES
        weight_box = Entry(root)
        weight_box.grid(row=2, column=1)

        height_box = Entry(root)
        height_box.grid(row=3, column=1)

        def calculate():
            weight = float(weight_box.get())
            height = float(height_box.get())/100
            bmi = round(weight/(height**2),0)
            #Result
            result_label = Label(root, text="Your BMI is: " + str(bmi))
            result_label.grid(row=4)
            weight_box.delete(0,END)
            height_box.delete(0,END)
        #Calculate button

        calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
        calculate_button.grid(row=4,column=1,pady=10)

    ####################FFMI####################
    if selected == Options[2]:
        calculate_button.destroy()
      #LABELS
        weight_label = Label(root,text="Enter your weight in kg here: ", padx=10,pady=5)
        weight_label.grid(row=2, column=0, sticky=W)
        height_label = Label(root,text="Enter your height in cm here: ", padx=10,pady=5)
        height_label.grid(row=3, column=0, sticky=W)
        bf_label = Label(root,text="Enter your estimated bodyfat % here: ", padx=10,pady=5)
        bf_label.grid(row=4, column=0, sticky=W)
        #ENTRY BOXES
        weight_box = Entry(root)
        weight_box.grid(row=2, column=1)
        height_box = Entry(root)
        height_box.grid(row=3, column=1)
        bf_box = Entry(root)
        bf_box.grid(row=4, column=1)
        def calculate():
            weight = float(weight_box.get())
            height = float(height_box.get())/100
            bf = float(bf_box.get())
            total_bf = weight*(bf)
            lean_weight = weight*(1-(bf/100))
            ffmi = round((lean_weight/height**2),2)
            adjusted_ffmi = ffmi + 6.1 * (1.8 - height)
            #Result
            result_label = Label(root, text="Lean Mass: " + str(lean_weight) + " kg")
            result_label.grid(row=6, sticky=W, padx=5)
            result_label2 = Label(root, text="FFMI: " + str(ffmi))
            result_label2.grid(row=7, sticky=W, padx=5)
            result_label3 = Label(root, text="adjusted-FFMI: " + str(adjusted_ffmi))
            result_label3.grid(row=8,sticky=W, padx=5)
            weight_box.delete(0,END)
            height_box.delete(0,END)
            bf_box.delete(0,END)
        #Calculate button
        calculate_button = Button(root,text="Calculate",command=calculate, width=16 )
        calculate_button.grid(row=5,column=1,pady=10)

calculate_button = Button(root,text="Calculate", width=16 )
calculate_button.grid(row=4,column=1,pady=10)
calculate_button.destroy()

#Dropdownbox

drop = ttk.Combobox(root, value=Options, state="readonly")
drop.current(0)
drop.grid(row=0)
drop.bind("<<ComboboxSelected>>", picker)

result_label = Label(root,text="test")
result_label.grid(row=4)

result2_label = Label(root,text="")
result2_label.grid(row=4)

result3_label = Label(root,text="")
result3_label.grid(row=4)

bf_label = Label(root)
bf_box = Entry(root)

picker(drop.current(0))
root.mainloop()

Here a Screenshot of the problem I'm referencing to:


问:
Hadoop 2.6 Mapreduce permissions incorrectly set on Windows
I have installed Hadoop 2.6 on Windows as a test bed for some software that is dependent on Hadoop.  The install worked correctly as far as I can tell. I have Hadoop saved in C:\Hadoop and my temporary folder in C:\hadooptemp.  I followed this tutorial on getting it set up:
https://drive.google.com/file/d/0BweVwq32koypYm1QWHNvRTZWTm8/view

When I run the hadoop-mapreduce-examples-2.6.0.jar for pi, as provided in the tutorial, I get the following output:

```<code>Number of Maps  = 2
Samples per Map = 5
Wrote input for Map #0
Wrote input for Map #1
Starting Job
15/08/27 15:55:10 INFO client.RMProxy: Connecting to ResourceManager at /155.41.90.116:8032
15/08/27 15:55:12 INFO input.FileInputFormat: Total input paths to process : 2
15/08/27 15:55:12 INFO mapreduce.JobSubmitter: number of splits:2
15/08/27 15:55:13 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1440705227041_0001
15/08/27 15:55:14 INFO impl.YarnClientImpl: Submitted application application_1440705227041_0001
15/08/27 15:55:14 INFO mapreduce.Job: The url to track the job: http://mycomp:8088/proxy/application_1440705227041_0001/
15/08/27 15:55:14 INFO mapreduce.Job: Running job: job_1440705227041_0001
15/08/27 15:55:35 INFO mapreduce.Job: Job job_1440705227041_0001 running in uber mode : false
15/08/27 15:55:35 INFO mapreduce.Job:  map 0% reduce 0%
15/08/27 15:55:35 INFO mapreduce.Job: Job job_1440705227041_0001 failed with state FAILED due to: Application application_1440705227041_0001 failed 2 times due to AM Container for appattempt_1440705227041_0001_000002 exited with  exitCode: -1000
For more detailed output, check application tracking page:http://mycomp:8088/proxy/application_1440705227041_0001/Then, click on links to logs of each attempt.
</code>```

Diagnostics: Failed to setup local dir /hadooptemp/nm-local-dir, which was marked as good.

```<code>Failing this attempt. Failing the application.
15/08/27 15:55:35 INFO mapreduce.Job: Counters: 0
Job Finished in 25.444 seconds
java.io.FileNotFoundException: File does not exist: hdfs://155.41.90.116:8020/user/me/QuasiMonteCarlo_1440705304456_1878814183/out/reduce-out
        at org.apache.hadoop.hdfs.DistributedFileSystem$18.doCall(DistributedFileSystem.java:1122)
        at org.apache.hadoop.hdfs.DistributedFileSystem$18.doCall(DistributedFileSystem.java:1114)
        at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
        at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1130)
        at org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1751)
        at org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1774)
        at org.apache.hadoop.examples.QuasiMonteCarlo.estimatePi(QuasiMonteCarlo.java:314)
        at org.apache.hadoop.examples.QuasiMonteCarlo.run(QuasiMonteCarlo.java:354)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
        at org.apache.hadoop.examples.QuasiMonteCarlo.main(QuasiMonteCarlo.java:363)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:71)
        at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:144)
        at org.apache.hadoop.examples.ExampleDriver.main(ExampleDriver.java:74)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
</code>```

From what I have been tracing with the exitCode: -1000, to comes down to Hadoop not being able to setup the local directory with appropriate permissions. I believe in the tutorial I am using above, that is why they disable the User Account Controls. Whether or not I do this, I get the same error.

I also found a similar issue in this link:
Mapreduce error: Failed to setup local dir

I tried to follow as they said, and make both C:\Hadoop and C:\hadooptemp owned by my user account through the folder properties, security, and advanced settings. I was listed as the owner before, and I have full control access to the folder according to this. Either that isn't the issue, or I have incorrectly assigned the ownership to my account.

Finally, in my YARN Node Manager, I get the following error that seems to possibly be related which pops up in a few places:

```<code>15/08/27 15:55:34 WARN localizer.ResourceLocalizationService: Permissions incorrectly set for dir /hadooptemp/nm-local-dir/usercache, should be rwxr-xr-x, actual value = rwxrwxr-x
</code>```

It seems that I have too many permissions, as it states they are incorrectly set?  I can't imagine this is the cause of the issue, that my group also has write permissions, but I couldn't figure out how to alter that in Windows.

Any help on figuring out the details of the permissions problem to fix this error would be appreciated.

答: Run command prompt as administrator and the use commands start-dfs and start-yarn.

Body:
I have installed Hadoop 2.6 on Windows as a test bed for some software that is dependent on Hadoop.  The install worked correctly as far as I can tell. I have Hadoop saved in C:\Hadoop and my temporary folder in C:\hadooptemp.  I followed this tutorial on getting it set up:
https://drive.google.com/file/d/0BweVwq32koypYm1QWHNvRTZWTm8/view

When I run the hadoop-mapreduce-examples-2.6.0.jar for pi, as provided in the tutorial, I get the following output:

Number of Maps  = 2
Samples per Map = 5
Wrote input for Map #0
Wrote input for Map #1
Starting Job
15/08/27 15:55:10 INFO client.RMProxy: Connecting to ResourceManager at /155.41.90.116:8032
15/08/27 15:55:12 INFO input.FileInputFormat: Total input paths to process : 2
15/08/27 15:55:12 INFO mapreduce.JobSubmitter: number of splits:2
15/08/27 15:55:13 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1440705227041_0001
15/08/27 15:55:14 INFO impl.YarnClientImpl: Submitted application application_1440705227041_0001
15/08/27 15:55:14 INFO mapreduce.Job: The url to track the job: http://mycomp:8088/proxy/application_1440705227041_0001/
15/08/27 15:55:14 INFO mapreduce.Job: Running job: job_1440705227041_0001
15/08/27 15:55:35 INFO mapreduce.Job: Job job_1440705227041_0001 running in uber mode : false
15/08/27 15:55:35 INFO mapreduce.Job:  map 0% reduce 0%
15/08/27 15:55:35 INFO mapreduce.Job: Job job_1440705227041_0001 failed with state FAILED due to: Application application_1440705227041_0001 failed 2 times due to AM Container for appattempt_1440705227041_0001_000002 exited with  exitCode: -1000
For more detailed output, check application tracking page:http://mycomp:8088/proxy/application_1440705227041_0001/Then, click on links to logs of each attempt.

Diagnostics: Failed to setup local dir /hadooptemp/nm-local-dir, which was marked as good.

Failing this attempt. Failing the application.
15/08/27 15:55:35 INFO mapreduce.Job: Counters: 0
Job Finished in 25.444 seconds
java.io.FileNotFoundException: File does not exist: hdfs://155.41.90.116:8020/user/me/QuasiMonteCarlo_1440705304456_1878814183/out/reduce-out
        at org.apache.hadoop.hdfs.DistributedFileSystem$18.doCall(DistributedFileSystem.java:1122)
        at org.apache.hadoop.hdfs.DistributedFileSystem$18.doCall(DistributedFileSystem.java:1114)
        at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
        at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1130)
        at org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1751)
        at org.apache.hadoop.io.SequenceFile$Reader.<init>(SequenceFile.java:1774)
        at org.apache.hadoop.examples.QuasiMonteCarlo.estimatePi(QuasiMonteCarlo.java:314)
        at org.apache.hadoop.examples.QuasiMonteCarlo.run(QuasiMonteCarlo.java:354)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
        at org.apache.hadoop.examples.QuasiMonteCarlo.main(QuasiMonteCarlo.java:363)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:71)
        at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:144)
        at org.apache.hadoop.examples.ExampleDriver.main(ExampleDriver.java:74)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:136)

From what I have been tracing with the exitCode: -1000, to comes down to Hadoop not being able to setup the local directory with appropriate permissions. I believe in the tutorial I am using above, that is why they disable the User Account Controls. Whether or not I do this, I get the same error.

I also found a similar issue in this link:
Mapreduce error: Failed to setup local dir

I tried to follow as they said, and make both C:\Hadoop and C:\hadooptemp owned by my user account through the folder properties, security, and advanced settings. I was listed as the owner before, and I have full control access to the folder according to this. Either that isn't the issue, or I have incorrectly assigned the ownership to my account.

Finally, in my YARN Node Manager, I get the following error that seems to possibly be related which pops up in a few places:

15/08/27 15:55:34 WARN localizer.ResourceLocalizationService: Permissions incorrectly set for dir /hadooptemp/nm-local-dir/usercache, should be rwxr-xr-x, actual value = rwxrwxr-x

It seems that I have too many permissions, as it states they are incorrectly set?  I can't imagine this is the cause of the issue, that my group also has write permissions, but I couldn't figure out how to alter that in Windows.

Any help on figuring out the details of the permissions problem to fix this error would be appreciated.


问:
How to get receipts from near-api-js?
When calling a change function a function with near-api-js, how can I get the receipt of the transaction?

I've tried:

const response = await contract.changeMethod({args})
console.log(response)
```

But it doesn't seem to be working

答:
You have to use the functionCall method on the wallet to get the receipt of the transaction.

const response = await wallet.account().functionCall({
 contractId: 'yourContractId',
 methodName: 'changeMethod',
 args,
})
```

More details in this answer.

Title: How to get receipts from near-api-js?

Body:
When calling a change function a function with near-api-js, how can I get the receipt of the transaction?

I've tried:

const response = await contract.changeMethod({args})
console.log(response)

But it doesn't seem to be working

Body:
You have to use the functionCall method on the wallet to get the receipt of the transaction.

const response = await wallet.account().functionCall({
 contractId: 'yourContractId',
 methodName: 'changeMethod',
 args,
})

More details in this answer.


问:
Spring boot unable to autowire class in tests after disable JPA
hope you all are doing well

I'm facing some problems on testing my Spring Boot application. I created a simple API (currently has only one method, and it's working) and I created the domain tests disabling JPA configurations. When I test with JPA disabled, the tests provide the following error:

```<code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mhrehbein.curriculum.register.infrastructure.mysql.ISpringDataAboutMeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
</code>```

When I enable JPA configuration it works fine, but I would like to disable once it is unit tests. You can check the code in the following PR: https://github.com/retatu/curriculum/pull/6/files (sorry for it)

In the code you can see that all tests are broke, the tests are basically the same and the example is here: https://github.com/retatu/curriculum/blob/dev/src/test/java/com/mhrehbein/curriculum/register/domain/entity/AboutMeTest.java

Appreciate any help

答:
Spring has it's spring application context which is working as a container of beans. The BeanFactory represents spring's inversion of control container. What it does is exposing beans to the application. When your application requires a bean which is not available then it throws NoSuchBeanDefinitionException.

I think your question and the root cause is best answered in the below question. Hope it will five you insights of the problem.

What is a NoSuchBeanDefinitionException and how do I fix it?

Body:
hope you all are doing well

I'm facing some problems on testing my Spring Boot application. I created a simple API (currently has only one method, and it's working) and I created the domain tests disabling JPA configurations. When I test with JPA disabled, the tests provide the following error:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mhrehbein.curriculum.register.infrastructure.mysql.ISpringDataAboutMeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

When I enable JPA configuration it works fine, but I would like to disable once it is unit tests. You can check the code in the following PR: https://github.com/retatu/curriculum/pull/6/files (sorry for it)

In the code you can see that all tests are broke, the tests are basically the same and the example is here: https://github.com/retatu/curriculum/blob/dev/src/test/java/com/mhrehbein/curriculum/register/domain/entity/AboutMeTest.java

Appreciate any help


问:
view.py got an unexpected keyword argument topic_id #p
I'm trying to fix this view keep getting this error message,
'''
Exception Type: TypeError
Exception Value:

topics() got an unexpected keyword argument 'topic_id'
Exception Location: /home/draco/shola/learning_log/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response
'''

view.py

```<code>def topics(request):

    topics = TopicModel.objects.order_by('date_added')
    context = {'topics' : topics}
    return render(request, 'learning_logs/topics.html',context)

def topic(request, topic_id):
    topic = TopicModel.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('date_added')
    context = {'topic':topic, 'entries': entries}
    return render(request,'learning_logs/topic.html',context)
</code>```

urls.py

```<code>url(r'^$', views.index, name='index.html'),

url(r'^topics/$',views.topics, name='topics.html'),
url(r'^topics/(?P<topic_id>\d+)\$',views.topics,name='topic.html')
</code>```

models.py

```<code>    from django.db import models

class Topic(models.Model):

    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):

        return self.text

class Entry(models.Model):

    topic = models.ForeignKey(Topic,
                              on_delete = models.DO_NOTHING)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        if len(self.text) >50:

            return  self.text[:50]+"....."

        else:
            return self.text
</code>```

Template

```<code>    <!DOCTYPE html>
{% extends "learning_logs/base.html" %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% block content%}
<p>Topics</p>

<ul>
    {%for topic in topics%}
    <li>
        <a href="{% url 'learning_logs:topic.html' topic.id %}">{{topic}}</a>
    </li>
    {%empty%}
    <li>no topic have been added yet</li>
    {%endfor%}

</ul>
{%endblock content%}
</body>
</html>
</code>```

答:
Error in this line of code:

```<code> url(r'^topics/(?P<topic_id>\d+)\$',views.topics,name='topic.html')

 url(r'^topics/(?P<topic_id>\d+)\$',**views.topics**,name='topic.html')
</code>```

should be corrected for

```<code> url(r'^topics/(?P<topic_id>\d+)\$',**views.topic**,name='topic.html')
</code>```

Body:
I'm trying to fix this view keep getting this error message,
'''
Exception Type: TypeError
Exception Value:

topics() got an unexpected keyword argument 'topic_id'
Exception Location: /home/draco/shola/learning_log/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response
'''

view.py

def topics(request):

    topics = TopicModel.objects.order_by('date_added')
    context = {'topics' : topics}
    return render(request, 'learning_logs/topics.html',context)

def topic(request, topic_id):
    topic = TopicModel.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('date_added')
    context = {'topic':topic, 'entries': entries}
    return render(request,'learning_logs/topic.html',context)

urls.py

url(r'^$', views.index, name='index.html'),

url(r'^topics/$',views.topics, name='topics.html'),
url(r'^topics/(?P<topic_id>\d+)\$',views.topics,name='topic.html')

models.py

    from django.db import models

class Topic(models.Model):

    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):

        return self.text

class Entry(models.Model):

    topic = models.ForeignKey(Topic,
                              on_delete = models.DO_NOTHING)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        if len(self.text) >50:

            return  self.text[:50]+"....."

        else:
            return self.text

Template

    <!DOCTYPE html>
{% extends "learning_logs/base.html" %}

    <meta charset="UTF-8">
    <title>Title</title>

{% block content%}

Topics

    {%for topic in topics%}

        {{topic}}

    {%empty%}

no topic have been added yet

    {%endfor%}

{%endblock content%}

Body:
Error in this line of code:

 url(r'^topics/(?P<topic_id>\d+)\$',views.topics,name='topic.html')

 url(r'^topics/(?P<topic_id>\d+)\$',**views.topics**,name='topic.html')

should be corrected for

 url(r'^topics/(?P<topic_id>\d+)\$',**views.topic**,name='topic.html')


问:
Extracting values from one of multiple PRISM rasters in R for date
I have tried to follow the code from [https://stackoverflow.com/questions/63237565/extracting-values-from-one-of-multiple-prism-rasters-in-r][1] but I keep running into multiple errors.  I am also trying to extra daily precipitation rather than monthly temperature.

```<code>dates <-  seq(as.Date("2019-01-01"),as.Date("2019-12-31"), by="days")

library(prism)

for (d in unique(dates)) {
  dir.create(d, FALSE)
  options(prism.path = d)
  get_prism_dailys(type = "ppt", dates = d)
}

#Error in dir.create(d, FALSE) : invalid 'path' argument

locs <- foo.df[,5:4]
head(locs)
length(locs)

locs$Longitude<-as.numeric(locs$Longitude)
locs$Latitude<-as.numeric(locs$Latitude)

#Keep things simple and put the results in a list first
temps <- list()
for(i in 1:length(dates)) {
  options(prism.path = dates[i])
  climate_data <- prism_stack(ls_prism_data())
  temps[[i]] <- extract(climate_data, locs)
}

#Error in list.files(getOption("prism.path")) : invalid 'path' argument
#In addition: Warning messages:
#  1: 'prism_stack' is deprecated.
#Use '`pd_stack()`' instead.
#See help("Deprecated")
#2: 'ls_prism_data' is deprecated.
#Use '`prism_archive_ls()`' instead.
#See help("Deprecated")
</code>```

I'm not sure what I need to change to a) make this code work for days vs years and b) how to convert this script from the deprecated code to the newest code.

Thanks for your help

答:
Let's go step by step.

library(prism)
#> Be sure to set the download folder using `prism_set_dl_dir()`.
dates <-  seq(as.Date("2019-01-01"),as.Date("2019-01-02"), by="days")
unique(dates)
#> [1] "2019-01-01" "2019-01-02"
```
<p>Till now everything is fine.</p>
```for (d in unique(dates)) {
  dir.create(d, FALSE)
  options(prism.path = d)
  get_prism_dailys(type = "ppt", dates = d)
}

#Error in dir.create(d, FALSE) : invalid 'path' argument
```
<p>Why?? Let's see what's wrong:</p>
<pre class="lang-r prettyprint-override"><code>for (d in unique(dates)) {
  print(d)
}

#> [1] 17897
#> [1] 17898
</code>```

Ah, d in dates is converted to integer, and dir.create() expects an character. Let's change it providing the dates as.character:

for (d in 1:length(dates)) {
  dir.create(as.character(dates[d]), TRUE)
  options(prism.path = as.character(dates[d]))
  get_prism_dailys(type = "ppt", dates = dates[d])
}
#>   |   0%  |
     |======================================================================| 100%
#>   |   0%  |
     |======================================================================| 100%
```
<p>Seems data was downloaded; to be sure we can check it right now:</p>
<pre class="lang-r prettyprint-override"><code>list.files(as.character(dates[1]))
#> [1] "PRISM_ppt_stable_4kmD2_20190101_bil"
#> [2] "PRISM_ppt_stable_4kmD2_20190101_bil.zip"
</code>```

As you haven's shared details of `foo.df`` I will skip this part:

locs <- foo.df[,5:4]
head(locs)
length(locs)

locs$Longitude<-as.numeric(locs$Longitude)
locs$Latitude<-as.numeric(locs$Latitude)
```
<p>The rest is pretty simple: below error is the same as previous, <code>path</code> has to be <code>character</code></p>
<pre class="lang-r prettyprint-override"><code>#Error in list.files(getOption("prism.path")) : invalid 'path' argument
</code>```

So, let's supply as.character as needed. The deprecated function should be replaced by the new ones, like:

#Keep things simple and put the results in a list first
temps <- list()
for(i in 1:length(dates)) {
  options(prism.path = as.character(dates[i]))
  climate_data <- pd_stack(prism_archive_ls())
  temps[[i]] <- extract(climate_data, locs)
}
```

Regards,
Grzegorz

Body:
I have tried to follow the code from [https://stackoverflow.com/questions/63237565/extracting-values-from-one-of-multiple-prism-rasters-in-r][1] but I keep running into multiple errors.  I am also trying to extra daily precipitation rather than monthly temperature.

dates <-  seq(as.Date("2019-01-01"),as.Date("2019-12-31"), by="days")

library(prism)

for (d in unique(dates)) {
  dir.create(d, FALSE)
  options(prism.path = d)
  get_prism_dailys(type = "ppt", dates = d)
}

#Error in dir.create(d, FALSE) : invalid 'path' argument

locs <- foo.df[,5:4]
head(locs)
length(locs)

locs$Longitude<-as.numeric(locs$Longitude)
locs$Latitude<-as.numeric(locs$Latitude)

#Keep things simple and put the results in a list first
temps <- list()
for(i in 1:length(dates)) {
  options(prism.path = dates[i])
  climate_data <- prism_stack(ls_prism_data())
  temps[[i]] <- extract(climate_data, locs)
}

#Error in list.files(getOption("prism.path")) : invalid 'path' argument
#In addition: Warning messages:
#  1: 'prism_stack' is deprecated.
#Use '`pd_stack()`' instead.
#See help("Deprecated")
#2: 'ls_prism_data' is deprecated.
#Use '`prism_archive_ls()`' instead.
#See help("Deprecated")

I'm not sure what I need to change to a) make this code work for days vs years and b) how to convert this script from the deprecated code to the newest code.

Thanks for your help

Body:
Let's go step by step.

library(prism)
#> Be sure to set the download folder using `prism_set_dl_dir()`.
dates <-  seq(as.Date("2019-01-01"),as.Date("2019-01-02"), by="days")
unique(dates)
#> [1] "2019-01-01" "2019-01-02"

Till now everything is fine.

for (d in unique(dates)) {
  dir.create(d, FALSE)
  options(prism.path = d)
  get_prism_dailys(type = "ppt", dates = d)
}

#Error in dir.create(d, FALSE) : invalid 'path' argument

Why?? Let's see what's wrong:

for (d in unique(dates)) {
  print(d)
}

#> [1] 17897
#> [1] 17898

Ah, d in dates is converted to integer, and dir.create() expects an character. Let's change it providing the dates as.character:

for (d in 1:length(dates)) {
  dir.create(as.character(dates[d]), TRUE)
  options(prism.path = as.character(dates[d]))
  get_prism_dailys(type = "ppt", dates = dates[d])
}
#>   |   0%  |
     |======================================================================| 100%
#>   |   0%  |
     |======================================================================| 100%

Seems data was downloaded; to be sure we can check it right now:

list.files(as.character(dates[1]))
#> [1] "PRISM_ppt_stable_4kmD2_20190101_bil"
#> [2] "PRISM_ppt_stable_4kmD2_20190101_bil.zip"

As you haven's shared details of `foo.df`` I will skip this part:

locs <- foo.df[,5:4]
head(locs)
length(locs)

locs$Longitude<-as.numeric(locs$Longitude)
locs$Latitude<-as.numeric(locs$Latitude)

The rest is pretty simple: below error is the same as previous, path has to be character

#Error in list.files(getOption("prism.path")) : invalid 'path' argument

So, let's supply as.character as needed. The deprecated function should be replaced by the new ones, like:

#Keep things simple and put the results in a list first
temps <- list()
for(i in 1:length(dates)) {
  options(prism.path = as.character(dates[i]))
  climate_data <- pd_stack(prism_archive_ls())
  temps[[i]] <- extract(climate_data, locs)
}

Regards,
Grzegorz


问:
How to save a Dataframe in batches in Pyspark?
I am trying to split a dataframe into chunks using the following code:

```<code>chunk = 50
id1 = 0
id2 = chunk
df = df.withColumn('id_tmp', F.monotonically_increasing_id())
c = df.count()
while id1 < c:
    stop_df = df.filter((df['id_tmp'] < id2) & (df['id_tmp'] >= id1))

    stop_df.write \
        .mode('overwrite')\
        .option("header", True) \
        .option("sep", "|") \
        .option('quoteAll', True) \
        .format("csv") \
        .save("filepath")

    id1 += chunk
    id2 += chunk
</code>```

But it's only writing the first 50 rows (1st chunk) into csv.

What changes do I need to make to save other chunks as well?

答:
The problem is that the function monotonically_increasing_id doesn't generate consecutive numbers. From the docs:

The generated ID is guaranteed to be monotonically increasing and
unique, but not consecutive. The current implementation puts the partition ID in the upper 31 bits, and the record number within each partition in the lower 33 bits. ...

If we add df.show() to your code we can see this happening, it starts of OK but the next partition it jumps dramatically:

```<code>df = spark.range(0,90)
chunk = 50
id1 = 0
id2 = chunk
df = df.withColumn('id_tmp', F.monotonically_increasing_id())
df.show()

+---+-----------+
| id|     id_tmp|
+---+-----------+
|  0|          0|
|  1|          1|
|  2|          2|
|  3|          3|
|  4|          4|
|  5| 8589934592|
|  6| 8589934593|
|  7| 8589934594|
|  8| 8589934595|
|  9| 8589934596|
| 10| 8589934597|
| 11|17179869184|
| 12|17179869185|
| 13|17179869186|
| 14|17179869187|
| 15|17179869188|
| 16|25769803776|
| 17|25769803777|
| 18|25769803778|
| 19|25769803779|
+---+-----------+
</code>```

If you need exact batch sizes you could use row_number over a window, but this window would need to include your complete df, making it inefficient. Could be ok for smaller dfs at the end of a data processing pipeline, or if you can partition by a column.

Some other solutions are discussed in this SO question.
Finally, you probably want to use a different path for each batch, otherwise all data will be overwritten each time.

Body:
I am trying to split a dataframe into chunks using the following code:

chunk = 50
id1 = 0
id2 = chunk
df = df.withColumn('id_tmp', F.monotonically_increasing_id())
c = df.count()
while id1 < c:
    stop_df = df.filter((df['id_tmp'] < id2) & (df['id_tmp'] >= id1))

    stop_df.write \
        .mode('overwrite')\
        .option("header", True) \
        .option("sep", "|") \
        .option('quoteAll', True) \
        .format("csv") \
        .save("filepath")

    id1 += chunk
    id2 += chunk

But it's only writing the first 50 rows (1st chunk) into csv.

What changes do I need to make to save other chunks as well?

Body:
The problem is that the function monotonically_increasing_id doesn't generate consecutive numbers. From the docs:

The generated ID is guaranteed to be monotonically increasing and
unique, but not consecutive. The current implementation puts the partition ID in the upper 31 bits, and the record number within each partition in the lower 33 bits. ...

If we add df.show() to your code we can see this happening, it starts of OK but the next partition it jumps dramatically:

df = spark.range(0,90)
chunk = 50
id1 = 0
id2 = chunk
df = df.withColumn('id_tmp', F.monotonically_increasing_id())
df.show()

+---+-----------+
| id|     id_tmp|
+---+-----------+
|  0|          0|
|  1|          1|
|  2|          2|
|  3|          3|
|  4|          4|
|  5| 8589934592|
|  6| 8589934593|
|  7| 8589934594|
|  8| 8589934595|
|  9| 8589934596|
| 10| 8589934597|
| 11|17179869184|
| 12|17179869185|
| 13|17179869186|
| 14|17179869187|
| 15|17179869188|
| 16|25769803776|
| 17|25769803777|
| 18|25769803778|
| 19|25769803779|
+---+-----------+

If you need exact batch sizes you could use row_number over a window, but this window would need to include your complete df, making it inefficient. Could be ok for smaller dfs at the end of a data processing pipeline, or if you can partition by a column.

Some other solutions are discussed in this SO question.
Finally, you probably want to use a different path for each batch, otherwise all data will be overwritten each time.


问:
I don't understand how to return all values in string with return string[i:i+max_width]?
I have a code and I wanna return all values in string with newline.

```<code>def wrap(string, max_width):
for i in range(0, len(string), max_width):
    return string[i:i+max_width]

# You can't change anything here.
if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)
</code>```

My input

```<code>ABCDEFGHIJKLIMNOQRSTUVWXYZ
4
</code>```

Required output

```<code>ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
</code>```

My output

```<code>ABCD
</code>```

答:
The problem with the code is that you need to run the wrap function n times not just return the value. Also, return breaks the function so it executes only once. One of the correct codes would be:</p>
```<code>def wrap(string, max_width):
    temp = ''
    for i in range(0, len(string), max_width):
        temp += f'{string[i:i+max_width]}\n'
    return temp

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)
</code>```

Body:
I have a code and I wanna return all values in string with newline.

def wrap(string, max_width):
for i in range(0, len(string), max_width):
    return string[i:i+max_width]

# You can't change anything here.
if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

My input

ABCDEFGHIJKLIMNOQRSTUVWXYZ
4

Required output

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ

My output

ABCD

Body:
The problem with the code is that you need to run the wrap function n times not just return the value. Also, return breaks the function so it executes only once. One of the correct codes would be:

def wrap(string, max_width):
    temp = ''
    for i in range(0, len(string), max_width):
        temp += f'{string[i:i+max_width]}\n'
    return temp

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)


问:
Optionals with @ObservedObject and @Published var
I am getting quite mad with unwrapping optionals on a SwiftUI project. The project has (removed extra lines for readability):

struct Report: Decodable {
    var siteId: String = "nosite"

    enum ReportKeys: String, CodingKey { //some keys here
    }

    init(from decoder: Decoder) throws {
        // all the code for remapping json properties to the struct
    }
}

class ReportCaller: NSObject, URLSessionDelegate, ObservableObject {
    @Published var lastReport: Report?

    override init() {
        super.init()
        loadReport()
    }

    func loadReport() {
        // URL session code that finally returns
        self.lastReport =  try! decoder.decode(Report, from: data)
    }
```
<p>The, in my view, I have</p>
<pre class="lang-swift prettyprint-override"><code>struct ContentView: View {
    @ObservedObject var report = ReportCaller()
</code>```

Now, to make it working, I must unwrap each line, as below:

```<code>Text(report.lastReport?.siteId ?? "")
</code>```

The struct has defaults, so I would expect to not unwrap anything. I recognize I miss some initialization, but I cannot figure out where I should put it. The @ObservedObject calls a class, it seems not the place where to do it. Because the class publishes an optional Report?, I thought to remove the optional there, but I get another problem:

Property 'self.lastReport' not initialized at super.init call
```
<p>I can try to make</p>
<pre class="lang-swift prettyprint-override"><code>    override init() {
        self.lastReport = Metar()
        super.init()
        loadReport()
    }
</code>```

Although the compiler complains the from: is missing, because this is effectively what the init in the struct expects. So, I am getting confused on which should be the best way to manage the problem.

答:
The solution is apparently to extend my own struct and provide a default init

struct Report: Decodable {
    var siteId: String
    enum ReportKeys: String, CodingKey { //some keys here
    }

    init(from decoder: Decoder) throws {
        // all the code for remapping json properties to the struct
    }

    init() {
        self.siteId = "nosite"
    }
}
```

This allows to call a default init of the struct, which can happen without decoding anything, and removes the need to unwrap, because there is a default for everything.

Body:
I am getting quite mad with unwrapping optionals on a SwiftUI project. The project has (removed extra lines for readability):

struct Report: Decodable {
    var siteId: String = "nosite"

    enum ReportKeys: String, CodingKey { //some keys here
    }

    init(from decoder: Decoder) throws {
        // all the code for remapping json properties to the struct
    }
}

class ReportCaller: NSObject, URLSessionDelegate, ObservableObject {
    @Published var lastReport: Report?

    override init() {
        super.init()
        loadReport()
    }

    func loadReport() {
        // URL session code that finally returns
        self.lastReport =  try! decoder.decode(Report, from: data)
    }

The, in my view, I have

struct ContentView: View {
    @ObservedObject var report = ReportCaller()

Now, to make it working, I must unwrap each line, as below:

Text(report.lastReport?.siteId ?? "")

The struct has defaults, so I would expect to not unwrap anything. I recognize I miss some initialization, but I cannot figure out where I should put it. The @ObservedObject calls a class, it seems not the place where to do it. Because the class publishes an optional Report?, I thought to remove the optional there, but I get another problem:

Property 'self.lastReport' not initialized at super.init call

I can try to make

    override init() {
        self.lastReport = Metar()
        super.init()
        loadReport()
    }

Although the compiler complains the from: is missing, because this is effectively what the init in the struct expects. So, I am getting confused on which should be the best way to manage the problem.

Body:
The solution is apparently to extend my own struct and provide a default init

struct Report: Decodable {
    var siteId: String
    enum ReportKeys: String, CodingKey { //some keys here
    }

    init(from decoder: Decoder) throws {
        // all the code for remapping json properties to the struct
    }

    init() {
        self.siteId = "nosite"
    }
}

This allows to call a default init of the struct, which can happen without decoding anything, and removes the need to unwrap, because there is a default for everything.


问:
MatDatepickerFilter - Filter function can't access class variable
A MatDatePicker with a filter defined as followed:

<mat-form-field class="example-full-width">
  <input matInput [matDatepickerFilter]="myFilter" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
```

<pre class="lang-typescript prettyprint-override"><code>export class DatepickerFilterExample {
  someDateToBlock: number = 3;
  myFilter = (d: Date): boolean => {
    const day = d.getDay();
    // THIS FUNCTION CANNOT ACCESS THE VARIABLE 'someDateToBlock'
    return day !== 0 && day !== 6;
  }
}
</code>```

I would like to access the variable someDateToBlock (or any other) in the filter function. Is there a workaround to make this possbile?

答:
Type '(d: Date) => boolean' is not assignable to type 'DateFilterFn<Date | null>'</p>
```<code>myFilter = (d: Date ** |null **): boolean => {
   const day = (d || new Date()).getDay();
   // Prevent Saturday and Sunday from being selected.
   return day !== 0 && day !== 6;
};
</code>```

Body:
A MatDatePicker with a filter defined as followed:

<mat-form-field class="example-full-width">
  <input matInput [matDatepickerFilter]="myFilter" [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

export class DatepickerFilterExample {
  someDateToBlock: number = 3;
  myFilter = (d: Date): boolean => {
    const day = d.getDay();
    // THIS FUNCTION CANNOT ACCESS THE VARIABLE 'someDateToBlock'
    return day !== 0 && day !== 6;
  }
}

I would like to access the variable someDateToBlock (or any other) in the filter function. Is there a workaround to make this possbile?

Body:
Type '(d: Date) => boolean' is not assignable to type 'DateFilterFn<Date | null>'

myFilter = (d: Date ** |null **): boolean => {
   const day = (d || new Date()).getDay();
   // Prevent Saturday and Sunday from being selected.
   return day !== 0 && day !== 6;
};


问:
Join lists without redundant elements in a list [python]
I'm having this error when trying to remove topics in a List[Tuple[Union[bytes, str], Union[dict, dict]]]

Here a sample of the list:

```<code> analyzed_comments = [('setup.py', {'Topic_0': ['version', 'get'], 'Topic_1': ['version', 'get']}),
    ('translation.py', {'Topic_0': ['multiline', 'pattern', 'skip'], 'Topic_1': ['multiline', 'concat', 'text']})]
</code>```

I would like to have a resulting list that stores:

name of the file

list of non redundant topics

Something like:

```<code>comment_topics = [('setup.py', ['version', 'get']),
                    ('translation.py', ['multiline', 'pattern', 'skip', 'concat', 'text'])]
</code>```

This is what I wrote, but it doesn't seem to do this job well:

```<code>comment_topics = list()
temp_comments = list()
for file, comment in analyzed_comments:
    for topic in comment:
        elem = body[topic]
        temp_comments = list(set(elem + temp_comments))

    tupla = (file, temp_comments)
    comment_topics.append(tupla)
print(comment_topics)
</code>```

have you got any ideas?

答:
My idea would be to iterate over the files and simply combine all topics. In the end we create a set from the topics to remove all duplicates:

```<code>bodies = [('setup.py', {'Topic_0': ['version', 'get'], 'Topic_1': ['version', 'get']}),
    ('translation.py', {'Topic_0': ['multiline', 'pattern', 'skip'], 'Topic_1': ['multiline', 'concat', 'text']})]

result = {}
for x in bodies:
    values = []
    for v in x[1].values():
        values.extend(v)
    result[x[0]] = list(set(values))

result
</code>```

Output:

```<code>{'setup.py': ['version', 'get'],
 'translation.py': ['multiline', 'pattern', 'text', 'skip', 'concat']}
</code>```

You can also do it in one line:

```<code>{k: list(set(sum(v.values(),[]))) for k, v in bodies}
</code>```

or with itertools which should be faster than sum() in most cases:

```<code>import itertools
result = {k: list(set(itertools.chain.from_iterable(v.values()))) for k, v in bodies}
</code>```

Body:
I'm having this error when trying to remove topics in a List[Tuple[Union[bytes, str], Union[dict, dict]]]

Here a sample of the list:

 analyzed_comments = [('setup.py', {'Topic_0': ['version', 'get'], 'Topic_1': ['version', 'get']}),
    ('translation.py', {'Topic_0': ['multiline', 'pattern', 'skip'], 'Topic_1': ['multiline', 'concat', 'text']})]

I would like to have a resulting list that stores:

name of the file

list of non redundant topics

Something like:

comment_topics = [('setup.py', ['version', 'get']),
                    ('translation.py', ['multiline', 'pattern', 'skip', 'concat', 'text'])]

This is what I wrote, but it doesn't seem to do this job well:

comment_topics = list()
temp_comments = list()
for file, comment in analyzed_comments:
    for topic in comment:
        elem = body[topic]
        temp_comments = list(set(elem + temp_comments))

    tupla = (file, temp_comments)
    comment_topics.append(tupla)
print(comment_topics)

have you got any ideas?

Body:
My idea would be to iterate over the files and simply combine all topics. In the end we create a set from the topics to remove all duplicates:

bodies = [('setup.py', {'Topic_0': ['version', 'get'], 'Topic_1': ['version', 'get']}),
    ('translation.py', {'Topic_0': ['multiline', 'pattern', 'skip'], 'Topic_1': ['multiline', 'concat', 'text']})]

result = {}
for x in bodies:
    values = []
    for v in x[1].values():
        values.extend(v)
    result[x[0]] = list(set(values))

result

Output:

{'setup.py': ['version', 'get'],
 'translation.py': ['multiline', 'pattern', 'text', 'skip', 'concat']}

You can also do it in one line:

{k: list(set(sum(v.values(),[]))) for k, v in bodies}

or with itertools which should be faster than sum() in most cases:

import itertools
result = {k: list(set(itertools.chain.from_iterable(v.values()))) for k, v in bodies}


问:
Tic-Tac-Toe using python
I creat a Tic Tac Toe programm but i have a problem, I save user1 guesses in a list and also user2 guesses in another list. I want to compare user1 guess with other user1 guesses and if user1 guess is in the list user musst try one more time. i try several ways to solve this problem but i couldn't solve it, do you have any idea?

guesUser1 => user guess

user1Chooses => this is a list of user1 guesses

Code in gitHub

this is a part of my code

```<code>    chooseX_user1 = int(input("User1: X(0-2): "))
        chooseY_user1 = int(input("User1: Y(0-2): "))

        while (chooseX_user1 >= 3 or chooseX_user1 < 0) or `enter code here`(chooseY_user1 >= 3 or chooseY_user1 < 0):
            print("invalid X,Y")
            chooseX_user1 = int(input("User1: X(0-2): "))
            chooseY_user1 = int(input("User1: Y(0-2): "))

        guesUser1 = [chooseX_user1, chooseY_user1]

        user1Chooses.append(guesUser1)

        #Start: chack guesUser1 with other user1 guesses in user1Chooses

        #End: chack guesUser1 with other user1 guesses in user1Chooses

        for item in user2Chooses:
            if (guesUser1 == item) or (chooseX_user1 >= 3 or chooseX_user1 < 0) or (chooseY_user1 >= 3 or chooseY_user1 < 0):
                print("invalid X and Y")
                user1Chooses.pop()
                while(guesUser1 == item):
                    chooseX_user1 = int(input("User1: X(0-2): "))
                    chooseY_user1 = int(input("User1: Y(0-2): "))
                    print("invalid X and Y")
                    guesUser1 = [chooseX_user1, chooseY_user1]
                    user1Chooses.append(guesUser1)
                    if guesUser1 == item:
                        print("invalid X and Y")
                        user1Chooses.pop()

        os.system('cls')

        for i in range(0, 3):
            if chooseX_user1 == i:
                for j in range(0, 3):
                    if chooseY_user1 == j:
                        stages[i].pop(j)
                        stages[i].insert(j, "X")

        for line in stages:
            print(' '.join(line))
</code>```

答:
You could do

if guesUser1 in user1Chooses:
  # user1 guess is in the list
```
<p>to check if the guess is in the list, and the same for user2 except the variable is a little bit different.</p>
<pre class="lang-py prettyprint-override"><code>if guesUser2 in user2Chooses:
  # user2 guess is in the list
</code>```

Title: Tic-Tac-Toe using python

Body:
I creat a Tic Tac Toe programm but i have a problem, I save user1 guesses in a list and also user2 guesses in another list. I want to compare user1 guess with other user1 guesses and if user1 guess is in the list user musst try one more time. i try several ways to solve this problem but i couldn't solve it, do you have any idea?

guesUser1 => user guess

user1Chooses => this is a list of user1 guesses

Code in gitHub

this is a part of my code

    chooseX_user1 = int(input("User1: X(0-2): "))
        chooseY_user1 = int(input("User1: Y(0-2): "))

        while (chooseX_user1 >= 3 or chooseX_user1 < 0) or `enter code here`(chooseY_user1 >= 3 or chooseY_user1 < 0):
            print("invalid X,Y")
            chooseX_user1 = int(input("User1: X(0-2): "))
            chooseY_user1 = int(input("User1: Y(0-2): "))

        guesUser1 = [chooseX_user1, chooseY_user1]

        user1Chooses.append(guesUser1)

        #Start: chack guesUser1 with other user1 guesses in user1Chooses

        #End: chack guesUser1 with other user1 guesses in user1Chooses

        for item in user2Chooses:
            if (guesUser1 == item) or (chooseX_user1 >= 3 or chooseX_user1 < 0) or (chooseY_user1 >= 3 or chooseY_user1 < 0):
                print("invalid X and Y")
                user1Chooses.pop()
                while(guesUser1 == item):
                    chooseX_user1 = int(input("User1: X(0-2): "))
                    chooseY_user1 = int(input("User1: Y(0-2): "))
                    print("invalid X and Y")
                    guesUser1 = [chooseX_user1, chooseY_user1]
                    user1Chooses.append(guesUser1)
                    if guesUser1 == item:
                        print("invalid X and Y")
                        user1Chooses.pop()

        os.system('cls')

        for i in range(0, 3):
            if chooseX_user1 == i:
                for j in range(0, 3):
                    if chooseY_user1 == j:
                        stages[i].pop(j)
                        stages[i].insert(j, "X")

        for line in stages:
            print(' '.join(line))

Body:
You could do

if guesUser1 in user1Chooses:
  # user1 guess is in the list

to check if the guess is in the list, and the same for user2 except the variable is a little bit different.

if guesUser2 in user2Chooses:
  # user2 guess is in the list


问:
Ifelse with time range
Currently, I use the Sys.Date() for the filename on a daily basis.

```<code>timestamp <- Sys.Date()
</code>```

Since I'm increasing the outputs per Day to 3 I would like to adjust the filename based on a specific time range.

If the system time is between

22:00 - 05:59 = 3

06:00 - 13:59 = 1

14:00 - 21:59 = 2

How can I get the Sys.Date() + this 1,2 or 3 as a filename?

答:
We can use Sys.time() to get timestamp, extract hour from it and return a number based on hour of the day.

```<code>timestamp <- Sys.time()
hour <- as.integer(format(timestamp, '%H'))
names <- if(hour >= 20 || hour <= 5) '3' else if(hour >= 6 && hour <= 13) '1' else '2'
paste(as.Date(timestamp), names, sep = "_")
</code>```

Title: Ifelse with time range

Body:
Currently, I use the Sys.Date() for the filename on a daily basis.

timestamp <- Sys.Date()

Since I'm increasing the outputs per Day to 3 I would like to adjust the filename based on a specific time range.

If the system time is between

22:00 - 05:59 = 3

06:00 - 13:59 = 1

14:00 - 21:59 = 2

How can I get the Sys.Date() + this 1,2 or 3 as a filename?

Body:
We can use Sys.time() to get timestamp, extract hour from it and return a number based on hour of the day.

timestamp <- Sys.time()
hour <- as.integer(format(timestamp, '%H'))
names <- if(hour >= 20 || hour <= 5) '3' else if(hour >= 6 && hour <= 13) '1' else '2'
paste(as.Date(timestamp), names, sep = "_")


问:
Wordpress Database Optimisation for large Sites
I have a large Wordpress site with 170.000 users and a lot of daily page views.
I just tuned all MySQL indexes based on several comments but actually in my slow logs the SELECT distinct wp_usermeta.meta_key FROM wp_usermeta; takes around 3 seconds.
Server Hardware is: Dedicated Server with AMD Epyc 64 Cores, 128Gb DDR4, 2x480 NVMe SSD.

DB Server is MariaDB newest Version and config is (only innoDB tables):

```<code>innodb_buffer_pool_size = 64G
innodb_log_file_size = 16G
innodb_buffer_pool_instances = 16
innodb_io_capacity = 5000
max_binlog_size = 200M
max_connections = 250
wait_timeout = 28700
interactive_timeout = 28700
join_buffer_size = 128M
expire_logs_days = 3
skip-host-cache
skip-name-resolve
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
sql-mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"

tmp_table_size = 256M
max_heap_table_size = 256M
table_definition_cache = 500
sort_buffer_size = 24M
key_buffer_size = 32M
performance_schema = on
</code>```

Maybe someone has some suggestions

答:
Your server provisioning is fine. If anything, it's overprovisioned for your site.

If I understand your comments correctly, you have many occurrences of this offending SELECT distinct wp_usermeta.meta_key FROM wp_usermeta query. And it seems like that query generates a 172K row result set. Yet you say each user has the entirely reasonable number of 49 rows in wp_usermeta.

So, as @RickJames pointed out, it looks like each user somehow gets their own personal unique wp_usermeta.meta_key value. WordPress core doesn't do that and would never do that. The point of those wp_whatevermeta tables is to have a limited number of keys.  Also, rerunning that particular query very often is grossly inefficient. What conceivable purpose, other than some global list of users, does that query serve?  So a plugin is surely implicated in this. If you can get the Query Monitor (https://wordpress.org/plugins/query-monitor/) plugin to work, it will tell you what software generated the offending query.

There's nothing magic about queries without WHERE clauses. SELECTs like COUNT(*) and DISTINCT  generally need to scan through an entire table or index to generate their results, so when a table is large the query takes a long time. If you have an index on wp_usermeta.meta_key, and it indexes the whole column not the 191 prefix, the offending query should do a relatively inexpensive loose index scan.  But still, it has to do the index scan.

And, try the plugin Rick James and I put together.  https://wordpress.org/plugins/index-wp-mysql-for-speed/ It makes useful indexes, and also has a couple of diagnostic tools built in.

Body:
I have a large Wordpress site with 170.000 users and a lot of daily page views.
I just tuned all MySQL indexes based on several comments but actually in my slow logs the SELECT distinct wp_usermeta.meta_key FROM wp_usermeta; takes around 3 seconds.
Server Hardware is: Dedicated Server with AMD Epyc 64 Cores, 128Gb DDR4, 2x480 NVMe SSD.

DB Server is MariaDB newest Version and config is (only innoDB tables):

innodb_buffer_pool_size = 64G
innodb_log_file_size = 16G
innodb_buffer_pool_instances = 16
innodb_io_capacity = 5000
max_binlog_size = 200M
max_connections = 250
wait_timeout = 28700
interactive_timeout = 28700
join_buffer_size = 128M
expire_logs_days = 3
skip-host-cache
skip-name-resolve
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
sql-mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION"

tmp_table_size = 256M
max_heap_table_size = 256M
table_definition_cache = 500
sort_buffer_size = 24M
key_buffer_size = 32M
performance_schema = on

Maybe someone has some suggestions


问:
How do you get the values from a function in javascript?
I am very new to the Javascript and I am wondering how I can get the values from a function.

From my given code I would like to get the values of TheName, TheHeight, and TheGender, TheSexuality when I run the function so that I can use them for other purposes in my program.

Code:

```<code>function prng ()
{
    var Name = Object.values(person.Names);
    var Height = Object.values(person.Heights);
    var Gender = Object.values(person.Genders);
    var Sexuality = Object.values(person.Sexualities);
    var TheName = Name[Math.floor(Math.random() * Name.length)];
    var TheHeight = Height[Math.floor(Math.random() * Height.length)];
    var TheGender = Gender[Math.floor(Math.random() * Gender.length)];
    var TheSexuality = Sexuality[Math.floor(Math.random() * Sexuality.length)];
    console.log('Name: ' + TheName + ', Height: ' + TheHeight +
    ', Gender: ' + TheGender + ', Sexuality: ' + TheSexuality);
}
</code>```

Any help would be greatly appreciated. :)

答:
you can define object inline and return it like this

    function prng ()
    {
        var person = {Names:'xx' , Heights:123,Genders:'male',Sexualities:'',};
        var Name = Object.values(person.Names);
        var Height = person.Heights;
        var Gender = Object.values(person.Genders);
        var Sexuality = Object.values(person.Sexualities);
        var TheName = Name[Math.floor(Math.random() * Name.length)];
        var TheHeight = Height[Math.floor(Math.random() * Height.length)];
        var TheGender = Gender[Math.floor(Math.random() * Gender.length)];
        var TheSexuality = Sexuality[Math.floor(Math.random() * Sexuality.length)];
        return {Name : TheName ,Height: TheHeight, Gender:TheGender,Sexuality: TheSexuality};
    }

    var v = prng();
    console.log(v);
    ```

Body:
I am very new to the Javascript and I am wondering how I can get the values from a function.

From my given code I would like to get the values of TheName, TheHeight, and TheGender, TheSexuality when I run the function so that I can use them for other purposes in my program.

Code:

function prng ()
{
    var Name = Object.values(person.Names);
    var Height = Object.values(person.Heights);
    var Gender = Object.values(person.Genders);
    var Sexuality = Object.values(person.Sexualities);
    var TheName = Name[Math.floor(Math.random() * Name.length)];
    var TheHeight = Height[Math.floor(Math.random() * Height.length)];
    var TheGender = Gender[Math.floor(Math.random() * Gender.length)];
    var TheSexuality = Sexuality[Math.floor(Math.random() * Sexuality.length)];
    console.log('Name: ' + TheName + ', Height: ' + TheHeight +
    ', Gender: ' + TheGender + ', Sexuality: ' + TheSexuality);
}

Any help would be greatly appreciated. :)


问:
Silver and Gold GFG problem (https://practice.geeksforgeeks.org/contest/job-a-thon-for-internship/problems) it is the link of above problem
I have write code and it producing correct output but it can not fill all requirements please optimize my code or give me some suggestion.

It is my code...

// it is my code it produces correct output but not complete requirement.

public String flipCoins(int N,String s) {

        char ch[] = new char[N];
        for(int i=0;i<N;i++){
            ch[i] = s.charAt(i);
        }

        for(int i=1;i<N;i++){
            if(ch[i] == '1' || ch[i-1] == '1'){
                ch[i] = '1';
                ch[i-1] = '1';
            }else if(ch[i] == '0' || ch[i-1] == '0'){
                ch[i] = '1';
                ch[i-1] = '1';
            }else if(ch[i] == '0' || ch[i-1] == '1'){
                ch[i] = '1';
                ch[i-1] = '0';
            }else if(ch[i] == '1' || ch[i-1] == '0'){
                ch[i] = '0';
                ch[i-1]='1';
            }
        }
        int count = 0;
        for(char c: ch){
            if(c == '1')
                count++;
        }

        if(count == N)
            return "Yes";
        else
            return "No";

    }
```

答:
What I learned from the question is that you can flip any number of time, so
the question boils down to find whether there are even nos. of zeroes or not beacuse you can swap 00 pair to make 11 else it would always be 10 or 01</p>