问:
Spread Parameters<T> onto T without Typescript complaining
I've made a function for rendering a prop which may or may not be a React render prop/function:

```<code>import { isValidElement } from 'react';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type AnyFunction = (...args: any) => any;

export function isRenderFunction<F extends AnyFunction>(
  subject: React.ReactNode | F
): subject is F {
  return !isValidElement(subject) && subject instanceof Function;
}
export function render<F extends AnyFunction>(
  subject: React.ReactNode | F,
  ...parameters: Parameters<F>
): React.ReactNode {
  return isRenderFunction(subject)
    ? subject(
        // @ts-ignore
        ...parameters
      )
    : subject ?? null;
}
</code>```

The function works fine, but without that // @ts-ignore I'm getting the following error:

Type 'Parameters' must have a 'Symbol.iterator' method that returns an iterator.ts(2488)

I can make this error go away by changing to Parameters<F>[], i.e. typing it as an array, but then all the usages of the render function complains instead.

Playground Link:
Provided

Solution:
Based on accepted answer, I pulled out some "helper types", and ended up with this, which seems to work pretty good both code- and type-wise.

```<code>import { ReactNode, isValidElement } from 'react';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type AnyArg = any;

export type RenderFunction<A extends AnyArg[]> = (...args: A) => ReactNode;
export type RenderProp<A extends AnyArg[]> = ReactNode | RenderFunction<A>;

export function isRenderFunction<A extends AnyArg[]>(
  subject: RenderProp<A>
): subject is RenderFunction<A> {
  return !isValidElement(subject) && subject instanceof Function;
}

export function render<A extends AnyArg[]>(
  subject: RenderProp<A>,
  ...parameters: A
): ReactNode {
  return isRenderFunction(subject) ? subject(...parameters) : subject ?? null;
}
</code>```

答:
You could change the function to not use Parameters. Parameters being a conditional type can't be resolved until it does not contain any more type parameters, so it you use it you will need an assertion.

The version without Parameters would be:

```<code>import React, { isValidElement } from 'react';

export function isRenderFunction<P extends any[]>(
  subject: React.ReactNode | ((...p: P) => React.ReactNode)
): subject is ((...p: P) => React.ReactNode) {
  return !isValidElement(subject) && subject instanceof Function;
}
export function render<P extends any[]>(
  subject: React.ReactNode | ((...p: P) => React.ReactNode),
  ...parameters: P
): React.ReactNode {
  return isRenderFunction(subject)
    ? subject(
        ...parameters
      )
    : subject ?? null;
}
</code>```

Playground Link

Body:
I've made a function for rendering a prop which may or may not be a React render prop/function:

import { isValidElement } from 'react';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type AnyFunction = (...args: any) => any;

export function isRenderFunction<F extends AnyFunction>(
  subject: React.ReactNode | F
): subject is F {
  return !isValidElement(subject) && subject instanceof Function;
}
export function render<F extends AnyFunction>(
  subject: React.ReactNode | F,
  ...parameters: Parameters<F>
): React.ReactNode {
  return isRenderFunction(subject)
    ? subject(
        // @ts-ignore
        ...parameters
      )
    : subject ?? null;
}

The function works fine, but without that // @ts-ignore I'm getting the following error:

Type 'Parameters' must have a 'Symbol.iterator' method that returns an iterator.ts(2488)

I can make this error go away by changing to Parameters<F>[], i.e. typing it as an array, but then all the usages of the render function complains instead.

Playground Link:
Provided

Solution:
Based on accepted answer, I pulled out some "helper types", and ended up with this, which seems to work pretty good both code- and type-wise.

import { ReactNode, isValidElement } from 'react';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type AnyArg = any;

export type RenderFunction = (...args: A) => ReactNode;
export type RenderProp = ReactNode | RenderFunction;

export function isRenderFunction(
  subject: RenderProp
): subject is RenderFunction {
  return !isValidElement(subject) && subject instanceof Function;
}

export function render(
  subject: RenderProp,
  ...parameters: A
): ReactNode {
  return isRenderFunction(subject) ? subject(...parameters) : subject ?? null;
}

Body:
You could change the function to not use Parameters. Parameters being a conditional type can't be resolved until it does not contain any more type parameters, so it you use it you will need an assertion.

The version without Parameters would be:

import React, { isValidElement } from 'react';

export function isRenderFunction<P extends any[]>(
  subject: React.ReactNode | ((...p: P) => React.ReactNode)
): subject is ((...p: P) => React.ReactNode) {
  return !isValidElement(subject) && subject instanceof Function;
}
export function render<P extends any[]>(
  subject: React.ReactNode | ((...p: P) => React.ReactNode),
  ...parameters: P
): React.ReactNode {
  return isRenderFunction(subject)
    ? subject(
        ...parameters
      )
    : subject ?? null;
}

<a href="https://www.typescriptlang.org/play/?ssl=19&ssc=2&pln=1&pc=1#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDedgDOAaigDbAAmAoqUiEgHbwC+cAZlBCHAORSoYeAbgCwAKHGSxSAB6RY7AK4MMwCA3wFkDCkigAxZavUAeAApxZMRhQJwUDAJ4BtALoA+ABTi4cAooAjACskDAAuRAEYADpkdBgAOQhdOAAfOE9PaOywCLMASjgAXndI+NiopN188XyI-2DQ+EIMrJy8wpKyjAr4qqRCnB84fhhFKA0AQkIScmpaeiZPBpCMQoAydb9A1eaGAhgHNCQINjhDFRg1BlExZnFZeXg2Iyv1EZs9c0sZax07BwuDzeMS+FZNCJxHpQxLJJBpVrZaK5OAFYqlGG9DD9fKYYZIsAoKAoejWKAEPK1SFRLGwlJDUEfMYTTTaXQGV7XZY7Jo1Rm+AD820aGBBvnF4oJRJJSDJBGGEr5EvqPIwcAFQoYilIpFuzCAA" rel="nofollow noreferrer">Playground Link


来源: stackexchange

问:
How can I show the bit pattern for this type?
For example if I do:

```<code>  let sieve = new Uint32Array(1).fill(1);
</code>```

I would like to look at the bit pattern at index 0 which should be

0000000000000000000000000001

I want to print it out to the console so that I get something like this:

```<code>0 0
1 0
2 0
3 0
.
.
.
31 1
</code>```

Can I simply shift right to grab the 1 using >> or do I have to use a bitwise AND as & as well?

As a side, does it effect things if you switch to a signed representation such as here ...

Int32Array

答:
This is just a number to binary conversion.

let arr = new Uint32Array(1).fill(1);
for (let i = 0; i < 32; i++) {
  console.log(i, (arr[0] >>> i) & 1);
}```
</div>
</div>
</p>

<p>As it is, the fact that the number comes from <code>Uint32Array</code> makes no difference, but maybe this is because you simplified your question.</p>

<p>Also note that the "ones" bit, which you want in your question to be printed as 31, is in fact the first bit, because bits are counted starting from zero on the right (the least significant bit). If you really wanted to count it the non-standard way as in the question, then:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = new Uint32Array(1).fill(1);
for (let i = 0; i < 32; i++) {
  console.log(i, (arr[0] >>> (31 - i)) & 1);
}</code>```

Edit: for the values to be correct even when the MSB is set (the "sign bit"), unsigned bit shifting (>>>) has to be used.

ContentLicense: CC BY-SA 4.0

Body:
For example if I do:

  let sieve = new Uint32Array(1).fill(1);

I would like to look at the bit pattern at index 0 which should be

0000000000000000000000000001

I want to print it out to the console so that I get something like this:

0 0
1 0
2 0
3 0
.
.
.
31 1

Can I simply shift right to grab the 1 using >> or do I have to use a bitwise AND as & as well?

As a side, does it effect things if you switch to a signed representation such as here ...

Int32Array

Body:
This is just a number to binary conversion.

let arr = new Uint32Array(1).fill(1);
for (let i = 0; i < 32; i++) {
  console.log(i, (arr[0] >>> i) & 1);
}

As it is, the fact that the number comes from Uint32Array makes no difference, but maybe this is because you simplified your question.

Also note that the "ones" bit, which you want in your question to be printed as 31, is in fact the first bit, because bits are counted starting from zero on the right (the least significant bit). If you really wanted to count it the non-standard way as in the question, then:

let arr = new Uint32Array(1).fill(1);
for (let i = 0; i < 32; i++) {
  console.log(i, (arr[0] >>> (31 - i)) & 1);
}

Edit: for the values to be correct even when the MSB is set (the "sign bit"), unsigned bit shifting (>>>) has to be used.


问:
Splitting strings in Ruby
I want to split a string:

```<code>"00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"
</code>```

into two small strings like:

```<code>string1 => "00 85 00 04"
string2 => "79 E5 0B B5 82 AE C7 C9 96 37 93 AE"
</code>```

I tried using arrays but would like to try something new.

答:
Great place with a lot of examples in all sorts of languages like, python, perl, ruby and others pleac ruby string section.

The "great" thing is that all the different languages solve the same problems, making it easy to compare solutions between languages.

ContentLicense: CC BY-SA 3.0

Title: Splitting strings in Ruby

Body:
I want to split a string:

"00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

into two small strings like:

string1 => "00 85 00 04"
string2 => "79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

I tried using arrays but would like to try something new.


问:
How to format DayTime as Day of week Medium Time on Access
I was trying some SQL out on Access, but when I am trying to format the Date/Time data type so that I can input the day of the week and the medium time for my variables.

For example, I want to be able to input something like: Mon 1:00 PM.

I have tried formatting the data type as ddd h:nn AM/PM, but when I am trying to input the value, the system gives me an error stating that the input does not match my format.

I have also tried to auto-fill the input by clicking on the calendar next to the input box and selecting a date, but this way I cannot format the time.

Any help would be appreciated.

I did not add any pictures or code because I do not think that is needed to answer the question. If anything extra is needed, I am more than willing to provide them.

Thank You

答:
You can use a form bound to the table holding two unbound controls to display and modify the weekday and time - like this mock-up:

The two textboxes at top are bound to the Id and the date/time field of the table/query.

When opening the form, the combobox will be filled with the days of the week, and the first date of the week is calculated.

At the OnCurrent event, the combobox will be set to the weekday, and the textbox to the time. Modifying either of these will update the current record.

The combobox must be set to use a ValueList as RowSource and have the first column hidden (set ColumnWidths to: 0;)

The Time textbox can have the Format: Short time format

The code of the form will be:

Option Compare Database
Option Explicit

Private FirstDate       As Date
Private FirstWeekDay    As VbDayOfWeek

Private Sub Form_Current()

    Me!Weekday.Value = DatePart("w", Me!Date.Value)
    Me!Time.Value = TimeValue(Me!Date.Value)

End Sub

