问:
Catalina C++: Using <cmath> headers yield error: no member named 'signbit' in the global namespace
After upgrading to Catalina from Mojave, Setuping: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk in the env.

I'm unable to compile a program that use <cmath> header.

I tried changing CFLAGS, CCFLAGS, CXXFLAGS to point to the MacOSSDK Location that change nothing

```<code>Scanning dependencies of target OgreMain
/Applications/Xcode.app/Contents/Developer/usr/bin/make -f OgreMain/CMakeFiles/OgreMain.dir/build.make OgreMain/CMakeFiles/OgreMain.dir/build
[  0%] Building CXX object OgreMain/CMakeFiles/OgreMain.dir/src/OgreASTCCodec.cpp.o
cd /Users/roman/Downloads/ogre-1.12.2/build/OgreMain && /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++  -DOgreMain_EXPORTS -D__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES=0 -I/Users/roman/Downloads/ogre-1.12.2/OgreMain/src/OSX -I/Users/roman/Downloads/ogre-1.12.2/OgreMain/include/Threading -I/Users/roman/Downloads/ogre-1.12.2/OgreMain/src -I/Users/roman/Downloads/ogre-1.12.2/build/Dependencies/include -I/Users/roman/Downloads/ogre-1.12.2/OgreMain/include -I/Users/roman/Downloads/ogre-1.12.2/build/include -I/Users/roman/Downloads/ogre-1.12.2/OgreMain -isystem /usr/local/include  -Wall -Winit-self -Wcast-qual -Wwrite-strings -Wextra -Wundef -Wmissing-declarations -Wno-unused-parameter -Wshadow -Wno-missing-field-initializers -Wno-long-long -Wno-inconsistent-missing-override  -msse -O3 -DNDEBUG -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk -fPIC -fvisibility=hidden -fvisibility-inlines-hidden   -std=c++11 -o CMakeFiles/OgreMain.dir/src/OgreASTCCodec.cpp.o -c /Users/roman/Downloads/ogre-1.12.2/OgreMain/src/OgreASTCCodec.cpp
In file included from /Users/roman/Downloads/ogre-1.12.2/OgreMain/src/OgreASTCCodec.cpp:29:
In file included from /Users/roman/Downloads/ogre-1.12.2/OgreMain/src/OgreStableHeaders.h:40:
In file included from /Users/roman/Downloads/ogre-1.12.2/OgreMain/include/OgrePrerequisites.h:309:
In file included from /Users/roman/Downloads/ogre-1.12.2/OgreMain/include/OgreStdHeaders.h:10:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/cmath:314:9: error: no member named 'signbit' in the global namespace
using ::signbit;
      ~~^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/cmath:315:9: error: no member named 'fpclassify' in the global namespace
using ::fpclassify;
      ~~^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/cmath:316:9: error: no member named 'isfinite' in the global namespace; did you mean 'finite'?
using ::isfinite;
</code>```

for example the macro: isless is present in the global namespace and on my computer:

```<code>➜ cat math.h | grep "isless"

#define isless(x, y) __builtin_isless((x),(y))
#define islessequal(x, y) __builtin_islessequal((x),(y))
#define islessgreater(x, y) __builtin_islessgreater((x),(y))
➜  pwd
/usr/local/include
➜
</code>```

Even the cmath header include it:

```<code>➜ cat /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/cmath | grep "math.h"
#include <math.h>
</code>```

And my command line have the option -isystem /usr/local/include

This should work...

答:
@solodon's analysis is spot on. The issue is likely that the cmath file is including the wrong version of math.h based on the search order of the header files. At least, this is what was happening to me when I was getting the same error.

Scan your compiler output for #include <...> search starts here:. You can also force this output from the command line with (source):

```<code>gcc -Wp,-v -E -
</code>```

It should look something like this:

```<code> /usr/local/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.0/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks (framework directory)
</code>```

Notice that the paths with Toolchains come before those with Platforms. If in your case the order is reversed, you need to figure out what in your configuration is causing this. For me, it was an explicit setting of CPLUS_INCLUDE_PATH in my login script.

Offending code:

```<code>XCBASE=`xcrun --show-sdk-path`
export CPLUS_INCLUDE_PATH=$XCBASE/usr/include
</code>```

This was part of my attempt to work around Xcode 11 no longer providing the installation package for the SDK header files. After removing this code, I was able to successfully include cmath in my C++ code.

If you came here looking for solutions to this issue, you may require a different solution but hopefully this helps to shed light on what seems to be the root cause of this issue, header file search path order.

Body:
After upgrading to Catalina from Mojave, Setuping: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk in the env.

I'm unable to compile a program that use <cmath> header.

I tried changing CFLAGS, CCFLAGS, CXXFLAGS to point to the MacOSSDK Location that change nothing

Scanning dependencies of target OgreMain
/Applications/Xcode.app/Contents/Developer/usr/bin/make -f OgreMain/CMakeFiles/OgreMain.dir/build.make OgreMain/CMakeFiles/OgreMain.dir/build
[  0%] Building CXX object OgreMain/CMakeFiles/OgreMain.dir/src/OgreASTCCodec.cpp.o
cd /Users/roman/Downloads/ogre-1.12.2/build/OgreMain && /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++  -DOgreMain_EXPORTS -D__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES=0 -I/Users/roman/Downloads/ogre-1.12.2/OgreMain/src/OSX -I/Users/roman/Downloads/ogre-1.12.2/OgreMain/include/Threading -I/Users/roman/Downloads/ogre-1.12.2/OgreMain/src -I/Users/roman/Downloads/ogre-1.12.2/build/Dependencies/include -I/Users/roman/Downloads/ogre-1.12.2/OgreMain/include -I/Users/roman/Downloads/ogre-1.12.2/build/include -I/Users/roman/Downloads/ogre-1.12.2/OgreMain -isystem /usr/local/include  -Wall -Winit-self -Wcast-qual -Wwrite-strings -Wextra -Wundef -Wmissing-declarations -Wno-unused-parameter -Wshadow -Wno-missing-field-initializers -Wno-long-long -Wno-inconsistent-missing-override  -msse -O3 -DNDEBUG -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk -fPIC -fvisibility=hidden -fvisibility-inlines-hidden   -std=c++11 -o CMakeFiles/OgreMain.dir/src/OgreASTCCodec.cpp.o -c /Users/roman/Downloads/ogre-1.12.2/OgreMain/src/OgreASTCCodec.cpp
In file included from /Users/roman/Downloads/ogre-1.12.2/OgreMain/src/OgreASTCCodec.cpp:29:
In file included from /Users/roman/Downloads/ogre-1.12.2/OgreMain/src/OgreStableHeaders.h:40:
In file included from /Users/roman/Downloads/ogre-1.12.2/OgreMain/include/OgrePrerequisites.h:309:
In file included from /Users/roman/Downloads/ogre-1.12.2/OgreMain/include/OgreStdHeaders.h:10:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/cmath:314:9: error: no member named 'signbit' in the global namespace
using ::signbit;
      ~~^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/cmath:315:9: error: no member named 'fpclassify' in the global namespace
using ::fpclassify;
      ~~^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/cmath:316:9: error: no member named 'isfinite' in the global namespace; did you mean 'finite'?
using ::isfinite;

for example the macro: isless is present in the global namespace and on my computer:

➜ cat math.h | grep "isless"

#define isless(x, y) __builtin_isless((x),(y))
#define islessequal(x, y) __builtin_islessequal((x),(y))
#define islessgreater(x, y) __builtin_islessgreater((x),(y))
➜  pwd
/usr/local/include
➜

Even the cmath header include it:

➜ cat /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/cmath | grep "math.h"
#include <math.h>

And my command line have the option -isystem /usr/local/include

This should work...

Body:
@solodon's analysis is spot on. The issue is likely that the cmath file is including the wrong version of math.h based on the search order of the header files. At least, this is what was happening to me when I was getting the same error.

Scan your compiler output for #include <...> search starts here:. You can also force this output from the command line with (source):

gcc -Wp,-v -E -

It should look something like this:

 /usr/local/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.0/include
 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include
 /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks (framework directory)

Notice that the paths with Toolchains come before those with Platforms. If in your case the order is reversed, you need to figure out what in your configuration is causing this. For me, it was an explicit setting of CPLUS_INCLUDE_PATH in my login script.

Offending code:

XCBASE=`xcrun --show-sdk-path`
export CPLUS_INCLUDE_PATH=$XCBASE/usr/include

This was part of my attempt to work around Xcode 11 no longer providing the installation package for the SDK header files. After removing this code, I was able to successfully include cmath in my C++ code.

If you came here looking for solutions to this issue, you may require a different solution but hopefully this helps to shed light on what seems to be the root cause of this issue, header file search path order.


来源: stackexchange

问:
Improve the perfomance of a code that uses for-loops
I am trying to create a list based on some data, but the code I am using is very slow when I run it on large data. So I suspect I am not using all of the Python power for this task. Is there a more efficient and faster way of doing this in Python?

Here an explanantion of the code:

You can think of this problem as a list of games (list_type) each with a list of participating teams and the scores for each team in the game (list_xx).For each of the pairs in the current game it first calculate the sum of the differences in score from the previous competitions (win_comp_past_difs); including only the pairs in the current game.  Then it update each pair in the current game with the difference in scores. Using a defaultdict keeps track of the scores for each pair in each game and update this score as each game is played.

In the example below, based on some data, there are for-loops used to create a new variable list_zz.

The data and the for-loop code:

import pandas as pd
import numpy as np
from collections import defaultdict
from itertools import permutations

list_type = [['A', 'B'], ['B'], ['A', 'B', 'C', 'D', 'E'], ['B'], ['A', 'B', 'C'], ['A'], ['B', 'C'], ['A', 'B'], ['C', 'A', 'B'], ['A'], ['B', 'C']]

list_xx = [[1.0, 5.0], [3.0], [2.0, 7.0, 3.0, 1.0, 6.0], [3.0], [5.0, 2.0, 3.0], [1.0], [9.0, 3.0], [2.0, 7.0], [3.0, 6.0, 8.0], [2.0], [7.0, 9.0]]

