问:
How can I find and replace in an encoded markdown file?
I have a script that pulls a markdown file from github. I then decode the file find and replace parameters in that file with user given inputs.

```<code>tempdict = {'key_1': 'input_1', 'key 2','input_2'}
</code>```

It worked great until I realized that it was missing some instances. I realized that the text was read in chunks of size 256 bytes, and if my 'key' was at the end of this chunk, then it would be on a different line of rawtext and my find and replace function would miss it. How can I avoid this error?

Code below:

```<code>url = 'https://raw.githubusercontent.com/foo/documents/master/bar.md'
rawtext = requests.get(fullurl)

rep = {}
for k,v in tempdict.items():
    rep[k.replace('_','\\_')]=v

decodedtext = []
for line in rawtext:
    decodedtext.append(line.decode("utf-8"))

editedtext = []
rep = dict((re.escape(k),v) for k,v in rep.items())

pattern = re.compile('|'.join(rep.keys()))
for line in decodedtext:
    line = pattern.sub(lambda m: rep[re.escape(m.group(0))],line)
    editedtext.append(line)

encodedtext =[]
for line in editedtext:
    encodedtext.append(str.encode(line))

markdownfile = open('edited.md','wb')
for i in encodedtext:
    markdownfile.write(i)
markdownfile.close()
</code>```

Psuedo-Markdown file below.

```<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pharetra,
urna ullamcorper congue aliquet, leo nulla facilisis ipsum, tincidunt
suscipit eros erat tempor orci. Sed porttitor convallis ligula, a pharetra
nisl rhoncus sit key_1. Maecenas consequat sem nec urna mattis, non ornare
risus fermentum. Nam consectetur volutpat felis sed blandit. Etiam eu
sollicitudin diam, eu euismod diam. Fusce diam libero, sagittis varius elit
nec, ultricies key_2 est. Sed nibh purus, tincidunt eu fringilla ut,
ultrices et orci.
</code>```

Anytime I tried to use rawtext.text or rawtext.iter_items() it wouldn't keep the markdown format. Also, I replace the items in tempdict to rep because the rawtext adds \\ before every underscore.

答:
Your issue is that you are checking each section of a list for a match, which means that if a match is partially in 2 list entries then it will not be matched. Instead of creating a list, create 1 string, split it by new lines (assuming you are not trying to match any new lines) and perform your check against the new list.</p>

```<code>decodedtext = ""
for line in rawtext:
    decodedtext += line.decode("utf-8")
...
for line in decodedtext.split("\n"):
</code>```

Body:
I have a script that pulls a markdown file from github. I then decode the file find and replace parameters in that file with user given inputs.

tempdict = {'key_1': 'input_1', 'key 2','input_2'}

It worked great until I realized that it was missing some instances. I realized that the text was read in chunks of size 256 bytes, and if my 'key' was at the end of this chunk, then it would be on a different line of rawtext and my find and replace function would miss it. How can I avoid this error?

Code below:

url = 'https://raw.githubusercontent.com/foo/documents/master/bar.md'
rawtext = requests.get(fullurl)

rep = {}
for k,v in tempdict.items():
    rep[k.replace('_','\\_')]=v

decodedtext = []
for line in rawtext:
    decodedtext.append(line.decode("utf-8"))

editedtext = []
rep = dict((re.escape(k),v) for k,v in rep.items())

pattern = re.compile('|'.join(rep.keys()))
for line in decodedtext:
    line = pattern.sub(lambda m: rep[re.escape(m.group(0))],line)
    editedtext.append(line)

encodedtext =[]
for line in editedtext:
    encodedtext.append(str.encode(line))

markdownfile = open('edited.md','wb')
for i in encodedtext:
    markdownfile.write(i)
markdownfile.close()

Psuedo-Markdown file below.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pharetra,
urna ullamcorper congue aliquet, leo nulla facilisis ipsum, tincidunt
suscipit eros erat tempor orci. Sed porttitor convallis ligula, a pharetra
nisl rhoncus sit key_1. Maecenas consequat sem nec urna mattis, non ornare
risus fermentum. Nam consectetur volutpat felis sed blandit. Etiam eu
sollicitudin diam, eu euismod diam. Fusce diam libero, sagittis varius elit
nec, ultricies key_2 est. Sed nibh purus, tincidunt eu fringilla ut,
ultrices et orci.

Anytime I tried to use rawtext.text or rawtext.iter_items() it wouldn't keep the markdown format. Also, I replace the items in tempdict to rep because the rawtext adds \\ before every underscore.

Body:
Your issue is that you are checking each section of a list for a match, which means that if a match is partially in 2 list entries then it will not be matched. Instead of creating a list, create 1 string, split it by new lines (assuming you are not trying to match any new lines) and perform your check against the new list.

decodedtext = ""
for line in rawtext:
    decodedtext += line.decode("utf-8")
...
for line in decodedtext.split("\n"):


来源: stackexchange

问:
Merge multiple CSV into one DataFrame with filename as column name
I have a number of txt files in a directory that I'd like to combine.The following is an example of three files named df_A, df_B and df_c:

```<code>df_A
       0  1    2
0  James  1  yes
1   Jake  3   No
2   Jane  2  Yes

df_B
       0  1    2
0   Jane  2   No
1    Job  6   No
2  James  1  Yes

df_C
       0  1    2
0   Jack  4   No
1  Jenny  7  Yes
2  James  1   No
3   John  9  Yes
</code>```

AndI'd like the final dataframe to look like this:

```<code>ID  Name    df_A    df_B    df_C

1   James   Yes     Yes     No
3   Jake    No      NA      NA
2   Jane    Yes     No      NA
6   Job     NA      Yes     NA
4   Jack    NA      NA      No
7   Jenny   NA      NA      Yes
9   John    NA      NA      Yes
</code>```

this is the code I have thus far...

```<code>new_df = pd.DataFrame(columns = ['Name', 'ID'])

for filename in os.listdir('/path'):
    if filename.endswith('.txt'):
        course = os.path.splitext(filename)[0]

        new_df = pd.concat([combined_df,pd.DataFrame(columns=[course])])
        data = pd.read_csv(filename, sep="\t", header=None)

        for i in data[data.columns[1]]:
            if i not in new_df['ID']:
                new_df['ID'].append(i)
</code>```

