问:
How to type a text in imgeview. Right now sucessfully drawing using mouse
How  to type a text in imgeview... right now successfully drawing using mouse. I need to type text in same image view using keyboard... </p>

答:
Try superimposing a UITextView on top of your UIImageView and set appropriate frames for both so that the text appears until where you want it to appear.

Set this property for your UITextView

```<code>myTextView.backgroundColor = [UIColor clearColor];
myTextView.textColor = [UIColor redColor]; //or whatever color you like based on the background image in your UIImageView.
</code>```

Of course you will have to take care of the scrolling when the keyboard comes up after the UITextView becomes active.

If you want more assistance, please elaborate upon your question and your need.

Body:
Try superimposing a UITextView on top of your UIImageView and set appropriate frames for both so that the text appears until where you want it to appear.

Set this property for your UITextView

myTextView.backgroundColor = [UIColor clearColor];
myTextView.textColor = [UIColor redColor]; //or whatever color you like based on the background image in your UIImageView.

Of course you will have to take care of the scrolling when the keyboard comes up after the UITextView becomes active.

If you want more assistance, please elaborate upon your question and your need.


来源: stackexchange

问:
get IP address and email id when receiver open the email
I am using php mail() function. but i want that when receiver open email, his/her IP address and email id will save in my db table.

my mail function codes are-

```<code><?php
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();

// ---------- adjust these lines ---------------------------------------
$mail->Username = "mymail@gmail.com"; // your GMail user name
$mail->Password = "";
$mail->AddAddress("$userid"); // recipients email
$mail->FromName = "Nikhil Garg"; // readable name

$mail->Subject = "Newletter Subscription";
$mail->Body    = "$usermsg";
//-----------------------------------------------------------------------

$mail->SMTPSecure = "ssl";
$mail->Host='smtp.gmail.com';
$mail->Port = 465;
$mail->IsSMTP(); // use SMTP
$mail->SMTPKeepAlive = true;
$mail->Mailer = "smtp";
$mail->CharSet = 'utf-8';
$mail->SMTPDebug  = 0;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->From = $mail->Username;
if(!$mail->Send())
    echo "Mailer Error: " . $mail->ErrorInfo;
else
    echo "Message has been sent";
 }
 ?>
</code>```

They are working well. but i don't understand how to get receiver IP address and email Id when they open this email.

Actually i have more then 5000 email list and i want to sort them by city, state, country. with ip address, i can do that. if you know any other way please suggest

my goal is simple and genuine. I just want to know their country so that i will send emails according their country occasions for better selling results. for sending emails to more then 5000 users and ask them for details is not right way.

答: We can host tracking code in our c panel and generate one image link. Whenever image load into the email body it triggers the code and we can collect email id, ip address and time in csv file. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am using php mail() function. but i want that when receiver open email, his/her IP address and email id will save in my db table.

my mail function codes are-

<?php
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();

// ---------- adjust these lines ---------------------------------------
$mail->Username = "mymail@gmail.com"; // your GMail user name
$mail->Password = "";
$mail->AddAddress("$userid"); // recipients email
$mail->FromName = "Nikhil Garg"; // readable name

$mail->Subject = "Newletter Subscription";
$mail->Body    = "$usermsg";
//-----------------------------------------------------------------------

$mail->SMTPSecure = "ssl";
$mail->Host='smtp.gmail.com';
$mail->Port = 465;
$mail->IsSMTP(); // use SMTP
$mail->SMTPKeepAlive = true;
$mail->Mailer = "smtp";
$mail->CharSet = 'utf-8';
$mail->SMTPDebug  = 0;
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->From = $mail->Username;
if(!$mail->Send())
    echo "Mailer Error: " . $mail->ErrorInfo;
else
    echo "Message has been sent";
 }
 ?>

They are working well. but i don't understand how to get receiver IP address and email Id when they open this email.

Actually i have more then 5000 email list and i want to sort them by city, state, country. with ip address, i can do that. if you know any other way please suggest

my goal is simple and genuine. I just want to know their country so that i will send emails according their country occasions for better selling results. for sending emails to more then 5000 users and ask them for details is not right way.

ContentLicense: CC BY-SA 4.0


问:
Kalman Filter - Fusion of two equal sensors
I'm interested in implementing a Kalman Filter in Python. First, I have programmed a very simple version of a K-Filter - only one state (Position in Y-Direction).
My State transition Matrix looks like:

```<code>X <- X + v * t
</code>```

with v and t are constants.

I simulate the measurement with a simple linear function

```<code>y = mx + b
</code>```

and add noise to it:

```<code>y1 = np.random.normal(y, sigma, Nsamples).
</code>```