list_zz= []
#for-loop
wd = defaultdict(float)
for i, x in zip(list_type, list_xx):
    # staff 1
    if len(i) == 1:
        #print('NaN')
        list_zz.append(np.nan)
        continue
    # Pairs and difference generator for current game (i)
    pairs = list(permutations(i, 2))
    dgen = (value[0] - value[1] for value in permutations(x, 2))
    # Sum of differences from previous games incluiding only pair of teams in the current game
    for team, result in zip(i, x):
        win_comp_past_difs = sum(wd[key] for key in pairs if key[0] == team)
        #print(win_comp_past_difs)
        list_zz.append(win_comp_past_difs)
    # Update pair differences for current game
    for pair, diff in zip(pairs, dgen):
        wd[pair] += diff
print(list_zz)

```

<p>Which looks like this:</p>

<pre class="lang-py prettyprint-override"><code>[0.0,
 0.0,
 nan,
 -4.0,
 4.0,
 0.0,
 0.0,
 0.0,
 nan,
 -10.0,
 13.0,
 -3.0,
 nan,
 3.0,
 -3.0,
 -6.0,
 6.0,
 -10.0,
 -10.0,
 20.0,
 nan,
 14.0,
 -14.0]
</code>```

If you could elaborate on the code to make it more efficient and execute faster, I would really appreciate it.

答:
Without reviewing the overall design of your code, one improvement pops out at me: move your code to a function.

As currently written, all of the variables you use are global variables. Due to the dynamic nature of the global namespace, Python must look up each global variable you use each and every time you use access it.(1) In CPython, this corresponds to a hash table lookup, which can be expensive, particularly if hash collisions are present.

In contrast, local variables can be known at compile time, and so are stored in a fixed-size array. Accessing these variables therefore only involves dereferencing a pointer, which is comparatively much faster.

With this principal in mind, you should be able to boost your performance (somewhere around a 40% drop in run time) by moving all you your code into a "main" function:

```<code>def main():
    ...
    # Your code here

if __name__ == '__main__':
    main()
</code>```

(1) Source

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a list based on some data, but the code I am using is very slow when I run it on large data. So I suspect I am not using all of the Python power for this task. Is there a more efficient and faster way of doing this in Python?

Here an explanantion of the code:

You can think of this problem as a list of games (list_type) each with a list of participating teams and the scores for each team in the game (list_xx).For each of the pairs in the current game it first calculate the sum of the differences in score from the previous competitions (win_comp_past_difs); including only the pairs in the current game.  Then it update each pair in the current game with the difference in scores. Using a defaultdict keeps track of the scores for each pair in each game and update this score as each game is played.

In the example below, based on some data, there are for-loops used to create a new variable list_zz.

The data and the for-loop code:

import pandas as pd
import numpy as np
from collections import defaultdict
from itertools import permutations

list_type = [['A', 'B'], ['B'], ['A', 'B', 'C', 'D', 'E'], ['B'], ['A', 'B', 'C'], ['A'], ['B', 'C'], ['A', 'B'], ['C', 'A', 'B'], ['A'], ['B', 'C']]

list_xx = [[1.0, 5.0], [3.0], [2.0, 7.0, 3.0, 1.0, 6.0], [3.0], [5.0, 2.0, 3.0], [1.0], [9.0, 3.0], [2.0, 7.0], [3.0, 6.0, 8.0], [2.0], [7.0, 9.0]]

list_zz= []
#for-loop
wd = defaultdict(float)
for i, x in zip(list_type, list_xx):
    # staff 1
    if len(i) == 1:
        #print('NaN')
        list_zz.append(np.nan)
        continue
    # Pairs and difference generator for current game (i)
    pairs = list(permutations(i, 2))
    dgen = (value[0] - value[1] for value in permutations(x, 2))
    # Sum of differences from previous games incluiding only pair of teams in the current game
    for team, result in zip(i, x):
        win_comp_past_difs = sum(wd[key] for key in pairs if key[0] == team)
        #print(win_comp_past_difs)
        list_zz.append(win_comp_past_difs)
    # Update pair differences for current game
    for pair, diff in zip(pairs, dgen):
        wd[pair] += diff
print(list_zz)

Which looks like this:

[0.0,
 0.0,
 nan,
 -4.0,
 4.0,
 0.0,
 0.0,
 0.0,
 nan,
 -10.0,
 13.0,
 -3.0,
 nan,
 3.0,
 -3.0,
 -6.0,
 6.0,
 -10.0,
 -10.0,
 20.0,
 nan,
 14.0,
 -14.0]

If you could elaborate on the code to make it more efficient and execute faster, I would really appreciate it.

Body:
Without reviewing the overall design of your code, one improvement pops out at me: move your code to a function.

As currently written, all of the variables you use are global variables. Due to the dynamic nature of the global namespace, Python must look up each global variable you use each and every time you use access it.(1) In CPython, this corresponds to a hash table lookup, which can be expensive, particularly if hash collisions are present.

In contrast, local variables can be known at compile time, and so are stored in a fixed-size array. Accessing these variables therefore only involves dereferencing a pointer, which is comparatively much faster.

With this principal in mind, you should be able to boost your performance (somewhere around a 40% drop in run time) by moving all you your code into a "main" function:

def main():
    ...
    # Your code here

if __name__ == '__main__':
    main()

(1) Source


问:
Rails testing using Rspec and FactoryBot
I am new to rails rspec testing, I currently need to created nested data structure and using factorybot for data. And while it works for controller testing. Its not letting me do simple Factorybot.create(:model).
I have searched a lot. But didn't seem to find or understand a solution.
So, data structure i need to create is something like:

```<code>"email":"",
"name":"",
"personalDetail":{
"height":"",
"weight":"",
"color":""
}
"address":{
"street":"",
"postal_code":""
},
"experience":""
}
</code>```

(**note. this not association related, data in controller is received in such a way. There is no relationship involved)
 while i am currently achieving this structure using

```<code>initialize_with{{
"email":"",
"name":"",
"personalDetail":{
"height":"",
"weight":"",
"color":""
}
"address":{
"street":"",
"postal_code":""
},
"experience":""
}}
</code>```

its works for controller testing but it i'm not able to change key value while testing like:

```<code>FactoryBot.create(:model, name:"xyz")
</code>```

, and also is not working for FactoryBot.create(:model), which is giving me error of

** Api::V1::someController get #index
     Failure/Error: FactoryBot.create(:model)

```<code> NoMethodError:
   undefined method `save!' for #<Hash:0x0000563db7324060>
 # ./spec/controllers/api/v1/somecontroller_spec.rb:11:in `block (2 levels) in <main>'
 # -e:1:in `<main>' **
</code>```

So, my question is how can i generate this structure using FactoryBot usual method. i.e

```<code>factory :job_application do
    field1 { "" }
    field2 { "" }
  end
</code>```

so that i can use it usual way.

答:
factory :job_application will guess that you want to make an object of the class JobApplication. To make a Hash you need to make it explicit. See Defining Factories.

```<code>factory :job_application, class: Hash
</code>```

Because Hash.new does not take a bunch of key/value pairs, you need to override the default initialization behavior. I've found the simplest thing to do is to return the attributes of the factory. See Custom Construction.

Those use symbol keys, you want string keys, so we use deep_stringify_keys. This also takes care of cloning attributes just in case.

```<code>factory :job_application, class: Hash do
  initialize_with do
    attributes.deep_stringify_keys
  end
end
</code>```

Now you can add attributes in the normal way.

```<code>factory :job_application, class: Hash do
  email { "jorb@coachz.biz" }

  initialize_with do
    attributes.deep_stringify_keys
  end
end
</code>```

Because there is no save method, you can only build these Hash factories.

```<code># Yes
jorb = FactoryBot.build(:job_application)

# No
jorb = FactoryBot.create(:job_application)
</code>```

I find myself doing this a lot, so I've built a string_hash factory to inherit from.

```<code>factory :string_hash, class: Hash do
  initialize_with do
    attributes.deep_stringify_keys
  end
end

factory :job_application, parent: :string_hash do
  email { "jorb@coachz.biz" }
end
</code>```

If you want nested hashes, I suggest you make additional factories and associate them together. This allows you to easily change the values in the nested hashes.

Associations default to using create, we need to explicitly build our associations. See Associations.

```<code>factory :address, parent: :string_hash do
  street { "Ahead St." }
  postal_code { "12345" }
end

factory :job_application, parent: :string_hash do
  association :address, strategy: :build

  email { "jorb@coachz.biz" }
  name { "Coach Z" }
end

build(:job_application,
  address: build(:address, street: "Sesame St.")
)
</code>```

Do ask yourself whether it makes sense to define these as models. This makes them work with normal factories and features like validation and you can add methods and all that good stuff.

Since this is data you receive in a controller it might benefit from having validations and methods. See ActiveModel Form Objects by ThoughtBot.

```<code>class JobApplication
  include ActiveModel::Model
  include ActiveModel::Validations

  attr_accessor :email, :name, :address

  validates :name, :email, presence: true
end

class Address
  include ActiveModel::Model

  attr_accessor :street, :postal_code
end

factory :address do
  street { "Ahead St." }
  postal_code { "12345" }
end

factory :job_application do
  # Can't save a Model either.
  association :address, strategy: :build

  email { "jorb@coachz.biz" }
  name { "Coach Z" }