答:
```<code>import os
import pandas as pd

combinedDF = pd.DataFrame(columns=['Name','ID'])

for filename in os.listdir(os.getcwd()):
    if filename.endswith('.txt'):
        df = pd.read_csv(filename, header=None, delimiter=' ')
        df.columns=['Name','ID',filename[:-4]]
        combinedDF = combinedDF.merge(df, on=['Name', 'ID'], how='outer')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a number of txt files in a directory that I'd like to combine.The following is an example of three files named df_A, df_B and df_c:

df_A
       0  1    2
0  James  1  yes
1   Jake  3   No
2   Jane  2  Yes

df_B
       0  1    2
0   Jane  2   No
1    Job  6   No
2  James  1  Yes

df_C
       0  1    2
0   Jack  4   No
1  Jenny  7  Yes
2  James  1   No
3   John  9  Yes

AndI'd like the final dataframe to look like this:

ID  Name    df_A    df_B    df_C

1   James   Yes     Yes     No
3   Jake    No      NA      NA
2   Jane    Yes     No      NA
6   Job     NA      Yes     NA
4   Jack    NA      NA      No
7   Jenny   NA      NA      Yes
9   John    NA      NA      Yes

this is the code I have thus far...

new_df = pd.DataFrame(columns = ['Name', 'ID'])

for filename in os.listdir('/path'):
    if filename.endswith('.txt'):
        course = os.path.splitext(filename)[0]

        new_df = pd.concat([combined_df,pd.DataFrame(columns=[course])])
        data = pd.read_csv(filename, sep="\t", header=None)

        for i in data[data.columns[1]]:
            if i not in new_df['ID']:
                new_df['ID'].append(i)


问:
Which hook to add custom data In New Order Admin Woocommerce email
In WooCommerce, How and where I can apply some code for New Order Email notification, where I should get the Applied Coupon Code display.

In the template for New Order Email notification I have @hooked WC_Emails::order_details() that shows the order details table…

Also is WC_Email::order_details() the exact hook which I am searching for to update coupon code in New order mail to admin?

I am loosed, any help will be really appreciated…

答:
The hook that you are searching is woocommerce_email_order_details action hook that can be used this way:

```<code>add_action( 'woocommerce_email_order_details', 'action_email_order_details', 10, 4 );
    function action_email_order_details( $order, $sent_to_admin, $plain_text, $email ) {
     if( $sent_to_admin ): // For admin emails notification

     // Your code goes HERE

     endif;
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

In your function you can use any of the 4 arguments from the hook like $order the WC_Order object.

You can use the WC_Abstract_Order method get_used_coupons() that will give you an array of coupons codes used in the order, like:

```<code>// Get the array of coupons codes
$coupon_codes = $order->get_used_coupons();

// Convert and display the array in a coma separated string:
echo 'Coupon codes: ' . implode( ', ', $coupon_codes );
</code>```

Body:
The hook that you are searching is woocommerce_email_order_details action hook that can be used this way:

add_action( 'woocommerce_email_order_details', 'action_email_order_details', 10, 4 );
    function action_email_order_details( $order, $sent_to_admin, $plain_text, $email ) {
     if( $sent_to_admin ): // For admin emails notification

     // Your code goes HERE

     endif;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

In your function you can use any of the 4 arguments from the hook like $order the WC_Order object.

You can use the WC_Abstract_Order method get_used_coupons() that will give you an array of coupons codes used in the order, like:

// Get the array of coupons codes
$coupon_codes = $order->get_used_coupons();

// Convert and display the array in a coma separated string:
echo 'Coupon codes: ' . implode( ', ', $coupon_codes );


问:
JOIN or Conditional Logic Between 4+ Tables
Full disclosure, this is a homework question, but I have 20 more of these that are much more difficult, I just really can't wrap my head around some of the more complicated statements, so I'd appreciate the help before I just give up on the assignment completely. The professor and TA declined any help.

I'm using the 'HR' table that is present as a demo in all Oracle DBs. I need to create a unique listing of all jobs in a particular department along with the locations. It has the tables: REGIONS, LOCATIONS, DEPARTMENTS, JOBS, and EMPLOYEES of the form described below:

Locations:

```<code> Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 LOCATION_ID                   NOT NULL NUMBER(4)
 STREET_ADDRESS                     VARCHAR2(40)
 POSTAL_CODE                        VARCHAR2(12)
 CITY                      NOT NULL VARCHAR2(30)
 STATE_PROVINCE                     VARCHAR2(25)
 COUNTRY_ID                     CHAR(2)
</code>```

Jobs:

```<code> Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 JOB_ID                    NOT NULL VARCHAR2(10)
 JOB_TITLE                 NOT NULL VARCHAR2(35)
 MIN_SALARY                     NUMBER(6)
 MAX_SALARY                     NUMBER(6)
</code>```

Employees:

```<code> Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EMPLOYEE_ID                   NOT NULL NUMBER(6)
 FIRST_NAME                     VARCHAR2(20)
 LAST_NAME                 NOT NULL VARCHAR2(25)
 EMAIL                     NOT NULL VARCHAR2(25)
 PHONE_NUMBER                       VARCHAR2(20)
 HIRE_DATE                 NOT NULL DATE
 JOB_ID                    NOT NULL VARCHAR2(10)
 SALARY                         NUMBER(8,2)
 COMMISSION_PCT                     NUMBER(2,2)
 MANAGER_ID                     NUMBER(6)
 DEPARTMENT_ID                      NUMBER(4)
</code>```

Departments:

```<code> Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 DEPARTMENT_ID                 NOT NULL NUMBER(4)
 DEPARTMENT_NAME               NOT NULL VARCHAR2(30)
 MANAGER_ID                     NUMBER(6)
 LOCATION_ID                        NUMBER(4)
</code>```

So of course I can think through how the relational algebra kind of goes, but I have no clue how it would go in SQL syntax. I of course know how to do more trivial joins, but I'm not understanding how to agregate all of the requirements into one statement. I want to get all UNIQUE or DISTINCT JOB_IDs where DEPARTMENT_ID=80,Then do a join on Jobs to get the matching JOB_TITLE,then derive LOCATION_ID from DEPARTMENTS.DEPARTMENT_ID and finally join Locations to my original JOB_TITLE selection WHERE LOCATION.LOCATION_ID=DEPARTMENTS.DEPARTMENT_ID. So what does that look like. Do I have to do 3 joins to get all the information in one selection?

答:
This might help you. Add 'Where' condition as per your requirement.</p>

```<code>select (select j.job_title from jobs j where j.JOB_ID=x.JOB_ID) as Job_Title ,
        (select dp.department_name from department dp where dp.department_id) as Department_Name,
        (select l.City || l.State_province from Location l where l.location_id = x.location_id) as Location
(select
        e. JOB_ID,
        D.DEPARTMENT_ID,
        d.location_id
from Employees e inner join Department d on e.DEPARTMENT_ID = d.DEPARTMENT_ID
group by l.location_id,d.DEPARTMENT_ID , e.JOB_ID) x
</code>```

Body:
Full disclosure, this is a homework question, but I have 20 more of these that are much more difficult, I just really can't wrap my head around some of the more complicated statements, so I'd appreciate the help before I just give up on the assignment completely. The professor and TA declined any help.

I'm using the 'HR' table that is present as a demo in all Oracle DBs. I need to create a unique listing of all jobs in a particular department along with the locations. It has the tables: REGIONS, LOCATIONS, DEPARTMENTS, JOBS, and EMPLOYEES of the form described below:

Locations:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 LOCATION_ID                   NOT NULL NUMBER(4)
 STREET_ADDRESS                     VARCHAR2(40)
 POSTAL_CODE                        VARCHAR2(12)
 CITY                      NOT NULL VARCHAR2(30)
 STATE_PROVINCE                     VARCHAR2(25)
 COUNTRY_ID                     CHAR(2)

Jobs:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 JOB_ID                    NOT NULL VARCHAR2(10)
 JOB_TITLE                 NOT NULL VARCHAR2(35)
 MIN_SALARY                     NUMBER(6)
 MAX_SALARY                     NUMBER(6)

Employees:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EMPLOYEE_ID                   NOT NULL NUMBER(6)
 FIRST_NAME                     VARCHAR2(20)
 LAST_NAME                 NOT NULL VARCHAR2(25)
 EMAIL                     NOT NULL VARCHAR2(25)
 PHONE_NUMBER                       VARCHAR2(20)
 HIRE_DATE                 NOT NULL DATE
 JOB_ID                    NOT NULL VARCHAR2(10)
 SALARY                         NUMBER(8,2)
 COMMISSION_PCT                     NUMBER(2,2)
 MANAGER_ID                     NUMBER(6)
 DEPARTMENT_ID                      NUMBER(4)

Departments:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 DEPARTMENT_ID                 NOT NULL NUMBER(4)
 DEPARTMENT_NAME               NOT NULL VARCHAR2(30)
 MANAGER_ID                     NUMBER(6)
 LOCATION_ID                        NUMBER(4)

So of course I can think through how the relational algebra kind of goes, but I have no clue how it would go in SQL syntax. I of course know how to do more trivial joins, but I'm not understanding how to agregate all of the requirements into one statement. I want to get all UNIQUE or DISTINCT JOB_IDs where DEPARTMENT_ID=80,Then do a join on Jobs to get the matching JOB_TITLE,then derive LOCATION_ID from DEPARTMENTS.DEPARTMENT_ID and finally join Locations to my original JOB_TITLE selection WHERE LOCATION.LOCATION_ID=DEPARTMENTS.DEPARTMENT_ID. So what does that look like. Do I have to do 3 joins to get all the information in one selection?

Body:
This might help you. Add 'Where' condition as per your requirement.

select (select j.job_title from jobs j where j.JOB_ID=x.JOB_ID) as Job_Title ,
        (select dp.department_name from department dp where dp.department_id) as Department_Name,
        (select l.City || l.State_province from Location l where l.location_id = x.location_id) as Location
(select
        e. JOB_ID,
        D.DEPARTMENT_ID,
        d.location_id
from Employees e inner join Department d on e.DEPARTMENT_ID = d.DEPARTMENT_ID
group by l.location_id,d.DEPARTMENT_ID , e.JOB_ID) x


问:
div height calc(100% - 50px) not working
https://codepen.io/joshuajazleung/pen/EbbgBN

```<code><div class="outer">
  <div class="inner">
    <img src="https://placehold.it/300x200" alt="">
    <div>Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio animi harum impedit ex esse labore, placeat, tempore sapiente nisi cupiditate fugiat soluta ullam dicta ducimus accusamus tenetur consequuntur nesciunt earum!</div>
  </div>
</div>

.outer {
  background: red;
  position: relative;
  height: calc(100% - 60px);
}

.inner {
  position: relative;
  top: -100px;
}
</code>```

since .inner is moved to top a little bit, to reduce .outer overall space, I use

```<code>height: calc(100% - 50px); // my logic is that it's div's height minus 50px
</code>```

But it's not working, wondering why?

答:
```<code>.outer {
  background: red;
  position: relative;
  height: calc(100vh - 50px);
}
</code>```

Try to change 100% => 100vh

Body:
https://codepen.io/joshuajazleung/pen/EbbgBN

Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio animi harum impedit ex esse labore, placeat, tempore sapiente nisi cupiditate fugiat soluta ullam dicta ducimus accusamus tenetur consequuntur nesciunt earum!

.outer {
  background: red;
  position: relative;
  height: calc(100% - 60px);
}

.inner {
  position: relative;
  top: -100px;
}

since .inner is moved to top a little bit, to reduce .outer overall space, I use

height: calc(100% - 50px); // my logic is that it's div's height minus 50px

But it's not working, wondering why?

Body:
.outer {
  background: red;
  position: relative;
  height: calc(100vh - 50px);
}

Try to change 100% => 100vh


问:
How to get stack trace for all warnings?
Is it possible to get a stack trace printed for all warnings?

I can get it for all errors with: perl -MCarp::Always my_script.pl

But how can I get it for warnings?

答:
perl -d:Confess script.pl

from http://search.cpan.org/~haarg/Devel-Confess-0.006001/lib/Devel/Confess.pm


问:
Set value using php echo in select option tag
How do I get this to work?

```<code><div class="form-group">
    <label for="data[day]">Day:</label>
    <?php $day_of_week = array('','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday') ?>
    <select class="form-control">

        <?php foreach($day_of_week as $day):?>
        <option value="<?php echo $day; ?>"><?php echo $day; ?></option>
        <?php endforeach; ?>

    </select>
</div>
</code>```

I wanted the user to select day of the week using the combobox and it should return the value of the option tag into database.I am wondering why this method does not return any value in database. Any correction would be appreciated. This div tag is in form tag where it will return the form to the database.

答:
Your <select> tag doesn't have a name, so the value won't be submitted to the server. It also doesn't have an id, so the label won't be linked with it.

```<code><select id="data[day]" name="day" class="form-control">
</code>```

When the form is submitted, the value will be in $_POST['day'].

Body:
How do I get this to work?

    Day:
    <?php $day_of_week = array('','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday') ?>
    <select class="form-control">

        <?php foreach($day_of_week as $day):?>
        <option value="<?php echo $day; ?>"><?php echo $day; ?></option>
        <?php endforeach; ?>

    </select>

I wanted the user to select day of the week using the combobox and it should return the value of the option tag into database.I am wondering why this method does not return any value in database. Any correction would be appreciated. This div tag is in form tag where it will return the form to the database.

Body:
Your <select> tag doesn't have a name, so the value won't be submitted to the server. It also doesn't have an id, so the label won't be linked with it.

<select id="data[day]" name="day" class="form-control">

When the form is submitted, the value will be in $_POST['day'].


问:
Implementing Click on anywhere on Layout
I want to implement Click on anywhere on Layout but for some reason app get stopped and I don't understand why. here is relevant part of my code

```<code>public class MainActivity extends AppCompatActivity {
....
    private TextView Issue;
 ....
 private Handler handler = new Handler();
 private Runnable runnable = new Runnable() {
        @Override
        public void run() {
....

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

 ////here is where I code to touch screen
 RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.mainlayout);
        rlayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {

               mp.stop();
                return true;
            }
        });
</code>```

I also tried OnClickListener instead of setOnTouchListener and it didn't solve. Thanks

答:
1.Don't forget to add setContentView

2.Set RelativeLayout as global variable, it will be used in other method

3.Use setOnClickListener on RelativeLayout

```<code>private RelativeLayout rlayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // add setContentView here
    setContentView(R.layout.activity_main);
    //here is where I code to touch screen
    // set rlayout as global variable ,you can use it in other method
    rlayout = (RelativeLayout) findViewById(R.id.mainlayout);
    rlayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mp.stop();
        }
    });
}
</code>```

Body:
I want to implement Click on anywhere on Layout but for some reason app get stopped and I don't understand why. here is relevant part of my code

public class MainActivity extends AppCompatActivity {
....
    private TextView Issue;
 ....
 private Handler handler = new Handler();
 private Runnable runnable = new Runnable() {
        @Override
        public void run() {
....

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

 ////here is where I code to touch screen
 RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.mainlayout);
        rlayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {

               mp.stop();
                return true;
            }
        });

I also tried OnClickListener instead of setOnTouchListener and it didn't solve. Thanks

Body:
1.Don't forget to add setContentView

2.Set RelativeLayout as global variable, it will be used in other method

3.Use setOnClickListener on RelativeLayout

private RelativeLayout rlayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // add setContentView here
    setContentView(R.layout.activity_main);
    //here is where I code to touch screen
    // set rlayout as global variable ,you can use it in other method
    rlayout = (RelativeLayout) findViewById(R.id.mainlayout);
    rlayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mp.stop();
        }
    });
}