It works pretty well, I can redefine R and Q to change the measurement and process noise value (Until now, it isn't a matrix).

Now I have an idea...

What happens if I would have a second measurement?

```<code>    y2 = np.random.normal(y, sigma2, Nsamples)
</code>```

How could I handle it? Shall I prefilter measurement like :

```<code>(y1 + y2) / 2
</code>```

or is there a more suitable method/solution which involves the kalman filter?

答:
There are numerous ways to handle fusion of multiple sensor measurements using Kalman Filter. A way to do it would be sequentially updating the Kalman Filter with new measurements.

See the slides by sensor fusion pioneer Hugh Durrant-Whyte found in this answer for quite a few ways how to fuse sensor data.

Body:
I'm interested in implementing a Kalman Filter in Python. First, I have programmed a very simple version of a K-Filter - only one state (Position in Y-Direction).
My State transition Matrix looks like:

X <- X + v * t

with v and t are constants.

I simulate the measurement with a simple linear function

y = mx + b

and add noise to it:

y1 = np.random.normal(y, sigma, Nsamples).

It works pretty well, I can redefine R and Q to change the measurement and process noise value (Until now, it isn't a matrix).

Now I have an idea...

What happens if I would have a second measurement?

    y2 = np.random.normal(y, sigma2, Nsamples)

How could I handle it? Shall I prefilter measurement like :

(y1 + y2) / 2

or is there a more suitable method/solution which involves the kalman filter?


问:
How can I copy CTRL-C content from a single cell in DBISQL?
I use DBISQL on Win32 on 12.0.1.3769.

Usually, I am interested in copying cell content from the Result pane of DBISQL, not the contents of the complete row or the row headers.

I can do this by using the context menu and choose "copy data / cell" (I use a localised version, the English words may be different). But I would certainly like to use CTRL-C to copy only the contents of selected cells. As stated, however, CTRL-C copies the full row(s) including the header of the column. And all too often I try to insert a single number in a particular window, then insert an entire database unintentionally instead...

Question: Can I use another shortcut or is there a choice in the result pane to change the meaning of CTRL-C?

答:
It looks like Ctrl-C maps to Copy Data Rows effectively, while you (and I!!!) would like to MALL map it to Copy Data-Columns, as defined here: copying columns, rows and cells in an Interactive SQL result collection.

The complete list of Interactive SQL Keyboard Shortcuts dates back to 1985... However, even then, cool children's software allows you to change the key tasks (hint, hint:)

Thank you, Volker, for noting how Really Annoying Ctrl-C is [ end sarcasm alert ] ... [ sarcasm alert ] Until now it had been only one of the little irritants of your life such as an alarm that went away before you finished sleeping.


问:
How to output CDATA using yattag library
I'm trying with the following code to generate an XML file contains tags </documents>.

```<code>string = "dasdd Wonder asdf new single, “Tomorrow” #URL# | " \
    "oiojk asfddsf releases new asdfdf, “gfsg” | " \
    "Identity of asfqw who dasd off asdfsdf Mainland jtyjyjui revealed #URL#"

from yattag import Doc, indent
import html, re

doc, tag, text = Doc().tagtext()
with tag('author', lang='en'):
    with tag('documents'):
        for tweet in string.split(' | '):
            with tag('document'):
                tweet = html.unescape(tweet)
                text('<![CDATA[{}]]'.format(tweet))
result = indent(doc.getvalue(), indentation=' ' * 4, newline='\n')
with open('test.xml', 'w', encoding='utf-8') as f:
    f.write(result)
</code>```

I wanted to add CDATA token around the text, but when I open the generated file using Notepad++ instead of have the output as:

```<code><document><![CDATA[oiojk asfddsf releases new asdfdf, “gfsg”]]></document>
</code>```

it appears like (with HTML entities):

```<code><document><![CDATA[oiojk asfddsf releases new asdfdf, “gfsg”]]</document>
</code>```

I tried to use HTML library (html.unescape line) to discard the HTML entities but I wasn't able.

How can I solve this encoding issue?

答:
The text method always replaces '<' with <. If you wanted no escaping of that kind, you would use the asis method instead (it inserts the string "as is"). But, in your case, it would be more appropriate to use Yattag's cdata method.

```<code>from yattag import Doc
help(Doc.cdata)
</code>```

cdata(self, strg, safe=False) appends a CDATA section containing the supplied string.

You don't have to worry about potential ]]> sequences that would terminate
    the CDATA section. They are replaced with ]]]]><![CDATA[>.

If you're sure your string does not contain ]]>, you can pass safe = True.
If you do that, your string won't be searched for ]]> sequences.

So, in your case, you can do:

```<code>for tweet in string.split(' | '):
    with tag('document'):
        tweet = html.unescape(tweet)
        doc.cdata(tweet)
</code>```

Body:
I'm trying with the following code to generate an XML file contains tags </documents>.

string = "dasdd Wonder asdf new single, “Tomorrow” #URL# | " \
    "oiojk asfddsf releases new asdfdf, “gfsg” | " \
    "Identity of asfqw who dasd off asdfsdf Mainland jtyjyjui revealed #URL#"

from yattag import Doc, indent
import html, re

doc, tag, text = Doc().tagtext()
with tag('author', lang='en'):
    with tag('documents'):
        for tweet in string.split(' | '):
            with tag('document'):
                tweet = html.unescape(tweet)
                text('<![CDATA[{}]]'.format(tweet))
result = indent(doc.getvalue(), indentation=' ' * 4, newline='\n')
with open('test.xml', 'w', encoding='utf-8') as f:
    f.write(result)

I wanted to add CDATA token around the text, but when I open the generated file using Notepad++ instead of have the output as:

<document><![CDATA[oiojk asfddsf releases new asdfdf, “gfsg”]]></document>

it appears like (with HTML entities):

<document><![CDATA[oiojk asfddsf releases new asdfdf, “gfsg”]]</document>

I tried to use HTML library (html.unescape line) to discard the HTML entities but I wasn't able.

How can I solve this encoding issue?

Body:
The text method always replaces '<' with &lt;. If you wanted no escaping of that kind, you would use the asis method instead (it inserts the string "as is"). But, in your case, it would be more appropriate to use Yattag's cdata method.

from yattag import Doc
help(Doc.cdata)

cdata(self, strg, safe=False) appends a CDATA section containing the supplied string.

You don't have to worry about potential ]]> sequences that would terminate
    the CDATA section. They are replaced with ]]]]><![CDATA[>.

If you're sure your string does not contain ]]>, you can pass safe = True.
If you do that, your string won't be searched for ]]> sequences.

So, in your case, you can do:

for tweet in string.split(' | '):
    with tag('document'):
        tweet = html.unescape(tweet)
        doc.cdata(tweet)


问:
PowerShell: How to set culture?
I tried to Set-Culture -CultureInfo vi-VN but Powershell was not changed to my setted Culture.

I tested by open Powershell ISE and seen my setted Culture was changed successful.

How to make Powershell changes to my setted Culture?

答:
Assuming you've started a new session (see below):

You may have run into a Windows PowerShell bug, present as of v5.1.18362.628):

Changing to culture vi-VN (Vietnamese (Vietnam), LCID 1066), specifically[1], doesn't seem to work in Windows PowerShell (v5.1-) in console windows[2] (whereas it does work in the obsolescent PowerShell ISE, as you state).

Note: The change does take effect for the current user account in general, but not in Windows PowerShell console windows.

PowerShell [Core] 6+ is not affected.

As for a potential fix: Windows PowerShell is no longer in active development, so only critical fixes are being implemented.
You can report Windows PowerShell bugs in the relevant UserVoice forum.

Generally speaking:

Set-Culture persistently changes the current user's culture system-wide.

This only takes effect in future PowerShell sessions (processes), so you'll have to open a new PowerShell console window, for instance, for the change to take effect.

As of this writing, the Set-Culture help topic doesn't mention this requirement; fixing that is being suggested in this GitHub issue.

However, the taskbar's notification area will instantly reflect the new culture in its date and time display, and paying attention to that provides instant feedback as to whether the call succeeded in principle; e.g., if you run Set-Culture fr-FR (French), the date and time changes to something like this ("jeudi" is French for Thursday):

To start a new session, do one of the following:

Open a new PowerShell console window.

In Windows Terminal, open a new PowerShell tab.

In Visual Studio Code with the PowerShell extension installed, terminate the PowerShell Integrated Console as shown below and opt to restart it when prompted (alternatively, start a new regular (non-integrated) PowerShell instance in the integrated terminal).

In the - obsolescent - ISE, open a new PowerShell tab (File > New PowerShell Tab, Ctrl-T).

While a change is pending, i.e. before you've started a new session, Get-Culture reports the still effective (old) value, not the pending one.

You need to pass the name of a predefined specific culture as the (implied) -CultureInfo argument.

A specific culture has a name such as fr-FR, where fr designates the language (French) and FR the location (region or country); by contrast, a language-only culture name such as fr is not supported and quietly ignored.

To get the list of predefined specific cultures, run the following command or, for Windows only, consult this documentation:

[cultureinfo]::GetCultures('SpecificCultures')

[1] Not sure if other cultures are affected as well.

[2] Running in Windows Terminal doesn't help either. This suggests that the bug is inside the ConsoleHost PowerShell host inside of which console-based PowerShell sessions run (whereas the ISE implements its own host, Windows PowerShell ISE Host), as reflected in $HOST.

Title: PowerShell: How to set culture?


问:
Scrape a span text from multiple span elements of same name (IMDB)
```<code>for year_url in years_url:

    # For every page in the interval 1-4
    for page in pages:

        # Make a get request
        response = requests.get('http://www.imdb.com/search/title?release_date=' + year_url +
        '&sort=num_votes,desc&page=' + page)

        # Parse the content of the request with BeautifulSoup
        page_html = BeautifulSoup(response.text, 'lxml')

        # Select all the 50 movie containers from a single page
        mv_containers = page_html.find_all('div', class_ = 'lister-item mode-advanced')

        # For every movie of these 50
        for container in mv_containers:
            # If the movie has a Metascore, then:
            if container.find('div', class_ = 'ratings-metascore') is not None:

                # Scrape the name
                name = container.h3.a.text
                names.append(name)

                # Scrape the genre
                genre = container.p.find('span', class_ = 'genre').text.rstrip().replace("\n","").split(",")
                genres.append(genre)

                # Scrape the runtime
                runtime = container.p.find('span', class_ = 'runtime').text
                runtimes.append(runtime)

                # Scrape the year
                year = container.h3.find('span', class_ = 'lister-item-year').text
                years.append(year)

                # Scrape the IMDB rating
                imdb = float(container.strong.text)
                imdb_ratings.append(imdb)

                # Scrape the Metascore
                m_score = container.find('span', class_ = 'metascore').text
                metascores.append(int(m_score))

                # Scrape the number of votes
                vote = container.find('span', attrs = {'name':'nv'})['data-value']
                votes.append(int(vote))

                # Scrape the GrossMill
                gross = int(container.find('span', text='Gross:').find_next('span')['data-value'].replace(',', ''))
                print(gross)
                grossmill.append(gross)
</code>```

I am not able to create gross collection data from the above url
vote and gross has same attrs so i am finding difficult to extract gross data from the link mentioned below. how ever i am able to extract vote count.
the link to url = "https://www.imdb.com/search/title/?release_date=2019&sort=num_votes,desc&page=1"

答:
Your error means that for a given movie, there was no span found with text='Gross'. As I can see from the IMDB webpage you are scraping, it happens that some movies, while they have a Metascore, do not have their gross displayed. It is the case for movie 1917.

You should first check for gross' existence, before calling it using method find_next().

Replace:

```<code>gross = int(container.find('span', text='Gross:').find_next('span')['data-value'].replace(',', ''))
</code>```

by:

```<code>gross = container.find('span', text='Gross:')
if gross:
    gross = int(gross.find_next('span')['data-value'].replace(',', ''))
</code>```

Body:
for year_url in years_url:

    # For every page in the interval 1-4
    for page in pages:

        # Make a get request
        response = requests.get('http://www.imdb.com/search/title?release_date=' + year_url +
        '&sort=num_votes,desc&page=' + page)

        # Parse the content of the request with BeautifulSoup
        page_html = BeautifulSoup(response.text, 'lxml')

        # Select all the 50 movie containers from a single page
        mv_containers = page_html.find_all('div', class_ = 'lister-item mode-advanced')

        # For every movie of these 50
        for container in mv_containers:
            # If the movie has a Metascore, then:
            if container.find('div', class_ = 'ratings-metascore') is not None:

                # Scrape the name
                name = container.h3.a.text
                names.append(name)

                # Scrape the genre
                genre = container.p.find('span', class_ = 'genre').text.rstrip().replace("\n","").split(",")
                genres.append(genre)

                # Scrape the runtime
                runtime = container.p.find('span', class_ = 'runtime').text
                runtimes.append(runtime)

                # Scrape the year
                year = container.h3.find('span', class_ = 'lister-item-year').text
                years.append(year)

                # Scrape the IMDB rating
                imdb = float(container.strong.text)
                imdb_ratings.append(imdb)

                # Scrape the Metascore
                m_score = container.find('span', class_ = 'metascore').text
                metascores.append(int(m_score))

                # Scrape the number of votes
                vote = container.find('span', attrs = {'name':'nv'})['data-value']
                votes.append(int(vote))

                # Scrape the GrossMill
                gross = int(container.find('span', text='Gross:').find_next('span')['data-value'].replace(',', ''))
                print(gross)
                grossmill.append(gross)

I am not able to create gross collection data from the above url
vote and gross has same attrs so i am finding difficult to extract gross data from the link mentioned below. how ever i am able to extract vote count.
the link to url = "https://www.imdb.com/search/title/?release_date=2019&sort=num_votes,desc&page=1"

Body:
Your error means that for a given movie, there was no span found with text='Gross'. As I can see from the IMDB webpage you are scraping, it happens that some movies, while they have a Metascore, do not have their gross displayed. It is the case for movie 1917.

You should first check for gross' existence, before calling it using method find_next().

Replace:

gross = int(container.find('span', text='Gross:').find_next('span')['data-value'].replace(',', ''))

by:

gross = container.find('span', text='Gross:')
if gross:
    gross = int(gross.find_next('span')['data-value'].replace(',', ''))


问:
Split list of objects into multiple lists of fields values using Java streams
Let's say I have such object:

```<code>public class Customer {

    private Integer id;
    private String country;
    private Integer customerId;
    private String name;
    private String surname;
    private Date dateOfBirth;
}
</code>```

and I have a List<Customer>. I would like to split such list with Java streams so that I would get a list of ids List<Integer>, countries List<String>, customerIds List<Integer> etc.

I know that I could do it as simple as making 6 streams such as:

```<code>List<Integer> idsList = customerList.stream()
        .map(Customer::getId)
        .collect(Collectors.toList());
</code>```

but doing it that many times that I have fields seems pretty dull. I was thinking about custom Collector but I could not come up with anything useful that would be both neat and efficient.

答:
For a type safe solution, you’d need to define a class holding the desired results. This type may also provide the necessary methods for adding another Customer or partial result:

```<code>public class CustomerProperties {
    private List<Integer> id = new ArrayList<>();
    private List<String> country = new ArrayList<>();
    private List<Integer> customerId = new ArrayList<>();
    private List<String> name = new ArrayList<>();
    private List<String> surname = new ArrayList<>();
    private List<Date> dateOfBirth = new ArrayList<>();

    public void add(Customer c) {
        id.add(c.getId());
        country.add(c.getCountry());
        customerId.add(c.getCustomerId());
        name.add(c.getName());
        surname.add(c.getSurname());
        dateOfBirth.add(c.getDateOfBirth());
    }
    public void add(CustomerProperties c) {
        id.addAll(c.id);
        country.addAll(c.country);
        customerId.addAll(c.customerId);
        name.addAll(c.name);
        surname.addAll(c.surname);
        dateOfBirth.addAll(c.dateOfBirth);
    }
}
</code>```

Then, you can collect all results like

```<code>CustomerProperties all = customers.stream()
    .collect(CustomerProperties::new, CustomerProperties::add, CustomerProperties::add);
</code>```

Body:
Let's say I have such object:

public class Customer {

    private Integer id;
    private String country;
    private Integer customerId;
    private String name;
    private String surname;
    private Date dateOfBirth;
}

and I have a List<Customer>. I would like to split such list with Java streams so that I would get a list of ids List<Integer>, countries List<String>, customerIds List<Integer> etc.

I know that I could do it as simple as making 6 streams such as:

List<Integer> idsList = customerList.stream()
        .map(Customer::getId)
        .collect(Collectors.toList());

but doing it that many times that I have fields seems pretty dull. I was thinking about custom Collector but I could not come up with anything useful that would be both neat and efficient.

Body:
For a type safe solution, you’d need to define a class holding the desired results. This type may also provide the necessary methods for adding another Customer or partial result:

public class CustomerProperties {
    private List<Integer> id = new ArrayList<>();
    private List<String> country = new ArrayList<>();
    private List<Integer> customerId = new ArrayList<>();
    private List<String> name = new ArrayList<>();
    private List<String> surname = new ArrayList<>();
    private List<Date> dateOfBirth = new ArrayList<>();

    public void add(Customer c) {
        id.add(c.getId());
        country.add(c.getCountry());
        customerId.add(c.getCustomerId());
        name.add(c.getName());
        surname.add(c.getSurname());
        dateOfBirth.add(c.getDateOfBirth());
    }
    public void add(CustomerProperties c) {
        id.addAll(c.id);
        country.addAll(c.country);
        customerId.addAll(c.customerId);
        name.addAll(c.name);
        surname.addAll(c.surname);
        dateOfBirth.addAll(c.dateOfBirth);
    }
}

Then, you can collect all results like

CustomerProperties all = customers.stream()
    .collect(CustomerProperties::new, CustomerProperties::add, CustomerProperties::add);


问:
Why is JToken method causing a file-not-found error?
I'm calling JToken.FromObject() and it is throwing:

Could not load file or assembly 'System.ComponentModel.Annotations, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified

This is an Azure Function based on .Net Core 2.1 using Newtonsoft JSON 12.0.3

It is failing on my dev PC

Any ideas how to fix this, please?

答: Updating the Azure function project to core 3.1 solved the problem...</p>


问:
How can I use C++ class in Python?
I have implemented a class in C++. I want to use it with Python.
Please suggest step by step method and elaborate each step.
Somthing like this...

```<code>class Test{
     private:
        int n;
     public:
        Test(int k){
            n=k;
        }
        void setInt(int k){
            n = k;
        }
        int getInt(){
            return n;
        }
};
</code>```

Now, in Python

```<code>>>> T1 = Test(12)
>>> T1.getInt()
12
>>> T1.setInt(32)
>>> T1.getInt()
32
</code>```

Please suggest.How can I do this ?
NOTE: I would like to know manual way to do that. I don't want any third party library dependency.

答:
ctypes is good. It is really easy to use, and it comes standard with Python. Unfortunately it can only talk to shared libraries (Unix) or DLLs (Windows) that have a C-style interface, which means you can't directly interface to a C++ object. But you could use a handle system where a handle refers to a particular object.

```<code>>>> getInt(h)
12
</code>```

I think that is simple, easy to understand, and doesn't require extra libraries.

OwnerDisplayName: david makcenzie

ContentLicense: CC BY-SA 2.5

Title: How can I use C++ class in Python?

Body:
I have implemented a class in C++. I want to use it with Python.
Please suggest step by step method and elaborate each step.
Somthing like this...

class Test{
     private:
        int n;
     public:
        Test(int k){
            n=k;
        }
        void setInt(int k){
            n = k;
        }
        int getInt(){
            return n;
        }
};

Now, in Python

>>> T1 = Test(12)
>>> T1.getInt()
12
>>> T1.setInt(32)
>>> T1.getInt()
32

Please suggest.How can I do this ?
NOTE: I would like to know manual way to do that. I don't want any third party library dependency.

LastEditorDisplayName: david makcenzie

Body:
ctypes is good. It is really easy to use, and it comes standard with Python. Unfortunately it can only talk to shared libraries (Unix) or DLLs (Windows) that have a C-style interface, which means you can't directly interface to a C++ object. But you could use a handle system where a handle refers to a particular object.

>>> getInt(h)
12

I think that is simple, easy to understand, and doesn't require extra libraries.

OwnerDisplayName: dangph

LastEditorDisplayName: dangph


问:
NSKeyedArchiver not saving all properties of an object
I am having an issue where I am saving, among other things, an array of "nodes" (header below) that posses a color and a tag property.  When it saves as in - (void)saveDataToDiskWithPath:(NSURL*)path, the log shows that these properties exist.  When I load the array again at a later time from the saved file, the frame of the node persists, but each node in the array has lost its tag and color...any ideas why?  What could I be doing wrong?  Maybe I'm just tired, and it will all make sense later...

Node.h:

```<code>//
//  Node.h
//

#import <Cocoa/Cocoa.h>

@interface Node : NSView {
@private
    NSColor *thisColor;
    NSColor *originalColor;
    NSRect dragRect;
    BOOL msDn;
    long tag;
    BOOL amSelected;
}

@property long tag;
@property (nonatomic, retain) NSColor* originalColor;

- (id)initWithFrame:(NSRect)frame andColor:(NSColor*)color;
- (void)select:(BOOL)yesOrNo;

@end
</code>```

The save method:

```<code>- (void) saveDataToDiskWithPath:(NSURL*)path
{
    NSLog(@"Path is %@", [path absoluteString]);
    NSMutableDictionary * rootObject;
    rootObject = [NSMutableDictionary dictionary];
    for(Node* node in [sharedValues nodes]){
        NSLog(@"Node has color %@ and tag %ld.", [node originalColor], [node tag]);
    }
    [rootObject setValue: [imageView aPath] forKey:@"path"];
    [rootObject setValue:[sharedValues nodes] forKey:@"nodes"];
    [NSKeyedArchiver archiveRootObject: rootObject toFile: [path path]];
}
</code>```

The load method:

```<code>- (void)loadDataFromDiskWithPath:(NSURL*)path
{
    NSDictionary * rootObject;

    rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:[path path]];
    [imageView setAPath:[rootObject valueForKey:@"path"]];
    [sharedValues setNodes:[rootObject valueForKey:@"nodes"]];
    [imageView setNeedsDisplay:YES];
}
</code>```

答: You will have to adopt the NSCoding protocol and implement -initWithCoder: and -encodeWithCoder: methods for the object to archive properly. Since Node is a subclass of UIView which adopts the protocol, some parts of it are being archived correctly. These are the properties of UIView and its parent classes. To ensure proper archiving, Node will have to implement the protocol too. Go through this doc for additional insight.

Body:
I am having an issue where I am saving, among other things, an array of "nodes" (header below) that posses a color and a tag property.  When it saves as in - (void)saveDataToDiskWithPath:(NSURL*)path, the log shows that these properties exist.  When I load the array again at a later time from the saved file, the frame of the node persists, but each node in the array has lost its tag and color...any ideas why?  What could I be doing wrong?  Maybe I'm just tired, and it will all make sense later...

Node.h:

//
//  Node.h
//

#import <Cocoa/Cocoa.h>

@interface Node : NSView {
@private
    NSColor *thisColor;
    NSColor *originalColor;
    NSRect dragRect;
    BOOL msDn;
    long tag;
    BOOL amSelected;
}

@property long tag;
@property (nonatomic, retain) NSColor* originalColor;

- (id)initWithFrame:(NSRect)frame andColor:(NSColor*)color;
- (void)select:(BOOL)yesOrNo;

@end

The save method:

- (void) saveDataToDiskWithPath:(NSURL*)path
{
    NSLog(@"Path is %@", [path absoluteString]);
    NSMutableDictionary * rootObject;
    rootObject = [NSMutableDictionary dictionary];
    for(Node* node in [sharedValues nodes]){
        NSLog(@"Node has color %@ and tag %ld.", [node originalColor], [node tag]);
    }
    [rootObject setValue: [imageView aPath] forKey:@"path"];
    [rootObject setValue:[sharedValues nodes] forKey:@"nodes"];
    [NSKeyedArchiver archiveRootObject: rootObject toFile: [path path]];
}

The load method:

- (void)loadDataFromDiskWithPath:(NSURL*)path
{
    NSDictionary * rootObject;

    rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:[path path]];
    [imageView setAPath:[rootObject valueForKey:@"path"]];
    [sharedValues setNodes:[rootObject valueForKey:@"nodes"]];
    [imageView setNeedsDisplay:YES];
}