end
</code>```

Body:
I am new to rails rspec testing, I currently need to created nested data structure and using factorybot for data. And while it works for controller testing. Its not letting me do simple Factorybot.create(:model).
I have searched a lot. But didn't seem to find or understand a solution.
So, data structure i need to create is something like:

"email":"",
"name":"",
"personalDetail":{
"height":"",
"weight":"",
"color":""
}
"address":{
"street":"",
"postal_code":""
},
"experience":""
}

(**note. this not association related, data in controller is received in such a way. There is no relationship involved)
 while i am currently achieving this structure using

initialize_with{{
"email":"",
"name":"",
"personalDetail":{
"height":"",
"weight":"",
"color":""
}
"address":{
"street":"",
"postal_code":""
},
"experience":""
}}

its works for controller testing but it i'm not able to change key value while testing like:

FactoryBot.create(:model, name:"xyz")

, and also is not working for FactoryBot.create(:model), which is giving me error of

** Api::V1::someController get #index
     Failure/Error: FactoryBot.create(:model)

 NoMethodError:
   undefined method `save!' for #<Hash:0x0000563db7324060>
 # ./spec/controllers/api/v1/somecontroller_spec.rb:11:in `block (2 levels) in '
 # -e:1:in `' **

So, my question is how can i generate this structure using FactoryBot usual method. i.e

factory :job_application do
    field1 { "" }
    field2 { "" }
  end

so that i can use it usual way.

Body:
factory :job_application will guess that you want to make an object of the class JobApplication. To make a Hash you need to make it explicit. See Defining Factories.

factory :job_application, class: Hash

Because Hash.new does not take a bunch of key/value pairs, you need to override the default initialization behavior. I've found the simplest thing to do is to return the attributes of the factory. See Custom Construction.

Those use symbol keys, you want string keys, so we use deep_stringify_keys. This also takes care of cloning attributes just in case.

factory :job_application, class: Hash do
  initialize_with do
    attributes.deep_stringify_keys
  end
end

Now you can add attributes in the normal way.

factory :job_application, class: Hash do
  email { "jorb@coachz.biz" }

  initialize_with do
    attributes.deep_stringify_keys
  end
end

Because there is no save method, you can only build these Hash factories.

# Yes
jorb = FactoryBot.build(:job_application)

# No
jorb = FactoryBot.create(:job_application)

I find myself doing this a lot, so I've built a string_hash factory to inherit from.

factory :string_hash, class: Hash do
  initialize_with do
    attributes.deep_stringify_keys
  end
end

factory :job_application, parent: :string_hash do
  email { "jorb@coachz.biz" }
end

If you want nested hashes, I suggest you make additional factories and associate them together. This allows you to easily change the values in the nested hashes.

Associations default to using create, we need to explicitly build our associations. See Associations.

factory :address, parent: :string_hash do
  street { "Ahead St." }
  postal_code { "12345" }
end

factory :job_application, parent: :string_hash do
  association :address, strategy: :build

  email { "jorb@coachz.biz" }
  name { "Coach Z" }
end

build(:job_application,
  address: build(:address, street: "Sesame St.")
)

Do ask yourself whether it makes sense to define these as models. This makes them work with normal factories and features like validation and you can add methods and all that good stuff.

Since this is data you receive in a controller it might benefit from having validations and methods. See ActiveModel Form Objects by ThoughtBot.

class JobApplication
  include ActiveModel::Model
  include ActiveModel::Validations

  attr_accessor :email, :name, :address

  validates :name, :email, presence: true
end

class Address
  include ActiveModel::Model

  attr_accessor :street, :postal_code
end

factory :address do
  street { "Ahead St." }
  postal_code { "12345" }
end

factory :job_application do
  # Can't save a Model either.
  association :address, strategy: :build

  email { "jorb@coachz.biz" }
  name { "Coach Z" }
end


问:
i want to fetch data full in a single Textview from firebase database
I have created a barcode scanner app and it reads the barcode id and needed the output as voice output. in order to read all the things i need to fetch all data together in one single TextView. I did my level best to add the query from database. but it only shows in TextView as com.google.firebase.database.Query@9fc9e4d and my app TTS engine reads it clearly. But i need to set it as all data under a single TextView from database to speak out. please help me???? here only i attached the result handling method.

```<code>@Override
public void handleResult(Result result) { final String scanResult = result.getText();

    databasefetch = FirebaseDatabase.getInstance().getReference("save");
    databasefetch.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            setContentView(R.layout.activity_second);
            TextView text = (TextView) findViewById(R.id.textView3);
            String tst = databasefetch.child("save").orderByChild("id").equalTo(scanResult).toString();
            text.setText(tst);

            //text to speech
            String  toSpeak=text.getText().toString();
            //Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
            txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

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

答:
No need to run multiple query to filter the data based on id. Check below:

```<code>databasefetch = FirebaseDatabase.getInstance().getReference("save");
databasefetch.orderByChild("id").equalTo(scanResult).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        String  toSpeak = "";

        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {

            String name = childSnapshot.child("name").getValue(String.class);
            String price = childSnapshot.child("price").getValue(String.class);
            String details = childSnapshot.child("details").getValue(String.class);

            toSpeak = name + ", " + price + ", " + details;
        }

        text.setText(toSpeak);

        txt.speak(toSpeak, TextToSpeech.QUEUE_FLUSH,null);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
