问:
Regular Expressions to Display Messages from a Text Log File
I'm trying to figure out how to use regular expressions to condense and sort the information I'm getting from this code. Here's the code and I'll explain as I go:

```<code>import java.io.*;
import java.util.*;

public class baseline
{

// Class level variables
   static Scanner sc = new Scanner(System.in);

   public static void main(String[] args) throws IOException,
   FileNotFoundException { // Start of main

   // Variables
   String filename;

   // Connecting to the output file with a buffer
   PrintWriter outFile = new PrintWriter(
                          new BufferedWriter(
                           new FileWriter("chatOutput.log")));

   // Get the input file
   System.out.print("Please enter full name of the file: ");
   filename = sc.next();

   // Assign the name of the input file to a file object
   File log = new File(filename);
   String textLine = null; // Null
   String outLine = "";    // Null
   BufferedWriter bw = null;

  try
  {
  // assigns the input file to a filereader object
     BufferedReader infile = new BufferedReader(new FileReader(log));

      sc = new Scanner(log);
            while(sc.hasNext())
            {
                String line=sc.nextLine();
                if(line.contains("LANTALK"))
                    System.out.println(line);
            } // End of while

  try
   {
     // Read data from the input file
    while((textLine = infile.readLine()) != null)
     {
    // Print to output file
    outLine = textLine;
    sc = new Scanner (outLine);
          while(sc.hasNext())
          {
               String line=sc.nextLine();
               if(line.contains("LANTALK"))
                    outFile.printf("%s\n",outLine);
          }// end of while
      } // end of while
    } // end of try

   finally  // This gets executed even when an exception is thrown
      {
    infile.close();
    outFile.close();
      } // End of finally
    } // End of try

  catch (FileNotFoundException nf) // Goes with first try
  {
   System.out.println("The file \""+log+"\" was not found");
  } // End of catch
  catch (IOException ioex) // Goes with second try
  {
   System.out.println("Error reading the file");
  } // End of catch

 } // end of main

} // end of class
</code>```

So I'm reading an input file, getting only the lines that display "LANTALK", and printing them out to another file. And here is a sample of what the output looks like so far:

```<code>14:29:39.731 [D] [T:000FEC] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>922</MBXID><MBXTO>5608</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>It is mailing today right?
</MSGTEXT>
14:41:33.703 [D] [T:000FF4] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>929</MBXID><MBXTO>5601</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>Either today or tomorrow -
still waiting to hear. </MSGTEXT>
</code>```

And what I need is to get all of the characters between <MSGTEXT> and </MSGTEXT> to be able to display the message cleanly. How should I write this into the code to repeat with every "LANTALK" line and still write out correctly? Thanks!

答:
You can find MSGTEXT using a regex:

```<code><MSGTEXT>(.*?)</MSGTEXT>
</code>```

However, some of the messages contain newlines, which makes this a bit more difficult.

One way to get past this is to read the entire file into a String, and then look for matches.

```<code>try {
    String text = new String(Files.readAllBytes(Paths.get(log)));
    Matcher m = Pattern.compile("<MSGTEXT>(.*?)</MSGTEXT>", Pattern.DOTALL).matcher(text);
    while (m.find()) {
        System.out.println("Message: " + m.group(1));
    }
} catch (IOException e) {
    //Handle exception
}
</code>```

Console output:

```<code>Message: It is mailing today right?

Message: Either today or tomorrow -
still waiting to hear.
</code>```

Keep in mind that if you are dealing with large log files this approach could use a lot of memory.

Also note that parsing XML with regex is generally considered a bad idea; it works fine for now, but if you plan on doing anything more complicated you should use an XML parser as others have suggested.

Body:
I'm trying to figure out how to use regular expressions to condense and sort the information I'm getting from this code. Here's the code and I'll explain as I go:

import java.io.*;
import java.util.*;

public class baseline
{

// Class level variables
   static Scanner sc = new Scanner(System.in);

   public static void main(String[] args) throws IOException,
   FileNotFoundException { // Start of main

   // Variables
   String filename;

   // Connecting to the output file with a buffer
   PrintWriter outFile = new PrintWriter(
                          new BufferedWriter(
                           new FileWriter("chatOutput.log")));

   // Get the input file
   System.out.print("Please enter full name of the file: ");
   filename = sc.next();

   // Assign the name of the input file to a file object
   File log = new File(filename);
   String textLine = null; // Null
   String outLine = "";    // Null
   BufferedWriter bw = null;

  try
  {
  // assigns the input file to a filereader object
     BufferedReader infile = new BufferedReader(new FileReader(log));

      sc = new Scanner(log);
            while(sc.hasNext())
            {
                String line=sc.nextLine();
                if(line.contains("LANTALK"))
                    System.out.println(line);
            } // End of while

  try
   {
     // Read data from the input file
    while((textLine = infile.readLine()) != null)
     {
    // Print to output file
    outLine = textLine;
    sc = new Scanner (outLine);
          while(sc.hasNext())
          {
               String line=sc.nextLine();
               if(line.contains("LANTALK"))
                    outFile.printf("%s\n",outLine);
          }// end of while
      } // end of while
    } // end of try

   finally  // This gets executed even when an exception is thrown
      {
    infile.close();
    outFile.close();
      } // End of finally
    } // End of try

  catch (FileNotFoundException nf) // Goes with first try
  {
   System.out.println("The file \""+log+"\" was not found");
  } // End of catch
  catch (IOException ioex) // Goes with second try
  {
   System.out.println("Error reading the file");
  } // End of catch

 } // end of main

} // end of class

So I'm reading an input file, getting only the lines that display "LANTALK", and printing them out to another file. And here is a sample of what the output looks like so far:

14:29:39.731 [D] [T:000FEC] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>922</MBXID><MBXTO>5608</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>It is mailing today right?
</MSGTEXT>
14:41:33.703 [D] [T:000FF4] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>929</MBXID><MBXTO>5601</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>Either today or tomorrow -
still waiting to hear. </MSGTEXT>

And what I need is to get all of the characters between <MSGTEXT> and </MSGTEXT> to be able to display the message cleanly. How should I write this into the code to repeat with every "LANTALK" line and still write out correctly? Thanks!

Body:
You can find MSGTEXT using a regex:

<MSGTEXT>(.*?)</MSGTEXT>

However, some of the messages contain newlines, which makes this a bit more difficult.

One way to get past this is to read the entire file into a String, and then look for matches.

try {
    String text = new String(Files.readAllBytes(Paths.get(log)));
    Matcher m = Pattern.compile("<MSGTEXT>(.*?)</MSGTEXT>", Pattern.DOTALL).matcher(text);
    while (m.find()) {
        System.out.println("Message: " + m.group(1));
    }
} catch (IOException e) {
    //Handle exception
}

Console output:

Message: It is mailing today right?

Message: Either today or tomorrow -
still waiting to hear.

Keep in mind that if you are dealing with large log files this approach could use a lot of memory.

Also note that parsing XML with regex is generally considered a bad idea; it works fine for now, but if you plan on doing anything more complicated you should use an XML parser as others have suggested.


来源: stackexchange

问:
404 error when parsing URL using jsoup
I am getting a 404 error when using Jsoup. The call is Document doc = Jsoup.parse(url, 30000) and the URL string is http://www.myland.co.il/%D7%9E%D7%97%D7%A9%D7%91-%D7%94%D7%A9%D7%A7%D7%99%D7%94
and the URL displays fine in Chrome. The error I am getting is java.io.IOException: 404 error loading URL http://www.myland.co.il/vmchk/×××©×-××©×§××

Any ideas?

答:
try decodeURL()

```<code>String url = "http://www.myland.co.il/%D7%9E%D7%97%D7%A9%D7%91-%D7%94%D7%A9%D7%A7%D7%99%D7%94";
Document doc = Jsoup.connect(url.decodeURL()).get();
</code>```

ContentLicense: CC BY-SA 3.0

Title: 404 error when parsing URL using jsoup

Body:
try decodeURL()

String url = "http://www.myland.co.il/%D7%9E%D7%97%D7%A9%D7%91-%D7%94%D7%A9%D7%A7%D7%99%D7%94";
Document doc = Jsoup.connect(url.decodeURL()).get();


问:
Libraries for Choosing Color?
Do any open source libraries exist for programatically selecting and rating the compatibility of sets of colors using color theory?

It would be very useful to be able to select color palettes based on simple color harmony rules like complimentary, analogous, triadic, and tetradic colors.

答:
I just found this: Harmonies theory and math.

Also of interest is the rest of the EasyRGB site, which will explain how to do RGB to HSV, etc.

While it's not source code, it's the formulas for calculating the values.

Also interesting: "Color Jack"

OwnerDisplayName: maxhawkins

ContentLicense: CC BY-SA 2.5

Title: Libraries for Choosing Color?

OwnerDisplayName: Travis


问:
addEventListener ('click', ...) By clicking on 'numbers' button text on the display should be equal to that number
I am trying to build a javascript calculator as per freecodecamp requirement on front end track.

Codepen link: https://codepen.io/ekilja01/pen/MoXROe

By pressing any number on calculator the display must be changed to that number. Also the var number has to remember its value, because by clicking the number again it becomes a new number, so after that I can use operators and parseInt to evaluate and display the final value.  I've got an idea how can this be implemented by using jQuery, so something like this:

```<code>   $("#numbers a").not("#clear,#clearall").click(function(){
        number += $(this).text();
        totaldiv.text(number);

    });
    $("#operators a").not("#equals").click(function(){
        operator = $(this).text();
        newnumber = number;
        number = "";
        totaldiv.text("0");
    });
    $("#clear,#clearall").click(function(){
        number = "";
        totaldiv.text("0");
        if ($(this).attr("id") === "clearall") {
            newnumber = "";
        }
    });
    //Add your last .click() here!
    $("#equals").click(function(){
        if (operator === "+"){
            number = (parseInt(number, 10) + parseInt(newnumber,10)).toString(10);
        } else if (operator === "-"){
            number = (parseInt(newnumber, 10) - parseInt(number,10)).toString(10);
        } else if (operator === "÷"){
            number = (parseInt(newnumber, 10) / parseInt(number,10)).toString(10);
        } else if (operator === "×"){
            number = (parseInt(newnumber, 10) * parseInt(number,10)).toString(10);
        }
        totaldiv.text(number);
        number = "";
        newnumber = "";
    });
</code>```

But what can be equivalent to this in vanilla js? I've tried .textContent or .innerHTML, but neither of them work. On calculator's dispay either undefined or 1 ... AC. Also what is the equivalent to .not(). Any help will be much appreciated.

html:

```<code><div id="calculator">
          <p id="cal">CALCULATOR</p>
          <div id="total">
          </div>
          <div id="operators">
              <a>÷</a>
              <a>×</a>
              <a>+</a>
              <a>-</a>
              <a>=</a>
          </div>
          <div id="numbers">
              <a>1</a>
              <a>2</a>
              <a>3</a>
              <a>4</a>
              <a>5</a>
              <a>6</a>
              <a>7</a>
              <a>8</a>
              <a>9</a>
              <a id="clear">C</a>
              <a>0</a>
              <a id="clearall">AC</a>
          </div>
      </div>
</code>```

js:

```<code>document.addEventListener('DOMContentLoaded', function (event) {
    console.log('DOM OK');

    // Declare variables for number, new number and operators

    var number, newNumber, operator = "";

    // Declare variable total number to display total on the calculator's display

    var totalNumber = document.getElementById("total");
    totalNumber.textContent = "0";

    document.getElementById("numbers").addEventListener('click', function(){
        number += this.textContent;
        totalNumber.textContent = number;
    })

})
</code>```

答:
You may want to use the event argument in the callback function. For example:

```<code> number  = "";

document.getElementById("numbers").addEventListener('click', function(e){
    number += e.target.textContent;
    totalNumber.textContent = number;
})
</code>```

More information on the event target properties specifically:
https://developer.mozilla.org/en-US/docs/Web/API/Event/target

Entire JS code:

```<code> document.addEventListener('DOMContentLoaded', function (event) {
 console.log('DOM OK');

// Declare variables for number, new number and operators

var number, newNumber, operator = "";

// Declare variable total number to display total on the calculator's display

var totalNumber = document.getElementById("total");
totalNumber.textContent = "0";

number  = "";

document.getElementById("numbers").addEventListener('click', function(e){
 number += e.target.textContent;
 totalNumber.textContent = number;
})

})
</code>```

Body:
I am trying to build a javascript calculator as per freecodecamp requirement on front end track.

Codepen link: https://codepen.io/ekilja01/pen/MoXROe

By pressing any number on calculator the display must be changed to that number. Also the var number has to remember its value, because by clicking the number again it becomes a new number, so after that I can use operators and parseInt to evaluate and display the final value.  I've got an idea how can this be implemented by using jQuery, so something like this:

   $("#numbers a").not("#clear,#clearall").click(function(){
        number += $(this).text();
        totaldiv.text(number);

    });
    $("#operators a").not("#equals").click(function(){
        operator = $(this).text();
        newnumber = number;
        number = "";
        totaldiv.text("0");
    });
    $("#clear,#clearall").click(function(){
        number = "";
        totaldiv.text("0");
        if ($(this).attr("id") === "clearall") {
            newnumber = "";
        }
    });
    //Add your last .click() here!
    $("#equals").click(function(){
        if (operator === "+"){
            number = (parseInt(number, 10) + parseInt(newnumber,10)).toString(10);
        } else if (operator === "-"){
            number = (parseInt(newnumber, 10) - parseInt(number,10)).toString(10);
        } else if (operator === "÷"){
            number = (parseInt(newnumber, 10) / parseInt(number,10)).toString(10);
        } else if (operator === "×"){
            number = (parseInt(newnumber, 10) * parseInt(number,10)).toString(10);
        }
        totaldiv.text(number);
        number = "";
        newnumber = "";
    });

But what can be equivalent to this in vanilla js? I've tried .textContent or .innerHTML, but neither of them work. On calculator's dispay either undefined or 1 ... AC. Also what is the equivalent to .not(). Any help will be much appreciated.

html:

CALCULATOR

              ÷
              ×
              +
              -
              =

              1
              2
              3
              4
              5
              6
              7
              8
              9
              C
              0
              AC

js:

document.addEventListener('DOMContentLoaded', function (event) {
    console.log('DOM OK');

    // Declare variables for number, new number and operators

    var number, newNumber, operator = "";

    // Declare variable total number to display total on the calculator's display

    var totalNumber = document.getElementById("total");
    totalNumber.textContent = "0";

    document.getElementById("numbers").addEventListener('click', function(){
        number += this.textContent;
        totalNumber.textContent = number;
    })

})

Body:
You may want to use the event argument in the callback function. For example:

 number  = "";

document.getElementById("numbers").addEventListener('click', function(e){
    number += e.target.textContent;
    totalNumber.textContent = number;
})

More information on the event target properties specifically:
https://developer.mozilla.org/en-US/docs/Web/API/Event/target

Entire JS code:

 document.addEventListener('DOMContentLoaded', function (event) {
 console.log('DOM OK');

// Declare variables for number, new number and operators

var number, newNumber, operator = "";

// Declare variable total number to display total on the calculator's display

var totalNumber = document.getElementById("total");
totalNumber.textContent = "0";

number  = "";

document.getElementById("numbers").addEventListener('click', function(e){
 number += e.target.textContent;
 totalNumber.textContent = number;
})

})


问:
Polymorphic association: NoMethodError
NoMethodError in PostsController#create
undefined method `posts' for nil:NilClass

Posts#controller

```<code>class PostsController < ApplicationController
    # before_action :logged_in_user, only: [:create, :destroy]
    before_action :correct_user,   only: :destroy
    before_action :find_postable, except: [:index]

    def index
        @posts = Post.all.order('created_at DESC')
    end

    def new
        @post = Post.new
    end

    def create
        @post = @postable.posts.new post_params
        if @post.save
            redirect_to :back, notice: 'Your comment was successfully posted!'
        else
            redirect_to :back, notice: "Your comment wasn't posted!"
        end
    end

    def destroy
        Post.find(params[:id]).destroy
        redirect_to posts_path#, notice: "Post successfully deleted"
    end

    def edit
        @post = Post.find(params[:id])
    end

    def update
        @post = Post.find(params[:id])
        if @post.update_attributes(student_params)
            redirect_to post_path
        else
            redirect_to edit_post_path
        end
    end

    def show
        @post = Post.find (params[:id])
    end

    private

    def post_params
      params.require(:post).permit(:content, :image, :document, :audio, :video, :classroom_id)
    end

    def correct_user
      @post = current_user.posts.find_by(id: params[:id])
      redirect_to root_url if @post.nil?
    end

    def find_postable
      @postable = Post.find_by_id(params[:post_id]) if params[:post_id]
      @postable = Classroom.find_by_id(params[:classroom_id]) if params[:classroom_id]
    end
</code>```

Here is the post model

```<code>class Post < ActiveRecord::Base
  belongs_to :user

  belongs_to :classroom

  belongs_to :postable, polymorphic: true
  has_many :posts, as: :postable
end
</code>```

Here is the classroom model (it belongs to the class and this is selected in the new post form"

```<code>class Classroom < ActiveRecord::Base
  has_many :posts, as: :postable
  belongs_to :teachers
  # belongs_to :students
</code>```

Posts in Schema.rb

```<code>create_table "posts", force: :cascade do |t|
    t.text     "content"
    t.integer  "user_id"
    t.datetime "created_at",            null: false
    t.datetime "updated_at",            null: false
    t.integer  "classroom_id"
    t.integer  "postable_id"
    t.string   "postable_type"
  end
</code>```

I've tried many things with no success, I'm not quite sure why I'm getting this error. I'm following a video and trying to apply it to my existing post model but am still having trouble. Thanks

New Post Form:

```<code><%= form_for :post, html: { multipart: true, class: "post-form" }, url: posts_path do |f| %>

  <h4>Choose a Classroom</h4>
  <div class="form-group">
    <%= f.collection_select :classroom_id, current_user.classrooms, :id, :name %>
  </div>
  <h4>Write a post</h4>
  <div class="form-group">
    <%= f.text_area :content, class: "form-control" %>
  </div>
  <h4>Attach Files</h4>
  <div class="form-group">
    <%= f.file_field :image %>
  </div>
  <%= f.submit "Add Post", class: "btn btn-primary" %>
<% end %>
</code>```

For a post reply

```<code><li>
  <%= post.content %> -

  <%= form_for [post, Post.new] do |f| %>
      <%= f.text_area :content, placeholder: "Add a Reply" %><br/>
      <%= f.submit "Reply"  %>
      <% end %>

</li>
</code>```

答:
The error is in find_postable method, specifically in this line:

```<code>@postable = Classroom.find_by_id(params[:classroom_id]) if params[:classroom_id]
</code>```

You are trying to fetch classroom_id from params (i.e. params[:classroom_id]) but that key (classroom_id) exists within post key in your parameters hash:

```<code>Parameters: {
  "utf7"=>"✓",
  "authenticity_token"=>"bunchofletters==",
  "post"=>{
    "classroom_id"=>"1",
    "content"=>"hello"
  },
  "commit"=>"Add Post"
}
</code>```

To fix this, change params[:classroom_id] to params[:post][:classroom_id] in find_postable method:

```<code>def find_postable
  @postable = Post.find_by_id(params[:post_id]) if params[:post_id]
  @postable = Classroom.find_by_id(params[:post][:classroom_id]) if params[:classroom_id]
end
</code>```

Title: Polymorphic association: NoMethodError

Body:
NoMethodError in PostsController#create
undefined method `posts' for nil:NilClass

Posts#controller

class PostsController < ApplicationController
    # before_action :logged_in_user, only: [:create, :destroy]
    before_action :correct_user,   only: :destroy
    before_action :find_postable, except: [:index]

    def index
        @posts = Post.all.order('created_at DESC')
    end

    def new
        @post = Post.new
    end

    def create
        @post = @postable.posts.new post_params
        if @post.save
            redirect_to :back, notice: 'Your comment was successfully posted!'
        else
            redirect_to :back, notice: "Your comment wasn't posted!"
        end
    end

    def destroy
        Post.find(params[:id]).destroy
        redirect_to posts_path#, notice: "Post successfully deleted"
    end

    def edit
        @post = Post.find(params[:id])
    end

    def update
        @post = Post.find(params[:id])
        if @post.update_attributes(student_params)
            redirect_to post_path
        else
            redirect_to edit_post_path
        end
    end

    def show
        @post = Post.find (params[:id])
    end

    private

    def post_params
      params.require(:post).permit(:content, :image, :document, :audio, :video, :classroom_id)
    end

    def correct_user
      @post = current_user.posts.find_by(id: params[:id])
      redirect_to root_url if @post.nil?
    end

    def find_postable
      @postable = Post.find_by_id(params[:post_id]) if params[:post_id]
      @postable = Classroom.find_by_id(params[:classroom_id]) if params[:classroom_id]
    end

Here is the post model