问:
SQLiteBlobTooBigException: Row too big to fit into CursorWindow while writing to DB
I see the above error when I try to add to sqllite DB on android.I am using cloudant library. Here's the stack trace:

```<code>2019-07-17 18:04:48.292 5522-5753/org.iprd.identity E/SQLiteQuery: exception: Row too big to fit into CursorWindow requiredPos=0, totalRows=1; query: SELECT docs.docid, docs.doc_id, revid, sequence, current, deleted, parent, json FROM revs, docs WHERE docs.docid=? AND revs.doc_id=docs.doc_id AND revid=? ORDER BY revs.sequence LIMIT 1
2019-07-17 18:04:48.302 5522-5522/org.iprd.identity E/DatabaseImpl: Failed to create document
    java.util.concurrent.ExecutionException: android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1
        at java.util.concurrent.FutureTask.report(FutureTask.java:123)
        at java.util.concurrent.FutureTask.get(FutureTask.java:193)
        at com.cloudant.sync.internal.documentstore.DatabaseImpl.get(DatabaseImpl.java:1084)
        at com.cloudant.sync.internal.documentstore.DatabaseImpl.create(DatabaseImpl.java:925)
</code>```

I never got this issue previously, however, I recently made a change and started using a 3rd party tool to give me some images. With this new tool, the image sizes seem to be much bigger than before. I am storing these images in my db as a string by doing a Base64 encoding of the image. However, with this new tool, while storing the image, I get the above exception.

I have a unit test which I tried using one of the generated strings from this image, but that also throws an error that the string size is too large and does not even compile.

What is the best approach to solve this? -

What I was thinking of doing is to store the image in the device itself and just store the path in the DB.

Is there some compression we can do to the image to reduce its file size?

Is it possible to tune some db setting to ensure that it can handle larger image sizes?

Thanks in advance!

答:
If you want to save image as a byte array in SQLite or Room, you should compress the byte array.

like this

```<code>Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
</code>```