Private Sub Form_Load()

    Dim DayOfWeek       As VbDayOfWeek
    Dim LastWeekDay     As VbDayOfWeek
    Dim RowSource       As String

    FirstDate = DateAdd("d", Date, 1 - DatePart("w", Date, vbUseSystemDayOfWeek))
    FirstWeekDay = DatePart("w", FirstDate, vbUseSystemDayOfWeek)

    For DayOfWeek = 1 To 7
        RowSource = RowSource & """" & (FirstWeekDay - 1 + DayOfWeek) Mod 7 + 1 & """;""" & Format(DateAdd("d", DayOfWeek - 1, FirstDate), "dddd") & """;"
    Next
    Debug.Print RowSource
    Me!Weekday.RowSource = RowSource

End Sub

Private Sub Time_AfterUpdate()

    UpdateDate

End Sub

Private Sub Weekday_AfterUpdate()

    UpdateDate

End Sub

Private Sub UpdateDate()

    Me!Date.Value = DateAdd("d", (Me!Weekday.Value - 1 - FirstWeekDay + 7) Mod 7, FirstDate) + Nz(Me!Time.Value, #12:00:00 AM#)

End Sub
```


问:
How to diagnose a 401 error attempting to get an OAuth2 bearer token in c# .NET Core?
I have some limited skills in c++ and have recently moved in C# (asp.net) and azure Web services. As a PoC I'm trying to make REST calls into PayPal (which I'll need to be using professionally in 3 -6 months).

I've set up my personal PayPal account using the instructions here and I get a bearer token back using curl as described in the link. Awesome.

I'm now trying to do this from .NET Core C# and all I get is a 401 error. I've examined the request and it seems the same as the curl in terms of headers; the base64 encoded credentials I think I'm adding are the same as the ones in the verbose curl log (I examined the two base64 strings by eye) so it must be something I'm doing (or not doing) in the set up of the call. I'm looking for suggestions, pointers, or flat out laughter at the obvious mistake I've made.

I've set up what I believe to be a named client thus:

```<code> public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient("PayPal", c =>
            {
                c.BaseAddress = new Uri("https://api.sandbox.paypal.com/v1/");
                c.DefaultRequestHeaders.Add("Accept", "application/json");
                c.DefaultRequestHeaders.Add("Accept-Language", "en_US");
            });
</code>```

(with all the other stuff that comes free with VS under it omitted for brevity).

I attempt the call thus:

```<code>           string clientCredString = CLIENTID + ":" + SECRET;
            var clientCreds = System.Text.Encoding.UTF8.GetBytes(clientCredString);
            var client = _clientFactory.CreateClient("PayPal");
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(clientCreds));
            var messageBody = new Dictionary<string,string > ();
            messageBody.Add("grant_type", "client_credientials");
            var request = new HttpRequestMessage(HttpMethod.Get, "oauth2/token")
            {
                Content = new FormUrlEncodedContent(messageBody)
            };
            string token;
            var response = await client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                token = JsonConvert.DeserializeObject<string>(json);

            }
            else
            {
                throw new ApplicationException("Well that failed");
            }
</code>```

and get a 401 code for my trouble.

Suggestions for troubleshooting, better methods of doing this and laughter at my foolishness all welcomed.

答:
For the benefit of future readers:

It was, as suggested, an encoding problem. The line:

```<code>var clientCreds = System.Text.Encoding.UTF8.GetBytes(clientCredString);
</code>```

needed to be

```<code>var clientCreds = System.Text.Encoding.ASCII.GetBytes(clientCredString);
</code>```

It should also be noted that this particular operation requires a POST not a GET as I was using, but once I started sending properly encoded requests the errors started to make a lot more sense.

Body:
I have some limited skills in c++ and have recently moved in C# (asp.net) and azure Web services. As a PoC I'm trying to make REST calls into PayPal (which I'll need to be using professionally in 3 -6 months).

I've set up my personal PayPal account using the instructions here and I get a bearer token back using curl as described in the link. Awesome.

I'm now trying to do this from .NET Core C# and all I get is a 401 error. I've examined the request and it seems the same as the curl in terms of headers; the base64 encoded credentials I think I'm adding are the same as the ones in the verbose curl log (I examined the two base64 strings by eye) so it must be something I'm doing (or not doing) in the set up of the call. I'm looking for suggestions, pointers, or flat out laughter at the obvious mistake I've made.

I've set up what I believe to be a named client thus:

 public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpClient("PayPal", c =>
            {
                c.BaseAddress = new Uri("https://api.sandbox.paypal.com/v1/");
                c.DefaultRequestHeaders.Add("Accept", "application/json");
                c.DefaultRequestHeaders.Add("Accept-Language", "en_US");
            });

(with all the other stuff that comes free with VS under it omitted for brevity).

I attempt the call thus:

           string clientCredString = CLIENTID + ":" + SECRET;
            var clientCreds = System.Text.Encoding.UTF8.GetBytes(clientCredString);
            var client = _clientFactory.CreateClient("PayPal");
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(clientCreds));
            var messageBody = new Dictionary<string,string > ();
            messageBody.Add("grant_type", "client_credientials");
            var request = new HttpRequestMessage(HttpMethod.Get, "oauth2/token")
            {
                Content = new FormUrlEncodedContent(messageBody)
            };
            string token;
            var response = await client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                token = JsonConvert.DeserializeObject<string>(json);

            }
            else
            {
                throw new ApplicationException("Well that failed");
            }

and get a 401 code for my trouble.

Suggestions for troubleshooting, better methods of doing this and laughter at my foolishness all welcomed.

Body:
For the benefit of future readers:

It was, as suggested, an encoding problem. The line:

var clientCreds = System.Text.Encoding.UTF8.GetBytes(clientCredString);

needed to be

var clientCreds = System.Text.Encoding.ASCII.GetBytes(clientCredString);

It should also be noted that this particular operation requires a POST not a GET as I was using, but once I started sending properly encoded requests the errors started to make a lot more sense.


问:
In Swift, how do I explicitly specify a return value for map with anonymous closure arguments?
Say I call map like this, using the anonymous closure argument $0:

array.map {
  return $0.description
}
```

<p>How would I explicitly define that map returns a <code>string</code>? This doesn’t work:</p>

<pre class="lang-swift prettyprint-override"><code>array.map { -> String
  return $0.description
}
</code>```

Contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored

Does that mean if I want to specify a return value I have to name my arguments?

[EDIT: I know I do not need an explicit return type here; still would like how to specify one]

答:
The type will be inferred automatically if it's a string , otherwise you need a cast like this </p>

```<code>array.map { String($0.description) }
</code>```

Body:
Say I call map like this, using the anonymous closure argument $0:

array.map {
  return $0.description
}

How would I explicitly define that map returns a string? This doesn’t work:

array.map { -> String
  return $0.description
}

Contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored

Does that mean if I want to specify a return value I have to name my arguments?

[EDIT: I know I do not need an explicit return type here; still would like how to specify one]

Body:
The type will be inferred automatically if it's a string , otherwise you need a cast like this

array.map { String($0.description) }


问:
How to use optional command line arguments in a python function?
I want a more compact and scalable way to use command line args to feed a python function, here is what i have:

```<code>def getRelevant (number = 5, sortBy = "Change"):
    number, sortBy = int(number), sortBy
    relevant = ...
    return relevant

if __name__ == "__main__":
    if len(sys.argv) == 3:
        print(getRelevant(sys.argv[1], sys.argv[2]))
    elif len(sys.argv) == 2:
        print(getRelevant(sys.argv[1]))
    else:
        print(getRelevant())
</code>```

It works. But I'm not happy with this conditionals, is there a way to make it simpler?

答:
Argparse should do this. It is feature rich and flexible.
For your case, the below does the job:</p>

```<code>import argparse
parser = argparse.ArgumentParser(description='Description of your app here.')
parser.add_argument('-N', '--integers', default=5,  help='your help text here')
parser.add_argument('-S', '--sortby', default='Change', choices=['Change', 'SomeOtherOption'], help='some help text here ')

if __name__ == "__main__":
  args = parser.parse_args()
  print(args.integers) # prints 5 if nothing provided
  print(args.sortby)  # prints 'Change' if nothing provided
</code>```

Body:
I want a more compact and scalable way to use command line args to feed a python function, here is what i have:

def getRelevant (number = 5, sortBy = "Change"):
    number, sortBy = int(number), sortBy
    relevant = ...
    return relevant

if __name__ == "__main__":
    if len(sys.argv) == 3:
        print(getRelevant(sys.argv[1], sys.argv[2]))
    elif len(sys.argv) == 2:
        print(getRelevant(sys.argv[1]))
    else:
        print(getRelevant())

It works. But I'm not happy with this conditionals, is there a way to make it simpler?

Body:
Argparse should do this. It is feature rich and flexible.
For your case, the below does the job:

import argparse
parser = argparse.ArgumentParser(description='Description of your app here.')
parser.add_argument('-N', '--integers', default=5,  help='your help text here')
parser.add_argument('-S', '--sortby', default='Change', choices=['Change', 'SomeOtherOption'], help='some help text here ')

if __name__ == "__main__":
  args = parser.parse_args()
  print(args.integers) # prints 5 if nothing provided
  print(args.sortby)  # prints 'Change' if nothing provided


问:
Convert byte array (hex) to signed Int
I am trying to convert a (variable length) Hex String to Signed Integer (I need either positive or negative values).

[Int16] [int 32] and [int64] seem to work fine with 2,4+ byte length Hex Strings but I'm stuck with 3 byte strings [int24] (no such command in powershell).

Here's what I have now (snippet):

```<code>$start = $mftdatarnbh.Substring($DataRunStringsOffset+$LengthBytes*2+2,$StartBytes*2) -split "(..)"
[array]::reverse($start)
$start = -join $start