class Post < ActiveRecord::Base
  belongs_to :user

  belongs_to :classroom

  belongs_to :postable, polymorphic: true
  has_many :posts, as: :postable
end

Here is the classroom model (it belongs to the class and this is selected in the new post form"

class Classroom < ActiveRecord::Base
  has_many :posts, as: :postable
  belongs_to :teachers
  # belongs_to :students

Posts in Schema.rb

create_table "posts", force: :cascade do |t|
    t.text     "content"
    t.integer  "user_id"
    t.datetime "created_at",            null: false
    t.datetime "updated_at",            null: false
    t.integer  "classroom_id"
    t.integer  "postable_id"
    t.string   "postable_type"
  end

I've tried many things with no success, I'm not quite sure why I'm getting this error. I'm following a video and trying to apply it to my existing post model but am still having trouble. Thanks

New Post Form:

<%= form_for :post, html: { multipart: true, class: "post-form" }, url: posts_path do |f| %>

Choose a Classroom

    <%= f.collection_select :classroom_id, current_user.classrooms, :id, :name %>

Write a post

    <%= f.text_area :content, class: "form-control" %>

Attach Files

    <%= f.file_field :image %>

  <%= f.submit "Add Post", class: "btn btn-primary" %>
<% end %>

For a post reply

  <%= post.content %> -

  <%= form_for [post, Post.new] do |f| %>
      <%= f.text_area :content, placeholder: "Add a Reply" %>

      <%= f.submit "Reply"  %>
      <% end %>

Body:
The error is in find_postable method, specifically in this line:

@postable = Classroom.find_by_id(params[:classroom_id]) if params[:classroom_id]

You are trying to fetch classroom_id from params (i.e. params[:classroom_id]) but that key (classroom_id) exists within post key in your parameters hash:

Parameters: {
  "utf7"=>"✓",
  "authenticity_token"=>"bunchofletters==",
  "post"=>{
    "classroom_id"=>"1",
    "content"=>"hello"
  },
  "commit"=>"Add Post"
}

To fix this, change params[:classroom_id] to params[:post][:classroom_id] in find_postable method:

def find_postable
  @postable = Post.find_by_id(params[:post_id]) if params[:post_id]
  @postable = Classroom.find_by_id(params[:post][:classroom_id]) if params[:classroom_id]
end


问:
How to run the python script in batches?
I am looking for a solution to run the python command for a set of data in batches. For example, i want to run the below mentioned code for the first 10 rows,print output and run for the next batch until the row ends. Reason for doing this is that currently it is taking a lot of time to run 1000 rows.

Trying to use concurrent.futures.ProcessPoolExecutor but it is of no help. Is there a better way to do this?

here is the code:

```<code>import os, sys
import xlwt
import numpy

import tensorflow as tf
import xlsxwriter
import urllib

filename = "/home/shri/Desktop/tf_files/test1"

def getimg(count):
# open file to read
with open("{0}.csv".format(filename), 'r') as csvfile:
# iterate on all lines
i = 0
for line in csvfile:
    splitted_line = line.split(',')
    # check if we have an image URL
    if splitted_line[1] != '' and splitted_line[1] != "\n":
        urllib.urlretrieve(splitted_line[1], '/home/shri/Desktop/tf_files/images/{0}.jpg'.format (splitted_line[0]))
        print "Image saved for {0}".format(splitted_line[0])
        i += 1
    else:
        print "No result for {0}".format(splitted_line[0])

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

def run_inference(count):
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('output.xlsx')
worksheet = workbook.add_worksheet()
# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0

# search for files in 'images' dir
files_dir = os.getcwd() + '/images'
files = os.listdir(files_dir)

# loop over files, print prediction if it is an image
for f in files:
if f.lower().endswith(('.png', '.jpg', '.jpeg')):
        image_path = files_dir + '/' + f

        # Read in the image_data
        image_data = tf.gfile.FastGFile(image_path, 'rb').read()

        # Loads label file, strips off carriage return
        label_lines = [line.rstrip() for line
                    in tf.gfile.GFile("retrained_labels.txt")]

# Unpersists graph from file
with tf.gfile.FastGFile("retrained_graph.pb", 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        tf.import_graph_def(graph_def, name='')

 with tf.Session() as sess:
    # Feed the image_data as input to the graph and get first prediction
           softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')

           predictions = sess.run(softmax_tensor, \
                              {'DecodeJpeg/contents:0': image_data})

  # Sort to show labels of first highest prediction in order of confidence
  top_k = predictions[0].argsort()[-len(predictions):][::-1]

  for node_id in top_k:
        human_string = label_lines[node_id]
        score = predictions[0][node_id]

        worksheet.write_string(row, 1, image_path)
        worksheet.write(row, 2,  human_string)
        worksheet.write(row, 3, score)
        print(row)
        print(node_id)
        print(image_path)
        print('%s (score = %.5f)' % (human_string, score))
        row +=1

workbook.close()

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as e:
    for i in range(10):
        e.submit(run_inference, i)
</code>```

here is the data in excel sheet

答:
I'd suggest using the GNU Parallel. Create a text file with each line being a command you need to run, eg

```<code>python mycode.py someargs
python mycode.py someotherargs
...
</code>```

Then simply run

```<code>parallel commands.txt -j 8
</code>```

It will bring up 8 (or however many you choose) instances of your script in parallel to process the whole command list.

Body:
I am looking for a solution to run the python command for a set of data in batches. For example, i want to run the below mentioned code for the first 10 rows,print output and run for the next batch until the row ends. Reason for doing this is that currently it is taking a lot of time to run 1000 rows.

Trying to use concurrent.futures.ProcessPoolExecutor but it is of no help. Is there a better way to do this?

here is the code:

import os, sys
import xlwt
import numpy

import tensorflow as tf
import xlsxwriter
import urllib

filename = "/home/shri/Desktop/tf_files/test1"

def getimg(count):
# open file to read
with open("{0}.csv".format(filename), 'r') as csvfile:
# iterate on all lines
i = 0
for line in csvfile:
    splitted_line = line.split(',')
    # check if we have an image URL
    if splitted_line[1] != '' and splitted_line[1] != "\n":
        urllib.urlretrieve(splitted_line[1], '/home/shri/Desktop/tf_files/images/{0}.jpg'.format (splitted_line[0]))
        print "Image saved for {0}".format(splitted_line[0])
        i += 1
    else:
        print "No result for {0}".format(splitted_line[0])

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

def run_inference(count):
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('output.xlsx')
worksheet = workbook.add_worksheet()
# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0

# search for files in 'images' dir
files_dir = os.getcwd() + '/images'
files = os.listdir(files_dir)

# loop over files, print prediction if it is an image
for f in files:
if f.lower().endswith(('.png', '.jpg', '.jpeg')):
        image_path = files_dir + '/' + f

        # Read in the image_data
        image_data = tf.gfile.FastGFile(image_path, 'rb').read()

        # Loads label file, strips off carriage return
        label_lines = [line.rstrip() for line
                    in tf.gfile.GFile("retrained_labels.txt")]

# Unpersists graph from file
with tf.gfile.FastGFile("retrained_graph.pb", 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        tf.import_graph_def(graph_def, name='')

 with tf.Session() as sess:
    # Feed the image_data as input to the graph and get first prediction
           softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')

           predictions = sess.run(softmax_tensor, \
                              {'DecodeJpeg/contents:0': image_data})

  # Sort to show labels of first highest prediction in order of confidence
  top_k = predictions[0].argsort()[-len(predictions):][::-1]

  for node_id in top_k:
        human_string = label_lines[node_id]
        score = predictions[0][node_id]

        worksheet.write_string(row, 1, image_path)
        worksheet.write(row, 2,  human_string)
        worksheet.write(row, 3, score)
        print(row)
        print(node_id)
        print(image_path)
        print('%s (score = %.5f)' % (human_string, score))
        row +=1

workbook.close()

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as e:
    for i in range(10):
        e.submit(run_inference, i)

here is the data in excel sheet

Body:
I'd suggest using the GNU Parallel. Create a text file with each line being a command you need to run, eg

python mycode.py someargs
python mycode.py someotherargs
...

Then simply run

parallel commands.txt -j 8

It will bring up 8 (or however many you choose) instances of your script in parallel to process the whole command list.


问:
writing to columns in same row in csv file (python)
Im trying to write values to a csv file such that for every two iterations, the result is in the same row and then the next the values print to a new row. Any help would be greatly appreciated. Thank you!
This is what I have so far:

```<code>import csv
import math
savePath = '/home/dehaoliu/opencv_test/Engineering_drawings_outputs/'

with open(str(savePath) +'outputsTest.csv','w') as f1:
        writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
        temp = []
 for k in range(0,2):
        temp = []
       for i in range(0,4):
            a = 2 +i
            b = 3+ i
            list = [a,b]
            temp.append(list)
       writer.writerow(temp)
</code>```

The result I am getting now is

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

But I would like to get this (without the brackets) where each number in a row is in a separate column:

```<code>2 3 3 4
4 5 5 6
</code>```

答:
Try the following:

```<code>import csv
import math
savePath = '/home/dehaoliu/opencv_test/Engineering_drawings_outputs/'

with open(str(savePath) +'outputsTest.csv','w') as f1:
        writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
        temp = [2, 3]
        for i in range(2):
            temp = [x + i for x in temp]
            additional = [y+1 for y in temp]
            writer.writerow(temp + additional)
            temp = additional[:]
</code>```

This should return:

```<code># 2    3    3   4
# 4    5    5   6
</code>```

You start with a temporary containing the numbers 2 and 3. Then, you loop from 0 to 2 (excluding). At every iteration, you increment the values of the temporary by the current index and subsequently create an additional list with these new values of your temporary list. Once that's done, you join the two lists together and write the result out to your file. At this point, you can set your temporary list to be equal to the values of the additional list, before moving on to the next iteration.

I hope this helps.

Body:
Im trying to write values to a csv file such that for every two iterations, the result is in the same row and then the next the values print to a new row. Any help would be greatly appreciated. Thank you!
This is what I have so far:

import csv
import math
savePath = '/home/dehaoliu/opencv_test/Engineering_drawings_outputs/'

with open(str(savePath) +'outputsTest.csv','w') as f1:
        writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
        temp = []
 for k in range(0,2):
        temp = []
       for i in range(0,4):
            a = 2 +i
            b = 3+ i
            list = [a,b]
            temp.append(list)
       writer.writerow(temp)

The result I am getting now is

[2 3][3 4][4 5][5 6]
[2 3][3 4][4 5][5 6]

But I would like to get this (without the brackets) where each number in a row is in a separate column:

2 3 3 4
4 5 5 6

Body:
Try the following:

import csv
import math
savePath = '/home/dehaoliu/opencv_test/Engineering_drawings_outputs/'

with open(str(savePath) +'outputsTest.csv','w') as f1:
        writer=csv.writer(f1, delimiter='\t',lineterminator='\n',)
        temp = [2, 3]
        for i in range(2):
            temp = [x + i for x in temp]
            additional = [y+1 for y in temp]
            writer.writerow(temp + additional)
            temp = additional[:]

This should return:

# 2    3    3   4
# 4    5    5   6

You start with a temporary containing the numbers 2 and 3. Then, you loop from 0 to 2 (excluding). At every iteration, you increment the values of the temporary by the current index and subsequently create an additional list with these new values of your temporary list. Once that's done, you join the two lists together and write the result out to your file. At this point, you can set your temporary list to be equal to the values of the additional list, before moving on to the next iteration.

I hope this helps.


问:
Why is the `LIKE` operator not working with integer columns?
I'm trying to receive some ids from my database for an autocomplete search on my CAKEPHP 3.3 site. But my problem is that its only returning the id if I type in the exact id and not part of it.

Here is my function to search the data. The name variable is what is being passed from input.

```<code>public function search()
{
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices->find('all', [
            'conditions' => ['Invoices.id LIKE' => ($name . '%')]
        ]);
        $resultsArr = [];
        foreach ($resultArr as $result)
        {
             $resultsArr[] = ($result['id']);
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);
    }
}
</code>```

For example there is a id in the table '5254' and I type in part of the id '52' nothing is returned but when I type in the whole id '5254' the id is returned.

I'm unsure why this is the case because in my sql query i'm using the percent sign to say any characters after what has been typed into the input.

Here is part of my table

SQL debug when 52 is entered.

```<code>object(Cake\ORM\Query) {

    '(help)' => 'This is a Query object, to get the results execute or iterate it.',
    'sql' => 'SELECT Invoices.id AS `Invoices__id`, Invoices.start_date AS `Invoices__start_date`, Invoices.close_date AS `Invoices__close_date`, Invoices.customer_id AS `Invoices__customer_id`, Invoices.invoice_to_address AS `Invoices__invoice_to_address`, Invoices.ship_to_address AS `Invoices__ship_to_address`, Invoices.customer_contact_id AS `Invoices__customer_contact_id`, Invoices.aircraft_registration_id AS `Invoices__aircraft_registration_id`, Invoices.shipping_company_id AS `Invoices__shipping_company_id`, Invoices.notes AS `Invoices__notes`, Invoices.worksheet_notes AS `Invoices__worksheet_notes`, Invoices.closed AS `Invoices__closed`, Invoices.times_printed AS `Invoices__times_printed`, Invoices.payment_due AS `Invoices__payment_due`, Invoices.GST_rate AS `Invoices__GST_rate`, Invoices.opening_notes AS `Invoices__opening_notes`, Invoices.courier_ticket AS `Invoices__courier_ticket`, Invoices.job_description AS `Invoices__job_description`, Invoices.worksheets_printed AS `Invoices__worksheets_printed`, Invoices.supervising_engineer_id AS `Invoices__supervising_engineer_id`, Invoices.job_type_id AS `Invoices__job_type_id`, Invoices.opened_by_id AS `Invoices__opened_by_id`, Invoices.assigned_to_id AS `Invoices__assigned_to_id`, Invoices.certification_required AS `Invoices__certification_required`, Invoices.currency_id AS `Invoices__currency_id`, Invoices.xero_batch_number AS `Invoices__xero_batch_number`, Invoices.xero_amount AS `Invoices__xero_amount`, Invoices.exchange_rate AS `Invoices__exchange_rate`, Invoices.payment_instructions AS `Invoices__payment_instructions`, Invoices.email AS `Invoices__email`, Invoices.inv_email AS `Invoices__inv_email` FROM invoices Invoices WHERE Invoices.id like :c0',
    'params' => [
        ':c0' => [
            'value' => '52%',
            'type' => 'integer',
            'placeholder' => 'c0'
        ]
</code>```

答:
In this case You can "inject" plain query - array values with numeric index in conditions are treated as plain query, and it will not be parametrized. Be carefull: Typecast to integer is necessary in this case to prevent SQL Injection:

```<code>    $result = $this->Invoinces->find('all' , [
            'conditions' => [
                'id LIKE "'.(int)$input.'%" '
            ]
        ])
    ->toArray();
</code>```

Body:
I'm trying to receive some ids from my database for an autocomplete search on my CAKEPHP 3.3 site. But my problem is that its only returning the id if I type in the exact id and not part of it.

Here is my function to search the data. The name variable is what is being passed from input.

public function search()
{
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices->find('all', [
            'conditions' => ['Invoices.id LIKE' => ($name . '%')]
        ]);
        $resultsArr = [];
        foreach ($resultArr as $result)
        {
             $resultsArr[] = ($result['id']);
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);
    }
}

For example there is a id in the table '5254' and I type in part of the id '52' nothing is returned but when I type in the whole id '5254' the id is returned.

I'm unsure why this is the case because in my sql query i'm using the percent sign to say any characters after what has been typed into the input.

Here is part of my table

SQL debug when 52 is entered.

object(Cake\ORM\Query) {

    '(help)' => 'This is a Query object, to get the results execute or iterate it.',
    'sql' => 'SELECT Invoices.id AS `Invoices__id`, Invoices.start_date AS `Invoices__start_date`, Invoices.close_date AS `Invoices__close_date`, Invoices.customer_id AS `Invoices__customer_id`, Invoices.invoice_to_address AS `Invoices__invoice_to_address`, Invoices.ship_to_address AS `Invoices__ship_to_address`, Invoices.customer_contact_id AS `Invoices__customer_contact_id`, Invoices.aircraft_registration_id AS `Invoices__aircraft_registration_id`, Invoices.shipping_company_id AS `Invoices__shipping_company_id`, Invoices.notes AS `Invoices__notes`, Invoices.worksheet_notes AS `Invoices__worksheet_notes`, Invoices.closed AS `Invoices__closed`, Invoices.times_printed AS `Invoices__times_printed`, Invoices.payment_due AS `Invoices__payment_due`, Invoices.GST_rate AS `Invoices__GST_rate`, Invoices.opening_notes AS `Invoices__opening_notes`, Invoices.courier_ticket AS `Invoices__courier_ticket`, Invoices.job_description AS `Invoices__job_description`, Invoices.worksheets_printed AS `Invoices__worksheets_printed`, Invoices.supervising_engineer_id AS `Invoices__supervising_engineer_id`, Invoices.job_type_id AS `Invoices__job_type_id`, Invoices.opened_by_id AS `Invoices__opened_by_id`, Invoices.assigned_to_id AS `Invoices__assigned_to_id`, Invoices.certification_required AS `Invoices__certification_required`, Invoices.currency_id AS `Invoices__currency_id`, Invoices.xero_batch_number AS `Invoices__xero_batch_number`, Invoices.xero_amount AS `Invoices__xero_amount`, Invoices.exchange_rate AS `Invoices__exchange_rate`, Invoices.payment_instructions AS `Invoices__payment_instructions`, Invoices.email AS `Invoices__email`, Invoices.inv_email AS `Invoices__inv_email` FROM invoices Invoices WHERE Invoices.id like :c0',
    'params' => [
        ':c0' => [
            'value' => '52%',
            'type' => 'integer',
            'placeholder' => 'c0'
        ]

Body:
In this case You can "inject" plain query - array values with numeric index in conditions are treated as plain query, and it will not be parametrized. Be carefull: Typecast to integer is necessary in this case to prevent SQL Injection:

    $result = $this->Invoinces->find('all' , [
            'conditions' => [
                'id LIKE "'.(int)$input.'%" '
            ]
        ])
    ->toArray();


问:
Which constructor should I use for the StringBuilder class?
I'm building a large string from a list of items.  Each item will generate a string which is approximately 200 characters long (plus or minus 100%).

Will I get a (noticeable) performance benefit from using

```<code>Dim sb = New StringBuilder(averageCharacterCount * items.Count)
</code>```

instead of

```<code>Dim sb = New StringBuilder()
</code>```

even if the specified capacity is just a guess?

答: You'll most likely see some improvement, since the class won't have to reallocate and copy its items as many times. You'll have to profile in order to determine how much this will benefit you, but since it's a simple change I don't see a reason not to do it.</p>

Body:
I'm building a large string from a list of items.  Each item will generate a string which is approximately 200 characters long (plus or minus 100%).

Will I get a (noticeable) performance benefit from using

Dim sb = New StringBuilder(averageCharacterCount * items.Count)

instead of

Dim sb = New StringBuilder()

even if the specified capacity is just a guess?


问:
SQL Server: "CREATE DATABASE" query timeout
I have a .Net application that is creating a new database. The current code is working great in development environment and in many production environments. So I am confident the code is fine.

However, we have a specific instance where the user is getting a timeout while the application is running the following SQL Command:

```<code>CREATE DATABASE NameOfDatabase
</code>```

The code is pretty simple, and as you can see it uses the default timeout period for SQL commands which is 30 seconds:

```<code>using (SqlConnection connection = new SqlConnection(connectionString))
{
    string query = "CREATE DATABASE " + databaseName;

    SqlCommand command = new SqlCommand(query, connection);

    connection.Open();
    command.ExecuteNonQuery();
}
</code>```

Note: our log file shows the error occurs on ExecuteNonQuery which suggests that this is NOT a timeout while opening the connection, and rather during query execution.

The specific .Net error is:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

With a line from the stack trace to show my reasoning on it being a command timeout (not a connection timeout):

at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

Note: This error information is obtained using a try/catch around the code which was left out of the question for simplicity as it is not relevant to the problem.

Questions

Under any reasonable (or even uncommon) situations, should a CREATE DATABASE query take this long to run and still be successful?

If it shouldn't take that long, what are the common causes for a timeout? (where should I be looking to debug the problem?)

答:
I do not have enough rep points to comment.  To get the specific error wrap command.ExecuteNonQuery(); in a try catch.  at least you can get the specific error that is occurring.  Also use using with SqlCommand that will dispose that object.  Connection State

```<code>using (SqlConnection connection = new SqlConnection(connectionString))
{
    string query = "CREATE DATABASE " + databaseName;

    using(SqlCommand command = new SqlCommand(query, connection))
    {
        try
        {
            connection.Open();
            if (connection.State == ConnectionState.Open)
                command.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }
    }
}
</code>```

Maybe this TechNet article can help?  Troubleshooting: Timeout Expired

Body:
I have a .Net application that is creating a new database. The current code is working great in development environment and in many production environments. So I am confident the code is fine.

However, we have a specific instance where the user is getting a timeout while the application is running the following SQL Command:

CREATE DATABASE NameOfDatabase

The code is pretty simple, and as you can see it uses the default timeout period for SQL commands which is 30 seconds:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    string query = "CREATE DATABASE " + databaseName;

    SqlCommand command = new SqlCommand(query, connection);

    connection.Open();
    command.ExecuteNonQuery();
}

Note: our log file shows the error occurs on ExecuteNonQuery which suggests that this is NOT a timeout while opening the connection, and rather during query execution.

The specific .Net error is:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

With a line from the stack trace to show my reasoning on it being a command timeout (not a connection timeout):

at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

Note: This error information is obtained using a try/catch around the code which was left out of the question for simplicity as it is not relevant to the problem.

Questions

Under any reasonable (or even uncommon) situations, should a CREATE DATABASE query take this long to run and still be successful?

If it shouldn't take that long, what are the common causes for a timeout? (where should I be looking to debug the problem?)

Body:
I do not have enough rep points to comment.  To get the specific error wrap command.ExecuteNonQuery(); in a try catch.  at least you can get the specific error that is occurring.  Also use using with SqlCommand that will dispose that object.  Connection State

using (SqlConnection connection = new SqlConnection(connectionString))
{
    string query = "CREATE DATABASE " + databaseName;

    using(SqlCommand command = new SqlCommand(query, connection))
    {
        try
        {
            connection.Open();
            if (connection.State == ConnectionState.Open)
                command.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }
    }
}

Maybe this TechNet article can help?  Troubleshooting: Timeout Expired


问:
SQLIte how to insert unique data on change of column value
I am using SQLite Database for my application. I have 4 columns-  Student_Name,Student_Enroll, Student_Mob, Student_Address in my database. Now I can add new record if and only if one of four column value is different or all values are different. If all column values are same then no new record should be generated.
Can you please guide me to solve this issue?</p>

答:
To enforce that a set of columns must be unique, add a UNIQUE constraint:

```<code>create table Students (
 /* ID              INTEGER PRIMARY KEY, */
    Student_Name    TEXT,
    Student_Enroll  TEXT,
    Student_Mob     TEXT,
    Student_Address TEXT,
    UNIQUE (Student_Name, Student_Enroll, Student_Mob, Student_Address)
);
</code>```

This allows new rows only if at least one of the four columns has a different value.

With a plain INSERT, attempting to insert a duplicate row will result in an error. If you simply want to ignore it instead, use INSERT OR IGNORE:

```<code>INSERT OR IGNORE INTO Students ...;
</code>```

Body:
To enforce that a set of columns must be unique, add a UNIQUE constraint:

create table Students (
 /* ID              INTEGER PRIMARY KEY, */
    Student_Name    TEXT,
    Student_Enroll  TEXT,
    Student_Mob     TEXT,
    Student_Address TEXT,
    UNIQUE (Student_Name, Student_Enroll, Student_Mob, Student_Address)
);

This allows new rows only if at least one of the four columns has a different value.

With a plain INSERT, attempting to insert a duplicate row will result in an error. If you simply want to ignore it instead, use INSERT OR IGNORE:

INSERT OR IGNORE INTO Students ...;


问:
Background image using the background-image property not appearing so not able to get the desired display
I am new to html/css and I do not understand why my background image is not showing up over the button in the search box on the right. I want to display an image of magnifying glass over the right button in the search box?

.sbox {
  width: 297.297px;
  height: 25px;
  background-color: rgba (0, 0, 0, 0);
  font-family: Helvetica, Arial, sans-serif;
  font-size: 14px;
  font-stretch: normal;
  font-style: normal;
  font-variant-caps: normal;
  font-variant-ligatures: normal;
  font-variant-numeric: normal;
  font-weight: normal;
  cursor: auto;
  position: relative;

}

.fb {
  background: url("../img/mag.png") no-repeat 0 0;
  background-size: 50px 50px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

  <head>
    <link rel="stylesheet" href="css/facebook.css">
  </head>

  <body>
    <button value="1" class="tools" aria-label="Search" type="submit">
  <i class=fb></i>
</button>
    <input type="text" class="sbox" placeholder="Search " arial-label="Search" />
  </body>

</html></code>```

答:
You should add background image to the button rather than using an i tag. i tags are used in html for alternate text moods. eg adding italics etc.

The reason they were adopted by font-awesome and bootstrap to show icons was mostly because they are inline-block by default and are efficient. But the way they do it is by adding a font file rather than using its background property

Here you should add the background to the button along with specifying a specific height and width to it.

```<code><button value="1" class="tools fa" aria-label="Search" type="submit">
</button>

.fb {
  background: url("../img/mag.png") no-repeat 0 0;
  background-size: 50px 50px;
 height:45px;
    width:50px;
  }
</code>```

Body:
I am new to html/css and I do not understand why my background image is not showing up over the button in the search box on the right. I want to display an image of magnifying glass over the right button in the search box?

.sbox {
  width: 297.297px;
  height: 25px;
  background-color: rgba (0, 0, 0, 0);
  font-family: Helvetica, Arial, sans-serif;
  font-size: 14px;
  font-stretch: normal;
  font-style: normal;
  font-variant-caps: normal;
  font-variant-ligatures: normal;
  font-variant-numeric: normal;
  font-weight: normal;
  cursor: auto;
  position: relative;

}

.fb {
  background: url("../img/mag.png") no-repeat 0 0;
  background-size: 50px 50px;
  }

<!DOCTYPE html>

    <link rel="stylesheet" href="css/facebook.css">

    <button value="1" class="tools" aria-label="Search" type="submit">

</button>
    <input type="text" class="sbox" placeholder="Search " arial-label="Search" />

Body:
You should add background image to the button rather than using an i tag. i tags are used in html for alternate text moods. eg adding italics etc.

The reason they were adopted by font-awesome and bootstrap to show icons was mostly because they are inline-block by default and are efficient. But the way they do it is by adding a font file rather than using its background property

Here you should add the background to the button along with specifying a specific height and width to it.

<button value="1" class="tools fa" aria-label="Search" type="submit">
</button>

.fb {
  background: url("../img/mag.png") no-repeat 0 0;
  background-size: 50px 50px;
 height:45px;
    width:50px;
  }


问:
ComputerBrowser service is missing in Windows Server 2012
I'm using Windows Server 2012 to manage my network domain. The problem is that the ComputerBrowser service is missing in my services list. How can I reinstall or repair it?

答: Did you disable SMBv1, or remove the client for Microsoft network Windows feature?</p>


问:
React HTML point and click generator
I want users to be able to design a simple web page to render their content on a page on my site. Are there any projects (ideally react) out there currently that allow a point and click layout design similar to wordpress and generate html?</p>

答:
I have since found the Ory Editor - Seems to fulfil all my requirements.
https://github.com/ory/editor</p>

Title: React HTML point and click generator


问:
Using destructuring assignment and the rest syntax for default variables
The following is an attempt to set the default value for an argument, based on the first argument:

function tree(values, ...[[curr] = values]) {
    console.log(curr);
}

tree(['foo']); // foo
tree(['foo'], ['bar']); // bar ```

It appears to work (actually it isn't quite what I want, but I want to understand this first).

What is going on here?

答:
This happens because default parameters can reference previous parameters. In your example you are destructuring values to curr, that's why the console is printing the first element of the array. You could suppress the spread operator and the result would be the same:

```<code>function tree(values, [curr] = values) {
    console.log(curr);
}

tree(['foo']); // foo
tree(['foo'], ['bar']); // bar
</code>```

What is happening to the second call tree(['foo'], ['bar']) is that the second argument (['bar']) is overriding [curr] default value.

Please let me know if I wasn't clear enough.

Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters (look for the section titled "Default parameters are available to later default parameters")

Body:
The following is an attempt to set the default value for an argument, based on the first argument:

function tree(values, ...[[curr] = values]) {
    console.log(curr);
}

tree(['foo']); // foo
tree(['foo'], ['bar']); // bar

It appears to work (actually it isn't quite what I want, but I want to understand this first).

What is going on here?

Body:
This happens because default parameters can reference previous parameters. In your example you are destructuring values to curr, that's why the console is printing the first element of the array. You could suppress the spread operator and the result would be the same:

function tree(values, [curr] = values) {
    console.log(curr);
}

tree(['foo']); // foo
tree(['foo'], ['bar']); // bar

What is happening to the second call tree(['foo'], ['bar']) is that the second argument (['bar']) is overriding [curr] default value.

Please let me know if I wasn't clear enough.

Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters (look for the section titled "Default parameters are available to later default parameters")


问:
Status 502 in Nginx
I have configured Nginx on a CentOS 7 server. There I have 2 sites running, I installed the SSL certificate using Cerbot and the process was executed with no errors. There I have 2 subdomains, x.mydomain.com and y.mydomain.com

The sites that I am running correspond to applications that are running on their own ports, 9100 for one and 9200 for the second one, so I configured Nginx to redirect the petitions to the corresponding port. For example, the server block for the first application is:

```<code>   server {
                listen          80;
                server_name     x.mydomain.com;
                access_log      logs/mydomainX.log main;

                location / {
                        proxy_pass      http://127.0.0.1:9100;
                }

                listen 443 ssl; # managed by Certbot
                ssl_certificate /etc/letsencrypt/live/x.mydomain.com/fullchain.pem; # managed by Certbot
                ssl_certificate_key /etc/letsencrypt/live/x.mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

}
</code>```

So, if I open in the browser x.mydomain.com I get status code 502 from Nginx, however, if I open directly using the IP: xxx.xxx.xxx.xxx.xxx:9100 then I can see the site. So I must have something wrong in the Nginx configuration, what am I missing? Thanks

答:
Status code 502 shows that nginx could connect to proxy upstream, so there is something wrong with upstream on 127.0.0.1:9100.

If request to xxx.xxx.xxx.xxx.xxx:9100 working fine, you could change your nginx configuration to something like this:

```<code>server {
    listen          80;
    server_name     x.mydomain.com;
    access_log      logs/mydomainX.log main;

    location / {
           proxy_pass      http://xxx.xxx.xxx.xxx.xxx:9100;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/x.mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/x.mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

}
</code>```

If you still want to use 127.0.0.1:9100 for proxy_pass, you should check your application, may be it not binded on 127.0.0.1.

Title: Status 502 in Nginx

Body:
I have configured Nginx on a CentOS 7 server. There I have 2 sites running, I installed the SSL certificate using Cerbot and the process was executed with no errors. There I have 2 subdomains, x.mydomain.com and y.mydomain.com

The sites that I am running correspond to applications that are running on their own ports, 9100 for one and 9200 for the second one, so I configured Nginx to redirect the petitions to the corresponding port. For example, the server block for the first application is:

   server {
                listen          80;
                server_name     x.mydomain.com;
                access_log      logs/mydomainX.log main;

                location / {
                        proxy_pass      http://127.0.0.1:9100;
                }

                listen 443 ssl; # managed by Certbot
                ssl_certificate /etc/letsencrypt/live/x.mydomain.com/fullchain.pem; # managed by Certbot
                ssl_certificate_key /etc/letsencrypt/live/x.mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

}

So, if I open in the browser x.mydomain.com I get status code 502 from Nginx, however, if I open directly using the IP: xxx.xxx.xxx.xxx.xxx:9100 then I can see the site. So I must have something wrong in the Nginx configuration, what am I missing? Thanks

Body:
Status code 502 shows that nginx could connect to proxy upstream, so there is something wrong with upstream on 127.0.0.1:9100.

If request to xxx.xxx.xxx.xxx.xxx:9100 working fine, you could change your nginx configuration to something like this:

server {
    listen          80;
    server_name     x.mydomain.com;
    access_log      logs/mydomainX.log main;

    location / {
           proxy_pass      http://xxx.xxx.xxx.xxx.xxx:9100;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/x.mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/x.mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

}

If you still want to use 127.0.0.1:9100 for proxy_pass, you should check your application, may be it not binded on 127.0.0.1.


问:
Canot push to remote repo - "Please make sure you have the correct access rights and the repository exists."
I'm constantly facing authentication issues as a consequence of moving between pushing to my private projects and my work ones.  Each time I move from a work context to a personal one, I spend some time dealing with my ssh keys and configuration.  I often go through the github documentation around generating and adding ssh public keys to the site.

Today, I'm getting:

```<code>ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

I tried generating a new ssh key pair and submitting the public key to github but github says "key already in use".  I googled that for a bit but could not fully make sense of that error message.

Switching gears I noticed that when running the command ssh -T git@github.com, the output greets me as the Github user associated with my personal account username and not my work one.

My understanding of ssh was that it was in some sense "accountless".  No username or password is part of the ssh connection process.  So now that I believe the authentication issue revolves around some system believing I'm logged in as my private github account's username, what can I do?

答:
How GitHub knows who you are

My understanding of ssh was that it was in some sense "accountless". No username or password is part of the ssh connection process. So now that I believe the authentication issue revolves around some system believing I'm logged in as my private github account's username

You are correct: the problem is GitHub makes an assumption about your GitHub username, but it's not always correct for your current need.

All SSH connections have a username. In the case of GitHub, it is always "git". That's the "git@" part of your GitHub URL, e.g.

```<code>git@github.com:username/projectname.git
</code>```

As far as SSH is concerned, the username is always "git".

But GitHub (the application running on the server) has another layer. It looks at the SSH key you used to authenticate, and looks up which GitHub user has that key associated with their account. That is how it maps your SSH connection to a GitHub username.

The problem

You have multiple accounts on GitHub. So you need a way to control which one you are using. But SSH will, by default, always use the same key for "github.com".

The solution

(The below assumes macOS or Linux - how to do this in Windows is different, but the same concept applies.)

You can control which key is used by mapping different virtual hostnames.

Let's say you have two keys,

~/.ssh/id_github_work

~/.ssh/id_github_personal

You can set up profiles like this in ~/.ssh/config:

```<code>Host github.com-work
    Hostname github.com
    User git
    IdentityFile ~/.ssh/id_github_work

Host github.com-personal
    Hostname github.com
    User git
    IdentityFile ~/.ssh/id_github_personal
</code>```

Now you can control, using the hostname, which key is used. You can clone like this:

```<code>git clone github.com-personal:yourusername/projectname
</code>```

It will use your personal key. To use the other key, just use the other hostname.

Why this works

SSH will see the hostname in your URL, e.g.

```<code>github.com-personal
</code>```

Before doing anything else, it looks in its own configuration to see if there are any parameters associated with that hostname. Since this hostname matches an entry we added to ~/.ssh/config, it loads those parameters.

One of those parameters, Hostname, tells SSH that the hostname we gave it is not the real hostname of the service. SSH (and therefore Git) will still connect to the hostname "github.com", but it will use the SSH key (and username) specified by this SSH profile.

Fixing existing repos

If you already have a repo, you don't need to re-clone it. You can just change the URL.

```<code>git remote set-url origin github.com-personal:yourusername/projectname
</code>```

git-passport

You can also try git-passport as was suggested by RichouHunter in the comments. I have no experience with that tool so I can't vouch for it, but it appears to try to address the same problem.

Body:
I'm constantly facing authentication issues as a consequence of moving between pushing to my private projects and my work ones.  Each time I move from a work context to a personal one, I spend some time dealing with my ssh keys and configuration.  I often go through the github documentation around generating and adding ssh public keys to the site.

Today, I'm getting:

ERROR: Repository not found.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I tried generating a new ssh key pair and submitting the public key to github but github says "key already in use".  I googled that for a bit but could not fully make sense of that error message.

Switching gears I noticed that when running the command ssh -T git@github.com, the output greets me as the Github user associated with my personal account username and not my work one.

My understanding of ssh was that it was in some sense "accountless".  No username or password is part of the ssh connection process.  So now that I believe the authentication issue revolves around some system believing I'm logged in as my private github account's username, what can I do?

Body:
How GitHub knows who you are

My understanding of ssh was that it was in some sense "accountless". No username or password is part of the ssh connection process. So now that I believe the authentication issue revolves around some system believing I'm logged in as my private github account's username

You are correct: the problem is GitHub makes an assumption about your GitHub username, but it's not always correct for your current need.

All SSH connections have a username. In the case of GitHub, it is always "git". That's the "git@" part of your GitHub URL, e.g.

git@github.com:username/projectname.git

As far as SSH is concerned, the username is always "git".

But GitHub (the application running on the server) has another layer. It looks at the SSH key you used to authenticate, and looks up which GitHub user has that key associated with their account. That is how it maps your SSH connection to a GitHub username.

The problem

You have multiple accounts on GitHub. So you need a way to control which one you are using. But SSH will, by default, always use the same key for "github.com".

The solution

(The below assumes macOS or Linux - how to do this in Windows is different, but the same concept applies.)

You can control which key is used by mapping different virtual hostnames.

Let's say you have two keys,

~/.ssh/id_github_work

~/.ssh/id_github_personal

You can set up profiles like this in ~/.ssh/config:

Host github.com-work
    Hostname github.com
    User git
    IdentityFile ~/.ssh/id_github_work

Host github.com-personal
    Hostname github.com
    User git
    IdentityFile ~/.ssh/id_github_personal

Now you can control, using the hostname, which key is used. You can clone like this:

git clone github.com-personal:yourusername/projectname

It will use your personal key. To use the other key, just use the other hostname.

Why this works

SSH will see the hostname in your URL, e.g.

github.com-personal

Before doing anything else, it looks in its own configuration to see if there are any parameters associated with that hostname. Since this hostname matches an entry we added to ~/.ssh/config, it loads those parameters.

One of those parameters, Hostname, tells SSH that the hostname we gave it is not the real hostname of the service. SSH (and therefore Git) will still connect to the hostname "github.com", but it will use the SSH key (and username) specified by this SSH profile.

Fixing existing repos

If you already have a repo, you don't need to re-clone it. You can just change the URL.

git remote set-url origin github.com-personal:yourusername/projectname

git-passport

You can also try git-passport as was suggested by RichouHunter in the comments. I have no experience with that tool so I can't vouch for it, but it appears to try to address the same problem.

ContentLicense: CC BY-SA 4.0


问:
capistrano doesn't respect port
I'm deploying to production as follow:

```<code>HOSTS = [
  'api1.app.io',
  'api2.app.io',
  'api3.app.io',
  'api4.app.io',
  'api5.app.io',
  'api6.app.io',
  'api7.app.io',
  'api8.app.io',
  'api9.app.io',
  'api10.app.io'
].freeze

HOSTS.each do |host|
  server host, roles: %i[app web], user: 'deploy', port: 2323
end
</code>```

although it fails when capistrano tries to ssh into the servers because it still tries to connect using port 22...

```<code>(Backtrace restricted to imported tasks)
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host api2.app.io: Net::SSH::ConnectionTimeout

Net::SSH::ConnectionTimeout: Net::SSH::ConnectionTimeout

Errno::ETIMEDOUT: Connection timed out - connect(2) for xx.xx.xx.xx:22
</code>```

Is there any other way to configure the ports?

答:
The :port option should work. If it does not, that it is a bug. Please open a bug report at https://github.com/capistrano/capistrano/issues .

As a workaround, you can also specify the port via the hostname using the <host>:<port> syntax, like this:

```<code>HOSTS.each do |host|
  server "#{host}:#{port}", roles: %i[app web], user: 'deploy'
end
</code>```

Title: capistrano doesn't respect port

Body:
I'm deploying to production as follow:

HOSTS = [
  'api1.app.io',
  'api2.app.io',
  'api3.app.io',
  'api4.app.io',
  'api5.app.io',
  'api6.app.io',
  'api7.app.io',
  'api8.app.io',
  'api9.app.io',
  'api10.app.io'
].freeze

HOSTS.each do |host|
  server host, roles: %i[app web], user: 'deploy', port: 2323
end

although it fails when capistrano tries to ssh into the servers because it still tries to connect using port 22...

(Backtrace restricted to imported tasks)
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing on host api2.app.io: Net::SSH::ConnectionTimeout

Net::SSH::ConnectionTimeout: Net::SSH::ConnectionTimeout

Errno::ETIMEDOUT: Connection timed out - connect(2) for xx.xx.xx.xx:22

Is there any other way to configure the ports?

Body:
The :port option should work. If it does not, that it is a bug. Please open a bug report at https://github.com/capistrano/capistrano/issues .

As a workaround, you can also specify the port via the hostname using the <host>:<port> syntax, like this:

HOSTS.each do |host|
  server "#{host}:#{port}", roles: %i[app web], user: 'deploy'
end


问:
How to set Queue name from Header value in Apache Camel
Im trying to set activemq queue name from header value but its not happening below is my
Spring DSL

```<code><setHeader headerName="x-so-queue-name" id="_setHeader1">
   <xpath resultType="java.lang.String">/Message/@IntObjectName</xpath>
</setHeader>
<log id="_log1" message="x-so-queue-name::: ${header.x-so-queue-name}"/>
<to id="_to1" uri="activemq:queue:${header.x-so-queue-name}"/>
</code>```

LOGS
16:03:57,601 | INFO  | _route1 | x-so-queue-name::: IDC_SO_Refill_IO

header value is printing in the logs but queue name is set to "${header.x-so-queue-name}" why its not retrieving the the value for header, am i doing some thing wrong

答:
Replace the 'x-so-queue-name' header name with the header named 'CamelJmsDestinationName'

Then in the uri, remove the ${header.x-so-queue-name}.. you can put whatever queue name you want, since the ActiveMQ component will look at the header to determine the destination name. I generally use the below, as a reminder that I'm using dynamic queue naming in the route:

Reference: Camel JMS Component (search for CamelJmsDestinationName)

Body:
Im trying to set activemq queue name from header value but its not happening below is my
Spring DSL

<setHeader headerName="x-so-queue-name" id="_setHeader1">
   <xpath resultType="java.lang.String">/Message/@IntObjectName</xpath>
</setHeader>
<log id="_log1" message="x-so-queue-name::: ${header.x-so-queue-name}"/>
<to id="_to1" uri="activemq:queue:${header.x-so-queue-name}"/>

LOGS
16:03:57,601 | INFO  | _route1 | x-so-queue-name::: IDC_SO_Refill_IO

header value is printing in the logs but queue name is set to "${header.x-so-queue-name}" why its not retrieving the the value for header, am i doing some thing wrong


问:
hash function to index similar text
I'm searching about a sort of hash function to index similar text. So for example if we have two very long text called "A" and "B" where A and B differ not so much, then the hash function (called H) applied to A and B should return the same number.

So H(A) = H(B) where A and B are similar text.

I tried the "DoubleMetaphone" (I use italian language text), but I saw that it depends very strong from the string prefixes. For example:

A = "This is the very long text that I want to hash"
B = "This is the very"

==> doubleMetaPhone(A) = doubleMetaPhone(B)

And this is not so good for me, beacause strings with the same prefix could be compared as similar and I don't want this.

Could anyone suggest me any other way?

Title: hash function to index similar text

Body: see http://en.wikipedia.org/wiki/Locality_sensitive_hashing


问:
How can I wait for an unknown number of Rust threads to complete without using tracking handles?
What are some good ways to adapt this Barrier example to handle two differences:

the number of items is not known in advance (for example, in the case where splitting a large file into lines)

without tracking thread handles (e.g. without using the handles vector in the example below). The motivation is that doing so adds additional overhead.

Example code:

```<code>use std::sync::{Arc, Barrier};
use std::thread;

let mut handles = Vec::with_capacity(10);
let barrier = Arc::new(Barrier::new(10));
for _ in 0..10 {
    let c = barrier.clone();
    handles.push(thread::spawn(move|| {
        // do some work
        c.wait();
    }));
}
// Wait for other threads to finish.
for handle in handles {
    handle.join().unwrap();
}
</code>```

Code snippet is adapted slightly from the Barrier docs.

The first thing that crossed my mind would be (if possible) to mutate the inner value of the Barrier; however, the API does not provide mutable access to the num_threads property of the Barrier struct.

Another idea would be to not use the Barrier and instead write custom  logic with AtomicUsize.

I'm open to learning the most ergonomic / idiomatic ways to do this in Rust.

答:
You can use spinlock on atomic for waiting for all threads to exit. Of course, instead of using static atomic, you can pass Arc<AtomicUsize> into each thread.

Ordering::SeqCst is probably too strong, but concurrent programming is hard, and I'm not sure how this ordering can be relaxed.

While it can be done this way, cost of creating threads will probably dwarf micro optimization like this. Also it's worth considering that busy wait can decrease performance of a program.

```<code>use std::panic;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::thread;
use std::time::Duration;

static GLOBAL_THREAD_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;

fn main() {
    for i in 0..10 {
        // mark that the thread is about to run
        // we need to do it in the main thread to prevent spurious exits
        GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::SeqCst);
        thread::spawn(move|| {
            // We need to catch panics to reliably signal exit of a thread
            let result = panic::catch_unwind(move || {
                // do some work
                println!("{}-th thread reporting", i+1);
            });
            // process errors
            match result {
                _ => {}
            }
            // signal thread exit
            GLOBAL_THREAD_COUNT.fetch_sub(1, Ordering::SeqCst);
        });
    }
    // Wait for other threads to finish.
    while GLOBAL_THREAD_COUNT.load(Ordering::SeqCst) != 0 {
        thread::sleep(Duration::from_millis(1));
    }
}
</code>```

Playground link

Body:
What are some good ways to adapt this Barrier example to handle two differences:

the number of items is not known in advance (for example, in the case where splitting a large file into lines)

without tracking thread handles (e.g. without using the handles vector in the example below). The motivation is that doing so adds additional overhead.

Example code:

use std::sync::{Arc, Barrier};
use std::thread;

let mut handles = Vec::with_capacity(10);
let barrier = Arc::new(Barrier::new(10));
for _ in 0..10 {
    let c = barrier.clone();
    handles.push(thread::spawn(move|| {
        // do some work
        c.wait();
    }));
}
// Wait for other threads to finish.
for handle in handles {
    handle.join().unwrap();
}

Code snippet is adapted slightly from the Barrier docs.

The first thing that crossed my mind would be (if possible) to mutate the inner value of the Barrier; however, the API does not provide mutable access to the num_threads property of the Barrier struct.

Another idea would be to not use the Barrier and instead write custom  logic with AtomicUsize.

I'm open to learning the most ergonomic / idiomatic ways to do this in Rust.

Body:
You can use spinlock on atomic for waiting for all threads to exit. Of course, instead of using static atomic, you can pass Arc<AtomicUsize> into each thread.

Ordering::SeqCst is probably too strong, but concurrent programming is hard, and I'm not sure how this ordering can be relaxed.

While it can be done this way, cost of creating threads will probably dwarf micro optimization like this. Also it's worth considering that busy wait can decrease performance of a program.

use std::panic;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::thread;
use std::time::Duration;

static GLOBAL_THREAD_COUNT: AtomicUsize = ATOMIC_USIZE_INIT;

fn main() {
    for i in 0..10 {
        // mark that the thread is about to run
        // we need to do it in the main thread to prevent spurious exits
        GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::SeqCst);
        thread::spawn(move|| {
            // We need to catch panics to reliably signal exit of a thread
            let result = panic::catch_unwind(move || {
                // do some work
                println!("{}-th thread reporting", i+1);
            });
            // process errors
            match result {
                _ => {}
            }
            // signal thread exit
            GLOBAL_THREAD_COUNT.fetch_sub(1, Ordering::SeqCst);
        });
    }
    // Wait for other threads to finish.
    while GLOBAL_THREAD_COUNT.load(Ordering::SeqCst) != 0 {
        thread::sleep(Duration::from_millis(1));
    }
}

Playground link


问:
wxPython execution
How and where should the wxPython program be executed?</p>

答: the wxPython program can be executed from anywhere, just make sure you have the proper python version for your version of wxPython that you've downloaded. also make sure the bit type is right for your system. amd64 doesnt mean all amd cpus, its 64 bit. when in doubt go 32 bit and python 2.7</p>

OwnerDisplayName: moni

Title: wxPython execution


问:
The mapping of CLR type to EDM type is ambiguous with EF 6 & 5?
Please any one can help me to fix this error?

Schema specified is not valid. Errors:

The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'City_DAL'. Previously found CLR type 'CeossDAL.City_DAL', newly found CLR type 'CeossBLL.City_DAL'.

The main problem that I have DAL and this contains the EF and BLL and this contains the same classes of the DAL but differ in the namespace and this is what cause the problem

I can't know how to get rid of these problem, can you please help me?

Also I will be appreciated if some one give me sample to use n-tier architecture with EF

Thank you

答:
For EF 6.x, I found some notes at https://github.com/aspnet/EntityFramework/issues/941 and fixed this in my solution by adding annotation to the EDM type.

I edited the EDMX file manually and changed a line like this:

```<code><EntityType Name="CartItem">
</code>```

to this:

```<code><EntityType Name="CartItem" customannotation:ClrType="EntityModel.CartItem">
</code>```

or use this if you have existing type elsewhere:

```<code><EntityType Name="CartItem" customannotation:ClrType="MyApp.CartItem, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
</code>```

where EntityModel is the namespace used for my EF model, and MyApp is the namespace of a business object

Body:
For EF 6.x, I found some notes at https://github.com/aspnet/EntityFramework/issues/941 and fixed this in my solution by adding annotation to the EDM type.

I edited the EDMX file manually and changed a line like this:

<EntityType Name="CartItem">

to this:

<EntityType Name="CartItem" customannotation:ClrType="EntityModel.CartItem">

or use this if you have existing type elsewhere:

<EntityType Name="CartItem" customannotation:ClrType="MyApp.CartItem, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">

where EntityModel is the namespace used for my EF model, and MyApp is the namespace of a business object


问:
Streaming a file in ASP.NET, C#?
Assume we have the access to sth.avi on www.dl.com with a direct link.

e.g : www.dl.com\sth.avi

Also we have a website => www.dl2.com.

Now, we wanna let some users to download sth.avi from www.dl2.com, but we don't have enough space on www.dl2.com to save sth.avi.

Is it possible in ASP.NET for us to read sth.avi from www.dl.com as streaming file and share it without saving the file on our domain.

P.S:

I don't wanna share this link www.dl.com\sth.avi, actually I wanna share something like this link www.dl2.com\downloads\sth.avi

答:
Yes.

Make an HttpWebRequest to dl.com/... and copy the HttpWebResponse to Response.Out.

Make sure to disable buffering.

Title: Streaming a file in ASP.NET, C#?


问:
How to link React.js file to html
I just installed this Create React Apps program from here https://github.com/facebookincubator/create-react-app and I have all the files downloaded and I am able to edit the App.js file, but I already have made some html files for a website, I want to know how to link the App.js file to my current files. The html on the given Index.html, shows no

答:
Inside your project run

npm run build

This create the folder "/build" with the "index.html" file. Inside this you can see how all this magic is done. You can put your other/old stuff also there.

Title: How to link React.js file to html


问:
Find size of binary file, function tellg() returns -1
I've written a function which initialize some fields of FileDataTransfer object and also finds size of file.

Here is a code:

```<code>bool FileTransferData::initialize(const string& fileName, string& errMsg)
{
   if (this->transferInProgress)
   {
       errMsg = "\nFile Transfer already in progress. File Transfer Request denied.\a";
       return false;
   }
   this->inFileStream.open(fileName, ios::binary | ios::ate);
   if (!inFileStream.is_open())
   {
       errMsg = "\nRequested file: " + fileName + " does not exist or was not found.\a";
       return false;
   }
   this->fileName = fileName;
   this->fileSize = (int)this->inFileStream.tellg();
   this->inFileStream.seekg(0);
   this->fileOffset = 0;
   this->transferInProgress = true;
   return true;
}
</code>```

But field this->fileSize become -1 after completion of my function, I think tellg() returns -1, but why ?

答:
You can get the size of a file like this

```<code>long long filesize(const char *fname)
{
   int ch;
   FILE *fp;
   long long answer = 0;
   fp = fopen(fname, "rb");
   if(!fp)
     return -1;
   while( (ch = fgetc(fp)) != EOF)
      answer++;
   fclose(fp);
   return answer;
}
</code>```

It's portable, and whilst it does a pass over the file, usually you'll have to pass through the file anyway, so you're not blowing up the big O efficiency of your function. Plus fgetc() is highly optimised for buffering.

Body:
I've written a function which initialize some fields of FileDataTransfer object and also finds size of file.

Here is a code:

bool FileTransferData::initialize(const string& fileName, string& errMsg)
{
   if (this->transferInProgress)
   {
       errMsg = "\nFile Transfer already in progress. File Transfer Request denied.\a";
       return false;
   }
   this->inFileStream.open(fileName, ios::binary | ios::ate);
   if (!inFileStream.is_open())
   {
       errMsg = "\nRequested file: " + fileName + " does not exist or was not found.\a";
       return false;
   }
   this->fileName = fileName;
   this->fileSize = (int)this->inFileStream.tellg();
   this->inFileStream.seekg(0);
   this->fileOffset = 0;
   this->transferInProgress = true;
   return true;
}

But field this->fileSize become -1 after completion of my function, I think tellg() returns -1, but why ?

Body:
You can get the size of a file like this

long long filesize(const char *fname)
{
   int ch;
   FILE *fp;
   long long answer = 0;
   fp = fopen(fname, "rb");
   if(!fp)
     return -1;
   while( (ch = fgetc(fp)) != EOF)
      answer++;
   fclose(fp);
   return answer;
}

It's portable, and whilst it does a pass over the file, usually you'll have to pass through the file anyway, so you're not blowing up the big O efficiency of your function. Plus fgetc() is highly optimised for buffering.


问:
Change the splashscreen imagem by the date
I'm trying to create a function that changes the splashscreen image when a specific date is near, like:

```<code>30/nov/2017 - Default splashscreen

01/des/2017 ~ 31/des/2017 - Christmas theme splashscreen

01/jan/2018 - Default splashscreen
</code>```

I've created the splash screen putting SplashScreen-Image: splashdemo/splash.png inside the manifest.mf AND -splash:src/splashdemo/splash.png in Properties > Run > VM Options.

My main is basically this:

```<code>package splashdemo;

public class Splashdemo {

    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(2000);
    }
}
</code>```

The splash works fine as expected, but now I want to change the image somehow. How can I do this?

答:
Your approach at the moment relies on you re-releasing your application each time the date range changes.

I'd suggest you package the three images in the jar, and then dynamically determine the splash screen name based on date, and then call the SplashScreen class directly with the correct image.

See these links

How to make a splash screen for GUI?

http://docs.oracle.com/javase/tutorial/uiswing/misc/splashscreen.html

Body:
I'm trying to create a function that changes the splashscreen image when a specific date is near, like:

30/nov/2017 - Default splashscreen

01/des/2017 ~ 31/des/2017 - Christmas theme splashscreen

01/jan/2018 - Default splashscreen

I've created the splash screen putting SplashScreen-Image: splashdemo/splash.png inside the manifest.mf AND -splash:src/splashdemo/splash.png in Properties > Run > VM Options.

My main is basically this:

package splashdemo;

public class Splashdemo {

    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(2000);
    }
}

The splash works fine as expected, but now I want to change the image somehow. How can I do this?


问:
Sylius - How to assign a Channel to a Product programmatically?
I am trying to assign a Channel to my products created programmatically, so they will be displayed on shop. Unfortunately, there is no documentation for this use case.

Here is how I create my products:

```<code>$productFactory = $this->container->get('sylius.factory.product');
$productManager = $this->container->get('sylius.manager.product');
$productRepository = $this->get('sylius.repository.product');
$productVariantFactory = $this->get('sylius.factory.product_variant');
$productVariantRepository = $this->get('sylius.repository.product_variant');
$channelPricingFactory = $this->get('sylius.factory.channel_pricing');
$channelPricingRepository = $this->get('sylius.repository.channel_pricing');

//CREATE PRODUCT

$product = $factory->createNew();
$product->setName('TEST 2 - '.$title);
$product->setCode($this->generateRandomString());
$product->setSlug($this->generateRandomString());
$productRepository->add($product);

//CREATE VARIANT & ATTACH IT TO PRODUCT

$variant = $productVariantFactory->createNew();
$variant->setName('TEST 2 - '.$title);
$variant->setCode($this->generateRandomString());
$variant->setProduct($product);
$productVariantRepository->add($variant);

//CREATE PRICE & ATTACH IT TO VARIANT

$channelPricing = $channelPricingFactory->createNew();
$channelPricing->setPrice(999);
$channelPricing->setOriginalPrice(999);
$channelPricing->setChannelCode('US_WEB');
$channelPricing->setProductVariant($variant);
$channelPricingRepository->add($channelPricing);
</code>```

Unfortunately, the products are not linked to a Channel:

答:
Here is how I managed to create my products (to attach them then to my entities):</p>

```<code>function createProduct($livre,$options){

    $title = $livre['title'];
    $prix = $livre['prix'];

    // SYLIUS REPOSITORIES LOAD

    $productFactory = $options['sylius_factory_product'];
    $productRepository = $options['sylius_repository_product'];
    $productVariantFactory = $options['sylius_factory_product_variant'];
    $productVariantRepository = $options['sylius_repository_product_variant'];
    $channelPricingFactory = $options['sylius_factory_channel_pricing'];
    $channelPricingRepository = $options['sylius_repository_channel_pricing'];

    //CREATE PRODUCT

    $product = $productFactory->createNew();
    $product->setName($title);
    $product->setCode($title.'_'.$this->generateRandomString());
    $product->setSlug($title.'_'.$this->generateRandomString());
    $productRepository->add($product);

    //CREATE VARIANT & ATTACH IT TO PRODUCT

    $variant = $productVariantFactory->createNew();
    $variant->setName($title. 'Variant');
    $variant->setCode($title.'_'.$this->generateRandomString());
    $variant->setProduct($product);
    $productVariantRepository->add($variant);

    //CREATE PRICE & ATTACH IT TO VARIANT

    $channelPricing = $channelPricingFactory->createNew();
    $channelPricing->setPrice($prix*100);
    $channelPricing->setOriginalPrice($prix*100);
    $channelPricing->setChannelCode('CH');
    $channelPricing->setProductVariant($variant);
    $channelPricingRepository->add($channelPricing);

    $productId = $product->getId();

    return $productId;
}
</code>```

Body:
I am trying to assign a Channel to my products created programmatically, so they will be displayed on shop. Unfortunately, there is no documentation for this use case.

Here is how I create my products:

$productFactory = $this->container->get('sylius.factory.product');
$productManager = $this->container->get('sylius.manager.product');
$productRepository = $this->get('sylius.repository.product');
$productVariantFactory = $this->get('sylius.factory.product_variant');
$productVariantRepository = $this->get('sylius.repository.product_variant');
$channelPricingFactory = $this->get('sylius.factory.channel_pricing');
$channelPricingRepository = $this->get('sylius.repository.channel_pricing');

//CREATE PRODUCT

$product = $factory->createNew();
$product->setName('TEST 2 - '.$title);
$product->setCode($this->generateRandomString());
$product->setSlug($this->generateRandomString());
$productRepository->add($product);

//CREATE VARIANT & ATTACH IT TO PRODUCT

$variant = $productVariantFactory->createNew();
$variant->setName('TEST 2 - '.$title);
$variant->setCode($this->generateRandomString());
$variant->setProduct($product);
$productVariantRepository->add($variant);

//CREATE PRICE & ATTACH IT TO VARIANT

$channelPricing = $channelPricingFactory->createNew();
$channelPricing->setPrice(999);
$channelPricing->setOriginalPrice(999);
$channelPricing->setChannelCode('US_WEB');
$channelPricing->setProductVariant($variant);
$channelPricingRepository->add($channelPricing);

Unfortunately, the products are not linked to a Channel:

Body:
Here is how I managed to create my products (to attach them then to my entities):

function createProduct($livre,$options){

    $title = $livre['title'];
    $prix = $livre['prix'];

    // SYLIUS REPOSITORIES LOAD

    $productFactory = $options['sylius_factory_product'];
    $productRepository = $options['sylius_repository_product'];
    $productVariantFactory = $options['sylius_factory_product_variant'];
    $productVariantRepository = $options['sylius_repository_product_variant'];
    $channelPricingFactory = $options['sylius_factory_channel_pricing'];
    $channelPricingRepository = $options['sylius_repository_channel_pricing'];

    //CREATE PRODUCT

    $product = $productFactory->createNew();
    $product->setName($title);
    $product->setCode($title.'_'.$this->generateRandomString());
    $product->setSlug($title.'_'.$this->generateRandomString());
    $productRepository->add($product);

    //CREATE VARIANT & ATTACH IT TO PRODUCT

    $variant = $productVariantFactory->createNew();
    $variant->setName($title. 'Variant');
    $variant->setCode($title.'_'.$this->generateRandomString());
    $variant->setProduct($product);
    $productVariantRepository->add($variant);

    //CREATE PRICE & ATTACH IT TO VARIANT

    $channelPricing = $channelPricingFactory->createNew();
    $channelPricing->setPrice($prix*100);
    $channelPricing->setOriginalPrice($prix*100);
    $channelPricing->setChannelCode('CH');
    $channelPricing->setProductVariant($variant);
    $channelPricingRepository->add($channelPricing);

    $productId = $product->getId();

    return $productId;
}


问:
Images and List Items
I'm looking for a way to display an image on a webpage. This image needs to be just to the right of a list item within an unordered list. Preferably, I'd like it to be within the list item tags but just after the text that is within the list item. However, when I place this image within the list item tags, it bumps the image down to the next line. Does anyone know why this is happening and/or a way to fix it? Thanks.</p>

答: In your css set your background-image to the image in question, background-position:right, and add the width of the image to the right padding. This would effectively create the illusion of an image appearing the right of the list item.</p>

Title: Images and List Items