Body:
I see the above error when I try to add to sqllite DB on android.I am using cloudant library. Here's the stack trace:

2019-07-17 18:04:48.292 5522-5753/org.iprd.identity E/SQLiteQuery: exception: Row too big to fit into CursorWindow requiredPos=0, totalRows=1; query: SELECT docs.docid, docs.doc_id, revid, sequence, current, deleted, parent, json FROM revs, docs WHERE docs.docid=? AND revs.doc_id=docs.doc_id AND revid=? ORDER BY revs.sequence LIMIT 1
2019-07-17 18:04:48.302 5522-5522/org.iprd.identity E/DatabaseImpl: Failed to create document
    java.util.concurrent.ExecutionException: android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1
        at java.util.concurrent.FutureTask.report(FutureTask.java:123)
        at java.util.concurrent.FutureTask.get(FutureTask.java:193)
        at com.cloudant.sync.internal.documentstore.DatabaseImpl.get(DatabaseImpl.java:1084)
        at com.cloudant.sync.internal.documentstore.DatabaseImpl.create(DatabaseImpl.java:925)

I never got this issue previously, however, I recently made a change and started using a 3rd party tool to give me some images. With this new tool, the image sizes seem to be much bigger than before. I am storing these images in my db as a string by doing a Base64 encoding of the image. However, with this new tool, while storing the image, I get the above exception.

I have a unit test which I tried using one of the generated strings from this image, but that also throws an error that the string size is too large and does not even compile.

What is the best approach to solve this? -

What I was thinking of doing is to store the image in the device itself and just store the path in the DB.

Is there some compression we can do to the image to reduce its file size?

Is it possible to tune some db setting to ensure that it can handle larger image sizes?

Thanks in advance!

Body:
If you want to save image as a byte array in SQLite or Room, you should compress the byte array.

like this

Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();


问:
npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY
I am trying all possible ways to create a React application. I have tried Maven, and now I am trying create-react-app from Facebook Incubators.

When I tried to run the command create-react-app my-app in npm environment, it worked on my personal system with no issues. But, when I tried the same command in my work environment, I encountered the following error on my command line:

```<code>npm ERR! node v6.10.2
npm ERR! npm  v3.10.10
npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

npm ERR! unable to get local issuer certificate
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
</code>```

答:
After trying out every solution I could find:

Turning off strict ssl: npm config set strict-ssl=false

Changing the registry to http instead of https: npm config set registry http://registry.npmjs.org/

Changing my cafile setting: npm config set cafile /path/to/your/cert.pem

Stop rejecting unknown CAs: set NODE_TLS_REJECT_UNAUTHORIZED=0

The solution that seems to be working the best for me now is to use the NODE_EXTRA_CA_CERTS environment variable which extends the existing CAs rather than replacing them with the cafile option in your .npmrc file. You can set it by entering this in your terminal: NODE_EXTRA_CA_CERTS=path/to/your/cert.pem

Of course, setting this variable every time can be annoying, so I added it to my bash profile so that it will be set every time I open terminal. If you don’t already have a ~/.bash_profile file, create one. Then at the end of that file add export NODE_EXTRA_CA_CERTS=path/to/your/cert.pem. Then, remove the cafile setting in your .npmrc.

Body:
I am trying all possible ways to create a React application. I have tried Maven, and now I am trying create-react-app from Facebook Incubators.

When I tried to run the command create-react-app my-app in npm environment, it worked on my personal system with no issues. But, when I tried the same command in my work environment, I encountered the following error on my command line:

npm ERR! node v6.10.2
npm ERR! npm  v3.10.10
npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

npm ERR! unable to get local issuer certificate
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>


问:
assert no database update attempts during django pytest
I'm writing a django test and I want to assert that no update attempts have been made to the database, but I don't want to mock the models because I'm still using them to read information from the database.

Is there any way to assert that no update attempts have happened in the database? Or, more specifically, is there a way to assert that no new update attempts have happened in a particular table or particular row?

Typically I could query the DB after the function to see if a value has been updated, but I want to guard against even attempted updates. For instance, I want to guard against code calling User.objects.update(age=new_age) when it should know that user.age already is equal to new_age.

答:
You can capture queries during a test with django.test.utils.CaptureQueriesContext

Example:

from django.db import connection
from django.test.utils import CaptureQueriesContext

def test_no_db_updates():
    with CaptureQueriesContext(connection) as context:
        do_test()

    for query in context.captured_queries:
        sql = query['sql']
        assert not (sql.startswith('INSERT INTO ') or sql.startswith('UPDATE ')), \
            'The DB was unexpectedly updated:\n' + sql
```

If you want to check for a specific table, assert it doesn't start with

f'INSERT INTO `{TheModel._meta.db_table}`'

or

f'UPDATE `{TheModel._meta.db_table}`'

Body:
You can capture queries during a test with django.test.utils.CaptureQueriesContext

Example:

from django.db import connection
from django.test.utils import CaptureQueriesContext

def test_no_db_updates():
    with CaptureQueriesContext(connection) as context:
        do_test()

    for query in context.captured_queries:
        sql = query['sql']
        assert not (sql.startswith('INSERT INTO ') or sql.startswith('UPDATE ')), \
            'The DB was unexpectedly updated:\n' + sql

If you want to check for a specific table, assert it doesn't start with

f'INSERT INTO `{TheModel._meta.db_table}`'

or

f'UPDATE `{TheModel._meta.db_table}`'


问:
VBA: Use "Find" to get the row of a value / fixing object variable errors
I need to use the "find" function to get the row of a value, where that value is defined from another worksheet, but I keep getting object-variable not defined errors even when I try defining everything.

I was initially able to get the code below to work. (I paste the "test" version of the code that only uses a small range of 20 cells. The result is placed in cell "A1" to make sure it works correctly in testing.)

```<code>X = Range("D6").Value

Range("A1").Value = Range("D2:D20").Find(X).Row
</code>```

But when I use this line in a large data set, I keep getting error 91 ("Object variable or With block variable not set").

So instead, I try code that defines everything more explicitly, but for the life of me, I can't get this code to work even on the small test set. (I also include a few lines that I've tried but that also produce errors.)

```<code> Sub Test3()

    Sheets("2017").Select
    Dim X As Long
    X = Range("D6").Value

    Dim ws As Worksheet
    Set ws = Worksheets("2017")

    Dim SearchRange As Range
    Dim FindRow As Range
    Set SearchRange = ws.Range("D2", ws.Range("D20").End(xlUp))
    Set FindRow = SearchRange.Find(X, LookIn:=xlValues, lookat:=xlWhole)

    If Not FindRow Is Nothing Then ReturnRowNumber = FindRow.Row

    'Range("A1").Value = FindRow 'Running this row gives application-defined error 1004

    Dim i_2017 As Long
    i_2017 = FindRow.Rows(1)  'All of these rows give object variable not set error 91
    'i_2017 = FindRow
    'i_2017 = FindRow.Rows.Item(1)
    Range("A1").Value = i_2017 'Check that the sub returns 6

End Sub
</code>```

If I try to return "FindRow" in cell "A1", I get error 1004 ("Application-defined or object-defined error")

If I try to store "FindRow" as another variable or use the "Item" property, I get error 91 ("Object variable or With block variable not set")

答:
You need to enclose all of your code that assumes FindRow has actually been found inside your If Not FindRow is Nothing statement.

```<code>Sub Test3()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("2017")
Dim Found As Range, ReturnRowNumber As Long

Set Found = ws.Range("D:D").Find (ws.Range("D6"), LookIn:=xlValues, LookAt:=xlxWhole)

If Not Found Is Nothing Then
    'All code that assumes your value is found goes HERE
    ReturnRowNumber = Found.Row
    Range("A1").Value = Found
Else
    'All code that assumed your value is NOT found goes HERE
    MsgBox ws.Range("2017") & ": Not Found in Range"
End If

