问:
Static files in ExpressJS cannot be loaded via Nginx
In short, Nginx and Node JS are both running on the same server 10.0.0.120. I can access a Node app via http://10.0.0.120:3000, all stylesheets are loaded properly.

I want the Node app to be accessed via 10.0.0.120/abc/ so I had the following Nginx setup in /etc/nginx/sites-available/default

```<code>location /abc/ {
  proxy_pass http://localhost:3000/;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
</code>```

}

Now that 10.0.0.120/abc/ can reach the Node app but returns without stylesheet loaded because the relative path maps into 10.0.0.120/stylesheets, which obviously does not exist.

On the NodeJS side, I simply used the Express template,in which public folder is used for serving static files.

```<code>app.use(express.static(path.join(__dirname, 'public')));
</code>```

The Node directory tree is shown below

```<code>Node App
|
|── public
|   ├── images
|   ├── javascripts
│   │   ├── bootstrap.js
│   │   ├── bootstrap.min.js
│   │   └── jquery.min.js
│   └── stylesheets
│       ├── animate.css
│       ├── bootstrap.css
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
</code>```

How should I change the Nginx setting to fix the issue?

答:
Exclude app.use(express.static(path.join(__dirname, 'public'))); from your code.

Configure nginx proxy (conf/nginx.conf file) similar below.

```<code>http {
...
  server {
    listen 2000;
    server_name localhost;
    root YOUR-APP-PATH/public;

    location / {
      try_files $uri @backend;
    }

    location @backend {
      proxy_pass http://localhost:3000;
    }
    ...
</code>```

Run application on 2000 port. Application with static files will be enable on 3000.

P.S. I'm a not nginx expert but it's work for me.

Body:
In short, Nginx and Node JS are both running on the same server 10.0.0.120. I can access a Node app via http://10.0.0.120:3000, all stylesheets are loaded properly.

I want the Node app to be accessed via 10.0.0.120/abc/ so I had the following Nginx setup in /etc/nginx/sites-available/default