if($StartBytes*8 -le 16){$startd =[int16]"0x$($start)"}
elseif($StartBytes*8 -in (17..48)){$startd =[int32]"0x$($start)"}
else{$startd =[int64]"0x$($start)"}
</code>```

With the above code, a $start value of "D35A71" gives '13851249' instead of '-2925967'. I tried to figure out a way to implement two's complement but got lost. Any easy way to do this right?

Thank you in advance

Edit: Basically, I think I need to implement something like this:

int num = (sbyte)array[0] << 16 | array[1] << 8 | array[2];

as seen here.

Just tried this:

$start = "D35A71"

[sbyte]"0x$($start.Substring(0,2))" -shl 16 -bor "0x$($start.Substring(2,2))" -shl 8 -bor "0x$($start.Substring(4,2))"

but doesn't seem to get the correct result :-/

答:
To parse your hex.-number string as a negative number you can use [bigint] (System.Numerics.BigInteger):

```<code># Since the most significant hex digit has a 1 as its most significant bit
# (is >= 0x8), it is parsed as a NEGATIVE number.
# To force unconditional interpretation as a positive number, prepend '0'
# to the input hex string.
PS> [bigint]::Parse('D35A71', 'AllowHexSpecifier')
-2925967
</code>```

You can cast the resulting [bigint] instance back to an [int] (System.Int32).

Note:

The result is a negative number, because the most significant hex digit of the hex input string is >= 0x8, i.e. has its high bit set.

To force [bigint] to unconditionally interpret a hex. input string as a positive number, prepend 0.

The internal two's complement representation of a resulting negative number is performed at byte boundaries, so that a given hex number with an odd number of digits (i.e. if the first hex digit is a "half byte") has the missing half byte filled with 1 bits.

Therefore, a hex-number string whose most significant digit is >= 0x8  (parses as a negative number) results in the same number as prepending one or more Fs (0xF == 1111) to it; e.g., the following calls all result in -2048:

[bigint]::Parse('800', 'AllowHexSpecifier'),

[bigint]::Parse('F800', 'AllowHexSpecifier'),

[bigint]::Parse('FF800', 'AllowHexSpecifier'), ...

See the docs for details about the parsing logic.

Examples:

```<code># First digit (7) is < 8 (high bit NOT set) -> positive number
[bigint]::Parse('7FF', 'AllowHexSpecifier') # -> 2047

# First digit (8) is >= 8 (high bit IS SET) -> negative number
[bigint]::Parse('800', 'AllowHexSpecifier') # -> -2048

# Prepending additional 'F's to a number that parses as
# a negative number yields the *same* result
[bigint]::Parse('F800', 'AllowHexSpecifier') # -> -2048
[bigint]::Parse('FF800', 'AllowHexSpecifier') # -> -2048
# ...

# Starting the hex-number string with '0'
# *unconditionally* makes the result a *positive* number
[bigint]::Parse('0800', 'AllowHexSpecifier') # -> 2048
</code>```

Title: Convert byte array (hex) to signed Int

Body:
I am trying to convert a (variable length) Hex String to Signed Integer (I need either positive or negative values).

[Int16] [int 32] and [int64] seem to work fine with 2,4+ byte length Hex Strings but I'm stuck with 3 byte strings [int24] (no such command in powershell).

Here's what I have now (snippet):

$start = $mftdatarnbh.Substring($DataRunStringsOffset+$LengthBytes*2+2,$StartBytes*2) -split "(..)"
[array]::reverse($start)
$start = -join $start

if($StartBytes*8 -le 16){$startd =[int16]"0x$($start)"}
elseif($StartBytes*8 -in (17..48)){$startd =[int32]"0x$($start)"}
else{$startd =[int64]"0x$($start)"}

With the above code, a $start value of "D35A71" gives '13851249' instead of '-2925967'. I tried to figure out a way to implement two's complement but got lost. Any easy way to do this right?

Thank you in advance

Edit: Basically, I think I need to implement something like this:

int num = (sbyte)array[0] << 16 | array[1] << 8 | array[2];

as seen here.

Just tried this:

$start = "D35A71"

[sbyte]"0x$($start.Substring(0,2))" -shl 16 -bor "0x$($start.Substring(2,2))" -shl 8 -bor "0x$($start.Substring(4,2))"

but doesn't seem to get the correct result :-/

Body:
To parse your hex.-number string as a negative number you can use [bigint] (System.Numerics.BigInteger):

# Since the most significant hex digit has a 1 as its most significant bit
# (is >= 0x8), it is parsed as a NEGATIVE number.
# To force unconditional interpretation as a positive number, prepend '0'
# to the input hex string.
PS> [bigint]::Parse('D35A71', 'AllowHexSpecifier')
-2925967

You can cast the resulting [bigint] instance back to an [int] (System.Int32).

Note:

The result is a negative number, because the most significant hex digit of the hex input string is >= 0x8, i.e. has its high bit set.

To force [bigint] to unconditionally interpret a hex. input string as a positive number, prepend 0.

The internal two's complement representation of a resulting negative number is performed at byte boundaries, so that a given hex number with an odd number of digits (i.e. if the first hex digit is a "half byte") has the missing half byte filled with 1 bits.

Therefore, a hex-number string whose most significant digit is >= 0x8  (parses as a negative number) results in the same number as prepending one or more Fs (0xF == 1111) to it; e.g., the following calls all result in -2048:

[bigint]::Parse('800', 'AllowHexSpecifier'),

[bigint]::Parse('F800', 'AllowHexSpecifier'),

[bigint]::Parse('FF800', 'AllowHexSpecifier'), ...

See the docs for details about the parsing logic.

Examples:

# First digit (7) is < 8 (high bit NOT set) -> positive number
[bigint]::Parse('7FF', 'AllowHexSpecifier') # -> 2047

# First digit (8) is >= 8 (high bit IS SET) -> negative number
[bigint]::Parse('800', 'AllowHexSpecifier') # -> -2048

# Prepending additional 'F's to a number that parses as
# a negative number yields the *same* result
[bigint]::Parse('F800', 'AllowHexSpecifier') # -> -2048
[bigint]::Parse('FF800', 'AllowHexSpecifier') # -> -2048
# ...

# Starting the hex-number string with '0'
# *unconditionally* makes the result a *positive* number
[bigint]::Parse('0800', 'AllowHexSpecifier') # -> 2048


问:
Bokeh plot not showing with show(p) or p.show()
Trying to get a Bokeh chart to show with this code, I either get nothing if I use show(p) or

```<code>AttributeError: 'Figure' object has no attribute 'show'
</code>```

How can I fix this?

```<code>from math import pi
import pandas as pd
from bokeh.plotting import figure, show, output_notebook
from bokeh.models.annotations import Title
from nsepy import get_history
from datetime import date
from datetime import datetime
from pykalman import KalmanFilter

df  =  get_history(symbol="TCS", start = date(2018,1,1),end = date(2018,7,22))
print(df)
kf = KalmanFilter(transition_matrices = [1],
                  observation_matrices = [1],
                  initial_state_mean = df['Close'].values[0],
                  initial_state_covariance = 1,
                  observation_covariance=1,
                  transition_covariance=.01)
state_means,_ = kf.filter(df[['Close']].values)
state_means = state_means.flatten()

df["date"] = pd.to_datetime(df.index)

mids = (df.Open + df.Close)/2
spans = abs(df.Close-df.Open)

inc = df.Close > df.Open
dec = df.Open > df.Close
w = 12*60*60*1000 # half day in ms

output_notebook()

TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
#This causes an exception tol with p.show() no show in figure
p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=1000, toolbar_location="left",y_axis_label = "Price",
           x_axis_label = "Date")
p.segment(df.date, df.High, df.date, df.Low, color="black")
p.rect(df.date[inc], mids[inc], w, spans[inc], fill_color='green', line_color="green")
p.rect(df.date[dec], mids[dec], w, spans[dec], fill_color='red', line_color="red")
p.line(df.date,state_means,line_width=1,line_color = 'blue',legend="Kalman filter")
t = Title()
t.text = 'Kalman Filter Estimation'
p.title = t
p.xaxis.major_label_orientation = pi/4
p.grid.grid_line_alpha=0.3
p.show() #Throws attribute error show does not exist
#show(p) #Nothing happens on this
</code>```

答:
Your import is wrong:
change "from bokeh.plotting import output_notebook" to "from bokeh.io import output_notebook"</p>

Body:
Trying to get a Bokeh chart to show with this code, I either get nothing if I use show(p) or

AttributeError: 'Figure' object has no attribute 'show'

How can I fix this?

from math import pi
import pandas as pd
from bokeh.plotting import figure, show, output_notebook
from bokeh.models.annotations import Title
from nsepy import get_history
from datetime import date
from datetime import datetime
from pykalman import KalmanFilter

df  =  get_history(symbol="TCS", start = date(2018,1,1),end = date(2018,7,22))
print(df)
kf = KalmanFilter(transition_matrices = [1],
                  observation_matrices = [1],
                  initial_state_mean = df['Close'].values[0],
                  initial_state_covariance = 1,
                  observation_covariance=1,
                  transition_covariance=.01)
state_means,_ = kf.filter(df[['Close']].values)
state_means = state_means.flatten()

df["date"] = pd.to_datetime(df.index)

mids = (df.Open + df.Close)/2
spans = abs(df.Close-df.Open)

inc = df.Close > df.Open
dec = df.Open > df.Close
w = 12*60*60*1000 # half day in ms

output_notebook()

TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
#This causes an exception tol with p.show() no show in figure
p = figure(x_axis_type="datetime", tools=TOOLS, plot_width=1000, toolbar_location="left",y_axis_label = "Price",
           x_axis_label = "Date")
p.segment(df.date, df.High, df.date, df.Low, color="black")
p.rect(df.date[inc], mids[inc], w, spans[inc], fill_color='green', line_color="green")
p.rect(df.date[dec], mids[dec], w, spans[dec], fill_color='red', line_color="red")
p.line(df.date,state_means,line_width=1,line_color = 'blue',legend="Kalman filter")
t = Title()
t.text = 'Kalman Filter Estimation'
p.title = t
p.xaxis.major_label_orientation = pi/4
p.grid.grid_line_alpha=0.3
p.show() #Throws attribute error show does not exist
#show(p) #Nothing happens on this


问:
How to put content under fixed header or nav when opened in browser?
Hello I have problem when I make header using html and css. I have my header in fixed position, but the content is covered up my header. I want my content position under header when I run it. One more, I set header width 100% but it shift to the right so it doesn't cover up whole width on the screen.
[UPDATED]

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Flexbox</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>

</head>

<body>
    <header>
        <h1> Flexbox</h1>
    </header>
    <div class="whole-container">
    <div class="container-1">
        <div class="box-1">
            <h3>Box 1</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="box-2">
            <h3>Box 2</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="box-3">
            <h3>Box 3</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
    </div>

    <div class="container-2">
        <div class="container-2-box">
            <h3>Box 4</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-2-box">
            <h3>Box 5</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-2-box">
            <h3>Box 6</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
    </div>
    <div class="container-3">
        <div class="container-3-box">
            <h3>Box 7</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-3-box">
            <h3>Box 8</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-3-box">

            <h3>Box 9</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-3-box">
            <h3>Box 10</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-3-box">
            <h3>Box 11</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
        <div class="container-3-box">
            <h3>Box 12</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
    </div>
</div>
</body>
</html></code>```

答:
body {
  margin: 0;
}

body {
  margin: 0;
}

header {
  padding: 0.5rem;
  text-align: center;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: beige;
  position: fixed;
  width: 100%;
  /*not cover whole width*/
  margin: 0;
}