End Sub
</code>```

Body:
I need to use the "find" function to get the row of a value, where that value is defined from another worksheet, but I keep getting object-variable not defined errors even when I try defining everything.

I was initially able to get the code below to work. (I paste the "test" version of the code that only uses a small range of 20 cells. The result is placed in cell "A1" to make sure it works correctly in testing.)

X = Range("D6").Value

Range("A1").Value = Range("D2:D20").Find(X).Row

But when I use this line in a large data set, I keep getting error 91 ("Object variable or With block variable not set").

So instead, I try code that defines everything more explicitly, but for the life of me, I can't get this code to work even on the small test set. (I also include a few lines that I've tried but that also produce errors.)

 Sub Test3()

    Sheets("2017").Select
    Dim X As Long
    X = Range("D6").Value

    Dim ws As Worksheet
    Set ws = Worksheets("2017")

    Dim SearchRange As Range
    Dim FindRow As Range
    Set SearchRange = ws.Range("D2", ws.Range("D20").End(xlUp))
    Set FindRow = SearchRange.Find(X, LookIn:=xlValues, lookat:=xlWhole)

    If Not FindRow Is Nothing Then ReturnRowNumber = FindRow.Row

    'Range("A1").Value = FindRow 'Running this row gives application-defined error 1004

    Dim i_2017 As Long
    i_2017 = FindRow.Rows(1)  'All of these rows give object variable not set error 91
    'i_2017 = FindRow
    'i_2017 = FindRow.Rows.Item(1)
    Range("A1").Value = i_2017 'Check that the sub returns 6

End Sub

If I try to return "FindRow" in cell "A1", I get error 1004 ("Application-defined or object-defined error")

If I try to store "FindRow" as another variable or use the "Item" property, I get error 91 ("Object variable or With block variable not set")

Body:
You need to enclose all of your code that assumes FindRow has actually been found inside your If Not FindRow is Nothing statement.

Sub Test3()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("2017")
Dim Found As Range, ReturnRowNumber As Long

Set Found = ws.Range("D:D").Find (ws.Range("D6"), LookIn:=xlValues, LookAt:=xlxWhole)

If Not Found Is Nothing Then
    'All code that assumes your value is found goes HERE
    ReturnRowNumber = Found.Row
    Range("A1").Value = Found
Else
    'All code that assumed your value is NOT found goes HERE
    MsgBox ws.Range("2017") & ": Not Found in Range"
End If

End Sub


问:
Add more than one icon in a treeview field with python 3 and tkinter
I know how to add an icon in the #0 column using the tags keyword :

```<code>icon = ImageTk.PhotoImage(Image.open('path/to/icon.gif')
myTreeView.tag_configure('tag_with_this_icon', image=icon)

# some loop
myTreeView.insert( [...],tags='tag_with_this_icon')
</code>```

I would need to add an additional icon, or add an icon in any other column of the treeview, is it possible with tkinter ?

or do I need to tweak my icon gif files with two icons in the same icon file (all possible permutation)

or stich another treeview to the left of the first treeview with one column/empty text jsu for a second icon ?
seems a bad hack... any better ideas appreciated, thanks.

答:
A way would be to use GTK3 rather than tkinter, a valid example below. OP ask for a solution with tkinter, but OP is me and did not find its way with it, so...

```<code>from gi.repository import Gtk, Gdk, GdkPixbuf

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_default_size(200, 200)

        self.liststore = Gtk.ListStore(str, str, str)
        self.treeview = Gtk.TreeView(model=self.liststore)

        self.liststore.append(["dot_red16x16.png", "This is a symbol1","dot_green16x16.png"])

        px_renderer = Gtk.CellRendererPixbuf()
        px_column = Gtk.TreeViewColumn('')
        px_column.pack_start(px_renderer, False)

        str_renderer = Gtk.CellRendererText()
        px_column.pack_start(str_renderer, False)

        px_renderer2 = Gtk.CellRendererPixbuf()
        px_column.pack_start(px_renderer2, False)

        # set data connector function/method
        px_column.set_cell_data_func(px_renderer, self.get_tree_cell_pixbuf,0)
        px_column.set_cell_data_func(px_renderer2, self.get_tree_cell_pixbuf,2)
        px_column.set_cell_data_func(str_renderer, self.get_tree_cell_text)
        self.treeview.append_column(px_column)

        self.add(self.treeview)

    def get_tree_cell_text(self, col, cell, model, iter, user_data):
        cell.set_property('text', model.get_value(iter, 1))

    def get_tree_cell_pixbuf(self, col, cell, model, iter, user_data):
        cell.set_property('pixbuf', GdkPixbuf.Pixbuf.new_from_file(model.get_value(iter, user_data)))

if __name__ == '__main__':
    win = MyWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()
</code>```

line 11, replace dot_red16x16.png and dot_green16x16.png names with your own icon files and save this snipped aside the icon files.

gtk readthedocs : https://python-gtk-3-tutorial.readthedocs.io

side note :
actually the harder (on windows) is to setup GTK3 to work. Here is two ways I tested :

Run gcc python from msys and setup everything (ok with Python 3.8.1) :

https://www.gtk.org/download/windows.php

https://pygobject.readthedocs.io/en/latest/getting_started.html#windows-getting-started

The lazy way with Cpython 3.4.4 for windows, plus pygi-aio-3.24.1, a huge pack of gtk ressources :

https://sourceforge.net/projects/pygobjectwin32/files

Body:
I know how to add an icon in the #0 column using the tags keyword :

icon = ImageTk.PhotoImage(Image.open('path/to/icon.gif')
myTreeView.tag_configure('tag_with_this_icon', image=icon)

# some loop
myTreeView.insert( [...],tags='tag_with_this_icon')

I would need to add an additional icon, or add an icon in any other column of the treeview, is it possible with tkinter ?

or do I need to tweak my icon gif files with two icons in the same icon file (all possible permutation)

or stich another treeview to the left of the first treeview with one column/empty text jsu for a second icon ?
seems a bad hack... any better ideas appreciated, thanks.

Body:
A way would be to use GTK3 rather than tkinter, a valid example below. OP ask for a solution with tkinter, but OP is me and did not find its way with it, so...

from gi.repository import Gtk, Gdk, GdkPixbuf

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_default_size(200, 200)

        self.liststore = Gtk.ListStore(str, str, str)
        self.treeview = Gtk.TreeView(model=self.liststore)

        self.liststore.append(["dot_red16x16.png", "This is a symbol1","dot_green16x16.png"])

        px_renderer = Gtk.CellRendererPixbuf()
        px_column = Gtk.TreeViewColumn('')
        px_column.pack_start(px_renderer, False)

        str_renderer = Gtk.CellRendererText()
        px_column.pack_start(str_renderer, False)

        px_renderer2 = Gtk.CellRendererPixbuf()
        px_column.pack_start(px_renderer2, False)

        # set data connector function/method
        px_column.set_cell_data_func(px_renderer, self.get_tree_cell_pixbuf,0)
        px_column.set_cell_data_func(px_renderer2, self.get_tree_cell_pixbuf,2)
        px_column.set_cell_data_func(str_renderer, self.get_tree_cell_text)
        self.treeview.append_column(px_column)

        self.add(self.treeview)

    def get_tree_cell_text(self, col, cell, model, iter, user_data):
        cell.set_property('text', model.get_value(iter, 1))

    def get_tree_cell_pixbuf(self, col, cell, model, iter, user_data):
        cell.set_property('pixbuf', GdkPixbuf.Pixbuf.new_from_file(model.get_value(iter, user_data)))

if __name__ == '__main__':
    win = MyWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()

line 11, replace dot_red16x16.png and dot_green16x16.png names with your own icon files and save this snipped aside the icon files.

gtk readthedocs : https://python-gtk-3-tutorial.readthedocs.io

side note :
actually the harder (on windows) is to setup GTK3 to work. Here is two ways I tested :

Run gcc python from msys and setup everything (ok with Python 3.8.1) :

https://www.gtk.org/download/windows.php

https://pygobject.readthedocs.io/en/latest/getting_started.html#windows-getting-started

The lazy way with Cpython 3.4.4 for windows, plus pygi-aio-3.24.1, a huge pack of gtk ressources :

https://sourceforge.net/projects/pygobjectwin32/files


问:
Which of the Azure Cosmos DB types of database should I use to log simple events from my mobile application?
I would like to set up event logging for my application.  Simple information such as date (YYYYMMDD), activity and appVersion.  Later I would like to query this to give me some simple information such as how many times a certain activity occurred for each month.

From what I see there are a few different types of database in Cosmos such as NoSQL and Casandra.

Which would be the most suitable to meet my simple needs?

答:
You can use Cosmos DB SQL API for storing this data. It has rich querying capabilities and also has a great support for aggregate functions.

One thing you would need to keep in mind is your data partitioning strategy and design your container's partition key accordingly. Considering you're going to do data aggregation on a monthly basis, I would recommend creating a partition key for year and month so that data for a month (and year) stays in a single logical partition. However, please note that a logical partition can only contain 10GB data (including indexes) so you may have to rethink your partitioning strategy if you expect the data to go above 10GB.

A cheaper alternative for you would be to use Azure Table Storage however it doesn't have that rich querying capabilities and also it doesn't have aggregation capability. However with some code (running in Azure Functions), you can aggregate the data yourself.


问:
Printed output not displayed when using joblib in jupyter notebook
So I am using joblib to parallelize some code and I noticed that I couldn't print things when using it inside a jupyter notebook.

I tried using doing the same example in ipython and it worked perfectly.

Here is a minimal (not) working example to write in a jupyter notebook cell

from joblib import Parallel, delayed
Parallel(n_jobs=8)(delayed(print)(i) for i in range(10))
```

<p>So I am getting the output as <code>[None, None, None, None, None, None, None, None, None, None]</code> but nothing is printed.</p>

<p>What I expect to see (print order could be random in reality):</p>

<pre class="lang-py prettyprint-override"><code>1
2
3
4
5
6
7
8
9
10
[None, None, None, None, None, None, None, None, None, None]
</code>```

Note:

You can see the prints in the logs of the notebook process. But I would like the prints to happen in the notebook, not the logs of the notebook process.

EDIT

I have opened a Github issue, but with minimal attention so far.

答:
I think this caused in part by the way Parallel spawns the child workers, and how Jupyter Notebook handles IO for those workers. When started without specifying a value for backend, Parallel will default to loky which utilizes a pooling strategy that directly uses a fork-exec model to create the subprocesses.

If you start Notebook from a terminal using

```<code>$ jupyter-notebook
</code>```

the regular stderr and stdout streams appear to remain attached to that terminal, while the notebook session will start in a new browser window. Running the posted code snippet in the notebook does produce the expected output, but it seems to go to stdout and ends up in the terminal (as hinted in the Note in the question). This further supports the suspicion that this behavior is caused by the interaction between loky and notebook, and the way the standard IO streams are handled by notebook for child processes.

This lead me to this discussion on github (active within the past 2 weeks as of this posting) where the authors of notebook appear to be aware of this, but it would seem that there is no obvious and quick fix for the issue at the moment.

If you don't mind switching the backend that Parallel uses to spawn children, you can do so like this:

```<code>from joblib import Parallel, delayed
Parallel(n_jobs=8, backend='multiprocessing')(delayed(print)(i) for i in range(10))
</code>```

with the multiprocessing backend, things work as expected. threading looks to work fine too. This may not be the solution you were hoping for, but hopefully it is sufficient while the notebook authors work on finding a proper solution.

I'll cross-post this to GitHub in case anyone there cares to add to this answer (I don't want to misstate anyone's intent or put words in people mouths!).

Test Environment:

MacOS - Mojave (10.14)

Python - 3.7.3

pip3 - 19.3.1

Tested in 2 configurations. Confirmed to produce the expected output when using both multiprocessing and threading for the backend parameter. Packages install using pip3.

Setup 1:

```<code>ipykernel                               5.1.1
ipython                                 7.5.0
jupyter                                 1.0.0
jupyter-client                          5.2.4
jupyter-console                         6.0.0
jupyter-core                            4.4.0
notebook                                5.7.8
</code>```

Setup 2:

```<code>ipykernel                               5.1.4
ipython                                 7.12.0
jupyter                                 1.0.0
jupyter-client                          5.3.4
jupyter-console                         6.1.0
jupyter-core                            4.6.2
notebook                                6.0.3
</code>```

I also was successful using the same versions as 'Setup 2' but with the notebook package version downgraded to 6.0.2.

Note:

This approach works inconsistently on Windows. Different combinations of software versions yield different results. Doing the most intuitive thing-- upgrading everything to the latest version-- does not guarantee it will work.

Body:
So I am using joblib to parallelize some code and I noticed that I couldn't print things when using it inside a jupyter notebook.

I tried using doing the same example in ipython and it worked perfectly.

Here is a minimal (not) working example to write in a jupyter notebook cell

from joblib import Parallel, delayed
Parallel(n_jobs=8)(delayed(print)(i) for i in range(10))

So I am getting the output as [None, None, None, None, None, None, None, None, None, None] but nothing is printed.

What I expect to see (print order could be random in reality):

1
2
3
4
5
6
7
8
9
10
[None, None, None, None, None, None, None, None, None, None]

Note:

You can see the prints in the logs of the notebook process. But I would like the prints to happen in the notebook, not the logs of the notebook process.

EDIT

I have opened a Github issue, but with minimal attention so far.

Body:
I think this caused in part by the way Parallel spawns the child workers, and how Jupyter Notebook handles IO for those workers. When started without specifying a value for backend, Parallel will default to loky which utilizes a pooling strategy that directly uses a fork-exec model to create the subprocesses.

If you start Notebook from a terminal using

$ jupyter-notebook

the regular stderr and stdout streams appear to remain attached to that terminal, while the notebook session will start in a new browser window. Running the posted code snippet in the notebook does produce the expected output, but it seems to go to stdout and ends up in the terminal (as hinted in the Note in the question). This further supports the suspicion that this behavior is caused by the interaction between loky and notebook, and the way the standard IO streams are handled by notebook for child processes.

This lead me to this discussion on github (active within the past 2 weeks as of this posting) where the authors of notebook appear to be aware of this, but it would seem that there is no obvious and quick fix for the issue at the moment.

If you don't mind switching the backend that Parallel uses to spawn children, you can do so like this:

from joblib import Parallel, delayed
Parallel(n_jobs=8, backend='multiprocessing')(delayed(print)(i) for i in range(10))

with the multiprocessing backend, things work as expected. threading looks to work fine too. This may not be the solution you were hoping for, but hopefully it is sufficient while the notebook authors work on finding a proper solution.

I'll cross-post this to GitHub in case anyone there cares to add to this answer (I don't want to misstate anyone's intent or put words in people mouths!).

Test Environment:

MacOS - Mojave (10.14)

Python - 3.7.3

pip3 - 19.3.1

Tested in 2 configurations. Confirmed to produce the expected output when using both multiprocessing and threading for the backend parameter. Packages install using pip3.

Setup 1:

ipykernel                               5.1.1
ipython                                 7.5.0
jupyter                                 1.0.0
jupyter-client                          5.2.4
jupyter-console                         6.0.0
jupyter-core                            4.4.0
notebook                                5.7.8

Setup 2:

ipykernel                               5.1.4
ipython                                 7.12.0
jupyter                                 1.0.0
jupyter-client                          5.3.4
jupyter-console                         6.1.0
jupyter-core                            4.6.2
notebook                                6.0.3

I also was successful using the same versions as 'Setup 2' but with the notebook package version downgraded to 6.0.2.

Note:

This approach works inconsistently on Windows. Different combinations of software versions yield different results. Doing the most intuitive thing-- upgrading everything to the latest version-- does not guarantee it will work.


问:
In React DevTools my component is re-rendering but the parent is not, and it's state/props are not changing
I have a React App that is currently re-rendering more often than I'd like. I'm using React DevTools Profiler to record my session and I have the option checked to record why the components re-render.

For the component in question, under 'Why did this component render?' it says 'The parent component rendered.' However in the component tree of the devtools, none of the parent components are rendering. They all say 'Did not render during this profiling session.' The component I'm troubleshooting is basically the highest level component in the actual project.

Above it are the following components:

App

BrowserRouter

Router

Context.Provider

Switch

Context.Consumer

Route

Context.Consumer

Context.Provider

MyComponent

答:
The component is most likely being re-rendered due to a change in context, and the React DevTools isn't reporting this accurately.

See https://github.com/facebook/react/pull/17068 for some more detail on the DevTool reporting in this situation.


问:
WebView not loading certain pages
Unable to load following webpage in WebView

https://6awlanow.com/about/faqs

Tried following so far -

```<code>    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setUserAgentString("Android WebView");
    webView.setWebViewClient(new WebViewClient() {

      @Override
      public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        view.loadUrl(request.getUrl().getPath());
        //if (progressDialog != null && progressDialog.isShowing()) {
        //  progressDialog.dismiss();
        //}
        return true;
      }

      //If you will not use this method url links are opeen in new brower not in webview
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
      }

      //Show loader on url load
      @Override
      public void onLoadResource(WebView view, String url) {
      }
      @Override
      public void onPageFinished(WebView view, String url) {
        try {
          //if (progressDialog.isShowing()) {
          //  progressDialog.dismiss();
          //}
        } catch (Exception exception) {
          exception.printStackTrace();
        }
      }

      @Override
      public void onReceivedError(
        WebView view, WebResourceRequest request, WebResourceError error
      ) {
        //progressDialog.dismiss();
        super.onReceivedError(view, request, error);
      }

    });