location /abc/ {
  proxy_pass http://localhost:3000/;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

Now that 10.0.0.120/abc/ can reach the Node app but returns without stylesheet loaded because the relative path maps into 10.0.0.120/stylesheets, which obviously does not exist.

On the NodeJS side, I simply used the Express template,in which public folder is used for serving static files.

app.use(express.static(path.join(__dirname, 'public')));

The Node directory tree is shown below

Node App
|
|── public
|   ├── images
|   ├── javascripts
│   │   ├── bootstrap.js
│   │   ├── bootstrap.min.js
│   │   └── jquery.min.js
│   └── stylesheets
│       ├── animate.css
│       ├── bootstrap.css
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js

How should I change the Nginx setting to fix the issue?

Body:
Exclude app.use(express.static(path.join(__dirname, 'public'))); from your code.

Configure nginx proxy (conf/nginx.conf file) similar below.

http {
...
  server {
    listen 2000;
    server_name localhost;
    root YOUR-APP-PATH/public;

    location / {
      try_files $uri @backend;
    }

    location @backend {
      proxy_pass http://localhost:3000;
    }
    ...

Run application on 2000 port. Application with static files will be enable on 3000.

P.S. I'm a not nginx expert but it's work for me.


来源: stackexchange

问:
Flow of execution in word2vec tensorflow
From past few days, I have been trying to figure out the flow of execution in the code https://github.com/tensorflow/models/blob/master/tutorials/embedding/word2vec.py#L28  .

I understood the logic behind negative sampling and loss function, but I am getting so confused about the flow of execution inside the train function, especially when it comes to _train_thread_body function. I am so confused about the while and if loops ( what is the impact ) and the concurrency related parts. It would be great, if someone can give a decent explanation, before down-voting this.

答:
This sample code is called "Multi-threaded word2vec mini-batched skip-gram model", that's why it uses several independent threads for training. Word2Vec can be trained with a single thread as well, but this tutorial shows that word2vec is faster to compute when done in parallel.

The input, label and epoch tensors are provided by the native word2vec.skipgram_word2vec function, which is implemented in tutorials/embedding/word2vec_kernels.cc file. There you can see that current_epoch is a tensor updated once the whole corpus of sentences is processed.

The method you're asking about is actually pretty simple:

def _train_thread_body(self):
  initial_epoch, = self._session.run([self._epoch])
  while True:
    _, epoch = self._session.run([self._train, self._epoch])
    if epoch != initial_epoch:
      break
```

First, it computes the current epoch, then it invokes the training until the epoch is increased. This means that all of threads running this method will make exactly one epoch of training. Each thread is doing one step at a time in parallel with others.

self._train is an op that optimizes the loss function (see optimize method), which is computed from current examples and labels (see build_graph method). The exact value of these tensors is in native code again, namely in NextExample. Essentially, each call of word2vec.skipgram_word2vec extracts the set of examples and labels, which form the input to the optimization function. Hope, it makes it clearer now.

By the way, this model uses NCE loss in training, not negative sampling.

ContentLicense: CC BY-SA 3.0

Body:
This sample code is called "Multi-threaded word2vec mini-batched skip-gram model", that's why it uses several independent threads for training. Word2Vec can be trained with a single thread as well, but this tutorial shows that word2vec is faster to compute when done in parallel.

The input, label and epoch tensors are provided by the native word2vec.skipgram_word2vec function, which is implemented in tutorials/embedding/word2vec_kernels.cc file. There you can see that current_epoch is a tensor updated once the whole corpus of sentences is processed.

The method you're asking about is actually pretty simple:

def _train_thread_body(self):
  initial_epoch, = self._session.run([self._epoch])
  while True:
    _, epoch = self._session.run([self._train, self._epoch])
    if epoch != initial_epoch:
      break

First, it computes the current epoch, then it invokes the training until the epoch is increased. This means that all of threads running this method will make exactly one epoch of training. Each thread is doing one step at a time in parallel with others.

self._train is an op that optimizes the loss function (see optimize method), which is computed from current examples and labels (see build_graph method). The exact value of these tensors is in native code again, namely in NextExample. Essentially, each call of word2vec.skipgram_word2vec extracts the set of examples and labels, which form the input to the optimization function. Hope, it makes it clearer now.

By the way, this model uses NCE loss in training, not negative sampling.


问:
Rails: no block given (yield)
I'm getting in my rails app this error no block given (yield) and this is referred to this line in my file elements = Element.where(study_version_id: self.id).find_each I'm trying to export to an XML file some data which is generated in my app. When I try to export I have that error and I would like some help to resolve it.

The entire code related:

```<code>def to_xml
    # Build the document and the header elements
    odm_document = Odm.new("ODM-#{self.id}", "Assero", "Tourmalet", Version::VERSION)
    odm = odm_document.root
    study = odm.add_study("S-#{self.id}")
    global_variables = study.add_global_variables()
    global_variables.add_study_name("#{self.name}")
    global_variables.add_study_description("#{self.description}")
    global_variables.add_protocol_name("#{self.protocol_name}")
    metadata_version = study.add_metadata_version("MDV-#{self.id}", "Metadata for #{self.description}", "Study export.")
    protocol = metadata_version.add_protocol()
    # Get the set of visits, forms and elements.
    visits = Visit.where(study_version_id: self.id).order(ordinal: :asc)
    forms = Form.where(study_version_id: self.id).order(ordinal: :asc)
    elements = Element.where(study_version_id: self.id).find_each
    # Build the Protocol element.
    visits.each do |visit|
      protocol.add_study_event_ref("SE-#{visit.ordinal}", "#{visit.ordinal}", "Yes", "")
    end
    # Build the StudyEventDef elements
    visits.each do |visit|
      study_event_def = metadata_version.add_study_event_def("SE-#{visit.ordinal}", "#{visit.long_name}", "No", "Scheduled", "")
      elements = Element.where(study_version_id: self.id, visit_id: visit.id).find_each
      elements.each do |element|
        #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "Element=#{element.to_json}")
        form = Form.find(element.form_id)
        study_event_def.add_form_ref("#{form.form_id}", "#{form.ordinal}", "Yes", "")
      end
    end
    # Now the remainder of the metadata
    forms.each do |form|
      form_json = Mdr.form_to_hash(form.form_id, form.form_namespace)
      #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "JSON=#{form_json}")
      xml_node(form_json, metadata_version, nil)
    end
    return odm_document.to_xml
  end
</code>```

答:
You don't need to assign the query results to a local variable elements if you are using find_each.  Instead use a block (do |element| ... end)

```<code>Element.where(study_version_id: self.id, visit_id: visit.id).find_each do |element|
  #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "Element=#{element.to_json}")
  form = Form.find(element.form_id)
  study_event_def.add_form_ref("#{form.form_id}", "#{form.ordinal}", "Yes", "")
end
</code>```

Title: Rails: no block given (yield)

Body:
I'm getting in my rails app this error no block given (yield) and this is referred to this line in my file elements = Element.where(study_version_id: self.id).find_each I'm trying to export to an XML file some data which is generated in my app. When I try to export I have that error and I would like some help to resolve it.

The entire code related:

def to_xml
    # Build the document and the header elements
    odm_document = Odm.new("ODM-#{self.id}", "Assero", "Tourmalet", Version::VERSION)
    odm = odm_document.root
    study = odm.add_study("S-#{self.id}")
    global_variables = study.add_global_variables()
    global_variables.add_study_name("#{self.name}")
    global_variables.add_study_description("#{self.description}")
    global_variables.add_protocol_name("#{self.protocol_name}")
    metadata_version = study.add_metadata_version("MDV-#{self.id}", "Metadata for #{self.description}", "Study export.")
    protocol = metadata_version.add_protocol()
    # Get the set of visits, forms and elements.
    visits = Visit.where(study_version_id: self.id).order(ordinal: :asc)
    forms = Form.where(study_version_id: self.id).order(ordinal: :asc)
    elements = Element.where(study_version_id: self.id).find_each
    # Build the Protocol element.
    visits.each do |visit|
      protocol.add_study_event_ref("SE-#{visit.ordinal}", "#{visit.ordinal}", "Yes", "")
    end
    # Build the StudyEventDef elements
    visits.each do |visit|
      study_event_def = metadata_version.add_study_event_def("SE-#{visit.ordinal}", "#{visit.long_name}", "No", "Scheduled", "")
      elements = Element.where(study_version_id: self.id, visit_id: visit.id).find_each
      elements.each do |element|
        #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "Element=#{element.to_json}")
        form = Form.find(element.form_id)
        study_event_def.add_form_ref("#{form.form_id}", "#{form.ordinal}", "Yes", "")
      end
    end
    # Now the remainder of the metadata
    forms.each do |form|
      form_json = Mdr.form_to_hash(form.form_id, form.form_namespace)
      #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "JSON=#{form_json}")
      xml_node(form_json, metadata_version, nil)
    end
    return odm_document.to_xml
  end

Body:
You don't need to assign the query results to a local variable elements if you are using find_each.  Instead use a block (do |element| ... end)

Element.where(study_version_id: self.id, visit_id: visit.id).find_each do |element|
  #ConsoleLogger.log(C_CLASS_NAME, "to_xml", "Element=#{element.to_json}")
  form = Form.find(element.form_id)
  study_event_def.add_form_ref("#{form.form_id}", "#{form.ordinal}", "Yes", "")
end


问:
mysql. Stored Procedure Error 1328
This is really baffling me. I am converting a simple procedure from informix into mysql. What it basically does is tell me what the next event is from an event table and a calendar table. In informix the procedure is simple.

```<code>FOREACH
SELECT  date,weekno,event
INTO    l_date,l_week,l_event
FROM    event,calendar
WHERE   dayno = dayno
AND     date = l_today
AND     start >= l_now
UNION
SELECT  date,weekno,event
FROM    event,calendar
WHERE   dayno = dayno
AND     date > l_today
UNION
SELECT  TODAY,9999,9999
FROM    event,calendar
WHERE   dayno   = dayno
AND     event = (SELECT MAX(event) FROM event)
ORDER BY 3

if l_event = 9999 then <error> end if;
EXIT FOREACH
END FOREACH
</code>```

So basically the query finds the next event and returns it. l_today and l_event are parameters that are passed. So on to the mysql version.

```<code>looper: BEGIN
    DECLARE curs1 CURSOR FOR
        SELECT CONCAT("SELECT date, weekno, event FROM event INNER JOIN calendar ON dayno = dayno",
                " WHERE date = '", lv_today ,"' AND start >= '", lv_time ,"'",
                " UNION SELECT date, weekno, event FROM event INNER JOIN calendar ON dayno = dayno WHERE date > '", lv_today ,"'",
                " UNION SELECT DATE(NOW()) AS date, 9999 AS weekno, 9999 AS event FROM event INNER JOIN calendar ON dayno = dayno",
                " WHERE (SELECT MAX(event) FROM event) ORDER BY event ");

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := TRUE;

    OPEN curs1;
    loop1: LOOP
        FETCH curs1 INTO ldate, lweek, levent;
        SELECT ldate, lweek, levent;
        LEAVE looper;
    END LOOP loop1;
END;
</code>```

I haven't checked that the rest of the methodology works because I get this error:

Incorrect number of FETCH variables.

Does this mean that I have declare a different variable for each of the query returns? I am new to mysql. If this is the case what would be the best way to solve this conundrum? I have also changed to column and table names.

Many thanks

答:
```<code>looper: BEGIN
DECLARE curs1 CURSOR FOR
SELECT eve_date, dia_weekno, eve_event
FROM game_event
INNER JOIN stan_calendar ON eve_abs_dayno = dia_abs_dayno
WHERE eve_date = lv_today
AND eve_start >= lv_time
UNION
SELECT eve_date, dia_weekno, eve_event
FROM game_event
INNER JOIN stan_calendar ON eve_abs_dayno = dia_abs_dayno
WHERE eve_date > lv_today
UNION SELECT DATE(NOW()) AS eve_date, 9999 AS dia_weekno, 9999 AS eve_event
FROM game_event
INNER JOIN stan_calendar ON eve_abs_dayno = dia_abs_dayno
WHERE (SELECT MAX(eve_event) FROM game_event) ORDER BY eve_event;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := TRUE;

OPEN curs1;

curs_loop: LOOP
    FETCH curs1 INTO lv_date, lv_week, lv_event;

    SELECT lv_date, lv_week, lv_event;
    LEAVE looper;

    CLOSE curs1;
END LOOP curs_loop;
</code>```

Thank you for answering my question, I have put it back to how I thought it was... and it now works. Here is the loop in full.

Title: mysql. Stored Procedure Error 1328

Body:
This is really baffling me. I am converting a simple procedure from informix into mysql. What it basically does is tell me what the next event is from an event table and a calendar table. In informix the procedure is simple.

FOREACH
SELECT  date,weekno,event
INTO    l_date,l_week,l_event
FROM    event,calendar
WHERE   dayno = dayno
AND     date = l_today
AND     start >= l_now
UNION
SELECT  date,weekno,event
FROM    event,calendar
WHERE   dayno = dayno
AND     date > l_today
UNION
SELECT  TODAY,9999,9999
FROM    event,calendar
WHERE   dayno   = dayno
AND     event = (SELECT MAX(event) FROM event)
ORDER BY 3

if l_event = 9999 then <error> end if;
EXIT FOREACH
END FOREACH

So basically the query finds the next event and returns it. l_today and l_event are parameters that are passed. So on to the mysql version.

looper: BEGIN
    DECLARE curs1 CURSOR FOR
        SELECT CONCAT("SELECT date, weekno, event FROM event INNER JOIN calendar ON dayno = dayno",
                " WHERE date = '", lv_today ,"' AND start >= '", lv_time ,"'",
                " UNION SELECT date, weekno, event FROM event INNER JOIN calendar ON dayno = dayno WHERE date > '", lv_today ,"'",
                " UNION SELECT DATE(NOW()) AS date, 9999 AS weekno, 9999 AS event FROM event INNER JOIN calendar ON dayno = dayno",
                " WHERE (SELECT MAX(event) FROM event) ORDER BY event ");

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := TRUE;

    OPEN curs1;
    loop1: LOOP
        FETCH curs1 INTO ldate, lweek, levent;
        SELECT ldate, lweek, levent;
        LEAVE looper;
    END LOOP loop1;
END;

I haven't checked that the rest of the methodology works because I get this error:

Incorrect number of FETCH variables.

Does this mean that I have declare a different variable for each of the query returns? I am new to mysql. If this is the case what would be the best way to solve this conundrum? I have also changed to column and table names.

Many thanks

Body:
looper: BEGIN
DECLARE curs1 CURSOR FOR
SELECT eve_date, dia_weekno, eve_event
FROM game_event
INNER JOIN stan_calendar ON eve_abs_dayno = dia_abs_dayno
WHERE eve_date = lv_today
AND eve_start >= lv_time
UNION
SELECT eve_date, dia_weekno, eve_event
FROM game_event
INNER JOIN stan_calendar ON eve_abs_dayno = dia_abs_dayno
WHERE eve_date > lv_today
UNION SELECT DATE(NOW()) AS eve_date, 9999 AS dia_weekno, 9999 AS eve_event
FROM game_event
INNER JOIN stan_calendar ON eve_abs_dayno = dia_abs_dayno
WHERE (SELECT MAX(eve_event) FROM game_event) ORDER BY eve_event;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := TRUE;

OPEN curs1;

curs_loop: LOOP
    FETCH curs1 INTO lv_date, lv_week, lv_event;

    SELECT lv_date, lv_week, lv_event;
    LEAVE looper;

    CLOSE curs1;
END LOOP curs_loop;

Thank you for answering my question, I have put it back to how I thought it was... and it now works. Here is the loop in full.


问:
woo commerce new account registration
I have add the field on registration form for phone number

 Phone * <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="">
```
</div>
</div>
</p>

<p>Onece user register my website admin geting bellow email but they are missing phone number </p>

<p>Thanks for creating an account on our website . Your username is sales</p>

<p>Your password has been automatically generated: %6h51J$xFK)Z</p>

<p>Phone No:(i want print here phone number)</p>

<p>You can access your account area to view your orders and change your</p>

<p>Email Template:</p>

```if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

?>

<?php do_action( 'woocommerce_email_header', $email_heading, $email ); ?>

<?php printf( __( 'Thanks for creating an account on %1$s. Your username is %2$s', 'woocommerce' ), esc_html( $blogname ), '' . esc_html( $user_login ) . '' ); ?>

<?php if ( 'yes' === get_option( 'woocommerce_registration_generate_password' ) && $password_generated ) : ?>

<?php printf( __( 'Your password has been automatically generated: %s', 'woocommerce' ), '' . esc_html( $user_pass ) . '' ); ?>

Phone No:<?php echo get_user_meta( $customer_id, 'billing_phone', true ) ?>

<?php endif; ?>

<?php printf( __( 'You can access your account area to view your orders and change your password here: %s.', 'woocommerce' ), make_clickable( esc_url( wc_get_page_permalink( 'myaccount' ) ) ) ); ?>

<?php do_action( 'woocommerce_email_footer', $email );
```

答:
Make sure that $customer_id is set in the email template. If it's not set, you'll have to get the user in PHP so you can query user meta. This should work if $customer_id isn't available in the script.

```<code>if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

?>

$user = get_user_by('login', $user_login);

<?php do_action( 'woocommerce_email_header', $email_heading, $email ); ?>

<p><?php printf( __( 'Thanks for creating an account on %1$s. Your username is %2$s', 'woocommerce' ), esc_html( $blogname ), '<strong>' . esc_html( $user_login ) . '</strong>' ); ?></p>

<?php if ( 'yes' === get_option( 'woocommerce_registration_generate_password' ) && $password_generated ) : ?>

<p><?php printf( __( 'Your password has been automatically generated: %s', 'woocommerce' ), '<strong>' . esc_html( $user_pass ) . '</strong>' ); ?></p>
<p>Phone No:<?php echo get_user_meta( $user->ID, 'billing_phone', true ) ?></p>

<?php endif; ?>

<p><?php printf( __( 'You can access your account area to view your orders and change your password here: %s.', 'woocommerce' ), make_clickable( esc_url( wc_get_page_permalink( 'myaccount' ) ) ) ); ?></p>
</code>```

Title: woo commerce new account registration

Body:
I have add the field on registration form for phone number

 Phone * <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="">

Onece user register my website admin geting bellow email but they are missing phone number

Thanks for creating an account on our website . Your username is sales

Your password has been automatically generated: %6h51J$xFK)Z

Phone No:(i want print here phone number)

You can access your account area to view your orders and change your

Email Template:

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

?>

<?php do_action( 'woocommerce_email_header', $email_heading, $email ); ?>

<?php printf( __( 'Thanks for creating an account on %1$s. Your username is %2$s', 'woocommerce' ), esc_html( $blogname ), '' . esc_html( $user_login ) . '' ); ?>

<?php if ( 'yes' === get_option( 'woocommerce_registration_generate_password' ) && $password_generated ) : ?>

<?php printf( __( 'Your password has been automatically generated: %s', 'woocommerce' ), '' . esc_html( $user_pass ) . '' ); ?>

Phone No:<?php echo get_user_meta( $customer_id, 'billing_phone', true ) ?>

<?php endif; ?>

<?php printf( __( 'You can access your account area to view your orders and change your password here: %s.', 'woocommerce' ), make_clickable( esc_url( wc_get_page_permalink( 'myaccount' ) ) ) ); ?>

<?php do_action( 'woocommerce_email_footer', $email );

Body:
Make sure that $customer_id is set in the email template. If it's not set, you'll have to get the user in PHP so you can query user meta. This should work if $customer_id isn't available in the script.

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

?>

$user = get_user_by('login', $user_login);

<?php do_action( 'woocommerce_email_header', $email_heading, $email ); ?>

<p><?php printf( __( 'Thanks for creating an account on %1$s. Your username is %2$s', 'woocommerce' ), esc_html( $blogname ), '<strong>' . esc_html( $user_login ) . '</strong>' ); ?></p>

<?php if ( 'yes' === get_option( 'woocommerce_registration_generate_password' ) && $password_generated ) : ?>

<p><?php printf( __( 'Your password has been automatically generated: %s', 'woocommerce' ), '<strong>' . esc_html( $user_pass ) . '</strong>' ); ?></p>
<p>Phone No:<?php echo get_user_meta( $user->ID, 'billing_phone', true ) ?></p>

<?php endif; ?>

<p><?php printf( __( 'You can access your account area to view your orders and change your password here: %s.', 'woocommerce' ), make_clickable( esc_url( wc_get_page_permalink( 'myaccount' ) ) ) ); ?></p>


问:
What is the quickest path to writing a lightweight GUI program on Windows?
I want a small (< 30MB) standalone Windows executable (a single file) that creates a window which asks the user for the location of a directory and then launches a different program in that directory.

This executable has to run on XP, Vista, Server 2003, and Server 2008 versions of Windows in 32-bits and 64 bits on x86-64 architecture as well as Itanium chips.

It would be spectacular if we only had to build it once in order to run it on all these platforms, but that is not a requirement.  This is for a proprietary system, so GPL code is off-limits.

What is the fastest way to put this together?

These are some things I'm looking into, so if you have info about their viability, I'm all about it:

Perl/Tk using perl2exe to get the binary.

Ruby with wxruby

Learn MFC programming and do it the right way like everybody else.

答:
PyQt works really well for this. Binaries for Windows here:

http://www.riverbankcomputing.co.uk/software/pyqt/download

A good book here:

http://www.amazon.com/Programming-Python-Prentice-Software-Development/dp/0132354187/ref=sr_1_1?ie=UTF8&qid=1295369454&sr=8-1

And you can freeze these using various methods if you need exe(s).

OwnerDisplayName: Adrian Dunston

ContentLicense: CC BY-SA 2.5


问:
How to store the values in Office js for add ins?
I'm creating a word add-in using react js. </p>

<p>Currently, I'm using the browser local storage to store the values. Due to using local storage, the Word add-in is working as expected with Word Online but not with Word 2016. </p>

答:
Using the Office.js API, you can use the Settings object (Office.context.document.settings) to store data (as name/value pairs) in the host document. For details about how this works, see the documentation here:

https://dev.office.com/reference/add-ins/shared/settings

As the documentation indicates, the settings that you create/save using the Settings object are saved per add-in and per document.

Body:
I'm creating a word add-in using react js.

Currently, I'm using the browser local storage to store the values. Due to using local storage, the Word add-in is working as expected with Word Online but not with Word 2016.


问:
Laravel Queues Doc. - Passing an Eloquent Model
There is a statement I don't understand in Queues chapter of Laravel's 5.5 documentation. It says:

If your queued job accepts an Eloquent model in its constructor, only
  the identifier for the model will be serialized onto the queue.

I want to understand what this means. Thanks in advance.

答:
Well, you should read further:

When the job is actually handled, the queue system will automatically re-retrieve the full model instance from the database. It's all totally transparent to your application and prevents issues that can arise from serializing full Eloquent model instances.

what means that if you pass to Queue user with id 1 and something will be changed before executing job than when executing this job, those changes will be available because fresh model will be taken from database.


问:
Export UDO to XML on SAP B1
I want to export the UDOs and its predefined forms to XML on SAP B1 client.

Is it possible on SAP B1 client? How?

Thanks

答:
There is no way to do it through the SAP Business One Interface. You will have to use DI API.</p>

```<code>SAPbobsCOM.UserObjectsMD oUDO = (SAPbobsCOM.UserObjectsMD)SBOSharedConnection.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oUserObjectsMD);
oUDO.GetByKey(code);
oUDO.GetAsXML();
</code>```

Title: Export UDO to XML on SAP B1

Body:
There is no way to do it through the SAP Business One Interface. You will have to use DI API.

SAPbobsCOM.UserObjectsMD oUDO = (SAPbobsCOM.UserObjectsMD)SBOSharedConnection.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oUserObjectsMD);
oUDO.GetByKey(code);
oUDO.GetAsXML();