问:
Strange Rails console behaviour
When I run a multi-line statement in the Rails 3.0.1 console, pressing enter doesn't actually run the statement. Instead, it goes to a new console line, and the cursor has been tabbed to the right. Then I have to run a basic line (like p "hey"), and then the multi-line statement will run.

```<code>ruby-1.9.2-p0 > images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;
ruby-1.9.2-p0 >     p "hey"
</code>```

I've been doing it like this for awhile and it's been working okay. But now I've got a problem in the console and it might be related. When I ran the above code, instead of it working like it normally does, it just went to a new console line with a ? added

```<code>ruby-1.9.2-p0 > images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;
ruby-1.9.2-p0 >     p "hey"
ruby-1.9.2-p0 ?>
</code>```

When it does this, I can't exit the console

```<code>ruby-1.9.2-p0 ?>  exit
ruby-1.9.2-p0 ?>  ^C
</code>```

Are these problems related? How can I fix them?

答:
Dunno what's wrong with irb/console but your ruby code could look a lot nicer:

```<code>images = Image.all.each { |im| im.save if im.imagestore_width.blank? }
</code>```

The general consensus is to use {} rather than do/end for single line blocks in ruby.

ContentLicense: CC BY-SA 2.5

Title: Strange Rails console behaviour

Body:
When I run a multi-line statement in the Rails 3.0.1 console, pressing enter doesn't actually run the statement. Instead, it goes to a new console line, and the cursor has been tabbed to the right. Then I have to run a basic line (like p "hey"), and then the multi-line statement will run.

ruby-1.9.2-p0 > images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;
ruby-1.9.2-p0 >     p "hey"

I've been doing it like this for awhile and it's been working okay. But now I've got a problem in the console and it might be related. When I ran the above code, instead of it working like it normally does, it just went to a new console line with a ? added

ruby-1.9.2-p0 > images = Image.all;images.each do |im|; if im.imagestore_width.blank?;im.save;end;
ruby-1.9.2-p0 >     p "hey"
ruby-1.9.2-p0 ?>

When it does this, I can't exit the console

ruby-1.9.2-p0 ?>  exit
ruby-1.9.2-p0 ?>  ^C

Are these problems related? How can I fix them?

Body:
Dunno what's wrong with irb/console but your ruby code could look a lot nicer:

images = Image.all.each { |im| im.save if im.imagestore_width.blank? }

The general consensus is to use {} rather than do/end for single line blocks in ruby.


问:
Cannot connect to elasticsearch on docker from golang
I'm using olivere's elastic go library (https://godoc.org/gopkg.in/olivere/elastic.v5) to create a connection to elasticsearch like so:

```<code>addr = "http://172.17.0.2:9200"
client, err := elastic.NewClient(elastic.SetURL(addr))
</code>```

and am getting this error:

```<code>health check timeout: no Elasticsearch node available
</code>```

Elasticsearch is running in a docker container and I am able to curl it from both my local machine and from the docker container. However, the go code (running on the docker container) is not able to connect to it.

```<code>curl -s -XGET 'http://172.17.0.2:9200/_nodes/http?pretty=1'
{
  "_nodes" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "cluster_name" : "elasticsearch",
  "nodes" : {
    "pGBN2DBISgSZ8hd9lFgmHw" : {
      "name" : "pGBN2DB",
      "transport_address" : "127.0.0.1:9300",
      "host" : "127.0.0.1",
      "ip" : "127.0.0.1",
      "version" : "5.6.4",
      "build_hash" : "8bbedf5",
      "roles" : [
        "master",
        "data",
        "ingest"
      ],
      "http" : {
        "bound_address" : [
          "0.0.0.0:9200"
        ],
        "publish_address" : "172.17.0.2:9200",
        "max_content_length_in_bytes" : 104857600
      }
    }
  }
}
</code>```

I'm using Docker for Mac. The publish address and IP are off, not sure if that has something to do with it. Would appreciate any help!

答:
Edit /etc/elasticsearch/elasticsearch.yml to add the following line:

```<code>network.host: 0.0.0.0
</code>```

This will allow connections from other IPs.

Possible duplicate of This question

Body:
I'm using olivere's elastic go library (https://godoc.org/gopkg.in/olivere/elastic.v5) to create a connection to elasticsearch like so:

addr = "http://172.17.0.2:9200"
client, err := elastic.NewClient(elastic.SetURL(addr))

and am getting this error:

health check timeout: no Elasticsearch node available

Elasticsearch is running in a docker container and I am able to curl it from both my local machine and from the docker container. However, the go code (running on the docker container) is not able to connect to it.

curl -s -XGET 'http://172.17.0.2:9200/_nodes/http?pretty=1'
{
  "_nodes" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "cluster_name" : "elasticsearch",
  "nodes" : {
    "pGBN2DBISgSZ8hd9lFgmHw" : {
      "name" : "pGBN2DB",
      "transport_address" : "127.0.0.1:9300",
      "host" : "127.0.0.1",
      "ip" : "127.0.0.1",
      "version" : "5.6.4",
      "build_hash" : "8bbedf5",
      "roles" : [
        "master",
        "data",
        "ingest"
      ],
      "http" : {
        "bound_address" : [
          "0.0.0.0:9200"
        ],
        "publish_address" : "172.17.0.2:9200",
        "max_content_length_in_bytes" : 104857600
      }
    }
  }
}

I'm using Docker for Mac. The publish address and IP are off, not sure if that has something to do with it. Would appreciate any help!

Body:
Edit /etc/elasticsearch/elasticsearch.yml to add the following line:

network.host: 0.0.0.0

This will allow connections from other IPs.

Possible duplicate of This question


问:
How To Transverse/Manipulate the DOM in Angular 4
I am looking for how to access a DOM element in A4.

I am having a hard time trying to wrap my head around this...  I've been reading about ElementRef, ViewChild, etc... but I still don't fully understand how to transverse the DOM elements in Angular 4.  For example what would this jQuery statement be in A4?

```<code>$('events > ion-content > div.scroll-content > ion-grid:nth-child(1)').css({blah blah});
</code>```

Like:

```<code>ElementRef.nativeElement - events > ion-content > div.scroll-content > ion-grid:nth-child(1)
</code>```

How do I access that element in the fashion above - without adding any ids, classes, or #template tags?  In certain situations I cannot access the html so I would like to know how to do this without the  use of jQuery since it's frowned upon with Angular :[

答:
How about this
<ion-grid [class.add-this-class]="whenThisState === true"></ion-grid> ?
or ngClass syntax if you fancy that.

Or do you want to get that element from a parent component or some other component ?

-EDIT-

If you cannot go to the angular template and do some binding there as I mentioned before, then basically you have 2 options Vanilla JS:
private theElementYouAreLookingFor: HTMLElement

In ngAfterViewInit() lifecycle try to fetch it with JS and store it this.theElementYouAreLookingFor or

with by using the new Angular way
@ViewChild('someVar') el:ElementRef;
constructor(private renderer: Renderer2) {}
and in ngAfterViewInit() this.el.nativeElement();

or by using Observables something like this:
`const clickEl = document.querySelector('#my-button');

const click$ = Rx.Observable.fromEvent(clickEl, 'click');`

and then subscribe

click$.subscribe(...)

Body:
I am looking for how to access a DOM element in A4.

I am having a hard time trying to wrap my head around this...  I've been reading about ElementRef, ViewChild, etc... but I still don't fully understand how to transverse the DOM elements in Angular 4.  For example what would this jQuery statement be in A4?

$('events > ion-content > div.scroll-content > ion-grid:nth-child(1)').css({blah blah});

Like:

ElementRef.nativeElement - events > ion-content > div.scroll-content > ion-grid:nth-child(1)

How do I access that element in the fashion above - without adding any ids, classes, or #template tags?  In certain situations I cannot access the html so I would like to know how to do this without the  use of jQuery since it's frowned upon with Angular :[


问:
Why .paintComponent() is defined on JComponent?
Sorry if my question doesn't adjust to the Stackoverflow requirements due to it is theorical but i don't know where else to ask.

For the past few weeks i've been trying to understand better how the Swing API works and it's components in order to create my own custom components. I've read tons of tutorials, searched in here, i am neck-deep in Java's swing source code and frankly... my mind is a mess.

As far as i understand, the swing components are composed of 3 parts:

the model: where the component state and data are stored

the UI delegate: which paints the component and

the JComponent: it ties everything together.

In this tutorial https://docs.oracle.com/javase/tutorial/uiswing/painting/step2.html there is a paragraph that says:

The paintComponent method is where all of your custom painting takes place. >This method is defined by javax.swing.JComponent and then overridden by your >subclasses to provide their custom behavior

Why is there a paintComponent method on a JComponent? Shouldn't it be an exclusive method of an UI delegate?

答:
Swing is based on AWT. So the initial restriction is based on how AWT paints it components.  Because Swing is light weight, when a components root component is painted, the child, Swing, components need to be notified that they need to update as well.  This is done by calling the paint methods of all the child components affected by the update (which in turn call the paintComponent methods).

Much of the decisions about the Swing API's paint chain are based around the concept of customisation.  It reduces the complexity involved (by discouraging the overriding of paint and focus the functionality down t the paintComponent method).

The Look and Feel API is based on a "delegate" model.  This means that the functionality used to perform a said action is "delegated" to some other object.  This means that the UI delegate UI doesn't actually know when a component "needs" to be painted, but instead is told, by the component, that it needs to be painted.  This makes it much more flexible and in many cases, easier to customise.

Based on your previous question a custom ButtonUI is probably one the better choices, this way you gain much more control over how the button is painted.

Trying to get the buttons to follow the current look and feels color schemes would be very difficult, but you could try having a look at the src.jar which is installed with the JDK, which includes many implementations of look and feels (and if your on Windows you should get the Windows look and feel as well, if your on Mac, then you don't get either Mac or Windows )

I started by having a look at BasicButtonUI and ButtonUI to get a better understanding of there properties.  I pulled some of more interesting methods into a custom ShapeButtonUI...

```<code>public class ShapeButtonUI extends BasicButtonUI {

    private Shape shape;

    public ShapeButtonUI(Shape shape) {
        this.shape = shape;
    }

    protected Color getSelectColor() {
        return UIManager.getColor(getPropertyPrefix() + "select");
    }

    protected Color getDisabledTextColor() {
        return UIManager.getColor(getPropertyPrefix()
                        + "disabledText");
    }

    protected Color getFocusColor() {
        return UIManager.getColor(getPropertyPrefix() + "focus");
    }

    @Override
    protected void installDefaults(AbstractButton b) {
        super.installDefaults(b);
    }

    @Override
    protected void uninstallDefaults(AbstractButton b) {
        super.uninstallDefaults(b);
    }

    @Override
    public void paint(Graphics g, JComponent c) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setClip(shape);
        Rectangle bounds = shape.getBounds();
        LinearGradientPaint lgp = new LinearGradientPaint(
                        new Point(bounds.x, bounds.y),
                        new Point(bounds.x, bounds.y + bounds.height),
                        new float[]{0, 1},
                        new Color[]{c.getBackground().brighter(), c.getBackground().darker()});
        g2d.setPaint(lgp);
        g2d.fill(shape);
        g2d.dispose();
        g2d = (Graphics2D) g.create();
        g2d.setColor(c.getForeground());
        g2d.draw(shape);
        g2d.dispose();
        super.paint(g, c);
    }

    @Override
    protected void paintButtonPressed(Graphics g, AbstractButton b) {
        super.paintButtonPressed(g, b);
    }

    @Override
    protected void paintFocus(Graphics g, AbstractButton b,
                    Rectangle viewRect, Rectangle textRect, Rectangle iconRect) {
        super.paintFocus(g, b, viewRect, textRect, iconRect);
    }

    @Override
    protected void paintText(Graphics g, AbstractButton b, Rectangle textRect, String text) {
        super.paintText(g, b, textRect, text);

//          ButtonModel model = b.getModel();
//          FontMetrics fm = SwingUtilities2.getFontMetrics(c, g);
//          int mnemIndex = b.getDisplayedMnemonicIndex();
//
//          /* Draw the Text */
//          if (model.isEnabled()) {
//              /**
//               * * paint the text normally
//               */
//              g.setColor(b.getForeground());
//          } else {
//              /**
//               * * paint the text disabled **
//               */
//              g.setColor(getDisabledTextColor());
//          }
//          SwingUtilities2.drawStringUnderlineCharAt(c, g, text, mnemIndex,
//                          textRect.x, textRect.y + fm.getAscent());

    }

    @Override
    public Dimension getMinimumSize(JComponent c) {
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.x + bounds.width + 1, bounds.y + bounds.height + 1);
    }

    @Override
    public Dimension getPreferredSize(JComponent c) {
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.x + bounds.width + 1, bounds.y + bounds.height + 1);
    }

    @Override
    public Dimension getMaximumSize(JComponent c) {
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.x + bounds.width + 1, bounds.y + bounds.height + 1);
    }

}
</code>```

Most of these you probably don't need to worry about, but you should at least know they exist as you may want to customise some of the other properties/functionality later.

This delegate is intended to be installed on a button as needed, as apposed to installing it as the default UI delegate for buttons.  The reason for this is the need for the shape object.  This allows each button to have it's own shape if you want.

You could seed a single shape into the UIManager's properties as well and use that instead, but I've not bothered for this example.

I then created my own shape/path...

```<code>public class PointerPath extends Path2D.Double {

    public PointerPath() {
        moveTo(1, 1);
        lineTo(150, 1);
        lineTo(198, 100);
        lineTo(150, 198);
        lineTo(1, 198);
        lineTo(50, 100);
        closePath();
    }

}
</code>```

And the applied it to a button...

```<code>ShapeButtonUI shapeUI = new ShapeButtonUI(new PointerPath());
JButton btn = new JButton("That way");
btn.setUI(shapeUI);
</code>```

Which finally generated something like...

Now, this is a really basic example, as realistically, the button should be sizing itself around the text (with some additional padding/margin information), but this would require a multi part shape, so we knew which sections could be resized and in what directions, so, complicated.

Body:
Swing is based on AWT. So the initial restriction is based on how AWT paints it components.  Because Swing is light weight, when a components root component is painted, the child, Swing, components need to be notified that they need to update as well.  This is done by calling the paint methods of all the child components affected by the update (which in turn call the paintComponent methods).

Much of the decisions about the Swing API's paint chain are based around the concept of customisation.  It reduces the complexity involved (by discouraging the overriding of paint and focus the functionality down t the paintComponent method).

The Look and Feel API is based on a "delegate" model.  This means that the functionality used to perform a said action is "delegated" to some other object.  This means that the UI delegate UI doesn't actually know when a component "needs" to be painted, but instead is told, by the component, that it needs to be painted.  This makes it much more flexible and in many cases, easier to customise.

Based on your previous question a custom ButtonUI is probably one the better choices, this way you gain much more control over how the button is painted.

Trying to get the buttons to follow the current look and feels color schemes would be very difficult, but you could try having a look at the src.jar which is installed with the JDK, which includes many implementations of look and feels (and if your on Windows you should get the Windows look and feel as well, if your on Mac, then you don't get either Mac or Windows )

I started by having a look at BasicButtonUI and ButtonUI to get a better understanding of there properties.  I pulled some of more interesting methods into a custom ShapeButtonUI...

public class ShapeButtonUI extends BasicButtonUI {

    private Shape shape;

    public ShapeButtonUI(Shape shape) {
        this.shape = shape;
    }

    protected Color getSelectColor() {
        return UIManager.getColor(getPropertyPrefix() + "select");
    }

    protected Color getDisabledTextColor() {
        return UIManager.getColor(getPropertyPrefix()
                        + "disabledText");
    }

    protected Color getFocusColor() {
        return UIManager.getColor(getPropertyPrefix() + "focus");
    }

    @Override
    protected void installDefaults(AbstractButton b) {
        super.installDefaults(b);
    }

    @Override
    protected void uninstallDefaults(AbstractButton b) {
        super.uninstallDefaults(b);
    }

    @Override
    public void paint(Graphics g, JComponent c) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setClip(shape);
        Rectangle bounds = shape.getBounds();
        LinearGradientPaint lgp = new LinearGradientPaint(
                        new Point(bounds.x, bounds.y),
                        new Point(bounds.x, bounds.y + bounds.height),
                        new float[]{0, 1},
                        new Color[]{c.getBackground().brighter(), c.getBackground().darker()});
        g2d.setPaint(lgp);
        g2d.fill(shape);
        g2d.dispose();
        g2d = (Graphics2D) g.create();
        g2d.setColor(c.getForeground());
        g2d.draw(shape);
        g2d.dispose();
        super.paint(g, c);
    }

    @Override
    protected void paintButtonPressed(Graphics g, AbstractButton b) {
        super.paintButtonPressed(g, b);
    }

    @Override
    protected void paintFocus(Graphics g, AbstractButton b,
                    Rectangle viewRect, Rectangle textRect, Rectangle iconRect) {
        super.paintFocus(g, b, viewRect, textRect, iconRect);
    }

    @Override
    protected void paintText(Graphics g, AbstractButton b, Rectangle textRect, String text) {
        super.paintText(g, b, textRect, text);

//          ButtonModel model = b.getModel();
//          FontMetrics fm = SwingUtilities2.getFontMetrics(c, g);
//          int mnemIndex = b.getDisplayedMnemonicIndex();
//
//          /* Draw the Text */
//          if (model.isEnabled()) {
//              /**
//               * * paint the text normally
//               */
//              g.setColor(b.getForeground());
//          } else {
//              /**
//               * * paint the text disabled **
//               */
//              g.setColor(getDisabledTextColor());
//          }
//          SwingUtilities2.drawStringUnderlineCharAt(c, g, text, mnemIndex,
//                          textRect.x, textRect.y + fm.getAscent());

    }

    @Override
    public Dimension getMinimumSize(JComponent c) {
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.x + bounds.width + 1, bounds.y + bounds.height + 1);
    }

    @Override
    public Dimension getPreferredSize(JComponent c) {
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.x + bounds.width + 1, bounds.y + bounds.height + 1);
    }

    @Override
    public Dimension getMaximumSize(JComponent c) {
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.x + bounds.width + 1, bounds.y + bounds.height + 1);
    }

}

