问:
Spring boot dependency injection for value
I am a newbee here and I have one question on Spring Boot.

I have the following classes:

```<code>ClassA
{
    LocalDate d1;
    LocalDate d2;
    List<ClassB> bList;
    List<ClassC> cList;
    //.. and a few more such List attributes
}

ClassB
{

    //Certain logic for which I need LocalDate d1 and LocalDate d2.
}

ClassC
{

    //Certain logic for which I need LocalDate d1 and LocalDate d2.
}
</code>```

Classes B and C have a certain logic for which I need "LocalDate d1" and "LocalDate d2" from ClassA. Basically, imagine ClassB and ClassC also have local "LocalDate d1" and local "LocalDate d2" variables, but values for these should be same as ClassA values.

Question: What is the best way to pass "LocalDate d1" and "LocalDate
  d2" values to ClassB and ClassC.

I do not want to use InnerClass. (Too big classes and too many of
them)

I can not make "LocalDate d1" and "LocalDate d2" static, as
there will be many instances of ClassA each with different "LocalDate
d1" and "LocalDate d2"

Without Dependency Injection, I would have manually instantiated bList inside ClassA and would have passed (LocalDate d1, LocalDate d2) as constructor parameter to each instance that I add to the bList. But how to achieve this with dependency injection?

答:
LocalDate seems like a bad candidate for dependency injection as it does not contain any custom logic.

It often gets generated as a result of some action, API response, DB fetch, data messaging etc etc.

These actions are what should be injected by the spring container and not the raw results that they might return.

Body:
I am a newbee here and I have one question on Spring Boot.

I have the following classes:

ClassA
{
    LocalDate d1;
    LocalDate d2;
    List<ClassB> bList;
    List<ClassC> cList;
    //.. and a few more such List attributes
}

ClassB
{

    //Certain logic for which I need LocalDate d1 and LocalDate d2.
}

ClassC
{

    //Certain logic for which I need LocalDate d1 and LocalDate d2.
}

Classes B and C have a certain logic for which I need "LocalDate d1" and "LocalDate d2" from ClassA. Basically, imagine ClassB and ClassC also have local "LocalDate d1" and local "LocalDate d2" variables, but values for these should be same as ClassA values.

Question: What is the best way to pass "LocalDate d1" and "LocalDate
  d2" values to ClassB and ClassC.

I do not want to use InnerClass. (Too big classes and too many of
them)

I can not make "LocalDate d1" and "LocalDate d2" static, as
there will be many instances of ClassA each with different "LocalDate
d1" and "LocalDate d2"

Without Dependency Injection, I would have manually instantiated bList inside ClassA and would have passed (LocalDate d1, LocalDate d2) as constructor parameter to each instance that I add to the bList. But how to achieve this with dependency injection?


来源: stackexchange

问:
Question regarding multi-threaded environment of servlet
If there is a servlet, inside a servlet container such as Websphere. The servlet are executed by some threads. I would like to ask, what does the threads share? How variables are shared between them?

Do they have a local copy of the following variables?

1) private/protected/public final Semaphore permits = new Semaphore(50);

2) private/protected/public final static Semaphore permits = new Semaphore(50);

3) private/protected/public Semaphore permits = new Semaphore(50);

4) private/protected/public static Semaphore permits = new Semaphore(50);

How should I declare the semaphore so that I can use semaphore to control them? I don't want them to have each of them a copy of the semaphore. Thanks.

答:
Each thread has its own stack, but all share the same memory space. With that in mind, a single instance can be shared, and so its state/properties, among multiple threads. Hence, we need to take care of state using synchronisation or similar techniques.

If you define a static variable or a single instance of servlet will be used -- which is highly likely but no guarantee, then it would be the same for all threads.

Nonetheless, you should create a class which provide a singleton semaphore to be used in servlet. That way servlet instances will be using the one and the same semaphore object, no matter what.

ContentLicense: CC BY-SA 3.0


问:
Rails API Globalize get all translations
In an API-only rails app using globalize - how do I return all the translations for a model?

ie.

```<code>[
    {
        "id": 1,
        "name_ar": "كرستوفر نولان",
        "name_en": "Christopher Nolan",
        "name_fr": "Christopher Nolan"
    },
    {
        "id": 2,
        "name_ar": "ميشيل جوندري",
        "name_en": "Michael Gondry",
        "name_fr": "Michael Gondry"
    },
    // ...
]
</code>```

I've been searching for quite some time about this but I have failed to find a solution.

答:
You can do something like this: (not a complete efficient solution but just a try if that helps)

```<code># translated attribute names
attrs = %w[title description]

def translated_attributes(objects, attributes)
  result = []
  objects.each do |obj|
    trans = {}
    obj.translations.each do |tr|
      trans['id'] = obj.id
      attributes.each do |attr|
       trans[attr + '_' + tr['locale']] = tr[attr]
     end
    end
    result << trans
  end
  result
end

translated_attributes(objects, attrs)
</code>```

Please change the names according to your application and pass the attributes accordingly.

ContentLicense: CC BY-SA 4.0

Body:
In an API-only rails app using globalize - how do I return all the translations for a model?

ie.

[
    {
        "id": 1,
        "name_ar": "كرستوفر نولان",
        "name_en": "Christopher Nolan",
        "name_fr": "Christopher Nolan"
    },
    {
        "id": 2,
        "name_ar": "ميشيل جوندري",
        "name_en": "Michael Gondry",
        "name_fr": "Michael Gondry"
    },
    // ...
]

I've been searching for quite some time about this but I have failed to find a solution.

Body:
You can do something like this: (not a complete efficient solution but just a try if that helps)

# translated attribute names
attrs = %w[title description]

def translated_attributes(objects, attributes)
  result = []
  objects.each do |obj|
    trans = {}
    obj.translations.each do |tr|
      trans['id'] = obj.id
      attributes.each do |attr|
       trans[attr + '_' + tr['locale']] = tr[attr]
     end
    end
    result << trans
  end
  result
end

translated_attributes(objects, attrs)

Please change the names according to your application and pass the attributes accordingly.


问:
How do I linear search two arrays in c++?
I have two arrays of data type double - called array1[10] and array2[8]. I am required to search for array2 inside array1 at each element using a linear search function. The function declaration is

```<code>string linSearch (double array1[10], double array2[8]);
</code>```

If array2 is found inside array1 then I need to print out the index of where it is found in array1. If its not found I need the output to be "NA". This output must be a delimited-comma- string.
eg.

```<code>//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}

//after the linear search completes, the output must be the index in which //array2 is found in array1. if its not found, then it must be NA:

2,NA,5,6,0,NA,NA,7
</code>```

So far I have the code that follows. Its my first time working with arrays and I am still having difficulties grasping the concept- like once I define the function how do I even call it in the main program?! anyway..the function definition I have (excluding the main program) is:

```<code>string linSearch (double array1[10], double array2[8])
{
    int index1 = 0;
    int index2 =0;
    int position =-1;
    bool found = false;
    while (index1<10 && !found && index2<8)
    {
        if array1[index1] == array2[index2])
        {
            found = true;
            position = index1;
        }
        index1++;
        index2++;
    }

    return position;

}
</code>```

I am EXTREMELY confused about searching for one array in the other and how to output the delimited list as well as how to connect it to my main program. Any help would be GREATLY appreciated. Thanks!

答:
In your example of arrays and the expected output

```<code>//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}
</code>```

and

```<code>2,NA,5,6,0,NA,NA,7
       ^
</code>```

there is a typo. The output should be

```<code>2,NA,5,3,0,NA,NA,7
       ^
</code>```

because the number 7 is found in the third position of the array array1.

Here you are.

```<code>#include <iostream>
#include <string>
#include <sstream>

std::string linearSearch( const double a1[], size_t n1, const double a2[], size_t n2 )
{
    std::ostringstream os;

    for ( size_t i = 0; i < n2; i++ )
    {
        if ( i != 0  ) os << ',';

        size_t j = 0;

        while ( j < n1 && a2[i] != a1[j] ) ++j;

        if ( j == n1 ) os << "NA";
        else os << j;
    }

    return os.str();
}

int main()
{
    double a1[] = { 1.1, 1.2, 6, 7, 3.5, 2, 7, 8.8, 9, 23.4 };
    const size_t N1 = sizeof( a1 ) / sizeof( *a1 );
    double a2[] = { 6, 45, 2, 7, 1.1, 5, 4, 8.8 };
    const size_t N2 = sizeof( a2 ) / sizeof( *a2 );

    std::cout << linearSearch( a1, N1, a2, N2 ) << '\n';

    return 0;
}
</code>```

The program output is

```<code>2,NA,5,3,0,NA,NA,7
</code>```

Body:
I have two arrays of data type double - called array1[10] and array2[8]. I am required to search for array2 inside array1 at each element using a linear search function. The function declaration is

string linSearch (double array1[10], double array2[8]);

If array2 is found inside array1 then I need to print out the index of where it is found in array1. If its not found I need the output to be "NA". This output must be a delimited-comma- string.
eg.

//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}

//after the linear search completes, the output must be the index in which //array2 is found in array1. if its not found, then it must be NA:

2,NA,5,6,0,NA,NA,7

So far I have the code that follows. Its my first time working with arrays and I am still having difficulties grasping the concept- like once I define the function how do I even call it in the main program?! anyway..the function definition I have (excluding the main program) is:

string linSearch (double array1[10], double array2[8])
{
    int index1 = 0;
    int index2 =0;
    int position =-1;
    bool found = false;
    while (index1<10 && !found && index2<8)
    {
        if array1[index1] == array2[index2])
        {
            found = true;
            position = index1;
        }
        index1++;
        index2++;
    }

    return position;

}

I am EXTREMELY confused about searching for one array in the other and how to output the delimited list as well as how to connect it to my main program. Any help would be GREATLY appreciated. Thanks!

Body:
In your example of arrays and the expected output

//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}

and

2,NA,5,6,0,NA,NA,7
       ^

there is a typo. The output should be

2,NA,5,3,0,NA,NA,7
       ^

because the number 7 is found in the third position of the array array1.

Here you are.

#include <iostream>
#include <string>
#include <sstream>