</code>```

I have already provided internet permission. The URL loads fine everywhere, except on WebView. I get following error -

Get following Info on my console -

```<code>I: [INFO:CONSOLE(31)] "Uncaught TypeError: Object.assign is not a function", source: https://6awlanow.com/app.c98a13d5a9fdd32775ca.js (31)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
</code>```

答:
what worked for me is

1 .Enabling dom Storage and javascript

```<code>webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
</code>```

2.running webview on handler

```<code> new Handler().post(new Runnable() {
                   @Override
                   public void run() {

                       webView.loadUrl(webview_url);

                   }
               });
</code>```

Title: WebView not loading certain pages

Body:
Unable to load following webpage in WebView

https://6awlanow.com/about/faqs

Tried following so far -

    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setUserAgentString("Android WebView");
    webView.setWebViewClient(new WebViewClient() {

      @Override
      public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        view.loadUrl(request.getUrl().getPath());
        //if (progressDialog != null && progressDialog.isShowing()) {
        //  progressDialog.dismiss();
        //}
        return true;
      }

      //If you will not use this method url links are opeen in new brower not in webview
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
      }

      //Show loader on url load
      @Override
      public void onLoadResource(WebView view, String url) {
      }
      @Override
      public void onPageFinished(WebView view, String url) {
        try {
          //if (progressDialog.isShowing()) {
          //  progressDialog.dismiss();
          //}
        } catch (Exception exception) {
          exception.printStackTrace();
        }
      }

      @Override
      public void onReceivedError(
        WebView view, WebResourceRequest request, WebResourceError error
      ) {
        //progressDialog.dismiss();
        super.onReceivedError(view, request, error);
      }

    });

I have already provided internet permission. The URL loads fine everywhere, except on WebView. I get following error -

Get following Info on my console -

I: [INFO:CONSOLE(31)] "Uncaught TypeError: Object.assign is not a function", source: https://6awlanow.com/app.c98a13d5a9fdd32775ca.js (31)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)
I: [INFO:CONSOLE(0)] "Error: Invalid negative value for <rect> attribute ry="-.125"", source: https://6awlanow.com/about/faqs (0)

Body:
what worked for me is

1 .Enabling dom Storage and javascript

webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDomStorageEnabled(true);

2.running webview on handler

 new Handler().post(new Runnable() {
                   @Override
                   public void run() {

                       webView.loadUrl(webview_url);

                   }
               });


问:
Why include when you can require in PHP?
What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?

答:
Require will stop the script if it can't include the file.

Include will just give an error message.

Btw.: *_once is slow. Shouldn't use it unless you really need to.


问:
Convert JavaRDD<List<SomeClass>> to JavaRDD<SomeClass>
I have a JavaRDD of a list of class objects.  I want to flatten it to a JaveRDD of class objects such that
JavaRDD<{1, 2, 3, 4}, {5, 6, 7}> goes to JavaRDD<1, 2, 3, 4, 5, 6, 7>

in this post
Convert RDD List to RDD of individual element in spark
one solution is

```<code>val newrdd = rdd.flatmap(line => line)
</code>```

however, line=>line is scala (I think)
I tried

```<code>rdd.flatmap(line-> line)
</code>```

and it gives and error

"no instance(s) of type variable(s) U exist so that List conforms to Iterator "

答:
The function you pass to flatMap should return a java.util.Iterator<T>, not a List<T>. It should suffice to do this:

```<code>JavaRDD<SomeClass> newRdd = rdd.flatMap(List::iterator);
</code>```

Body:
I have a JavaRDD of a list of class objects.  I want to flatten it to a JaveRDD of class objects such that
JavaRDD<{1, 2, 3, 4}, {5, 6, 7}> goes to JavaRDD<1, 2, 3, 4, 5, 6, 7>

in this post
Convert RDD List to RDD of individual element in spark
one solution is

val newrdd = rdd.flatmap(line => line)

however, line=>line is scala (I think)
I tried

rdd.flatmap(line-> line)

and it gives and error

"no instance(s) of type variable(s) U exist so that List conforms to Iterator "

Body:
The function you pass to flatMap should return a java.util.Iterator<T>, not a List<T>. It should suffice to do this:

JavaRDD<SomeClass> newRdd = rdd.flatMap(List::iterator);


问:
Xcode > Symbolic Breakpoint > Log Message > prints class of object property instead of value
I have created a symbolic breakpoint in Xcode 11.3.1 to log the name property of the first parameter ($rdx) to an Objective-C method.  Although my expression:

```<code>(NSString*)[(NSRelationshipDescription*)$rdx name]
</code>```

prints the expected value when passed via the print object (po) command, the message logged by the breakpoint prints instead

```<code>class name = _PFEncodedString
</code>```

It also logs the value as expected if I enter a Debugger Command (with po) instead of Log Message as the breakpoint Action.  But of course that omits my label (unless I were to try to print a formatted string – what a kludge!), and it prints an extra blank line.  I was hoping Log Message would be helpful in debugging a difficult problem.

Am I doing something wrong or is Xcode's Log Message just broken?

答: Well, since no one has answered after a week, I conclude that this is a bug in Xcode.  I have submitted it to Apple in FB7585394.</p>

Body:
I have created a symbolic breakpoint in Xcode 11.3.1 to log the name property of the first parameter ($rdx) to an Objective-C method.  Although my expression:

(NSString*)[(NSRelationshipDescription*)$rdx name]

prints the expected value when passed via the print object (po) command, the message logged by the breakpoint prints instead

class name = _PFEncodedString

It also logs the value as expected if I enter a Debugger Command (with po) instead of Log Message as the breakpoint Action.  But of course that omits my label (unless I were to try to print a formatted string – what a kludge!), and it prints an extra blank line.  I was hoping Log Message would be helpful in debugging a difficult problem.

Am I doing something wrong or is Xcode's Log Message just broken?


问:
Django rest framework: How do I send and download xlsx file?
I have been stuck for awhile now trying to send a file to client side using django-rest-framework. I am able to send it as a byte but I don't know how to manage it client side to download it as an xlsx file. Everything I tried ends with a corrupted file.

Here is what I have so far:

```<code># views.py
from django.http import HttpResponse
from openpyxl import load_workbook
from openpyxl.writer.excel import save_virtual_workbook