Most of these you probably don't need to worry about, but you should at least know they exist as you may want to customise some of the other properties/functionality later.

This delegate is intended to be installed on a button as needed, as apposed to installing it as the default UI delegate for buttons.  The reason for this is the need for the shape object.  This allows each button to have it's own shape if you want.

You could seed a single shape into the UIManager's properties as well and use that instead, but I've not bothered for this example.

I then created my own shape/path...

public class PointerPath extends Path2D.Double {

    public PointerPath() {
        moveTo(1, 1);
        lineTo(150, 1);
        lineTo(198, 100);
        lineTo(150, 198);
        lineTo(1, 198);
        lineTo(50, 100);
        closePath();
    }

}

And the applied it to a button...

ShapeButtonUI shapeUI = new ShapeButtonUI(new PointerPath());
JButton btn = new JButton("That way");
btn.setUI(shapeUI);

Which finally generated something like...

Now, this is a really basic example, as realistically, the button should be sizing itself around the text (with some additional padding/margin information), but this would require a multi part shape, so we knew which sections could be resized and in what directions, so, complicated.


问:
How do I set up Gtk on Windows for Haskell development?
So far I have installed full version from https://www.haskell.org/platform/windows.html

Initially, pacman did not work so I did run as an administrator mingw64.exe found in

```<code>C:\Program Files\Haskell Platform\8.2.1\msys
</code>```

I have updated the msys2 sytem running pacman -Syu and installed all Gtk libraries. I am trying to compile https://github.com/mmsbrggr/hsudoku using stack. I have gone past the missing dll errors and now I get the following:

haskell-gi-base-0.20.4: configure

--  While building package haskell-gi-base-0.20.4 using:
        C:\sr\setup-exe-cache\x86_64-windows\Cabal-simple_Z6RU0evB_1.24.2.0_ghc-8.0.2.exe --builddir=.stack-work\dist\ca59d0ab configure --with-ghc=C:\Users\Jacek\AppData\Local\Programs\stack\x86_64-windows\ghc-8.0.2\bin\ghc.EXE
  --with-ghc-pkg=C:\Users\Jacek\AppData\Local\Programs\stack\x86_64-windows\ghc-8.0.2\bin\ghc-pkg.EXE
  --user --package-db=clear --package-db=global --package-db=C:\sr\snapshots\7eb65607\pkgdb --libdir=C:\sr\snapshots\7eb65607\lib --bindir=C:\sr\snapshots\7eb65607\bin --datadir=C:\sr\snapshots\7eb65607\share --libexecdir=C:\sr\snapshots\7eb65607\libexec --sysconfdir=C:\sr\snapshots\7eb65607\etc --docdir=C:\sr\snapshots\7eb65607\doc\haskell-gi-base-0.20.4 --htmldir=C:\sr\snapshots\7eb65607\doc\haskell-gi-base-0.20.4 --haddockdir=C:\sr\snapshots\7eb65607\doc\haskell-gi-base-0.20.4 --dependency=base=base-4.9.1.0 --dependency=bytestring=bytestring-0.10.8.1 --dependency=containers=containers-0.5.7.1 --dependency=text=text-1.2.2.2-9UQZjEJZQFSGMffj1Z5g00 "--extra-include-dirs=C:\Program Files\Haskell
  Platform\8.2.1\msys\mingw64\include"
  "--extra-include-dirs=C:\Program Files\Haskell
  Platform\8.2.1\msys\mingw64\include\GLIB-2.0"
  --extra-include-dirs=C:\Users\Jacek\AppData\Local\Programs\stack\x86_64-windows\msys2-20150512\mingw64\include
  --extra-include-dirs=C:\Users\Jacek\Downloads\glib-2.54.1 "--extra-lib-dirs=C:\Program Files\Haskell
  Platform\8.2.1\msys\mingw64\bin" "--extra-lib-dirs=C:\Program
  Files\Haskell Platform\8.2.1\msys\usr\bin"
  --extra-lib-dirs=C:\Users\Jacek\AppData\Local\Programs\stack\x86_64-windows\msys2-20150512\mingw64\bin
  --extra-lib-dirs=C:\Users\Jacek\AppData\Local\Programs\stack\x86_64-windows\msys2-20150512\mingw64\lib
      Process exited with code: ExitFailure 1
      Logs have been written to: C:\Users\Jacek\Documents\ExperimentingHaskell\hsudoku.stack-work\logs\haskell-gi-base-0.20.4.log