std::string linearSearch( const double a1[], size_t n1, const double a2[], size_t n2 )
{
    std::ostringstream os;

    for ( size_t i = 0; i < n2; i++ )
    {
        if ( i != 0  ) os << ',';

        size_t j = 0;

        while ( j < n1 && a2[i] != a1[j] ) ++j;

        if ( j == n1 ) os << "NA";
        else os << j;
    }

    return os.str();
}

int main()
{
    double a1[] = { 1.1, 1.2, 6, 7, 3.5, 2, 7, 8.8, 9, 23.4 };
    const size_t N1 = sizeof( a1 ) / sizeof( *a1 );
    double a2[] = { 6, 45, 2, 7, 1.1, 5, 4, 8.8 };
    const size_t N2 = sizeof( a2 ) / sizeof( *a2 );

    std::cout << linearSearch( a1, N1, a2, N2 ) << '\n';

    return 0;
}

The program output is

2,NA,5,3,0,NA,NA,7


问:
How to Increase Line spacing in UILabel in Swift
I have a label which has few lines of text and I want to increase the spacing between the lines. There are similar questions asked by others but the solutions don't solve my problems. Also my label may or may not contain paragraphs. I am new to Swift. Is there a solution using storyboard? Or only through NSAttributedString its possible?

答:
Swift 4 and Swift 5

```<code>extension NSAttributedString {
    func withLineSpacing(_ spacing: CGFloat) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(attributedString: self)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineBreakMode = .byTruncatingTail
        paragraphStyle.lineSpacing = spacing
        attributedString.addAttribute(.paragraphStyle,
                                      value: paragraphStyle,
                                      range: NSRange(location: 0, length: string.count))
        return NSAttributedString(attributedString: attributedString)
    }
}
</code>```

How to use

```<code>    let example = NSAttributedString(string: "This is Line 1 \nLine 2 \nLine 3 ").withLineSpacing(15)
    testLabel.attributedText = example
</code>```

Body:
Swift 4 and Swift 5

extension NSAttributedString {
    func withLineSpacing(_ spacing: CGFloat) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(attributedString: self)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineBreakMode = .byTruncatingTail
        paragraphStyle.lineSpacing = spacing
        attributedString.addAttribute(.paragraphStyle,
                                      value: paragraphStyle,
                                      range: NSRange(location: 0, length: string.count))
        return NSAttributedString(attributedString: attributedString)
    }
}

How to use

    let example = NSAttributedString(string: "This is Line 1 \nLine 2 \nLine 3 ").withLineSpacing(15)
    testLabel.attributedText = example


问:
Capture only hour and minute from logs. Want to exclude seconds in output
I am running below command to capture output. In time section seconds are also getting captured. I want to exclude seconds in output. Please help

cat /tmp/dnsmasq.log  | grep query | egrep -iv 'AAA|PTR|SRV' | awk '{print $1" "$2" "$3","$8","$6}' | awk 'BEGIN{FS=OFS=","} {num=split($NF,arra
  y,".");$NF=array[num-1]"."array[num]} 1'

Sample input file is below:

May 31 17:58:57 dnsmasq[1695]: query[A] sites.google.com from 10.0.0.35

May 31 17:59:15 dnsmasq[1695]: query[A] presence.teams.microsoft.com from 10.0.0.35

I want output like this:

May 31 17:49,127.0.0.1,scotiabank.com

May 31 17:49,10.0.0.35,google.com

答:
EDIT: Adding 1 more solution after seeing your Input_file but still not clear about conditions how to get it, try following once. Written and tested with shown samples only.

```<code>awk '
BEGIN{
  OFS=","
}
/query/ && match($0,/^[a-zA-Z]+ [0-9]{2} [0-9]{2}:[0-9]{2}/){
  print substr($0,RSTART,RLENGTH),$NF,$(NF-2)
}
'  Input_file
</code>```

Since you have not shown your actual Input_file so following is written by seeing your shown command's output only.

```<code>your_command | awk 'BEGIN{FS=OFS=","} {sub(/:[0-9]{2}$/,"",$1)} 1'
</code>```

IMHO you could do all these operations in a single awk itself if you show us the sample of  Input_file, rather than using 3 to 4 pipe commands.

EDIT BY OP(Working command is): cat /tmp/dnsmasq.log| grep query | egrep -iv 'AAA|PTR|SRV' | awk '{print $1" "$2" "$3","$8","$6}' | awk 'BEGIN{FS=OFS=","} {sub(/:[0-9]{2}$/,"",$1)} 1' | awk 'BEGIN{FS=OFS=","} {num=split($NF,array,".");$NF=array[num-1]"."array[num]} 1' |sort | uniq

NOTE: This task could be done in a single awk but OP has added above commands into his/her existing code. For future users a single awk will be more efficient here.

Body:
EDIT: Adding 1 more solution after seeing your Input_file but still not clear about conditions how to get it, try following once. Written and tested with shown samples only.

awk '
BEGIN{
  OFS=","
}
/query/ && match($0,/^[a-zA-Z]+ [0-9]{2} [0-9]{2}:[0-9]{2}/){
  print substr($0,RSTART,RLENGTH),$NF,$(NF-2)
}
'  Input_file

Since you have not shown your actual Input_file so following is written by seeing your shown command's output only.

your_command | awk 'BEGIN{FS=OFS=","} {sub(/:[0-9]{2}$/,"",$1)} 1'

IMHO you could do all these operations in a single awk itself if you show us the sample of  Input_file, rather than using 3 to 4 pipe commands.

EDIT BY OP(Working command is): cat /tmp/dnsmasq.log| grep query | egrep -iv 'AAA|PTR|SRV' | awk '{print $1" "$2" "$3","$8","$6}' | awk 'BEGIN{FS=OFS=","} {sub(/:[0-9]{2}$/,"",$1)} 1' | awk 'BEGIN{FS=OFS=","} {num=split($NF,array,".");$NF=array[num-1]"."array[num]} 1' |sort | uniq

NOTE: This task could be done in a single awk but OP has added above commands into his/her existing code. For future users a single awk will be more efficient here.


答:
Using the 6 predictions example you show here:

```<code>import numpy as np

tweets_emotion = np.array([[3.1052819e-01, 2.7634043e-01, 1.6270137e-03, 7.7674150e-01],
                           [5.0230421e-02, 7.7430069e-01, 7.7313791e-09, 2.0278792e-01],
                           [9.9952579e-01, 1.3450404e-03, 5.8804121e-20, 3.2991991e-07],
                           [3.9727339e-01, 2.8888196e-01, 1.9649005e-02, 2.1239746e-01],
                           [1.2528910e-01, 3.2127723e-01, 3.2503495e-03, 5.5401272e-01],
                           [5.8543805e-02, 4.5720499e-05, 2.9060062e-12, 9.3766922e-01]])

tweets_emotion_class = np.argmax(tweets_emotion, axis=1)
tweets_emotion_class
# array([3, 1, 0, 0, 3, 3])
</code>```

You should be able to verify by simple visual inspection that indeed, the maximum values of each array element are the ones shown in tweets_emotion_class.

Irrelevant to your issue but, as mentioned in the comments, sigmoid activation for the last network layer does not make sense in single-label multi-class settings with one-hot encoded labels, as your setting seems to be - you should change it to softmax.

Title: Tweet emotion prediction using CNN

Body:
I have a built a CNN model for tweet emotion detection and the final step is as follows:

tweets_emotion = model.predict(val_tweets, verbose= 0)

which gave me predicted output like this

array([[3.1052819e-01, 2.7634043e-01, 1.6270137e-03, 7.7674150e-01],
       [5.0230421e-02, 7.7430069e-01, 7.7313791e-09, 2.0278792e-01],
       [9.9952579e-01, 1.3450404e-03, 5.8804121e-20, 3.2991991e-07],
       ...,
       [3.9727339e-01, 2.8888196e-01, 1.9649005e-02, 2.1239746e-01],
       [1.2528910e-01, 3.2127723e-01, 3.2503495e-03, 5.5401272e-01],
       [5.8543805e-02, 4.5720499e-05, 2.9060062e-12, 9.3766922e-01]],
      dtype=float32)

my actual output should look like this:

array([[1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       ...,
       [0., 0., 0., 1.],
       [0., 0., 0., 1.],
       [0., 0., 0., 1.]], dtype=float32)

Is there a way to convert my predicted output (tweets_emotion) to look like the output that I expected?

Body:
Using the 6 predictions example you show here:

import numpy as np

tweets_emotion = np.array([[3.1052819e-01, 2.7634043e-01, 1.6270137e-03, 7.7674150e-01],
                           [5.0230421e-02, 7.7430069e-01, 7.7313791e-09, 2.0278792e-01],
                           [9.9952579e-01, 1.3450404e-03, 5.8804121e-20, 3.2991991e-07],
                           [3.9727339e-01, 2.8888196e-01, 1.9649005e-02, 2.1239746e-01],
                           [1.2528910e-01, 3.2127723e-01, 3.2503495e-03, 5.5401272e-01],
                           [5.8543805e-02, 4.5720499e-05, 2.9060062e-12, 9.3766922e-01]])

tweets_emotion_class = np.argmax(tweets_emotion, axis=1)
tweets_emotion_class
# array([3, 1, 0, 0, 3, 3])

You should be able to verify by simple visual inspection that indeed, the maximum values of each array element are the ones shown in tweets_emotion_class.

Irrelevant to your issue but, as mentioned in the comments, sigmoid activation for the last network layer does not make sense in single-label multi-class settings with one-hot encoded labels, as your setting seems to be - you should change it to softmax.


问:
How does Android application store state
I want to ask that where does the password gets stored after we login to the application from our phone. I need to know the mechanism of working of how the state is saved in the case of mobile applications.</p>

答:
There is no specific place to store the user credentials. The thing is we should be able to read and write from the place we write it.

Mainly we use sharedPreferences for this. This is a file that is saved in a folder that is specific to that particular app. This is cleared when we uninstall the app or clear the data. It stores data as key, value pair.

Actually we don't store the username and password. When we submit the username and password to the server, if the credentials are valid, we get a access token in response. That will be a string and is saved in sharedPreferences. Next time when we open the app, we first check whether a token is already present in the sharedPreferences. If yes we directly goto the inside of the app and any server calls can be authenticated using this token. If such token is not present, we goto login screen.


问:
What is wrong with my PHP WordPress code?
This is my code in index.php of the WordPress theme:

```<code><div id="content">
            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "";
                } else {
                    $specialprt = "prt-right";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">
                <div class="prt-img">
                    <?php echo bdw_get_images($post->the_ID, 'medium'); ?>
                </div>
                <div class="prt-tags">
                    <?php the_tags(' ', ''); ?>
                </div>
                <h2 class="prt-title">
                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a>
                </h2>
                <span class="prt-small">Posted on <?php the_time('l F jS') ?> by <?php the_author() ?></span>
                <p><?php the_excerpt(); ?></p>
                <p><?php edit_post_link('Edit', '', ''); ?></p>
            </div>
            <?php $counter++; ?>
            <?php endwhile; ?>
            <?php endif; ?>
        </div><!-- #content -->
</code>```

Problems:

All the posts have the same image. Why?

Page loads very slow. Why?

Can anybody give a hand of help? :)

