问:
Why can't I reassign variables in this function?
Here is the question:

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.

Here is my code:

```<code>def sort_array(source_array):
    odd_ints = []

    for i in source_array:
        if i % 2 == 1:
            odd_ints.append(i)
            odd_ints.sort()
        else:
            pass
    counter = 0
    for x in source_array:
        if x % 2 == 1:
            x = odd_ints[counter]
            counter += 1
            print(source_array)
        else:
            pass

    return source_array
</code>```

When I test it, it does this:

```<code>>>> sort_array([5, 3, 2, 8, 1, 4])
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]

[5, 3, 2, 8, 1, 4]
</code>```

For some reason, I can't re-assign the variable x in the function to odd_ints in ascending order. Would anyone know the problem in my code?

答:
Modified answer by @eli-harold to use slightly more readable syntax:

def sort_array(source_array):
    odd_ints = []
    positions = []
    for i, elem in enumerate(source_array):
        if elem % 2:
            odd_ints.append(elem)  # keep the values
            positions.append(i)  # keep the position

    odd_ints.sort()  # sort for replacement

    for pos, elem in zip(positions, odd_ints):
        source_array[pos] = elem  # place the sorted values
    return source_array

print(sort_array([5, 3, 2, 8, 1, 4]))
```
<p>Or, being more concise,</p>
<pre class="lang-py prettyprint-override"><code>def sort_array(source_array):
    positions, odd_ints = zip(*[(i, elem)
                                for i, elem in enumerate(source_array)
                                if elem % 2])
    pos = iter(positions)
    for elem in sorted(odd_ints):
        source_array[next(pos)] = elem
    return source_array
</code>```

Bonus: if we should not sort inplace (modify given list), the following will work:

def sort_array(arr):
    odd_sorted_it = iter(sorted(el for el in arr if el % 2))
    return [el if not el % 2 else next(odd_sorted_it) for el in arr]
```

Body:
Here is the question:

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.

Here is my code:

def sort_array(source_array):
    odd_ints = []

    for i in source_array:
        if i % 2 == 1:
            odd_ints.append(i)
            odd_ints.sort()
        else:
            pass
    counter = 0
    for x in source_array:
        if x % 2 == 1:
            x = odd_ints[counter]
            counter += 1
            print(source_array)
        else:
            pass

    return source_array

When I test it, it does this:

>>> sort_array([5, 3, 2, 8, 1, 4])
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]

[5, 3, 2, 8, 1, 4]

For some reason, I can't re-assign the variable x in the function to odd_ints in ascending order. Would anyone know the problem in my code?

Body:
Modified answer by @eli-harold to use slightly more readable syntax:

def sort_array(source_array):
    odd_ints = []
    positions = []
    for i, elem in enumerate(source_array):
        if elem % 2:
            odd_ints.append(elem)  # keep the values
            positions.append(i)  # keep the position

    odd_ints.sort()  # sort for replacement

    for pos, elem in zip(positions, odd_ints):
        source_array[pos] = elem  # place the sorted values
    return source_array

print(sort_array([5, 3, 2, 8, 1, 4]))

Or, being more concise,

def sort_array(source_array):
    positions, odd_ints = zip(*[(i, elem)
                                for i, elem in enumerate(source_array)
                                if elem % 2])
    pos = iter(positions)
    for elem in sorted(odd_ints):
        source_array[next(pos)] = elem
    return source_array

Bonus: if we should not sort inplace (modify given list), the following will work:

def sort_array(arr):
    odd_sorted_it = iter(sorted(el for el in arr if el % 2))
    return [el if not el % 2 else next(odd_sorted_it) for el in arr]


来源: stackexchange

问:
C# / RegEx - How can I improve my RegEx expression?
I have an question about my code with RegEx. My case is that I have about 700 text files, which I import within my tool and that is sometime taking under one second or sometimes taking up to 7 seconds.

So I profiled my tool and it was saying File.ReadAllLinesand my RegEx is taking the most time.. So maybe some RegEx pro can help me and teach me how I can improve my RegEx expression.

This is my code:

```<code>var entries = new List<SomeModelObject>();

            try
            {
                var allLines = File.ReadAllLines(filepath, Encoding.Default);

                var isHashCollected = false;
                // main pattern
                var pattern = @"[a-zA-Z<>:_]+\s+SYMBOL:\s(?<var>\w+)(|\s+)=\s(?<value>\W\w+|\w+)\s;\s\/\/(?<comment>.*)";
                Match match;
                Regex regex = new Regex(pattern,
                      RegexOptions.Singleline);

                var secondPattern = @"<0:64:0>[\w\s;]+\/\/\s(?<second>\w+)";
                Regex regexSecondPattern  = new Regex(secondPattern , RegexOptions.Singleline);

                var thirdPattern = @"<@\(#\)(?<third>\w+)";
                Regex regexThirdPattern  = new Regex(thirdPattern , RegexOptions.Singleline);

                foreach (var line in allLines)
                {
                    if (!isHashCollected)
                    {
                        isHashCollected = GetHash(regexThirdPattern.Match(line), someObject, isHashCollected);
                    }

                    match = regex.Match(line);

                    if (match.Success)
                    {
                        // get entries
                        var someModelObject= new SomeModelObject();
                        someModelObject.projCase = match.Groups["var"].Value;
                        someModelObject.projValue = match.Groups["value"].Value;
                        someModelObject.projComment = match.Groups["comment"].Value;
                        entries.Add(someModelObject);
                        continue;
                    }

                    GetSecondHash(regexSecondPattern.Match(line), someObject);

                }

                return entries;
            }
            catch (Exception e)
            {
                return new List<SomeModelObject>();
            }
</code>```

For completness:

```<code>private static bool GetHash(Match match, SomeObject someObject, bool isHashCollected)
    {
        if (match.Success)
        {
            someObject.hash = match.Groups["third"].Value;
            return true;
        }
        return isHashCollected;
    }

    private static void GetSecondHash(Match match, SomeObject someObject)
    {
        if (match.Success)
        {
            someObject.hash = match.Groups["second"].Value;
        }
    }