class DownloadApiView(APIView):
    authentication_classes = [BasicAuthentication, SessionAuthentication]
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        try:
            file_path = './temp.xlsx'
            pk = request.data['xml_id']
            report = Report.objects.get(pk=pk)
            wbrd = load_workbook(filename=file_path)
            bytes = save_virtual_workbook(wb)

            response = HttpResponse(bytes, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            response['Content-Disposition'] = "attachment; filename=temp.xlsx"
            return response
        except Exception as error_msg:
            logger.error(error_msg)
            return Response({'error': 'Failed to retrieve file.'}, status=HTTP_400_BAD_REQUEST)

# client js called onclick()
function downloadFile(xmlID, type) {
    let url = '/api/download_report/';
    let $submit = $.ajax({
        type: 'POST',
        url: url,
        data: JSON.stringify(inputData),
        contentType: 'application/json',
        headers: {"X-CSRFToken": getCookie("csrftoken")},
    });
    $submit.done(function (data) {
        console.log(data);

        let a = window.document.createElement('a');
        a.href = window.URL.createObjectURL(new Blob(data, {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
        a.download = 'temp.xlsx';

        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);

    });
}

</code>```

答:
you can do this easily using django models field models.FileField you can follow this tutorial very brief and easy to understand step by step guide

https://blog.vivekshukla.xyz/uploading-file-using-api-django-rest-framework/

```<code>file = models.FileField(blank=False, null=False)
#you can edit this to
file = models.FileField(upload_to='/the path where you want to download files',blank=False, null=False)
</code>```

Body:
I have been stuck for awhile now trying to send a file to client side using django-rest-framework. I am able to send it as a byte but I don't know how to manage it client side to download it as an xlsx file. Everything I tried ends with a corrupted file.

Here is what I have so far:

# views.py
from django.http import HttpResponse
from openpyxl import load_workbook
from openpyxl.writer.excel import save_virtual_workbook

class DownloadApiView(APIView):
    authentication_classes = [BasicAuthentication, SessionAuthentication]
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        try:
            file_path = './temp.xlsx'
            pk = request.data['xml_id']
            report = Report.objects.get(pk=pk)
            wbrd = load_workbook(filename=file_path)
            bytes = save_virtual_workbook(wb)

            response = HttpResponse(bytes, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            response['Content-Disposition'] = "attachment; filename=temp.xlsx"
            return response
        except Exception as error_msg:
            logger.error(error_msg)
            return Response({'error': 'Failed to retrieve file.'}, status=HTTP_400_BAD_REQUEST)

# client js called onclick()
function downloadFile(xmlID, type) {
    let url = '/api/download_report/';
    let $submit = $.ajax({
        type: 'POST',
        url: url,
        data: JSON.stringify(inputData),
        contentType: 'application/json',
        headers: {"X-CSRFToken": getCookie("csrftoken")},
    });
    $submit.done(function (data) {
        console.log(data);

        let a = window.document.createElement('a');
        a.href = window.URL.createObjectURL(new Blob(data, {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}));
        a.download = 'temp.xlsx';

        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);

    });
}

Body:
you can do this easily using django models field models.FileField you can follow this tutorial very brief and easy to understand step by step guide

https://blog.vivekshukla.xyz/uploading-file-using-api-django-rest-framework/

file = models.FileField(blank=False, null=False)
#you can edit this to
file = models.FileField(upload_to='/the path where you want to download files',blank=False, null=False)


问:
Python swap function is not working using index method with list=[1,2,3]
I am trying to swap elements using python list index method which would return index of an element.
So that I Can swap as like as I need using know elements.

Here's the code...

```<code>a = [1,2,3,4,5,6]

a[a.index(1)],a[a.index(2)] = a[a.index(2)],a[a.index(1)]

</code>```

output

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

And again I tried to use swap elements and now here's the output

```<code>a = [2,1,3,4,5,6]

a[a.index(1)],a[a.index(2)] = a[a.index(2)],a[a.index(1)]

</code>```

output

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

output with list [1,2,3,4,5,6]

答:
This is because of Python's evaluation order and because of the fact that you change the list in the middle of this evaluation:

For an assignment, first the RHS is evaluated, from left to right:

```<code># a = [1,2,3,4,5,6]
a[a.index(2)], a[a.index(1)] =>  2, 1
</code>```

Now, the LHS is evaluated from left to right. So, first:

```<code># a = [1,2,3,4,5,6]
a[a.index(1)] => a[0] = 2
# now a = [2,2,3,4,5,6]
</code>```

Notice that now the (first) index of 2 is 0!!!

Next evaluation is:

```<code># a = [2,2,3,4,5,6]
a[a.index(2)] => a[0] = 1
# now a = [1,2,3,4,5,6]
</code>```

So you end up with the same list...

This is also because the index() method returns the:

index of the first occurrence of x in s

For the second list, the RHS is evaluated the same, but then at the LHS you have:

```<code># a = [2,1,3,4,5,6]
a[a.index(1)] => a[1] = 2
# now a = [2,2,3,4,5,6]
</code>```

And now:

```<code># a = [2,2,3,4,5,6]
a[a.index(2)] => a[0] = 1
# now a = [1,2,3,4,5,6]
</code>```

So it seems fine...

Body:
I am trying to swap elements using python list index method which would return index of an element.
So that I Can swap as like as I need using know elements.

Here's the code...

a = [1,2,3,4,5,6]

a[a.index(1)],a[a.index(2)] = a[a.index(2)],a[a.index(1)]

output

>>>a
>>>[1,2,3,4,5,6]

And again I tried to use swap elements and now here's the output

a = [2,1,3,4,5,6]

a[a.index(1)],a[a.index(2)] = a[a.index(2)],a[a.index(1)]

output

>>> a
>>> [1,2,3,4,5,6]

output with list [1,2,3,4,5,6]

Body:
This is because of Python's evaluation order and because of the fact that you change the list in the middle of this evaluation:

For an assignment, first the RHS is evaluated, from left to right:

# a = [1,2,3,4,5,6]
a[a.index(2)], a[a.index(1)] =>  2, 1

Now, the LHS is evaluated from left to right. So, first:

# a = [1,2,3,4,5,6]
a[a.index(1)] => a[0] = 2
# now a = [2,2,3,4,5,6]

Notice that now the (first) index of 2 is 0!!!

Next evaluation is:

# a = [2,2,3,4,5,6]
a[a.index(2)] => a[0] = 1
# now a = [1,2,3,4,5,6]

So you end up with the same list...

This is also because the index() method returns the:

index of the first occurrence of x in s

For the second list, the RHS is evaluated the same, but then at the LHS you have:

# a = [2,1,3,4,5,6]
a[a.index(1)] => a[1] = 2
# now a = [2,2,3,4,5,6]

And now:

# a = [2,2,3,4,5,6]
a[a.index(2)] => a[0] = 1
# now a = [1,2,3,4,5,6]

So it seems fine...


问:
Google sheets to Calendar - Update previous event script
I have a budget set in Sheets and a script to update my calendar with the due dates. My script is:

```<code>function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Sync to Calendar')
      .addItem('Unpaid Items', 'unpaidItems')
      .addItem('Delete All', 'deleteEvent')
      .addToUi();
};

function unpaidItems() {
var spreadsheet = SpreadsheetApp.getActiveSheet();

//First Calendar beceause of different colour
var calendarId = spreadsheet.getRange("K72").getValue();
var eventCal = CalendarApp.getCalendarById(calendarId);

//Second Calendar beceause of different colour
var calendarIdPaid = spreadsheet.getRange("K71").getValue();
var eventCalPaid = CalendarApp.getCalendarById(calendarIdPaid);

var signups = spreadsheet.getRange("B15:I16").getValues();

  for (x=0; x<signups.length; x++) {
    var shift = signups[x];
    var statt = shift[7];

    if (statt == "Required Soon" ) {
       var Debtor = shift[0];
       var startTime = shift[6];
       var endTime = shift[6];
       eventCal.createAllDayEvent(Debtor, startTime, endTime+1);
      //Ideally to use a single calendar and change the color of this entry
    }
    else if (statt == "Late Payment" ) {
       var Debtor = shift[0];
       var startTime = shift[6];
       var endTime = shift[6];
       eventCal.createAllDayEvent(Debtor, startTime, endTime+1);
      //Ideally to use a single calendar and change the color of this entry
    }
    else if (statt == "Paid" ) {
       var Debtor = shift[0];
       var startTime = shift[6];
       var endTime = shift[6];
       eventCalPaid.createAllDayEvent(Debtor, startTime, endTime+1);
      //Ideally to use a single calendar and change the color of this entry
      //This entry would have existed under Required soon or Late Payment so that has to be deleted now and replaced with this in a green colour showing its been paid
    }
  }
}
</code>```

** All works but in the "For" section there's a few hashed out items. How can I:

Use a single calendar but change the color of the entry event based on if its Required soon, Late Payment or Paid?

More importantly, Once an item has been paid this is flagged in the sheet but it still has to be removed from my calendar or updated with a green colour to indicate its now been paid.

答:
You can set event colors with the method setColor(color)

Thereby, you can chose between event colors, as specified here.

Just implement in each of your if statements an event color as desired, e.g.

```<code>    ...
    else if (statt == "Paid" ) {
       var Debtor = shift[0];
       var startTime = shift[6];
       var endTime = shift[6];
       var event = eventCalPaid.createAllDayEvent(Debtor, startTime, endTime+1);
       event.setColor(CalendarApp.EventColor.GREEN);
    }
    ...
</code>```

UPDATE

if you want to verify first either an event exists and modify if does - you can do it as following:

```<code>    ...
    else if (statt == "Paid" ) {
       var Debtor = shift[0];
       var startTime = shift[6];
       var endTime = shift[6];
       var events = eventCal.getEvents(startTime, endTime, {search : Debtor});
       var event = events[0];
       if(!event){
        var event = eventCal.createAllDayEvent(Debtor, startTime, endTime);
       }
       event.setColor(CalendarApp.EventColor.GREEN);
    }
    ...
</code>```

Be careful with endTime+1, your event might not be found if the
  times don't correspond.

Body:
I have a budget set in Sheets and a script to update my calendar with the due dates. My script is:

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Sync to Calendar')
      .addItem('Unpaid Items', 'unpaidItems')
      .addItem('Delete All', 'deleteEvent')
      .addToUi();
};

function unpaidItems() {
var spreadsheet = SpreadsheetApp.getActiveSheet();

//First Calendar beceause of different colour
var calendarId = spreadsheet.getRange("K72").getValue();
var eventCal = CalendarApp.getCalendarById(calendarId);

//Second Calendar beceause of different colour
var calendarIdPaid = spreadsheet.getRange("K71").getValue();
var eventCalPaid = CalendarApp.getCalendarById(calendarIdPaid);

var signups = spreadsheet.getRange("B15:I16").getValues();

  for (x=0; x<signups.length; x++) {
    var shift = signups[x];
    var statt = shift[7];

    if (statt == "Required Soon" ) {
       var Debtor = shift[0];
       var startTime = shift[6];
       var endTime = shift[6];
       eventCal.createAllDayEvent(Debtor, startTime, endTime+1);
      //Ideally to use a single calendar and change the color of this entry
    }
    else if (statt == "Late Payment" ) {
       var Debtor = shift[0];
       var startTime = shift[6];
       var endTime = shift[6];
       eventCal.createAllDayEvent(Debtor, startTime, endTime+1);
      //Ideally to use a single calendar and change the color of this entry
    }
    else if (statt == "Paid" ) {
       var Debtor = shift[0];
       var startTime = shift[6];
       var endTime = shift[6];
       eventCalPaid.createAllDayEvent(Debtor, startTime, endTime+1);
      //Ideally to use a single calendar and change the color of this entry
      //This entry would have existed under Required soon or Late Payment so that has to be deleted now and replaced with this in a green colour showing its been paid
    }
  }
}

** All works but in the "For" section there's a few hashed out items. How can I:

Use a single calendar but change the color of the entry event based on if its Required soon, Late Payment or Paid?

More importantly, Once an item has been paid this is flagged in the sheet but it still has to be removed from my calendar or updated with a green colour to indicate its now been paid.

Body:
You can set event colors with the method setColor(color)

Thereby, you can chose between event colors, as specified here.

Just implement in each of your if statements an event color as desired, e.g.

    ...
    else if (statt == "Paid" ) {
       var Debtor = shift[0];
       var startTime = shift[6];
       var endTime = shift[6];
       var event = eventCalPaid.createAllDayEvent(Debtor, startTime, endTime+1);
       event.setColor(CalendarApp.EventColor.GREEN);
    }
    ...

UPDATE

if you want to verify first either an event exists and modify if does - you can do it as following:

    ...
    else if (statt == "Paid" ) {
       var Debtor = shift[0];
       var startTime = shift[6];
       var endTime = shift[6];
       var events = eventCal.getEvents(startTime, endTime, {search : Debtor});
       var event = events[0];
       if(!event){
        var event = eventCal.createAllDayEvent(Debtor, startTime, endTime);
       }
       event.setColor(CalendarApp.EventColor.GREEN);
    }
    ...

Be careful with endTime+1, your event might not be found if the
  times don't correspond.


问:
Is it worth learning Smarty for PHP templating?
I'm building a simple 10-page site using an MVC-like architecture. Is it worth learning the Smarty templating engine?</p>

答:
I used Smarty a long time ago, I would recommend you that it's no need to use Template Engine like that. Smarty slows down the whole system because its core source code is really complex, and somehow unnecessary. If I had a recommendation on Template Engine, I would say:

1) Use some basic and light Template Engine such as XTemplate. I'm not sure if it's still developing but it's really useful, everything is in one class file, ready to use. The syntax is also clear and sweet.

2) Write your own Template Engine, so that you can customize it on your own that best fits your current system.

But, however, for tiny and small project (less then 5-7 pages) in which you can have a control over everything, then using Template Engine is probably unnecessary.


问:
DB2 inserting both timestamp values and null values into a nullable timestamp column
When selecting timestamps (which are nullable with defualt null) from a source table through a PHP script and trying to insert into an identical destination table,
I get the error 'SYNTAX of date, time or timestamp value not valid SQL state 22008'. I believe it's because some source records are null. When the script runs, I get about half the records inserted into my destination table successfully but only the ones that have actual timestamp values. The null records haven't been inserted.

My statements:

```<code>    SELECT
        TIMESTAMP_EXPIRATION
    FROM TABLE1;

    INSERT INTO TABLE2 (EXPIRATION_T)
    VALUES ($TIMESTAMP_EXPIRATION);
</code>```

The problem is that half of my  source records are null and the other half are TIMESTAMP with a degree of 6

The definition of source and destination tables have the column as 'TIMESTAMP_EXPIRATION FOR COLUMN 0011TTT TIMESTAMP DEFAULT NULL' and 'EXPIRATION_T FOR COLUMN 00EETTT TIMESTAMP DEFAULT NULL'

WHat can I do to get the null values to insert as well?

UPDATE: CREATION STATEMENTS

```<code> CREATE TABLE TABLE1 (
    ID INTEGER GENERATED ALWAYS AS IDENTITY (
    START WITH 1 INCREMENT BY 1 ),

    TIMESTAMP_EXPIRATION FOR COLUMN 0011TTT TIMESTAMP DEFAULT NULL )

    RCDFMT TABLE1      ;

CREATE TABLE TABLE2 (
    ID INTEGER GENERATED ALWAYS AS IDENTITY (
    START WITH 1 INCREMENT BY 1 ),

    EXPIRATION_T} FOR COLUMN 00EETTT TIMESTAMP DEFAULT NULL )

    RCDFMT TABLE2      ;
</code>```

UPDATE: PHP SCRIPT

```<code>    $getDev = "
    SELECT
        ID,
        TIMESTAMP_EXPIRATION
    FROM TABLE1
";

$stmt = odbc_exec($DB2connDEV, $getDev);

while($gettingItems = odbc_fetch_array($stmt)){

    $rows[] = $gettingItems;
}

foreach($rows as $row){

    $originalID = $row['ID'];
    $expiration = $row['TIMESTAMP_EXPIRATION'];

    $insertTable = "INSERT INTO table2 (id,expiration_t) VALUES (
        $originalID,
        '$expiration')";

    $stmt = odbc_exec($DB2connPROD, $insertTable);
}
</code>```

答:
Consider parameterization with a prepared statement and not string interpolation such as this '$expiration' that renders null to empty string:

$apn_stmt = odbc_prepare($DB2connPROD, "INSERT INTO table2 (id, expiration_t) VALUES (?, ?)");
$sel_stmt = odbc_exec($DB2connDEV, "SELECT ID, TIMESTAMP_EXPIRATION FROM TABLE1");

while($gettingItems = odbc_fetch_array($sel_stmt)) {
    $rows[] = $gettingItems;
}

foreach($rows as $row) {
    $originalID = $row['ID'];
    $expiration = ($row['TIMESTAMP_EXPIRATION'] == '' ? NULL : $row['TIMESTAMP_EXPIRATION']);
    $insertTable = odbc_execute($apn_stmt, array($originalID, $expiration));
}
```