</code>```

Body:
I have created a barcode scanner app and it reads the barcode id and needed the output as voice output. in order to read all the things i need to fetch all data together in one single TextView. I did my level best to add the query from database. but it only shows in TextView as com.google.firebase.database.Query@9fc9e4d and my app TTS engine reads it clearly. But i need to set it as all data under a single TextView from database to speak out. please help me???? here only i attached the result handling method.

@Override
public void handleResult(Result result) { final String scanResult = result.getText();

    databasefetch = FirebaseDatabase.getInstance().getReference("save");
    databasefetch.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            setContentView(R.layout.activity_second);
            TextView text = (TextView) findViewById(R.id.textView3);
            String tst = databasefetch.child("save").orderByChild("id").equalTo(scanResult).toString();
            text.setText(tst);

            //text to speech
            String  toSpeak=text.getText().toString();
            //Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
            txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

Body:
No need to run multiple query to filter the data based on id. Check below:

databasefetch = FirebaseDatabase.getInstance().getReference("save");
databasefetch.orderByChild("id").equalTo(scanResult).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        String  toSpeak = "";

        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {

            String name = childSnapshot.child("name").getValue(String.class);
            String price = childSnapshot.child("price").getValue(String.class);
            String details = childSnapshot.child("details").getValue(String.class);

            toSpeak = name + ", " + price + ", " + details;
        }

        text.setText(toSpeak);

        txt.speak(toSpeak, TextToSpeech.QUEUE_FLUSH,null);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});


问:
MPI Warning: Program exiting with outstanding receive requests
I wish to send a contiguous array of memory between two nodes using MPI. For this purpose, I use the following Non-blocking Send/Receive command (MPI_Isend, MPI_Irecv). While executing the run command, I see two warning statements as follows:

```<code>Warning: Program exiting with outstanding receive requests
</code>```

Basically, I want to see that the array data from "NorthEdge1" is passed to "NorthofNorthEdge3". How could I fix this?  What else could I try to check this communication?

Here is an excerpt from the source code:

```<code> #define Rows 48
 ...

 double *northedge1 = new double[Rows];
 double *northofnorthedge3 = new double[Rows];
 ...
 ...

 int main (int argc, char *argv[])
 {
  ....
  ....

   MPI_Request send_request, recv_request;
 ...
 ...
 {
   MPI_Isend(northedge1, Rows, MPI_DOUBLE, my_rank+1, 0, MPI_COMM_WORLD, &send_request);
   MPI_Irecv(northofnorthedge3, Rows, MPI_DOUBLE, my_rank+1, MPI_ANY_TAG, MPI_COMM_WORLD,
   &recv_request);
 }
</code>```

答: It looks like you haven't called MPI_Waitall(). The "immediate" send and receive routines only begin the communication. You have to block your process to ensure the communication has finished. Blocking in MPI is with a variant of MPI_Wait(); in your case, you need MPI_Waitall().

ContentLicense: CC BY-SA 3.0

Body:
I wish to send a contiguous array of memory between two nodes using MPI. For this purpose, I use the following Non-blocking Send/Receive command (MPI_Isend, MPI_Irecv). While executing the run command, I see two warning statements as follows:

Warning: Program exiting with outstanding receive requests

Basically, I want to see that the array data from "NorthEdge1" is passed to "NorthofNorthEdge3". How could I fix this?  What else could I try to check this communication?

Here is an excerpt from the source code:

 #define Rows 48
 ...

 double *northedge1 = new double[Rows];
 double *northofnorthedge3 = new double[Rows];
 ...
 ...

 int main (int argc, char *argv[])
 {
  ....
  ....

   MPI_Request send_request, recv_request;
 ...
 ...
 {
   MPI_Isend(northedge1, Rows, MPI_DOUBLE, my_rank+1, 0, MPI_COMM_WORLD, &send_request);
   MPI_Irecv(northofnorthedge3, Rows, MPI_DOUBLE, my_rank+1, MPI_ANY_TAG, MPI_COMM_WORLD,
   &recv_request);
 }


问:
Trying to Convert a Text file into data structure
I have like this text data as following contents. What am i trying is to convert this text into data structure(Lists of dictionaries or list of lists) to be able to handle with.

test.txt

```<code>0           1           1
3,1         3,1         3,1
5,0         5,1         5,0
6,1         6,0         6,0
</code>```

Output formate like this:

```<code>   0     1      1
   ---------------
3| 1    1       1
5| 0    1      0
6| 1    0       0
</code>```

I tried lot of things but unfortunately it did not succeeded.

答:
I don't know if this is exactly the structure you want, but try this:

```<code>import collections

txt = """0           1           1
3,1         3,1         3,1
5,0         5,1         5,0
6,1         6,0         6,0"""

header = list(map(int,txt.splitlines()[0].split()))

output = collections.OrderedDict()
for line in txt.splitlines()[1:]:
    cols = line.split()
    row_num = int(cols[0].split(",")[0])

    vals = [(header[i],int(c.split(",")[1])) for i, c in enumerate(cols)]
    output[row_num] = vals

print(output)
</code>```

Output:

```<code>OrderedDict([('3', [(0, 1), (1, 1), (1, 1)]), ('5', [(0, 0), (1, 1), (1, 0)]), ('6', [(0, 1), (1, 0), (1, 0)])])
</code>```

To load a file:

```<code>with open("file.txt") as f:
    txt = f.read()
</code>```

Body:
I have like this text data as following contents. What am i trying is to convert this text into data structure(Lists of dictionaries or list of lists) to be able to handle with.

test.txt

0           1           1
3,1         3,1         3,1
5,0         5,1         5,0
6,1         6,0         6,0

Output formate like this:

   0     1      1
   ---------------
3| 1    1       1
5| 0    1      0
6| 1    0       0

I tried lot of things but unfortunately it did not succeeded.

Body:
I don't know if this is exactly the structure you want, but try this:

import collections

txt = """0           1           1
3,1         3,1         3,1
5,0         5,1         5,0
6,1         6,0         6,0"""

header = list(map(int,txt.splitlines()[0].split()))

output = collections.OrderedDict()
for line in txt.splitlines()[1:]:
    cols = line.split()
    row_num = int(cols[0].split(",")[0])

    vals = [(header[i],int(c.split(",")[1])) for i, c in enumerate(cols)]
    output[row_num] = vals

print(output)

Output:

OrderedDict([('3', [(0, 1), (1, 1), (1, 1)]), ('5', [(0, 0), (1, 1), (1, 0)]), ('6', [(0, 1), (1, 0), (1, 0)])])

To load a file:

with open("file.txt") as f:
    txt = f.read()


问:
What's the most efficient way to create a live dashboard for Big Data using .Net in Azure?
Hypothetical simplified scenario:

I have an Asp.Net Core 3 API that takes in Pizza orders from Javascript.
A pizza is ordered, I Deserialize the object in the C# API.
I have now an object "Pizza":

```<code>{
   "name": "Margherita",
   "date": "20201502",
   "amount": "10"
   "ingredients": ["tomato", "mozzarella"]
}
</code>```

I receive 100 millions pizza orders per day, I need a live Dashboard showing the orders, with a menu for searching historical data like "Yesterday", "This Month", "Last Year" etc..

I also need a list of the most ordered pizzas in a given timeframe, or top ingredients used.

What is the most modern, efficient way using Microsoft Azure and C# to achieve such result?

There are too many Queues, Data Factories, Lakes, Storage, Streams etc Analytics services to choose from.

I can think of 2 ways:

1)

Send each pizza order to a queue like Service Fabric Queues, AzureStorage Queue or Event Hubs

Dequeue the objects keeping them in memory temporarily

After 10k or more elements are in memory, aggregate them in such way to satisfy future queries and save them to CosmosDB instead of saving each single order

This is CPU inefficient and limited in future queries but save costs on storage since no single object is stored but just aggregated data

2)

Send each pizza to a queue like Event Hubs or Stream Analytics

Save each single object to a storage for "Big Data"

Use Apache Spark on Azure or similar to query the data

Create a worker role that every minute query the Dataset and create single aggregated records using for example the "date" as PartitionKey to show in the dashboard

Unsure if delete the data to save on storage costs make sense

I think the #2 is the way to go but I'm undecided on what is the best "stack" for the task that is easy and cost efficient.

答:
I would recommend you look at implementing some technologies that follow the Lambda architecture. Basically that is separate hot path and cold path technologies. Here is a good introduction though I wouldn’t focus only on the technologies James mentions.

If you have some standing queries like “number of pizzas ordered in rolling 5 minute window” then Azure Stream Analytics can output a constant stream of these aggregations.

Then the pizza order events can be also archived in Blob storage for ingestion into some batch technology. For example, do a daily or hourly load to Azure SQL Data Warehouse (rebranded Azure Synapse Analytics recently). Then your app can run queries like “most popular pizza toppings last month” in an ad-hoc fashion. The combination of these hot path and cold path technologies should work better than trying to get one tool to do everything.

Another option is Spark. I would recommend looking at Spark streaming in Azure Databricks. You should be able to do streaming aggregations and also load Delta tables for batch queries for older time periods. This article might give you an example.

Body:
Hypothetical simplified scenario:

I have an Asp.Net Core 3 API that takes in Pizza orders from Javascript.
A pizza is ordered, I Deserialize the object in the C# API.
I have now an object "Pizza":

{
   "name": "Margherita",
   "date": "20201502",
   "amount": "10"
   "ingredients": ["tomato", "mozzarella"]
}

I receive 100 millions pizza orders per day, I need a live Dashboard showing the orders, with a menu for searching historical data like "Yesterday", "This Month", "Last Year" etc..

I also need a list of the most ordered pizzas in a given timeframe, or top ingredients used.

What is the most modern, efficient way using Microsoft Azure and C# to achieve such result?

There are too many Queues, Data Factories, Lakes, Storage, Streams etc Analytics services to choose from.

I can think of 2 ways:

1)

Send each pizza order to a queue like Service Fabric Queues, AzureStorage Queue or Event Hubs

Dequeue the objects keeping them in memory temporarily

After 10k or more elements are in memory, aggregate them in such way to satisfy future queries and save them to CosmosDB instead of saving each single order

This is CPU inefficient and limited in future queries but save costs on storage since no single object is stored but just aggregated data

2)

Send each pizza to a queue like Event Hubs or Stream Analytics

Save each single object to a storage for "Big Data"

Use Apache Spark on Azure or similar to query the data

Create a worker role that every minute query the Dataset and create single aggregated records using for example the "date" as PartitionKey to show in the dashboard

Unsure if delete the data to save on storage costs make sense

I think the #2 is the way to go but I'm undecided on what is the best "stack" for the task that is easy and cost efficient.


问:
R - multiple calls to dplyr::crossing() - can I simplify?
I have a piece of code:

```<code>library(tidyr)
library(dplyr)

df_ref <- data.frame(factor_1 = "A", factor_2 = "Y", factor_3 = "3")

factor_1_levels <- c("A", "B", "C")
factor_2_levels <- c("X", "Y", "Z")
factor_3_levels <- c("1", "2", "3")

df_ref_1 <- crossing(select(df_ref, -factor_1), factor_1_levels) %>% rename(factor_1 = factor_1_levels)
df_ref_2 <- crossing(select(df_ref, -factor_2), factor_2_levels) %>% rename(factor_2 = factor_2_levels)
df_ref_3 <- crossing(select(df_ref, -factor_3), factor_3_levels) %>% rename(factor_3 = factor_3_levels)
</code>```

You can see I've got 3 factors defined, and I'm doing the exact same thing with each of them. The code does what I need it to do, but it's bad code. In real world examples I might have 200 factors instead, and doing the above 200 times over is obviously very bad indeed. Is there a nice way to code this using one of the apply() type functions, or similar?

Thank you.

答:
We can use combn to create pairwise combinations of the names into a list, then select the columns from the 'df_ref' and create the crossing from the list of 'factor_\d+_levelsobjects inmap2andrename` the column

```<code>library(dplyr)
library(tidyr)
library(purrr)
library(stringr)
lst1 <- combn(rev(names(df_ref)), 2, FUN = function(nm1)
       df_ref %>%
            select(nm1), simplify = FALSE)
imap(mget(ls(pattern = "^factor_\\d+_levels$")),
        ~ list(.x, .y) ) %>%
             map2(lst1, ., ~  crossing(.x, !! .y[[2]] := .y[[1]]) %>%
             rename_at(vars(ends_with('levels')), ~ str_remove(., '_levels')))
#[[1]]
# A tibble: 3 x 3
#  factor_3 factor_2 factor_1
#  <fct>    <fct>    <chr>
#1 3        Y        A
#2 3        Y        B
#3 3        Y        C

#[[2]]
# A tibble: 3 x 3
#  factor_3 factor_1 factor_2
#  <fct>    <fct>    <chr>
#1 3        A        X
#2 3        A        Y
#3 3        A        Z

#[[3]]
# A tibble: 3 x 3
#  factor_2 factor_1 factor_3
#  <fct>    <fct>    <chr>
#1 Y        A        1
#2 Y        A        2
#3 Y        A        3
</code>```

Body:
I have a piece of code:

library(tidyr)
library(dplyr)

df_ref <- data.frame(factor_1 = "A", factor_2 = "Y", factor_3 = "3")

factor_1_levels <- c("A", "B", "C")
factor_2_levels <- c("X", "Y", "Z")
factor_3_levels <- c("1", "2", "3")

df_ref_1 <- crossing(select(df_ref, -factor_1), factor_1_levels) %>% rename(factor_1 = factor_1_levels)
df_ref_2 <- crossing(select(df_ref, -factor_2), factor_2_levels) %>% rename(factor_2 = factor_2_levels)
df_ref_3 <- crossing(select(df_ref, -factor_3), factor_3_levels) %>% rename(factor_3 = factor_3_levels)

You can see I've got 3 factors defined, and I'm doing the exact same thing with each of them. The code does what I need it to do, but it's bad code. In real world examples I might have 200 factors instead, and doing the above 200 times over is obviously very bad indeed. Is there a nice way to code this using one of the apply() type functions, or similar?

Thank you.

Body:
We can use combn to create pairwise combinations of the names into a list, then select the columns from the 'df_ref' and create the crossing from the list of 'factor_\d+_levelsobjects inmap2andrename` the column

library(dplyr)
library(tidyr)
library(purrr)
library(stringr)
lst1 <- combn(rev(names(df_ref)), 2, FUN = function(nm1)
       df_ref %>%
            select(nm1), simplify = FALSE)
imap(mget(ls(pattern = "^factor_\\d+_levels$")),
        ~ list(.x, .y) ) %>%
             map2(lst1, ., ~  crossing(.x, !! .y[[2]] := .y[[1]]) %>%
             rename_at(vars(ends_with('levels')), ~ str_remove(., '_levels')))
#[[1]]
# A tibble: 3 x 3
#  factor_3 factor_2 factor_1
#  <fct>    <fct>    <chr>
#1 3        Y        A
#2 3        Y        B
#3 3        Y        C

#[[2]]
# A tibble: 3 x 3
#  factor_3 factor_1 factor_2
#  <fct>    <fct>    <chr>
#1 3        A        X
#2 3        A        Y
#3 3        A        Z

#[[3]]
# A tibble: 3 x 3
#  factor_2 factor_1 factor_3
#  <fct>    <fct>    <chr>
#1 Y        A        1
#2 Y        A        2
#3 Y        A        3


问:
GraphQLServer union types "Abstract type N must resolve to an Object type at runtime" error
Given a GraphQL union return type:

```<code>union GetBankAccountsResponseOrUserInputRequest = GetAccountsResponse | UserInputRequest
</code>```

meant to be returned by a given resolver:

```<code>type Query {
  getBankAccounts: GetBankAccountsResponseOrUserInputRequest!
}
</code>```

I'm getting these warnings or errors regarding a __resolveType or __isTypeOf function:

```<code>Abstract type N must resolve to an Object type at runtime for field Query.getBankAccounts with value { ..., __isTypeOf: [function __isTypeOf] }, received "undefined". Either the N type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.'
</code>```

I've searched for days in github issues and SO questions looking to resolve this error.

Implementing __resolveType or __isTypeOf in my resolvers is not working:

```<code>export const Query = {
  getBankAccounts: (parent, args, context: IContext, info) => {
    return {
      __isTypeOf(obj) { // OR __resolveType, none of them work
        return `GetAccountsResponse`;
      },
      accounts: []
    };
  },
};
</code>```

答:
Since implementing __resolveType or __isTypeOf in my resolvers didn't work for me, I ended up solving this issue by adding the __typename directly into the resolver return Object.

In the getBankAccounts resolver implementation:

async getBankAccounts(): GetBankAccountsResponseOrUserInputRequest {
    if (shouldGetUserInputRequest()) {
      return {
        __typename: "UserInputRequest",
        ...response,
      };
    }

    return {
      __typename: "GetAccountsResponse",
      accounts,
    };
  }
```

Hope that this helps somebody.

Body:
Given a GraphQL union return type:

union GetBankAccountsResponseOrUserInputRequest = GetAccountsResponse | UserInputRequest

meant to be returned by a given resolver:

type Query {
  getBankAccounts: GetBankAccountsResponseOrUserInputRequest!
}

I'm getting these warnings or errors regarding a __resolveType or __isTypeOf function:

Abstract type N must resolve to an Object type at runtime for field Query.getBankAccounts with value { ..., __isTypeOf: [function __isTypeOf] }, received "undefined". Either the N type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.'

I've searched for days in github issues and SO questions looking to resolve this error.

Implementing __resolveType or __isTypeOf in my resolvers is not working:

export const Query = {
  getBankAccounts: (parent, args, context: IContext, info) => {
    return {
      __isTypeOf(obj) { // OR __resolveType, none of them work
        return `GetAccountsResponse`;
      },
      accounts: []
    };
  },
};

Body:
Since implementing __resolveType or __isTypeOf in my resolvers didn't work for me, I ended up solving this issue by adding the __typename directly into the resolver return Object.

In the getBankAccounts resolver implementation:

async getBankAccounts(): GetBankAccountsResponseOrUserInputRequest {
    if (shouldGetUserInputRequest()) {
      return {
        __typename: "UserInputRequest",
        ...response,
      };
    }

    return {
      __typename: "GetAccountsResponse",
      accounts,
    };
  }

Hope that this helps somebody.


问:
webpack - Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin'
I got this error when I do ng serve --open. I had latest node/npm and angular-cli, etc. This is the error.

node -v (v10.13.0) & npm (6.4.1)

What can be done to fix this issue?

```<code>ERROR in ./src/main.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (C:\Users\mic\angular\test7\node_modules\@ngtools\webpack\src\resource_loader.js:16:28)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)