Thanks.

UPDATE:

I have better results with this:

```<code><div id="content">
            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); $counter++; ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "prt-right";
                } else {
                    $specialprt = "";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">
                <div class="prt-img">
                    <?php
                    $args = array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $post->ID );
                    $attachments = get_posts($args);
                    if ($attachments) {
                        foreach ( $attachments as $attachment ) {
                            the_attachment_link( $attachment->ID , true, false, false );
                        }
                    } else {
                        echo "<img src=\"<?php bloginfo('stylesheet_directory'); ?>/images/no-image.jpg\" width=\"250\" height=\"155\" />";
                    }
                    ?>
                </div>
                <div class="prt-tags">
                    <?php the_tags(' ', ''); ?>
                </div>
                <h2 class="prt-title">
                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a>
                </h2>
                <span class="prt-small">Posted on <?php the_time('l F jS') ?> by <?php the_author() ?></span>
                <p><?php the_excerpt(); ?></p>
                <p><?php edit_post_link('Edit', '', ''); ?></p>
            </div>
            <?php endwhile; ?>
            <?php endif; ?>
        </div><!-- #content -->
</code>```

答:
How many images is

```
<code>
echo "hello world";
</code>
```

returning? If it is loading in a lot of images, or just a few large ones that could be the cause of your page loading slowly.

Body:
This is my code in index.php of the WordPress theme:

            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "";
                } else {
                    $specialprt = "prt-right";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">

                    <?php echo bdw_get_images($post->the_ID, 'medium'); ?>

                    <?php the_tags(' ', ''); ?>

                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?>

                Posted on <?php the_time('l F jS') ?> by <?php the_author() ?>

<?php the_excerpt(); ?>

<?php edit_post_link('Edit', '', ''); ?>

            <?php $counter++; ?>
            <?php endwhile; ?>
            <?php endif; ?>

Problems:

All the posts have the same image. Why?

Page loads very slow. Why?

Can anybody give a hand of help? :)

Thanks.

UPDATE:

I have better results with this:

            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); $counter++; ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "prt-right";
                } else {
                    $specialprt = "";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">

                    <?php
                    $args = array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $post->ID );
                    $attachments = get_posts($args);
                    if ($attachments) {
                        foreach ( $attachments as $attachment ) {
                            the_attachment_link( $attachment->ID , true, false, false );
                        }
                    } else {
                        echo "<img src=\"<?php bloginfo('stylesheet_directory'); ?>/images/no-image.jpg\" width=\"250\" height=\"155\" />";
                    }
                    ?>

                    <?php the_tags(' ', ''); ?>

                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?>

                Posted on <?php the_time('l F jS') ?> by <?php the_author() ?>

<?php the_excerpt(); ?>

<?php edit_post_link('Edit', '', ''); ?>

            <?php endwhile; ?>
            <?php endif; ?>

Body:
How many images is

echo "hello world";

returning? If it is loading in a lot of images, or just a few large ones that could be the cause of your page loading slowly.


问:
spring mvc resource not found in form action login
in login.jsp user input username and password, if username or password is not correct,then echo error message to ${error}.

But when I type login button(http://localhost:8080/project_name/login.jsp),it navigates to  "http://localhost:8080/project_name/login",and shows resource [/project_name/login] not found.

WebContent/login.jsp

```<code><%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Login</title>
</head>
<body>
    <form action="login" method="post">
        <table>
            <tr>
                <td>username: </td>
                <td><input type="text" name="username" /></td>
            </tr>
            <tr>
                <td>password: </td>
                <td><input type="text" name="password" /></td>
            </tr>
            <tr>
                <td><input type="submit" value="login"></td>
                <td></td>
            </tr>
        </table>
    </form>
    <font color="red">${error}</font>
</body>
</html>
</code>```

WebContent/WEB-INF/web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>dbquery</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

</web-app>
</code>```

src/com/wise/controller/LoginController.java

```<code>@Controller
public class LoginController {
    @Autowired
    LoginService service;
    @Autowired
    HttpServletRequest request;

    @RequestMapping(value="/login")
    public ModelAndView doLogin() {
        String loginUrl = "/login.jsp";
        String successUrl = "/WEB-INF/jsp/query.jsp";
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        return service.doLogin(loginUrl, successUrl, username, password);
    }
}
</code>```

答:
in WebContent/WEB-INF/web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>dbquery</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

    <servlet>
        <servlet-name>dbquery</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dbquery</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

and add new WebContent/WEB-INF/dbquery-servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        classpath:/org/springframework/beans/factory/xml/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        classpath:/org/springframework/context/config/spring-context.xsd">

    <mvc:annotation-driven />
    <context:component-scan
        base-package="com.wise.controller" />
    <mvc:default-servlet-handler />
</beans>
</code>```

Body:
in login.jsp user input username and password, if username or password is not correct,then echo error message to ${error}.

But when I type login button(http://localhost:8080/project_name/login.jsp),it navigates to  "http://localhost:8080/project_name/login",and shows resource [/project_name/login] not found.

WebContent/login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Login</title>

    <form action="login" method="post">

                username:
                <input type="text" name="username" />

                password:
                <input type="text" name="password" />

                <input type="submit" value="login">

    </form>
    ${error}

WebContent/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>dbquery</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

</web-app>

src/com/wise/controller/LoginController.java

@Controller
public class LoginController {
    @Autowired
    LoginService service;
    @Autowired
    HttpServletRequest request;

    @RequestMapping(value="/login")
    public ModelAndView doLogin() {
        String loginUrl = "/login.jsp";
        String successUrl = "/WEB-INF/jsp/query.jsp";
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        return service.doLogin(loginUrl, successUrl, username, password);
    }
}

Body:
in WebContent/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>dbquery</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

    <servlet>
        <servlet-name>dbquery</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dbquery</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

and add new WebContent/WEB-INF/dbquery-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        classpath:/org/springframework/beans/factory/xml/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        classpath:/org/springframework/context/config/spring-context.xsd">

    <mvc:annotation-driven />
    <context:component-scan
        base-package="com.wise.controller" />
    <mvc:default-servlet-handler />
</beans>


答: It's saved in the database but not as plain text. Before storing it the password is hashed and when checking the login information the given password is hashed and verified with the hashed password from the database.</p>

Title: How does Android application store state

Body: I want to ask that where does the password gets stored after we login to the application from our phone. I need to know the mechanism of working of how the state is saved in the case of mobile applications.


问:
Falling back / 3-way messages in rebase
When I rebase on the remote tracking branch for master, I get the following message

```<code>$ git rebase origin/master
First, rewinding head to replay your work on top of it...
Applying: 'XXX'
Using index info to reconstruct a base tree...
Falling back to patching base and 3-way merge...
</code>```

What does "patching base" mean here? Are 3-way merges done on a file by file basis? Is there any way to disable them?

答:
It is a technical message, which shouldn't bother you.

The important thing is to see :

if git tells you that there is a merge conflict : git will stop with an explicit message right afterwards,

or if it managed to apply the changes and proceed : git will proceed with its regular progress messages until the "successfully rebased x ..." message appears.

Title: Falling back / 3-way messages in rebase

Body:
When I rebase on the remote tracking branch for master, I get the following message

$ git rebase origin/master
First, rewinding head to replay your work on top of it...
Applying: 'XXX'
Using index info to reconstruct a base tree...
Falling back to patching base and 3-way merge...

What does "patching base" mean here? Are 3-way merges done on a file by file basis? Is there any way to disable them?


问:
How to tell from a JSON array or a JSON?
I have a JSON file which is from a server but don't know what the difference from a string or a list or a array.

What I am trying to do is using the server html such as http://servername:5018/hoteldata and I don't know how to tell from an array or list or string, I want to call it from that as it is a JSON file and call it on HTML

```<code>        [
  {
    "firstname": "Bill",
    "lastname": "Richson",
    "numberofguest": "1"
  },
  {
    "firstname": "Jane",
    "lastname": "Freda",
    "numberofguest": "3"
  },
  {
    "firstname": "Mark",
    "lastname": "Harrison",
    "numberofguest": "7"
  },
  {
    "firstname": "Chris",
    "lastname": "Asher",
    "numberofguest": "4"
  },
  {
    "firstname": "Ruth",
    "lastname": "King",
    "numberofguest": "2"
  },
  {
    "firstname": "Andy",
    "lastname": "Webb",
    "numberofguest": "5"
  },
  {
    "firstname": "Mary ",
    "lastname": "Gardner",
    "numberofguest": "2"
  },
  {
    "firstname": "Mark",
    "lastname": "Harrison",
    "numberofguest": "7"
  },
  {
    "firstname": "Anna ",
    "lastname": "Mitchell",
    "numberofguest": "1"
  },
  {
    "firstname": "Karl",
    "lastname": "Robertson",
    "numberofguest": "3"
  },
  {
    "firstname": "Liam",
    "lastname": "Barnard",
    "numberofguest": "2"
  },
  {
    "firstname": "Tommy",
    "lastname": "McCree",
    "numberofguest": "4"
  },
  {
    "firstname": "Peter",
    "lastname": "Root",
    "numberofguest": "6"
  },
  {
    "firstname": "Test",
    "lastname": "Guest",
    "numberofguest": "1"
  }
]
</code>```

答:
The individual components within the {}-brackets stand for a name and a value. "firstname" would be the name of the value and "Richson" is the value. That would be a string. The entirety within the {}-brackets is a JSON-object. The entirety within the []-brackets is a JSON-array.

Check out this link for more information on JSON-syntax: https://www.w3schools.com/js/js_json_syntax.asp

Body:
I have a JSON file which is from a server but don't know what the difference from a string or a list or a array.

What I am trying to do is using the server html such as http://servername:5018/hoteldata and I don't know how to tell from an array or list or string, I want to call it from that as it is a JSON file and call it on HTML

        [
  {
    "firstname": "Bill",
    "lastname": "Richson",
    "numberofguest": "1"
  },
  {
    "firstname": "Jane",
    "lastname": "Freda",
    "numberofguest": "3"
  },
  {
    "firstname": "Mark",
    "lastname": "Harrison",
    "numberofguest": "7"
  },
  {
    "firstname": "Chris",
    "lastname": "Asher",
    "numberofguest": "4"
  },
  {
    "firstname": "Ruth",
    "lastname": "King",
    "numberofguest": "2"
  },
  {
    "firstname": "Andy",
    "lastname": "Webb",
    "numberofguest": "5"
  },
  {
    "firstname": "Mary ",
    "lastname": "Gardner",
    "numberofguest": "2"
  },
  {
    "firstname": "Mark",
    "lastname": "Harrison",
    "numberofguest": "7"
  },
  {
    "firstname": "Anna ",
    "lastname": "Mitchell",
    "numberofguest": "1"
  },
  {
    "firstname": "Karl",
    "lastname": "Robertson",
    "numberofguest": "3"
  },
  {
    "firstname": "Liam",
    "lastname": "Barnard",
    "numberofguest": "2"
  },
  {
    "firstname": "Tommy",
    "lastname": "McCree",
    "numberofguest": "4"
  },
  {
    "firstname": "Peter",
    "lastname": "Root",
    "numberofguest": "6"
  },
  {
    "firstname": "Test",
    "lastname": "Guest",
    "numberofguest": "1"
  }
]


问:
Doctrine skips datasets when using joins and offset
I'm working with Doctrine 1.2 in Symfony 1.4 on PHP5.3.

I have a database, in which events have multiple start datetimes (1:n) and types (n:m).

For a program, I want a list of start times and event title, which belong to a special type and are not outdated:

```<code>$dql = Doctrine_Query::create()
  ->select('ed.start_datetime,e.title')/*edd.*,*/
  ->from('EventDate ed')
  ->leftJoin('ed.Event e')
  ->leftJoin('e.EventTypes et')
  ->leftJoin('e.Domain d')
  ->orderBy('ed.start_datetime, ed.event_id');
  ->where('e.start_datetime >= ? AND e3.id = ?',array('2011-05-27 17:19:41',2))
  ->fetchArray();
</code>```

The schema can be reviewed at pastebin.com/SdjvsaxW.

Now, doctrine makes two statements

```<code>SELECT DISTINCT e5.event_id FROM event_date e5 LEFT JOIN event e6 ON e5.event_id = e6.id LEFT JOIN event_event_type e8 ON (e6.id = e8.event_id) LEFT JOIN event_type e7 ON e7.id = e8.event_type_id WHERE (e5.start_datetime >= '2011-05-27 17:19:41' AND e7.id = '2') ORDER BY e5.start_datetime, e5.event_id

SELECT e.event_id AS e__event_id, e.start_datetime AS e__start_datetime, e2.id AS e2__id, e2.title AS e2__title FROM event_date e LEFT JOIN event e2 ON e.event_id = e2.id LEFT JOIN event_event_type e4 ON (e2.id = e4.event_id) LEFT JOIN event_type e3 ON e3.id = e4.event_type_id WHERE e.event_id IN (*all the IDs from the first query*) AND (e.start_datetime >= '2011-05-27 17:19:41' AND e3.id = '2') ORDER BY e.start_datetime, e.event_id
</code>```

The problem starts when I introduce pagination: When I add an offset, it will be added in the first query. Now, as there might be more than one start time for an event, the number of IDs from the first SELECT DISTINCT query may be smaller than the number of dates. Consequently, dates may be skipped. In my case, there are even less than 50 different events, so the second pages displaying event date 51-100 is indeed empty, despite the fact that there are several hundred event dates (due to recurring events).

I think the problem might be solved leaving away the distinct, but I cannot control that.

Anyone any idea?

答:
Doctrine runs two queries, the first a distinct, in a mode called "limit subquery", when you have a base table and join across a one-to-many relationship.  This is because you are going to select the product of the join, and will end up with more rows than there are records in the base table.  For example, the database will return Event #5 in two rows if there are two EventTypes for Event #5.  This two query behavior is in MySQL only, other databases can run a limit in a subquery, and Doctrine generates a single query.

Since your Events have multiple dates, and EventDate has a compound primary key, Doctrine SHOULD select a distinct set of (event_id, start_datetime) in the first query, but it seems to be ignoring the second part of your compound primary key, probably because it can't stuff them into the ON clause in the second query.

You can probably work around this in one of two, or maybe three, ways:
1) add a unique primary key to EventDate (autoincrement column).  you likely don't have to reference it anywhere else, but doctrine will start using that
2) do the 2 queries manually.  Select all of the distinct event_id, start_datetime from EventDate, add your limit and offset, and then programmatically create an where clause:

```<code> ... WHERE ((event_id = ? AND start_datetime = ?) OR (event_id = ? AND start_datetime = ?))...
</code>```

3) Reorder your query to start from a different table or add a DISTINCT in the select. Try selecting distinct(ed.event_id, ed.start_datetime). Sometimes these things can avoid the limit-subquery algorithm from firing.
4) Turn this system off, see link below, never tried this and I'm not sure what side effects there are in hydration and the doctrine object cache.

Personally, I would go with #1.  I've found that it always helps to have that extra primary key column with Doctrine, even when you can form a primary key across multiple columns.

If you want to see the code doctrine uses for this, see lib/Doctrine/Record.php, function getLimitSubquery().  You'll note the comment "// what about composite keys?" in the code twice.  You can also read http://www.doctrine-project.org/documentation/manual/1_2/en/dql-doctrine-query-language:limit-and-offset-clauses:the-limit-subquery-algorithm

Body:
I'm working with Doctrine 1.2 in Symfony 1.4 on PHP5.3.

I have a database, in which events have multiple start datetimes (1:n) and types (n:m).

For a program, I want a list of start times and event title, which belong to a special type and are not outdated:

$dql = Doctrine_Query::create()
  ->select('ed.start_datetime,e.title')/*edd.*,*/
  ->from('EventDate ed')
  ->leftJoin('ed.Event e')
  ->leftJoin('e.EventTypes et')
  ->leftJoin('e.Domain d')
  ->orderBy('ed.start_datetime, ed.event_id');
  ->where('e.start_datetime >= ? AND e3.id = ?',array('2011-05-27 17:19:41',2))
  ->fetchArray();

The schema can be reviewed at pastebin.com/SdjvsaxW.

Now, doctrine makes two statements

SELECT DISTINCT e5.event_id FROM event_date e5 LEFT JOIN event e6 ON e5.event_id = e6.id LEFT JOIN event_event_type e8 ON (e6.id = e8.event_id) LEFT JOIN event_type e7 ON e7.id = e8.event_type_id WHERE (e5.start_datetime >= '2011-05-27 17:19:41' AND e7.id = '2') ORDER BY e5.start_datetime, e5.event_id

SELECT e.event_id AS e__event_id, e.start_datetime AS e__start_datetime, e2.id AS e2__id, e2.title AS e2__title FROM event_date e LEFT JOIN event e2 ON e.event_id = e2.id LEFT JOIN event_event_type e4 ON (e2.id = e4.event_id) LEFT JOIN event_type e3 ON e3.id = e4.event_type_id WHERE e.event_id IN (*all the IDs from the first query*) AND (e.start_datetime >= '2011-05-27 17:19:41' AND e3.id = '2') ORDER BY e.start_datetime, e.event_id

The problem starts when I introduce pagination: When I add an offset, it will be added in the first query. Now, as there might be more than one start time for an event, the number of IDs from the first SELECT DISTINCT query may be smaller than the number of dates. Consequently, dates may be skipped. In my case, there are even less than 50 different events, so the second pages displaying event date 51-100 is indeed empty, despite the fact that there are several hundred event dates (due to recurring events).

I think the problem might be solved leaving away the distinct, but I cannot control that.

Anyone any idea?

Body:
Doctrine runs two queries, the first a distinct, in a mode called "limit subquery", when you have a base table and join across a one-to-many relationship.  This is because you are going to select the product of the join, and will end up with more rows than there are records in the base table.  For example, the database will return Event #5 in two rows if there are two EventTypes for Event #5.  This two query behavior is in MySQL only, other databases can run a limit in a subquery, and Doctrine generates a single query.

Since your Events have multiple dates, and EventDate has a compound primary key, Doctrine SHOULD select a distinct set of (event_id, start_datetime) in the first query, but it seems to be ignoring the second part of your compound primary key, probably because it can't stuff them into the ON clause in the second query.

You can probably work around this in one of two, or maybe three, ways:
1) add a unique primary key to EventDate (autoincrement column).  you likely don't have to reference it anywhere else, but doctrine will start using that
2) do the 2 queries manually.  Select all of the distinct event_id, start_datetime from EventDate, add your limit and offset, and then programmatically create an where clause:

 ... WHERE ((event_id = ? AND start_datetime = ?) OR (event_id = ? AND start_datetime = ?))...

3) Reorder your query to start from a different table or add a DISTINCT in the select. Try selecting distinct(ed.event_id, ed.start_datetime). Sometimes these things can avoid the limit-subquery algorithm from firing.
4) Turn this system off, see link below, never tried this and I'm not sure what side effects there are in hydration and the doctrine object cache.

Personally, I would go with #1.  I've found that it always helps to have that extra primary key column with Doctrine, even when you can form a primary key across multiple columns.

