问:
Dictionary not selecting correct key
I have a strange problem with one of my dictionaries.

Below is a method that will execute another method based on the time frame it receives. The time frames are m1, m5, m15, m30, H1, H4, D1, W1, M1.

Basically from 1 minute to 1 month.

```<code>def get_trading_range(self, init_date, time_frame):
    """
    """
    key = time_frame[:1]
    tr_dict = {
        'D' : self._daily_range(init_date),
        'W' : self._weekly_range(init_date),
        'M' : self._monthly_range(init_date),
        'H' : self._hourly_range(init_date, time_frame),
        'm' : self._minutely_range(init_date, time_frame)
    }
    return tr_dict[key]
</code>```

The method is called with the following

```<code>DateRange().get_trading_range(datetime(some_date), 'D1')
</code>```

It seems to be selecting the 'm' method. I tried removing the 'm' key and value, then when executed again it selects the 'H' method. Only when I remove both the 'm' & 'H' keys and values will the 'D' method be executed.

Is this some strange bug?

This is the traceback

Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "engine.py", line 25, in _historical
    HistoricalCollector().historical_prices(hist_queue, live_queue, event)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 90, in historical_prices
    self._historical_iter(hist_queue, live_queue, fxoffer)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 73, in _historical_iter
    self._collect_data(fxc, offer, time_frame, init_date)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 28, in _collect_data
    dtx = DateRange().get_trading_range(init_date, time_frame)
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 84, in get_trading_range
    'm' : self._minutely_range(init_date, time_frame),
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 103, in _minutely_range
    freq = self._data_frequency(time_frame)[0]
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 23, in _data_frequency
    return freq_keys[time_frame]
KeyError: 'D1'
```

<p>Also tried with <code>key = time_frame[0]</code></p>

<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "engine.py", line 25, in _historical
    HistoricalCollector().historical_prices(hist_queue, live_queue, event)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 90, in historical_prices
    self._historical_iter(hist_queue, live_queue, fxoffer)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 73, in _historical_iter
    self._collect_data(fxc, offer, time_frame, init_date)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 28, in _collect_data
    dtx = DateRange().get_trading_range(init_date, str(time_frame))
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 84, in get_trading_range
    'm' : self._minutely_range(init_date, time_frame),
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 103, in _minutely_range
    freq = self._data_frequency(time_frame)[0]
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 23, in _data_frequency
    return freq_keys[time_frame]
KeyError: 'D1'
</code>```

答:
The problem is that those method get called when tr_dict is created, not when you access it, and this is why your _minutely_range is getting called with time_frame = "D1".

Try something like:

```<code>tr_dict = {
    'D' : lambda: self._daily_range(init_date),
    'W' : lambda: self._weekly_range(init_date),
    'M' : lambda: self._monthly_range(init_date),
    'H' : lambda: self._hourly_range(init_date, time_frame),
    'm' : lambda: self._minutely_range(init_date, time_frame)
}
return tr_dict[key]()
</code>```

This way, the methods will be called only if necessary.

Title: Dictionary not selecting correct key

Body:
I have a strange problem with one of my dictionaries.

Below is a method that will execute another method based on the time frame it receives. The time frames are m1, m5, m15, m30, H1, H4, D1, W1, M1.

Basically from 1 minute to 1 month.

def get_trading_range(self, init_date, time_frame):
    """
    """
    key = time_frame[:1]
    tr_dict = {
        'D' : self._daily_range(init_date),
        'W' : self._weekly_range(init_date),
        'M' : self._monthly_range(init_date),
        'H' : self._hourly_range(init_date, time_frame),
        'm' : self._minutely_range(init_date, time_frame)
    }
    return tr_dict[key]

The method is called with the following

DateRange().get_trading_range(datetime(some_date), 'D1')

It seems to be selecting the 'm' method. I tried removing the 'm' key and value, then when executed again it selects the 'H' method. Only when I remove both the 'm' & 'H' keys and values will the 'D' method be executed.

Is this some strange bug?

This is the traceback

Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "engine.py", line 25, in _historical
    HistoricalCollector().historical_prices(hist_queue, live_queue, event)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 90, in historical_prices
    self._historical_iter(hist_queue, live_queue, fxoffer)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 73, in _historical_iter
    self._collect_data(fxc, offer, time_frame, init_date)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 28, in _collect_data
    dtx = DateRange().get_trading_range(init_date, time_frame)
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 84, in get_trading_range
    'm' : self._minutely_range(init_date, time_frame),
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 103, in _minutely_range
    freq = self._data_frequency(time_frame)[0]
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 23, in _data_frequency
    return freq_keys[time_frame]
KeyError: 'D1'

Also tried with key = time_frame[0]

Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "engine.py", line 25, in _historical
    HistoricalCollector().historical_prices(hist_queue, live_queue, event)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 90, in historical_prices
    self._historical_iter(hist_queue, live_queue, fxoffer)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 73, in _historical_iter
    self._collect_data(fxc, offer, time_frame, init_date)
  File "/home/nonroot/fxcmminer_1.1/fxcm/historical.py", line 28, in _collect_data
    dtx = DateRange().get_trading_range(init_date, str(time_frame))
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 84, in get_trading_range
    'm' : self._minutely_range(init_date, time_frame),
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 103, in _minutely_range
    freq = self._data_frequency(time_frame)[0]
  File "/home/nonroot/fxcmminer_1.1/fxcm/tradinghours.py", line 23, in _data_frequency
    return freq_keys[time_frame]
KeyError: 'D1'

Body:
The problem is that those method get called when tr_dict is created, not when you access it, and this is why your _minutely_range is getting called with time_frame = "D1".

Try something like:

tr_dict = {
    'D' : lambda: self._daily_range(init_date),
    'W' : lambda: self._weekly_range(init_date),
    'M' : lambda: self._monthly_range(init_date),
    'H' : lambda: self._hourly_range(init_date, time_frame),
    'm' : lambda: self._minutely_range(init_date, time_frame)
}
return tr_dict[key]()

This way, the methods will be called only if necessary.


来源: stackexchange

问:
Error when uploading mySQL file
After i used the new answer i uploaded the file and this is what i get now.</p>