</code>```

So I got three expressions, but I think "main pattern" must be improved. Maybe there is some other culprint here and I dont see it (any help is appreciated!)

And those are some lines from one file (where I do my RegEx) each has the same format:

```<code><@(#)123456788c81a76adc83466212345678
//
<ABC_Defg:Element>  SYMBOL: ABCDEF = 00001  ;   //Some text
<ABC_Defg:Value>    SYMBOL: ABCDEF = 00000  ;   //Some text
<ABC_Defg:Value>    SYMBOL: ABCDEF = 00000  ;   //Some text

<0:64:0> 0xABCDEF 0xABCDEF 0xABCDEF0 0xABCDEF ; // 12345678f0aa885f12345678
</code>```

As I said any help is appreciated!!! Thanks

UPDATE

I updated my pattern to this (?<var>[^:]*)[=](?<value>[^=]*)[;](?<comment>[^;]*) and I also parallized the reading of files with Parallel.ForeEach (thanks @charlieface) so I have now ~1 second to read and display input of 700 files. Thanks buddys for helping me out!

答:
When the data has specific patterns, change any positive search to be a negative search. So take you the pattern of a non word then any words or | just words to have it consume everything up to the ;.

```<code> (?<value>\W\w+|\w+)
</code>```

and change it to consume anything that is not a ;

```<code>(?<value>[^;]+)
</code>```

which will do the same thing but not have the parser doing extra work because of the | you have. Because everything then ends at the \s; which I would remove and have ; only.  At minimum have it be \W?\w+ instead.

ContentLicense: CC BY-SA 4.0

Body:
I have an question about my code with RegEx. My case is that I have about 700 text files, which I import within my tool and that is sometime taking under one second or sometimes taking up to 7 seconds.

So I profiled my tool and it was saying File.ReadAllLinesand my RegEx is taking the most time.. So maybe some RegEx pro can help me and teach me how I can improve my RegEx expression.

This is my code:

var entries = new List<SomeModelObject>();

            try
            {
                var allLines = File.ReadAllLines(filepath, Encoding.Default);

                var isHashCollected = false;
                // main pattern
                var pattern = @"[a-zA-Z<>:_]+\s+SYMBOL:\s(?<var>\w+)(|\s+)=\s(?<value>\W\w+|\w+)\s;\s\/\/(?<comment>.*)";
                Match match;
                Regex regex = new Regex(pattern,
                      RegexOptions.Singleline);

                var secondPattern = @"<0:64:0>[\w\s;]+\/\/\s(?<second>\w+)";
                Regex regexSecondPattern  = new Regex(secondPattern , RegexOptions.Singleline);

                var thirdPattern = @"<@\(#\)(?<third>\w+)";
                Regex regexThirdPattern  = new Regex(thirdPattern , RegexOptions.Singleline);

                foreach (var line in allLines)
                {
                    if (!isHashCollected)
                    {
                        isHashCollected = GetHash(regexThirdPattern.Match(line), someObject, isHashCollected);
                    }

                    match = regex.Match(line);

                    if (match.Success)
                    {
                        // get entries
                        var someModelObject= new SomeModelObject();
                        someModelObject.projCase = match.Groups["var"].Value;
                        someModelObject.projValue = match.Groups["value"].Value;
                        someModelObject.projComment = match.Groups["comment"].Value;
                        entries.Add(someModelObject);
                        continue;
                    }

                    GetSecondHash(regexSecondPattern.Match(line), someObject);

                }

                return entries;
            }
            catch (Exception e)
            {
                return new List<SomeModelObject>();
            }

For completness:

private static bool GetHash(Match match, SomeObject someObject, bool isHashCollected)
    {
        if (match.Success)
        {
            someObject.hash = match.Groups["third"].Value;
            return true;
        }
        return isHashCollected;
    }

    private static void GetSecondHash(Match match, SomeObject someObject)
    {
        if (match.Success)
        {
            someObject.hash = match.Groups["second"].Value;
        }
    }

So I got three expressions, but I think "main pattern" must be improved. Maybe there is some other culprint here and I dont see it (any help is appreciated!)

And those are some lines from one file (where I do my RegEx) each has the same format:

<@(#)123456788c81a76adc83466212345678
//
<ABC_Defg:Element>  SYMBOL: ABCDEF = 00001  ;   //Some text
<ABC_Defg:Value>    SYMBOL: ABCDEF = 00000  ;   //Some text
<ABC_Defg:Value>    SYMBOL: ABCDEF = 00000  ;   //Some text

<0:64:0> 0xABCDEF 0xABCDEF 0xABCDEF0 0xABCDEF ; // 12345678f0aa885f12345678

As I said any help is appreciated!!! Thanks

UPDATE

I updated my pattern to this (?<var>[^:]*)[=](?<value>[^=]*)[;](?<comment>[^;]*) and I also parallized the reading of files with Parallel.ForeEach (thanks @charlieface) so I have now ~1 second to read and display input of 700 files. Thanks buddys for helping me out!

Body:
When the data has specific patterns, change any positive search to be a negative search. So take you the pattern of a non word then any words or | just words to have it consume everything up to the ;.

 (?<value>\W\w+|\w+)

and change it to consume anything that is not a ;

(?<value>[^;]+)

which will do the same thing but not have the parser doing extra work because of the | you have. Because everything then ends at the \s; which I would remove and have ; only.  At minimum have it be \W?\w+ instead.


问:
Knex.js: Create table and insert data
Given that I have a Knex.js script like this:

```<code>exports.up = function(knex, Promise) {
    return knex.schema.createTable('persons', function(table) {
        table.increments('id').primary();
        table.string('name').notNullable();
    });
};
</code>```

which currently creates a table.

How do I add subsequent insert statements to this script?

What I want to do is add a line like this (or similar):

```<code>knex.insert({id: 1, name: 'Test'}).into('persons')
</code>```

I'm not sure I understand how this promise-based approach works. Am I supposed to write another script with insert statements? Or can I somehow append them to my existing script?

Unfortunately, I don't find any complete example of create + insert in Knex.js documentation.

答:
With modern Javascript's await/async keywords, you could do it like this:

```<code>exports.up = async function(knex) {
    await knex.schema.createTable('persons', function(table) {
        table.increments('id').primary();
        table.string('name').notNullable();
    });

    // You could replace "return" by "await" here if you wish.
    return knex.insert({id: 1, name: 'Test'}).into('persons');
};
</code>```

It's basically the same, except using await/async instead of then.

ContentLicense: CC BY-SA 3.0

Title: Knex.js: Create table and insert data

Body:
Given that I have a Knex.js script like this:

exports.up = function(knex, Promise) {
    return knex.schema.createTable('persons', function(table) {
        table.increments('id').primary();
        table.string('name').notNullable();
    });
};

which currently creates a table.

How do I add subsequent insert statements to this script?

What I want to do is add a line like this (or similar):

knex.insert({id: 1, name: 'Test'}).into('persons')

I'm not sure I understand how this promise-based approach works. Am I supposed to write another script with insert statements? Or can I somehow append them to my existing script?

Unfortunately, I don't find any complete example of create + insert in Knex.js documentation.

Body:
With modern Javascript's await/async keywords, you could do it like this:

exports.up = async function(knex) {
    await knex.schema.createTable('persons', function(table) {
        table.increments('id').primary();
        table.string('name').notNullable();
    });

    // You could replace "return" by "await" here if you wish.
    return knex.insert({id: 1, name: 'Test'}).into('persons');
};

It's basically the same, except using await/async instead of then.


问:
Visual Studio C++ ofstream can't creat .txt files but it can create other types
My problem is that in this specific drive, visual studio C++ refuses create .txt files using ofstream or fstream the worst part is this is only targeting .txt extension I can create the file with any extension except .txt.

I am able to create .txt file in another drive(able to with bothofstream and fstream) . The drive I'm unable to create a text document in is a HDD that got split into 2 partitions, and the one I am able to create a text document on is jsut an SSD that's not split. Visual Studio is installed on my C drive which is also an SSD.

Please help, I'm desperate.

This is the code I'm using to test.

```<code>#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream file("filename.p");
    file << "1";
    file.close();
}
</code>```

答: SOLVED: it is antivirus which blocks file creation of .txt files. So just add the whole directory of your project to the exceptions.</p>

Body:
My problem is that in this specific drive, visual studio C++ refuses create .txt files using ofstream or fstream the worst part is this is only targeting .txt extension I can create the file with any extension except .txt.

I am able to create .txt file in another drive(able to with bothofstream and fstream) . The drive I'm unable to create a text document in is a HDD that got split into 2 partitions, and the one I am able to create a text document on is jsut an SSD that's not split. Visual Studio is installed on my C drive which is also an SSD.

Please help, I'm desperate.

This is the code I'm using to test.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream file("filename.p");
    file << "1";
    file.close();
}


问:
How to resolve Intersection and Union doesn't match in ts?
I want to create a function that will create a different class by passing different args ,

but I am getting an error in the code below；

It looks like even though I specify the generic, typescript can't understand it

type ClassAOptions = {
  fooA: string;
  barA: string;
};
class ClassA {
  constructor(options: ClassAOptions) {}

  static new(options: ClassAOptions): ClassA {
    return new ClassA(options);
  }
}

type ClassBOptions = {
  fooB: boolean;
  barB: boolean;
};
class ClassB {
  constructor(options: ClassBOptions) {}

  static new(options: ClassBOptions): ClassB {
    return new ClassB(options);
  }
}

const classList = {
  first: ClassA,
  second: ClassB,
};

function createClass<K extends keyof typeof classList>(
  className: K,
  args: ConstructorParameters<typeof classList[K]>[0]
) {
  //  type error
  //  Argument of type 'ClassAOptions | ClassBOptions' is not assignable to parameter of type 'ClassAOptions & ClassBOptions'.
  return new classList[className](->args<-);
}

createClass("first", { fooA: "false", barA: "false" });
createClass("second", { fooB: false, barB: false });
```

this type error is make me crazy, does anyone know why typescript will show an error here,

I can't find my answer on google at all;

Or let me know the key point of this type err, I can google it then

答:
The issue you are having is that Typescript will not resolve K until you actually pass in a value to createClass.  In other words, it will not conditionally resolve K inside the generic function createClass, even though it is resolvable when createClass is called.

For more on this issue, see this SO answer.

You can nevertheless achieve what you want via an explicit return type (return types are resolved when the function is actually called) and an internal assertion.

function createClass<K extends keyof typeof classList>(
  className: K,
  args: ConstructorParameters<typeof classList[K]>[0]
): InstanceType<typeof classList[K]> {
  return new classList[className](args) as InstanceType<typeof classList[K]>;
}
```

Body:
I want to create a function that will create a different class by passing different args ,

but I am getting an error in the code below；

It looks like even though I specify the generic, typescript can't understand it

type ClassAOptions = {
  fooA: string;
  barA: string;
};
class ClassA {
  constructor(options: ClassAOptions) {}

  static new(options: ClassAOptions): ClassA {
    return new ClassA(options);
  }
}

type ClassBOptions = {
  fooB: boolean;
  barB: boolean;
};
class ClassB {
  constructor(options: ClassBOptions) {}

  static new(options: ClassBOptions): ClassB {
    return new ClassB(options);
  }
}

const classList = {
  first: ClassA,
  second: ClassB,
};

function createClass<K extends keyof typeof classList>(
  className: K,
  args: ConstructorParameters<typeof classList[K]>[0]
) {
  //  type error
  //  Argument of type 'ClassAOptions | ClassBOptions' is not assignable to parameter of type 'ClassAOptions & ClassBOptions'.
  return new classList[className](->args<-);
}

createClass("first", { fooA: "false", barA: "false" });
createClass("second", { fooB: false, barB: false });

this type error is make me crazy, does anyone know why typescript will show an error here,

I can't find my answer on google at all;

Or let me know the key point of this type err, I can google it then


问:
How to change checkbox's border style in CSS?
How can I change checkbox (input) border's style? I've put border:1px solid #1e5180 upon it, but in FireFox 3.5, nothing happens!

答:
It's actually just two things you have to do</p>
```<code>outline: 1px solid #63DDCF
border: none !important;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It's actually just two things you have to do

outline: 1px solid #63DDCF
border: none !important;


问:
How to use streamlit in ROS?
I have a ROS node written in Python that captures messages and writes them to disk but I also need to visualize my data through a web interface. I am an experienced Streamlit user but I couldn't find an appropriate way to use this library in ROS. In Streamlit to run our code, there is command: "streamlit run FILENAME.py"

But in ROS, in order to subscribe from the ROS nodes, I need to run my python file using rosrun or roslaunch.

Any idea How to use these libraries together?
OS: Ubuntu 20.04
Python 3.7

答:
Here is a very basic example on how to use ROS subscribe and publish in combination with streamlit. In this example a String gets published to the rostopic /mystring when the input text field is changed. The streamlit metric is updated every second with the current Int32 value published to the rostopic /mynumber

Python Code:

```<code>from streamlit import cli as stcli
import streamlit as st
import rospy
from std_msgs.msg import String, Int32
import sys
import time

mynum=0
mydelta=0

def callback(data):
  global mydelta, mynum
  mydelta=mynum-data.data
  mynum=data.data
  #rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)

def getData():
  return mynum, mydelta

rospy.init_node('my_streamlit_ros_node')
pub = rospy.Publisher('/mystring', String, queue_size=10)
rospy.Subscriber("mynumber", Int32 , callback)

def main():
  st.title('Streamlit APP:')
  st.subheader('Commuicating with ROS')
  mytext = st.text_input('Send String to ROS', 'Life of Brian')
  pub.publish(mytext)
  metrics = st.empty()
  while True:
    mynum, mydelta=getData()
    with metrics:
      st.metric(label="Get Int32 Number from ROS", value=mynum, delta=mydelta, delta_color="inverse")
    time.sleep(1)

if __name__ == '__main__':
    if st._is_running_with_streamlit:
        main()
    else:
        sys.argv = ["streamlit", "run", sys.argv[0]]
        sys.exit(stcli.main())
</code>```

Execution:

source your ros workspace

python3 scriptname.py

Title: How to use streamlit in ROS?

Body:
Here is a very basic example on how to use ROS subscribe and publish in combination with streamlit. In this example a String gets published to the rostopic /mystring when the input text field is changed. The streamlit metric is updated every second with the current Int32 value published to the rostopic /mynumber

Python Code:

from streamlit import cli as stcli
import streamlit as st
import rospy
from std_msgs.msg import String, Int32
import sys
import time

mynum=0
mydelta=0

def callback(data):
  global mydelta, mynum
  mydelta=mynum-data.data
  mynum=data.data
  #rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)

def getData():
  return mynum, mydelta

rospy.init_node('my_streamlit_ros_node')
pub = rospy.Publisher('/mystring', String, queue_size=10)
rospy.Subscriber("mynumber", Int32 , callback)

def main():
  st.title('Streamlit APP:')
  st.subheader('Commuicating with ROS')
  mytext = st.text_input('Send String to ROS', 'Life of Brian')
  pub.publish(mytext)
  metrics = st.empty()
  while True:
    mynum, mydelta=getData()
    with metrics:
      st.metric(label="Get Int32 Number from ROS", value=mynum, delta=mydelta, delta_color="inverse")
    time.sleep(1)