问:
Which of these pieces of code is faster in Java?
a) for(int i = 100000; i > 0; i--) {}

b) for(int i = 1; i < 100001; i++) {}

The answer is there on this website (question 3). I just can't figure out why? From website:

 3. a

答:
I decided to bite and necro back the thread.

both of the loops are ignored by the JVM as no-ops. so essentially even one of the loops were till 10 and the other till 10000000, there would have been no difference.

Looping back to zero is another thing (for jne instruction but again, it's not compiled like that), the linked site is plain weird (and wrong).

This type of a question doesn't fit any JVM (nor any other compiler that can optimize).


问:
How to compute in R the minimum number of observations to be removed to achieve complete separability between 2 groups
Problem: to compute in R the minimum number of observations to be removed to achieve complete separation between 2 groups (Nout).

Eg:

```<code>df<-data.frame(c(1,2,3,4,5,6,7,10,4,5.5,6,6.5,8,9,12),c(rep("a",8),rep("b",7)))
colnames(df)<-c("Values","Groups")
df
boxplot(df[,1]~df[,2])
points(df[,1]~df[,2],cex=2)
abline(6.2,0)
</code>```

See the plot produced with the above code here.

In that case, removing the 2 higher values of a and 3 lowest values of b gives a possible solution with Nout = 2 + 3 = 5.
This corresponds to treshold value of for example 6.2 (red line on the plot)

Is there a R tool to easily compute that automatically?

I found 2 similar tools in R ARCHIVE:

Ncomplete package:
https://cran.r-project.org/src/contrib/Archive/ncomplete/ (for
complete separation)

Noverlap package :
https://cran.r-project.org/src/contrib/Archive/noverlap/ (for
quasi-complete separation)

They seem however not validated (code start by "NO WARRANTY", and are not in active R package list)

答:
I think median is useful here, although you need to apply it differently based on the 3 general cases you'll encounter

```<code>case 1: distribution of values do not overlap
case 2: distribution of values in 1 group completely overlaps with distribution of values in other group
case 3: distribution of values partially overlap (the data example you gave)
</code>```

How you'll need to apply the median in the different cases follows

```<code>case 1: median value of all values
case 2: median value of all values
case 3: median value of only overlapping values
</code>```

Your data and your plot function

```<code>plotfun <- function(df) {
    with(df, boxplot(Values~Groups))
    with(df, points(Values~Groups, cex=2))
}

df<-data.frame(Values = c(1,2,3,4,5,6,7,10,4,5.5,6,6.5,8,9,12),
            Groups = c(rep("a",8),rep("b",7)))
df
plotfun(df)
</code>```

The workhorse function is myfun. It will determine which of the 3 cases is relevant, and then apply the median accordingly. You can supply an additional argument unitofchange in case your values are not integers. That is, perhaps you're dealing with data that increments by 0.1.

```<code>library(dplyr)
myfun <- function(df, unitofchange=1) {
    unitofchange <- unitofchange / 10
    require(dplyr)
    summarydf <- df %>%
            group_by(Groups) %>%
            summarise(min = min(Values), max = max(Values)) %>%
            arrange(min)

    if (summarydf$max[1] < summarydf$min[2]) {
        # Case 1: distributions do not overlap
        ans <- list(Break = median(df$Values), Nout = 0)
    } else if (summarydf$max[1] > summarydf$max[2]) {
        # Case 2: one distribution is completely between other distribution
        ans <- list(Break = median(df$Values))
        ans[["Break"]] <- modifyiftie(df, unitofchange, ans[["Break"]])
        ans["Nout"] <- sum(df$Values < ans[["Break"]])
    } else {
        # Case 3: distributions partially overlap
        subset_df <- df %>%
                filter(between(Values, summarydf$min[2], summarydf$max[1]))
        ans <- list(Break = median(subset_df$Values))
        ans[["Break"]] <- modifyiftie(df, unitofchange, ans[["Break"]])
        ans["Nout"] <- sum(subset_df$Values[subset_df$Groups == summarydf$Groups[1]] > ans[["Break"]],
                    subset_df$Values[subset_df$Groups == summarydf$Groups[1]] < ans[["Break"]])
    }
    return(ans)
}
</code>```

I also included another function modifyiftie in cases like the example you gave where the separation value is found in both groups

```<code>modifyiftie <- function(df, unitofchange, b) {
    require(dplyr)
    tie <- df %>%
        group_by(Groups) %>%
        filter(Values == b)

    if (nrow(tie) > 0 & all(unique(tie$Groups) %in% unique(df$Groups))) {       # tie is true
        return(b + unitofchange)
    } else {
        return(b)
    }
}
</code>```

Output of the 3 different cases

Case 3: Your data

```<code>df<-data.frame(Values = c(1,2,3,4,5,6,7,10,4,5.5,6,6.5,8,9,12),
            Groups = c(rep("a",8),rep("b",7)))
df
myfun(df)

# $Break
# [1] 6.1

# $Nout
# [1] 5
</code>```

Case 1: Distributions do not overlap

```<code>set.seed(1)
df<-data.frame(Values = c(runif(10)*10, (runif(10)*10)+10),
            Groups = rep(c("a","b"), each=10))
plotfun(df)
myfun(df)

# $Break
# [1] 10.60616

# $Nout
# [1] 0
</code>```

Case 2: Distribution of one group falls in between distribution of other group

```<code>set.seed(1)
df<-data.frame(Values = c((runif(10)*5)+5, runif(10)*20),
            Groups = rep(c("a","b"), each=10))
plotfun(df)
myfun(df)

# $Break
# [1] 8.22478

# $Nout
# [1] 10
</code>```

Body:
Problem: to compute in R the minimum number of observations to be removed to achieve complete separation between 2 groups (Nout).

Eg:

df<-data.frame(c(1,2,3,4,5,6,7,10,4,5.5,6,6.5,8,9,12),c(rep("a",8),rep("b",7)))
colnames(df)<-c("Values","Groups")
df
boxplot(df[,1]~df[,2])
points(df[,1]~df[,2],cex=2)
abline(6.2,0)

See the plot produced with the above code here.

In that case, removing the 2 higher values of a and 3 lowest values of b gives a possible solution with Nout = 2 + 3 = 5.
This corresponds to treshold value of for example 6.2 (red line on the plot)

Is there a R tool to easily compute that automatically?

I found 2 similar tools in R ARCHIVE:

Ncomplete package:
https://cran.r-project.org/src/contrib/Archive/ncomplete/ (for
complete separation)

Noverlap package :
https://cran.r-project.org/src/contrib/Archive/noverlap/ (for
quasi-complete separation)

They seem however not validated (code start by "NO WARRANTY", and are not in active R package list)

Body:
I think median is useful here, although you need to apply it differently based on the 3 general cases you'll encounter

case 1: distribution of values do not overlap
case 2: distribution of values in 1 group completely overlaps with distribution of values in other group
case 3: distribution of values partially overlap (the data example you gave)

How you'll need to apply the median in the different cases follows

case 1: median value of all values
case 2: median value of all values
case 3: median value of only overlapping values

Your data and your plot function

plotfun <- function(df) {
    with(df, boxplot(Values~Groups))
    with(df, points(Values~Groups, cex=2))
}

df<-data.frame(Values = c(1,2,3,4,5,6,7,10,4,5.5,6,6.5,8,9,12),
            Groups = c(rep("a",8),rep("b",7)))
df
plotfun(df)

The workhorse function is myfun. It will determine which of the 3 cases is relevant, and then apply the median accordingly. You can supply an additional argument unitofchange in case your values are not integers. That is, perhaps you're dealing with data that increments by 0.1.