```<code>Configuring haskell-gi-base-0.20.4...
Cabal-simple_Z6RU0evB_1.24.2.0_ghc-8.0.2.exe: Missing dependencies on foreign
libraries:
* Missing C libraries: gobject-2.0, glib-2.0, intl
This problem can usually be solved by installing the system packages that
provide these libraries (you may need the "-dev" versions). If the libraries
are already installed but in a non-standard location then you can use the
flags --extra-include-dirs= and --extra-lib-dirs= to specify where they are.
</code>```

I am able to find includes, but I am concerned that some compiler options are wrapped in quotes. Could it be a problem?

How do I correctly add development files when I develop with Haskell and Gtk on Windows? How do I tell the Haskell compiler where it can find the includes?

extra-include-dirs: ['C:\Program Files\Haskell
  Platform\8.2.1\msys\mingw64\include',
  'C:\Users\Jacek\Downloads\glib-2.54.1','C:\Program Files\Haskell
  Platform\8.2.1\msys\mingw64\include\GLIB-2.0'] extra-lib-dirs:
  ['C:\Program Files\Haskell Platform\8.2.1\msys\mingw64\bin',
  'C:\Program Files\Haskell Platform\8.2.1\msys\usr\bin']

My extra-include dirs seem to be garbled in the compiler output.

答:
After all, I have managed to compile and launch example Haskell program written using Gtk library.

This gist is the record of the steps taken.

https://gist.github.com/bigos/62defeec09a06f18ee38daf644af5340

Body:
So far I have installed full version from https://www.haskell.org/platform/windows.html

Initially, pacman did not work so I did run as an administrator mingw64.exe found in

C:\Program Files\Haskell Platform\8.2.1\msys

I have updated the msys2 sytem running pacman -Syu and installed all Gtk libraries. I am trying to compile https://github.com/mmsbrggr/hsudoku using stack. I have gone past the missing dll errors and now I get the following:

haskell-gi-base-0.20.4: configure

--  While building package haskell-gi-base-0.20.4 using:
        C:\sr\setup-exe-cache\x86_64-windows\Cabal-simple_Z6RU0evB_1.24.2.0_ghc-8.0.2.exe --builddir=.stack-work\dist\ca59d0ab configure --with-ghc=C:\Users\Jacek\AppData\Local\Programs\stack\x86_64-windows\ghc-8.0.2\bin\ghc.EXE
  --with-ghc-pkg=C:\Users\Jacek\AppData\Local\Programs\stack\x86_64-windows\ghc-8.0.2\bin\ghc-pkg.EXE
  --user --package-db=clear --package-db=global --package-db=C:\sr\snapshots\7eb65607\pkgdb --libdir=C:\sr\snapshots\7eb65607\lib --bindir=C:\sr\snapshots\7eb65607\bin --datadir=C:\sr\snapshots\7eb65607\share --libexecdir=C:\sr\snapshots\7eb65607\libexec --sysconfdir=C:\sr\snapshots\7eb65607\etc --docdir=C:\sr\snapshots\7eb65607\doc\haskell-gi-base-0.20.4 --htmldir=C:\sr\snapshots\7eb65607\doc\haskell-gi-base-0.20.4 --haddockdir=C:\sr\snapshots\7eb65607\doc\haskell-gi-base-0.20.4 --dependency=base=base-4.9.1.0 --dependency=bytestring=bytestring-0.10.8.1 --dependency=containers=containers-0.5.7.1 --dependency=text=text-1.2.2.2-9UQZjEJZQFSGMffj1Z5g00 "--extra-include-dirs=C:\Program Files\Haskell
  Platform\8.2.1\msys\mingw64\include"
  "--extra-include-dirs=C:\Program Files\Haskell
  Platform\8.2.1\msys\mingw64\include\GLIB-2.0"
  --extra-include-dirs=C:\Users\Jacek\AppData\Local\Programs\stack\x86_64-windows\msys2-20150512\mingw64\include
  --extra-include-dirs=C:\Users\Jacek\Downloads\glib-2.54.1 "--extra-lib-dirs=C:\Program Files\Haskell
  Platform\8.2.1\msys\mingw64\bin" "--extra-lib-dirs=C:\Program
  Files\Haskell Platform\8.2.1\msys\usr\bin"
  --extra-lib-dirs=C:\Users\Jacek\AppData\Local\Programs\stack\x86_64-windows\msys2-20150512\mingw64\bin
  --extra-lib-dirs=C:\Users\Jacek\AppData\Local\Programs\stack\x86_64-windows\msys2-20150512\mingw64\lib
      Process exited with code: ExitFailure 1
      Logs have been written to: C:\Users\Jacek\Documents\ExperimentingHaskell\hsudoku.stack-work\logs\haskell-gi-base-0.20.4.log

Configuring haskell-gi-base-0.20.4...
Cabal-simple_Z6RU0evB_1.24.2.0_ghc-8.0.2.exe: Missing dependencies on foreign
libraries:
* Missing C libraries: gobject-2.0, glib-2.0, intl
This problem can usually be solved by installing the system packages that
provide these libraries (you may need the "-dev" versions). If the libraries
are already installed but in a non-standard location then you can use the
flags --extra-include-dirs= and --extra-lib-dirs= to specify where they are.

I am able to find includes, but I am concerned that some compiler options are wrapped in quotes. Could it be a problem?

How do I correctly add development files when I develop with Haskell and Gtk on Windows? How do I tell the Haskell compiler where it can find the includes?

extra-include-dirs: ['C:\Program Files\Haskell
  Platform\8.2.1\msys\mingw64\include',
  'C:\Users\Jacek\Downloads\glib-2.54.1','C:\Program Files\Haskell
  Platform\8.2.1\msys\mingw64\include\GLIB-2.0'] extra-lib-dirs:
  ['C:\Program Files\Haskell Platform\8.2.1\msys\mingw64\bin',
  'C:\Program Files\Haskell Platform\8.2.1\msys\usr\bin']

My extra-include dirs seem to be garbled in the compiler output.


问:
nmake: can a batch file run as part of a make command block, affect the environment of the nmake.exe process?
I think in nmake if I do this:

```<code> example :
        set value=77
        echo %%value%%
</code>```

The result will display 77 on the console.

Is there a way for me to invoke a .cmd or .bat file that will affect the environment of the nmake.exe process?  Suppose I put the statement set value=77 in a file called "setvalue.cmd".  Then change the makefile to this:

```<code> example :
        setvalue
        echo %%value%%
</code>```

I get:

```<code>%value%
</code>```

Alternatively, if there's a way to set a macro within a command block, that would also work.  Or, a way to set the value of a macro from a batch file, even outside a command block.

答:
You can create an nmake snippet during makefile pre-processing, and read that in. Assuming batch.cmd outputs valid nmake syntax, then

```<code>!if [batch.cmd >makefile.auto]
!error *** Could not create makefile.auto
!endif
!include makefile.auto
</code>```

You should ensure batch.cmd sets %errorlevel% appropriately (e.g., exit /b 22).

makefile.auto can contain anything, but you would probably want stuff like value=77. A couple of points:

Dereference value using nmake syntax ($(value))

You can pass parameters to batch.cmd if necessary ([batch.cmd $(OBJECTS) >makefile.auto])

Body:
I think in nmake if I do this:

 example :
        set value=77
        echo %%value%%

The result will display 77 on the console.

Is there a way for me to invoke a .cmd or .bat file that will affect the environment of the nmake.exe process?  Suppose I put the statement set value=77 in a file called "setvalue.cmd".  Then change the makefile to this:

 example :
        setvalue
        echo %%value%%

I get:

%value%

Alternatively, if there's a way to set a macro within a command block, that would also work.  Or, a way to set the value of a macro from a batch file, even outside a command block.

Body:
You can create an nmake snippet during makefile pre-processing, and read that in. Assuming batch.cmd outputs valid nmake syntax, then

!if [batch.cmd >makefile.auto]
!error *** Could not create makefile.auto
!endif
!include makefile.auto

You should ensure batch.cmd sets %errorlevel% appropriately (e.g., exit /b 22).

makefile.auto can contain anything, but you would probably want stuff like value=77. A couple of points:

Dereference value using nmake syntax ($(value))

You can pass parameters to batch.cmd if necessary ([batch.cmd $(OBJECTS) >makefile.auto])


问:
Finding three numbers whose sum is divisible by a given number
How can I search through an array and find every combination of three values whose sum is divisible by a given number(x) in java.

In other words, every combination where (n1+n2+n3) % x == 0.

I know this would be a simple solution using a triple for loop but I need something with a time complexity of O(N^2).

Any idea's?

答:
1 - Hash every (element % x) in the list.

2 - Sum every pair of elements in the list (lets call the sum y) and do modded_y = y % x.

3 - Check if x - modded_y is in the hash table. If it is and it's not one of the other 2 numbers then you found a possible combination. Keep iterating and hashing the combinations you found so that they don't repeat.

This is called a meet in the middle strategy.

It's complexity is O(n + (n^2 * 1)) = O(n^2)


问:
Cats - how to use for-comprehension when `Monad` instance in scope?
How can I use for-comprehension on type M in the method below?

```<code>def foo[M[_]: Monad](m1: M[Int], m2: M[Int]) =
  for {
     a <- m1
     b <- m2
  } yield (a + b)
</code>```

I'll get a

```<code>value flatMap is not a member of type parameter M[Int]
</code>```

I can make it work by defining the flatMap and map methods like so:

```<code>implicit class MOps[A](m: M[A])(implicit monad: Monad[M]) {
  def flatMap[B](f: A => M[B]): M[B] = monad.flatMap(m)(f)
  def map[B](f: A => B): M[B]        = monad.map(m)(f)
}
</code>```

But surely there must be a way for Cats to provide these methods?

答:
Try:</p>

```<code>import cats.syntax.functor._, cats.syntax.flatMap._
</code>```

Body:
How can I use for-comprehension on type M in the method below?

def foo[M[_]: Monad](m1: M[Int], m2: M[Int]) =
  for {
     a <- m1
     b <- m2
  } yield (a + b)

I'll get a

value flatMap is not a member of type parameter M[Int]

I can make it work by defining the flatMap and map methods like so:

implicit class MOps[A](m: M[A])(implicit monad: Monad[M]) {
  def flatMap[B](f: A => M[B]): M[B] = monad.flatMap(m)(f)
  def map[B](f: A => B): M[B]        = monad.map(m)(f)
}

But surely there must be a way for Cats to provide these methods?

Body:
Try:

import cats.syntax.functor._, cats.syntax.flatMap._


答:
This is intended to get you started. The core of your need comes from 2 tables employee (for job_id) and department (for location_id) and the relationship between employee and department is via the shared department_id column (this becomes the join)

```<code>SELECT
      e.JOB_ID
    , d.LOCATION_ID
FROM Employees e
INNER JOIN Departments d ON e.DEPARTMENT_ID = d.DEPARTMENT_ID
WHERE e.DEPARTMENT_ID = 80
</code>```

Now you need to figure how to get the "uniqueness"

One way is to add select distinct and while this will work, it does limit your options

```<code>SELECT DISTINCT
      e.JOB_ID
    , d.LOCATION_ID
FROM Employees e
INNER JOIN Departments d ON e.DEPARTMENT_ID = d.DEPARTMENT_ID
WHERE e.DEPARTMENT_ID = 80
</code>```

OR, to use GROUP BY which open up other possibilities such as aggregations

```<code>SELECT
      e.JOB_ID
    , d.LOCATION_ID
    , COUNT(*) as count_of_employees
FROM Employees e
INNER JOIN Departments d ON e.DEPARTMENT_ID = d.DEPARTMENT_ID
WHERE e.DEPARTMENT_ID = 80
GROUP BY
      e.JOB_ID
    , d.LOCATION_ID
</code>```

What I leave for you to discover is how to bring the names into the result.

Title: JOIN or Conditional Logic Between 4+ Tables

Body:
Full disclosure, this is a homework question, but I have 20 more of these that are much more difficult, I just really can't wrap my head around some of the more complicated statements, so I'd appreciate the help before I just give up on the assignment completely. The professor and TA declined any help.

I'm using the 'HR' table that is present as a demo in all Oracle DBs. I need to create a unique listing of all jobs in a particular department along with the locations. It has the tables: REGIONS, LOCATIONS, DEPARTMENTS, JOBS, and EMPLOYEES of the form described below:

Locations:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 LOCATION_ID                   NOT NULL NUMBER(4)
 STREET_ADDRESS                     VARCHAR2(40)
 POSTAL_CODE                        VARCHAR2(12)
 CITY                      NOT NULL VARCHAR2(30)
 STATE_PROVINCE                     VARCHAR2(25)
 COUNTRY_ID                     CHAR(2)

Jobs:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 JOB_ID                    NOT NULL VARCHAR2(10)
 JOB_TITLE                 NOT NULL VARCHAR2(35)
 MIN_SALARY                     NUMBER(6)
 MAX_SALARY                     NUMBER(6)

Employees:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EMPLOYEE_ID                   NOT NULL NUMBER(6)
 FIRST_NAME                     VARCHAR2(20)
 LAST_NAME                 NOT NULL VARCHAR2(25)
 EMAIL                     NOT NULL VARCHAR2(25)
 PHONE_NUMBER                       VARCHAR2(20)
 HIRE_DATE                 NOT NULL DATE
 JOB_ID                    NOT NULL VARCHAR2(10)
 SALARY                         NUMBER(8,2)
 COMMISSION_PCT                     NUMBER(2,2)
 MANAGER_ID                     NUMBER(6)
 DEPARTMENT_ID                      NUMBER(4)

Departments:

 Name                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 DEPARTMENT_ID                 NOT NULL NUMBER(4)
 DEPARTMENT_NAME               NOT NULL VARCHAR2(30)
 MANAGER_ID                     NUMBER(6)
 LOCATION_ID                        NUMBER(4)

So of course I can think through how the relational algebra kind of goes, but I have no clue how it would go in SQL syntax. I of course know how to do more trivial joins, but I'm not understanding how to agregate all of the requirements into one statement. I want to get all UNIQUE or DISTINCT JOB_IDs where DEPARTMENT_ID=80,Then do a join on Jobs to get the matching JOB_TITLE,then derive LOCATION_ID from DEPARTMENTS.DEPARTMENT_ID and finally join Locations to my original JOB_TITLE selection WHERE LOCATION.LOCATION_ID=DEPARTMENTS.DEPARTMENT_ID. So what does that look like. Do I have to do 3 joins to get all the information in one selection?

Body:
This is intended to get you started. The core of your need comes from 2 tables employee (for job_id) and department (for location_id) and the relationship between employee and department is via the shared department_id column (this becomes the join)

SELECT
      e.JOB_ID
    , d.LOCATION_ID
FROM Employees e
INNER JOIN Departments d ON e.DEPARTMENT_ID = d.DEPARTMENT_ID
WHERE e.DEPARTMENT_ID = 80

Now you need to figure how to get the "uniqueness"

One way is to add select distinct and while this will work, it does limit your options

SELECT DISTINCT
      e.JOB_ID
    , d.LOCATION_ID
FROM Employees e
INNER JOIN Departments d ON e.DEPARTMENT_ID = d.DEPARTMENT_ID
WHERE e.DEPARTMENT_ID = 80

OR, to use GROUP BY which open up other possibilities such as aggregations

SELECT
      e.JOB_ID
    , d.LOCATION_ID
    , COUNT(*) as count_of_employees
FROM Employees e
INNER JOIN Departments d ON e.DEPARTMENT_ID = d.DEPARTMENT_ID
WHERE e.DEPARTMENT_ID = 80
GROUP BY
      e.JOB_ID
    , d.LOCATION_ID

What I leave for you to discover is how to bring the names into the result.


问:
Loops for assigning/calculating student grade (c++)
I'm sort of having a hard time with my program, and I would really appreciate any help. Forgive me for my really bad code, I'm new.

```<code>#include <iostream>
#include <string.h>

using namespace std;
//functions
string getFirstName();
string getLastName();
int getScores();
double calculateSum(double sum, double score);
double calculateAvg(double avg, double sum);
char calculateGrade(double score, char grade);
void displayResults(string firstname, string lastname, double avg, char
grade);

int main(){
//variables
string firstname;
string lastname;
int score;
double sum;
double avg;
char grade;
//functions and parameters
firstname = getFirstName();
lastname = getLastName();
score = getScores();
sum = calculateSum(sum, score);
avg = calculateAvg(avg, sum);
grade = calculateGrade(score, grade);
displayResults(firstname,lastname,avg,grade);

while (true)
{
firstname = getFirstName();
cin >> firstname;
if (firstname == "done")break;
lastname = getLastName();
cin >> lastname;
sum=0.0;

  for (int i = 0; i<10; i++)
    {
        double score;
     cin >> score;
     sum - calculateSum(sum, score);
      sum+=score;
      //sum = sum+score;
    }
     avg = calculateAvg(avg, sum);
  avg = sum/10.0;
    displayResults(firstname,lastname,avg,grade);
 }
return 0;
}

string getFirstName()
{
string firstname;
cout<<"Enter first name: " << endl;
cin >>firstname;
return firstname;
}

string getLastName()
{
string lastname;
cout<<"Enter last name: ";
cin >>lastname;
return lastname;
}

int getScores()
{
int score;
cout <<"Input score: ";
cin >>score;
return score;
}

double calculateSum(double sum, double score)
{
sum+=score;
return sum;
}

double calculateAvg(double avg, double sum)
{
avg = sum/10.0;
return avg;
}

char calculateGrade(double score, char grade)
{

if (score >= 90)
grade = 'A';
else if (score >=80)
grade = 'B';
else if (score >=70)
grade = 'C';
else if (score >=60)
grade = 'D';
else
grade = 'F';
return grade;
}

void displayResults(string firstname, string lastname, double avg, char
grade)
{
cout<<firstname<< lastname<<": "<<avg << grade;
}
</code>```

I don't really understand loops, or how they work, so what I have written down for my loop was just given to us by our professor, so if anyone could please explain/dissect it then I would really appreciate it! I want to know how to do this, not just have answers handed to me.

So, I'm not sure why my program won't properly execute. I've listed the call functions and all of the functions seem to be correct. My loops are inside of the main as well, but I don't know why they're not working. Also, when I run it, I don't have any errors.

It seems to be stuck on the enter first name and enter last name part, but I'm not sure why.Again, I'd really appreciate any help, thank you!

答:
The loop is just a way of executing the same piece of code over and over again. By putting code in a loop, you do not have to copy and paste it. Any variable changes which happen during one run through a loop are still present during the next.

In your code:

```<code>for (int i = 0; i<10; i++)
{
   ...
}
</code>```

is your loop. The "..." is code which will be executed over and over.

The big question which needs to be asked with a loop is: How does a loop know how many times to run your code before it exits?

This is what the:

```<code>int i = 0; i<10; i++
</code>```

is about. Though it looks strange it is actually 3 separate commands. The commands are separated by the semi-colon ';'

int i=0

i<10

i++

Command (1) initialize the loop. You are simply setting the variable i, which an integer, to 0.

Command (2) condition to continue looping. If command (2) is true then the loop will execute (and execute again). Your code is saying execute the loop whilst i is less than 10.

Command (3) calculations executed once per loop. We know in Command (1) that you set i to 0. We know in Command (2) that the loop will run while i is less than 10. 0 is less than 10, so the loop will execute... forever. We don't want this, so during Command (3) we increase i. We count the number of times we run the loop.

So your loop will run 10 times in a row, the code inside it and then exit.

Body:
I'm sort of having a hard time with my program, and I would really appreciate any help. Forgive me for my really bad code, I'm new.

#include <iostream>
#include <string.h>

using namespace std;
//functions
string getFirstName();
string getLastName();
int getScores();
double calculateSum(double sum, double score);
double calculateAvg(double avg, double sum);
char calculateGrade(double score, char grade);
void displayResults(string firstname, string lastname, double avg, char
grade);

int main(){
//variables
string firstname;
string lastname;
int score;
double sum;
double avg;
char grade;
//functions and parameters
firstname = getFirstName();
lastname = getLastName();
score = getScores();
sum = calculateSum(sum, score);
avg = calculateAvg(avg, sum);
grade = calculateGrade(score, grade);
displayResults(firstname,lastname,avg,grade);

while (true)
{
firstname = getFirstName();
cin >> firstname;
if (firstname == "done")break;
lastname = getLastName();
cin >> lastname;
sum=0.0;

  for (int i = 0; i<10; i++)
    {
        double score;
     cin >> score;
     sum - calculateSum(sum, score);
      sum+=score;
      //sum = sum+score;
    }
     avg = calculateAvg(avg, sum);
  avg = sum/10.0;
    displayResults(firstname,lastname,avg,grade);
 }
return 0;
}

string getFirstName()
{
string firstname;
cout<<"Enter first name: " << endl;
cin >>firstname;
return firstname;
}

string getLastName()
{
string lastname;
cout<<"Enter last name: ";
cin >>lastname;
return lastname;
}

int getScores()
{
int score;
cout <<"Input score: ";
cin >>score;
return score;
}

double calculateSum(double sum, double score)
{
sum+=score;
return sum;
}

double calculateAvg(double avg, double sum)
{
avg = sum/10.0;
return avg;
}

char calculateGrade(double score, char grade)
{

if (score >= 90)
grade = 'A';
else if (score >=80)
grade = 'B';
else if (score >=70)
grade = 'C';
else if (score >=60)
grade = 'D';
else
grade = 'F';
return grade;
}

void displayResults(string firstname, string lastname, double avg, char
grade)
{
cout<<firstname<< lastname<<": "<<avg << grade;
}

I don't really understand loops, or how they work, so what I have written down for my loop was just given to us by our professor, so if anyone could please explain/dissect it then I would really appreciate it! I want to know how to do this, not just have answers handed to me.

So, I'm not sure why my program won't properly execute. I've listed the call functions and all of the functions seem to be correct. My loops are inside of the main as well, but I don't know why they're not working. Also, when I run it, I don't have any errors.

It seems to be stuck on the enter first name and enter last name part, but I'm not sure why.Again, I'd really appreciate any help, thank you!

Body:
The loop is just a way of executing the same piece of code over and over again. By putting code in a loop, you do not have to copy and paste it. Any variable changes which happen during one run through a loop are still present during the next.

In your code:

for (int i = 0; i<10; i++)
{
   ...
}

is your loop. The "..." is code which will be executed over and over.

The big question which needs to be asked with a loop is: How does a loop know how many times to run your code before it exits?

This is what the:

int i = 0; i<10; i++

is about. Though it looks strange it is actually 3 separate commands. The commands are separated by the semi-colon ';'

int i=0

i<10

i++

Command (1) initialize the loop. You are simply setting the variable i, which an integer, to 0.

Command (2) condition to continue looping. If command (2) is true then the loop will execute (and execute again). Your code is saying execute the loop whilst i is less than 10.

Command (3) calculations executed once per loop. We know in Command (1) that you set i to 0. We know in Command (2) that the loop will run while i is less than 10. 0 is less than 10, so the loop will execute... forever. We don't want this, so during Command (3) we increase i. We count the number of times we run the loop.

So your loop will run 10 times in a row, the code inside it and then exit.


问:
can't get form to remain on top, in .net
I can't get a form to remain on top, in .net

I have checked  How to make form always on top in Application   and the  answer there mentions form1.TopLevel = true;  and I've checked How to make a window always stay on top in .Net?  and it says Form.ActiveForm.TopMost so i've tried Form.ActiveForm.TopMost = true; and this.TopMost = true;

```<code>private void Form1_Load(object sender, EventArgs e)
{
  this.TopLevel = true; //default anyway

  Form.ActiveForm.TopMost = true;
  this.TopMost = true;
}
</code>```

But as you can see, a notepad window or any window can cover it.

Added

I have tried every suggestion made so far.

In response to Han's advice, "Of all the possible places to set TopMost property, the Load event is the worst. It should be set in the constructor, so the window gets created top-most right away. Or it should be set after it is visible, so after the Load event. Use the constructor. ".  I tried putting those lines in the constructor.

```<code>    public Form1()
    {
        InitializeComponent();
        this.TopLevel = true; //default anyway

        //Form.ActiveForm.TopMost = true; (commented to prevent a System.InvalidOperationException, presumably the form isn't yet active at this stage)
        this.TopMost = true;
    }
</code>```

And the the other two suggestions, from others-

I tried setting the Form's TopMost field in the designer to True.

And running the EXE directly rather than just clicking play in visual studio.

Same issue.

And if you find that hard to believe, i've taken a 1min video here showing just that.  https://screencast-o-matic.com/watch/cbXXrw2oTN

A potentially useful comment was mentioned..

Steve comments - "OK something definitively odd is happening here. I have tried to create a simple topmost form using linqpad and at the first run I get your same behavior. At the second run though everything works as expected."

答:
A workaround, is this,  following on from Han's point to put not put it in Load. Load is indeed too early. I've been finding that (at least on the system with the issue), The Constructor is also too early.  I find that putting it in the Shown event, works.

One possible solution to this, is to run this patch, https://support.microsoft.com/en-us/help/2587473/topmost-windows-are-not-always-in-the-topmost-position-in-windows-7-or  But be warned,  if you want to uninstall it, I have some doubts whether it uninstalls correctly.  And it's also not clear to me whether the patch is working or working sporadically.  It likely works but it's hard for me to tell.

One commenter thought it's just my system, though that's not the case, as Steve ran into the same issue the first time he ran it.  I find it may be most prone to happen after windows restarts, So, the program is running very fresh.  But I find that putting that code in the Shown event, is fine and the form stays on top.

I tried instead of TopMost=true,  using SetWindowPos, to set the window on top, I tried it fairly early like in the constructor,  and late, like in the Shown event or on a button click, and I found it was fine in the Shown event or on a button click. So the issue was related to the TopMost=true line, or SetWindowPos line, firing too early, prior to the window it is setting appearing.

When calling SetWindowPos later one can use either this.Handle or GetForegroundWindow(), the former is easier as it's native.  When calling it earlier one must use this.Handle.  And using this.TopMost=true avoids all winAPI calls completely.

So in short, you could try the patch, though note that it might not uninstall right.. Or you can try the workaround of putting this.TopMost=true in the Shown event of the form.

Body:
I can't get a form to remain on top, in .net

I have checked  How to make form always on top in Application   and the  answer there mentions form1.TopLevel = true;  and I've checked How to make a window always stay on top in .Net?  and it says Form.ActiveForm.TopMost so i've tried Form.ActiveForm.TopMost = true; and this.TopMost = true;

private void Form1_Load(object sender, EventArgs e)
{
  this.TopLevel = true; //default anyway

  Form.ActiveForm.TopMost = true;
  this.TopMost = true;
}

But as you can see, a notepad window or any window can cover it.

Added

I have tried every suggestion made so far.

In response to Han's advice, "Of all the possible places to set TopMost property, the Load event is the worst. It should be set in the constructor, so the window gets created top-most right away. Or it should be set after it is visible, so after the Load event. Use the constructor. ".  I tried putting those lines in the constructor.

    public Form1()
    {
        InitializeComponent();
        this.TopLevel = true; //default anyway

        //Form.ActiveForm.TopMost = true; (commented to prevent a System.InvalidOperationException, presumably the form isn't yet active at this stage)
        this.TopMost = true;
    }

And the the other two suggestions, from others-

I tried setting the Form's TopMost field in the designer to True.

And running the EXE directly rather than just clicking play in visual studio.

Same issue.

And if you find that hard to believe, i've taken a 1min video here showing just that.  https://screencast-o-matic.com/watch/cbXXrw2oTN

A potentially useful comment was mentioned..

Steve comments - "OK something definitively odd is happening here. I have tried to create a simple topmost form using linqpad and at the first run I get your same behavior. At the second run though everything works as expected."


问:
MySQL order by launch date within 3 months from now first, then launch date desc
I have got a table like the following. The select order needs to show closest launch date from now first(it is more urgent), then launch date desc. Say current date is 17-11-2017

tblProduct

01-02-2016
09-05-2015
03-11-2017
30-11-2017
02-01-2018
09-06-2018```
</div>
</div>
</p>

<p>The output order should be</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>30-11-2017
02-01-2018
09-06-2018
03-11-2017
09-05-2015
01-02-2016</code>```

The top 2 are within 3 months from now, so are shown first(between the 2 results, 30-11-2017 is closer from now so shown first).

What's the mysql query?

答:
I'm sure not the most elegant way, but this could help you

http://sqlfiddle.com/#!9/2a6eca/1

```<code>SELECT *, IF(mydate BETWEEN NOW() AND DATE_ADD( NOW() , INTERVAL +3 MONTH) , 1, 0) as `dateInRange`
FROM `demo`
ORDER BY  `dateInRange` DESC,
     CASE WHEN `dateInRange` = 1 THEN `mydate` END ASC,
     CASE WHEN `dateInRange` = 0 THEN `mydate` END DESC
</code>```

What this does is adds another column dateInRange to the selection (and sets it to 1 if date is between now and 3 monts from now.

Then in the order by part we first sort by this column (making sure all the dates that are in the 3 months range are on the top), and when this column is equal to 0, then we sort by the actual date ascending. If this column is 0 we sort by dates descending.
This code does what you would like, but there must be a more elegant way to go about this.

Body:
I have got a table like the following. The select order needs to show closest launch date from now first(it is more urgent), then launch date desc. Say current date is 17-11-2017

tblProduct

01-02-2016
09-05-2015
03-11-2017
30-11-2017
02-01-2018
09-06-2018

The output order should be

30-11-2017
02-01-2018
09-06-2018
03-11-2017
09-05-2015
01-02-2016

The top 2 are within 3 months from now, so are shown first(between the 2 results, 30-11-2017 is closer from now so shown first).

What's the mysql query?

Body:
I'm sure not the most elegant way, but this could help you

http://sqlfiddle.com/#!9/2a6eca/1

SELECT *, IF(mydate BETWEEN NOW() AND DATE_ADD( NOW() , INTERVAL +3 MONTH) , 1, 0) as `dateInRange`
FROM `demo`
ORDER BY  `dateInRange` DESC,
     CASE WHEN `dateInRange` = 1 THEN `mydate` END ASC,
     CASE WHEN `dateInRange` = 0 THEN `mydate` END DESC

What this does is adds another column dateInRange to the selection (and sets it to 1 if date is between now and 3 monts from now.

Then in the order by part we first sort by this column (making sure all the dates that are in the 3 months range are on the top), and when this column is equal to 0, then we sort by the actual date ascending. If this column is 0 we sort by dates descending.
This code does what you would like, but there must be a more elegant way to go about this.


问:
Angular - Change css using ng-style
I am trying to change top position of a DIV on Scroll event -

In controller i have-

```<code>    angular.element($window).on("scroll", function(e) {
        vm.scrollTop = angular.element($window).scrollTop()+'px';
        console.log(vm.scrollTop);
    });
</code>```

In html -

```<code><div ng-style="{'top': vm.scrollTop}">
    Hello World
</div>
</code>```

On scroll event is printing scrollTop values in console but "Div" style never gets updated.

Please correct me if this is syntactically incorrect.

答: You need to call $scope.$apply(); after setting vm.scrollTop because the event handler is executing outside of angular's awareness.

Title: Angular - Change css using ng-style

Body:
I am trying to change top position of a DIV on Scroll event -

In controller i have-

    angular.element($window).on("scroll", function(e) {
        vm.scrollTop = angular.element($window).scrollTop()+'px';
        console.log(vm.scrollTop);
    });

In html -

    Hello World

On scroll event is printing scrollTop values in console but "Div" style never gets updated.

Please correct me if this is syntactically incorrect.


问:
Pytorch AssertionError: Torch not compiled with CUDA enabled
I am trying to run code from this repo. I have disabled cuda by changing lines 39/40 in main.py from

```<code>parser.add_argument('--type', default='torch.cuda.FloatTensor', help='type of tensor - e.g torch.cuda.HalfTensor')
</code>```

to

```<code>parser.add_argument('--type', default='torch.FloatTensor', help='type of tensor - e.g torch.HalfTensor')
</code>```

Despite this, running the code gives me the following exception:

```<code>Traceback (most recent call last):
  File "main.py", line 190, in <module>
    main()
  File "main.py", line 178, in main
    model, train_data, training=True, optimizer=optimizer)
  File "main.py", line 135, in forward
    for i, (imgs, (captions, lengths)) in enumerate(data):
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 201, in __next__
    return self._process_next_batch(batch)
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 221, in _process_next_batch
    raise batch.exc_type(batch.exc_msg)
AssertionError: Traceback (most recent call last):
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 62, in _pin_memory_loop
    batch = pin_memory_batch(batch)
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 123, in pin_memory_batch
    return [pin_memory_batch(sample) for sample in batch]
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 123, in <listcomp>
    return [pin_memory_batch(sample) for sample in batch]
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 117, in pin_memory_batch
    return batch.pin_memory()
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/tensor.py", line 82, in pin_memory
    return type(self)().set_(storage.pin_memory()).view_as(self)
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/storage.py", line 83, in pin_memory
    allocator = torch.cuda._host_allocator()
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/cuda/__init__.py", line 220, in _host_allocator
    _lazy_init()
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/cuda/__init__.py", line 84, in _lazy_init
    _check_driver()
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/cuda/__init__.py", line 51, in _check_driver
    raise AssertionError("Torch not compiled with CUDA enabled")
AssertionError: Torch not compiled with CUDA enabled
</code>```

Spent some time looking through the issues in the Pytorch github, to no avail. Help, please?

答:
If you look into the data.py file, you can see the function:

```<code>def get_iterator(data, batch_size=32, max_length=30, shuffle=True, num_workers=4, pin_memory=True):
    cap, vocab = data
    return torch.utils.data.DataLoader(
        cap,
        batch_size=batch_size, shuffle=shuffle,
        collate_fn=create_batches(vocab, max_length),
        num_workers=num_workers, pin_memory=pin_memory)
</code>```

which is called twice in main.py file to get an iterator for the train and dev data. If you see the DataLoader class in pytorch, there is a parameter called:

pin_memory (bool, optional) – If True, the data loader will copy tensors into CUDA pinned memory before returning them.

which is by default True in the get_iterator function. And as a result you are getting this error. You can simply pass the pin_memory param value as False when you are calling get_iterator function as follows.

```<code>train_data = get_iterator(get_coco_data(vocab, train=True),
                          batch_size=args.batch_size,
                          ...,
                          ...,
                          ...,
                          pin_memory=False)
</code>```

Body:
I am trying to run code from this repo. I have disabled cuda by changing lines 39/40 in main.py from

parser.add_argument('--type', default='torch.cuda.FloatTensor', help='type of tensor - e.g torch.cuda.HalfTensor')

to

parser.add_argument('--type', default='torch.FloatTensor', help='type of tensor - e.g torch.HalfTensor')

Despite this, running the code gives me the following exception:

Traceback (most recent call last):
  File "main.py", line 190, in <module>
    main()
  File "main.py", line 178, in main
    model, train_data, training=True, optimizer=optimizer)
  File "main.py", line 135, in forward
    for i, (imgs, (captions, lengths)) in enumerate(data):
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 201, in __next__
    return self._process_next_batch(batch)
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 221, in _process_next_batch
    raise batch.exc_type(batch.exc_msg)
AssertionError: Traceback (most recent call last):
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 62, in _pin_memory_loop
    batch = pin_memory_batch(batch)
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 123, in pin_memory_batch
    return [pin_memory_batch(sample) for sample in batch]
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 123, in <listcomp>
    return [pin_memory_batch(sample) for sample in batch]
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 117, in pin_memory_batch
    return batch.pin_memory()
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/tensor.py", line 82, in pin_memory
    return type(self)().set_(storage.pin_memory()).view_as(self)
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/storage.py", line 83, in pin_memory
    allocator = torch.cuda._host_allocator()
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/cuda/__init__.py", line 220, in _host_allocator
    _lazy_init()
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/cuda/__init__.py", line 84, in _lazy_init
    _check_driver()
  File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/cuda/__init__.py", line 51, in _check_driver
    raise AssertionError("Torch not compiled with CUDA enabled")
AssertionError: Torch not compiled with CUDA enabled

Spent some time looking through the issues in the Pytorch github, to no avail. Help, please?

Body:
If you look into the data.py file, you can see the function:

def get_iterator(data, batch_size=32, max_length=30, shuffle=True, num_workers=4, pin_memory=True):
    cap, vocab = data
    return torch.utils.data.DataLoader(
        cap,
        batch_size=batch_size, shuffle=shuffle,
        collate_fn=create_batches(vocab, max_length),
        num_workers=num_workers, pin_memory=pin_memory)

which is called twice in main.py file to get an iterator for the train and dev data. If you see the DataLoader class in pytorch, there is a parameter called:

pin_memory (bool, optional) – If True, the data loader will copy tensors into CUDA pinned memory before returning them.

which is by default True in the get_iterator function. And as a result you are getting this error. You can simply pass the pin_memory param value as False when you are calling get_iterator function as follows.

train_data = get_iterator(get_coco_data(vocab, train=True),
                          batch_size=args.batch_size,
                          ...,
                          ...,
                          ...,
                          pin_memory=False)


问:
div height calc(100% - 50px) not working
https://codepen.io/joshuajazleung/pen/EbbgBN

```<code><div class="outer">
  <div class="inner">
    <img src="https://placehold.it/300x200" alt="">
    <div>Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio animi harum impedit ex esse labore, placeat, tempore sapiente nisi cupiditate fugiat soluta ullam dicta ducimus accusamus tenetur consequuntur nesciunt earum!</div>
  </div>
</div>

.outer {
  background: red;
  position: relative;
  height: calc(100% - 60px);
}

.inner {
  position: relative;
  top: -100px;
}
</code>```

since .inner is moved to top a little bit, to reduce .outer overall space, I use

```<code>height: calc(100% - 50px); // my logic is that it's div's height minus 50px
</code>```

But it's not working, wondering why?

答:
This won't work because the html and body elements don't span the full height by default. You're then setting a height: calc(100% - 50px); of something inside of that... To simplify it, just set height: 100% and you'll notice it isn't doing what you want.

You could set the height on the body and html to 100% as well, or you could try using 100vh instead of 100%.

Body:
https://codepen.io/joshuajazleung/pen/EbbgBN

Lorem ipsum dolor sit amet consectetur adipisicing elit. Optio animi harum impedit ex esse labore, placeat, tempore sapiente nisi cupiditate fugiat soluta ullam dicta ducimus accusamus tenetur consequuntur nesciunt earum!

.outer {
  background: red;
  position: relative;
  height: calc(100% - 60px);
}

.inner {
  position: relative;
  top: -100px;
}

since .inner is moved to top a little bit, to reduce .outer overall space, I use

height: calc(100% - 50px); // my logic is that it's div's height minus 50px

But it's not working, wondering why?


问:
How can I union or combine some columns and not others using sql
I have the following separate reports that I have a request to combine:

```<code>--REPORT #1
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate  between '01-NOV-2017' and '17-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #2
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate  between '01-OCT-2017' and '01-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #3
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate >='01-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #4
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate is null
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)
</code>```

I need to combine these reports so they can be run as one query. The issue I am running into is that the quantity column needs to be separate for each of the reports and using UNION combines them. Each separate Report may not have any results in common so a join doesn't work. So the end result would be something like:

orderid, orderdate, shippeddate, itemcode, itemdescription, QuanitityA, QuantityB, QuantityC, QuantityD

答:
```<code>IS this what you want?
    select o.orderid
    , o.orderdate
    , o.shippeddate
    , od.itemcode
    , od.itemdescription
    , od.quantity AS QuantityA
    , NULL AS QuantityB
    , NULL AS QuantityC
    , NULL AS QuantityD
    from orders o
    join orderdetails od on od.orderid=o.orderid
    where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
    and o.shippeddate  between '01-NOV-2017' and '17-NOV-2017'
    and o.warehouseid=1
    and o.ordertypeid not in (7,8)
    and o.orderstatusid in (7,8,9)
    UNION
    select o.orderid
    , o.orderdate
    , o.shippeddate
    , od.itemcode
    , od.itemdescription
    , NULL AS QuantityA
    , od.quantity AS QuantityB
    , NULL AS QuantityC
    , NULL AS QuantityD
    from orders o
    join orderdetails od on od.orderid=o.orderid
    where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
    and o.shippeddate  between '01-OCT-2017' and '01-NOV-2017'
    and o.warehouseid=1
    and o.ordertypeid not in (7,8)
    and o.orderstatusid in (7,8,9)
    UNION
    select o.orderid
    , o.orderdate
    , o.shippeddate
    , od.itemcode
    , od.itemdescription
    , NULL AS QuantityA
    , NULL AS QuantityB
    , od.quantity AS QuantityC
    , NULL AS QuantityD
    from orders o
    join orderdetails od on od.orderid=o.orderid
    where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
    and o.shippeddate >='01-NOV-2017'
    and o.warehouseid=1
    and o.ordertypeid not in (7,8)
    and o.orderstatusid in (7,8,9)
    UNION
    select o.orderid
    , o.orderdate
    , o.shippeddate
    , od.itemcode
    , od.itemdescription
    , NULL AS QuantityA
    , NULL AS QuantityB
    , NULL AS QuantityC
    , od.quantity AS QuantityD
    from orders o
    join orderdetails od on od.orderid=o.orderid
    where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
    and o.shippeddate is null
    and o.warehouseid=1
    and o.ordertypeid not in (7,8)
    and o.orderstatusid in (7,8,9)
</code>```

Body:
I have the following separate reports that I have a request to combine:

--REPORT #1
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate  between '01-NOV-2017' and '17-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #2
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate  between '01-OCT-2017' and '01-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #3
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate >='01-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #4
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate is null
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

I need to combine these reports so they can be run as one query. The issue I am running into is that the quantity column needs to be separate for each of the reports and using UNION combines them. Each separate Report may not have any results in common so a join doesn't work. So the end result would be something like:

orderid, orderdate, shippeddate, itemcode, itemdescription, QuanitityA, QuantityB, QuantityC, QuantityD