```<code>SQL query:

CREATE TABLE IF NOT EXISTS `games` ( ) INSERT INTO `games` (`name`, `creatorid`, `gameid`, `id`, `plays) VALUES ('בדיקה', 'לא ידוע', 1,1,0) CREATE TABLE IF NOT EXISTS `gamewall` ( `userid` int(11) NOT NULL, `reason` text NOT NULL, `comment` text NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `bannedbyid` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE IF NOT EXISTS `bans_IP` ( `IP` mediumtext NOT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, `bannerid` int(11) NOT NULL, `reason` mediumtext NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; CREATE TABLE IF NOT EXISTS `buysell` ( `buysell` int(11) NOT NULL, `sellerid` int(11) NOT NULL, `price` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE IF NOT EXISTS `competitions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` mediumtext NOT NULL, `startedbyid` int(11) NOT NULL, `descripti[...]

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')

INSERT INTO `games` (`name`, `creatorid`, `gameid`, `id`, `plays) VALUES
('' at line 3
</code>```

答:
You are receiving this error because you have selected all the columns of your table but values are available for first 11 columns and you missed ) in last

This code will fix your problem

```<code>INSERT INTO `accounts` (
   `Username`,
   `Password`,
   `Email`,
   `salt`,
   `Reebs`,
   `online`,
   `lastOnline`,
   `lastOnlineMinutes`,
   `lastOnlineHours`,
   `status`,
   `blurb`
)
VALUES
   (
      'AvatarLife',
      'df3ed1ad53c4cc2f3b5c6bdf04d33a9f094df53b',
      'fawrsnipng@gmail.com',
      'jBqnW?Dk9Epzpg4',
      '9223372036854775807',
      '1',
      '205',
      '26',
      '13',
      '',
      'Avatar Life is the only good life!')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Error when uploading mySQL file

Body:
After i used the new answer i uploaded the file and this is what i get now.

SQL query:

CREATE TABLE IF NOT EXISTS `games` ( ) INSERT INTO `games` (`name`, `creatorid`, `gameid`, `id`, `plays) VALUES ('בדיקה', 'לא ידוע', 1,1,0) CREATE TABLE IF NOT EXISTS `gamewall` ( `userid` int(11) NOT NULL, `reason` text NOT NULL, `comment` text NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `bannedbyid` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE IF NOT EXISTS `bans_IP` ( `IP` mediumtext NOT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, `bannerid` int(11) NOT NULL, `reason` mediumtext NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; CREATE TABLE IF NOT EXISTS `buysell` ( `buysell` int(11) NOT NULL, `sellerid` int(11) NOT NULL, `price` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE IF NOT EXISTS `competitions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` mediumtext NOT NULL, `startedbyid` int(11) NOT NULL, `descripti[...]

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')

INSERT INTO `games` (`name`, `creatorid`, `gameid`, `id`, `plays) VALUES
('' at line 3

Body:
You are receiving this error because you have selected all the columns of your table but values are available for first 11 columns and you missed ) in last

This code will fix your problem

INSERT INTO `accounts` (
   `Username`,
   `Password`,
   `Email`,
   `salt`,
   `Reebs`,
   `online`,
   `lastOnline`,
   `lastOnlineMinutes`,
   `lastOnlineHours`,
   `status`,
   `blurb`
)
VALUES
   (
      'AvatarLife',
      'df3ed1ad53c4cc2f3b5c6bdf04d33a9f094df53b',
      'fawrsnipng@gmail.com',
      'jBqnW?Dk9Epzpg4',
      '9223372036854775807',
      '1',
      '205',
      '26',
      '13',
      '',
      'Avatar Life is the only good life!')


问:
How do I map URLs to resources instead of JSF pages?
I'm very used to Jax-RS and the ability to make data available to the caller through custom URLs like:

/bicycles/by_color/blue

by doing:

```<code>@Path("{searchCategory}/{searchParam}")
List<Item> get(@PathParam....
</code>```

What is the equivalent in JSF? I have an application with a ReST API and would like to display a template page, grabbing a specific entity from the database according to part of the URL for the xhtml page to get data from that will be displayed.

I've seen examples with query parameters like '?id=5&pages=true' but nothing with URL mapping like '/5/true.' How do I accomplish this?

答:
For those Googling for an actual answer to the question, PrettyFaces is one way of doing this. It does URL 'beautification,' which includes making elements of the URL's path into receivable parameters.

I'm going to give an example using JAX-RS, then the equivalent with PrettyFaces:

Jax-RS

```<code>@Path("user")
public class UserEndpoint{
    @PersistenceContext
    EntityManager em;

    @GET
    @Path("{userid}")
    public UserEntity getUser(@PathParam("userid")long userId){
        return em.find(UserEntity.class, userId);
    }
}
</code>```

JSF with PrettyFaces

Good help for it on here: http://www.ocpsoft.org/prettyfaces/

Backing Bean

```<code>@Named
public class UserViewController{
    @PersistenceContext
    EntityManager em;

    public UserEntity getUser(){
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        Map<String, String> params = ec.getRequestParameterMap();
        long userId = Long.valueOf(params.get("userid"));
        return em.find(UserEntity.class, userId);
    }
}
</code>```

pretty-config.xml (special file that must be created inside the WEB-INF folder)

```<code><pretty-config xmlns="http://ocpsoft.org/schema/rewrite-config-prettyfaces"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://ocpsoft.org/schema/rewrite-config-prettyfaces
                                http://ocpsoft.org/xml/ns/prettyfaces/rewrite-config-prettyfaces.xsd">

<url-mapping id="view-user">
        <pattern value="/user/#{userid}" />
        <view-id value="/user/view.xhtml" />
    </url-mapping>
</pretty-config>
</code>```

Body:
I'm very used to Jax-RS and the ability to make data available to the caller through custom URLs like:

/bicycles/by_color/blue

by doing:

@Path("{searchCategory}/{searchParam}")
List<Item> get(@PathParam....

What is the equivalent in JSF? I have an application with a ReST API and would like to display a template page, grabbing a specific entity from the database according to part of the URL for the xhtml page to get data from that will be displayed.

I've seen examples with query parameters like '?id=5&pages=true' but nothing with URL mapping like '/5/true.' How do I accomplish this?

Body:
For those Googling for an actual answer to the question, PrettyFaces is one way of doing this. It does URL 'beautification,' which includes making elements of the URL's path into receivable parameters.

I'm going to give an example using JAX-RS, then the equivalent with PrettyFaces:

Jax-RS

@Path("user")
public class UserEndpoint{
    @PersistenceContext
    EntityManager em;

    @GET
    @Path("{userid}")
    public UserEntity getUser(@PathParam("userid")long userId){
        return em.find(UserEntity.class, userId);
    }
}

JSF with PrettyFaces

Good help for it on here: http://www.ocpsoft.org/prettyfaces/

Backing Bean

@Named
public class UserViewController{
    @PersistenceContext
    EntityManager em;

    public UserEntity getUser(){
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        Map<String, String> params = ec.getRequestParameterMap();
        long userId = Long.valueOf(params.get("userid"));
        return em.find(UserEntity.class, userId);
    }
}

pretty-config.xml (special file that must be created inside the WEB-INF folder)

<pretty-config xmlns="http://ocpsoft.org/schema/rewrite-config-prettyfaces"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://ocpsoft.org/schema/rewrite-config-prettyfaces
                                http://ocpsoft.org/xml/ns/prettyfaces/rewrite-config-prettyfaces.xsd">

<url-mapping id="view-user">
        <pattern value="/user/#{userid}" />
        <view-id value="/user/view.xhtml" />
    </url-mapping>
</pretty-config>


问:
chef - replace coredump parameter in sysctl.conf file
for example am already having a parameter for the core dump i.e

kernel.core_pattern = /usr/local/core-%e.%t.%p.%u.%g

Now i wanted to change it to this i.e

kernel.core_pattern = /usr/local/core.%e.%p.%h.%t

mycode as follows :

```<code>ruby_block "edit /etc/sysctl.conf" do
    block do
        file = Chef::Util::FileEdit.new("/etc/sysctl.conf")
        file.search_file_replace_line(/^kernel.core_pattern.*$/, "kernel.core_pattern=/usr/local/core.%e.%p.%h.%t")
        rc.write_file
    end
    not_if "grep 'kernel.core_pattern' /etc/sysctl.conf"
</code>```

Any suggestions

答: Don't use FileEdit, it's an internal API within Chef. In the general case, use the line or (disclaimer: mine) poise-file cookbooks if you must do in-place edits. That said, it is generally safer to manage whole files. In the case of sysctls specifically it does have to edit a file but we have a community cookbook (sysctl) that can handle the heavy lifting in this case.

Body:
for example am already having a parameter for the core dump i.e

kernel.core_pattern = /usr/local/core-%e.%t.%p.%u.%g

Now i wanted to change it to this i.e

kernel.core_pattern = /usr/local/core.%e.%p.%h.%t

mycode as follows :

ruby_block "edit /etc/sysctl.conf" do
    block do
        file = Chef::Util::FileEdit.new("/etc/sysctl.conf")
        file.search_file_replace_line(/^kernel.core_pattern.*$/, "kernel.core_pattern=/usr/local/core.%e.%p.%h.%t")
        rc.write_file
    end
    not_if "grep 'kernel.core_pattern' /etc/sysctl.conf"

Any suggestions


问:
How to correctly transfer folders to 000webhost server from filezilla?
I am a complete beginner at building websites so I apologize if I'm not using the correct terms when describing my problem.

I used filezilla to transfer a website onto my server hosted by 000webhost. I placed the folder with all the files into the public_html folder. When I try to open the site, I get the message :

You see this page because your website doesn't have "index.php" or "index.html" file in public_html folder.

It's able to recognize and process the index.php file when I upload the single file directly into the public_html folder, but not when it's in a folder that's uploaded into the public_html folder. Is it not able to process any of the files within the folder that I uploaded unless I remove them from the folder? Or am I not transferring the folder to the right place?

答:
are you sure you didn't upload the folder itself instead of the "contents" of the folder there ? you need to ensure that, when you browse to the public_html folder on the FTP server (with filezilla) you can see the index.php file as well as other files and subfolders,and not just 1 folder.

i don't know 000webhost, but under public_html, you should have something like this :

```<code>public_html
  ->  index.php
  ->  other_pages.php
  ->  images/
  ->  css/
  ->  blabla/
</code>```

and not :

```<code>public_html
  ->  your_folder/   # containing index.php
</code>```

in filezilla, browse to your folder locally, and "select all files and subfolders" in it, and upload them all to public_html on the server

Body:
are you sure you didn't upload the folder itself instead of the "contents" of the folder there ? you need to ensure that, when you browse to the public_html folder on the FTP server (with filezilla) you can see the index.php file as well as other files and subfolders,and not just 1 folder.

i don't know 000webhost, but under public_html, you should have something like this :

public_html
  ->  index.php
  ->  other_pages.php
  ->  images/
  ->  css/
  ->  blabla/

and not :

public_html
  ->  your_folder/   # containing index.php

in filezilla, browse to your folder locally, and "select all files and subfolders" in it, and upload them all to public_html on the server


问:
What is the main benefit for using pointers in this particular program?
The first program below is utilizing a pointer for the array movie:

```<code>#include <stdio.h>

int main(void) {
    char movie [20];
    char * pMovie = movie;

    fgets(pMovie, 20, stdin);
    puts(pMovie);

    return 0;
}
</code>```

While the second program below is not utilizing any pointer and essentially achieves the same outcome. I am not understanding the benefit that the teacher is trying to show with using pointers within the pointer but I can assume that it goes beyond this particular example:

```<code>#include <stdio.h>

int main(void) {
    char movie [20];

    fgets(movie, 20, stdin);
    puts(movie);

    return 0;
}
</code>```

答:
There is absolutely no benefit, because both things are very similar. In C an array can be considered as the pointer to the first element of the array (Inside of the scope of the function where the array is declared the compiler is also aware of the size of the array, so there is some different behavior between the 2, although not in your examples). A char array is a pointer to the first element in the array, notice how there is no type casting when he does:

```<code>char * pMovie = movie;
</code>```

There is no need to type cast because these 2 variables are considered to be the same type (char *) by the compiler.

A similar way to create an array is:

```<code>char *test = (char*)malloc(sizeof(char)*size_of_array);
</code>```

I am assuming your teacher is trying to make you familiar with this concept (that arrays in C are similar to pointers and vice-versa)

Body:
The first program below is utilizing a pointer for the array movie:

#include <stdio.h>

int main(void) {
    char movie [20];
    char * pMovie = movie;

    fgets(pMovie, 20, stdin);
    puts(pMovie);

    return 0;
}

While the second program below is not utilizing any pointer and essentially achieves the same outcome. I am not understanding the benefit that the teacher is trying to show with using pointers within the pointer but I can assume that it goes beyond this particular example:

#include <stdio.h>

int main(void) {
    char movie [20];

    fgets(movie, 20, stdin);
    puts(movie);

    return 0;
}

Body:
There is absolutely no benefit, because both things are very similar. In C an array can be considered as the pointer to the first element of the array (Inside of the scope of the function where the array is declared the compiler is also aware of the size of the array, so there is some different behavior between the 2, although not in your examples). A char array is a pointer to the first element in the array, notice how there is no type casting when he does:

char * pMovie = movie;

There is no need to type cast because these 2 variables are considered to be the same type (char *) by the compiler.

A similar way to create an array is:

char *test = (char*)malloc(sizeof(char)*size_of_array);

I am assuming your teacher is trying to make you familiar with this concept (that arrays in C are similar to pointers and vice-versa)


问:
Centralizing RecyclerView with LinearLayoutManager
I am trying to centralize a RecyclerView list in the screen. Its going to be a single list, so I will use the LinearLayoutManager (LLM).
However using the LLM its not centralizing the items, and it looks like this on the landscape mode:

The XML code looks like this:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recipe_card"
        android:layout_gravity="center"
        android:layout_width="400dp"
        android:layout_height="186dp"
        style="@style/CardViewStyle">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/recipe_image"
                android:layout_width="120dp"
                android:layout_height="163dp"
                app:srcCompat="@mipmap/ic_pan"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                tools:layout_editor_absoluteY="3dp" />

            <TextView
                android:id="@+id/recipe_name"
                android:layout_width="250dp"
                android:layout_height="119dp"
                android:text="TextView"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" />

            <TextView
                android:id="@+id/recipe_servings"
                android:layout_width="164dp"
                android:layout_height="32dp"
                android:text="TextView"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/recipe_name"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="94dp"
                app:layout_constraintVertical_bias="0.0" />
        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>
</code>```

On the Android Studio's Preview, it looks fine, but on the app, it does not.
I manage to fix it by changing the LLM for a GridLayoutManager with only one column. But it looks ugly.

Does anyone knows what is going on?
Thanks.

答:
Try to set the content gravity of main layout to center. There are two ways to do that:

Add "centerHorozontal" property to "true" to your frame layout.

Change your frame layout to linear layout and set gravity of main linear layout to "center".

Hope it will work, if it doesn't then just send me the images you are using in your layout, I'll try to fix it by using some other techniques and will send you the updated code.

Body:
I am trying to centralize a RecyclerView list in the screen. Its going to be a single list, so I will use the LinearLayoutManager (LLM).
However using the LLM its not centralizing the items, and it looks like this on the landscape mode:

The XML code looks like this:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recipe_card"
        android:layout_gravity="center"
        android:layout_width="400dp"
        android:layout_height="186dp"
        style="@style/CardViewStyle">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/recipe_image"
                android:layout_width="120dp"
                android:layout_height="163dp"
                app:srcCompat="@mipmap/ic_pan"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                tools:layout_editor_absoluteY="3dp" />

            <TextView
                android:id="@+id/recipe_name"
                android:layout_width="250dp"
                android:layout_height="119dp"
                android:text="TextView"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" />

            <TextView
                android:id="@+id/recipe_servings"
                android:layout_width="164dp"
                android:layout_height="32dp"
                android:text="TextView"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/recipe_name"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="94dp"
                app:layout_constraintVertical_bias="0.0" />
        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>

On the Android Studio's Preview, it looks fine, but on the app, it does not.
I manage to fix it by changing the LLM for a GridLayoutManager with only one column. But it looks ugly.

Does anyone knows what is going on?
Thanks.


问:
Spring boot WebSockets TextWebSocketHandler not working with json messges
I have added web sockets to my app for transmitting messages and make an interactive app.

What I need to transmit with web-sockets is the POJO Objects. But, the TextWebSocketHandler is not working and not sending messages. When I test the web sockets, I get:

WebSocket is already in CLOSING or CLOSED state.

I don't know if it work but I think the size of the messages is stopping the web socket.

Code:

```<code>@Configuration
@EnableWebSocket
public class WebsocketConfig implements WebSocketConfigurer{
    @Bean
    public WebSocketHandler myMessageHandler() {
        return new MyMessageHandler();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myMessageHandler(), "/my-websocket-endpoint");
    }

}

public class MyMessageHandler extends TextWebSocketHandler {

    @Autowired
    UserRepository userRepository;

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // The WebSocket has been closed
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // The WebSocket has been opened
        // I might save this session object so that I can send messages to it outside of this method

        // Let's send the first message
        Gson gson=new Gson();
        session.sendMessage(new TextMessage(gson.toJson(findall())));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
        // A message has been received

            Gson gson=new Gson();
            session.sendMessage(new TextMessage(gson.toJson(findall())));

    }

    public List<User> findall(){

        return userRepository.findAll();

    }

}
</code>```

答: Trying removing the throws Exception in the methods where you use the json parsing, then apply the try and catch around the parsing operation and deal with the exception you might encounter.  </p>

ContentLicense: CC BY-SA 4.0

Body:
I have added web sockets to my app for transmitting messages and make an interactive app.

What I need to transmit with web-sockets is the POJO Objects. But, the TextWebSocketHandler is not working and not sending messages. When I test the web sockets, I get:

WebSocket is already in CLOSING or CLOSED state.

I don't know if it work but I think the size of the messages is stopping the web socket.

Code:

@Configuration
@EnableWebSocket
public class WebsocketConfig implements WebSocketConfigurer{
    @Bean
    public WebSocketHandler myMessageHandler() {
        return new MyMessageHandler();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myMessageHandler(), "/my-websocket-endpoint");
    }

}

public class MyMessageHandler extends TextWebSocketHandler {

    @Autowired
    UserRepository userRepository;

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // The WebSocket has been closed
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // The WebSocket has been opened
        // I might save this session object so that I can send messages to it outside of this method

        // Let's send the first message
        Gson gson=new Gson();
        session.sendMessage(new TextMessage(gson.toJson(findall())));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
        // A message has been received

            Gson gson=new Gson();
            session.sendMessage(new TextMessage(gson.toJson(findall())));

    }

    public List<User> findall(){

        return userRepository.findAll();

    }

}


问:
How to cut off int at the end of a line
I have a txt file similar to the following:

```<code>f1, max, inputs: 10 2 4

f2, sum, inputs: 2 4 5

f3, prod, inputs: 6 5
</code>```

I should find the max from the line where the max is stated (10), print the sum of the numbers from where the sum is (11), and the product from where the prod is (30).

My code looks like this:

```<code>f = File.open("test.txt") or die "Unable to open file..."
contentArray=[]
f.each_line {|line|
    contentArray.push line
}

i=0
while i<contentArray.size() do
    if contentArray[i].include? "max"
        print "max is here"
        i+=1
    elsif contentArray[i].include? "sum"
        print "sum is here"
        i+=1
    elsif contentArray[i].include? "prod"
        print "prod is here"
        i+=1
    end
end
</code>```

I can find which line has the max, sum, or prod string, but I don't know how I should cut off the integers from the end and do the maths with them.

答:
Code

```<code>def print_totals(fname)
  File.foreach(fname) do |line|
    _, op, _, *a = line.split(/, *|: *| +(?=\d)/)
    a.map!(&:to_i)
    tot = a.reduce do |t,n|
      case op
      when 'max'  then [t,n].max
      when 'sum'  then t+n
      when 'prod' then t*n
      end
    end
    puts "%s %s = %d" % [op, a, tot]
  end
end
</code>```

line.split(/, *|: *| +(?=\d)/) reads, "split line on a) a comma followed by zero or more spaces or b) a colon followed by zero or more spaces or c) one or more spaces followed by a digit" ((?=\d) being a positive lookahead). That line operates as follows.

```<code>line = "f1, max, inputs: 10 2 4"
_, op, _, *a = line.split(/, *|: *| +(?=\d)/)
   #=> ["f1", "max", "inputs", "10", "2", "4"]
op #=> "max"
a  #=> ["10", "2", "4"]
</code>```

Example

First create a test file.

```<code>contents =<<-_
f1, max, inputs: 10 2 4
f2, sum, inputs: 2 4 5
f3, prod, inputs: 6 5
_

FName = 'temp'
File.write(FName, contents)
  #=> 69
</code>```

Confirm its contents.

```<code>puts File.read(FName)
f1, max, inputs: 10 2 4
f2, sum, inputs: 2 4 5
f3, prod, inputs: 6 5
</code>```

Print the desired results.

```<code>print_totals FName
max [10, 2, 4] = 10
sum [2, 4, 5] = 11
prod [6, 5] = 30
</code>```

Title: How to cut off int at the end of a line

Body:
I have a txt file similar to the following:

f1, max, inputs: 10 2 4

f2, sum, inputs: 2 4 5

f3, prod, inputs: 6 5

I should find the max from the line where the max is stated (10), print the sum of the numbers from where the sum is (11), and the product from where the prod is (30).

My code looks like this:

f = File.open("test.txt") or die "Unable to open file..."
contentArray=[]
f.each_line {|line|
    contentArray.push line
}

i=0
while i<contentArray.size() do
    if contentArray[i].include? "max"
        print "max is here"
        i+=1
    elsif contentArray[i].include? "sum"
        print "sum is here"
        i+=1
    elsif contentArray[i].include? "prod"
        print "prod is here"
        i+=1
    end
end

I can find which line has the max, sum, or prod string, but I don't know how I should cut off the integers from the end and do the maths with them.

Body:
Code

def print_totals(fname)
  File.foreach(fname) do |line|
    _, op, _, *a = line.split(/, *|: *| +(?=\d)/)
    a.map!(&:to_i)
    tot = a.reduce do |t,n|
      case op
      when 'max'  then [t,n].max
      when 'sum'  then t+n
      when 'prod' then t*n
      end
    end
    puts "%s %s = %d" % [op, a, tot]
  end
end

line.split(/, *|: *| +(?=\d)/) reads, "split line on a) a comma followed by zero or more spaces or b) a colon followed by zero or more spaces or c) one or more spaces followed by a digit" ((?=\d) being a positive lookahead). That line operates as follows.

line = "f1, max, inputs: 10 2 4"
_, op, _, *a = line.split(/, *|: *| +(?=\d)/)
   #=> ["f1", "max", "inputs", "10", "2", "4"]
op #=> "max"
a  #=> ["10", "2", "4"]

Example

First create a test file.

contents =<<-_
f1, max, inputs: 10 2 4
f2, sum, inputs: 2 4 5
f3, prod, inputs: 6 5
_

FName = 'temp'
File.write(FName, contents)
  #=> 69

Confirm its contents.

puts File.read(FName)
f1, max, inputs: 10 2 4
f2, sum, inputs: 2 4 5
f3, prod, inputs: 6 5

Print the desired results.

print_totals FName
max [10, 2, 4] = 10
sum [2, 4, 5] = 11
prod [6, 5] = 30


问:
Python, MIME, Embed image in email
I am testing the sending of an email with an embeded png file. I use the code:

```<code>from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

template ="""
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Image Test</h2>
<img src="/home/depot/wintergreen/mplplots/01.png">
</body>
</html>"""

MAIL_HOST = 'smtp.gmail.com:587'
MAIL_USER = 'xxx@gmail.com'
MAIL_PASSWORD = 'xxx'
MAIL_REPICIENTS = ['vincent.konate@gmail.com']

message = MIMEMultipart('alternative')
message['Subject'] = "Test Image"

html = MIMEText(template, 'html', "utf-8")
message.attach(html)

smtp = SMTP(MAIL_HOST)
smtp.ehlo()
smtp.starttls()
smtp.login(MAIL_USER, MAIL_PASSWORD)
smtp.sendmail(MAIL_USER, MAIL_REPICIENTS, message.as_string())
smtp.close()
</code>```

The sending works, however the image doesnt show up, instead this is what I see:

I am testing with the Jupyter notebook; When i type

```<code>from IPython.display import Image
Image("/home/depot/wintergreen/mplplots/01.png")
</code>```

The image shows, so the path is correct.

What could be wrong here?

答:
Your image URL needs to include the hostname. You have only:

```<code><img src="/home/depot/wintergreen/mplplots/01.png">
</code>```

You need something like:

```<code><img src="http://myhostname.com/home/depot/wintergreen/mplplots/01.png">
</code>```

Because when your user gets the email, there needs to be the domain.

Now, if the image isn't hosted somewhere, but is available on a filesystem accessible by all of your recipients (say, while reading on a corporate intranet) you can use a file URI rather than http. For example

```<code><img src="file:///home/depot/wintergreen/mplplots/01.png">
</code>```

Which will work for those recipients whose device can access the local directory for the file.

Finally, there is the option include the image itself within the email (rather than just a link to it). To actually include the image, you'll need to send a MIME message which, itself, includes the HTML, the Image and a reference from one to the other (the "link" within the HTML part would be like:  where the cid refers to the Content-ID of the image. See Embed picture in email for details.

(You could use a data-uri directly in the HTML, but this has spotty support in email clients. See, for example, What is Data URI support like in major email client software?. You'd need to investigate if that's appropriate for your user base.)

Title: Python, MIME, Embed image in email

Body:
I am testing the sending of an email with an embeded png file. I use the code:

from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

template ="""
<!DOCTYPE html>

Image Test

"""

MAIL_HOST = 'smtp.gmail.com:587'
MAIL_USER = 'xxx@gmail.com'
MAIL_PASSWORD = 'xxx'
MAIL_REPICIENTS = ['vincent.konate@gmail.com']

message = MIMEMultipart('alternative')
message['Subject'] = "Test Image"

html = MIMEText(template, 'html', "utf-8")
message.attach(html)

smtp = SMTP(MAIL_HOST)
smtp.ehlo()
smtp.starttls()
smtp.login(MAIL_USER, MAIL_PASSWORD)
smtp.sendmail(MAIL_USER, MAIL_REPICIENTS, message.as_string())
smtp.close()

The sending works, however the image doesnt show up, instead this is what I see:

I am testing with the Jupyter notebook; When i type

from IPython.display import Image
Image("/home/depot/wintergreen/mplplots/01.png")

The image shows, so the path is correct.

What could be wrong here?

Body:
Your image URL needs to include the hostname. You have only:

<img src="/home/depot/wintergreen/mplplots/01.png">

You need something like:

<img src="http://myhostname.com/home/depot/wintergreen/mplplots/01.png">

Because when your user gets the email, there needs to be the domain.

Now, if the image isn't hosted somewhere, but is available on a filesystem accessible by all of your recipients (say, while reading on a corporate intranet) you can use a file URI rather than http. For example

<img src="file:///home/depot/wintergreen/mplplots/01.png">

Which will work for those recipients whose device can access the local directory for the file.

Finally, there is the option include the image itself within the email (rather than just a link to it). To actually include the image, you'll need to send a MIME message which, itself, includes the HTML, the Image and a reference from one to the other (the "link" within the HTML part would be like: <img src="cid:XXX"> where the cid refers to the Content-ID of the image. See Embed picture in email for details.

(You could use a data-uri directly in the HTML, but this has spotty support in email clients. See, for example, What is Data URI support like in major email client software?. You'd need to investigate if that's appropriate for your user base.)


答: It looks like the function isn't returning 'm' or 'H', but is in the process of evaluating them when it hits the traceback. Could it be key you want to pass into their functions instead of time_frame?

Title: Dictionary not selecting correct key


问:
Scanner for console?
I am making a game for my com sci class and it uses console to display user inputs. I want to use the Java Scanner class to receive a text of line from the user however when I try to use the scanner inputs, it doesn't work.

This is the import I use:

```<code>import java.util.Scanner;
</code>```

this  is essentially what I'm trying to do

```<code>Scanner keyboard = new Scanner(System.in); // not system.in but something compatible to console
</code>```

maybe scanner isn't compatible with console and perhaps I need to use another class? Or maybe i'm doing something wrong? Thanks :)

答:
From my understanding of your question, what you need to do is:

```<code>Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.NextLine();
</code>```

This will read the console input from the user.

The import statement is also wrong. It should be:

```<code>import java.util.Scanner;
</code>```

Also as mentioned in the comments above, look at this post:
How can I read input from the console using the Scanner class in Java?

Title: Scanner for console?

Body:
I am making a game for my com sci class and it uses console to display user inputs. I want to use the Java Scanner class to receive a text of line from the user however when I try to use the scanner inputs, it doesn't work.

This is the import I use:

import java.util.Scanner;

this  is essentially what I'm trying to do

Scanner keyboard = new Scanner(System.in); // not system.in but something compatible to console

maybe scanner isn't compatible with console and perhaps I need to use another class? Or maybe i'm doing something wrong? Thanks :)

Body:
From my understanding of your question, what you need to do is:

Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.NextLine();

This will read the console input from the user.

The import statement is also wrong. It should be:

import java.util.Scanner;

Also as mentioned in the comments above, look at this post:
How can I read input from the console using the Scanner class in Java?


问:
struct of struct arrays
I am trying to create a deck of cards using two structs, one for cards and the other for deck. I am getting errors in initializing deck. The current error is

"error: subscripted value is neither array nor pointer nor vector"

I have attached my code. I do not know where exactly I am going wrong. The above error is for the line
"D[i].deck_cards = (c.s[i/13] = suit[i/13] , c.f[i%13] = face[i%13]);"

Please suggest me if there is any better way of doing it. Thank you for the help.

```<code>#include <stdio.h>
#include<time.h>
#define NCARDS 52

char* suit[4] = {"spades","hearts","clubs","diamonds"};
char* face[13] ={"ace","two","three","four","five","six","seven","eight","nine",
                     "ten","jack","queen","king"};

struct card{
   char* s;
   char* f;
};

struct Deck{

struct card* deck_cards;
};

void PrintCard(struct Deck, int i);
void InitDeck(struct Deck);

int main()
{
   srand(time(NULL));
   struct Deck deck;

   int i;
   InitDeck(deck);
   for (i=0; i<NCARDS; i++)
   {
       PrintCard(deck,i);
   }
   return 0;
}

void InitDeck(struct Deck D)
{
   int i;
   struct card c;
   for(i=0; i< NCARDS; i++)
   {
       D[i].deck_cards = (c.s[i/13] = suit[i/13] , c.f[i%13] = face[i%13]);

   }
}

void PrintCard(struct Deck, int i)
{
     printf("Card %d = %s \n", i, Deck.deck_cards[i]);
}
</code>```

答:
I have created a working version, intentionally trying to stay as close as possible to your own attempt.

I commented my changes.
I also commented on some, but not all, things which could be improved.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NCARDS 52

char* suit[4]  = {"spades","hearts","clubs","diamonds"};
char* face[13] = {"ace","two","three","four","five","six","seven","eight","nine",
                     "ten","jack","queen","king"};

struct card
{
   char* s;
   char* f;
};

// a struct with a single member,
// code would be easier if the deck were just an array of cards
struct Deck
{
    // member of type array of "struct card",
    // using an array instead of only a pointer,
    // makes sure that the memory for it exists
    struct card deck_cards[NCARDS];
};

void PrintCard(struct Deck D, int i);

// pointer to deck (i.e. call by reference) needed,
// to have an external effect
void InitDeck(struct Deck* D);

int main(void)
{
   // using this requires <stdlib.h>
   srand(time(NULL));

   struct Deck deck;

   int i;

   // give address of the deck you want to change,
   // otherwise the init will only happen to a copy
   InitDeck(&deck);
   for (i=0; i<NCARDS; i++)
   {
       PrintCard(deck,i);
   }
   return 0;
}

void InitDeck(struct Deck* D)
{
   int i;
   for(i=0; i< NCARDS; i++)
   {   // only for the initialisation of a variable
       // (a local variable in this case)
       // an "anonymous struct" similar to what you tried
       // can be used; but actually it is only a specific syntax
       // for initialising a struct
       struct card c = {suit[i/13], face[i%13]};
       // D is a pointer to a deck, dereference it by "D->",
       // which also includes the "." for accessing a member,
       // the only member "deck_cards",
       // which is an array,
       // index into it to access a single card, using "[i]"
       D->deck_cards[i] = c;
   }
}

void PrintCard(struct Deck deck, int i)
{
     // printing a struct with two pointers to string
     // requires some more details on how to do that
     printf("Card %d = %s of %s \n", i, deck.deck_cards[i].f, deck.deck_cards[i].s);
}
</code>```

Output (compile gcc -Wall): No errors, no warnings

Output runtime:

```<code>Card 0 = ace of spades
Card 1 = two of spades
Card 2 = three of spades
Card 3 = four of spades
Card 4 = five of spades
Card 5 = six of spades
Card 6 = seven of spades
Card 7 = eight of spades
Card 8 = nine of spades
Card 9 = ten of spades
Card 10 = jack of spades
Card 11 = queen of spades
Card 12 = king of spades
Card 13 = ace of hearts
Card 14 = two of hearts
Card 15 = three of hearts
Card 16 = four of hearts
Card 17 = five of hearts
Card 18 = six of hearts
Card 19 = seven of hearts
Card 20 = eight of hearts
Card 21 = nine of hearts
Card 22 = ten of hearts
Card 23 = jack of hearts
Card 24 = queen of hearts
Card 25 = king of hearts
Card 26 = ace of clubs
Card 27 = two of clubs
Card 28 = three of clubs
Card 29 = four of clubs
Card 30 = five of clubs
Card 31 = six of clubs
Card 32 = seven of clubs
Card 33 = eight of clubs
Card 34 = nine of clubs
Card 35 = ten of clubs
Card 36 = jack of clubs
Card 37 = queen of clubs
Card 38 = king of clubs
Card 39 = ace of diamonds
Card 40 = two of diamonds
Card 41 = three of diamonds
Card 42 = four of diamonds
Card 43 = five of diamonds
Card 44 = six of diamonds
Card 45 = seven of diamonds
Card 46 = eight of diamonds
Card 47 = nine of diamonds
Card 48 = ten of diamonds
Card 49 = jack of diamonds
Card 50 = queen of diamonds
Card 51 = king of diamonds
</code>```

Title: struct of struct arrays

Body:
I am trying to create a deck of cards using two structs, one for cards and the other for deck. I am getting errors in initializing deck. The current error is

"error: subscripted value is neither array nor pointer nor vector"

I have attached my code. I do not know where exactly I am going wrong. The above error is for the line
"D[i].deck_cards = (c.s[i/13] = suit[i/13] , c.f[i%13] = face[i%13]);"

Please suggest me if there is any better way of doing it. Thank you for the help.

#include <stdio.h>
#include<time.h>
#define NCARDS 52

char* suit[4] = {"spades","hearts","clubs","diamonds"};
char* face[13] ={"ace","two","three","four","five","six","seven","eight","nine",
                     "ten","jack","queen","king"};

struct card{
   char* s;
   char* f;
};

struct Deck{

struct card* deck_cards;
};

void PrintCard(struct Deck, int i);
void InitDeck(struct Deck);

int main()
{
   srand(time(NULL));
   struct Deck deck;

   int i;
   InitDeck(deck);
   for (i=0; i<NCARDS; i++)
   {
       PrintCard(deck,i);
   }
   return 0;
}

void InitDeck(struct Deck D)
{
   int i;
   struct card c;
   for(i=0; i< NCARDS; i++)
   {
       D[i].deck_cards = (c.s[i/13] = suit[i/13] , c.f[i%13] = face[i%13]);

   }
}

void PrintCard(struct Deck, int i)
{
     printf("Card %d = %s \n", i, Deck.deck_cards[i]);
}

Body:
I have created a working version, intentionally trying to stay as close as possible to your own attempt.

I commented my changes.
I also commented on some, but not all, things which could be improved.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NCARDS 52

char* suit[4]  = {"spades","hearts","clubs","diamonds"};
char* face[13] = {"ace","two","three","four","five","six","seven","eight","nine",
                     "ten","jack","queen","king"};

struct card
{
   char* s;
   char* f;
};

// a struct with a single member,
// code would be easier if the deck were just an array of cards
struct Deck
{
    // member of type array of "struct card",
    // using an array instead of only a pointer,
    // makes sure that the memory for it exists
    struct card deck_cards[NCARDS];
};

void PrintCard(struct Deck D, int i);

// pointer to deck (i.e. call by reference) needed,
// to have an external effect
void InitDeck(struct Deck* D);

int main(void)
{
   // using this requires <stdlib.h>
   srand(time(NULL));

   struct Deck deck;

   int i;

   // give address of the deck you want to change,
   // otherwise the init will only happen to a copy
   InitDeck(&deck);
   for (i=0; i<NCARDS; i++)
   {
       PrintCard(deck,i);
   }
   return 0;
}

void InitDeck(struct Deck* D)
{
   int i;
   for(i=0; i< NCARDS; i++)
   {   // only for the initialisation of a variable
       // (a local variable in this case)
       // an "anonymous struct" similar to what you tried
       // can be used; but actually it is only a specific syntax
       // for initialising a struct
       struct card c = {suit[i/13], face[i%13]};
       // D is a pointer to a deck, dereference it by "D->",
       // which also includes the "." for accessing a member,
       // the only member "deck_cards",
       // which is an array,
       // index into it to access a single card, using "[i]"
       D->deck_cards[i] = c;
   }
}

void PrintCard(struct Deck deck, int i)
{
     // printing a struct with two pointers to string
     // requires some more details on how to do that
     printf("Card %d = %s of %s \n", i, deck.deck_cards[i].f, deck.deck_cards[i].s);
}

Output (compile gcc -Wall): No errors, no warnings

Output runtime:

Card 0 = ace of spades
Card 1 = two of spades
Card 2 = three of spades
Card 3 = four of spades
Card 4 = five of spades
Card 5 = six of spades
Card 6 = seven of spades
Card 7 = eight of spades
Card 8 = nine of spades
Card 9 = ten of spades
Card 10 = jack of spades
Card 11 = queen of spades
Card 12 = king of spades
Card 13 = ace of hearts
Card 14 = two of hearts
Card 15 = three of hearts
Card 16 = four of hearts
Card 17 = five of hearts
Card 18 = six of hearts
Card 19 = seven of hearts
Card 20 = eight of hearts
Card 21 = nine of hearts
Card 22 = ten of hearts
Card 23 = jack of hearts
Card 24 = queen of hearts
Card 25 = king of hearts
Card 26 = ace of clubs
Card 27 = two of clubs
Card 28 = three of clubs
Card 29 = four of clubs
Card 30 = five of clubs
Card 31 = six of clubs
Card 32 = seven of clubs
Card 33 = eight of clubs
Card 34 = nine of clubs
Card 35 = ten of clubs
Card 36 = jack of clubs
Card 37 = queen of clubs
Card 38 = king of clubs
Card 39 = ace of diamonds
Card 40 = two of diamonds
Card 41 = three of diamonds
Card 42 = four of diamonds
Card 43 = five of diamonds
Card 44 = six of diamonds
Card 45 = seven of diamonds
Card 46 = eight of diamonds
Card 47 = nine of diamonds
Card 48 = ten of diamonds
Card 49 = jack of diamonds
Card 50 = queen of diamonds
Card 51 = king of diamonds


问:
How upload files in root domain while in subdomain
I've a domain and a subdomain with this structure:

```<code>Domain: mydomain.com
Subdomain: m.mydomain.com (which "mydomain.com/mobile/" is the folder)
</code>```

While I'm on mydomain.com, I upload images to the folder "images", this is the structure:

```<code>mydomain.com/images/image.jpg
</code>```

And I've no problems with it, because the folder /images/ is in the domain.

Now, when I'm in m.mydomain.com, how can I upload images to the domain folder (mydomain.com/images) and not to the subdomain folder (m.mydomain.com/images)?

Thank you guys

PS. I'm using Routing with both domains, with the index.php as "router"

答:
Since m.domain.com is in domain.com you can use m.domain.com/images for both.

Use the same directory for both domains and use .htaccess to route the mobile to index.m.php or something like that in the same directory.

More complicated. You can serve files through a url page built in php. Basically just a page that takes the file name searches for it in the server directory outside the site and dumps the content with appropriate headers.

Similar to 2 you can route both mobile and normal to the same directory. Detect in index.php if the subdomain is specified and load the site files from your mobile folder. This is my preferred method.

Body:
I've a domain and a subdomain with this structure:

Domain: mydomain.com
Subdomain: m.mydomain.com (which "mydomain.com/mobile/" is the folder)

While I'm on mydomain.com, I upload images to the folder "images", this is the structure:

mydomain.com/images/image.jpg

And I've no problems with it, because the folder /images/ is in the domain.

Now, when I'm in m.mydomain.com, how can I upload images to the domain folder (mydomain.com/images) and not to the subdomain folder (m.mydomain.com/images)?

Thank you guys

PS. I'm using Routing with both domains, with the index.php as "router"


问:
How to implement tf.space_to_depth with numpy?
These is a function in tensorflow called tf.space_to_depth. The implementation of this function in Tensorflow source code is so difficult for me. Could you please help me to implement it using numpy?

Here is some code to visualize how this function works. By the way, before everything, it is good to mention that the input to tensorflow's function should have input shape : [batch, height, width, depth]

Assuming this code. First we need to define a tensor:

```<code>norm = tf.reshape(tf.range(0,72),(1,6,6,2))
</code>```

Here is the value of depth 1 (norm[0,:,:,0]):

```<code>[[ 0,  2,  4,  6,  8, 10],
 [12, 14, 16, 18, 20, 22],
 [24, 26, 28, 30, 32, 34],
 [36, 38, 40, 42, 44, 46],
 [48, 50, 52, 54, 56, 58],
 [60, 62, 64, 66, 68, 70]]
</code>```

Here is the value of depth 2 (norm[0,:,:,1]):

```<code>[[ 1,  3,  5,  7,  9, 11],
 [13, 15, 17, 19, 21, 23],
 [25, 27, 29, 31, 33, 35],
 [37, 39, 41, 43, 45, 47],
 [49, 51, 53, 55, 57, 59],
 [61, 63, 65, 67, 69, 71]]
</code>```

In the next step, I would like to apply tf.space_to_depth function and here it is:

```<code>trans = tf.space_to_depth(norm,2)
</code>```

Output shape is : (1,3,3,8) and here is the output of this function:

```<code>trans[0,:,:,0]
[[ 0,  4,  8],
 [24, 28, 32],
 [48, 52, 56]]
trans[0,:,:,1]
[[ 1,  5,  9],
 [25, 29, 33],
 [49, 53, 57]]
trans[0,:,:,2]
[[ 2,  6, 10],
 [26, 30, 34],
 [50, 54, 58]]
trans[0,:,:,3]
[[ 3,  7, 11],
 [27, 31, 35],
 [51, 55, 59]]
trans[0,:,:,4]
[[12, 16, 20],
 [36, 40, 44],
 [60, 64, 68]]
trans[0,:,:,5]
[[13, 17, 21],
 [37, 41, 45],
 [61, 65, 69]]
trans[0,:,:,6]
[[14, 18, 22],
 [38, 42, 46],
 [62, 66, 70]]
trans[0,:,:,7]
[[15, 19, 23],
 [39, 43, 47],
 [63, 67, 71]]
</code>```

May someone help me how can I implement a vectorized version of this function in numpy?

Appreciating in advance for any response!

Body:
These is a function in tensorflow called tf.space_to_depth. The implementation of this function in Tensorflow source code is so difficult for me. Could you please help me to implement it using numpy?

Here is some code to visualize how this function works. By the way, before everything, it is good to mention that the input to tensorflow's function should have input shape : [batch, height, width, depth]

Assuming this code. First we need to define a tensor:

norm = tf.reshape(tf.range(0,72),(1,6,6,2))

Here is the value of depth 1 (norm[0,:,:,0]):

[[ 0,  2,  4,  6,  8, 10],
 [12, 14, 16, 18, 20, 22],
 [24, 26, 28, 30, 32, 34],
 [36, 38, 40, 42, 44, 46],
 [48, 50, 52, 54, 56, 58],
 [60, 62, 64, 66, 68, 70]]

Here is the value of depth 2 (norm[0,:,:,1]):

[[ 1,  3,  5,  7,  9, 11],
 [13, 15, 17, 19, 21, 23],
 [25, 27, 29, 31, 33, 35],
 [37, 39, 41, 43, 45, 47],
 [49, 51, 53, 55, 57, 59],
 [61, 63, 65, 67, 69, 71]]

In the next step, I would like to apply tf.space_to_depth function and here it is:

trans = tf.space_to_depth(norm,2)

Output shape is : (1,3,3,8) and here is the output of this function:

trans[0,:,:,0]
[[ 0,  4,  8],
 [24, 28, 32],
 [48, 52, 56]]
trans[0,:,:,1]
[[ 1,  5,  9],
 [25, 29, 33],
 [49, 53, 57]]
trans[0,:,:,2]
[[ 2,  6, 10],
 [26, 30, 34],
 [50, 54, 58]]
trans[0,:,:,3]
[[ 3,  7, 11],
 [27, 31, 35],
 [51, 55, 59]]
trans[0,:,:,4]
[[12, 16, 20],
 [36, 40, 44],
 [60, 64, 68]]
trans[0,:,:,5]
[[13, 17, 21],
 [37, 41, 45],
 [61, 65, 69]]
trans[0,:,:,6]
[[14, 18, 22],
 [38, 42, 46],
 [62, 66, 70]]
trans[0,:,:,7]
[[15, 19, 23],
 [39, 43, 47],
 [63, 67, 71]]

May someone help me how can I implement a vectorized version of this function in numpy?

Appreciating in advance for any response!

Body:
You can implement space_to_depth with appropriate calls to the reshape() and swapaxes() functions:

import numpy as np

def space_to_depth(x, block_size):
    x = np.asarray(x)
    batch, height, width, depth = x.shape
    reduced_height = height // block_size
    reduced_width = width // block_size
    y = x.reshape(batch, reduced_height, block_size,
                         reduced_width, block_size, depth)
    z = np.swapaxes(y, 2, 3).reshape(batch, reduced_height, reduced_width, -1)
    return z

Here are the examples from the documentation of tf.space_to_depth:

In [328]: x = [[[[1], [2]],
     ...:       [[3], [4]]]]
     ...:

In [329]: space_to_depth(x, 2)
Out[329]: array([[[[1, 2, 3, 4]]]])

In [330]: x = [[[[1, 2, 3], [4, 5, 6]],
     ...:       [[7, 8, 9], [10, 11, 12]]]]
     ...:

In [331]: space_to_depth(x, 2)
Out[331]: array([[[[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]]]])

In [332]: x = [[[[1],   [2],  [5],  [6]],
     ...:       [[3],   [4],  [7],  [8]],
     ...:       [[9],  [10], [13],  [14]],
     ...:       [[11], [12], [15],  [16]]]]
     ...:

In [333]: space_to_depth(x, 2)
Out[333]:
array([[[[ 1,  2,  3,  4],
         [ 5,  6,  7,  8]],

        [[ 9, 10, 11, 12],
         [13, 14, 15, 16]]]])

And here is your example:

In [334]: norm = np.arange(72).reshape(1, 6, 6, 2)

In [335]: trans = space_to_depth(norm, 2)

In [336]: trans[0, :, :, 0]
Out[336]:
array([[ 0,  4,  8],
       [24, 28, 32],
       [48, 52, 56]])

In [337]: trans[0, :, :, 1]
Out[337]:
array([[ 1,  5,  9],
       [25, 29, 33],
       [49, 53, 57]])

In [338]: trans[0, :, :, 7]
Out[338]:
array([[15, 19, 23],
       [39, 43, 47],
       [63, 67, 71]])


问:
Google Spreadsheet Creation - Node.js
I am trying to create new google spreadsheet using the google spreadsheet api using node.js

I have managed to get the Google OAuth 2.0 working, where I am getting the access tokens for the clients.

Now on searching the Google API docs there are example using the gData client library but nothing giving me pointers to node.js

Here are my findings for creating a new google spreadhseet

Upload a spreadsheet manually  OR

Use a resumable upload link

There is not much information on the resumable upload link.

I can see the HTTP Post Request and Response but I do not understand how to construct the post request in node.js

EDIT--

I am reading Google Apps Platform

答:
Here is how to do it with the create method of the Google Sheets API (currently v4).

This code examples does not use any 3rd party libraries, it uses googleapis: Google API's official Node.js client

```<code>const google = require('googleapis');
const sheets = google.sheets('v4');

// authenticate, and store that authentication, in this example
// it is stored in a variable called `auth`. I am using JWT
// authentication, but you can use the any form of authentication

const auth = new google.auth.JWT(
  key.client_email,
  null,
  key.private_key,
  ['https://www.googleapis.com/auth/spreadsheets'], // make sure that your auth scope includes `spreadsheets`, `drive` or `drive.file`
  null
);

sheets.spreadsheets.create({
  auth: auth,
  resource: {
    properties: {
      title: 'Title of your new spreadsheet'
    }
  }
}, (err, response) => {
  if (err) {
    console.log(`The API returned an error: ${err}`);
    return;
  }

  console.log('Created a new spreadsheet:')
  console.log(response);
});
</code>```

Title: Google Spreadsheet Creation - Node.js

Body:
Here is how to do it with the create method of the Google Sheets API (currently v4).

This code examples does not use any 3rd party libraries, it uses googleapis: Google API's official Node.js client

const google = require('googleapis');
const sheets = google.sheets('v4');

// authenticate, and store that authentication, in this example
// it is stored in a variable called `auth`. I am using JWT
// authentication, but you can use the any form of authentication

const auth = new google.auth.JWT(
  key.client_email,
  null,
  key.private_key,
  ['https://www.googleapis.com/auth/spreadsheets'], // make sure that your auth scope includes `spreadsheets`, `drive` or `drive.file`
  null
);

sheets.spreadsheets.create({
  auth: auth,
  resource: {
    properties: {
      title: 'Title of your new spreadsheet'
    }
  }
}, (err, response) => {
  if (err) {
    console.log(`The API returned an error: ${err}`);
    return;
  }

  console.log('Created a new spreadsheet:')
  console.log(response);
});


问:
How can i crawl web data that not in tags(class name is same)
Sorry.
I have asked a question like this.
After that i still have problem about data not in tag.
A few different the question i asked
(How can i crawl web data that not in tags)

```<code><div class="bbs" id="main-content">
    <div class="metaline">
        <span class="article-meta-tag">
             author
        </span>
        <span class="article-meta-value">
             Jorden
        </span>
    </div>
    <div class="metaline">
        <span class="article-meta-tag">
            board
        </span>
        <span class="article-meta-value">
            NBA
        </span>
    </div>

I am here

</div>
</code>```

I only need

I am here

答:
The string is a child of the main div of type NavigableString, so you can loop through div.children and filter based on the type of the node:

```<code>from bs4 import BeautifulSoup, NavigableString
[x.strip() for x in soup.find("div", {'id': 'main-content'}).children if isinstance(x, NavigableString) and x.strip()]
# [u'I am here']
</code>```

Data:

```<code>soup = BeautifulSoup("""<div class="bbs" id="main-content">
    <div class="metaline">
        <span class="article-meta-tag">
             author
        </span>
        <span class="article-meta-value">
             Jorden
        </span>
    </div>
    <div class="metaline">
        <span class="article-meta-tag">
            board
        </span>
        <span class="article-meta-value">
            NBA
        </span>
    </div>
I am here
</div>""", "html.parser")
</code>```

Body:
Sorry.
I have asked a question like this.
After that i still have problem about data not in tag.
A few different the question i asked
(How can i crawl web data that not in tags)

             author

             Jorden

            board

            NBA

I am here

I only need

I am here

Body:
The string is a child of the main div of type NavigableString, so you can loop through div.children and filter based on the type of the node:

from bs4 import BeautifulSoup, NavigableString
[x.strip() for x in soup.find("div", {'id': 'main-content'}).children if isinstance(x, NavigableString) and x.strip()]
# [u'I am here']

Data:

soup = BeautifulSoup("""<div class="bbs" id="main-content">
    <div class="metaline">
        <span class="article-meta-tag">
             author
        </span>
        <span class="article-meta-value">
             Jorden
        </span>
    </div>
    <div class="metaline">
        <span class="article-meta-tag">
            board
        </span>
        <span class="article-meta-value">
            NBA
        </span>
    </div>
I am here
</div>""", "html.parser")


问:
How come you don't need to assign a value to an extern const (int) when including it in a header file? in c++
Usually when declaring a const of any sort you're supposed to assign a value to it immediately, but not in header files? why?</p>

答: It's because you declared it extern, extern tells the compiler that the definition and declaration of the variable are in another file and you are simply making your code "aware" of the existence of that variable, as such the compiler does not expect any assignment on the header.