library(dplyr)
myfun <- function(df, unitofchange=1) {
    unitofchange <- unitofchange / 10
    require(dplyr)
    summarydf <- df %>%
            group_by(Groups) %>%
            summarise(min = min(Values), max = max(Values)) %>%
            arrange(min)

    if (summarydf$max[1] < summarydf$min[2]) {
        # Case 1: distributions do not overlap
        ans <- list(Break = median(df$Values), Nout = 0)
    } else if (summarydf$max[1] > summarydf$max[2]) {
        # Case 2: one distribution is completely between other distribution
        ans <- list(Break = median(df$Values))
        ans[["Break"]] <- modifyiftie(df, unitofchange, ans[["Break"]])
        ans["Nout"] <- sum(df$Values < ans[["Break"]])
    } else {
        # Case 3: distributions partially overlap
        subset_df <- df %>%
                filter(between(Values, summarydf$min[2], summarydf$max[1]))
        ans <- list(Break = median(subset_df$Values))
        ans[["Break"]] <- modifyiftie(df, unitofchange, ans[["Break"]])
        ans["Nout"] <- sum(subset_df$Values[subset_df$Groups == summarydf$Groups[1]] > ans[["Break"]],
                    subset_df$Values[subset_df$Groups == summarydf$Groups[1]] < ans[["Break"]])
    }
    return(ans)
}

I also included another function modifyiftie in cases like the example you gave where the separation value is found in both groups

modifyiftie <- function(df, unitofchange, b) {
    require(dplyr)
    tie <- df %>%
        group_by(Groups) %>%
        filter(Values == b)

    if (nrow(tie) > 0 & all(unique(tie$Groups) %in% unique(df$Groups))) {       # tie is true
        return(b + unitofchange)
    } else {
        return(b)
    }
}

Output of the 3 different cases

Case 3: Your data

df<-data.frame(Values = c(1,2,3,4,5,6,7,10,4,5.5,6,6.5,8,9,12),
            Groups = c(rep("a",8),rep("b",7)))
df
myfun(df)

# $Break
# [1] 6.1

# $Nout
# [1] 5

Case 1: Distributions do not overlap

set.seed(1)
df<-data.frame(Values = c(runif(10)*10, (runif(10)*10)+10),
            Groups = rep(c("a","b"), each=10))
plotfun(df)
myfun(df)

# $Break
# [1] 10.60616

# $Nout
# [1] 0

Case 2: Distribution of one group falls in between distribution of other group

set.seed(1)
df<-data.frame(Values = c((runif(10)*5)+5, runif(10)*20),
            Groups = rep(c("a","b"), each=10))
plotfun(df)
myfun(df)

# $Break
# [1] 8.22478

# $Nout
# [1] 10


问:
sql- exceeding variable size in a exec?
I inherited some partially complete sql code that I can't get to work.

it accesses multiple databases, so it first searches for proper database using a userID number, then inserts that database name into a query. the part i'm having a problem with (extremely abbreviated) is...

```<code>DECLARE @sql AS VARCHAR(8000)
    SET @sql = 'INSERT INTO ['+@DatabaseName+'].dbo.[customer]
                  ( -- containing about 200 columns. )
                VALUES(...)'
PRINT @sql
EXEC(@sql)
</code>```

i would get errors in the middle of a column name, sometimes saying it's expecting a parenthesis or quote. i started deleting white space so that, ie, [first name],[last name] were on the same line and not two different lines and that would get me a little further down the query. i don't have much more white spaces i can delete and i'm only just getting into the Values(...) portion of it. the weird thing is. i copy and pasted just the columns portion and put it into Word and it comes up as being only about 3,000 characters, including white space.

am i missing something?

if it means anything, i'm running microsoft sql server 2005, and using the sql server management studio for editing

thanks!

答: See here: SQL Server: When 8000 Characters Is Not Enough for a couple of solutions</p>

Title: sql- exceeding variable size in a exec?

Body:
I inherited some partially complete sql code that I can't get to work.

it accesses multiple databases, so it first searches for proper database using a userID number, then inserts that database name into a query. the part i'm having a problem with (extremely abbreviated) is...

DECLARE @sql AS VARCHAR(8000)
    SET @sql = 'INSERT INTO ['+@DatabaseName+'].dbo.[customer]
                  ( -- containing about 200 columns. )
                VALUES(...)'
PRINT @sql
EXEC(@sql)

i would get errors in the middle of a column name, sometimes saying it's expecting a parenthesis or quote. i started deleting white space so that, ie, [first name],[last name] were on the same line and not two different lines and that would get me a little further down the query. i don't have much more white spaces i can delete and i'm only just getting into the Values(...) portion of it. the weird thing is. i copy and pasted just the columns portion and put it into Word and it comes up as being only about 3,000 characters, including white space.

am i missing something?

if it means anything, i'm running microsoft sql server 2005, and using the sql server management studio for editing

thanks!


问:
How to hide 'Minimize', 'Maximize' and 'Close' buttons from PrismUserControl WPF?
In my Prism 6 WPF MVVM application I use the following PrismUserControl WPF for displaying of modal notification dialogs:

```<code><UserControl x:Class="CommonWpfControlLibrary.NotificationDialogPopupView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
         xmlns:prism="http://prismlibrary.com/"
         prism:ViewModelLocator.AutoWireViewModel="True"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300" MaxHeight="300" MaxWidth="600">

    <StackPanel Orientation="Vertical" Margin="20">
        <TextBlock Text="{Binding Message}" TextWrapping="Wrap"/>
        <telerik:RadButton Content="OK" Command="{Binding OnOkPressedCommand}" HorizontalAlignment="Center" Width="50" Margin="0 10 0 0"/>
    </StackPanel>
</UserControl>
</code>```

In the Views where I use this UserControl as a modal dialog content I define it as following:

```<code><i:Interaction.Triggers>
    <prism:InteractionRequestTrigger SourceObject="{Binding NotificationRequest, Mode=OneWay}">
        <prism:PopupWindowAction IsModal="True" CenterOverAssociatedObject="True">
            <prism:PopupWindowAction.WindowContent>
                <commonControls:NotificationDialogPopupView/>
            </prism:PopupWindowAction.WindowContent>
        </prism:PopupWindowAction>
    </prism:InteractionRequestTrigger>
</i:Interaction.Triggers>
</code>```

When I activate the dialog it is displayed, for example, as the following:

But as you can see 'Minimize', 'Maximize' and 'Close' buttons are visible and enabled. And the system menu (activated in upper left corner of the dialog) is enabled too. How can I hide 'Minimize', 'Maximize' and 'Close' buttons and disable the system menu?

答:
I have a workaround, if it suits your structure. Expose a Usercontrol loaded event in code behind (can be achieved also using MVVM) of your Usercontrol NotificationDialogPopupView </p>

```<code>Loaded="UserControl_Loaded"
</code>```

<p>and write down following code in the Loaded event </p>

```<code>private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Window win = ((UserControl)sender).Parent as Window;
            if(win != null)
            {
                win.WindowStyle = WindowStyle.None;
                win.ResizeMode = ResizeMode.NoResize;

            }
        }
</code>```

Body:
In my Prism 6 WPF MVVM application I use the following PrismUserControl WPF for displaying of modal notification dialogs:

<UserControl x:Class="CommonWpfControlLibrary.NotificationDialogPopupView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
         xmlns:prism="http://prismlibrary.com/"
         prism:ViewModelLocator.AutoWireViewModel="True"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300" MaxHeight="300" MaxWidth="600">

    <StackPanel Orientation="Vertical" Margin="20">
        <TextBlock Text="{Binding Message}" TextWrapping="Wrap"/>
        <telerik:RadButton Content="OK" Command="{Binding OnOkPressedCommand}" HorizontalAlignment="Center" Width="50" Margin="0 10 0 0"/>
    </StackPanel>
</UserControl>

In the Views where I use this UserControl as a modal dialog content I define it as following:

    <prism:InteractionRequestTrigger SourceObject="{Binding NotificationRequest, Mode=OneWay}">
        <prism:PopupWindowAction IsModal="True" CenterOverAssociatedObject="True">
            <prism:PopupWindowAction.WindowContent>
                <commonControls:NotificationDialogPopupView/>
            </prism:PopupWindowAction.WindowContent>
        </prism:PopupWindowAction>
    </prism:InteractionRequestTrigger>

When I activate the dialog it is displayed, for example, as the following:

But as you can see 'Minimize', 'Maximize' and 'Close' buttons are visible and enabled. And the system menu (activated in upper left corner of the dialog) is enabled too. How can I hide 'Minimize', 'Maximize' and 'Close' buttons and disable the system menu?

Body:
I have a workaround, if it suits your structure. Expose a Usercontrol loaded event in code behind (can be achieved also using MVVM) of your Usercontrol NotificationDialogPopupView

Loaded="UserControl_Loaded"

and write down following code in the Loaded event

private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Window win = ((UserControl)sender).Parent as Window;
            if(win != null)
            {
                win.WindowStyle = WindowStyle.None;
                win.ResizeMode = ResizeMode.NoResize;

            }
        }


问:
How to make right query to vTiger CRM API
I got an sql query:

```<code>$vtiger->query('*', 'Products', "(productname LIKE '%$name%' OR description LIKE '%$name%') AND cf_1007 = 'Ready'", null, 50, null);
</code>```