If you want to see the code doctrine uses for this, see lib/Doctrine/Record.php, function getLimitSubquery().  You'll note the comment "// what about composite keys?" in the code twice.  You can also read http://www.doctrine-project.org/documentation/manual/1_2/en/dql-doctrine-query-language:limit-and-offset-clauses:the-limit-subquery-algorithm


问:
Calculate first number in a list like BlackJack card game
I am just a newbie to python and my teacher tell me to create BlackJack game.And i stuck at the stage is count the total number of card.Here is what i got now, i need general solution for this one so i create a new python for this stage(just for testing)

```<code>list=["20","10","30"]
###I want to check first character of the number and add it together so i do this.

i = 0
while i < len(list):
      first_letter=list[i][0]
      i=i+1
      second_letter=list[i][0]
      total = first_letter+second_letter
      print(total)
####This is just an example for testing.
</code>```

And when i run the code it work somehow but also have this message :

```<code>
Traceback (most recent call last):

  File "D:\PYTHON BLACKJACK\00.py", line 9, in <module>

    second_letter=int(movie[i][0])

IndexError: list index out of range
</code>```

i can not understand this one. can someone help me with this???

答:
I'm gonna try and help you while changing as little to your code as possible.

```<code> `first_letter=list[i][0]
  i=i+1
  second_letter=list[i][0]`
</code>```

Look closely what you are doing there. list[i] takes the first element of the list: "20". [0] takes the first character of that element, so: "2". What you want to do is get the second character of the string. When you change your i variable, you are changing the element you are getting from the list, not the character. What you should do is:

```<code>first_letter = list[i][0]
second_letter = list[i][1]
i += 1
</code>```

Where i =+= 1 makes sure you switch to your next item in the list for the next 'loop'.

Besides that, when you try and add characters, they will not 'add up'. If you want to numerically add the first_letter to the second_letter, you should do this:

```<code>print(int(first_letter) + int(second_letter)
</code>```

Here int() converts the character to an integer, which can be added together.

And finally, note that this method will only work when you have one digit numbers. If you want to do this with numbers regardless of their size, you should probably use a list in a list. f.e.:

```<code>items = [[3,0],[2,0],[1,0]]
</code>```

Your loop would work just fine with the edited code, and you wouldn't need to use int().

Body:
I am just a newbie to python and my teacher tell me to create BlackJack game.And i stuck at the stage is count the total number of card.Here is what i got now, i need general solution for this one so i create a new python for this stage(just for testing)

list=["20","10","30"]
###I want to check first character of the number and add it together so i do this.

i = 0
while i < len(list):
      first_letter=list[i][0]
      i=i+1
      second_letter=list[i][0]
      total = first_letter+second_letter
      print(total)
####This is just an example for testing.

And when i run the code it work somehow but also have this message :

Traceback (most recent call last):

  File "D:\PYTHON BLACKJACK\00.py", line 9, in <module>

    second_letter=int(movie[i][0])

IndexError: list index out of range

i can not understand this one. can someone help me with this???

Body:
I'm gonna try and help you while changing as little to your code as possible.

 `first_letter=list[i][0]
  i=i+1
  second_letter=list[i][0]`

Look closely what you are doing there. list[i] takes the first element of the list: "20". [0] takes the first character of that element, so: "2". What you want to do is get the second character of the string. When you change your i variable, you are changing the element you are getting from the list, not the character. What you should do is:

first_letter = list[i][0]
second_letter = list[i][1]
i += 1

Where i =+= 1 makes sure you switch to your next item in the list for the next 'loop'.

Besides that, when you try and add characters, they will not 'add up'. If you want to numerically add the first_letter to the second_letter, you should do this:

print(int(first_letter) + int(second_letter)

Here int() converts the character to an integer, which can be added together.

And finally, note that this method will only work when you have one digit numbers. If you want to do this with numbers regardless of their size, you should probably use a list in a list. f.e.:

items = [[3,0],[2,0],[1,0]]

Your loop would work just fine with the edited code, and you wouldn't need to use int().


问:
Django + Vue.js can't display images from database
I am trying to make a simple website that displays a list of fundraisers from a database with a picture for each fundraiser. However, I can't figure out why the images aren't appearing. My fundraiser model is as follows:

```<code>class Fundraiser(models.Model):
    fundraiserImage = models.ImageField(upload_to='images/', blank=True)
</code>```

I tried to display each fundraiser in the database as shown in the vue file below.

```<code>template>
  <div>
    <div>
      <ul>
        <li v-for="f of fundraisers" v-bind:key="f.id">
          <img src="f.fundraiser.fundraiserImage.url" width="500">
        </li>
      </ul>
      {{fundraisers}}
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'Fundraiser',
  data () {
    return {
      fundraisers: []
    }
  },
  mounted: function () {
    this.getFundraisers()
  },
  methods: {
    getFundraisers: function () {
      // var app = this;
      axios.get('/api/fundraisers/?format=json')
        .then(response => (this.fundraisers = response.data))
    }
  }
}
</script>
<style>
</style>
</code>```

Here's a snippet of the relevant code from my settings.py file:

```<code>STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, '../frontend/dist/static/')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mellon/media')
</code>```

and here's a snippet of the relevant code from my urls.py file:

```<code>urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

答:
you should concat your base dir with the image file name:
and i think here, there is no base url in your src image it should be like:</p>

```<code><img :src="'127.0.0.1:8000/static/'+f.fundraiser.fundraiserImage.url">
</code>```

Body:
I am trying to make a simple website that displays a list of fundraisers from a database with a picture for each fundraiser. However, I can't figure out why the images aren't appearing. My fundraiser model is as follows:

class Fundraiser(models.Model):
    fundraiserImage = models.ImageField(upload_to='images/', blank=True)

I tried to display each fundraiser in the database as shown in the vue file below.

template>

      {{fundraisers}}

</template>

Here's a snippet of the relevant code from my settings.py file:

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, '../frontend/dist/static/')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mellon/media')

and here's a snippet of the relevant code from my urls.py file:

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Body:
you should concat your base dir with the image file name:
and i think here, there is no base url in your src image it should be like:

<img :src="'127.0.0.1:8000/static/'+f.fundraiser.fundraiserImage.url">


问:
SQL query to convert Date to another format
Thanks for your help. I am not able to make out the type/format of the "Value" in a Date column.I guess its in Julian Date format.

The Column  is      paid_month and the values are below.

```<code>                  200901
                  200902
</code>```

So,please help in writing SQL query  to convert the above values(Mostly in Julian Format) in the Date Column to normal date (MM/DD/YYYY) .

Thanks
Rohit

Hi,

I am sorry for missing in giving the whole information.

1)Its a Oracle Database.
2)The column given is Paid_Month with values 200901,200902

3)I am also confused that the above value gives month & year.Day isnt given if my guess is right.

4)If its not in Julian format ,then also please help me the SQL to get at least mm/yyyy

I am using a Oracle DB and running the query
THANKS i GOT THE ANSWER.

**Now,i have to do the reverse meaning converting a date 01/09/2010 to a String which has 6 digits.
Pls help with syntax-
select to_char(01/01/2010,**

答:
For MySQL check
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

Example:

```<code>SELECT DATE_FORMAT(NOW(), '%d/%m/%Y')
</code>```

Body:
Thanks for your help. I am not able to make out the type/format of the "Value" in a Date column.I guess its in Julian Date format.

The Column  is      paid_month and the values are below.

                  200901
                  200902

So,please help in writing SQL query  to convert the above values(Mostly in Julian Format) in the Date Column to normal date (MM/DD/YYYY) .

Thanks
Rohit

Hi,

I am sorry for missing in giving the whole information.

1)Its a Oracle Database.
2)The column given is Paid_Month with values 200901,200902

3)I am also confused that the above value gives month & year.Day isnt given if my guess is right.

4)If its not in Julian format ,then also please help me the SQL to get at least mm/yyyy

I am using a Oracle DB and running the query
THANKS i GOT THE ANSWER.

**Now,i have to do the reverse meaning converting a date 01/09/2010 to a String which has 6 digits.
Pls help with syntax-
select to_char(01/01/2010,**

Body:
For MySQL check
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format

Example:

SELECT DATE_FORMAT(NOW(), '%d/%m/%Y')


问:
How do I grab a count of all the documents in a firebase collelction in angular?
I have code that grabs the documents in a collection, but it seems to only grab 15 at a time(from what I seem to understand) and I was trying to use this list to determine the total number of documents in the collection for a program I'm creating. I need to be able to tell how many documents are in the specified collection from the start.

Here is the beginning of the code, where it is apparent that the limit that the var will register is 15 and then I can never get the accurate number.

```<code>getStatistics(): void{
    const visitArray = this.afs.collection("visits").snapshotChanges();

    //console.log([this.afs.collectionGroup("visits")].length);
    this.k = 0;
    for (let val of visitArray.toString()){
        this.k += 1;
        console.log(this.k);
    }
}
</code>```

Is there a way to get the 'length' of the collection from the get-go? It is essential that I know the number of documents in the document from the very beginning.

I tried using the .get() command too and it returned the same initial number(15) of documents from the collection.

答:
You just need to subscribe to the initial pull of the collection's contents and then grab the length of that variable. So for me, I did:

```<code>const visitArray = this.afs.collection("visits").snapshotChanges();

    visitArray.subscribe(payload => {
        this.totalVisitCount = payload.length;
    });
</code>```

Then the number of documents in the specified collection is stored in totalVisitCount.

Body:
I have code that grabs the documents in a collection, but it seems to only grab 15 at a time(from what I seem to understand) and I was trying to use this list to determine the total number of documents in the collection for a program I'm creating. I need to be able to tell how many documents are in the specified collection from the start.

Here is the beginning of the code, where it is apparent that the limit that the var will register is 15 and then I can never get the accurate number.

getStatistics(): void{
    const visitArray = this.afs.collection("visits").snapshotChanges();

    //console.log([this.afs.collectionGroup("visits")].length);
    this.k = 0;
    for (let val of visitArray.toString()){
        this.k += 1;
        console.log(this.k);
    }
}

Is there a way to get the 'length' of the collection from the get-go? It is essential that I know the number of documents in the document from the very beginning.

I tried using the .get() command too and it returned the same initial number(15) of documents from the collection.

Body:
You just need to subscribe to the initial pull of the collection's contents and then grab the length of that variable. So for me, I did:

const visitArray = this.afs.collection("visits").snapshotChanges();

    visitArray.subscribe(payload => {
        this.totalVisitCount = payload.length;
    });

Then the number of documents in the specified collection is stored in totalVisitCount.


问:
How to double split string in PHP?
I have problem that I can't solve even hours searching for answer in Google.

I have string for example:

```<code>$string = "___username1,password1___username2,password2";
</code>```

I need to split string from "___" then save result into variable and then split it again from every "," so result should be:

From first split result:

```<code>$s[0] = username1,password1
$s[1] = username2,passwrod2
</code>```

And from second split I need to get result like:

```<code>username1
password1
username2
password2
</code>```

I tried:

```<code>$s0 = explode("___",$string);
$s1 = explode(",",$s0);
</code>```

Error:

Warning: explode() expects parameter 2 to be string, array given

Could you help me please?

答:
I am not sure about the best practice but maybe we could replace "_" to something else. </p>

```<code>    $s[0] = str_replace("___","*+*",$string);
    $s[0] = explode("*+*",$string);
</code>```

Title: How to double split string in PHP?

Body:
I have problem that I can't solve even hours searching for answer in Google.

I have string for example:

$string = "___username1,password1___username2,password2";

I need to split string from "___" then save result into variable and then split it again from every "," so result should be:

From first split result:

$s[0] = username1,password1
$s[1] = username2,passwrod2

And from second split I need to get result like:

username1
password1
username2
password2

I tried:

$s0 = explode("___",$string);
$s1 = explode(",",$s0);

Error:

Warning: explode() expects parameter 2 to be string, array given

Could you help me please?

Body:
I am not sure about the best practice but maybe we could replace "_" to something else.

    $s[0] = str_replace("___","*+*",$string);
    $s[0] = explode("*+*",$string);


答:
You can use JSON.parse() to parse the incoming JSON, then it's easy to spot if it's an array or not with Array.isArray()

var json =  `[
  {
    "firstname": "Richson",
    "hotel_id": "Bill",
    "lastname": "1"
  },
  {
    "firstname": "Freda",
    "hotel_id": "Jane",
    "lastname": "3"
  },
  {
    "firstname": "Harrison",
    "hotel_id": "Mark",
    "lastname": "7"
  },
  {
    "firstname": "Asher",
    "hotel_id": "Chris",
    "lastname": "4"
  },
  {
    "firstname": "King",
    "hotel_id": "Ruth",
    "lastname": "2"
  },
  {
    "firstname": "Webb",
    "hotel_id": "Andy",
    "lastname": "5"
  },
  {
    "firstname": "Gardner",
    "hotel_id": "Mary ",
    "lastname": "2"
  },
  {
    "firstname": "Harrison",
    "hotel_id": "Mark",
    "lastname": "7"
  },
  {
    "firstname": "Mitchell",
    "hotel_id": "Anna ",
    "lastname": "1"
  },
  {
    "firstname": "Robertson",
    "hotel_id": "Karl",
    "lastname": "3"
  },
  {
    "firstname": "Barnard",
    "hotel_id": "Liam",
    "lastname": "2"
  },
  {
    "firstname": "McCree",
    "hotel_id": "Tommy",
    "lastname": "4"
  },
  {
    "firstname": "Root",
    "hotel_id": "Peter",
    "lastname": "6"
  },
  {
    "firstname": "Guest",
    "hotel_id": "Test",
    "lastname": "1"
  }
]`;

var parsedJson = JSON.parse(json);

console.log(Array.isArray(parsedJson))```

Title: How to tell from a JSON array or a JSON?


问:
onActivityCreated is deprecated, how to properly use LifecycleObserver?
Google deprecate fragment’s onActivityCreated() on Android and recommend to use LifeCycleObserver:

```<code> To get a callback specifically when a Fragment activity's
     * {@link Activity#onCreate(Bundle)} is called, register a
     * {@link androidx.lifecycle.LifecycleObserver} on the Activity's
     * {@link Lifecycle} in {@link #onAttach(Context)}, removing it when it receives the
     * {@link Lifecycle.State#CREATED} callback.
</code>```

So I try to make it in recommended way, but only state I can observe in Logcat is just State: INITIALIZED.

```<code> private lateinit var lifecycleObserver: LifecycleObserver

 override fun onAttach(context: Context) {
    super.onAttach(context)

    hostActivity = context as HostActivity

    lifecycleObserver = object : LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onCreate() {
            Logger.tag("SOME-TAG")d("State: ${lifecycle.currentState}")

            if(lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) {
                Logger.tag("SOME-TAG").d("CREATED")
                hostActivity.lifecycle.removeObserver(lifecycleObserver)
            }
        }
    }

    hostActivity.lifecycle.addObserver(lifecycleObserver)
}
</code>```

What is wrong in code above?

UPDATE 1: Looks like I forgot to use hostActivity.lifecycle.currentState and checked fragment's lifecycle instead of Activities lifecycle.

UPDATE 2: Suggested by Google approach not worked for
1 Host activity and 2 fragments when you click back button from one to another, cause onAttach never called, but onActivityCreated called.

答:
All I needed was onActivityCreated(...), hence I did implement an observer that:

Automatically removes itself (using .removeObserver(...)).

Then calls passed callback (update()).

I did it in next way:

```<code>class MyActivityObserver(
    private val update: () -> Unit
) : DefaultLifecycleObserver {

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        owner.lifecycle.removeObserver(this)
        update()
    }
}
</code>```

and use it in fragments onAttach (or another lifecycle method) like:

```<code>myActivity.lifecycle.addObserver(MyActivityObserver {
    myOnActivityCreated()
})
</code>```

But to support older Android API levels, either your Activity needs to be of androidx's AppCompatActivity type (which has getLifecycle()), or, use a simple @SuppressWarnings("deprecation").

Body:
Google deprecate fragment’s onActivityCreated() on Android and recommend to use LifeCycleObserver:

 To get a callback specifically when a Fragment activity's
     * {@link Activity#onCreate(Bundle)} is called, register a
     * {@link androidx.lifecycle.LifecycleObserver} on the Activity's
     * {@link Lifecycle} in {@link #onAttach(Context)}, removing it when it receives the
     * {@link Lifecycle.State#CREATED} callback.

So I try to make it in recommended way, but only state I can observe in Logcat is just State: INITIALIZED.

 private lateinit var lifecycleObserver: LifecycleObserver

 override fun onAttach(context: Context) {
    super.onAttach(context)

    hostActivity = context as HostActivity

    lifecycleObserver = object : LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onCreate() {
            Logger.tag("SOME-TAG")d("State: ${lifecycle.currentState}")

            if(lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) {
                Logger.tag("SOME-TAG").d("CREATED")
                hostActivity.lifecycle.removeObserver(lifecycleObserver)
            }
        }
    }

    hostActivity.lifecycle.addObserver(lifecycleObserver)
}

What is wrong in code above?

UPDATE 1: Looks like I forgot to use hostActivity.lifecycle.currentState and checked fragment's lifecycle instead of Activities lifecycle.

UPDATE 2: Suggested by Google approach not worked for
1 Host activity and 2 fragments when you click back button from one to another, cause onAttach never called, but onActivityCreated called.

Body:
All I needed was onActivityCreated(...), hence I did implement an observer that:

Automatically removes itself (using .removeObserver(...)).

Then calls passed callback (update()).

I did it in next way:

class MyActivityObserver(
    private val update: () -> Unit
) : DefaultLifecycleObserver {

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        owner.lifecycle.removeObserver(this)
        update()
    }
}

and use it in fragments onAttach (or another lifecycle method) like:

myActivity.lifecycle.addObserver(MyActivityObserver {
    myOnActivityCreated()
})

But to support older Android API levels, either your Activity needs to be of androidx's AppCompatActivity type (which has getLifecycle()), or, use a simple @SuppressWarnings("deprecation").


问:
Handle custom row click
```<code><v-data-table
      :headers="headers"
      :items="medications"
      @click:row="detail"
      class="elevation-23"
    >
</code>```

This is how I have included @click:row in the v-data-table. With this when the row is clicked the detail function is called. But I have some columns in the row which is used to edit and delete option. When that is clicked I want some other functions to be called which I have defined.
But when I click that edit or delete options the details function is being called.

How can I stop @click:row to call detail function when the Actions column is clicked.

答:
To prevent click event to propagate to parent row, you should use .stop modifier in child (action buttons):</p>

```<code><v-btn @click.stop="edit">Edit</v-btn>
</code>```

Title: Handle custom row click

Body:
<v-data-table
      :headers="headers"
      :items="medications"
      @click:row="detail"
      class="elevation-23"
    >

This is how I have included @click:row in the v-data-table. With this when the row is clicked the detail function is called. But I have some columns in the row which is used to edit and delete option. When that is clicked I want some other functions to be called which I have defined.
But when I click that edit or delete options the details function is being called.

How can I stop @click:row to call detail function when the Actions column is clicked.

Body:
To prevent click event to propagate to parent row, you should use .stop modifier in child (action buttons):

<v-btn @click.stop="edit">Edit</v-btn>


答:
It looks like YYYYMM - depending on your database variant, try STR_TO_DATE(paid_month, 'YYYYMM'), then format that.

Note: MM/DD/YYYY is not "normal" format - only Americans use it. The rest of the world uses DD/MM/YYYY

Title: SQL query to convert Date to another format


问:
Controlling which form will load when in C#
I have made a project with Multiple forms in it. I am very beginner and I made main form before the login form.
Now, the main form loads first.
I want the Login form to load first.
What should I do?

EDIT:
When I tried to Change the

```<code> static void Main()
    {

        Application.Run(new Form1());
    }
</code>```

To

```<code> static void Main()
    {

        Application.Run(new startform());
    }
</code>```

Image of code after changing

When I debugged the application I got I List of Warnings And Errors

Image of Errors and Warnings

答:
Go to Program.cs File and change Name of Form in this line
 Application.Run(new Form1());

Body:
I have made a project with Multiple forms in it. I am very beginner and I made main form before the login form.
Now, the main form loads first.
I want the Login form to load first.
What should I do?

EDIT:
When I tried to Change the

 static void Main()
    {

        Application.Run(new Form1());
    }

To

 static void Main()
    {

        Application.Run(new startform());
    }

Image of code after changing

When I debugged the application I got I List of Warnings And Errors

Image of Errors and Warnings


问:
React Native Custom icon / image in Tab.Screen navigation
I have a bottomtab in my React Native setup;

<NavigationContainer>
  <Tab.Navigator>
    <Tab.Screen name="News" component={News} />
    <Tab.Screen name="Mens" component={Mens} />
    <Tab.Screen name="Ladies" component={Ladies} />
    <Tab.Screen name="Watch" component={Fixtures} />
  </Tab.Navigator>
</NavigationContainer>
```

<p>What I'd like to do is add in the middle a dummy Tab so I can add a custom icon;</p>

<pre class="lang-html prettyprint-override"><code><NavigationContainer>
  <Tab.Navigator>
    <Tab.Screen name="News" component={News} />
    <Tab.Screen name="Mens" component={Mens} />
    <Tab.Screen name="logo" />
    <Tab.Screen name="Ladies" component={Ladies} />
    <Tab.Screen name="Watch" component={Fixtures} />
  </Tab.Navigator>
</NavigationContainer>
</code>```

The challenge I'm having is where to start (TabBarOptions doesn't appear to work within the tab.screen). I've found loads of explains (they seem like overkill for adding an icon), but they all use pre-defined icon sets. What I want to do is create an icon from a custom image and then use that for the logo tab so it appears in my bottom navigation.

答:
You can set the tabbaricon like below. The there are parameters for focused as well which you can use to set images based on condition.</p>

```<code>       <Tab.Screen
          name="Settings1"
          component={SettingsScreen}
          options={{
            title: 'My profile',
            tabBarIcon: ({size,focused,color}) => {
              return (
                <Image
                  style={{ width: size, height: size }}
                  source={{
                    uri:
                      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==',
                  }}
                />
              );
            },
          }}
        />
</code>```

Body:
I have a bottomtab in my React Native setup;

<NavigationContainer>
  <Tab.Navigator>
    <Tab.Screen name="News" component={News} />
    <Tab.Screen name="Mens" component={Mens} />
    <Tab.Screen name="Ladies" component={Ladies} />
    <Tab.Screen name="Watch" component={Fixtures} />
  </Tab.Navigator>
</NavigationContainer>

What I'd like to do is add in the middle a dummy Tab so I can add a custom icon;

<NavigationContainer>
  <Tab.Navigator>
    <Tab.Screen name="News" component={News} />
    <Tab.Screen name="Mens" component={Mens} />
    <Tab.Screen name="logo" />
    <Tab.Screen name="Ladies" component={Ladies} />
    <Tab.Screen name="Watch" component={Fixtures} />
  </Tab.Navigator>
</NavigationContainer>

The challenge I'm having is where to start (TabBarOptions doesn't appear to work within the tab.screen). I've found loads of explains (they seem like overkill for adding an icon), but they all use pre-defined icon sets. What I want to do is create an icon from a custom image and then use that for the logo tab so it appears in my bottom navigation.