at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (C:\Users\mic\angular\test7\node_modules\@ngtools\webpack\src\angular_compiler_plugin.js:23:27)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
ERROR in ./src/polyfills.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (C:\Users\mic\angular\test7\node_modules\@ngtools\webpack\src\resource_loader.js:16:28)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (C:\Users\mic\angular\test7\node_modules\@ngtools   \webpack\src\angular_compiler_plugin.js:23:27)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
</code>```

答:
I guess that I've had the same problem and I fixed it with this:

at first type this:

```<code>npm i webpack -g
</code>```

then type:

```<code>npm link webpack --save-dev
</code>```

at the end:

```<code>ng serve
</code>```

Body:
I got this error when I do ng serve --open. I had latest node/npm and angular-cli, etc. This is the error.

node -v (v10.13.0) & npm (6.4.1)

What can be done to fix this issue?

ERROR in ./src/main.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (C:\Users\mic\angular\test7\node_modules\@ngtools\webpack\src\resource_loader.js:16:28)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)

at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (C:\Users\mic\angular\test7\node_modules\@ngtools\webpack\src\angular_compiler_plugin.js:23:27)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
ERROR in ./src/polyfills.ts
Module build failed (from ./node_modules/@ngtools/webpack/src/index.js):
Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
at Function.Module._load (internal/modules/cjs/loader.js:506:25)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (C:\Users\mic\angular\test7\node_modules\@ngtools\webpack\src\resource_loader.js:16:28)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (C:\Users\mic\angular\test7\node_modules\@ngtools   \webpack\src\angular_compiler_plugin.js:23:27)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)

Body:
I guess that I've had the same problem and I fixed it with this:

at first type this:

npm i webpack -g

then type:

npm link webpack --save-dev

at the end:

ng serve


问:
data rollback when one of the stored prod found faile in .net c#
Does anyone know how can I all data rollback in .net c# if one of the stored proc failed during the process?

Example:

```<code> protected void btnSave_Click(object sender, EventArgs e)
   {
      int ixTest= SaveTest("123");
      CreateTest(ixTest);

   }

   protected int SaveTest(int ixTestID)
   {
      SubSonic.StoredProcedure sp = Db.SPs.TestInsert(
         null,
         ixTestID);
      sp.Execute();
      int ixTest= (int)sp.OutputValues[0];
      return ixTest;
   }

   private long CreateTest(int ixTest)
   {
      long ixTestCustomer = CreateTestCustomer();

      TestCustomer testCustomer= new TestCustomer();
      try
      {
          testCustomer.TestCustomerId = ixTest;
          testCustomer.InteractionId = ixTestCustomer ;
          testCustomer.Save();
      }
      catch
      {
          Response.Redirect("pgCallSaveFailure.aspx");
      }

      m_saleDetail = new TestSaleDetail();
      try
      {
          m_saleDetail.SaleId = sale.SaleId;
          m_saleDetail.Save();
      }
      catch
      {
          Response.Redirect("pgCallSaveFailure.aspx");
      }

      return ixTestCustomer ;
   }