.whole-container {
  margin-top: 2.0rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <header>
    0000
  </header>

</body></code>```

Body:
Hello I have problem when I make header using html and css. I have my header in fixed position, but the content is covered up my header. I want my content position under header when I run it. One more, I set header width 100% but it shift to the right so it doesn't cover up whole width on the screen.
[UPDATED]

    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Flexbox</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>

 Flexbox

Box 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 3

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 4

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 5

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 6

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 7

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 8

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 9

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 10

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 11

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Box 12

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Body:
body {
  margin: 0;
}

body {
  margin: 0;
}

header {
  padding: 0.5rem;
  text-align: center;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: beige;
  position: fixed;
  width: 100%;
  /*not cover whole width*/
  margin: 0;
}

.whole-container {
  margin-top: 2.0rem;
}

<body>
  <header>
    0000
  </header>

</body>


问:
Is there a way to also select the row count from the same following query?
Would I be able to add a rowcount to this same query or would I need to create a separate one?</p>

```<code>SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, \
                ( \
                    SELECT DISTINCT p.CONSTRAINT_TYPE \
                    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \
                        INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME AND p.CONSTRAINT_TYPE=\'PRIMARY KEY\' \
                    WHERE kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME=c.COLUMN_NAME \
                ) AS CONSTRAINT_TYPE, NULL AS DATA_PRECISION, NULL AS DATA_SCALE \
                FROM INFORMATION_SCHEMA.COLUMNS c
</code>```

答:
```<code>SELECT DISTINCT c.TABLE_SCHEMA,
                c.TABLE_NAME,
                c.COLUMN_NAME,
                c.DATA_TYPE,
                ( SELECT DISTINCT p.CONSTRAINT_TYPE
                  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
                  INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p
                       ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME
                      AND p.CONSTRAINT_TYPE='PRIMARY KEY'
                  WHERE kcu.TABLE_NAME = c.TABLE_NAME
                    AND kcu.COLUMN_NAME=c.COLUMN_NAME ) AS CONSTRAINT_TYPE,
                NULL AS DATA_PRECISION,
                NULL AS DATA_SCALE,

                COUNT(*) OVER () total_records_count

FROM INFORMATION_SCHEMA.COLUMNS c
</code>```

Body:
Would I be able to add a rowcount to this same query or would I need to create a separate one?

SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, \
                ( \
                    SELECT DISTINCT p.CONSTRAINT_TYPE \
                    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \
                        INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME AND p.CONSTRAINT_TYPE=\'PRIMARY KEY\' \
                    WHERE kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME=c.COLUMN_NAME \
                ) AS CONSTRAINT_TYPE, NULL AS DATA_PRECISION, NULL AS DATA_SCALE \
                FROM INFORMATION_SCHEMA.COLUMNS c


问:
Please tell me the name of this jquery menu
could please someone can tell me the name of this type of jquery menu?

http://imageshack.us/photo/my-images/10/97395002.png/

答:
If it's the image rotator that you mean....

Typically jquery plug-ins are in separate files.

It appears to be jquery rotate http://code.google.com/p/jquery-rotate/

The easiest way to find that out yourself is to search the html source code for ".js" to see what JavaScript files are included.

Or the way I approached it was using Google Chrome's developer tools and see what resources (in this case js files) are downloaded.

I think the rotate buttons are probably custom made and not part of the rotate plugin.


问:
Scrape facebook profile image link python3 selenium
Question is hot to get facebook profile image link using python3, selenium

When inspecting profile photo element it gives:

```<code><image style="height: 168px; width: 168px;" x="0" y="0" height="100%" preserveAspectRatio="xMidYMid slice" width="100%" xlink:href="https://scontent.fskp2-1.fna.fbcdn.net/v/t1.0-1/p160x160/66377281_10219519738489211_3470999363818356736_n.jpg?_nc_cat=102&_nc_ohc=wwARRHDG764AX8QTDeA&_nc_ht=scontent.fskp2-1.fna&_nc_tp=6&oh=af9af2ffed61664c18229d3474cea541&oe=5ECC34A6"></image>
</code>```

However, $x('//image') gives 0 results. I'm already logged on facebook.
Any hint?

答:
Here it is how I solved this problem.  </p>

<p>Idea of whole screen screenshot by browser (selenium) and then cutting photo to exact coordinates.  </p>

```<code># selenium imports
from PIL import Image
...
driver.save_screenshot("shot.png")
x = 100
y = 80
w = 200
h = 220
width = x + w
height = y + h

im = Image.open('shot.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('image.png')
</code>```

Body:
Question is hot to get facebook profile image link using python3, selenium

When inspecting profile photo element it gives:

<image style="height: 168px; width: 168px;" x="0" y="0" height="100%" preserveAspectRatio="xMidYMid slice" width="100%" xlink:href="https://scontent.fskp2-1.fna.fbcdn.net/v/t1.0-1/p160x160/66377281_10219519738489211_3470999363818356736_n.jpg?_nc_cat=102&_nc_ohc=wwARRHDG764AX8QTDeA&_nc_ht=scontent.fskp2-1.fna&_nc_tp=6&oh=af9af2ffed61664c18229d3474cea541&oe=5ECC34A6"></image>

However, $x('//image') gives 0 results. I'm already logged on facebook.
Any hint?

Body:
Here it is how I solved this problem.

Idea of whole screen screenshot by browser (selenium) and then cutting photo to exact coordinates.

# selenium imports
from PIL import Image
...
driver.save_screenshot("shot.png")
x = 100
y = 80
w = 200
h = 220
width = x + w
height = y + h

im = Image.open('shot.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('image.png')


问:
Name conflicts with refs/heads/release when trying to create release/ branch
I'm trying to create release/0.1.0 branch in Azure DevOps repo but getting error Name conflicts with refs/heads/release:

It doesn't matter based on what branch I'm trying to create,

it also works fine when I'm trying to create feature/0.1.0 branch

Is it a king of a permissions issue (I'm not admin in this Azure DevOps project)?

答:
A git limitation due to how Git store references as files (and folder tree) in the .git/refs/heads folder.

When you trying to create the branch release/0.1.0, Git tries to create the folder release to create a file named 0.1.0 inside it.

Because there is already a file named release corresponding to the branch already created, Git can't create a folder with the same name (the file system doesn't allow it).

Due to this limitation linked to how git handles ref through the file system, git doesn't allow this case and verify this type of case when you try to create it (even if refs are packed).


问:
Nuget Packages are not found in nexus repo
I am using nexus OSS 3.15.2-01 and its new instance.
Issue we are facing is with nuget proxy repos, if i try it manually curl nuget org on nexus server it reaches the URL. but when i try to download it from VS or from cmd it says file not found.

I have created a seperate blob for nuget and new repo nuget_gallery, and provided the nuget org in proxy configuring it but its not working

From VS it says,

Severity Code Description Project File Line Suppression State
Error The feed ‘nexus prod [repo URL]’ lists package ‘Microsoft.AspNet.WebApi.Client.5.2.7’ but multiple attempts to download the nupkg have failed. The feed is either invalid or required packages were removed while the current operation was in progress. Verify the package exists on the feed and try again.
Unable to find package ‘Microsoft.AspNet.WebApi.Client.5.2.7’.

How ever the version is fetched in nexus if we browse the repo but even when we try to download it says file not found (0 bytes)

答:
Bit late to the party, but I had this same problem.  It seems to be down to lack of NuGet protocol 3 support in Nexus.

Workaround was to add protocolVersion="2" to my nuget.config like this;

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <!--To inherit the global NuGet package sources remove the <clear/> line below -->
    <clear />

    <add key="your-nexus-repo" value="http://your-nexus-repo/nexus/service/local/nuget/your-repo-name/" protocolVersion="2"/>
  </packageSources>
</configuration>
</code>```

I still had problems with dotnet core 3 packages, so also had to add back nuget.org (or remove <clear/> if nuget.org is in your global config)

```<code><add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
</code>```

Body:
Bit late to the party, but I had this same problem.  It seems to be down to lack of NuGet protocol 3 support in Nexus.

Workaround was to add protocolVersion="2" to my nuget.config like this;

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <!--To inherit the global NuGet package sources remove the <clear/> line below -->
    <clear />

    <add key="your-nexus-repo" value="http://your-nexus-repo/nexus/service/local/nuget/your-repo-name/" protocolVersion="2"/>
  </packageSources>
</configuration>

I still had problems with dotnet core 3 packages, so also had to add back nuget.org (or remove <clear/> if nuget.org is in your global config)

<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />


问:
`reload!` on terminal now retrieves NoMethodError
I have gem 'pry', '~> 0.10.3' on my bundle.
My application.rb goes as follows:

```<code>  class Application < Rails::Application

    config.load_defaults 5.2
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]

    config.generators.system_tests = nil

    if Rails.env.development?
      console do
        require 'pry'
        config.console = Pry
        ActiveRecord::Base.connection
      end
    end
  end
</code>```

My reload! method was working just fine and suddenly it stopped.
gitStatus shows no changes. what are the possible causes?

Thanks

答:
Somehow the line below seems to break !reload command while on pry.
!reload was working just fine on IRB.

Body:
I have gem 'pry', '~> 0.10.3' on my bundle.
My application.rb goes as follows:

  class Application < Rails::Application

    config.load_defaults 5.2
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]

    config.generators.system_tests = nil

    if Rails.env.development?
      console do
        require 'pry'
        config.console = Pry
        ActiveRecord::Base.connection
      end
    end
  end

My reload! method was working just fine and suddenly it stopped.
gitStatus shows no changes. what are the possible causes?

Thanks


问:
Javascript object.creation problem in particular example
Most likely a noob question, but after reading about component paradigm with javascript I was trying to build a simple component system for learning purposes.

After a while I come to something like the code bellow where different instances of the Base object should hold several components in its _Comp member -Using just one here for clarity-, to easily cicle them and ask if a component is present or not:

```<code>    // Base
    const Base = {
        _sName:"",
        _Comp:{},           // To store components
    };

    // Component
    var Component = {
        Constructor:function( MyBase )
        {
            this._MyBase = MyBase;
        }
    };

    // Factory
    function CreateBase( sName )
    {
        let MyBase = Object.create( Base );
        MyBase._sName = sName;

        MyBase._Comp.Component = Object.create( Component );
        MyBase._Comp.Component.Constructor( MyBase );
        return MyBase;
    };

    // Create test Bases

    var A = CreateBase( "A" );
    var B = CreateBase( "B" );

    console.log( A._Comp.Component._MyBase._sName );
    console.log( B._Comp.Component._MyBase._sName );
</code>```

As you can see I want the components to have a reference to their Base holder to be able to access the Base within the component functions.

But When running this code both of the final logs output "B".

I was expecting "A" and "B". But somehow the CreateBase("B") is overwriting also the component objects previously added to A. I'm trying to figure why this happens, and a valid/proper way to do something like this.

Any help would be appreciated.

答:
Base is being used as the prototype for both objects. Since neither have their own _Comp property, changing _Comp on either will change it on Base, not the inherited objects. To have the objects encapsulate their own properties, define them for each one:

```<code> // Base
    const Base = {
        _sName:"",
        _Comp:{},           // To store components
    };

    // Component
    var Component = {
        Constructor:function( MyBase )
        {
            this._MyBase = MyBase;
        }
    };

    // Factory
    function CreateBase( sName )
    {
        let MyBase = Object.create(Base);
        MyBase._sName = sName;
        MyBase._Comp = {}; //Define _Comp on MyBase so any changes go here.

        MyBase._Comp.Component = Object.create( Component );
        MyBase._Comp.Component.Constructor( MyBase );
        return MyBase;
    };

    // Create test Bases

    var A = CreateBase( "A" );
    var B = CreateBase( "B" );

    console.log( A._Comp.Component._MyBase._sName );
    console.log( B._Comp.Component._MyBase._sName );
</code>```

Body:
Most likely a noob question, but after reading about component paradigm with javascript I was trying to build a simple component system for learning purposes.

After a while I come to something like the code bellow where different instances of the Base object should hold several components in its _Comp member -Using just one here for clarity-, to easily cicle them and ask if a component is present or not:

    // Base
    const Base = {
        _sName:"",
        _Comp:{},           // To store components
    };

    // Component
    var Component = {
        Constructor:function( MyBase )
        {
            this._MyBase = MyBase;
        }
    };

    // Factory
    function CreateBase( sName )
    {
        let MyBase = Object.create( Base );
        MyBase._sName = sName;

        MyBase._Comp.Component = Object.create( Component );
        MyBase._Comp.Component.Constructor( MyBase );
        return MyBase;
    };

    // Create test Bases

    var A = CreateBase( "A" );
    var B = CreateBase( "B" );

    console.log( A._Comp.Component._MyBase._sName );
    console.log( B._Comp.Component._MyBase._sName );

As you can see I want the components to have a reference to their Base holder to be able to access the Base within the component functions.

But When running this code both of the final logs output "B".

I was expecting "A" and "B". But somehow the CreateBase("B") is overwriting also the component objects previously added to A. I'm trying to figure why this happens, and a valid/proper way to do something like this.

Any help would be appreciated.

Body:
Base is being used as the prototype for both objects. Since neither have their own _Comp property, changing _Comp on either will change it on Base, not the inherited objects. To have the objects encapsulate their own properties, define them for each one:

 // Base
    const Base = {
        _sName:"",
        _Comp:{},           // To store components
    };

    // Component
    var Component = {
        Constructor:function( MyBase )
        {
            this._MyBase = MyBase;
        }
    };

    // Factory
    function CreateBase( sName )
    {
        let MyBase = Object.create(Base);
        MyBase._sName = sName;
        MyBase._Comp = {}; //Define _Comp on MyBase so any changes go here.

        MyBase._Comp.Component = Object.create( Component );
        MyBase._Comp.Component.Constructor( MyBase );
        return MyBase;
    };

    // Create test Bases

    var A = CreateBase( "A" );
    var B = CreateBase( "B" );

    console.log( A._Comp.Component._MyBase._sName );
    console.log( B._Comp.Component._MyBase._sName );


问:
Inner Join with streaming dataframes
So I have this streaming dataframe (gps_messages) in pyspark-

and I want a resulting dataframe to have same (all) columns but one record / row for each device_unique_id which has highest value for timestamp, so basically something like -

```<code>                                                              (MAX)
+----------------+-----------+--------+---------+---------+----------+
|device_unique_id|signal_type|latitude|longitude|elevation| Timestamp|
+----------------+-----------+--------+---------+---------+----------+
|       TR1      |loc_update |-35.5484|149.61684|666.47164|   12345  |  <-- *NOTE - please check below
|       TR2      |loc_update |-35.5484|149.61684|666.47164|   87251  |
|       TR3      |loc_update |-35.5484|149.61684|666.47164|   32458  |
|       TR4      |loc_update |-35.5484|149.61684|666.47164|   98274  |
+----------------+-----------+--------+---------+---------+----------+

*Note = only 1 record for TR1 from previous dataframe which had max value of timeframe among all records having 'device_unique_id'=='TR1'
</code>```

so far, I have wrote this code,

```<code>gps_messages.createOrReplaceTempView('gps_table')
SQL_QUERY = 'SELECT device_unique_id, max(timestamp) as timestamp ' \
            'FROM gps_table ' \
            'GROUP BY device_unique_id'

# SQL_QUERY1 = 'SELECT * ' \
#              'FROM gps_table t2 ' \
#              'JOIN (SELECT device_unique_id AS unique_id, max(timestamp) AS time ' \
#              'FROM gps_table t1 ' \
#              'GROUP BY unique_id) t1 ' \
#              'ON t2.device_unique_id = t1.unique_id ' \
#              'AND t2.timestamp = t1.time'

filtered_gps_messages = spark.sql(SQL_QUERY)

filtered_gps_messages.createOrReplaceTempView('table_max_ts')
SQL_QUERY = 'SELECT a.device_unique_id, a.signal_type, a.longitude, a.latitude, a.timestamp ' \
            'FROM table_max_ts b, gps_table a ' \
            'WHERE b.timestamp==a.timestamp AND b.device_unique_id==a.device_unique_id'

latest_data_df = spark.sql(SQL_QUERY)

query = latest_data_df \
    .writeStream \
    .outputMode('append') \
    .format('console') \
    .start()

query.awaitTermination()

</code>```

And it throws out this error -

```<code>raise AnalysisException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.AnalysisException: 'Append output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets without watermark;;\nProject [device_unique_id#25, signal_type#26, latitude#27, longitude#28, elevation#29, timestamp#30, unique_id#43, time#44]\n+- Join Inner, ((device_unique_id#25 = unique_id#43) && (timestamp#30 = time#44))\n   :- SubqueryAlias `t2`\n   :  +- SubqueryAlias `gps_table`\n   :     +- Project [json#23.device_unique_id AS device_unique_id#25, json#23.signal_type AS signal_type#26, json#23.latitude AS latitude#27, json#23.longitude AS longitude#28, json#23.elevation AS elevation#29, json#23.timestamp AS timestamp#30]\n   :        +- Project [jsontostructs(StructField(device_unique_id,StringType,true), StructField(signal_type,StringType,true), StructField(latitude,StringType,true), StructField(longitude,StringType,true), StructField(elevation,StringType,true), StructField(timestamp,StringType,true), value#21, Some(Asia/Kolkata)) AS json#23]\n   :           +- Project [cast(value#8 as string) AS value#21]\n   :              +- StreamingRelationV2 org.apache.spark.sql.kafka010.KafkaSourceProvider@49a5cdc2, kafka, Map(subscribe -> gpx_points_input, kafka.bootstrap.servers -> 172.17.9.26:9092), [key#7, value#8, topic#9, partition#10, offset#11L, timestamp#12, timestampType#13], StreamingRelation DataSource(org.apache.spark.sql.SparkSession@611544,kafka,List(),None,List(),None,Map(subscribe -> gpx_points_input, kafka.bootstrap.servers -> 172.17.9.26:9092),None), kafka, [key#0, value#1, topic#2, partition#3, offset#4L, timestamp#5, timestampType#6]\n   +- SubqueryAlias `t1`\n      +- Aggregate [device_unique_id#25], [device_unique_id#25 AS unique_id#43, max(timestamp#30) AS time#44]\n         +- SubqueryAlias `t1`\n            +- SubqueryAlias `gps_table`\n               +- Project [json#23.device_unique_id AS device_unique_id#25, json#23.signal_type AS signal_type#26, json#23.latitude AS latitude#27, json#23.longitude AS longitude#28, json#23.elevation AS elevation#29, json#23.timestamp AS timestamp#30]\n                  +- Project [jsontostructs(StructField(device_unique_id,StringType,true), StructField(signal_type,StringType,true), StructField(latitude,StringType,true), StructField(longitude,StringType,true), StructField(elevation,StringType,true), StructField(timestamp,StringType,true), value#21, Some(Asia/Kolkata)) AS json#23]\n                     +- Project [cast(value#8 as string) AS value#21]\n                        +- StreamingRelationV2 org.apache.spark.sql.kafka010.KafkaSourceProvider@49a5cdc2, kafka, Map(subscribe -> gpx_points_input, kafka.bootstrap.servers -> 172.17.9.26:9092), [key#7, value#8, topic#9, partition#10, offset#11L, timestamp#12, timestampType#13], StreamingRelation DataSource(org.apache.spark.sql.SparkSession@611544,kafka,List(),None,List(),None,Map(subscribe -> gpx_points_input, kafka.bootstrap.servers -> 172.17.9.26:9092),None), kafka, [key#0, value#1, topic#2, partition#3, offset#4L, timestamp#5, timestampType#6]\n'

Process finished with exit code 1

</code>```

if I try with "complete" output mode, it says -

Analysis Exception: Inner Join between two streaming dataframes/datasets is not supported in Complete mode, only in append mode.

What am I doing wrong here? Is there any alternative way or a workaround?
Apologies for the type of question, I am new to spark.
Thanks.

答:
Have a look here => http://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#support-matrix-for-joins-in-streaming-queries Some joins aren't suported on streaming mode.

Maybe using a left outer join.

And writing in append mode should do the trick

```<code>SQL_QUERY = 'SELECT a.device_unique_id, a.signal_type, a.longitude, a.latitude, a.timestamp ' \
        'FROM table_max_ts b
         LEFT JOIN gps_table a ' \
        'ON b.timestamp==a.timestamp AND b.device_unique_id==a.device_unique_id'
</code>```

EDIT : watermarking is needed to ensure looking to the rights data in a time maner. For outer joins

```<code>    filtered_gps_messagesW = filtered_gps_messages.withWatermark("timestamp", "2 hours")
    gps_messagesW= gps_messages.withWatermark("timestamp", "3 hours")
</code>```

Then register you watermarked DS as tmpTables and you should be ok.Adjust time intervals to you need.

Title: Inner Join with streaming dataframes

Body:
So I have this streaming dataframe (gps_messages) in pyspark-

and I want a resulting dataframe to have same (all) columns but one record / row for each device_unique_id which has highest value for timestamp, so basically something like -

                                                              (MAX)
+----------------+-----------+--------+---------+---------+----------+
|device_unique_id|signal_type|latitude|longitude|elevation| Timestamp|
+----------------+-----------+--------+---------+---------+----------+
|       TR1      |loc_update |-35.5484|149.61684|666.47164|   12345  |  <-- *NOTE - please check below
|       TR2      |loc_update |-35.5484|149.61684|666.47164|   87251  |
|       TR3      |loc_update |-35.5484|149.61684|666.47164|   32458  |
|       TR4      |loc_update |-35.5484|149.61684|666.47164|   98274  |
+----------------+-----------+--------+---------+---------+----------+

*Note = only 1 record for TR1 from previous dataframe which had max value of timeframe among all records having 'device_unique_id'=='TR1'

so far, I have wrote this code,

gps_messages.createOrReplaceTempView('gps_table')
SQL_QUERY = 'SELECT device_unique_id, max(timestamp) as timestamp ' \
            'FROM gps_table ' \
            'GROUP BY device_unique_id'

# SQL_QUERY1 = 'SELECT * ' \
#              'FROM gps_table t2 ' \
#              'JOIN (SELECT device_unique_id AS unique_id, max(timestamp) AS time ' \
#              'FROM gps_table t1 ' \
#              'GROUP BY unique_id) t1 ' \
#              'ON t2.device_unique_id = t1.unique_id ' \
#              'AND t2.timestamp = t1.time'

filtered_gps_messages = spark.sql(SQL_QUERY)

filtered_gps_messages.createOrReplaceTempView('table_max_ts')
SQL_QUERY = 'SELECT a.device_unique_id, a.signal_type, a.longitude, a.latitude, a.timestamp ' \
            'FROM table_max_ts b, gps_table a ' \
            'WHERE b.timestamp==a.timestamp AND b.device_unique_id==a.device_unique_id'

latest_data_df = spark.sql(SQL_QUERY)

query = latest_data_df \
    .writeStream \
    .outputMode('append') \
    .format('console') \
    .start()

query.awaitTermination()

And it throws out this error -

raise AnalysisException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.AnalysisException: 'Append output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets without watermark;;\nProject [device_unique_id#25, signal_type#26, latitude#27, longitude#28, elevation#29, timestamp#30, unique_id#43, time#44]\n+- Join Inner, ((device_unique_id#25 = unique_id#43) && (timestamp#30 = time#44))\n   :- SubqueryAlias `t2`\n   :  +- SubqueryAlias `gps_table`\n   :     +- Project [json#23.device_unique_id AS device_unique_id#25, json#23.signal_type AS signal_type#26, json#23.latitude AS latitude#27, json#23.longitude AS longitude#28, json#23.elevation AS elevation#29, json#23.timestamp AS timestamp#30]\n   :        +- Project [jsontostructs(StructField(device_unique_id,StringType,true), StructField(signal_type,StringType,true), StructField(latitude,StringType,true), StructField(longitude,StringType,true), StructField(elevation,StringType,true), StructField(timestamp,StringType,true), value#21, Some(Asia/Kolkata)) AS json#23]\n   :           +- Project [cast(value#8 as string) AS value#21]\n   :              +- StreamingRelationV2 org.apache.spark.sql.kafka010.KafkaSourceProvider@49a5cdc2, kafka, Map(subscribe -> gpx_points_input, kafka.bootstrap.servers -> 172.17.9.26:9092), [key#7, value#8, topic#9, partition#10, offset#11L, timestamp#12, timestampType#13], StreamingRelation DataSource(org.apache.spark.sql.SparkSession@611544,kafka,List(),None,List(),None,Map(subscribe -> gpx_points_input, kafka.bootstrap.servers -> 172.17.9.26:9092),None), kafka, [key#0, value#1, topic#2, partition#3, offset#4L, timestamp#5, timestampType#6]\n   +- SubqueryAlias `t1`\n      +- Aggregate [device_unique_id#25], [device_unique_id#25 AS unique_id#43, max(timestamp#30) AS time#44]\n         +- SubqueryAlias `t1`\n            +- SubqueryAlias `gps_table`\n               +- Project [json#23.device_unique_id AS device_unique_id#25, json#23.signal_type AS signal_type#26, json#23.latitude AS latitude#27, json#23.longitude AS longitude#28, json#23.elevation AS elevation#29, json#23.timestamp AS timestamp#30]\n                  +- Project [jsontostructs(StructField(device_unique_id,StringType,true), StructField(signal_type,StringType,true), StructField(latitude,StringType,true), StructField(longitude,StringType,true), StructField(elevation,StringType,true), StructField(timestamp,StringType,true), value#21, Some(Asia/Kolkata)) AS json#23]\n                     +- Project [cast(value#8 as string) AS value#21]\n                        +- StreamingRelationV2 org.apache.spark.sql.kafka010.KafkaSourceProvider@49a5cdc2, kafka, Map(subscribe -> gpx_points_input, kafka.bootstrap.servers -> 172.17.9.26:9092), [key#7, value#8, topic#9, partition#10, offset#11L, timestamp#12, timestampType#13], StreamingRelation DataSource(org.apache.spark.sql.SparkSession@611544,kafka,List(),None,List(),None,Map(subscribe -> gpx_points_input, kafka.bootstrap.servers -> 172.17.9.26:9092),None), kafka, [key#0, value#1, topic#2, partition#3, offset#4L, timestamp#5, timestampType#6]\n'

Process finished with exit code 1

if I try with "complete" output mode, it says -

Analysis Exception: Inner Join between two streaming dataframes/datasets is not supported in Complete mode, only in append mode.

What am I doing wrong here? Is there any alternative way or a workaround?
Apologies for the type of question, I am new to spark.
Thanks.

Body:
Have a look here => http://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#support-matrix-for-joins-in-streaming-queries Some joins aren't suported on streaming mode.

Maybe using a left outer join.

And writing in append mode should do the trick

SQL_QUERY = 'SELECT a.device_unique_id, a.signal_type, a.longitude, a.latitude, a.timestamp ' \
        'FROM table_max_ts b
         LEFT JOIN gps_table a ' \
        'ON b.timestamp==a.timestamp AND b.device_unique_id==a.device_unique_id'

EDIT : watermarking is needed to ensure looking to the rights data in a time maner. For outer joins

    filtered_gps_messagesW = filtered_gps_messages.withWatermark("timestamp", "2 hours")
    gps_messagesW= gps_messages.withWatermark("timestamp", "3 hours")

Then register you watermarked DS as tmpTables and you should be ok.Adjust time intervals to you need.


问:
testing select element in react with Jest
I am trying to test functionality of a select element in a React component.

Note: This is not a duplicate of this question because I am not using enzyme, but rather trying to do things simply using act() from React's Test Utilities and running tests with Jest.

Given a component with a select element like this:

class TestSelect extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            choice: "apples",
        };
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(event) {
        this.setState({choice: event.target.value});
    }
    render() {
        return (

                <select value={this.state.choice} onChange={this.handleChange}>
                    <option value="apples">apples</option>
                    <option value="oranges">oranges</option>
                </select>

You like {this.state.choice}

        );
    }
}
```

<p>I would like to be able to test it like this:</p>

<pre class="lang-js prettyprint-override"><code>import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";

test("Should change preference", () => {
    act(() => {
        render(<TestSelect/>, container);
    });
    let message = container.querySelector("h4");
    expect(message.innerHTML).toContain("apples");
    const selectElement = container.querySelector("select");
    act(() => {
        selectElement.dispatchEvent(new Event("change"), {
            target: { value: "oranges"},
            bubbles: true,
        });
    });
    message = container.querySelector("h4");
    // Test fails here: Value does not change
    expect(message.innerHTML).toContain("oranges");
});
</code>```