if __name__ == '__main__':
    if st._is_running_with_streamlit:
        main()
    else:
        sys.argv = ["streamlit", "run", sys.argv[0]]
        sys.exit(stcli.main())

Execution:

source your ros workspace

python3 scriptname.py


问:
Clicking on Buy now Button in Aliexpress Python Selenium
I am trying to Click on Buy now Button in Aliexpress Python Selenium

for example

```<code>https://www.aliexpress.com/item/4000001810642.html

clikcononbuynows= driver.find_element_by_css_selector('#root > div > div.product-main > div > div.product-info > div.product-action > span.buy-now-wrap > button')
clikcononbuynows.click()
</code>```

Also one more issue I want to click on the Search button and write something like "android cable"
but it doesn't click
the code I am using for that is

```<code>search = driver.find_element_by_css_selector('#search-key')
search.send_keys('android data cable')
</code>```

Kindly Let me know What I am missing and help me

答:
To type in the search box and click on Search:

```<code>driver.find_element(By.ID, "search-key").send_keys("android data cable")
driver.find_element(By.XPATH, "//div[@class='header-search-btn']//button[@type='submit']").click()
</code>```

To click on Buy Now option:

```<code>driver.find_element(By.XPATH, "//div[@class='product-action']//button[text()='Buy Now']").click()
</code>```

Updated per user query:
Search Button Clicked Snapshot

Full code for Search button: Note the time delays:

```<code>driver.get("https://www.aliexpress.com/item/4000001810642.html")
time.sleep(5)
driver.find_element(By.ID, "search-key").send_keys("android data cable")
time.sleep(2)
driver.find_element(By.XPATH, "//div[@class='header-search-btn']//button[@type='submit']").click()
</code>```

Please use webdriverwait instead of time.sleep

Body:
I am trying to Click on Buy now Button in Aliexpress Python Selenium

for example

https://www.aliexpress.com/item/4000001810642.html

clikcononbuynows= driver.find_element_by_css_selector('#root > div > div.product-main > div > div.product-info > div.product-action > span.buy-now-wrap > button')
clikcononbuynows.click()

Also one more issue I want to click on the Search button and write something like "android cable"
but it doesn't click
the code I am using for that is

search = driver.find_element_by_css_selector('#search-key')
search.send_keys('android data cable')

Kindly Let me know What I am missing and help me

Body:
To type in the search box and click on Search:

driver.find_element(By.ID, "search-key").send_keys("android data cable")
driver.find_element(By.XPATH, "//div[@class='header-search-btn']//button[@type='submit']").click()

To click on Buy Now option:

driver.find_element(By.XPATH, "//div[@class='product-action']//button[text()='Buy Now']").click()

Updated per user query:
Search Button Clicked Snapshot

Full code for Search button: Note the time delays:

driver.get("https://www.aliexpress.com/item/4000001810642.html")
time.sleep(5)
driver.find_element(By.ID, "search-key").send_keys("android data cable")
time.sleep(2)
driver.find_element(By.XPATH, "//div[@class='header-search-btn']//button[@type='submit']").click()

Please use webdriverwait instead of time.sleep


答:
I think you just need to do it directly because df[0] is already a list.

np.array(df[0])
```

That is if 0 is a column and not and index of your DataFrame (using numbers for columns can be misleading)

Title: Convert a list in a pandas df column into a numpy array

Body:
I have a pandas column with a list of lists.

df[0]
[[[11305.45, 4840.39],
[11298.25, 4842.75],
[11292.25, 4846.94],
[11287.77, 4852.81],
[11286.58, 4860.15],
[11305.45, 4840.39]]]

I would like to turn the column into an array.

pd.DataFrame(df[0].values.tolist()).

But I get

AttributeError: 'list' object has no attribute 'values'

The desired output is:

array([[11305.45, 4840.39],
  [11298.25, 4842.75],
  [11292.25, 4846.94],
  [11287.77, 4852.81],
  [11286.58, 4860.15],
  [11305.45, 4840.39]])

Any help greatly appreciated.

Body:
I think you just need to do it directly because df[0] is already a list.

np.array(df[0])

That is if 0 is a column and not and index of your DataFrame (using numbers for columns can be misleading)


问:
how to get an HTML element who called a function?
I have HTML elements with 'onclick' attribute like this one:

```<code>  <div class="item add pt-3" data-toggle="modal" data-target="#uploadModal"
   onclick="myFunction();"><i class="ni ni-fat-add"></i></div>