</code>```

I have the following code will call to btnSave_Click, then it will call to another 2 function Savetest() and CreateTest() to save data into the database. How can I rollback all data transaction in the following code if issue only happened in CreateTest() and which Savetest() have run successfully. How can I rollback all data for both Savetest() and CreateTest()?

答: Use the TransactionScope class</p>

Body:
Does anyone know how can I all data rollback in .net c# if one of the stored proc failed during the process?

Example:

 protected void btnSave_Click(object sender, EventArgs e)
   {
      int ixTest= SaveTest("123");
      CreateTest(ixTest);

   }

   protected int SaveTest(int ixTestID)
   {
      SubSonic.StoredProcedure sp = Db.SPs.TestInsert(
         null,
         ixTestID);
      sp.Execute();
      int ixTest= (int)sp.OutputValues[0];
      return ixTest;
   }

   private long CreateTest(int ixTest)
   {
      long ixTestCustomer = CreateTestCustomer();

      TestCustomer testCustomer= new TestCustomer();
      try
      {
          testCustomer.TestCustomerId = ixTest;
          testCustomer.InteractionId = ixTestCustomer ;
          testCustomer.Save();
      }
      catch
      {
          Response.Redirect("pgCallSaveFailure.aspx");
      }

      m_saleDetail = new TestSaleDetail();
      try
      {
          m_saleDetail.SaleId = sale.SaleId;
          m_saleDetail.Save();
      }
      catch
      {
          Response.Redirect("pgCallSaveFailure.aspx");
      }

      return ixTestCustomer ;
   }

I have the following code will call to btnSave_Click, then it will call to another 2 function Savetest() and CreateTest() to save data into the database. How can I rollback all data transaction in the following code if issue only happened in CreateTest() and which Savetest() have run successfully. How can I rollback all data for both Savetest() and CreateTest()?

Body: Use the TransactionScope class


问:
Write inline assembly without clobber lists?
Is it possible to write inline assembly (Intel syntax) with GCC or Clang, without needing to understand the clobber list "stuff"?

I'm going to guess "no" because the clobber list "stuff" ensures you don't over-write the register the compiler wrote to (immediately before your inline assembly begins)?

答:
GNU C Basic inline asm statements (no operand/clobber lists) are not recommended for basically anything except maybe the body of an __attribute__((naked)) function.  Why can't local variable be used in GNU C basic inline asm statements? (globals can't safely be used either.)

https://gcc.gnu.org/wiki/DontUseInlineAsm says to see ConvertBasicAsmToExtended for reasons not to use Basic asm statements.  You can't really do anything safely in Basic asm; even asm("cli"); can get reordered with any memory accesses that aren't volatile.

If you're going to use inline asm at all (instead of writing a stand-alone function in asm, or C with intrinsics), you need to describe your string of asm instruction in exact detail to the compiler, in terms of a black box with input and/or output operands, and/or clobbers.  See https://stackoverflow.com/tags/inline-assembly/info for links to guides, including some SO answers about using input / output constraints.

Think hard before deciding it's really worth using GNU C inline asm for anything.  If you can get the compiler to emit the same instructions another way, that's almost always better.  Intrinsics or pure C allow constant-propagation optimization; inline asm doesn't (unless you do stuff like  if(_builtin_constant_p(x)) { pure C version } else { inline asm version }).

Intel syntax: in GCC, compile with -masm=intel so your asm template will be part of an Intel-syntax .s, and the compiler will substitute in operands in Intel syntax.  (Like dword ptr [rsp] instead of (%rsp) for "m"(my_int)).

In clang I'm not sure there's any convenient way to use Intel-syntax in normal asm statements.

There is one other option though, if you don't care about efficient code (but then why are you using asm?):  clang supports -fasm-blocks to allow syntax like MSVC's inefficient style of inline asm.  And yes, this uses Intel syntax.

Is there any way to complie a microsoft style inline-assembly code on a linux platform? shows how inefficient the resulting code is: full of compiler-generated instructions to store input variables to memory for the asm{} block to read them.  Because MSVC-style asm blocks can't do inputs or outputs in registers.  (Clang doesn't support the leave-a-value-in-EAX method for getting a single value out so the output has to be stored/reloaded as well.)

You don't get to specify clobbers for this, so I assume an asm block implies a "memory" clobber, along with clobbers on all registers you write.  (Or maybe even just mention.)

I would not recommend this; it's basically not possible to wrap a single instruction or handful of instructions efficiently this way.  Only if you're writing a whole loop can you amortize the overhead of getting inputs into an asm{} block.


问:
OS dev: triple fault when trying to enable paging
I am building a simple OS for learning purposes and I am (currently; I followed different tutorials earlier and customized something by myself) following this tutorial for enabling paging. I'm using QEMU instead of Bochs as my emulator.

If I keep paging disabled everything works fine (even the very basic kmalloc() I implemented), but as soon as I set the PG bit in the cr0 register (i.e. enable paging), everything crashes and QEMU reboots: I suspect that some of the structures (i.e. page directory, page tables, etc.) I have are not created or loaded properly, but I have no way of checking.

I've been trying to solve this problem since a while now, but haven't found a solution. Can anyone see where my mistake is?

Here you can find my complete code: https://github.com/davidedellagiustina/ScratchOS (commit 83b5c8c). Paging code is located in src/cpu/paging.*.

Edit: Setting up a super-basic page directory following exactly this tutorial results in working code. Basing on this simple example, I'm trying to build up the more complex structures (i.e. page_t, page_table_t, page_directory_t) in order to understand the mistake.

答:
In general:

pointers should be for virtual addresses only (and should never be used for physical addresses)

physical addresses should probably be using a typedef (e.g. like typedef uint32_t phys_address_t) so that later (when you want to support PAE/Physical Address Extensions) you can change the type (e.g. use typedef uint64_t phys_address_t instead) without breaking everything. This also means you get compile-time warnings/errors when you make silly mistakes (e.g. using a virtual address/pointer where you need a physical address/unsigned integer).

almost all of the kernel should be using pointers/virtual addresses for everything. Physical addresses are only used by some device drivers (for bus mastering/DMA) and for the physical memory management itself (to allocate physical pages for page tables, etc; before mapping them into a virtual address space). This includes high level memory management ("kmalloc()" should return a void * pointer and not a physical address).

during boot, there's a small period of time when none of the kernel's normal code can work because it uses virtual addresses and paging hasn't been initialized yet. To minimize the size of this period of time (and code duplication caused by having 2 versions of functions - one for "before paging initialized" and another for "after paging initialized") you want to initialize paging as soon as possible; either with a dedicated piece of assembly language startup code that's executed before "main()" (possibly using "statically allocated at compile time" memory in the kernel's ".bss" section for the page directory and page tables), or in the boot loader itself (which is cleaner and more powerful/flexible). Things like setting up a valid kernel stack, and initializing  (physical, virtual then heap) memory management, can/should wait until after paging has been initialized.

for identity mapping; you'd only need 2 loops (one to create page directory entries and another to create all page table entries), where both loops can be like this (just with different initial values in eax, ecx and edi):

```<code>.nextEntry:
    stosd
    add eax,0x00001000
    loop .nextEntry
</code>```

identity mapping isn't great. Normally you want the kernel at a high virtual address (e.g. 0xC0000000) with an area of "deliberately not used to catch NULL pointers" at 0x0000000, and user-space (processes, etc) using normal virtual addresses between them (e.g. maybe starting at virtual address 0x00400000). This makes it annoying for the code that initializes paging and the kernel's linker script (which is why it's cleaner to initialize paging in the boot loader and avoid the mess in the kernel). For this case; you will need to temporarily identity map one page (the page containing the final "mov cr0" that enables paging and the jmp kernel_entry that transfers control to code/the kernel at a higher address), and will want to delete that temporarily identity mapped page after kernel's main is started.

you will need to become "very familiar" with the debugging capabilities of your emulator. Qemu has a log that can provide very useful clues, and includes a built in monitor that offers a variety of commands (see https://en.wikibooks.org/wiki/QEMU/Monitor ). You should be able to replace the "mov cr0" (that enables paging) with an endless loop (.die: jmp die), then use the monitor to stop the emulator after it reaches the endless loop and inspect everything (contents of cr3, contents of physical memory) and find out what is wrong with the page directory or page table entries (and do similar immediately after paging is enabled to inspect the virtual address space before your code does anything with it). Qemu also allows you to attach a remote debugger (GDB).

Body:
In general:

pointers should be for virtual addresses only (and should never be used for physical addresses)

physical addresses should probably be using a typedef (e.g. like typedef uint32_t phys_address_t) so that later (when you want to support PAE/Physical Address Extensions) you can change the type (e.g. use typedef uint64_t phys_address_t instead) without breaking everything. This also means you get compile-time warnings/errors when you make silly mistakes (e.g. using a virtual address/pointer where you need a physical address/unsigned integer).

almost all of the kernel should be using pointers/virtual addresses for everything. Physical addresses are only used by some device drivers (for bus mastering/DMA) and for the physical memory management itself (to allocate physical pages for page tables, etc; before mapping them into a virtual address space). This includes high level memory management ("kmalloc()" should return a void * pointer and not a physical address).

during boot, there's a small period of time when none of the kernel's normal code can work because it uses virtual addresses and paging hasn't been initialized yet. To minimize the size of this period of time (and code duplication caused by having 2 versions of functions - one for "before paging initialized" and another for "after paging initialized") you want to initialize paging as soon as possible; either with a dedicated piece of assembly language startup code that's executed before "main()" (possibly using "statically allocated at compile time" memory in the kernel's ".bss" section for the page directory and page tables), or in the boot loader itself (which is cleaner and more powerful/flexible). Things like setting up a valid kernel stack, and initializing  (physical, virtual then heap) memory management, can/should wait until after paging has been initialized.

for identity mapping; you'd only need 2 loops (one to create page directory entries and another to create all page table entries), where both loops can be like this (just with different initial values in eax, ecx and edi):

.nextEntry:
    stosd
    add eax,0x00001000
    loop .nextEntry

identity mapping isn't great. Normally you want the kernel at a high virtual address (e.g. 0xC0000000) with an area of "deliberately not used to catch NULL pointers" at 0x0000000, and user-space (processes, etc) using normal virtual addresses between them (e.g. maybe starting at virtual address 0x00400000). This makes it annoying for the code that initializes paging and the kernel's linker script (which is why it's cleaner to initialize paging in the boot loader and avoid the mess in the kernel). For this case; you will need to temporarily identity map one page (the page containing the final "mov cr0" that enables paging and the jmp kernel_entry that transfers control to code/the kernel at a higher address), and will want to delete that temporarily identity mapped page after kernel's main is started.

you will need to become "very familiar" with the debugging capabilities of your emulator. Qemu has a log that can provide very useful clues, and includes a built in monitor that offers a variety of commands (see https://en.wikibooks.org/wiki/QEMU/Monitor ). You should be able to replace the "mov cr0" (that enables paging) with an endless loop (.die: jmp die), then use the monitor to stop the emulator after it reaches the endless loop and inspect everything (contents of cr3, contents of physical memory) and find out what is wrong with the page directory or page table entries (and do similar immediately after paging is enabled to inspect the virtual address space before your code does anything with it). Qemu also allows you to attach a remote debugger (GDB).


问:
How can one use one's own SVG in Font Awesome?
I have a custom made .svg file called "carport.svg". I would like to use it as if it was already included in FontAwesome and therefore use the FontAwesome infrastructure. I have placed my file in the \svgs\solid folder.

What more do I need to do to import it fully? I would like to then write in my HTML:

```<code><i class="fas fa-carport"></i>
</code>```

答:
To use the Font Awesome icons, add the following line inside the  section of your HTML page:

```<code><link href="/your-path-to-fontawesome/css/fontawesome.css" rel="stylesheet">
</code>```

Refer to https://fontawesome.com/how-to-use/on-the-web/referencing-icons/basic-use

Body:
To use the Font Awesome icons, add the following line inside the  section of your HTML page:

<link href="/your-path-to-fontawesome/css/fontawesome.css" rel="stylesheet">

Refer to https://fontawesome.com/how-to-use/on-the-web/referencing-icons/basic-use


问:
I need assistance with cog_command_error
I'm new to using cogs and have just found out about cog_command_error. I have attempted to apply it to my code

    @commands.Cog.listener()
    async def cog_command_error(self, ctx, error):
        """Reports errors to users"""
        m, s = divmod(error.retry_after, 60)
        h, m = divmod(m, 60)
        if isinstance(error, commands.errors.MissingRole):
            await ctx.send("You do not have the correct role for this command.")
        elif isinstance(error,commands.errors.CheckFailure):
            await ctx.send("This command is blocked from this channel please use it in <#597918255188803588>")
        elif isinstance(error, commands.CommandOnCooldown):
            errMessage = f"{ctx.author.mention}, Try again in {round(h)} hours, {round(m)} minutes, and {round(s)} seconds."
            await ctx.send(errMessage)
```

<p>however i keep getting this error :</p>