After a lot of fiddling and trying different options I am not able to simulate an event that ends up changing the selected value in the select element.

答:
I found a way to do this using Simulate from react-dom test-utils.</p>

```<code>import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act, Simulate } from "react-dom/test-utils";

test("Should change preference", () => {
    act(() => {
        render(<TestSelect/>, container);
    });
    let message = container.querySelector("h4");
    expect(message.innerHTML).toContain("apples");
    const selectElement = container.querySelector("select");
    act(() => {
        Simulate.change(selectElement, { target: { value: "oranges" }});
    });
    message = container.querySelector("h4");
    expect(message.innerHTML).toContain("oranges");
});
</code>```

Body:
I am trying to test functionality of a select element in a React component.

Note: This is not a duplicate of this question because I am not using enzyme, but rather trying to do things simply using act() from React's Test Utilities and running tests with Jest.

Given a component with a select element like this:

class TestSelect extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            choice: "apples",
        };
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(event) {
        this.setState({choice: event.target.value});
    }
    render() {
        return (

                <select value={this.state.choice} onChange={this.handleChange}>
                    <option value="apples">apples</option>
                    <option value="oranges">oranges</option>
                </select>

You like {this.state.choice}

        );
    }
}

I would like to be able to test it like this:

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";

test("Should change preference", () => {
    act(() => {
        render(<TestSelect/>, container);
    });
    let message = container.querySelector("h4");
    expect(message.innerHTML).toContain("apples");
    const selectElement = container.querySelector("select");
    act(() => {
        selectElement.dispatchEvent(new Event("change"), {
            target: { value: "oranges"},
            bubbles: true,
        });
    });
    message = container.querySelector("h4");
    // Test fails here: Value does not change
    expect(message.innerHTML).toContain("oranges");
});