Body:
You can set the tabbaricon like below. The there are parameters for focused as well which you can use to set images based on condition.

       <Tab.Screen
          name="Settings1"
          component={SettingsScreen}
          options={{
            title: 'My profile',
            tabBarIcon: ({size,focused,color}) => {
              return (
                <Image
                  style={{ width: size, height: size }}
                  source={{
                    uri:
                      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==',
                  }}
                />
              );
            },
          }}
        />


问:
Iterating over df column list and replacing existing keys with their values from a dictionary efficiently python
I have a dict with items probabilities.
I have a df with 5 milion rows that looks like that:

```<code>user_id   item_list
 U1       [I1,I3,I4]
 U2       [I5,I4]
</code>```

and a dict: {'I1': 0.1, 'I4': 0.4, ..}

I am trying to go each row and creat a list with probailities, like that:

```<code>user_id   item_list     prob_list
 U1       [I1,I3,I4]    [0.1,0.4]
 U2       [I5,I4]       [0.4]
</code>```

not all items have probabilities.

This is my code:

```<code>keys = list(prob_dict.keys())
df['prob_list'] = df.progress_apply(lambda x: get_probability(prob_dict=prob_dict,
keys=keys, item_list=x['item_list']),axis=1)

def get_probability(prob_dict, keys, item_list):

    prob_list = []
    for item in item_list:
        if item  in keys:
           prob = prob_dict[item ]
           prob_list.append(prob)

    if len(prob_list)>=1:
        return prob_list
    else:
        return np.nan
</code>```

Since I am using tqdm I know how long its going to take (120 hours), which is too much and it's clearly not efficient.

Any ideas on how I can do it more efficently?

答:
Use, Series.transform to transform each item in item_list to pandas Series and correspondingly map this series using Series.map to a mapping dictionary d, then use dropna to drop the NaN values:

```<code>d = {'I1': 0.1, 'I4': 0.4}

df['prob_list'] = (
    df['item_list'].transform(lambda s: pd.Series(s).map(d).dropna().values)
)
</code>```

UPDATE (Use multiprocessing to improve the speed of mapping the item_list to prob_list):

```<code>import multiprocessing as mp

def map_prob(s):
    s = s[~s.isna()]
    return s.transform(
        lambda lst: [d[k] for k in lst if k in d] or np.nan)

def parallel_map(item_list):
    splits = np.array_split(item_list, mp.cpu_count())
    pool = mp.Pool()
    prob_list = pd.concat(pool.map(map_prob, splits))
    pool.close()
    pool.join()
    return prob_list

df['prob_list'] = parallel_map(df['item_list'])
</code>```

Result:

```<code># print(df)
  uer_id     item_list   prob_list
0     U1  [I1, I3, I4]  [0.1, 0.4]
1     U2      [I5, I4]       [0.4]
</code>```

Body:
I have a dict with items probabilities.
I have a df with 5 milion rows that looks like that:

user_id   item_list
 U1       [I1,I3,I4]
 U2       [I5,I4]

and a dict: {'I1': 0.1, 'I4': 0.4, ..}

I am trying to go each row and creat a list with probailities, like that:

user_id   item_list     prob_list
 U1       [I1,I3,I4]    [0.1,0.4]
 U2       [I5,I4]       [0.4]

not all items have probabilities.

This is my code:

keys = list(prob_dict.keys())
df['prob_list'] = df.progress_apply(lambda x: get_probability(prob_dict=prob_dict,
keys=keys, item_list=x['item_list']),axis=1)

def get_probability(prob_dict, keys, item_list):

    prob_list = []
    for item in item_list:
        if item  in keys:
           prob = prob_dict[item ]
           prob_list.append(prob)

    if len(prob_list)>=1:
        return prob_list
    else:
        return np.nan

Since I am using tqdm I know how long its going to take (120 hours), which is too much and it's clearly not efficient.

Any ideas on how I can do it more efficently?

Body:
Use, Series.transform to transform each item in item_list to pandas Series and correspondingly map this series using Series.map to a mapping dictionary d, then use dropna to drop the NaN values:

d = {'I1': 0.1, 'I4': 0.4}

df['prob_list'] = (
    df['item_list'].transform(lambda s: pd.Series(s).map(d).dropna().values)
)

UPDATE (Use multiprocessing to improve the speed of mapping the item_list to prob_list):

import multiprocessing as mp

def map_prob(s):
    s = s[~s.isna()]
    return s.transform(
        lambda lst: [d[k] for k in lst if k in d] or np.nan)

def parallel_map(item_list):
    splits = np.array_split(item_list, mp.cpu_count())
    pool = mp.Pool()
    prob_list = pd.concat(pool.map(map_prob, splits))
    pool.close()
    pool.join()
    return prob_list

df['prob_list'] = parallel_map(df['item_list'])

Result:

# print(df)
  uer_id     item_list   prob_list
0     U1  [I1, I3, I4]  [0.1, 0.4]
1     U2      [I5, I4]       [0.4]


问:
How to create a DbContext instance of the specified database type
I know that the default return here is the SQL Server database type, but I need the MySQL database type, the problem is to create a DbContext instance of the specified database type?

Of course, I know that it can also be created by specifying the connectionName, but the database connection string is encrypted and the string needs to be decrypted

The pseudo code is as follows:

```<code>public partial class MyDbContext : DbContext
{
    static string mysqlConn = ReadConnectionString(); //Get the encrypted MySQL connection string

    public MyDbContext() : base(mysqlConn)
    {
        // Even if I want to modify the connection string in this way, nor will it throw a connection string malformed exception
        Database.Connection.ConnectionString = DecryptConnectionString(mysqlConn);
    }
}
</code>```

答:
I had same problem and found .Net framework 4.5 needs additional attribute on DbContext class to use MySql as below</p>

```<code>[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class MySqlContext : DbContext
{
...
}
</code>```

Body:
I know that the default return here is the SQL Server database type, but I need the MySQL database type, the problem is to create a DbContext instance of the specified database type?

Of course, I know that it can also be created by specifying the connectionName, but the database connection string is encrypted and the string needs to be decrypted

The pseudo code is as follows:

public partial class MyDbContext : DbContext
{
    static string mysqlConn = ReadConnectionString(); //Get the encrypted MySQL connection string

    public MyDbContext() : base(mysqlConn)
    {
        // Even if I want to modify the connection string in this way, nor will it throw a connection string malformed exception
        Database.Connection.ConnectionString = DecryptConnectionString(mysqlConn);
    }
}

Body:
I had same problem and found .Net framework 4.5 needs additional attribute on DbContext class to use MySql as below

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class MySqlContext : DbContext
{
...
}


问:
Selecting rows with groupby, summing columns and creating new column with the sum for all groupby elements
I have this dataframe:

```<code>nome       code  tipo   score
Alexandre   AAA  Frads  4000
Alexandre   AAA  Memb   10000
Alexandre   AAA  Memb   20000
Bruno       BBB  Dans   10000
Bruno       BBB  Grap   4000
</code>```

Values available in this Google Sheets