(using https://github.com/sumocoders/vtiger-api). It has an WHERE clause. How to make it right? (current query throws exception). I need to take all rows where productname or description contains %name% and where cell cf_1007 = "Ready".

UPD: answer from vTiger API (forgot to add it here)

```<code>{"success":false,"error":{"code":"QUERY_SYNTAX_ERROR","message":"Syntax Error on line 1: token '(' Unexpected PARENOPEN((), expected one of: COLUMNNAME"}}
</code>```

答:
I dug deeper regarding this issue and found the following:
The API you're using sends a request to the VTIGER web service. There's nothing wrong in the API and your usage seems to be fine. So, next station would be to check the webservice documentations.

Then I came across this page and found the following:

```<code>SELECT * | <column_list> | <count(*)> FROM <object> [WHERE
<conditionals>] [ORDER BY <column_list>] [LIMIT [<m>, ] <n>]
</code>```

Notice the description of the  part:

<condition_operations> or <in_clauses> or <like_clauses> separated by
  ‘and’ or ‘or’ operators these are processed from left to right. The
  are no grouping that is bracket operators.

So it seems that you can't use the (field1=val1 OR field2=val2) AND field3=val3 format. You should use field1=val1 OR field2=val AND field3=val3.

Body:
I got an sql query:

$vtiger->query('*', 'Products', "(productname LIKE '%$name%' OR description LIKE '%$name%') AND cf_1007 = 'Ready'", null, 50, null);

(using https://github.com/sumocoders/vtiger-api). It has an WHERE clause. How to make it right? (current query throws exception). I need to take all rows where productname or description contains %name% and where cell cf_1007 = "Ready".

UPD: answer from vTiger API (forgot to add it here)

{"success":false,"error":{"code":"QUERY_SYNTAX_ERROR","message":"Syntax Error on line 1: token '(' Unexpected PARENOPEN((), expected one of: COLUMNNAME"}}

Body:
I dug deeper regarding this issue and found the following:
The API you're using sends a request to the VTIGER web service. There's nothing wrong in the API and your usage seems to be fine. So, next station would be to check the webservice documentations.

Then I came across this page and found the following:

SELECT * | <column_list> | <count(*)> FROM <object> [WHERE
<conditionals>] [ORDER BY <column_list>] [LIMIT [<m>, ] <n>]

Notice the description of the  part:

<condition_operations> or <in_clauses> or <like_clauses> separated by
  ‘and’ or ‘or’ operators these are processed from left to right. The
  are no grouping that is bracket operators.

So it seems that you can't use the (field1=val1 OR field2=val2) AND field3=val3 format. You should use field1=val1 OR field2=val AND field3=val3.


问:
Lucene pagination using searchAfter while index is updated
I have implemented pagination with Lucene using the searchAfter method provided by IndexSearcher. In every call, I pass the last ScoreDoc returned in the previous page.

The problem is that sometimes, the index gets updated between page and page and occasionally I am getting this exception:

```<code>java.lang.IllegalArgumentException: after.doc exceeds the number of
documents in the reader: after.doc=337 limit=337
    at
org.apache.lucene.search.IndexSearcher.searchAfter(IndexSearcher.java:434)
</code>```

I understand that Lucene changes the docs ids every now and then (segment merges, etc.) and I guess that is why that exception is happening as searchAfter relies on those docs ids.

How could I improve this pagination mechanism to avoid this exception? Is there any better way to implement pagination with Lucene?

答:
I'm not familiar with this error but i would suggest to implement a way you can use NRT (Near real time) searches with a SearcherManager (JavaDoc)

it's a big effort but at the end you receive a better update handling for indices especially if they update more frequently.

See:
Lucene NRT beginner tutorial or related stackoverflow answer

Body:
I have implemented pagination with Lucene using the searchAfter method provided by IndexSearcher. In every call, I pass the last ScoreDoc returned in the previous page.

The problem is that sometimes, the index gets updated between page and page and occasionally I am getting this exception:

java.lang.IllegalArgumentException: after.doc exceeds the number of
documents in the reader: after.doc=337 limit=337
    at
org.apache.lucene.search.IndexSearcher.searchAfter(IndexSearcher.java:434)

I understand that Lucene changes the docs ids every now and then (segment merges, etc.) and I guess that is why that exception is happening as searchAfter relies on those docs ids.

How could I improve this pagination mechanism to avoid this exception? Is there any better way to implement pagination with Lucene?


问:
Format path within Text File for consumption in Python
I am writing a Python script for use by multiple non-Python users.
I have a text file containing the parameters my script needs to run.

One of the inputs is a path. I cannot get my script to run and was thinking it was because I had referenced my path incorrectly.

I have tried:

```<code>C:\temp\test
"C:\temp\test"
r"C:\temp\test"
C:/temp/test
"C:/temp/test"
C:\\temp\\test
"C:\\temp\\test"
</code>```

I have added each one of these into a text file, which is called and read in my Python script.
I have other parameters and they are called correctly, my script seems to run when I hard code the path in. I say seems because I think there are a few bugs I need to check, but it runs with no errors.

When I use the text file I get this error - which varies depending on if I used one of the above examples:

WindowsError: [Error 123] The filename, directory name, or volume
  label syntax is incorrect: 'c:\temp\match1\jpg\n/.'

My code is as follows:

```<code>print ("Linking new attachments to feature")
fp = open(r"C:\temp\Match1\Match_Table.txt","r") #reads my text file with inputs

lines=fp.readlines()

InFeat = lines[1]
print (InFeat)

AttFolder = lines[3] #reads the folder from the text file
print (AttFolder)

OutTable = lines[5]
if arcpy.Exists(OutTable):
    print("Table Exists")
    arcpy.Delete_management(OutTable)

OutTable = lines[5]
print (OutTable)

LinkF = lines[7]
print (LinkF)
fp.close()

#adding from https://community.esri.com/thread/90280

if arcpy.Exists("in_memory\\matchtable"):
    arcpy.Delete_management("in_memory\\matchtable")
print ("CK Done")
input = InFeat
inputField = "OBJECTID"

matchTable = arcpy.CreateTable_management("in_memory", "matchtable")
matchField = "MatchID"
pathField = "Filename"
print ("Table Created")
arcpy.AddField_management(matchTable, matchField, "TEXT")
arcpy.AddField_management(matchTable, pathField, "TEXT")

picFolder = r"C:\temp\match1\JPG" #hard coded in

print (picFolder)

print ("Fields added")

fields = ["MatchID", "Filename"]
cursor = arcpy.da.InsertCursor(matchTable, fields)
  ##go thru the picFolder of .png images to attach
for file in os.listdir(picFolder):
    if str(file).find(".jpg") > -1:
       pos = int(str(file).find("."))
       newfile = str(file)[0:pos]
       cursor.insertRow((newfile, file))
del cursor

arcpy.AddAttachments_management(input, inputField, matchTable, matchField, pathField, picFolder)
</code>```

答:
From your error "'c:\temp\match1\jpg\n/.'", i can see "\n" character, \n is symbole of new line ( when you press enter button ) you should remove that character from end of your path! did you try to do that? you can use .lstrip("\n") , replcae() or regx methods for remove that character.

Try to open and read line by line of your input file like this:

```<code>read_lines = [line.rstrip('\n') for line in open(r"C:\temp\Match1\Match_Table.txt")]
print(read_lines)
print(read_lines[1])
</code>```

Body:
I am writing a Python script for use by multiple non-Python users.
I have a text file containing the parameters my script needs to run.

One of the inputs is a path. I cannot get my script to run and was thinking it was because I had referenced my path incorrectly.

I have tried:

C:\temp\test
"C:\temp\test"
r"C:\temp\test"
C:/temp/test
"C:/temp/test"
C:\\temp\\test
"C:\\temp\\test"

I have added each one of these into a text file, which is called and read in my Python script.
I have other parameters and they are called correctly, my script seems to run when I hard code the path in. I say seems because I think there are a few bugs I need to check, but it runs with no errors.

When I use the text file I get this error - which varies depending on if I used one of the above examples:

WindowsError: [Error 123] The filename, directory name, or volume
  label syntax is incorrect: 'c:\temp\match1\jpg\n/.'

My code is as follows:

print ("Linking new attachments to feature")
fp = open(r"C:\temp\Match1\Match_Table.txt","r") #reads my text file with inputs

lines=fp.readlines()

InFeat = lines[1]
print (InFeat)

AttFolder = lines[3] #reads the folder from the text file
print (AttFolder)

OutTable = lines[5]
if arcpy.Exists(OutTable):
    print("Table Exists")
    arcpy.Delete_management(OutTable)

OutTable = lines[5]
print (OutTable)

LinkF = lines[7]
print (LinkF)
fp.close()

#adding from https://community.esri.com/thread/90280

if arcpy.Exists("in_memory\\matchtable"):
    arcpy.Delete_management("in_memory\\matchtable")
print ("CK Done")
input = InFeat
inputField = "OBJECTID"

matchTable = arcpy.CreateTable_management("in_memory", "matchtable")
matchField = "MatchID"
pathField = "Filename"
print ("Table Created")
arcpy.AddField_management(matchTable, matchField, "TEXT")
arcpy.AddField_management(matchTable, pathField, "TEXT")

picFolder = r"C:\temp\match1\JPG" #hard coded in

print (picFolder)

print ("Fields added")

fields = ["MatchID", "Filename"]
cursor = arcpy.da.InsertCursor(matchTable, fields)
  ##go thru the picFolder of .png images to attach
for file in os.listdir(picFolder):
    if str(file).find(".jpg") > -1:
       pos = int(str(file).find("."))
       newfile = str(file)[0:pos]
       cursor.insertRow((newfile, file))
del cursor

arcpy.AddAttachments_management(input, inputField, matchTable, matchField, pathField, picFolder)

Body:
From your error "'c:\temp\match1\jpg\n/.'", i can see "\n" character, \n is symbole of new line ( when you press enter button ) you should remove that character from end of your path! did you try to do that? you can use .lstrip("\n") , replcae() or regx methods for remove that character.

Try to open and read line by line of your input file like this:

read_lines = [line.rstrip('\n') for line in open(r"C:\temp\Match1\Match_Table.txt")]
print(read_lines)
print(read_lines[1])


问:
(A+B')' (A'+B) convert to product of sums
(A+B')' (A'+B) convert this to PoS (product of sums ) expression using De Morgan's law

i can do (A+B') (A'+B) one but i can not convert (A+B')' (A'+B) because it has single over bars on more than one variable.please help me

答:
```<code>(A+B')'(A'+B)    starting expression
(A'B)(A'+B)      De Morgan on (A+B')'
A'BA'+A'BB       distributive property
A'A'B+A'BB       commutative property
A'B+A'BB         XX=X on A'A'B
A'B+A'B          XX=X on A'BB
A'B              X+X=X on A'B+A'B
</code>```

I don't know that I'd call that "product of sums" form but it is the simplest equivalent expression. If you really insist on product of sums then we can run the X+X=X rule in reverse:

```<code>A'B               starting expression
(A'+A')B          X=X+X on A'
(A'+A')(B+B)      X=X+X on B
</code>```

Body:
(A+B')'(A'+B)    starting expression
(A'B)(A'+B)      De Morgan on (A+B')'
A'BA'+A'BB       distributive property
A'A'B+A'BB       commutative property
A'B+A'BB         XX=X on A'A'B
A'B+A'B          XX=X on A'BB
A'B              X+X=X on A'B+A'B

I don't know that I'd call that "product of sums" form but it is the simplest equivalent expression. If you really insist on product of sums then we can run the X+X=X rule in reverse:

A'B               starting expression
(A'+A')B          X=X+X on A'
(A'+A')(B+B)      X=X+X on B


问:
plot 1, 2 and 3 SD with stat_summary function
Is the "fun.args" function within stat_summary for specifying the numbers of SD I want to plot for an interval of the data mean?

```<code>ggplot(mtcars, aes(factor(cyl), mpg)) + geom_point() +
  stat_summary(
    fun.data= "mean_sdl", fun.args = list(mult = 1),
    geom="crossbar",color="red", size=0.5)+
  stat_summary(
    fun.data= "mean_sdl", fun.args = list(mult = 2),
    geom="crossbar",color="green")+
  stat_summary(
    fun.data= "mean_sdl", fun.args = list(mult = 3),
    geom="crossbar",color="blue")
</code>```

答:
Yes, it is used to specify the number of standard deviations around your mean. To see why, you have to click through some help pages:

From the help page of stat_summary, you'll find that fun.args is used to supply arguments for the function you specified in the fun_data argument (here: mean_sdl).

Digging a bit deeper: From the help page of mean_sdl (or actually, the help page of smean.sld) we find:

smean.sdl computes the mean plus or minus a constant times the standard deviation.

The function can be used like: smean.sdl(x, mult=2), where 2 specifies the "constant" that is referred to in the quote above. In other words, mult refers to the width of the confidence interval in terms of standard deviations.

If you supply mean_sdl within stat_summary, the x-argument will automatically be filled with the data you supplied to your ggplot-call.

Body:
Is the "fun.args" function within stat_summary for specifying the numbers of SD I want to plot for an interval of the data mean?

ggplot(mtcars, aes(factor(cyl), mpg)) + geom_point() +
  stat_summary(
    fun.data= "mean_sdl", fun.args = list(mult = 1),
    geom="crossbar",color="red", size=0.5)+
  stat_summary(
    fun.data= "mean_sdl", fun.args = list(mult = 2),
    geom="crossbar",color="green")+
  stat_summary(
    fun.data= "mean_sdl", fun.args = list(mult = 3),
    geom="crossbar",color="blue")


问:
Syntax error integer
There is an Angular 4 client side Nodejs-Express back end and PostgreSQL database. The problem is that if I want to send data to server ( in my submodule, what is a todo function ) the backend send me the next:

My error message is:

POST /api/datatodo 500 1.150 ms - 969
error: invalid input syntax for integer: ""

modal.ts

```<code>class Searches {
    _id: string;
    title: string;
    newdata: string;

    constructor(
    ){
        this.title = ""
        this._id = ""
        this.newdata = ""
    }
}
</code>```

the insert query on backend:

```<code>function createSearch(req, res, next) {
  req.body.launched = parseInt(req.body.launched);
  db.none('INSERT INTO table (userid, word)' +
      'values(${_id}, ${newdata})',
    req.body)
    .then(function () {
      res.status(200)
        .json({
          status: 'success',
          message: 'Cool'
        });
    })
    .catch(function (err) {
      return next(err);
    });
}
</code>```

答:
pg-promise formats values according to their JavaScript type. And from the error it looks like at least one of _id or newdata is a string, while an integer is expected.

So what you did for field launched, which you do not even use, you should do to those fields to rectify the type:

```<code>const a = req.body;
a._id = +a._id;
a.newdata = +a.newdata;
db.none('INSERT INTO table(userid, word) VALUES(${_id}, ${newdata})', a)
</code>```

That's the recommended approach. Alternatively, you can do server-side casting by appending ::int to the integer parameters:

```<code>db.none('INSERT INTO table(userid, word) VALUES(${_id}::int, ${newdata}::int)', req.body)
</code>```

And another usable approach:

```<code>const a = req.body;
db.none('INSERT INTO table(userid, word) VALUES($1, $2)', [+a._id, +a.newdata])
</code>```

Title: Syntax error integer

Body:
There is an Angular 4 client side Nodejs-Express back end and PostgreSQL database. The problem is that if I want to send data to server ( in my submodule, what is a todo function ) the backend send me the next:

My error message is:

POST /api/datatodo 500 1.150 ms - 969
error: invalid input syntax for integer: ""

modal.ts

class Searches {
    _id: string;
    title: string;
    newdata: string;

    constructor(
    ){
        this.title = ""
        this._id = ""
        this.newdata = ""
    }
}

the insert query on backend:

function createSearch(req, res, next) {
  req.body.launched = parseInt(req.body.launched);
  db.none('INSERT INTO table (userid, word)' +
      'values(${_id}, ${newdata})',
    req.body)
    .then(function () {
      res.status(200)
        .json({
          status: 'success',
          message: 'Cool'
        });
    })
    .catch(function (err) {
      return next(err);
    });
}

Body:
pg-promise formats values according to their JavaScript type. And from the error it looks like at least one of _id or newdata is a string, while an integer is expected.

So what you did for field launched, which you do not even use, you should do to those fields to rectify the type:

const a = req.body;
a._id = +a._id;
a.newdata = +a.newdata;
db.none('INSERT INTO table(userid, word) VALUES(${_id}, ${newdata})', a)

That's the recommended approach. Alternatively, you can do server-side casting by appending ::int to the integer parameters:

db.none('INSERT INTO table(userid, word) VALUES(${_id}::int, ${newdata}::int)', req.body)

And another usable approach:

const a = req.body;
db.none('INSERT INTO table(userid, word) VALUES($1, $2)', [+a._id, +a.newdata])


问:
Debugging with 'Attach to Process' magic with Visual Studio 2010/Xcode/gdb
I see that with the 'Attach to Process', one can debug the process by setting up break point in Visual Studio IDE.

I think it's pretty cool, and I'm curious what's the mechanism that enables it. I also found that gdb and Mac's Xcode supports the technology.

Q1 : Can anyone explain how does this work? How can the process mapped to a breakpoint in an IDE or gdb environment?

Q2 : Are there other compiler/debugger options than /Zi or -g (adding debug info)?

Q3 : Is this the way to debug dll (dynamic library)?

ADDED

I found this one with MSDN - http://msdn.microsoft.com/en-us/library/c6wf8e4z.aspx

答:
The most common scenario I know of is using a browser to debug web code. In these cases, you start Visual Studio in debug mode and then attach to the browser and call the page in question. When the page is called it starts running the code in the debugger. Essentially, the debugger watches the process and when it hits code in VS, it starts debugging.

The same is true with other applications that are calling code you are running in Visual Studio. When you cross the boundary to the code, the debugger catches the call and starts running code in VS.


问:
WPF ScrollIntoView strange behaviour
I', using ScrollIntoView to scroll to the topmost item in list (by default it's always scrolled to the bottom ones, but in some specified case I need this the other way)

So first items are added to list, and then ScrollIntoView(Items[0]) called.
ScrollIntoView called inside Dispatcher.BeginInvoke, so it's in UI thread.

The general idea is that user sees initial list with items 'short' description, then selects one of them, and sees all the info, which contains also 'short' part.

I.e.:

1)

2)

So when I'm clicking on element 1 in case 1, I'm expecting to see the picture 2. But instead sometimes I see

I noticed, for example, that view is always updated properly, when cursor stayed on listbox. I've checked callstack of the "AddItem" and "ScrollTop" methods, they are in correct ordering, and "ScrollTop" is always called properly.

In all other cases (when I'm picking up Item 2, or Item 0) "ScrollTop" working well.

So I think it's some kind of WPF optimization or so. Because Item 1 info in 1) is same and on the same place as in case 2). WPF just does not each time updates the view.

Is there any way, to make list box to be updated every time after I scroll to top?

I've tried with UpdateLayout(). It didn't help.

UPDATE (code example):
main thread code:

```<code>UIManager.AddListItem(item1);
UIManager.AddListItem(item2);
UIManager.AddListItem(item3);
UIManager.ScrollToTop();
</code>```

UIManager implementation:

```<code>public void AddListItem(ListItem item)
{
 ExecuteUI(() =>
 {
  MyList.AddItem(item);
 });
}

public void ScrollToTop()
{
 ExecuteUI(() =>
 {
  MyList.ScrollToTop();
 });
}
</code>```

MyListModel implementation:

```<code>public void AddItem(ListItem item)
{
 lock (linesLock)
 {
   if (Lines == null)
     Lines = new ObservableCollection<ItemModel>();

   ItemModel line = new ItemModel(item);
   Lines.Add(line); //When line added it automatically scrolls to it
  // via ((INotifyCollectionChanged)ListLines.Items).CollectionChanged += LinesChanged;
 }
}

public void ScrollToTop()
{
   if (Lines.Count == 0 || ScrollEvent == null)
            return;
    ScrollEvent(this, new ScrollEventArgs(Lines[0]));
   // via Model.ScrollEvent += ScrollEvent;
}
</code>```

Model xaml code:

```<code>// ListLines is a ListBox

private void LinesChanged(object sender, NotifyCollectionChangedEventArgs e)
{
        ListLines.ScrollIntoView(e.NewItems[0]);
}

private void ScrollEvent(object sender, ScrollEventArgs e)
{
  ListLines.ScrollIntoView(e.Item);
}
</code>```

答:
Try to use the ScrollToVerticalOffset or the ScrollToTop method of the ScrollViewer:

```<code>public void Click(object sender, RoutedEventArgs e)
{
    ScrollViewer sv = GetChildOfType<ScrollViewer>(listBox);
    if (sv != null)
        sv.ScrollToVerticalOffset(0);
}

public static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj == null)
        return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != null)
            return result;
    }
    return null;
}
</code>```

But please also always remember to provide a Minimal, Complete, and Verifiable example of your issue when asking a question.

Title: WPF ScrollIntoView strange behaviour

Body:
I', using ScrollIntoView to scroll to the topmost item in list (by default it's always scrolled to the bottom ones, but in some specified case I need this the other way)

So first items are added to list, and then ScrollIntoView(Items[0]) called.
ScrollIntoView called inside Dispatcher.BeginInvoke, so it's in UI thread.

The general idea is that user sees initial list with items 'short' description, then selects one of them, and sees all the info, which contains also 'short' part.

I.e.:

1)

2)

So when I'm clicking on element 1 in case 1, I'm expecting to see the picture 2. But instead sometimes I see

I noticed, for example, that view is always updated properly, when cursor stayed on listbox. I've checked callstack of the "AddItem" and "ScrollTop" methods, they are in correct ordering, and "ScrollTop" is always called properly.

In all other cases (when I'm picking up Item 2, or Item 0) "ScrollTop" working well.

So I think it's some kind of WPF optimization or so. Because Item 1 info in 1) is same and on the same place as in case 2). WPF just does not each time updates the view.

Is there any way, to make list box to be updated every time after I scroll to top?

I've tried with UpdateLayout(). It didn't help.

UPDATE (code example):
main thread code:

UIManager.AddListItem(item1);
UIManager.AddListItem(item2);
UIManager.AddListItem(item3);
UIManager.ScrollToTop();

UIManager implementation:

public void AddListItem(ListItem item)
{
 ExecuteUI(() =>
 {
  MyList.AddItem(item);
 });
}

public void ScrollToTop()
{
 ExecuteUI(() =>
 {
  MyList.ScrollToTop();
 });
}

MyListModel implementation:

public void AddItem(ListItem item)
{
 lock (linesLock)
 {
   if (Lines == null)
     Lines = new ObservableCollection<ItemModel>();

   ItemModel line = new ItemModel(item);
   Lines.Add(line); //When line added it automatically scrolls to it
  // via ((INotifyCollectionChanged)ListLines.Items).CollectionChanged += LinesChanged;
 }
}

public void ScrollToTop()
{
   if (Lines.Count == 0 || ScrollEvent == null)
            return;
    ScrollEvent(this, new ScrollEventArgs(Lines[0]));
   // via Model.ScrollEvent += ScrollEvent;
}

Model xaml code:

// ListLines is a ListBox

private void LinesChanged(object sender, NotifyCollectionChangedEventArgs e)
{
        ListLines.ScrollIntoView(e.NewItems[0]);
}

private void ScrollEvent(object sender, ScrollEventArgs e)
{
  ListLines.ScrollIntoView(e.Item);
}

Body:
Try to use the ScrollToVerticalOffset or the ScrollToTop method of the ScrollViewer:

public void Click(object sender, RoutedEventArgs e)
{
    ScrollViewer sv = GetChildOfType<ScrollViewer>(listBox);
    if (sv != null)
        sv.ScrollToVerticalOffset(0);
}

public static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj == null)
        return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);

        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != null)
            return result;
    }
    return null;
}

But please also always remember to provide a Minimal, Complete, and Verifiable example of your issue when asking a question.


问:
delphi Check whether function result value is used
My question is the same as this one here except for the language. I am using Delphi.

Following the link you'll see in Java this seems to be impossible, so I would assume this applies to Delphi as well, but I am not entirely sure

I want to know, whether a function can check, if the calling procedure/function is making use of the return value the function provides.

I've tried this, but it didn't work: (I guess if a solution exists it would behave similar to this)

```<code>  if Assigned(Result) then begin
    showmessage('return value is assigned');
  end else begin
    showmessage('return value is NOT assigned');
  end;
</code>```

It may seem to be useless to check, but my function produces an encrypted file, for which the return value is beeing needed to decrypt this file, so it would be nice to notify the user instead of just producing an useless file and therefore I would like to check the usage of the return value.

Possible workaround:

I've got an Idea, but either don't know whether this is possible nor how to do that: The function could scan the part of RAM, which is occupied by my application and check for the return value (String) to exist after the command Result := 'something like F8975BE8AC0192#2983FE4A#B9DFE25' has been fired. It is soooo unlikeley that the String exists twice, that this simple check would completely fit my purpose.
In general this may not work, because the Result could exist twice, but in my case this is somehow impossible.

So to do this workaround I expand my original question:
How can I search for a String in the part of RAM occupied by the application containing the function, which wants to check this?
As far as I know it would be much harder to check this for an external application, which is not needed here.

答:
I believe your question might stem from either the desire to implement something absolutely bullet-proof, or a design choice that makes things harder than they are.

Bullet proof implementation

If you have done a good job as a developer, function naming and signature will indicate the intended use to a caller. Whether he understands that and uses it correctly in the end, is likely out of your control, as comments have indicated: where do you stop? There might always be a way to defeat your implementation.

Can and should anything be done?

But thinking about the technical aspect of your question and the inability to check if something is done with a function result - as the functions code is already exited - my idea would have been to make the result itself 'smarter'.

You mentioned your encryption key is a string you would call 'unique'. So it could be possible to use Delphi's string reference counting - at least for strings other than WideString - to make sure it is still referenced somewhere. Coupled with an IInterfacedObject that is also reference counted, the TInterfaceObject could check if it outlives the monitored string.

Interface

```<code>  IRefCheck = interface
  ['{E6A54A33-E4DB-4486-935A-00549E6793AC}']
    function Value: string;
  end;
</code>```

Implemented by a TInterfacedObject

```<code>  TRefCheck = class(TInterfacedObject, IRefCheck)
  strict private
    FString: string;
  public
    constructor Create(const S: string);
    destructor Destroy; override;
    function Value: string;
  end;
</code>```

Implemented like

```<code>constructor TRefCheck.Create(const S: string);
begin
  FString := S;
end;

destructor TRefCheck.Destroy;
begin
  Assert(StringRefCount(FString) > 1, 'Reference check failed for ' + FString);
  inherited Destroy;
end;

function TRefCheck.Value: string;
begin
  Result := FString;
end;
</code>```

So whenever TRefCheck is destroyed and holds the only reference to its string, the Assert will fail. I opted for the interface as result because when it was a string, the caller didn't need to control the life-time of the result and doesn't need now. Your function will now look similar to this:

```<code>function GetEncryptedFileKey(Key: string): IRefCheck;
begin
  Result := TRefCheck.Create(Key);
end;
</code>```

And is used like this:

```<code>procedure Test;
var
  S: string;
begin
  S := GetEncryptedFileKey('Test Value 1').Value;
  GetEncryptedFileKey('Test Value 2');
end;
</code>```

A small test program calling Test will fail with

EAssertionFailed: Reference check failed for Test Value 2

As this requires the knowledge of the IRefCheck interface for the caller to access the Value and implicit operators are not available for classes (or interfaces) I tried it with an record, so it can be used like your string function before:

```<code>  TRefCheckRec = record
  private
    RefCheck: IRefCheck;
    function AsString: string;
  public
    class operator Implicit(Value: TRefCheckRec): string;
    class function CreateNew(S: string): TRefCheckRec; static;
  end;

function TRefCheckRec.AsString: string;
begin
  RefCheck.Value;
end;

class function TRefCheckRec.CreateNew(S: string): TRefCheckRec;
begin
  Result.RefCheck := TRefCheck.Create(S);
end;

class operator TRefCheckRec.Implicit(Value: TRefCheckRec): string;
begin
  Result := Value.AsString;
end;
</code>```

Your function and the test code then look like this:

```<code>function GetEncryptedFileKey(Key: string): TRefCheckRec;
begin
  Result := TRefCheckRec.CreateNew(Key);
end;
procedure Test2;
var
  S: string;
begin
  S := GetEncryptedFileKey('Test Value Record');
  GetEncryptedFileKey('Test Value Record 2');
end;
</code>```

At the end even with all this, defeating is as easy as never really 'using' S, in fact the test code does exactly that. All fluff and no advantage over

```<code>function GetEncryptedFileKey: string;
</code>```

or

```<code>procedure EncryptFile(var EncryptionKey: string);
</code>```

Design choice

Reading your comments and the question what I believe I would have done is encapsulate your logic into a class, and let your function return an instance of it.

```<code>  TEncryptedFile = class
  private
    FEncryptionKey: string;
    FKeyPersisted: Boolean;
  public
    constructor Create;
    destructor Destroy; override;
    function GetEncryptionKey: string;
    procedure SaveEncryptionKeyToFile;
  end;

constructor TEncryptedFile.Create;
begin
  FKeyPersisted := False;
  FEncryptionKey := ...
end;

destructor TEncryptedFile.Destroy;
begin
  if not FKeyPersisted then
    SaveEncryptionKeyToFile;
  inherited Destroy;
end;

function TEncryptedFile.GetEncryptionKey: string;
begin
  Result := FEncryptionKey;
  FKeyPersisted := True;
end;

procedure TEncryptedFile.SaveEncryptionKeyToFile;
begin
  FKeyPersisted := True;
  // Save to file
  ...
end;
</code>```

Your function now returns an instance of it, caller is responsible for clean-up, as indicated by function name.

```<code>  function CreateEncryptedFile: TEncryptedFile;
  begin
    Result := TEncryptedFile.Create;
  end;
</code>```

Whether he decides to access your key directly or save it to a file is up to him. If he cleans up the instance and none of both is done already, the key is automatically saved.

Body:
My question is the same as this one here except for the language. I am using Delphi.

Following the link you'll see in Java this seems to be impossible, so I would assume this applies to Delphi as well, but I am not entirely sure

I want to know, whether a function can check, if the calling procedure/function is making use of the return value the function provides.

I've tried this, but it didn't work: (I guess if a solution exists it would behave similar to this)

  if Assigned(Result) then begin
    showmessage('return value is assigned');
  end else begin
    showmessage('return value is NOT assigned');
  end;

It may seem to be useless to check, but my function produces an encrypted file, for which the return value is beeing needed to decrypt this file, so it would be nice to notify the user instead of just producing an useless file and therefore I would like to check the usage of the return value.

Possible workaround:

I've got an Idea, but either don't know whether this is possible nor how to do that: The function could scan the part of RAM, which is occupied by my application and check for the return value (String) to exist after the command Result := 'something like F8975BE8AC0192#2983FE4A#B9DFE25' has been fired. It is soooo unlikeley that the String exists twice, that this simple check would completely fit my purpose.
In general this may not work, because the Result could exist twice, but in my case this is somehow impossible.

So to do this workaround I expand my original question:
How can I search for a String in the part of RAM occupied by the application containing the function, which wants to check this?
As far as I know it would be much harder to check this for an external application, which is not needed here.

Body:
I believe your question might stem from either the desire to implement something absolutely bullet-proof, or a design choice that makes things harder than they are.

Bullet proof implementation

If you have done a good job as a developer, function naming and signature will indicate the intended use to a caller. Whether he understands that and uses it correctly in the end, is likely out of your control, as comments have indicated: where do you stop? There might always be a way to defeat your implementation.

Can and should anything be done?

But thinking about the technical aspect of your question and the inability to check if something is done with a function result - as the functions code is already exited - my idea would have been to make the result itself 'smarter'.

You mentioned your encryption key is a string you would call 'unique'. So it could be possible to use Delphi's string reference counting - at least for strings other than WideString - to make sure it is still referenced somewhere. Coupled with an IInterfacedObject that is also reference counted, the TInterfaceObject could check if it outlives the monitored string.

Interface

  IRefCheck = interface
  ['{E6A54A33-E4DB-4486-935A-00549E6793AC}']
    function Value: string;
  end;

Implemented by a TInterfacedObject

  TRefCheck = class(TInterfacedObject, IRefCheck)
  strict private
    FString: string;
  public
    constructor Create(const S: string);
    destructor Destroy; override;
    function Value: string;
  end;

Implemented like

constructor TRefCheck.Create(const S: string);
begin
  FString := S;
end;

destructor TRefCheck.Destroy;
begin
  Assert(StringRefCount(FString) > 1, 'Reference check failed for ' + FString);
  inherited Destroy;
end;

function TRefCheck.Value: string;
begin
  Result := FString;
end;

So whenever TRefCheck is destroyed and holds the only reference to its string, the Assert will fail. I opted for the interface as result because when it was a string, the caller didn't need to control the life-time of the result and doesn't need now. Your function will now look similar to this:

function GetEncryptedFileKey(Key: string): IRefCheck;
begin
  Result := TRefCheck.Create(Key);
end;

And is used like this:

procedure Test;
var
  S: string;
begin
  S := GetEncryptedFileKey('Test Value 1').Value;
  GetEncryptedFileKey('Test Value 2');
end;

A small test program calling Test will fail with

EAssertionFailed: Reference check failed for Test Value 2

As this requires the knowledge of the IRefCheck interface for the caller to access the Value and implicit operators are not available for classes (or interfaces) I tried it with an record, so it can be used like your string function before:

  TRefCheckRec = record
  private
    RefCheck: IRefCheck;
    function AsString: string;
  public
    class operator Implicit(Value: TRefCheckRec): string;
    class function CreateNew(S: string): TRefCheckRec; static;
  end;

function TRefCheckRec.AsString: string;
begin
  RefCheck.Value;
end;

class function TRefCheckRec.CreateNew(S: string): TRefCheckRec;
begin
  Result.RefCheck := TRefCheck.Create(S);
end;

class operator TRefCheckRec.Implicit(Value: TRefCheckRec): string;
begin
  Result := Value.AsString;
end;

Your function and the test code then look like this:

function GetEncryptedFileKey(Key: string): TRefCheckRec;
begin
  Result := TRefCheckRec.CreateNew(Key);
end;
procedure Test2;
var
  S: string;
begin
  S := GetEncryptedFileKey('Test Value Record');
  GetEncryptedFileKey('Test Value Record 2');
end;

At the end even with all this, defeating is as easy as never really 'using' S, in fact the test code does exactly that. All fluff and no advantage over

function GetEncryptedFileKey: string;

or

procedure EncryptFile(var EncryptionKey: string);

Design choice

Reading your comments and the question what I believe I would have done is encapsulate your logic into a class, and let your function return an instance of it.

  TEncryptedFile = class
  private
    FEncryptionKey: string;
    FKeyPersisted: Boolean;
  public
    constructor Create;
    destructor Destroy; override;
    function GetEncryptionKey: string;
    procedure SaveEncryptionKeyToFile;
  end;

constructor TEncryptedFile.Create;
begin
  FKeyPersisted := False;
  FEncryptionKey := ...
end;

destructor TEncryptedFile.Destroy;
begin
  if not FKeyPersisted then
    SaveEncryptionKeyToFile;
  inherited Destroy;
end;

function TEncryptedFile.GetEncryptionKey: string;
begin
  Result := FEncryptionKey;
  FKeyPersisted := True;
end;

procedure TEncryptedFile.SaveEncryptionKeyToFile;
begin
  FKeyPersisted := True;
  // Save to file
  ...
end;

Your function now returns an instance of it, caller is responsible for clean-up, as indicated by function name.

  function CreateEncryptedFile: TEncryptedFile;
  begin
    Result := TEncryptedFile.Create;
  end;

Whether he decides to access your key directly or save it to a file is up to him. If he cleans up the instance and none of both is done already, the key is automatically saved.


问:
Using (DR)STRACE to compare Windows program execution
I'm posing a question here directly in relation to this issue on github for node-serialport. In a nutshell something that used to work fine in v4.x of the library no longer works in v6.x of the library. I think it must have something to do with how the library is opening the COM port (options or something), and I suspect its artificially limiting the power delivered over USB in the current version of the library.

I wrote the simplest scripts that I could to reproduce the problem (scripts posted in the issue) using:

NodeJS and v4.x of the library [works]

NodeJS and v6.x of the library [fails]

Python and PySerial equivalent [works]

Following through on a recommendation by the repository maintainer, I researched and found a utility for windows called drstrace that allowed me to capture logs of the execution of each of these scripts executing for a period of time (these logs are posted as attachments in the referenced issue).

Now I'm stuck, as I don't know how to make heads or tails of the drstrace logs, though I feel confident that the difference is probably evident in comparing the three files. I just don't know enough about how to read the drstrace logs and windows drivers and system calls to break through.

I realized posting this question here is something of an act of desperation, but I figure it's worth a shot. Hopefully it is clear that I've not lacked in effort pursuing this on my own, I'm just over my head at this point, and could use help getting further. Any guidance would be appreciated. Most awesome would be someone who is versed in this level of diagnostics giving it a look and reading the tea leaves. It would be great to contribute back to such an important open source library.

Update 2017 Nov 10

I reached out to FTDI support asking:

I use the FT231X in many of my products. I need some help with
  understanding how the Windows FTDI driver manages power. More to the
  point, I'm hoping you can help me understand how to direct the driver
  to allow the full 500mA allowed by USB to be delivered to my product
  by a Windows computer.

The reply was:

Just use our FT_Prog utility to set the max VBUS current to 500
  mA:

This drive current becomes available after the FT231X enumerates.

I haven't tried this advice yet, but I wanted to share it with anyone reading this. The fact remains that node-serialport 6.0.4 behavior differs from both node-serialport 4.0.7 behavior and pyserial behavior.

答:
Here is an alternative theory you could look into:

Windows interacting with V6.x might be interacting with the flow control settings differently, which might be causing your device to respond with an unexpected state causing your test to fail.


问:
HTML/CSS/JavaScript LaTeX algorithm for word spacing
I would like to know if there is a way to integrate the LaTeX word spacing algorithm in a website? I'm not talking about equations.

To better illustrate what I mean, look at thr picture. Above is a normal justify and below is a valuable word spacing with LaTeX.

justify vs. LaTeX

Any ideas?

答:
Yes, there is, using JavaScript: https://github.com/bramstein/typeset

Whether you want to use it in production is a different question.


问:
Type mismatch-problems in java card/deck-classes
I'm trying to solve the playing cards-exercises in the Oracle-Java tutorial:

```<code>public class CardClass {
    public static String suit;
    public static String rank;
    final String[] suits = {"cloves","hearts","spades","diamonds"};
    final String[] ranks = {"Ace","2","3","4","5","6","7","8","9","Jack","Queen","King"};

    public CardClass(int suit, int rank) {
        // TODO Auto-generated constructor stub
        CardClass.suit = suits[suit];
        CardClass.rank = ranks[rank];
    }

    public static void printCard() {
        System.out.println("The card's suit is: " + suit + " and the card's rank is: " + rank);

    }

    public static void main(String[] args) {
        new CardClass(1,1);
        printCard();
    }
}
</code>```

and

```<code>public class DeckClass{
    public static String[][] deck;

    public DeckClass() {
        // TODO Auto-generated constructor stub
        for(int i=0; i<4;i++) {
            for(int j=0; j<13; j++)
            deck[i][j]= new CardClass(i,j);
        }
    }

    public static void printDeck() {
        for(String a: deck["hearts"]) {
        System.out.println("In hearts the deck contains:"+ a);
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new DeckClass();
        printDeck();
    }
}
</code>```

And I get the following errors:

Type mismatch: cannot convert from CardClass to String in
      deck[i][j]= new CardClass(i,j);

Type mismatch: Cannot convert from String to int in
      for(String a: deck["hearts"]) {

What to do? I am pretty a newbie at this and only could think of choosing a certain suit to print out the cards in the two-dimensional array, so i chose hearts.

答:
In your constructor for DeckClass you are trying to assign an instance of the CardClass class to an array of String. In order for that code to work, you need to change deck to array of CardClass.

For your printDeck method, you cannot access an index in a primitive array with a String. You must use an int value. For instance to access the 3 of hearts (assuming your constructor is working) I would use:

final CardClass fourOfHearts = deck[1][3];

Check out the Array Access section of this doc:
https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html

Body:
I'm trying to solve the playing cards-exercises in the Oracle-Java tutorial:

public class CardClass {
    public static String suit;
    public static String rank;
    final String[] suits = {"cloves","hearts","spades","diamonds"};
    final String[] ranks = {"Ace","2","3","4","5","6","7","8","9","Jack","Queen","King"};

    public CardClass(int suit, int rank) {
        // TODO Auto-generated constructor stub
        CardClass.suit = suits[suit];
        CardClass.rank = ranks[rank];
    }

    public static void printCard() {
        System.out.println("The card's suit is: " + suit + " and the card's rank is: " + rank);

    }

    public static void main(String[] args) {
        new CardClass(1,1);
        printCard();
    }
}

and

public class DeckClass{
    public static String[][] deck;

    public DeckClass() {
        // TODO Auto-generated constructor stub
        for(int i=0; i<4;i++) {
            for(int j=0; j<13; j++)
            deck[i][j]= new CardClass(i,j);
        }
    }

    public static void printDeck() {
        for(String a: deck["hearts"]) {
        System.out.println("In hearts the deck contains:"+ a);
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new DeckClass();
        printDeck();
    }
}

And I get the following errors:

Type mismatch: cannot convert from CardClass to String in
      deck[i][j]= new CardClass(i,j);

Type mismatch: Cannot convert from String to int in
      for(String a: deck["hearts"]) {

What to do? I am pretty a newbie at this and only could think of choosing a certain suit to print out the cards in the two-dimensional array, so i chose hearts.


问:
Why does C manage the heap, instead of the operating system?
In other words, why doesn't free() just return the memory to the operating system, and malloc simply request memory from the operating system?

This unpacks to three closely related questions:

Why does C need to manage its own heap? (Is it because the OS will only allow you to allocate and free contiguous memory of a minimum size?)

Assuming what I wrote in parentheses is true, why is it?

Can this problem affect the operating system itself, so that it's unable to allocate blocks of memory to any running processes?

答:
Actually it is left for the implementation. The question :

why doesn't free() just return the memory to the operating system, and
  malloc simply request memory from the operating system?

is wrong as nothing stops the implementation from doing it. So there is no answer for this question - every implementation can be potentially different (it only has to be standard compliant)

ContentLicense: CC BY-SA 4.0


问:
Force Windows Batch Script Return Code 0
A vendor has provided us with a Windows Batch script that needs to have a return code of 0.

Per that vendor, there are safe to ignore messages being printed by the script.

The scripts are used for quiescing the application for a proper backup. Our backup software requires a return code of 0.

How can I do this?

答:
adding a line to the end of the script

```<code>Ver > nul
</code>```

should do the trick

Body:
adding a line to the end of the script

Ver > nul

should do the trick


问:
Multiple filter condition in Spark Filter method
How to write multiple case in filter() method in spark using scala like, I have an Rdd of cogroup

```<code>(1,(CompactBuffer(1,john,23),CompactBuffer(1,john,24)).filter(x => (x._2._1 != x._2._2))//value not equal
(2,(CompactBuffer(),CompactBuffer(2,Arun,24)).filter(x => (x._2._1==null))//Second tuple first value is null
(3,(CompactBuffer(3,kumar,25),CompactBuffer()).filter(x => (x._2._2==null))//Second tuple second value is null

val a = source_primary_key.cogroup(destination_primary_key).filter(x => (x._2._1 != x._2._2))

val c=  a.map { y =>

    val key = y._1
    val value = y._2

    srcs = value._1.mkString(",")
    destt = value._2.mkString(",")

    if (srcs.equalsIgnoreCase(destt) == false) {
      srcmis :+= srcs
      destmis :+= destt
    }

    if (srcs == "") {
      extraindest :+= destt.mkString("")
    }

    if (destt == "") {
      extrainsrc :+= srcs.mkString("")
    }

}
</code>```

How to store each condition in 3 different Array[String]

I tried like above but seems naive, is there anyway way we can do it efficiently ?

答:
You can use collect on your RDD and then toList  .
Example :

```<code>(1,(CompactBuffer(1,john,23),CompactBuffer(1,john,24)).filter(x => (x._2._1 != x._2._2)).collect().toList
</code>```

Body:
How to write multiple case in filter() method in spark using scala like, I have an Rdd of cogroup

(1,(CompactBuffer(1,john,23),CompactBuffer(1,john,24)).filter(x => (x._2._1 != x._2._2))//value not equal
(2,(CompactBuffer(),CompactBuffer(2,Arun,24)).filter(x => (x._2._1==null))//Second tuple first value is null
(3,(CompactBuffer(3,kumar,25),CompactBuffer()).filter(x => (x._2._2==null))//Second tuple second value is null

val a = source_primary_key.cogroup(destination_primary_key).filter(x => (x._2._1 != x._2._2))

val c=  a.map { y =>

    val key = y._1
    val value = y._2

    srcs = value._1.mkString(",")
    destt = value._2.mkString(",")

    if (srcs.equalsIgnoreCase(destt) == false) {
      srcmis :+= srcs
      destmis :+= destt
    }

    if (srcs == "") {
      extraindest :+= destt.mkString("")
    }

    if (destt == "") {
      extrainsrc :+= srcs.mkString("")
    }

}

How to store each condition in 3 different Array[String]

I tried like above but seems naive, is there anyway way we can do it efficiently ?

Body:
You can use collect on your RDD and then toList  .
Example :

(1,(CompactBuffer(1,john,23),CompactBuffer(1,john,24)).filter(x => (x._2._1 != x._2._2)).collect().toList


问:
Aligning an image with text
I'm creating a very basic placeholder site. Centered, in the middle of the page, it should read:

(COMPANY LOGO) WEBSITE COMING IN 2018

The company logo uses the same font as the text.

By default the image sits alongside the text nicely, however this changes when I attempt to align it centrally.

body {
  background-color: #fff;
  background-size: cover;
  text-align: center;
}

img {
  float: left;
  width: 350px;
}

h1 {
  position: relative;
  top: 18px;
  left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="header">
    <img src="http://via.placeholder.com/350x100" alt="logo" />
    <h1>WEBSITE COMING IN 2018</h1>
  </div>
</body></code>```

What would be the most effective way to do this?

答:
You could approach this using flexbox

body {
  background-color: #fff;
  background-size: cover;
  /* added */
  margin: 0;
  height: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.header {
  display: flex;
  text-align: center;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="header">
    <img src="http://via.placeholder.com/350x100" alt="logo" />
    <h1>WEBSITE COMING IN 2018</h1>
  </div>
</body></code>```

Title: Aligning an image with text

Body:
I'm creating a very basic placeholder site. Centered, in the middle of the page, it should read:

(COMPANY LOGO) WEBSITE COMING IN 2018

The company logo uses the same font as the text.

By default the image sits alongside the text nicely, however this changes when I attempt to align it centrally.

body {
  background-color: #fff;
  background-size: cover;
  text-align: center;
}

img {
  float: left;
  width: 350px;
}

h1 {
  position: relative;
  top: 18px;
  left: 10px;
}

WEBSITE COMING IN 2018

What would be the most effective way to do this?

Body:
You could approach this using flexbox

body {
  background-color: #fff;
  background-size: cover;
  /* added */
  margin: 0;
  height: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.header {
  display: flex;
  text-align: center;
  align-items: center;
}

<body>
  <div class="header">
    <img src="http://via.placeholder.com/350x100" alt="logo" />
    <h1>WEBSITE COMING IN 2018</h1>
  </div>
</body>