After a lot of fiddling and trying different options I am not able to simulate an event that ends up changing the selected value in the select element.

Body:
I found a way to do this using Simulate from react-dom test-utils.

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act, Simulate } from "react-dom/test-utils";

test("Should change preference", () => {
    act(() => {
        render(<TestSelect/>, container);
    });
    let message = container.querySelector("h4");
    expect(message.innerHTML).toContain("apples");
    const selectElement = container.querySelector("select");
    act(() => {
        Simulate.change(selectElement, { target: { value: "oranges" }});
    });
    message = container.querySelector("h4");
    expect(message.innerHTML).toContain("oranges");
});


问:
Finding values of a column based on two columns values
Consider a dataframe </p>

```<code>variable1   variable2  variable3
   a            1         w1
   b            2         w2
   c            1         w1
   e            2         w2
   f            2         w2
   g            3         w3
</code>```

<p>As a dummy dataframe here you can see variable2 and variable3 as a single group, it has two values of variable1 i.e 'a' and 'c' for same (1,w1).  In a bigger dataframe I want to know the combinations of variable2 and variable3 and associated variable1 values for that . Thank you for your patience. The Expected dataframe for me would be </p>

```<code>variable2+variable3         variable1_Values
    (1,w1)                         a
                                   c
    (2,w2)                         b
                                   e
                                   f
    (3,w3)                         g
</code>```

答:
Try:</p>

```<code>df.groupby(['variable2','variable3'])['variable1'].agg(list)

variable2  variable3
1          w1           [a, c]
2          w2              [b]
</code>```

Body:
Consider a dataframe

variable1   variable2  variable3
   a            1         w1
   b            2         w2
   c            1         w1
   e            2         w2
   f            2         w2
   g            3         w3

As a dummy dataframe here you can see variable2 and variable3 as a single group, it has two values of variable1 i.e 'a' and 'c' for same (1,w1).  In a bigger dataframe I want to know the combinations of variable2 and variable3 and associated variable1 values for that . Thank you for your patience. The Expected dataframe for me would be