I need to create a new column summing the rows with same nome and code where tipo = 'Memb', in a way that it looks like this:

I tried groupby with transform('sum') however it is getting me the wrong result.

```<code>df['score'].loc[df['tipo'] == "Memb"]=df[['nome','code','score']].groupby(['nome','code'])['score'].transform('sum')
</code>```

What am I missing?

答:
For improve performance is possible replace score to 0 values by Series.mask and then use GroupBy.transform with sum:

```<code>df['Memb_sum']  = (df.assign(score=df['score'].mask(df['tipo'] != 'Memb', 0))
                     .groupby(['nome','code'])['score']
                     .transform('sum'))
print (df)
        nome code   tipo  score  Memb_sum
0  Alexandre  AAA  Frads   4000     30000
1  Alexandre  AAA   Memb  10000     30000
2  Alexandre  AAA   Memb  20000     30000
3      Bruno  BBB   Dans  10000         0
4      Bruno  BBB   Grap   4000         0
</code>```

Details:

```<code>print (df.assign(score=df['score'].mask(df['tipo'] != 'Memb', 0)))

        nome code   tipo  score
0  Alexandre  AAA  Frads      0
1  Alexandre  AAA   Memb  10000
2  Alexandre  AAA   Memb  20000
3      Bruno  BBB   Dans      0
4      Bruno  BBB   Grap      0
</code>```

Body:
I have this dataframe:

nome       code  tipo   score
Alexandre   AAA  Frads  4000
Alexandre   AAA  Memb   10000
Alexandre   AAA  Memb   20000
Bruno       BBB  Dans   10000
Bruno       BBB  Grap   4000

Values available in this Google Sheets

I need to create a new column summing the rows with same nome and code where tipo = 'Memb', in a way that it looks like this:

I tried groupby with transform('sum') however it is getting me the wrong result.

df['score'].loc[df['tipo'] == "Memb"]=df[['nome','code','score']].groupby(['nome','code'])['score'].transform('sum')

What am I missing?

Body:
For improve performance is possible replace score to 0 values by Series.mask and then use GroupBy.transform with sum:

df['Memb_sum']  = (df.assign(score=df['score'].mask(df['tipo'] != 'Memb', 0))
                     .groupby(['nome','code'])['score']
                     .transform('sum'))
print (df)
        nome code   tipo  score  Memb_sum
0  Alexandre  AAA  Frads   4000     30000
1  Alexandre  AAA   Memb  10000     30000
2  Alexandre  AAA   Memb  20000     30000
3      Bruno  BBB   Dans  10000         0
4      Bruno  BBB   Grap   4000         0

Details:

print (df.assign(score=df['score'].mask(df['tipo'] != 'Memb', 0)))

        nome code   tipo  score
0  Alexandre  AAA  Frads      0
1  Alexandre  AAA   Memb  10000
2  Alexandre  AAA   Memb  20000
3      Bruno  BBB   Dans      0
4      Bruno  BBB   Grap      0


问:
Get data to a python variable from a html input?
I am new to python. I need to get data from a html input to a python variable. But I can't find a way to do this. It shows output as None, None, None for output.
It doesn't print out the data too. How can I fix this issue?
This is the code in html file.

```<code>    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type=text/javascript>
            $(function() {
              $('button#add-income').bind('click', function() {
                $.getJSON('/add_income',
                    function(data) {
                  //do nothing
                });
                return false;
              });
            });
    </script>

    <form class="add-income-box" method="POST" action="">
        <div class="add-income-expences-top-div">
            <label>INCOME</label>
        </div>
        <div class="add-income-expences-label-div">
            <label class="add-income-expences-date-lbl">Date : </label>
            <label class="add-income-expences-details-lbl">Details : </label>
            <label class="add-income-expences-amount-lbl">Amount : </label>
        </div>
        <div class="add-income-expences-input-div" id="div1">
            <input class="add-income-expences-date-input" name="i_date" value="{{request.form.i_date}}">
            <input class="add-income-expences-details-input" name="i_details" value="{{request.form.i_details}}">
            <input class="add-income-expences-amount-input" name="i_amount" value="{{request.form.i_amount}}">
        </div>
        <button class="add-income-expences-bottom" id="add-income">ADD</button>
    </form>
</code>```

this is the code in python file

```<code>    @app.route('/add_income', methods=["GET", "POST"])
    def add_income():
        i_date = request.form.get('i_date')
        i_details = request.form.get('i_details')
        i_amount = request.form.get('i_amount')
        print(i_date)
        print(i_details)
        print(i_amount)
        return "nothing"
</code>```

output :-

```<code>None
None
None
127.0.0.1 - - [31/May/2020 16:56:07] "GET /add_income HTTP/1.1" 200 -
</code>```

答:
Change this form tag action attribute

```<code><form class="add-income-box" method="POST" action="{{ url_for('update_project')}}">
</code>```

In this way, when you click on button it will call the method specified in action attribute.

and if you want to call this API using AJAX then make use of JSON to send data. And if you want to send data using form then remove the Ajax code and change the code as above suggested and click on the button and you will not get the form data.

Body:
I am new to python. I need to get data from a html input to a python variable. But I can't find a way to do this. It shows output as None, None, None for output.
It doesn't print out the data too. How can I fix this issue?
This is the code in html file.

    <form class="add-income-box" method="POST" action="">

            INCOME

            Date :
            Details :
            Amount :

            <input class="add-income-expences-date-input" name="i_date" value="{{request.form.i_date}}">
            <input class="add-income-expences-details-input" name="i_details" value="{{request.form.i_details}}">
            <input class="add-income-expences-amount-input" name="i_amount" value="{{request.form.i_amount}}">

        <button class="add-income-expences-bottom" id="add-income">ADD</button>
    </form>

this is the code in python file

    @app.route('/add_income', methods=["GET", "POST"])
    def add_income():
        i_date = request.form.get('i_date')
        i_details = request.form.get('i_details')
        i_amount = request.form.get('i_amount')
        print(i_date)
        print(i_details)
        print(i_amount)
        return "nothing"

output :-

None
None
None
127.0.0.1 - - [31/May/2020 16:56:07] "GET /add_income HTTP/1.1" 200 -

Body:
Change this form tag action attribute

<form class="add-income-box" method="POST" action="{{ url_for('update_project')}}">

In this way, when you click on button it will call the method specified in action attribute.

and if you want to call this API using AJAX then make use of JSON to send data. And if you want to send data using form then remove the Ajax code and change the code as above suggested and click on the button and you will not get the form data.


问:
regex to validate a number range with decimal points
I would like to allow only number from 0 - 59 with 3 digits of decimal(decimal is optional).

^([0-5]?[0-9])(?:\.[0-9]{1,3})?$

^([0-5]?[0-9])(\.\d{1,3})?$

i tried by creating these 2 expressions ,unfortunately both of these returns invalid on form validations,but seems to valid on some online regex validators

am using angular reactive forms!

Any help Appreciated..!

答:
You can use the below regex to achieve your results:

```<code>^(?:[1-4]?[0-9])(?:\.\d{1,3})?$|^[5]?[0-8](?:\.\d{1,3})?$|^59(\.0{1,3})?$
</code>```

Explanation of the above regex:

(?:[1-4]?[0-9]) - Represents non-capturing group matching a single digit or two digit numbers. Notice 0[0-9] is not allowed. If you want to allow numbers like 04, 05, etc. make the class as [0-4].

(?:\.\d{1,3})? - Represents optional decimal places matching between 1 to 3 places of decimal.

| - Represents alternation.

^[5]?[0-8](?:\.\d{1,3})?$ - Matches the numbers from 50 through 58.999.

^59(\.0{1,3})?$ - Matches the numbers 59.000 assuming that your final limit is 59. If you want to allow 59.<some decimal digit> please remove this part of alternation and in the above part include ^[5]?[0-9].

You can find the demo of the above regex here.

Implementation in angular reactive-8 forms:

Since; the angular reactive 8 forms append ^ and $ automatically; you can omit them from the above regex.

app.component.html(Notice the [pattern]="digit")

```<code><input type="text" formControlName="digitCheck" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.digitCheck.errors }" [pattern]="digit" />
                    <div *ngIf="submitted && f.digitCheck.errors" class="invalid-feedback">
</code>```

app.component.ts

```<code>digit="^(?:[1-4]?[0-9])(?:\\.\\d{1,3})?$|^[5]?[0-8](?:\\.\\d{1,3})?$|^59(\\.0{1,3})?$";
digitCheck: [null, [Validators.required, Validators.pattern(this.digit)]]
</code>```

You can find the live implementation here.

Body:
You can use the below regex to achieve your results:

^(?:[1-4]?[0-9])(?:\.\d{1,3})?$|^[5]?[0-8](?:\.\d{1,3})?$|^59(\.0{1,3})?$

Explanation of the above regex:

(?:[1-4]?[0-9]) - Represents non-capturing group matching a single digit or two digit numbers. Notice 0[0-9] is not allowed. If you want to allow numbers like 04, 05, etc. make the class as [0-4].

(?:\.\d{1,3})? - Represents optional decimal places matching between 1 to 3 places of decimal.

| - Represents alternation.

^[5]?[0-8](?:\.\d{1,3})?$ - Matches the numbers from 50 through 58.999.

^59(\.0{1,3})?$ - Matches the numbers 59.000 assuming that your final limit is 59. If you want to allow 59.<some decimal digit> please remove this part of alternation and in the above part include ^[5]?[0-9].

You can find the demo of the above regex here.

Implementation in angular reactive-8 forms:

Since; the angular reactive 8 forms append ^ and $ automatically; you can omit them from the above regex.

app.component.html(Notice the [pattern]="digit")

<input type="text" formControlName="digitCheck" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.digitCheck.errors }" [pattern]="digit" />
                    <div *ngIf="submitted && f.digitCheck.errors" class="invalid-feedback">

app.component.ts

digit="^(?:[1-4]?[0-9])(?:\\.\\d{1,3})?$|^[5]?[0-8](?:\\.\\d{1,3})?$|^59(\\.0{1,3})?$";
digitCheck: [null, [Validators.required, Validators.pattern(this.digit)]]

You can find the live implementation here.