</code>```

Later in a script I want to have this element to manipulate it.

```<code>myFunction(){
  $(theElement).data('target'); //example
}
</code>```

答:
Just send it in:

```<code>onclick="myFunction(this);"
</code>```

And then you get it as the first argument to your function:

```<code>function myFunction(theElement) {
  $(theElement).data('target');
}
</code>```

But you should consider adding the event with JavaScript in the first place:

```<code><div class="item add pt-3" data-toggle="modal" data-target="#uploadModal">...</div>
</code>```

And your JavaScript file could contain something like:

```<code>// add click listeners to all DOM elements that have the class "add"
$('.add').on('click', function() {
  $(this).data('target');
});
</code>```

Or without jQuery, and modern JavaScript:

```<code>document.querySelectorAll('.add').forEach(el => {
  el.addEventListener('click', () => {
    el.dataset.target;
  });
});
</code>```

If the element is dynamically created, then you could consider using event delegation.

Body:
I have HTML elements with 'onclick' attribute like this one:

Later in a script I want to have this element to manipulate it.

myFunction(){
  $(theElement).data('target'); //example
}

Body:
Just send it in:

onclick="myFunction(this);"

And then you get it as the first argument to your function:

function myFunction(theElement) {
  $(theElement).data('target');
}

But you should consider adding the event with JavaScript in the first place:

<div class="item add pt-3" data-toggle="modal" data-target="#uploadModal">...</div>

And your JavaScript file could contain something like:

// add click listeners to all DOM elements that have the class "add"
$('.add').on('click', function() {
  $(this).data('target');
});

Or without jQuery, and modern JavaScript:

document.querySelectorAll('.add').forEach(el => {
  el.addEventListener('click', () => {
    el.dataset.target;
  });
});

If the element is dynamically created, then you could consider using event delegation.


问:
Mathematica - Force Logarithmic Scale on Plots & Grouped Axes Labels
I have a ListPointPlot3D plot and all three axes contain a logarithmic distribution of data points.

Like this:

```<code>..... .  .    .        .                .                                .
</code>```

How do I force Mathematica to make the axes' scales logarithmic so that I get a linear distribution of data points across them?

Thanks

答:
If you are willing to redo your plot as a BubbleChart3D (with constant bubble sizes, I guess), you can use the ScalingFunctions (documentation) option to rescale the axes to log form. It can also be used to scale axes in ways other than log-scale. Since you are using ListPointPlot3D, you might need to rearrange your input data as well.

This is one of the annoying distinctions between "charting" and "plotting" in Mathematica. As far as I know, the ScalingFunction option only applies to "charts" (financial, bar and bubble charts), not plots like ListPlot or ListPlot3D.

Body:
I have a ListPointPlot3D plot and all three axes contain a logarithmic distribution of data points.

Like this:

..... .  .    .        .                .                                .

How do I force Mathematica to make the axes' scales logarithmic so that I get a linear distribution of data points across them?

Thanks


问:
Export c++ code from simulink scheme with s-function
I have a simulink working simulink schema in which there are some s-function, I want to export this code in c++ and compile it. I already tried to export and compile a simple schema and it works, but when i try to compile the exported code of my project I get a lot of errors like

```<code>error: #error Unrecognized use
error: #error Must define one of RT,nNRT, MATLAB_MEX_FILE, SL_INTERNAL, or FIPXT_SHARED_MODULE
error: #error Unhandled case
error: ‘mxArray’ does not name a type  mxArray       **dlgParams; /* The S-function parameters
error: ‘mxArray’ has not been declared  mxArray **)
error: ‘mxArray’ does  not name a type mxArray     *propVal;
error: ‘RTWSfcnInfo’ does not name a type; did you mean ‘RTWLogInfo’? RTWSfcnInfo sfcnInfo
</code>```

The main settings that i used are:

```<code>Code generation system target file --> grt.tlc
language --> C++
Pack code and artifact --> <name_zip>
Tool chain GNU gcc/g++ | gmake (64-bit Linux)
default parameter behavior --> tuanble
code interface packaging --> nonreusable function
external mode --> chcked
standar math library --> c++ 03(ISO)
single output/update function --> checked
i used a fixed step size solver
</code>```

Im using Ubuntu 18.

The source is generated succesfully the problem is when i try to compile the code.
Once the code is generate I get a zip folder with all the sources and also some external header file that I include when I make the CMakeLists.txt. I also tryied to compile directly the code with the .mk file but also I get a bounch of errors. The problem is realated with the s-function because I built a simple simulink schema with a source an s-function that implements a dynamical model and an output and when i generate the code and compile it I get the same errors. I also tryied to make a simple schema without s-function and this works. So is there any settings for the s-function to be exportable

答:
At the end I found an answer that I post here in case someone else has my same problem.

The solution that worked form my is:

First of all once you have the generated zip file with all the sources and headers open it and load on the Matlab workspace the file buldinfo.mat then in the Matlab shell run

```<code>packNGo(buildInfo)
</code>```

in this way you generate a new .zip with all the sources and headers, this .zip differs from the previous because is flat, no nested folder.

Inside this folder there is a file called define.txt with a list of variables, all these variables should be passed as flags to the compiler. For example in my case I use a CMakelists.txt so to set these flags I used

```<code>set(CMAKE_CXX_FLAGS "-Wall -Wextra -DMODEL=test_sum_gain -DNUMST=2 -DNCSTATES=2 -DRT -DUSE_RTMODEL -DON_TARGET_WAIT_FOR_START=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=1 -DEXT_MODE=1 -DMAT_FILE=0 -DONESTEPFCN=1 -DTERMFCN=1 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0")
</code>```

this depends on the way in which you compile the source, but in any case you should set these variables that is I am not wrong are just a directive for the precompiler.

These two things worked for me.

Body:
I have a simulink working simulink schema in which there are some s-function, I want to export this code in c++ and compile it. I already tried to export and compile a simple schema and it works, but when i try to compile the exported code of my project I get a lot of errors like

error: #error Unrecognized use
error: #error Must define one of RT,nNRT, MATLAB_MEX_FILE, SL_INTERNAL, or FIPXT_SHARED_MODULE
error: #error Unhandled case
error: ‘mxArray’ does not name a type  mxArray       **dlgParams; /* The S-function parameters
error: ‘mxArray’ has not been declared  mxArray **)
error: ‘mxArray’ does  not name a type mxArray     *propVal;
error: ‘RTWSfcnInfo’ does not name a type; did you mean ‘RTWLogInfo’? RTWSfcnInfo sfcnInfo

The main settings that i used are:

Code generation system target file --> grt.tlc
language --> C++
Pack code and artifact --> <name_zip>
Tool chain GNU gcc/g++ | gmake (64-bit Linux)
default parameter behavior --> tuanble
code interface packaging --> nonreusable function
external mode --> chcked
standar math library --> c++ 03(ISO)
single output/update function --> checked
i used a fixed step size solver

Im using Ubuntu 18.

The source is generated succesfully the problem is when i try to compile the code.
Once the code is generate I get a zip folder with all the sources and also some external header file that I include when I make the CMakeLists.txt. I also tryied to compile directly the code with the .mk file but also I get a bounch of errors. The problem is realated with the s-function because I built a simple simulink schema with a source an s-function that implements a dynamical model and an output and when i generate the code and compile it I get the same errors. I also tryied to make a simple schema without s-function and this works. So is there any settings for the s-function to be exportable

Body:
At the end I found an answer that I post here in case someone else has my same problem.

The solution that worked form my is:

First of all once you have the generated zip file with all the sources and headers open it and load on the Matlab workspace the file buldinfo.mat then in the Matlab shell run

packNGo(buildInfo)

in this way you generate a new .zip with all the sources and headers, this .zip differs from the previous because is flat, no nested folder.

Inside this folder there is a file called define.txt with a list of variables, all these variables should be passed as flags to the compiler. For example in my case I use a CMakelists.txt so to set these flags I used

set(CMAKE_CXX_FLAGS "-Wall -Wextra -DMODEL=test_sum_gain -DNUMST=2 -DNCSTATES=2 -DRT -DUSE_RTMODEL -DON_TARGET_WAIT_FOR_START=0 -DCLASSIC_INTERFACE=0 -DALLOCATIONFCN=0 -DTID01EQ=1 -DEXT_MODE=1 -DMAT_FILE=0 -DONESTEPFCN=1 -DTERMFCN=1 -DMULTI_INSTANCE_CODE=0 -DINTEGER_CODE=0 -DMT=0")

this depends on the way in which you compile the source, but in any case you should set these variables that is I am not wrong are just a directive for the precompiler.

These two things worked for me.


问:
Youtube iframe is not working in Chrome browser on Mobile

Note: It also works fine in the incognito window of Chrome browser and other browsers (like Mozilla) on Mobile.

It loads the video data successfully but when I try to play the video it shows me an error.

Run this code using local environment like vs-code etc.

This snippet works on a computer browser properly, but when I open the same page using IP on my mobile Chrome browser, I got an error, but it works in the incognito mode and other browsers too.

I don't know why it is behaving like this, It would be really helpful if anyone can rid of this.

Computer Chrome Browser[Working fine]

Mobile Chrome Browser [Not Playing the video]

//YouTube embed with YouTube Iframe API
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// YouTube embed player details
var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player("player", {
    height: "390",
    width: "640",
    videoId: "668nUCeBHyY",

    //Features
    playerVars: {
      controls: 0,
      rel: 0,
      disablekb: 1,
    },
  });
}

//functions
function playYT() {
  player.playVideo();
}

function pauseYT() {
  player.pauseVideo();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="pointer-events:none" id="player"></div><br><br>
<button onclick="playYT()">Play</button>
<button onclick="pauseYT()">Pause</button></code>```

答:
I am using Live Preview extension for the previews in browser. You need change default(127.0.0.1) IP address in the extension settings to be able see the pages on other devices:

If you are using Live Server extension then change following setting:

If you just want to host the files without VSCode then you can use http-server tool. It is a simple, zero-configuration command-line static HTTP server. All you have to do is provide it the folder path and it'll host all the files in it.

If you are facing any other issue then let us know the exact error and the browser you are using on mobile.

Body:
Note: It also works fine in the incognito window of Chrome browser and other browsers (like Mozilla) on Mobile.

It loads the video data successfully but when I try to play the video it shows me an error.

Run this code using local environment like vs-code etc.

This snippet works on a computer browser properly, but when I open the same page using IP on my mobile Chrome browser, I got an error, but it works in the incognito mode and other browsers too.

I don't know why it is behaving like this, It would be really helpful if anyone can rid of this.

Computer Chrome Browser[Working fine]

Mobile Chrome Browser [Not Playing the video]

//YouTube embed with YouTube Iframe API
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// YouTube embed player details
var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player("player", {
    height: "390",
    width: "640",
    videoId: "668nUCeBHyY",

    //Features
    playerVars: {
      controls: 0,
      rel: 0,
      disablekb: 1,
    },
  });
}

//functions
function playYT() {
  player.playVideo();
}

function pauseYT() {
  player.pauseVideo();
}

<button onclick="playYT()">Play</button>
<button onclick="pauseYT()">Pause</button>


问:
How to set shortcut key to open query in ms access. can some body explain clearly
How to set shortcut key to open query in ms access. can some body explain clearly. how to set shortcut key to already designed qureiess</p>

答:
You can attach a command button to open the query, then in the Command button caption add & and the short cut key you want to use to open the query.

e.g if a command button's caption is Run Query , you can change it to
&NRun Query ,tis will ensure that Alt and N keys will open the query.

Check the images i attached.


问:
Terminate method not called in Access 2021
Anyone else finding that their Terminate() method in Access isn't being called?

Here's my code for my cBusyPointer class with the comments removed for brevity:

```<code>Option Compare Database     ' Use database order for string comparisons
Option Explicit             ' Declare EVERYTHING!
Option Base 1               ' Arrays start at 1

Public Sub show()
    DoCmd.hourGlass True
End Sub

Private Sub Class_Terminate()
    DoCmd.hourGlass False
End Sub
</code>```

Typical usage is:

```<code>Sub doTehThings()
    Dim hourGlass As New cBusyPointer
    hourGlass.show()
    ' Do all teh things
End Sub
</code>```

In previous versions, this class would restore the hourglass whenever the object went out of scope and was destroyed.

I even tried to manually destroy my hourglass object:

```<code>Sub doTehThings()
    Dim hourGlass As cBusyPointer
    Set hourGlass = New cBusyPointer
    hourGlass.show()
    ' Do all teh things
    Set hourGlass = Nothing
End Sub
</code>```

The only way to fix this is to add a hide() method and call that.

Has anyone else encountered this problem?

答:
I cannot replicate the issue. The Terminate() method is called upon reaching the Set hourGlass = Nothing.

A couple of points:

```<code>Dim hourGlass As New cBusyPointer
</code>```

This will create a new instance every time you call the hourGlass variable even to set it to Nothing. See the answer in the link below for additional info:

What's the difference between Dim As New vs Dim / Set

You should always use Dim/Set when working with objects.

```<code>hourGlass.show()
</code>```

This does not even compile in VBA. Subs do not accept parentheses even when arguments are being expected, unless they are preceded with the Call keyword.

Lastly, the cleanest way to reference an object is to access it using the With statement which ensures the object is terminated when the End With statement is reached.

```<code> With New cBusyPointer
     .show
 End With
</code>```

Body:
Anyone else finding that their Terminate() method in Access isn't being called?

Here's my code for my cBusyPointer class with the comments removed for brevity:

Option Compare Database     ' Use database order for string comparisons
Option Explicit             ' Declare EVERYTHING!
Option Base 1               ' Arrays start at 1

Public Sub show()
    DoCmd.hourGlass True
End Sub

Private Sub Class_Terminate()
    DoCmd.hourGlass False
End Sub

Typical usage is:

Sub doTehThings()
    Dim hourGlass As New cBusyPointer
    hourGlass.show()
    ' Do all teh things
End Sub

In previous versions, this class would restore the hourglass whenever the object went out of scope and was destroyed.

I even tried to manually destroy my hourglass object:

Sub doTehThings()
    Dim hourGlass As cBusyPointer
    Set hourGlass = New cBusyPointer
    hourGlass.show()
    ' Do all teh things
    Set hourGlass = Nothing
End Sub

The only way to fix this is to add a hide() method and call that.

Has anyone else encountered this problem?

Body:
I cannot replicate the issue. The Terminate() method is called upon reaching the Set hourGlass = Nothing.

A couple of points:

Dim hourGlass As New cBusyPointer

This will create a new instance every time you call the hourGlass variable even to set it to Nothing. See the answer in the link below for additional info:

What's the difference between Dim As New vs Dim / Set

You should always use Dim/Set when working with objects.

hourGlass.show()

This does not even compile in VBA. Subs do not accept parentheses even when arguments are being expected, unless they are preceded with the Call keyword.

Lastly, the cleanest way to reference an object is to access it using the With statement which ensures the object is terminated when the End With statement is reached.

 With New cBusyPointer
     .show
 End With


问:
Is there any alternative ajv(json-schema validator) for deno?
I'm looking for a ajv-like json schema validator for deno. Wondering is there any alternative?</p>

答: jtd is a viable alternative. It is a deno native implementation of JSON Type Definition, aka RFC 8927, which is an alternative to json-schema validation (and thus ajv) but has a similar purpose.


问:
Azure App Service on Linux - Static File Content not updated
I have created an App Service (inside Linux based App Service Plan). I have connected to wwwroot folder using FTP Client

In the hostingstaart.html, I made a simple text change.

I couldn't see the change getting reflected when I navigate to https://.azurewebsites.net/

However, when I navigate to Kudu and access the same page, I can see the change.

Below is the screenshot.
In the left hand side (kudu website), I can see the change that I have made (DevOps Engineers). However, In this right hand side, the changes is not shown.
In order to troubleshoot, I have added another file as well which is visible in Kudu. But, I'm not able to access the same.

This is not at all an issue in Windows Based App Service Plan. This is an issue only with Linux based app.
Is there any docker container internally where it reads the files from? if yes, how do change those files?

Appreciate any help here .

Thanks,
Praveen

答:
Yes, Azure App Service on Linux run in containers and depending on the platform, different webservers and locations are used which can get confusing.

For SSH access into the container go to https://<yourappname>.scm.azurewebsites.net/webssh/host - in .NET projects on Linux the default page you'll see on a new app service is stored at /defaulthome/hostingstart/wwwroot/hostingstart.html while files you upload via FTP will go to /home/site/wwwroot.

That being said, I'd recommend to use the documented ways to publish content based on the platform you want to use. For .NET, you can find the docs here.


问:
Can I check modelstate without modelbinding?
I'm getting my feet wet with the Entity Framework and am wondering if there is a way for me to check model state without model binding happening.

Say I create a user primarily from code, is there a way for me to check to make sure it is valid according to my predefined data annotations before I update?

```<code>    public ActionResult Index()
    {
        User u = new User();
        u.Username = "test";
        u.Password = "test";
        u.Email = "test";

        DefaultContext db = new DefaultContext();

        if (ModelState.IsValid)
        {
            db.Users.Add(u);
            db.SaveChanges();
            Response.Write(u.Id);
        }
        else
            // model is not valid

        return View();
    }
</code>```

The above code does not work because there is no binding happening. Or maybe I am confused of the process.

Thanks.

答:
you can use TryValidateModel    or ValidateModel

```<code> User u = new User();
    u.Username = "test";
    u.Password = "test";
    u.Email = "test";

    if (TryValidateModel(u))
     {

     }else{

     }
</code>```

Body:
I'm getting my feet wet with the Entity Framework and am wondering if there is a way for me to check model state without model binding happening.

Say I create a user primarily from code, is there a way for me to check to make sure it is valid according to my predefined data annotations before I update?

    public ActionResult Index()
    {
        User u = new User();
        u.Username = "test";
        u.Password = "test";
        u.Email = "test";

        DefaultContext db = new DefaultContext();

        if (ModelState.IsValid)
        {
            db.Users.Add(u);
            db.SaveChanges();
            Response.Write(u.Id);
        }
        else
            // model is not valid

        return View();
    }

The above code does not work because there is no binding happening. Or maybe I am confused of the process.

Thanks.

Body:
you can use TryValidateModel    or ValidateModel

 User u = new User();
    u.Username = "test";
    u.Password = "test";
    u.Email = "test";

    if (TryValidateModel(u))
     {

     }else{

     }


问:
How to set default Timezone on GORM time.Time data type
I am using gorm with mysql as database with go module like this :

gorm.io/gorm v1.21.7

github.com/go-sql-driver/mysql v1.6.0

My system timezone is +07:00 (Asia/Jakarta), and the mysql timezone is using the system timezone itself.

but something wrong happen when I've struct like this

```<code>type Name struct {
    ID         uint64    `gorm:"id;primaryKey;autoIncrement"`
    Name       string    `gorm:"column:name"`
    CreatedAt  time.Time `gorm:"column:created_at"`
    UpdatedAt  time.Time `gorm:"column:updated_at"`
}
</code>```

on the mysql table created_at and updated_at declared as DATETIME, when I print the CreatedAt and UpdatedAt value, the timezone is +0000 (UTC), when I'm trying to use the Time.In function I got the wrong value, like I'm converting a time from UTC to +07:00, how can I declare to GORM that I'm using +07:00 as default timezone.

答:
When connecting to the MySQL database, ensure you leverage the parseTime and loc parameters as per the docs:

to scan MySQL DATE and DATETIME values into time.Time variables, which
is the logical equivalent in Go to DATE and DATETIME in MySQL. You can
do that by changing the internal output type from []byte to time.Time
with the DSN parameter parseTime=true. You can set the default
time.Time location with the loc DSN parameter.

to generate a DSN connection strings to set parseTime & loc see i.e.

```<code>loc, _ := time.LoadLocation("Asia/Jakarta") // handle any errors!

c := mysql.Config{
    User:                    "....",
    Passwd:                  "....",
    DBName:                  "....",
    Addr:                    "....:3306",
    Net:                     "tcp",
    ParseTime:               true,
    Loc:                     loc,
}
fmt.Println(c.FormatDSN())
</code>```

https://go.dev/play/p/5yoEbmrPqlZ

Body:
I am using gorm with mysql as database with go module like this :

gorm.io/gorm v1.21.7

github.com/go-sql-driver/mysql v1.6.0

My system timezone is +07:00 (Asia/Jakarta), and the mysql timezone is using the system timezone itself.

but something wrong happen when I've struct like this

type Name struct {
    ID         uint64    `gorm:"id;primaryKey;autoIncrement"`
    Name       string    `gorm:"column:name"`
    CreatedAt  time.Time `gorm:"column:created_at"`
    UpdatedAt  time.Time `gorm:"column:updated_at"`
}

on the mysql table created_at and updated_at declared as DATETIME, when I print the CreatedAt and UpdatedAt value, the timezone is +0000 (UTC), when I'm trying to use the Time.In function I got the wrong value, like I'm converting a time from UTC to +07:00, how can I declare to GORM that I'm using +07:00 as default timezone.

Body:
When connecting to the MySQL database, ensure you leverage the parseTime and loc parameters as per the docs:

to scan MySQL DATE and DATETIME values into time.Time variables, which
is the logical equivalent in Go to DATE and DATETIME in MySQL. You can
do that by changing the internal output type from []byte to time.Time
with the DSN parameter parseTime=true. You can set the default
time.Time location with the loc DSN parameter.

to generate a DSN connection strings to set parseTime & loc see i.e.

loc, _ := time.LoadLocation("Asia/Jakarta") // handle any errors!

c := mysql.Config{
    User:                    "....",
    Passwd:                  "....",
    DBName:                  "....",
    Addr:                    "....:3306",
    Net:                     "tcp",
    ParseTime:               true,
    Loc:                     loc,
}
fmt.Println(c.FormatDSN())

https://go.dev/play/p/5yoEbmrPqlZ


问:
Flipper React Native Xcode iOS Simulator Version Mismatch
I'm getting the following error about mismatched Xcode versions. However, it doesn't seem to make sense. The UUID is the "Indentifier" of the simulator that is running, not any folder I can switch to. I've found a similar bug, but since it is closed, and old, I don't think I'll get much of a response over there: https://github.com/facebook/flipper/issues/1925#issuecomment-1030495731

I've tried running all the suggested commands with and without sudo and nothing helps. This looks like it might be an Xcode workspace configuration issue since I've not had these problems with other React Native applications.

Xcode version mismatch

Xcode version mismatch: Simulator is running from "286DC512-9354-4D32-A0F3-B354C61BD6B7/Contents/Developer" while Xcode CLI is "/Applications/Xcode.app/Contents/Developer". Running "xcode-select --switch 286DC512-9354-4D32-A0F3-B354C61BD6B7/Contents/Developer" can fix this. For example: "sudo xcode-select -s /Applications/Xcode.app/Contents/Developer"

Xcode version 13.2.1

Flipper version 0.132.0 (50.0.0)

iOS version 15.2

iPhone 11

答:
I've believe that is related with this version 0.132. I've downgrade my version from 0.132 to 0.113 (version that I was using). And everything is working fine.

You can find more releases here https://github.com/facebook/flipper/releases

I'm still looking for a solution to this on version 0.132.


问:
Python: save pandas data frame to parquet file
Is it possible to save a pandas data frame directly to a parquet file?
If not, what would be the suggested process?

The aim is to be able to send the parquet file to another team, which they can use scala code to read/open it. Thanks!

答:
Pandas directly support parquet so-

```<code>df.to_parquet('df.parquet.gzip', compression='gzip')
# this will convert the df to parquet format

df_parquet = pd.read_parquet('df.parquet.gzip')
# This will read the parquet file

df.to_csv('filename.csv')
# this will convert back the parquet to CSV
</code>```

Body:
Pandas directly support parquet so-

df.to_parquet('df.parquet.gzip', compression='gzip')
# this will convert the df to parquet format

df_parquet = pd.read_parquet('df.parquet.gzip')
# This will read the parquet file

df.to_csv('filename.csv')
# this will convert back the parquet to CSV


问:
How to make Android Splash Screen Fullscreen
This is my code. I am following a tutorial on Youtube. When I use android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" the screen does not show the splash screen and shows a blank screen instead. My code is as the following.

```<code><activity
   android:name="com.nowate.customerapp.activity.SplashActivity"
   android:screenOrientation="portrait"
   android:theme="@style/AppTheme.NoActionBar" >
   <intent-filter>
      <action android:name="android.intent.action.MAIN" />

      <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
</activity>
</code>```

答:
This is the proper way to add a splash screen to your app. It doesn't take any fixed time to display it because it is showing while the app really loads.

Declare a new theme in styles.xml:

```<code> <style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowBackground">@drawable/splash_screen</item>
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
 </style>
</code>```

Set the theme in AndroidManifest to your launcher activity (don't create a new activity just for a splash screen):

```<code><activity
   android:name="com.nowate.customerapp.activity.MainActivity"
   android:screenOrientation="portrait"
    android:theme="@style/SplashTheme" >
   <intent-filter>
      <action android:name="android.intent.action.MAIN" />

      <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
</activity>
</code>```

In your MainActivity in the onCreate() method set the original theme befor setting the layout:

```<code>setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
</code>```

Example of splash screen drawable ("ic_loading" is a vector):

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape
            android:shape="rectangle">
            <solid android:color="@color/black" />
        </shape>
    </item>
    <item
        android:gravity="center"
        android:drawable="@drawable/ic_loading"/>
</layer-list>
</code>```

Body:
This is my code. I am following a tutorial on Youtube. When I use android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" the screen does not show the splash screen and shows a blank screen instead. My code is as the following.

<activity
   android:name="com.nowate.customerapp.activity.SplashActivity"
   android:screenOrientation="portrait"
   android:theme="@style/AppTheme.NoActionBar" >
   <intent-filter>
      <action android:name="android.intent.action.MAIN" />

      <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
</activity>

Body:
This is the proper way to add a splash screen to your app. It doesn't take any fixed time to display it because it is showing while the app really loads.

Declare a new theme in styles.xml:

 <style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowBackground">@drawable/splash_screen</item>
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
 </style>

Set the theme in AndroidManifest to your launcher activity (don't create a new activity just for a splash screen):

<activity
   android:name="com.nowate.customerapp.activity.MainActivity"
   android:screenOrientation="portrait"
    android:theme="@style/SplashTheme" >
   <intent-filter>
      <action android:name="android.intent.action.MAIN" />

      <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
</activity>

In your MainActivity in the onCreate() method set the original theme befor setting the layout:

setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Example of splash screen drawable ("ic_loading" is a vector):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape
            android:shape="rectangle">
            <solid android:color="@color/black" />
        </shape>
    </item>
    <item
        android:gravity="center"
        android:drawable="@drawable/ic_loading"/>
</layer-list>


问:
How can I transform a query graphql to a json object?
I have a problem and I need to transform a query graphql to a json object. That is, I get a query in the following way and I would like to have a json of that query. How could I do it? I've been searching and I haven't found a way.

Thank you.

```<code>query {
  Patient(id:4){
    id
    birthDate {
      year,
      day
    }
    name {
      text
    }
  }
}
</code>```

答:
According to the documentation: to POST a graphQL query to a webservice in a JSON body, simply remove all newlines from the graphQL query, then put it in the following JSON:

```<code>{
    "query": "[graphQL query here]",
    "variables": {}
}
</code>```

In your case, this would look like:

```<code>{
    "query": "query { Patient(id:4){ id birthDate { year, day } name { text } } }",
    "variables": {}
}
</code>```

Body:
I have a problem and I need to transform a query graphql to a json object. That is, I get a query in the following way and I would like to have a json of that query. How could I do it? I've been searching and I haven't found a way.

Thank you.

query {
  Patient(id:4){
    id
    birthDate {
      year,
      day
    }
    name {
      text
    }
  }
}

Body:
According to the documentation: to POST a graphQL query to a webservice in a JSON body, simply remove all newlines from the graphQL query, then put it in the following JSON:

{
    "query": "[graphQL query here]",
    "variables": {}
}

In your case, this would look like:

{
    "query": "query { Patient(id:4){ id birthDate { year, day } name { text } } }",
    "variables": {}
}


问:
How to Copy Value from one Input Field to Another
I have two input fields:

```<code><input type="text" id="one" name="one" />
<input type="text" id="two" name="two" />
</code>```

I want to make it so that whatever that's typed into id one will automatically be put into id two.

Any ideas on how to do this? Possibly javascript needed?

答:
```<code>    $( "#one" ).dblclick(function() {
         copyInputValue()
     });

    function copyInputValue() {

        let text1 = document.getElementById('two').value;
        document.getElementById('one').value = text1;

    }
</code>```

Body:
I have two input fields:

<input type="text" id="one" name="one" />
<input type="text" id="two" name="two" />

I want to make it so that whatever that's typed into id one will automatically be put into id two.

Any ideas on how to do this? Possibly javascript needed?


问:
UDF executing multiple times with Structured References
I am experiencing performance problems with a large (wide and long) table that uses a UDF that has variables passed as structured references.

It seems that when a structured reference for a specific cell, eg "[@A]" is passed to the UDF, it flags the whole column, ie "[A]" as dirty and every cell in the column the UDF references is recalculated (this is the source of the performance problem).

I have found that if I change the UDF within the table to use cell address, eg "A2", then the UDF only executes when that cell changes.

To test, create a simple function with debug.print to highlight when it is run:

```<code>Public Function zap(a As Double, b As Double) As Double
    Debug.Print "zap: " & a & "+" & b
    zap = a + b
End Function
</code>```

Create a 3 column table (A, B, C), with column C as "=zap([@A],[@B])".  if you enter or change a value in column A or B, the UDF will execute for each row regardless of whether the value in the row/column intersection has changed.

if you change column C to use cell addressing, eg  "=zap(A2,B2)", then the UDF only executes once for the row that has changed.

I can use cell addressing to overcome the performance problem, however using a table with structured references provide a lot of benefits for this application.

I would like to know if I have missed or misunderstood something about structured references, or whether there is an adjustment to the UDF that can accommodate.

答: I used this formula in column C =zap([@A],[@B]) and as you can see in the video below I cannot reproduce your issue. It only re-calculates the formula in the row I changed something.

Body:
I am experiencing performance problems with a large (wide and long) table that uses a UDF that has variables passed as structured references.

It seems that when a structured reference for a specific cell, eg "[@A]" is passed to the UDF, it flags the whole column, ie "[A]" as dirty and every cell in the column the UDF references is recalculated (this is the source of the performance problem).

I have found that if I change the UDF within the table to use cell address, eg "A2", then the UDF only executes when that cell changes.

To test, create a simple function with debug.print to highlight when it is run:

Public Function zap(a As Double, b As Double) As Double
    Debug.Print "zap: " & a & "+" & b
    zap = a + b
End Function

Create a 3 column table (A, B, C), with column C as "=zap([@A],[@B])".  if you enter or change a value in column A or B, the UDF will execute for each row regardless of whether the value in the row/column intersection has changed.

if you change column C to use cell addressing, eg  "=zap(A2,B2)", then the UDF only executes once for the row that has changed.

I can use cell addressing to overcome the performance problem, however using a table with structured references provide a lot of benefits for this application.

I would like to know if I have missed or misunderstood something about structured references, or whether there is an adjustment to the UDF that can accommodate.


问:
How to decode column value from rare label by matching column names
I have two dataframes like as shown below

```<code>import numpy as np
import pandas as pd
from numpy.random import default_rng
rng = default_rng(100)
cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                   'grade': rng.choice(list('ACD'),size=(5)),
                   'dash': rng.choice(list('PQRS'),size=(5)),
                   'dumeel': rng.choice(list('QWER'),size=(5)),
                   'dumma': rng.choice((1234),size=(5)),
                   'target': rng.choice([0,1],size=(5))
})

tdf = pd.DataFrame({'Id': [1,1,1,1,3,3,3],
                   'feature': ['grade=Rare','dash=Q','dumma=rare','dumeel=R','dash=Rare','dumma=rare','grade=D'],
                   'value': [0.2,0.45,-0.32,0.56,1.3,1.5,3.7]})
</code>```

My objective is to

a) Replace the Rare or rare values in feature column of tdf dataframe by original value from cdf dataframe.

b) To identify original value, we can make use of the string before = Rare or =rare or = rare etc. That string represents the column name in cdf dataframe (from where original value to replace rare can be found)

I was trying something like the below but not sure how to go from here

```<code>replace_df = cdf.merge(tdf,how='inner',on='Id')
replace_df ["replaced_feature"] = np.where(((replace_df["feature"].str.contains('rare',regex=True)]) & (replace_df["feature"].str.split('='))])
</code>```

I have to apply this on a big data where I have million rows and more than 1000 replacements to be made like this.

I expect my output to be like as shown below

答:
```<code># list comprehension to find where rare is in the feature col
tdf['feature'] = [x if y.lower()=='rare' else x+'='+y for x,y in tdf['feature'].str.split('=')]
# create a mask where feature is in columns of cdf
mask = tdf['feature'].isin(cdf.columns)
# use loc to filter your frame and use merge to join cdf on the id and feature column - after you use stack
tdf.loc[mask, 'feature'] = tdf.loc[mask, 'feature']+'='+tdf.loc[mask].merge(cdf.set_index('Id').stack().to_frame(),
                                                                            right_index=True, left_on=['Id', 'feature'])[0].astype(str)

   Id     feature  value
0   1     grade=D   0.20
1   1      dash=Q   0.45
2   1  dumma=1123  -0.32
3   1    dumeel=R   0.56
4   3      dash=P   1.30
5   3   dumma=849   1.50
6   3     grade=D   3.70
</code>```

Body:
I have two dataframes like as shown below

import numpy as np
import pandas as pd
from numpy.random import default_rng
rng = default_rng(100)
cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                   'grade': rng.choice(list('ACD'),size=(5)),
                   'dash': rng.choice(list('PQRS'),size=(5)),
                   'dumeel': rng.choice(list('QWER'),size=(5)),
                   'dumma': rng.choice((1234),size=(5)),
                   'target': rng.choice([0,1],size=(5))
})

tdf = pd.DataFrame({'Id': [1,1,1,1,3,3,3],
                   'feature': ['grade=Rare','dash=Q','dumma=rare','dumeel=R','dash=Rare','dumma=rare','grade=D'],
                   'value': [0.2,0.45,-0.32,0.56,1.3,1.5,3.7]})

My objective is to

a) Replace the Rare or rare values in feature column of tdf dataframe by original value from cdf dataframe.

b) To identify original value, we can make use of the string before = Rare or =rare or = rare etc. That string represents the column name in cdf dataframe (from where original value to replace rare can be found)

I was trying something like the below but not sure how to go from here

replace_df = cdf.merge(tdf,how='inner',on='Id')
replace_df ["replaced_feature"] = np.where(((replace_df["feature"].str.contains('rare',regex=True)]) & (replace_df["feature"].str.split('='))])

I have to apply this on a big data where I have million rows and more than 1000 replacements to be made like this.

I expect my output to be like as shown below


问:
How can I dynamically set the array object to java object
I am new to java and I am stuck at one place.
I am taking xml request which is coming in array.

```<code><PassengersDetails>
 <Passenger>
  <passesngerName>ABC</passesngerName>
  <passengerAge>25</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>DEF</passesngerName>
  <passengerAge>28</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>GHI</passesngerName>
  <passengerAge>48</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>KLM</passesngerName>
  <passengerAge>18</passengerAge>
 </Passenger>
</PassengersDetails>
</code>```

My xml object is getting turned into array like below.

```<code>Passenger [] passenger= passengersDetails.getPassenger();
</code>```

And my java object looks like

```<code>class Passenger {
passengerName1;
passengerAge1;
passengerName2;
passengerAge2;
passengerName3;
passengerAge3;
passengerName4;
passengerAge4;
}
</code>```

with setter and getter.

I wanted to set all the data from array in java object.
I am able to set it individually after checking if array is preset or not.

```<code>if(arr[0] != null){
setPassengerName1 = arr[0].getPassengerName;
setPassengerAge1 = arr[0].getPassengerAge;
}
if(arr[1] != null){
setPassengerName2 = arr[1].getPassengerName;
setPassengerAge2 = arr[1].getPassengerAge;
}....
</code>```

How can I set passenger array into Passenger java object mentioned above.

But I wanted to know if there is any other way we can do this dynamically.

Something like in the same loop and setting it dynamically.

答:
But I wanted to know if there is any other way we can do this dynamically as we can get 0 or max 4 passenger elements in array.

Either:

Start with one size of array, such as ten. As you place objects into the elements of the array, keep count. As you reach the limits of the array, create a new bigger array. Copy over from old array to new array. Discard old array. Repeat until done.

Use a List implementation such as ArrayList.

Using a list.

```<code>List< Person > persons = new ArrayList<>() ;
</code>```

Define a record class to represent each person. You can declare the record as a separate class, a nested class, or as a local class (within a method).

```<code>record Person ( String name , int age ) {}
</code>```

Add each person.

```<code>Person person = new Person( "Bob" , 42 ) ;
persons.add( person ) ;
</code>```

When done, you may want to make an unmodifiable list to replace the modifiable one.

```<code>persons = List.of( persons ) ;
</code>```

Body:
I am new to java and I am stuck at one place.
I am taking xml request which is coming in array.

<PassengersDetails>
 <Passenger>
  <passesngerName>ABC</passesngerName>
  <passengerAge>25</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>DEF</passesngerName>
  <passengerAge>28</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>GHI</passesngerName>
  <passengerAge>48</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>KLM</passesngerName>
  <passengerAge>18</passengerAge>
 </Passenger>
</PassengersDetails>

My xml object is getting turned into array like below.

Passenger [] passenger= passengersDetails.getPassenger();

And my java object looks like

class Passenger {
passengerName1;
passengerAge1;
passengerName2;
passengerAge2;
passengerName3;
passengerAge3;
passengerName4;
passengerAge4;
}

with setter and getter.

I wanted to set all the data from array in java object.
I am able to set it individually after checking if array is preset or not.

if(arr[0] != null){
setPassengerName1 = arr[0].getPassengerName;
setPassengerAge1 = arr[0].getPassengerAge;
}
if(arr[1] != null){
setPassengerName2 = arr[1].getPassengerName;
setPassengerAge2 = arr[1].getPassengerAge;
}....

How can I set passenger array into Passenger java object mentioned above.

But I wanted to know if there is any other way we can do this dynamically.

Something like in the same loop and setting it dynamically.

Body:
But I wanted to know if there is any other way we can do this dynamically as we can get 0 or max 4 passenger elements in array.

Either:

Start with one size of array, such as ten. As you place objects into the elements of the array, keep count. As you reach the limits of the array, create a new bigger array. Copy over from old array to new array. Discard old array. Repeat until done.

Use a List implementation such as ArrayList.

Using a list.

List< Person > persons = new ArrayList<>() ;

Define a record class to represent each person. You can declare the record as a separate class, a nested class, or as a local class (within a method).

record Person ( String name , int age ) {}

Add each person.

Person person = new Person( "Bob" , 42 ) ;
persons.add( person ) ;

When done, you may want to make an unmodifiable list to replace the modifiable one.

persons = List.of( persons ) ;


问:
JQuery Ajax in Chrome sends GET instead of POST, but in Edge it sends correctly
The following code triggers a GET Method instead of POST.

```<code>$.ajax({type: 'POST',url: 'http://localhost:8000/DoAsync',data: {i:e},dataType: 'script'
    });
</code>```

It's happened in Chrome.

But, while I use the same code in Edge, it triggers correctly.

Don't know how to resolve it in Chrome? I've tried to clear the Cache. Also the same result.

答:
The 405 Method Not Allowed and Request Method: GET are a clear sign that the chrome browser use the default method GET.

You can try method: 'POST' instead of type: 'POST' as already mentioned by @aynber, but it would only solve the problem if you are using an old jQuery Version.

See jQuery ajax documentation for more information

'type' is an alias for 'method'. You should use 'type' if you're using versions of
jQuery prior to 1.9.0.

Body:
The following code triggers a GET Method instead of POST.

$.ajax({type: 'POST',url: 'http://localhost:8000/DoAsync',data: {i:e},dataType: 'script'
    });

It's happened in Chrome.

But, while I use the same code in Edge, it triggers correctly.

Don't know how to resolve it in Chrome? I've tried to clear the Cache. Also the same result.


问:
Create column conditioning the behavior of rows in the dataset
I would like to do something very specific. I have a vast set of data, which, in summary, looks more or less like this, with values 0, 1 and 2:

I need to create a situation variable so that it contains the value 0, 1 and 2.

The value 0 for cases that contain only 0's and 1's in the entire line.

The value 1 for the case where the value 2 appears, but at some point 1 appears before it.

The value 2 for the case where the value 2 appears, but at some point 0 appears before it.

So it's something close to:

```<code>structure(list(X1 = c(1, 1, 1, 1, 1, 1, 1, 1, 0, 1), X2 = c(1,
1, 1, 1, 0, 0, 0, 0, 0, 2), X3 = c(0, 1, 1, 1, 1, 0, 0, 1, 0,
0), X4 = c(0, 1, 1, 0, 1, 1, 0, 0, 0, 0), X5 = c(2, 1, 1, 0,
2, 1, 1, 0, 0, 0), X6 = c(2, 1, 1, 0, 2, 1, 1, 0, 0, 0), X7 = c(2,
1, 1, 1, 2, 1, 1, 2, 0, 0), X8 = c(0, 1, 1, 1, 2, 1, 2, 2, 2,
0)), class = "data.frame", row.names = c(NA, 10L))
</code>```

Body:
I would like to do something very specific. I have a vast set of data, which, in summary, looks more or less like this, with values 0, 1 and 2:

I need to create a situation variable so that it contains the value 0, 1 and 2.

The value 0 for cases that contain only 0's and 1's in the entire line.

The value 1 for the case where the value 2 appears, but at some point 1 appears before it.

The value 2 for the case where the value 2 appears, but at some point 0 appears before it.

So it's something close to:

structure(list(X1 = c(1, 1, 1, 1, 1, 1, 1, 1, 0, 1), X2 = c(1,
1, 1, 1, 0, 0, 0, 0, 0, 2), X3 = c(0, 1, 1, 1, 1, 0, 0, 1, 0,
0), X4 = c(0, 1, 1, 0, 1, 1, 0, 0, 0, 0), X5 = c(2, 1, 1, 0,
2, 1, 1, 0, 0, 0), X6 = c(2, 1, 1, 0, 2, 1, 1, 0, 0, 0), X7 = c(2,
1, 1, 1, 2, 1, 1, 2, 0, 0), X8 = c(0, 1, 1, 1, 2, 1, 2, 2, 2,
0)), class = "data.frame", row.names = c(NA, 10L))

Body:
I wrote a score function and applied it over all the rows of your dataframe.

score <- function(x) {
  a <- which(x == 2)
  ifelse(length(a) > 0, ifelse(a[1] >=2, 2 - x[a[1] - 1], 1), 0)
}

df <- structure(list(X1 = c(1, 1, 1, 1, 1, 1, 1, 1, 0, 1),
                     X2 = c(1, 1, 1, 1, 0, 0, 0, 0, 0, 2),
                     X3 = c(0, 1, 1, 1, 1, 0, 0, 1, 0, 0),
                     X4 = c(0, 1, 1, 0, 1, 1, 0, 0, 0, 0),
                     X5 = c(2, 1, 1, 0, 2, 1, 1, 0, 0, 0),
                     X6 = c(2, 1, 1, 0, 2, 1, 1, 0, 0, 0),
                     X7 = c(2, 1, 1, 1, 2, 1, 1, 2, 0, 0),
                     X8 = c(0, 1, 1, 1, 2, 1, 2, 2, 2, 0)),
                class = "data.frame", row.names = c(NA, 10L))
df$situation <- sapply(1:nrow(df), function(i) score(as.numeric(df[i,])))
df


问:
Ruby Mastermind White Pegs Count
I'm a newbie to Ruby programming. It is my second OOP project. I have trouble with counting white pegs under certain condition. And Wikipedia says that:

-A black key peg is placed for each code peg from the guess which is correct in both colour and position.

-A white key peg indicates the
existence of a correct colour code peg placed in the wrong position.

I believe that my black peg condition is true, but I can not count my white pegs correctly.
Here is the function code piece:

def check_guess(code, guess)
    @white_peg = 0
    @black_peg = 0
    index = 0
    while index  #{@black_peg}"
      elsif guess.any? { |c| code.include?(c) } && code[index] != guess[index]
        @white_peg += 1
        puts "White => #{@white_peg}"
      end
      index += 1
    end
    puts "There are #{@white_peg} white peg and #{@black_peg} black peg"
    is_win?
  end
end
```
<p>I'm invoking above function inside this condition</p>
<pre class="lang-rb prettyprint-override"><code>  def codebreaker_attempt
    guess_array = @codebreaker.guess_code
     @codebreaker.check_guess(@codemaker.code, guess_array)
  end
</code>```

And lastly my game method is here for stop the game

def play
    codemaker_choose
    (1..12).each do |i|
      puts "#{i}. GUESS\n"
     #puts "Guess array is #{guess}"
      break if codebreaker_attempt == true
    end
```

I'm leaving here repl.it repo of all my codes if you want to inspect.
https://replit.com/@Burakkepuc/Mastermind#main.rb

答:
-A white key peg indicates the existence of a correct colour code peg placed in the wrong position

I found my answer. The white peg code control should be

      elsif code.include?(guess[index]) && code[index] != guess[index]
```

Title: Ruby Mastermind White Pegs Count

Body:
I'm a newbie to Ruby programming. It is my second OOP project. I have trouble with counting white pegs under certain condition. And Wikipedia says that:

-A black key peg is placed for each code peg from the guess which is correct in both colour and position.

-A white key peg indicates the
existence of a correct colour code peg placed in the wrong position.

I believe that my black peg condition is true, but I can not count my white pegs correctly.
Here is the function code piece:

def check_guess(code, guess)
    @white_peg = 0
    @black_peg = 0
    index = 0
    while index  #{@black_peg}"
      elsif guess.any? { |c| code.include?(c) } && code[index] != guess[index]
        @white_peg += 1
        puts "White => #{@white_peg}"
      end
      index += 1
    end
    puts "There are #{@white_peg} white peg and #{@black_peg} black peg"
    is_win?
  end
end

I'm invoking above function inside this condition

  def codebreaker_attempt
    guess_array = @codebreaker.guess_code
     @codebreaker.check_guess(@codemaker.code, guess_array)
  end

And lastly my game method is here for stop the game

def play
    codemaker_choose
    (1..12).each do |i|
      puts "#{i}. GUESS\n"
     #puts "Guess array is #{guess}"
      break if codebreaker_attempt == true
    end

I'm leaving here repl.it repo of all my codes if you want to inspect.
https://replit.com/@Burakkepuc/Mastermind#main.rb


问:
Django why getting MultiValueDictKeyError?
here is my code:

```<code> if request.method == "POST":
       forms = GoogleAuthFroms(request.POST or None)
       if forms.is_valid():
            code = request.POST["auth_code"]

    context = {

        'forms':forms,

    }
    return render(request,'members/security.html',context)
</code>```

This line of code code = request.POST["auth_code"] throwing this error MultiValueDictKeyError at /security/ 'auth_code'

答:
If the code field is already in the form there's no need in repeating it,  in your post request.POST and also you don't put a request.POST (code = request.POST["auth_code"] ) right below the form validation condition test.</p>
```<code>def some_view(request):
    if request.method == "POST":
        forms = GoogleAuthFroms(request.POST or None)
        code = request.POST.get("auth_code")
        if forms.is_valid():
            forms.save()
            return redirect(...)#You will need to redirect to a url after the form is validated and save
        else:
            forms = GoogleAuthFroms()
    context = {
        'forms':forms,
    }
    return render(request,'members/security.html',context)
</code>```

Body:
here is my code:

 if request.method == "POST":
       forms = GoogleAuthFroms(request.POST or None)
       if forms.is_valid():
            code = request.POST["auth_code"]

    context = {

        'forms':forms,

    }
    return render(request,'members/security.html',context)

This line of code code = request.POST["auth_code"] throwing this error MultiValueDictKeyError at /security/ 'auth_code'

Body:
If the code field is already in the form there's no need in repeating it,  in your post request.POST and also you don't put a request.POST (code = request.POST["auth_code"] ) right below the form validation condition test.

def some_view(request):
    if request.method == "POST":
        forms = GoogleAuthFroms(request.POST or None)
        code = request.POST.get("auth_code")
        if forms.is_valid():
            forms.save()
            return redirect(...)#You will need to redirect to a url after the form is validated and save
        else:
            forms = GoogleAuthFroms()
    context = {
        'forms':forms,
    }
    return render(request,'members/security.html',context)


问:
Git rebase a branch on another after parent branch is merged to master
If I have branch_1 forked out of master with let's say 2 commits.

Next, I made branch_2 forked out of branch_1.

On branch_2 I have made changes which are not in the area branch_1. I of course have changes from branch_1 included here but I have not touched those changes.

Now let's say branch_1 merges into master.

Next, on branch_2 I do git pull upstream master --rebase to rebase branch_2 on top of master so that commits from branch_1 disappear from commit history of branch_2. I should not get merge conflicts here. Right? But I do in the same lines of code which were changed on branch_1. This is strange! Is this expected?

答:
I have reproduced your situation like in the first image below.

Notice here I have the following naming :

master ==> main

branch_1 ==> br1

branch_2 ==> br2

And the br1 is merged into main

And the head is at the main branch (*)

To rebase br2 into main, you should :

```<code>git checkout br2
git rebase main
</code>```

Body:
I have reproduced your situation like in the first image below.

Notice here I have the following naming :

master ==> main

branch_1 ==> br1

branch_2 ==> br2

And the br1 is merged into main

And the head is at the main branch (*)

To rebase br2 into main, you should :

git checkout br2
git rebase main


问:
Workaround for accessing non-static property in a static context for Validation C#
Let's say I have the class Wallet:

```<code>public class Wallet
{
       public double Min { get; set; }

       public double Max { get; set; }

       public double Value { get; set; }
}
</code>```

And let's say that the data is read from a database.

The user is able to modify Value from the UI.

I want to validate it somehow, so my initial thought was:

```<code>[Range(Min, Max, ErrorMessage = "The value is outside of bounds.")]
public double Value { get; set; }
</code>```

But an error is thrown: Cannot access non-static property in a static context attribute.

Is there a workaround or do I have to create a custom validation?

Context: WPF MVVM application, C#

答: You could move that validation to the setter, and throw the exact validation exception that the attribute class throws if any validation erros occur.</p>

Body:
Let's say I have the class Wallet:

public class Wallet
{
       public double Min { get; set; }

       public double Max { get; set; }

       public double Value { get; set; }
}

And let's say that the data is read from a database.

The user is able to modify Value from the UI.

I want to validate it somehow, so my initial thought was:

[Range(Min, Max, ErrorMessage = "The value is outside of bounds.")]
public double Value { get; set; }

But an error is thrown: Cannot access non-static property in a static context attribute.

Is there a workaround or do I have to create a custom validation?

Context: WPF MVVM application, C#


问:
No keyword with name 'Select Window' found
```<code>*** Settings ***
Library     Selenium2Library

*** Variable ***
${handles}

*** Test Case ***
Testing
    open browser    https://www.reddit.com/   chrome
    Execute Javascript    window.open('https://www.google.com')
    Execute Javascript    window.open('https://www.yahoo.com')
    Execute Javascript    window.open('https://images.google.com')

    ${handles}=     Get Window Handles

    Set Global Variable     ${handles}
    FOR     ${rowIndex}     IN RANGE    1   18
        Select Window   ${handles}[${rowIndex}]
    END
</code>```

Select Window Statement is not working. Please help.
*I have tried SeleniumLibrary as well. But, I am getting the same error.

答:
I have a set where for some tests I use the 'SeleniumLibrary' and others 'Browser'

https://robotframework-browser.org/

this case you might try the latter.

Body:
*** Settings ***
Library     Selenium2Library

*** Variable ***
${handles}

*** Test Case ***
Testing
    open browser    https://www.reddit.com/   chrome
    Execute Javascript    window.open('https://www.google.com')
    Execute Javascript    window.open('https://www.yahoo.com')
    Execute Javascript    window.open('https://images.google.com')

    ${handles}=     Get Window Handles

    Set Global Variable     ${handles}
    FOR     ${rowIndex}     IN RANGE    1   18
        Select Window   ${handles}[${rowIndex}]
    END

Select Window Statement is not working. Please help.
*I have tried SeleniumLibrary as well. But, I am getting the same error.


问:
PHP: Buy both and save $50?
OK my client wants to show a buy both feature in the cart, if they have 1 particular item type in the cart they want it to show up for another particular item type so if they buy both they can save $50 off the total. I am trying to wrap my head around what would be the best way to set this up so it couldn't be easily hacked (ie: adding both to the cart then removing one and keeping the discount)

does anyone have some general ideas in theory?

Thanks.

答: Add the discount to the cart and use another table to keep track of the discount's dependencies. Whenever an item is removed from the cart, check to make sure the discount is still valid. If it is, great. If not, remove it and recalculate the cart price.</p>

OwnerDisplayName: John Isaacks

Title: PHP: Buy both and save $50?

OwnerDisplayName: geetee


问:
Why do we usually use || over |? What is the difference?
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

```<code>if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
</code>```

```<code>if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass
</code>```

Can we use | instead of ||? Same thing with & and &&.

答:
The operators || and && are called conditional operators, while | and & are called bitwise operators. They serve different purposes.

Conditional operators works only with expressions that statically evaluate to boolean on both left- and right-hand sides.

Bitwise operators works with any numeric operands.

If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.

Body:
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass

if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.


问:
Equivalent tensorflow expression to numpy mask
I have a numpy array named PixelData of unknown shape, and I am using the following condition to filter values in the array greater than some value x using a mask:

```<code>PixelData[PixelData>=x] = PixelData[PixelData>=x] - x
</code>```

When I convert this numpy array to a tensor, I cannot perform the same masking operation. I have tried using tf.where as follows:

```<code>PixelData = tf.where(PixelData>=x, PixelData - x, PixelData)
</code>```

In the official documentation, they always seem to define the mask dimensions in advance to equal the dimensions of the tensor being masked, but then they talk about the dimensions being broadcasted automatically, so I am a bit confused. Are these two functions equivalent? Are there any situations where they may produce different outputs?

答:
Not sure what PixelData looks like, but here is working example with both methods:

import numpy as np
import tensorflow as tf

x = 2
np_pixel_data = np.array([[3, 4, 5, 1],
                       [6, 4, 2, 5]], dtype=np.float32)

np_pixel_data[np_pixel_data>=x] = np_pixel_data[np_pixel_data>=x] - x

tf_pixel_data = tf.constant([[3, 4, 5, 1],
                       [6, 4, 2, 5]], dtype=tf.float32)

tf_pixel_data = tf.where(tf.greater_equal(tf_pixel_data, x), tf_pixel_data - x, tf_pixel_data)

print(np_pixel_data)
print(tf_pixel_data)
```
```[[1. 2. 3. 1.]
 [4. 2. 0. 3.]]
tf.Tensor(
[[1. 2. 3. 1.]
 [4. 2. 0. 3.]], shape=(2, 4), dtype=float32)
```

You might have some minor rounding differences, but nothing significant.

Body:
I have a numpy array named PixelData of unknown shape, and I am using the following condition to filter values in the array greater than some value x using a mask:

PixelData[PixelData>=x] = PixelData[PixelData>=x] - x

When I convert this numpy array to a tensor, I cannot perform the same masking operation. I have tried using tf.where as follows:

PixelData = tf.where(PixelData>=x, PixelData - x, PixelData)

In the official documentation, they always seem to define the mask dimensions in advance to equal the dimensions of the tensor being masked, but then they talk about the dimensions being broadcasted automatically, so I am a bit confused. Are these two functions equivalent? Are there any situations where they may produce different outputs?

Body:
Not sure what PixelData looks like, but here is working example with both methods:

import numpy as np
import tensorflow as tf

x = 2
np_pixel_data = np.array([[3, 4, 5, 1],
                       [6, 4, 2, 5]], dtype=np.float32)

np_pixel_data[np_pixel_data>=x] = np_pixel_data[np_pixel_data>=x] - x

tf_pixel_data = tf.constant([[3, 4, 5, 1],
                       [6, 4, 2, 5]], dtype=tf.float32)

tf_pixel_data = tf.where(tf.greater_equal(tf_pixel_data, x), tf_pixel_data - x, tf_pixel_data)

print(np_pixel_data)
print(tf_pixel_data)

[[1. 2. 3. 1.]
 [4. 2. 0. 3.]]
tf.Tensor(
[[1. 2. 3. 1.]
 [4. 2. 0. 3.]], shape=(2, 4), dtype=float32)

You might have some minor rounding differences, but nothing significant.


答:
My feeling is there's no need to look for Rare values.
Extract the column name from tdf to lookup in cdf. After, flatten your cdf dataframe to extract the right values:

```<code>r = tdf.set_index('Id')['feature'].str.split('=').str[0].str.lower()

tdf['feature'] = r.values + '=' + cdf.set_index('Id').unstack() \
                                     .loc[zip(r.values, r.index)] \
                                     .astype(str).values
</code>```

Output:

```<code>>>> tdf
   Id     feature  value
0   1     grade=D   0.20
1   1      dash=Q   0.45
2   1  dumma=1123  -0.32
3   1    dumeel=R   0.56
4   3      dash=P   1.30
5   3   dumma=849   1.50
6   3     grade=A   3.70

>>> r
Id           # <- the index is the row of cdf
1     grade  # <- the values are the column of cdf
1      dash
1     dumma
1    dumeel
3      dash
3     dumma
3     grade
Name: feature, dtype: object
</code>```

Title: How to decode column value from rare label by matching column names

Body:
My feeling is there's no need to look for Rare values.
Extract the column name from tdf to lookup in cdf. After, flatten your cdf dataframe to extract the right values:

r = tdf.set_index('Id')['feature'].str.split('=').str[0].str.lower()

tdf['feature'] = r.values + '=' + cdf.set_index('Id').unstack() \
                                     .loc[zip(r.values, r.index)] \
                                     .astype(str).values

Output:

>>> tdf
   Id     feature  value
0   1     grade=D   0.20
1   1      dash=Q   0.45
2   1  dumma=1123  -0.32
3   1    dumeel=R   0.56
4   3      dash=P   1.30
5   3   dumma=849   1.50
6   3     grade=A   3.70

>>> r
Id           # <- the index is the row of cdf
1     grade  # <- the values are the column of cdf
1      dash
1     dumma
1    dumeel
3      dash
3     dumma
3     grade
Name: feature, dtype: object