variable2+variable3         variable1_Values
    (1,w1)                         a
                                   c
    (2,w2)                         b
                                   e
                                   f
    (3,w3)                         g

Body:
Try:

df.groupby(['variable2','variable3'])['variable1'].agg(list)

variable2  variable3
1          w1           [a, c]
2          w2              [b]


问:
How to automatically put environment variable to all lambdas created in my CDK project
We implement almost all our lambda's in Chalice and then consume them in CDK project as described here.

I need to add same environment variable to all lambda's in stack (different per developer). I would like to do it automatically, and not count on every developer adding variable to Chalice stage configuration. I can't use AWS Systems Manager Parameter Store, because it's the same for all dev stacks - we share the same AWS account. I can parse final cloudformation template before deploy and add variables to all lambda's, but may be there is a more elegant way ?

Thank you.

答:
You should have a look at Aspects.

Aspects are the way to apply an operation to all constructs in a given scope. The functionality could modify the constructs, such as by adding tags, or it could be verifying something about the state of the constructs, such as ensuring that all buckets are encrypted.

@jsii.implements(core.IAspect)
class EnvVarSetter:

  def visit(self, node):
    # See that we're dealing with a Function
    if isinstance(node, lambda.Function):
      # set env var here
      node.add_environment('KEY', 'VALUE')

# Apply to the stack
stack.node.apply_aspect(EnvVarSetter())
```


问:
What exactly is represented by the template parameter passed to std::function template?
std::function itself offers a great utility- it provides type erasure in order to generically store / provide access to callables. Its flexibility is great:

```<code>#include <functional>
#include <iostream>

void printer() {
    std::cout << "I print!";
}

int adder(int a, int b) {
    return a + b;
}

int main() {
    std::function<void()> fun1 = printer;       // fun1() calls printer()
    std::function<int(int, int)> fun2 = adder;  // fun2(1, 2) calls adder(1, 2)

    std::function<void()> fun3 = [](){};        // fun3() will do nothing - same for the lambda
    std::function<int(int, int)> fun4 =
            [](int a, int b) { return a + b; }; // fun4(1, 2) will yield the sum
}
</code>```

And, to be honest, everything makes sense. std::function<void()> says that it's a function, which, when called, returns void and takes no (()) arguments. Ditto for std::function<int(int, int)> - when called, it returns an int and requires two ints as its arguments.

While intuitive, I believe I lack fundamental understanding of that exactly is the explicit template parameter. What exactly is void() or int(int, int)? They cannot be function pointers, becasue when I do:

```<code>int main() {
    using type = void();

    type x = printer;
}
</code>```

I get the following warning and an error:

```<code>main.cpp:15:10: warning: declaration of 'void x()' has 'extern' and is initialized
 type x = printer;
      ^
main.cpp:15:14: error: function 'void x()' is initialized like a variable
 type x = printer;
          ^~~~~~~
</code>```

Well, obviously it looks like a variable - I wanted it to be a variable. However, if I wanted a function pointer, I would've had to do:

```<code>using type = void(*)();
</code>```

instead of:

```<code>using type = void();
</code>```

What exactly is the type with omitted *? What exactly is represented by the intuitive explicit template parameters when used with, for example, the std::function?

答:
What exactly is void() or int(int, int)?

They are function types. Eg. if you declare void foo(), type of foo is void():

```<code>#include <type_traits>

int main() {
  static_assert(std::is_function_v<int(int, int)> &&
                std::is_function_v<void()> &&
                std::is_same_v<decltype(main), int()>);
}
</code>```

LIVE

Body:
std::function itself offers a great utility- it provides type erasure in order to generically store / provide access to callables. Its flexibility is great:

#include <functional>
#include <iostream>

void printer() {
    std::cout << "I print!";
}

int adder(int a, int b) {
    return a + b;
}

int main() {
    std::function<void()> fun1 = printer;       // fun1() calls printer()
    std::function<int(int, int)> fun2 = adder;  // fun2(1, 2) calls adder(1, 2)

    std::function<void()> fun3 = [](){};        // fun3() will do nothing - same for the lambda
    std::function<int(int, int)> fun4 =
            [](int a, int b) { return a + b; }; // fun4(1, 2) will yield the sum
}

And, to be honest, everything makes sense. std::function<void()> says that it's a function, which, when called, returns void and takes no (()) arguments. Ditto for std::function<int(int, int)> - when called, it returns an int and requires two ints as its arguments.

While intuitive, I believe I lack fundamental understanding of that exactly is the explicit template parameter. What exactly is void() or int(int, int)? They cannot be function pointers, becasue when I do:

int main() {
    using type = void();

    type x = printer;
}

I get the following warning and an error:

main.cpp:15:10: warning: declaration of 'void x()' has 'extern' and is initialized
 type x = printer;
      ^
main.cpp:15:14: error: function 'void x()' is initialized like a variable
 type x = printer;
          ^~~~~~~

Well, obviously it looks like a variable - I wanted it to be a variable. However, if I wanted a function pointer, I would've had to do:

using type = void(*)();

instead of:

using type = void();

What exactly is the type with omitted *? What exactly is represented by the intuitive explicit template parameters when used with, for example, the std::function?

Body:
What exactly is void() or int(int, int)?

They are function types. Eg. if you declare void foo(), type of foo is void():

#include <type_traits>

int main() {
  static_assert(std::is_function_v<int(int, int)> &&
                std::is_function_v<void()> &&
                std::is_same_v<decltype(main), int()>);
}

LIVE


问:
Display Input Value Vertically CSS
I have an Input type=number in React, styled with styled-components. I need some of the inputs display it's value vertically

```<code>export const UnitValue = styled.input`
  ::-webkit-inner-spin-button,
  ::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
  font-weight: bold;
  text-align: center;
  margin-right: ${props => {props.marginRight};
  margin-top: ${props => props.marginTop};
  margin-left: ${props => {props.marginLeft};
  width: ${props => {props.width};
  height: ${props => {props.height}
  border: ${props => {props.border};
  background-color: ${props => props.color};
`;
</code>```

Some inputs displays vertically but it's value is horizontal. I need that value to be displayed vertically, is there a way to do that? Here's the input:

I need that the input value displays in the same direction of the text that is near to it without using transform css attribute. Is there a way?

答:
add this to your styles</p>

```<code>  transform: rotate(90deg);
  transform-origin: center;