```  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 596, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "c:\Users\Jimmy\Desktop\GovsM\cogs\fun.py", line 19, in <module>
    class fun(commands.Cog):
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\cog.py", line 124, in __new__
    raise TypeError(no_bot_cog.format(base, elem))
TypeError: Commands or listeners must not start with cog_ or bot_ (in method fun.cog_command_error)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\Users\Jimmy\.vscode\extensions\ms-python.python-2020.2.63072\pythonFiles\ptvsd_launcher.py", line 48, in <module>
    main(ptvsdArgs)
  File "c:\Users\Jimmy\.vscode\extensions\ms-python.python-2020.2.63072\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 432, in main
    run()
  File "c:\Users\Jimmy\.vscode\extensions\ms-python.python-2020.2.63072\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 316, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 263, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 96, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "c:\Users\Jimmy\Desktop\GovsM\Govs.py", line 438, in <module>
    loadall()
  File "c:\Users\Jimmy\Desktop\GovsM\Govs.py", line 436, in loadall
    bot.load_extension(f'cogs.{filename[:-3]}')
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 653, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 599, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: TypeError: Commands or listeners must not start with cog_ or bot_ (in method fun.cog_command_error)
```

I would appreciate any assistance in working out what's wrong, I've tried multiple ways and the only way I got it working was on on_command_error which I don't want.

答:
You need to remove the decorator. It should just be async def cog_command_error(self, ctx, error): with no decorator.

Here is a small example where if you pass in a string as the argument it print "Bad argument error" to console

```<code>@commands.command()
async def numError(self, ctx, test: int):
    await ctx.send(test)

async def cog_command_error(self, ctx, error):
    if isinstance(error, commands.BadArgument):
        print("Bad Argument Error")
</code>```

Body:
I'm new to using cogs and have just found out about cog_command_error. I have attempted to apply it to my code

    @commands.Cog.listener()
    async def cog_command_error(self, ctx, error):
        """Reports errors to users"""
        m, s = divmod(error.retry_after, 60)
        h, m = divmod(m, 60)
        if isinstance(error, commands.errors.MissingRole):
            await ctx.send("You do not have the correct role for this command.")
        elif isinstance(error,commands.errors.CheckFailure):
            await ctx.send("This command is blocked from this channel please use it in <#597918255188803588>")
        elif isinstance(error, commands.CommandOnCooldown):
            errMessage = f"{ctx.author.mention}, Try again in {round(h)} hours, {round(m)} minutes, and {round(s)} seconds."
            await ctx.send(errMessage)

however i keep getting this error :

  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 596, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "c:\Users\Jimmy\Desktop\GovsM\cogs\fun.py", line 19, in <module>
    class fun(commands.Cog):
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\cog.py", line 124, in __new__
    raise TypeError(no_bot_cog.format(base, elem))