Body:
When selecting timestamps (which are nullable with defualt null) from a source table through a PHP script and trying to insert into an identical destination table,
I get the error 'SYNTAX of date, time or timestamp value not valid SQL state 22008'. I believe it's because some source records are null. When the script runs, I get about half the records inserted into my destination table successfully but only the ones that have actual timestamp values. The null records haven't been inserted.

My statements:

    SELECT
        TIMESTAMP_EXPIRATION
    FROM TABLE1;

    INSERT INTO TABLE2 (EXPIRATION_T)
    VALUES ($TIMESTAMP_EXPIRATION);

The problem is that half of my  source records are null and the other half are TIMESTAMP with a degree of 6

The definition of source and destination tables have the column as 'TIMESTAMP_EXPIRATION FOR COLUMN 0011TTT TIMESTAMP DEFAULT NULL' and 'EXPIRATION_T FOR COLUMN 00EETTT TIMESTAMP DEFAULT NULL'

WHat can I do to get the null values to insert as well?

UPDATE: CREATION STATEMENTS

 CREATE TABLE TABLE1 (
    ID INTEGER GENERATED ALWAYS AS IDENTITY (
    START WITH 1 INCREMENT BY 1 ),

    TIMESTAMP_EXPIRATION FOR COLUMN 0011TTT TIMESTAMP DEFAULT NULL )

    RCDFMT TABLE1      ;

CREATE TABLE TABLE2 (
    ID INTEGER GENERATED ALWAYS AS IDENTITY (
    START WITH 1 INCREMENT BY 1 ),

    EXPIRATION_T} FOR COLUMN 00EETTT TIMESTAMP DEFAULT NULL )

    RCDFMT TABLE2      ;

UPDATE: PHP SCRIPT

    $getDev = "
    SELECT
        ID,
        TIMESTAMP_EXPIRATION
    FROM TABLE1
";

$stmt = odbc_exec($DB2connDEV, $getDev);

while($gettingItems = odbc_fetch_array($stmt)){

    $rows[] = $gettingItems;
}

foreach($rows as $row){

    $originalID = $row['ID'];
    $expiration = $row['TIMESTAMP_EXPIRATION'];

    $insertTable = "INSERT INTO table2 (id,expiration_t) VALUES (
        $originalID,
        '$expiration')";

    $stmt = odbc_exec($DB2connPROD, $insertTable);
}


问:
Setting gradient background color to LaunchScreen which will display a logo image at center
I have a requirement to set a Gradient background to the launch screen with a UIImageView in the center which shows the app logo . I tried having a view controller but I realised code will never be invoked.

I need some way to get behaviour as the code below does

```<code>self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!)
</code>```

I went through lot of answers about the same topic,  most of the questions on gradient colour don't seem to have any  additional requirements like showing another image other than the background .

I can hardcode the color in IB but i don't get the gradient.

答:
You can use 2 layers of UIImageView:

The first is large and contain the background gradient image, and a second layer of centered image (with transparent backgrount) of the logo.

Body:
I have a requirement to set a Gradient background to the launch screen with a UIImageView in the center which shows the app logo . I tried having a view controller but I realised code will never be invoked.

I need some way to get behaviour as the code below does

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!)

I went through lot of answers about the same topic,  most of the questions on gradient colour don't seem to have any  additional requirements like showing another image other than the background .

I can hardcode the color in IB but i don't get the gradient.