</code>```

Title: Display Input Value Vertically CSS

Body:
I have an Input type=number in React, styled with styled-components. I need some of the inputs display it's value vertically

export const UnitValue = styled.input`
  ::-webkit-inner-spin-button,
  ::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
  font-weight: bold;
  text-align: center;
  margin-right: ${props => {props.marginRight};
  margin-top: ${props => props.marginTop};
  margin-left: ${props => {props.marginLeft};
  width: ${props => {props.width};
  height: ${props => {props.height}
  border: ${props => {props.border};
  background-color: ${props => props.color};
`;

Some inputs displays vertically but it's value is horizontal. I need that value to be displayed vertically, is there a way to do that? Here's the input:

I need that the input value displays in the same direction of the text that is near to it without using transform css attribute. Is there a way?

Body:
add this to your styles

  transform: rotate(90deg);
  transform-origin: center;


问:
redirect user on previous page after successfull task
What should be good way to redirect user after successful action like edit or delete any item, in delete condition we could use $_SERVER['HTTP_REFERER'] but in case of edit, we show first of all edit form and then user clicks update, so if we use same approach user would be redirected to edit page not main page. I hope you got idea about my confusion. thanks.

答:
If you're OK with $_SERVER['HTTP_REFERER'] you can simply store that value in Session Information, and redirect to it when editing is finished.

For example, before showing the edit form you can do:

```<code>$_SESSION['originalReferer'] = $_SERVER['HTTP_REFERER'];
</code>```

And after clicking "Update" (if successful):

```<code>header("Location: ".$_SESSION['originalReferer']);
</code>```

But again, use this only if you trust  $_SERVER['HTTP_REFERER'] !

Body:
If you're OK with $_SERVER['HTTP_REFERER'] you can simply store that value in Session Information, and redirect to it when editing is finished.

For example, before showing the edit form you can do:

$_SESSION['originalReferer'] = $_SERVER['HTTP_REFERER'];

And after clicking "Update" (if successful):

header("Location: ".$_SESSION['originalReferer']);

But again, use this only if you trust  $_SERVER['HTTP_REFERER'] !


问:
Coding Newb:Python: Issues returning value from recursive function
This code is giving me a headache.

```<code>time = epoch_years ## this value is 50.13452189.....

def timex(t):  ## isolaing and return decimal value of t
    print("t;",t)
    if t < 1:
        return t
    else:
        timex(t-1)

result = timex(time)
</code>```

I can't seem to get the value t returned after isolating the fractional value.  There's probably an easier way to achieve what i want, though I'm hellbent on understanding why this code isn't working.   --Result-- keeps coming back as --None--

答:
As @rdas said in his comment:

Change:

def timex(t):  ## isolaing and return decimal value of t
    print("t;",t)
    if t < 1:
        return t
    else:
        timex(t-1)
```

<p>to:</p>

<pre class="lang-py prettyprint-override"><code>def timex(t):  ## isolaing and return decimal value of t
    print("t;",t)
    if t < 1:
        return t
    else:
        return timex(t-1)
</code>```

The return before timex(t-1) is the only change. I believe it works because the return will terminate the loop.

Body:
This code is giving me a headache.

time = epoch_years ## this value is 50.13452189.....

def timex(t):  ## isolaing and return decimal value of t
    print("t;",t)
    if t < 1:
        return t
    else:
        timex(t-1)

result = timex(time)

I can't seem to get the value t returned after isolating the fractional value.  There's probably an easier way to achieve what i want, though I'm hellbent on understanding why this code isn't working.   --Result-- keeps coming back as --None--

Body:
As @rdas said in his comment:

Change:

def timex(t):  ## isolaing and return decimal value of t
    print("t;",t)
    if t < 1:
        return t
    else:
        timex(t-1)

to:

def timex(t):  ## isolaing and return decimal value of t
    print("t;",t)
    if t < 1:
        return t
    else:
        return timex(t-1)

The return before timex(t-1) is the only change. I believe it works because the return will terminate the loop.


问:
chrome.tabs.executeScript only seems to execute in the active tab
I have the following code in a background.js.

```<code>chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {

        chrome.tabs.executeScript(tabId, {
            file: 'inject.js'
        });

  } // if (changeInfo.status == 'complete') {
});
</code>```

But when I change tabs the inject.js only runs in the active tab even if an inactive tab gets updated.  In the inject.js I have an automated process running for a particular website and it's clicking through some pages looking for specific text.  I want it to continue running on that one tab even if I open a new tab. But as soon as I change tabs the injection happens only on the active tab.  I thought tab.tabId or tabId would be for the tab that was updated but it seems like it's always the active tab.

Is there a way to figure out what tab updated so I can pass the correct tabId to executeScript?

Here is what my manifest looks like:

```<code>{
  "name": "Automated test",
  "version": "0.0.1",
  "manifest_version": 2,
  "background": {
    "scripts": [
      "background.js"
    ],
    "persistent": true
  },
  "browser_action": {
    "default_title": "Test"
  },
  "permissions": [
    "https://*/*",
    "http://*/*",
    "tabs",
    "webNavigation"
  ]
}
</code>```

答:
So, @wOxxOm led me to what I needed. I did need a content-script and the reason why I think I wasn't seeing the results I was expecting is that I was failing to remove and re-add my extension.  Sometimes it seems like it respects the changes made but maybe when you make changes to the manifest you need to remove and re-add the extension.

Once I did that it is correctly working on the inactive tab.

Body:
I have the following code in a background.js.

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {

        chrome.tabs.executeScript(tabId, {
            file: 'inject.js'
        });

  } // if (changeInfo.status == 'complete') {
});

But when I change tabs the inject.js only runs in the active tab even if an inactive tab gets updated.  In the inject.js I have an automated process running for a particular website and it's clicking through some pages looking for specific text.  I want it to continue running on that one tab even if I open a new tab. But as soon as I change tabs the injection happens only on the active tab.  I thought tab.tabId or tabId would be for the tab that was updated but it seems like it's always the active tab.

Is there a way to figure out what tab updated so I can pass the correct tabId to executeScript?

Here is what my manifest looks like:

{
  "name": "Automated test",
  "version": "0.0.1",
  "manifest_version": 2,
  "background": {
    "scripts": [
      "background.js"
    ],
    "persistent": true
  },
  "browser_action": {
    "default_title": "Test"
  },
  "permissions": [
    "https://*/*",
    "http://*/*",
    "tabs",
    "webNavigation"
  ]
}


问:
did i use lgbm correctly for categorical features?
Suppose my data has only 1 column of categorical feature (already converted it to astype(int)),

```<code>x_to_use = x_to_use.astype(int)
</code>```

I am using this in a sklearn Pipeline:

```<code>                                LGBMRegressor(**{
                                            "n_estimators":100,
                                    "categorical_feature":(0,),
                                            "max_depth":1,
                                        }
</code>```

I got this warning.

```<code>c:\programdata\miniconda3\lib\site-packages\lightgbm\basic.py:842: UserWarning: categorical_feature keyword has been found in `params` an
Please use categorical_feature argument of the Dataset constructor to pass this parameter.
</code>```

I want everything to be in standard sklearn machine learning pipeline format, so my input is always np.array. Is my pipeline construction correct or is                                  "categorical_feature":(0,), simply ignored and that column is not treated as categorical.

Edit:

OK... I constructed a simple test, "categorical_feature" is actually used correctly.

答:
The documentation says:

-categorical_feature (list of strings or int, or 'auto', optional (default='auto'))

Have you tried passing a list like this?

```<code>LGBMRegressor(**{"n_estimators":100,
                 "categorical_feature":[0],
                 "max_depth":1}
</code>```

Body:
Suppose my data has only 1 column of categorical feature (already converted it to astype(int)),

x_to_use = x_to_use.astype(int)

I am using this in a sklearn Pipeline:

                                LGBMRegressor(**{
                                            "n_estimators":100,
                                    "categorical_feature":(0,),
                                            "max_depth":1,
                                        }

I got this warning.

c:\programdata\miniconda3\lib\site-packages\lightgbm\basic.py:842: UserWarning: categorical_feature keyword has been found in `params` an
Please use categorical_feature argument of the Dataset constructor to pass this parameter.

I want everything to be in standard sklearn machine learning pipeline format, so my input is always np.array. Is my pipeline construction correct or is                                  "categorical_feature":(0,), simply ignored and that column is not treated as categorical.

Edit:

OK... I constructed a simple test, "categorical_feature" is actually used correctly.

Body:
The documentation says:

-categorical_feature (list of strings or int, or 'auto', optional (default='auto'))

Have you tried passing a list like this?

LGBMRegressor(**{"n_estimators":100,
                 "categorical_feature":[0],
                 "max_depth":1}


问:
Two different objects implement the same Interface in the same way - how to stay DRY
I have the interface:

IColored that guarantees the function getColor.

Now I have two objects:

 1. Ferrari

 2. RedApple

that both implement this interface/function in the same way.

(But cannot inherit from the same object - no multi-inheritance allowed).

How would you avoid code-duplication?

答:
DRY is a principle.  As a principle, its purpose is to guide you toward what is believed to be the best practices. But, as it is "just" a principle and not some unbreakable law, one needs to know when to apply it, and when it's preferable not.

My take on the DRY principle is that, it's not because 2 functions are implemented exactly the same that they don't both deserve to exists, for the exact same reasons why you can have multiple constants with the same values (ERROR_SUCCESS = NO_ERROR = SW_HIDE = etc...). Semantics and contexts matter.

If you changed 1 implementation tomorrow, would you need to also change the other? If the answer is no, I don't believe you are really breaking the DRY principle, or at the very least I don't believe you should apply the DRY principle in this case.

But granted, all this is slightly subjective.


问:
Laravel, relationship problems
this is my first Laravel project and I have to do a LMS(learning management system).
I have a course table and an user table.

Here is my controller code:

```<code>public function afficheFormation($id)
    {
        $formation = DB::table('formation')->select('formation.*')->where('id', $id)->first();
        $cours = DB::table('Course')->join('Course_formation', 'course_id', '=', 'Course.id')

            ->select('Course.*')->where('formation_id', $id)->get();

        return view('formation', compact('formation', 'cours'));
    }
</code>```

here is my view code:

```<code><tr>
 <td class="align-middle">{{ $cours->name }}</td>
 <td class="align-middle">{{ $cours->level}}</td>
 <td class="align-middle">{{ $cours->user() }}</td>
</tr>
@endforeach
@endif
</code>```

Course have a foreign key professor_id and I want to display the name of the user which created the course but have some errors

This is my Course model:

```<code>class Course extends Model
{

    protected $table = 'cours';
    public $timestamps = true;

    protected $fillable = [
        'name', 'lien', 'type', 'level', 'theme_id', 'prof_id'
    ];

    public function user()
    {
        return $this->hasOne('App\Models\User');
    }
}
</code>```

and this is my user model:

```<code>class User extends Authenticatable
{
    use Notifiable;

    protected $table = 'users';
    public $timestamps = true;

    protected $fillable = [
        'pseudo', 'email', 'password', 'name', 'prenom', 'image'
    ];

    public function roles()
    {
          //return $this->belongsToMany('App\Models\Role', 'user_role', 'user_id', 'role_id');
          return $this->belongsToMany(Role::class);
    }

    public function cours()
    {
        return $this->belongsToMany('App\Models\Course', 'professor_id', 'id');
    }
}
</code>```

thanks for helping.

答:
Edit

Thanks to Abir, I found the way with some changes.

If I understood, Cours::with('user') is a way to call the function user() in the model Cours. Is this right ?

```<code>public function afficheFormation($id)
    {
        $formation = DB::table('formation')->select('formation.*')->where('id', $id)->first();
        $cours = Cours::with('user')
            ->join('Cours_formation', 'cours_id', '=', 'Cours.id')
            ->select('cours.*')->where('formation_id', $id)->get();

        return view('formation', compact('formation', 'cours'));
    }
</code>```

In the view, we have this code:

```<code>@if(count($cours)> 0 )
@foreach($cours as $cours)
<tr>
  <td class="align-middle">
  {{ $cours->name }}
  </td>
  <td class="align-middle">
  {{ $cours->niveau}}
  </td>
  <td class="align-middle">
  {{ $cours->user->name}}
  </td>
</tr> @endforeach
@endif
</code>```

For the Cours model :

```<code>public function user()
    {
        return $this->belongsTo(User::class, 'prof_id', 'id');
    }
</code>```

And finale for the User model :

```<code>public function cours()
    {
        return $this->hasMany(Cours::class);
    }
</code>```

thanks.

Title: Laravel, relationship problems

Body:
this is my first Laravel project and I have to do a LMS(learning management system).
I have a course table and an user table.

Here is my controller code:

public function afficheFormation($id)
    {
        $formation = DB::table('formation')->select('formation.*')->where('id', $id)->first();
        $cours = DB::table('Course')->join('Course_formation', 'course_id', '=', 'Course.id')

            ->select('Course.*')->where('formation_id', $id)->get();

        return view('formation', compact('formation', 'cours'));
    }

here is my view code:

 {{ $cours->name }}
 {{ $cours->level}}
 {{ $cours->user() }}

@endforeach
@endif

Course have a foreign key professor_id and I want to display the name of the user which created the course but have some errors

This is my Course model:

class Course extends Model
{

    protected $table = 'cours';
    public $timestamps = true;

    protected $fillable = [
        'name', 'lien', 'type', 'level', 'theme_id', 'prof_id'
    ];

    public function user()
    {
        return $this->hasOne('App\Models\User');
    }
}

and this is my user model:

class User extends Authenticatable
{
    use Notifiable;

    protected $table = 'users';
    public $timestamps = true;

    protected $fillable = [
        'pseudo', 'email', 'password', 'name', 'prenom', 'image'
    ];

    public function roles()
    {
          //return $this->belongsToMany('App\Models\Role', 'user_role', 'user_id', 'role_id');
          return $this->belongsToMany(Role::class);
    }

    public function cours()
    {
        return $this->belongsToMany('App\Models\Course', 'professor_id', 'id');
    }
}

thanks for helping.

Body:
Edit

Thanks to Abir, I found the way with some changes.

If I understood, Cours::with('user') is a way to call the function user() in the model Cours. Is this right ?

public function afficheFormation($id)
    {
        $formation = DB::table('formation')->select('formation.*')->where('id', $id)->first();
        $cours = Cours::with('user')
            ->join('Cours_formation', 'cours_id', '=', 'Cours.id')
            ->select('cours.*')->where('formation_id', $id)->get();

        return view('formation', compact('formation', 'cours'));
    }

In the view, we have this code:

@if(count($cours)> 0 )
@foreach($cours as $cours)
<tr>
  <td class="align-middle">
  {{ $cours->name }}
  </td>
  <td class="align-middle">
  {{ $cours->niveau}}
  </td>
  <td class="align-middle">
  {{ $cours->user->name}}
  </td>
</tr> @endforeach
@endif

For the Cours model :

public function user()
    {
        return $this->belongsTo(User::class, 'prof_id', 'id');
    }

And finale for the User model :

public function cours()
    {
        return $this->hasMany(Cours::class);
    }

thanks.