TypeError: Commands or listeners must not start with cog_ or bot_ (in method fun.cog_command_error)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\Users\Jimmy\.vscode\extensions\ms-python.python-2020.2.63072\pythonFiles\ptvsd_launcher.py", line 48, in <module>
    main(ptvsdArgs)
  File "c:\Users\Jimmy\.vscode\extensions\ms-python.python-2020.2.63072\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 432, in main
    run()
  File "c:\Users\Jimmy\.vscode\extensions\ms-python.python-2020.2.63072\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py", line 316, in run_file
    runpy.run_path(target, run_name='__main__')
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 263, in run_path
    return _run_module_code(code, init_globals, run_name,
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 96, in _run_module_code
    _run_code(code, mod_globals, init_globals,
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "c:\Users\Jimmy\Desktop\GovsM\Govs.py", line 438, in <module>
    loadall()
  File "c:\Users\Jimmy\Desktop\GovsM\Govs.py", line 436, in loadall
    bot.load_extension(f'cogs.{filename[:-3]}')
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 653, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Jimmy\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 599, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: TypeError: Commands or listeners must not start with cog_ or bot_ (in method fun.cog_command_error)

I would appreciate any assistance in working out what's wrong, I've tried multiple ways and the only way I got it working was on on_command_error which I don't want.

Body:
You need to remove the decorator. It should just be async def cog_command_error(self, ctx, error): with no decorator.

Here is a small example where if you pass in a string as the argument it print "Bad argument error" to console

@commands.command()
async def numError(self, ctx, test: int):
    await ctx.send(test)

async def cog_command_error(self, ctx, error):
    if isinstance(error, commands.BadArgument):
        print("Bad Argument Error")


问:
Is it required for a Calendar app to use Calendar Provider?
I'm developing an app where the user can create Events(like Calendar apps), Tasks(like Todo apps), or a Habit(like Habits tracking apps). My question is: Is it required for my app to store the events that the user creates in the Calendar Provider, if so, then what about tasks and habits? Do I also store them in the Calendar Provider?</p>

答:
Is it required for my app to store the events that the user creates in the Calendar Provider

No. It is an option, but you can store the events in your own database if you prefer. Or, you could give the user the choice, either for the entire app or on a per-event basis, if you like.

if so, then what about tasks and habits? Do I also store them in the Calendar Provider?

CalendarProvider is only for calendar entries. My guess is that "tasks and habits" are not calendar entries, so they would go in your own database.


问:
MPAndroidChart - Remove Top and Bottom Spaces
I am using MPAndroidChart library.

I implement a PieChart in my application. Everything works fine, but there is a blank space at the top and at the end of the Chart.
I need to remove this space to properly visualize my activity layout

My question is:

Is possible to remove them programmatically?

P.D. In my layout, there is non marginTop or marginBottom.

Layout xml:

```<code><com.github.mikephil.charting.charts.PieChart
   android:id="@+id/pieChart"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_below="@id/_home_consumed" >
</com.github.mikephil.charting.charts.PieChart>
</code>```

答:
The pie chart does not only have a default offset of 10, but it also adds additional space to let you highlight the selected entry (see this comment on GitHub. To remove all padding you need to remove the space for the selected entry, too:

pieChart.setExtraOffsets(0, 0, 0, 0);

PieDataSet dataSet = new PieDataSet([..]);
dataSet.setSelectionShift(0f);
```

Body:
I am using MPAndroidChart library.

I implement a PieChart in my application. Everything works fine, but there is a blank space at the top and at the end of the Chart.
I need to remove this space to properly visualize my activity layout

My question is:

Is possible to remove them programmatically?

P.D. In my layout, there is non marginTop or marginBottom.

Layout xml:

<com.github.mikephil.charting.charts.PieChart
   android:id="@+id/pieChart"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_below="@id/_home_consumed" >
</com.github.mikephil.charting.charts.PieChart>


问:
Client ssl using mbedtls using C
I am getting error message during handshake

mbedtls_ssl_read_record_layer() returned -29184 (-0x7200)

mbedtls_ssl_read_record() returned -29184 (-0x7200)

Why this error..?

答:
You can look up Mbed TLS error codes with the strerror utility available with the library's source code.

```<code>programs/util/strerror 29184
Last error was: -0x7200 - SSL - An invalid SSL record was received
</code>```

There could be many reasons for receiving an invalid record. If this is on the first message received from a server, this probably indicates that the server isn't using the TLS protocol. At other times, it probably indicates that something is corrupting packets. This could also indicate that the peer is using some TLS protocol extension that your library doesn't support, although this would usually be detected during the handshake. With DTLS, it could be a stray packet remaining from a previous connection on the same ports.

Title: Client ssl using mbedtls using C

Body:
You can look up Mbed TLS error codes with the strerror utility available with the library's source code.

programs/util/strerror 29184
Last error was: -0x7200 - SSL - An invalid SSL record was received

There could be many reasons for receiving an invalid record. If this is on the first message received from a server, this probably indicates that the server isn't using the TLS protocol. At other times, it probably indicates that something is corrupting packets. This could also indicate that the peer is using some TLS protocol extension that your library doesn't support, although this would usually be detected during the handshake. With DTLS, it could be a stray packet remaining from a previous connection on the same ports.


问:
Data Studio - Can you display the date of a Max Metric within a Chart?
I am working on creating a table that displays the Max Value of a metric that exists across several different dimensions. I'd like to be able to have the date that max value was recorded within the table as well. Essentially we want to know what our current "record" is and when it was reached.

If I add the "date" as a dimension, the chart then pulls in every record rather than just the max for the other dimensions.

Any thoughts on how to achieve this?

答:
Created a Google Data Studio Report to demonstrate. One way it could be achieved is using the NARY_MAX function:

1) Create a  Table

  - Dimension: Date

2) Metric (Calculated Field)

  - NARY_MAX: The formula takes the MAX value in each row from the fields specified, for example (using 3 fields to demonstrate, although more or fewer fields could be used based on the use case):

```<code>NARY_MAX(Field_1, Field_2, Field_3, Field_n)
</code>```

3) Sort

  - Rows per page: 1

  - Sort: NARY_MAX (Field created in #2 above) in Descending order

Body:
Created a Google Data Studio Report to demonstrate. One way it could be achieved is using the NARY_MAX function:

1) Create a  Table

  - Dimension: Date

2) Metric (Calculated Field)

  - NARY_MAX: The formula takes the MAX value in each row from the fields specified, for example (using 3 fields to demonstrate, although more or fewer fields could be used based on the use case):

NARY_MAX(Field_1, Field_2, Field_3, Field_n)

3) Sort

  - Rows per page: 1

  - Sort: NARY_MAX (Field created in #2 above) in Descending order


问:
In CSS what is the difference between "." and "#" when declaring a set of styles?
What is the difference between # and . when declaring a set of styles for an element and what are the semantics that come into play when deciding which one to use?

答:
A couple of quick extensions on what has already been said...

An id must be unique, but you can use the same id to make different styles more specific.

For example, given this HTML extract:

```<code><div id="sidebar">
    <h2>Heading</h2>
    <ul class="menu">
        ...
    </ul>
</div>
<div id="content">
    <h2>Heading</h2>
    ...
</div>
<div id="footer">
    <ul class="menu">
        ...
    </ul>
</div>
</code>```

You could apply different styles with these:

```<code>#sidebar h2
{ ... }

#sidebar .menu
{ ... }

#content h2
{ ... }

#footer .menu
{ ... }
</code>```

Another useful thing to know: you can have multiple classes on an element, by space-delimiting them...

```<code><ul class="main menu">...</ul>
<ul class="other menu">...</ul>
</code>```

Which allows you to have common styling in .menu with specific styles using .main.menu and .sub.menu

```<code>.menu
{ ... }

.main.menu
{ ... }

.other.menu
{ ... }
</code>```

LastEditorDisplayName: Drew Noakes

Body:
A couple of quick extensions on what has already been said...

An id must be unique, but you can use the same id to make different styles more specific.

For example, given this HTML extract:

<div id="sidebar">
    <h2>Heading</h2>
    <ul class="menu">
        ...
    </ul>
</div>
<div id="content">
    <h2>Heading</h2>
    ...
</div>
<div id="footer">
    <ul class="menu">
        ...
    </ul>
</div>

You could apply different styles with these:

#sidebar h2
{ ... }

#sidebar .menu
{ ... }

#content h2
{ ... }

#footer .menu
{ ... }

Another useful thing to know: you can have multiple classes on an element, by space-delimiting them...

<ul class="main menu">...</ul>
<ul class="other menu">...</ul>

Which allows you to have common styling in .menu with specific styles using .main.menu and .sub.menu

.menu
{ ... }

.main.menu
{ ... }

.other.menu
{ ... }

OwnerDisplayName: Peter Boughton

ContentLicense: CC BY-SA 2.5


问:
MVVM binding viewmodel property child to viewmodel property
not sure if my title explains well the issue im having.

In my application i make a service calls to
-retrieve a list of customers.
-retrieve a list of organisations.

Then i bind this list of customers to a listbox on my view.

In my viewmodel i have the following properties:

```<code>IEnumerable<Organisation> Organisations
ObservableCollection<Customer> Customers
</code>```

Organisation properties: OrganisationId, OrganisationName

Customer properties: CustomerId, OrganisationId, CustomerFirstName, CustomerLastName

Inside the Listbox on my view i want to show the organisationname for each customer in the list.

how can i go about binding this in my view? I just want a textblock to show the organisationname for the customer.

答: I agree with Ritch that you should flatten the model, but if you really don't want to do that, you could use an IValueConverter. In the binding for where you want the name to be displayed, if you set Organizations to be the datacontext of another control, you could do element-to-element binding and pass the other control's datacontext in the binding, and in the ConverterParameter pass the OrganizationId, then in the Converter code use a little LINQ and return the Name you want</p>

Body:
not sure if my title explains well the issue im having.

In my application i make a service calls to
-retrieve a list of customers.
-retrieve a list of organisations.

Then i bind this list of customers to a listbox on my view.

In my viewmodel i have the following properties:

IEnumerable<Organisation> Organisations
ObservableCollection<Customer> Customers

Organisation properties: OrganisationId, OrganisationName

Customer properties: CustomerId, OrganisationId, CustomerFirstName, CustomerLastName

Inside the Listbox on my view i want to show the organisationname for each customer in the list.

how can i go about binding this in my view? I just want a textblock to show the organisationname for the customer.


问:
Python - How to filter a list by multiples of all elements of a list with a lambda function?
I have the following code:

```<code>a = [2, 4]
b = list(range(1,10))
print(list(filter((lambda x: (x % f == 0) for f in a), b)))
</code>```

My goal is to get back:

```<code>[4, 8]
</code>```

instead I get:

```<code>TypeError: 'generator' object is not callable
</code>```

This is because between 4 and 8 divide by both 2 and 4. (I'm trying to get my code to work, not solve the specific problem, I know I could just use 4 and solve it quick.) Thank you so much to all!!

答:
This works:

```<code>a = [2, 4]
b = list(range(1,10))
print(list(filter(lambda x: all(x % f == 0 for f in a), b)))
</code>```

Output:

```<code>[4, 8]
</code>```

The issue is that (lambda x: (x % f == 0) for f in a) is a generator, not a function (or lambda statement).

Body:
I have the following code:

a = [2, 4]
b = list(range(1,10))
print(list(filter((lambda x: (x % f == 0) for f in a), b)))

My goal is to get back:

[4, 8]

instead I get:

TypeError: 'generator' object is not callable

This is because between 4 and 8 divide by both 2 and 4. (I'm trying to get my code to work, not solve the specific problem, I know I could just use 4 and solve it quick.) Thank you so much to all!!

Body:
This works:

a = [2, 4]
b = list(range(1,10))
print(list(filter(lambda x: all(x % f == 0 for f in a), b)))

Output:

[4, 8]

The issue is that (lambda x: (x % f == 0) for f in a) is a generator, not a function (or lambda statement).


问:
Get rendered bounds of a view in viewDidLoad()
I've been searching for help on this all day but I can't find an answer.

I have a subview in which I am drawing a rectangle, the rectangle is framed by the subview so I need to know the size of the subview as adjusted by autolayout to correctly frame it.  I can't find a way of doing this from ViewDidLoad(), so that the rectangle is correctly rendered at start-up.  I have tried the following:

Using dayView.setNeedsLayout() followed by dayView.layoutIfNeeded() before I draw the rectangle in viewDidLoad() but a check either side of these statements shows the dayView.bounds unchanged.

Drawing the view from viewDidLayoutSubviews(), which works, but results in my rectangle being drawn 5 times as viewDidLayoutSubviews() is called for every subview (I have 5 of them) that is redrawn (the relevant subview containing the rectangle is redrawn on call 4 of 5) - this seems wasteful of resources, surely there is a better way?

Drawing the view twice within ViewDidLoad(), hoping the first forced draw will cause the view to be resized, so the second draw will have access to the new bounds after the first draw (desperate I know, but it still doesn't work).

I hope someone can help.

```<code>func drawGradient(object: UIView, rect: CGRect, slackX: Int, gradWidth: Int, yPos: Int) -> Void {
    // the rectangle width and height set to fit within view with x & y border.

    let gradientView = UIView(frame: rect)
    let gradient = CAGradientLayer()

    gradient.frame = gradientView.frame
    gradient.colors = getDayGradientLocations().gradientCol
    gradient.locations = getDayGradientLocations().gradientLoc
    dayView.layer.addSublayer(gradient)

    let civilDawn = getTimeAsProportionOfDay(time: tides.civilDawn) * Double(rect.height) + Double(yPos)
    let path = UIBezierPath()
    path.move(to: CGPoint(x: slackX, y: Int(civilDawn)))
    path.addLine(to: CGPoint(x: slackX + Int(rect.width), y: Int(civilDawn)))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = CGFloat(2)

    let civilDusk = getTimeAsProportionOfDay(time: tides.civilDusk) * Double(rect.height) + Double(yPos)
    path.move(to: CGPoint(x: slackX, y: Int(civilDusk)))
    path.addLine(to: CGPoint(x: slackX + Int(rect.width), y: Int(civilDusk)))
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = CGFloat(2)

    object.layer.addSublayer(shapeLayer)

    drawLabel(object: object, rect: rect, slackX: slackX, offset: 15, time: tides.civilDawn)
    drawLabel(object: object, rect: rect, slackX: slackX, offset: -15, time: tides.civilDusk)
}
</code>```

答:
Got to main thread in viewDidLoad and Perform action will resolve your issue</p>

```<code>         DispatchQueue.main.async {
                // here you can add anything it will have proper frame
            }
</code>```

Body:
I've been searching for help on this all day but I can't find an answer.

I have a subview in which I am drawing a rectangle, the rectangle is framed by the subview so I need to know the size of the subview as adjusted by autolayout to correctly frame it.  I can't find a way of doing this from ViewDidLoad(), so that the rectangle is correctly rendered at start-up.  I have tried the following:

Using dayView.setNeedsLayout() followed by dayView.layoutIfNeeded() before I draw the rectangle in viewDidLoad() but a check either side of these statements shows the dayView.bounds unchanged.

Drawing the view from viewDidLayoutSubviews(), which works, but results in my rectangle being drawn 5 times as viewDidLayoutSubviews() is called for every subview (I have 5 of them) that is redrawn (the relevant subview containing the rectangle is redrawn on call 4 of 5) - this seems wasteful of resources, surely there is a better way?

Drawing the view twice within ViewDidLoad(), hoping the first forced draw will cause the view to be resized, so the second draw will have access to the new bounds after the first draw (desperate I know, but it still doesn't work).

I hope someone can help.

func drawGradient(object: UIView, rect: CGRect, slackX: Int, gradWidth: Int, yPos: Int) -> Void {
    // the rectangle width and height set to fit within view with x & y border.

    let gradientView = UIView(frame: rect)
    let gradient = CAGradientLayer()

    gradient.frame = gradientView.frame
    gradient.colors = getDayGradientLocations().gradientCol
    gradient.locations = getDayGradientLocations().gradientLoc
    dayView.layer.addSublayer(gradient)

    let civilDawn = getTimeAsProportionOfDay(time: tides.civilDawn) * Double(rect.height) + Double(yPos)
    let path = UIBezierPath()
    path.move(to: CGPoint(x: slackX, y: Int(civilDawn)))
    path.addLine(to: CGPoint(x: slackX + Int(rect.width), y: Int(civilDawn)))

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = CGFloat(2)

    let civilDusk = getTimeAsProportionOfDay(time: tides.civilDusk) * Double(rect.height) + Double(yPos)
    path.move(to: CGPoint(x: slackX, y: Int(civilDusk)))
    path.addLine(to: CGPoint(x: slackX + Int(rect.width), y: Int(civilDusk)))
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = CGFloat(2)

    object.layer.addSublayer(shapeLayer)

    drawLabel(object: object, rect: rect, slackX: slackX, offset: 15, time: tides.civilDawn)
    drawLabel(object: object, rect: rect, slackX: slackX, offset: -15, time: tides.civilDusk)
}

Body:
Got to main thread in viewDidLoad and Perform action will resolve your issue

         DispatchQueue.main.async {
                // here you can add anything it will have proper frame
            }