问:
Pygame Executable Crashing
I have a small animation code that is built using PyGame (and Python 2.7). I am able to build the executable folder with Pyinstaller, however when I try to run the executable it is crashing, although I am able to run the same files (i.e. source code) through my terminal without any problem. </p>

```<code>import pygame
import exercise
import random as rd
import copy
import pandas as pd
import numpy as np

def animate():
    debug_mode=False

    done1 = False

    dc_x = 30
    dc_y = 30
    plant_x = 110
    plant_y = 30
    supp_x = 190
    supp_y = 30

    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0) #arrows
    RED = (255, 0, 0) # Box frames for summary of t, cost and lost sales
    GREEN = (0, 255, 0) # Box frames for shipment amounts
    DEEPSKYBLUE = (0,191,255)  # arc to represent backup WIP inv
    DOGERBLUE = (0,191,255)  # arc to represent backup FG inv
    INDIGO = (75,0,130)  # DC/Supp up state
    LAVENDER=(238, 130, 238) #DC/Supp down state
    OLIVE=(128,128,0) #plant down state
    YELLOWGREEN=(173,255,47) #plant up state
    DARKYELLOW=(204,204,0)

    pygame.init()
    screen = pygame.display.set_mode((1000, 600))

    clock = pygame.time.Clock()
    grand_record={}
    ############ READ AND PREPARE INITIAL SCREEN for t==0 ################
    PLANT_status, SUPP_status, DC_status, disruption, DC_BUp_Plan, Plant_BUp_Plan, Supp_BUp_Plan, Demand, P=exercise.init(debug_mode,False)
    grand_record[0]={"DC":DC_status, "Plant":PLANT_status, "Supplier":SUPP_status}

    basicFont = pygame.font.SysFont(None, 24)
    largeFont = pygame.font.SysFont(None, 35)
    pygame.display.set_caption('SCREAM!')
    if debug_mode: R=1
    else: R= rd.randint(0,25)
    scenario_score={"cost":0, "service":0}

    while not done1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done1 = True
            #if event.type == pygame.KEYDOWN:
            #    if event.key == pygame.K_DOWN:
            #        paused()
        end_of_one_run=1
        total_lost_customer=0
        cumulative_inv_holding_cost=0
        total_fixed_cost_paid=0
        table_output=[]
        chart_output=[]
        header=["Week","Demand","Upstream shipment", "Shipment from regular DC", "Shipment from backup DC",
                "FG Inv at Reg. DC", "FG Inv at B/up. DC", "FG Inv as B/up","LostSales","Start Order for b/up DC", "B/up DC starts","DC Disruption at","Disruption duration", "TotalAvailableWIPSupplyCap",
                "Start Order for b/up Supplier", "B/up Supplier starts","Supplier Disruption at","Disruption duration", "Storage Cap Available", "Plant production",
                 "WIP Inv as B/up","Start Order for b/up Plant", "B/up Plant starts","Plant Disruption at","Disruption duration"]
        table_output.append(header)
        for t in range(1,P+1): # for the specified number of periods
            screen.fill((0, 0, 0))
            picture = pygame.image.load('Background.png').convert() #MITwallpaper
            screen.blit(picture, [0, 0])
            #import pdb; pdb.set_trace()
            ################################## MAKE CALCULATIONS FOR t>0 ################
            grand_record,output=exercise.calculate(t, grand_record[t-1]["Plant"], grand_record[t-1]["Supplier"], grand_record[t-1]["DC"], disruption, DC_BUp_Plan, Plant_BUp_Plan,  Supp_BUp_Plan,Demand[R*P+t],grand_record,debug_mode)
            chart_output=exercise.prepare_chart_output(chart_output, grand_record)
            output_loc=copy.deepcopy(output)
            table_output.append(output_loc)
            end_of_one_run=end_of_one_run+1

            objectives=exercise.calculate_objectives(grand_record, DC_BUp_Plan, Plant_BUp_Plan, Supp_BUp_Plan, t)

            lost_cust_text = largeFont.render("Service: "+str(objectives["Service"]), True, WHITE, BLACK)
            lost_cust_textRect = lost_cust_text.get_rect()
            lost_cust_textRect.centerx = 380
            lost_cust_textRect.centery = 420
            pygame.draw.rect(screen, RED, (lost_cust_textRect.left - 3, lost_cust_textRect.top - 3, lost_cust_textRect.width + 3, lost_cust_textRect.height + 3))
            screen.blit(lost_cust_text, lost_cust_textRect)
            inv_hold_text = largeFont.render("Inv.Holding Cost(k$): "+str(round(objectives["InvHoldingCost"]*0.001,1)), True, WHITE, BLACK)
            inv_hold_textRect = inv_hold_text.get_rect()
            inv_hold_textRect.centerx = 600
            inv_hold_textRect.centery = 445
            pygame.draw.rect(screen, RED, (inv_hold_textRect.left - 3, inv_hold_textRect.top - 3, inv_hold_textRect.width + 3, inv_hold_textRect.height + 3))
            screen.blit(inv_hold_text, inv_hold_textRect)
            startup_text = largeFont.render("Startup Cost(k$): "+str(round(objectives["Startup_cost"]*0.001,1)), True, WHITE, BLACK)
            startup_textRect = startup_text.get_rect()
            startup_textRect.centerx = 840
            startup_textRect.centery = 470
            pygame.draw.rect(screen, RED, (startup_textRect.left - 3, startup_textRect.top - 3, startup_textRect.width + 3, startup_textRect.height + 3))
            screen.blit(startup_text, startup_textRect)

            ###################################################################################
            if t<P:
                pygame.display.flip()
                clock.tick(8)
            else:
                #import pdb; pdb.set_trace()
                table = pd.DataFrame(table_output)
                table.to_excel("Details.xlsx",index=False)

        #import pdb; pdb.set_trace()
        done1 = True
    ################################ Want A PARETO Button     ###################################
    x=500
    y=500
    w=200
    h=50
    pygame.draw.rect(screen, DEEPSKYBLUE,(x,y,w,h))
    buttontext = basicFont.render("Want A Pareto Solution?", True, BLACK , WHITE )
    buttontext_rect=buttontext.get_rect()
    buttontext_rect.centerx = (x+(w/2))
    buttontext_rect.centery = (y+(h/2))
    screen.blit(buttontext, buttontext_rect)
    pygame.display.flip()
    pygame.time.delay(120)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    exercise.plotcharts(chart_output)
################################################################################
animate()
</code>```

答:
my guess is that it crashes when trying to load the background image:

```<code>picture = pygame.image.load('Background.png').convert() #MITwallpaper
</code>```

When pyinstaller compiles your code, that is all it compiles (including the imported dependencies). It creates the dist directory where you can run your executable and you are good to go.

But, by default, pyinstaller will not pull in external resources. So when you run the executable, it can't find your image because it is in a different directory. You can test this by manually copying the image to the folder where the exe is located and see if it works.

Also, you can run the exe and push the output into a debug file:

```<code>your_file.exe > debug.txt
</code>```

This way you can capture the output from your program (including error messages).

Title: Pygame Executable Crashing

Body:
I have a small animation code that is built using PyGame (and Python 2.7). I am able to build the executable folder with Pyinstaller, however when I try to run the executable it is crashing, although I am able to run the same files (i.e. source code) through my terminal without any problem.

import pygame
import exercise
import random as rd
import copy
import pandas as pd
import numpy as np

def animate():
    debug_mode=False

    done1 = False

    dc_x = 30
    dc_y = 30
    plant_x = 110
    plant_y = 30
    supp_x = 190
    supp_y = 30

    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0) #arrows
    RED = (255, 0, 0) # Box frames for summary of t, cost and lost sales
    GREEN = (0, 255, 0) # Box frames for shipment amounts
    DEEPSKYBLUE = (0,191,255)  # arc to represent backup WIP inv
    DOGERBLUE = (0,191,255)  # arc to represent backup FG inv
    INDIGO = (75,0,130)  # DC/Supp up state
    LAVENDER=(238, 130, 238) #DC/Supp down state
    OLIVE=(128,128,0) #plant down state
    YELLOWGREEN=(173,255,47) #plant up state
    DARKYELLOW=(204,204,0)

    pygame.init()
    screen = pygame.display.set_mode((1000, 600))

    clock = pygame.time.Clock()
    grand_record={}
    ############ READ AND PREPARE INITIAL SCREEN for t==0 ################
    PLANT_status, SUPP_status, DC_status, disruption, DC_BUp_Plan, Plant_BUp_Plan, Supp_BUp_Plan, Demand, P=exercise.init(debug_mode,False)
    grand_record[0]={"DC":DC_status, "Plant":PLANT_status, "Supplier":SUPP_status}

    basicFont = pygame.font.SysFont(None, 24)
    largeFont = pygame.font.SysFont(None, 35)
    pygame.display.set_caption('SCREAM!')
    if debug_mode: R=1
    else: R= rd.randint(0,25)
    scenario_score={"cost":0, "service":0}

    while not done1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done1 = True
            #if event.type == pygame.KEYDOWN:
            #    if event.key == pygame.K_DOWN:
            #        paused()
        end_of_one_run=1
        total_lost_customer=0
        cumulative_inv_holding_cost=0
        total_fixed_cost_paid=0
        table_output=[]
        chart_output=[]
        header=["Week","Demand","Upstream shipment", "Shipment from regular DC", "Shipment from backup DC",
                "FG Inv at Reg. DC", "FG Inv at B/up. DC", "FG Inv as B/up","LostSales","Start Order for b/up DC", "B/up DC starts","DC Disruption at","Disruption duration", "TotalAvailableWIPSupplyCap",
                "Start Order for b/up Supplier", "B/up Supplier starts","Supplier Disruption at","Disruption duration", "Storage Cap Available", "Plant production",
                 "WIP Inv as B/up","Start Order for b/up Plant", "B/up Plant starts","Plant Disruption at","Disruption duration"]
        table_output.append(header)
        for t in range(1,P+1): # for the specified number of periods
            screen.fill((0, 0, 0))
            picture = pygame.image.load('Background.png').convert() #MITwallpaper
            screen.blit(picture, [0, 0])
            #import pdb; pdb.set_trace()
            ################################## MAKE CALCULATIONS FOR t>0 ################
            grand_record,output=exercise.calculate(t, grand_record[t-1]["Plant"], grand_record[t-1]["Supplier"], grand_record[t-1]["DC"], disruption, DC_BUp_Plan, Plant_BUp_Plan,  Supp_BUp_Plan,Demand[R*P+t],grand_record,debug_mode)
            chart_output=exercise.prepare_chart_output(chart_output, grand_record)
            output_loc=copy.deepcopy(output)
            table_output.append(output_loc)
            end_of_one_run=end_of_one_run+1

            objectives=exercise.calculate_objectives(grand_record, DC_BUp_Plan, Plant_BUp_Plan, Supp_BUp_Plan, t)

            lost_cust_text = largeFont.render("Service: "+str(objectives["Service"]), True, WHITE, BLACK)
            lost_cust_textRect = lost_cust_text.get_rect()
            lost_cust_textRect.centerx = 380
            lost_cust_textRect.centery = 420
            pygame.draw.rect(screen, RED, (lost_cust_textRect.left - 3, lost_cust_textRect.top - 3, lost_cust_textRect.width + 3, lost_cust_textRect.height + 3))
            screen.blit(lost_cust_text, lost_cust_textRect)
            inv_hold_text = largeFont.render("Inv.Holding Cost(k$): "+str(round(objectives["InvHoldingCost"]*0.001,1)), True, WHITE, BLACK)
            inv_hold_textRect = inv_hold_text.get_rect()
            inv_hold_textRect.centerx = 600
            inv_hold_textRect.centery = 445
            pygame.draw.rect(screen, RED, (inv_hold_textRect.left - 3, inv_hold_textRect.top - 3, inv_hold_textRect.width + 3, inv_hold_textRect.height + 3))
            screen.blit(inv_hold_text, inv_hold_textRect)
            startup_text = largeFont.render("Startup Cost(k$): "+str(round(objectives["Startup_cost"]*0.001,1)), True, WHITE, BLACK)
            startup_textRect = startup_text.get_rect()
            startup_textRect.centerx = 840
            startup_textRect.centery = 470
            pygame.draw.rect(screen, RED, (startup_textRect.left - 3, startup_textRect.top - 3, startup_textRect.width + 3, startup_textRect.height + 3))
            screen.blit(startup_text, startup_textRect)

            ###################################################################################
            if t<P:
                pygame.display.flip()
                clock.tick(8)
            else:
                #import pdb; pdb.set_trace()
                table = pd.DataFrame(table_output)
                table.to_excel("Details.xlsx",index=False)

        #import pdb; pdb.set_trace()
        done1 = True
    ################################ Want A PARETO Button     ###################################
    x=500
    y=500
    w=200
    h=50
    pygame.draw.rect(screen, DEEPSKYBLUE,(x,y,w,h))
    buttontext = basicFont.render("Want A Pareto Solution?", True, BLACK , WHITE )
    buttontext_rect=buttontext.get_rect()
    buttontext_rect.centerx = (x+(w/2))
    buttontext_rect.centery = (y+(h/2))
    screen.blit(buttontext, buttontext_rect)
    pygame.display.flip()
    pygame.time.delay(120)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    exercise.plotcharts(chart_output)
################################################################################
animate()

Body:
my guess is that it crashes when trying to load the background image:

picture = pygame.image.load('Background.png').convert() #MITwallpaper

When pyinstaller compiles your code, that is all it compiles (including the imported dependencies). It creates the dist directory where you can run your executable and you are good to go.

But, by default, pyinstaller will not pull in external resources. So when you run the executable, it can't find your image because it is in a different directory. You can test this by manually copying the image to the folder where the exe is located and see if it works.

Also, you can run the exe and push the output into a debug file:

your_file.exe > debug.txt

This way you can capture the output from your program (including error messages).


来源: stackexchange

问:
Conditionally display results by key
Given the following sample data, I need to display the results by type:

```<code>{
    "count": 50,
    "data": [{
        "id": "title",
        "image": "https://url-to-image.jpg",
        "permalink": "/folder/bob/",
        "text": "lots of text",
        "title": "Bob",
        "type": "User"
    }, {
        "id": "title2",
        "image": "https://url-to-image2.jpg",
        "permalink": "/folder/joe/",
        "text": "lots of text here",
        "title": "Joe",
        "type": "Article"
    }, {
        "id": "title3",
        "image": "https://url-to-image3.jpg",
        "permalink": "/attorneys/jim/",
        "text": "lots of text here",
        "title": "Jim",
        "type": "Blog"
    }]
}
</code>```

I'm trying to run a condition that if the type is a certain one, to display those posts:

```<code>$("#searchterm").keyup(function(e) {
   var q = $("#searchterm").val();
   //Only begin search with at least 3 characters.
   if(q.length > 3){
      ajax_search();
   }
   //Send search query
   function ajax_search(){
   $.getJSON("http://url-to-search?q=" + q, {
            dataType:'jsonp'
     },
     //Get results and make 'em look good
     function(data) {
       console.log(data);
       $(".results").empty();
      //  $(".results").append("Results for <b> " + q + "</b>");
         $.each(data.data, function(i, data) {
                     if(data.type === 'Article'){
             $(".articles").append("<li><a href=localhost:4000" + data.permalink + ">" + data.title + "</a></li>");
                     } else if(data.type === 'Blog'){
                         $(".blog").append("<li><a href=localhost:4000" + data.permalink + ">" + data.title + "</a></li>");
                     }
         });
      });
    }
});
</code>```

However, the results come up empty, although there are results without the conditional statements.

In the end, the results should look like this:

Article

Joe

Blog

Jim

答:
I guess you want something like this:

var result = {
    "count": 50,
    "data": [{
        "id": "title",
        "image": "https://url-to-image.jpg",
        "permalink": "/folder/bob/",
        "text": "lots of text",
        "title": "Bob",
        "type": "User"
    }, {
        "id": "title2",
        "image": "https://url-to-image2.jpg",
        "permalink": "/folder/joe/",
        "text": "lots of text here",
        "title": "Joe",
        "type": "Article"
    }, {
        "id": "title3",
        "image": "https://url-to-image3.jpg",
        "permalink": "/attorneys/jim/",
        "text": "lots of text here",
        "title": "Jim",
        "type": "Blog"
    }]
};

var filteredView = function(data,type,divclass){
  var filteredResults = $.grep(data, function(d){ return d.type == type; });
  var container = $("

").appendTo("#results");
  for(i in filteredResults){
     container.append("

" + filteredResults[i].title + "

" + filteredResults[i].text + "

");
  }
};

filteredView(result["data"],"Article","article");
filteredView(result["data"],"Blog","blog");
filteredView(result["data"],"User","user");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div></code>```

ContentLicense: CC BY-SA 3.0

Title: Conditionally display results by key

Body:
Given the following sample data, I need to display the results by type:

{
    "count": 50,
    "data": [{
        "id": "title",
        "image": "https://url-to-image.jpg",
        "permalink": "/folder/bob/",
        "text": "lots of text",
        "title": "Bob",
        "type": "User"
    }, {
        "id": "title2",
        "image": "https://url-to-image2.jpg",
        "permalink": "/folder/joe/",
        "text": "lots of text here",
        "title": "Joe",
        "type": "Article"
    }, {
        "id": "title3",
        "image": "https://url-to-image3.jpg",
        "permalink": "/attorneys/jim/",
        "text": "lots of text here",
        "title": "Jim",
        "type": "Blog"
    }]
}

I'm trying to run a condition that if the type is a certain one, to display those posts:

$("#searchterm").keyup(function(e) {
   var q = $("#searchterm").val();
   //Only begin search with at least 3 characters.
   if(q.length > 3){
      ajax_search();
   }
   //Send search query
   function ajax_search(){
   $.getJSON("http://url-to-search?q=" + q, {
            dataType:'jsonp'
     },
     //Get results and make 'em look good
     function(data) {
       console.log(data);
       $(".results").empty();
      //  $(".results").append("Results for  " + q + "");
         $.each(data.data, function(i, data) {
                     if(data.type === 'Article'){
             $(".articles").append("
" + data.title + "
");
                     } else if(data.type === 'Blog'){
                         $(".blog").append("
" + data.title + "
");
                     }
         });
      });
    }
});

However, the results come up empty, although there are results without the conditional statements.

In the end, the results should look like this:

Article

Joe

Blog

Jim

Body:
I guess you want something like this:

var result = {
    "count": 50,
    "data": [{
        "id": "title",
        "image": "https://url-to-image.jpg",
        "permalink": "/folder/bob/",
        "text": "lots of text",
        "title": "Bob",
        "type": "User"
    }, {
        "id": "title2",
        "image": "https://url-to-image2.jpg",
        "permalink": "/folder/joe/",
        "text": "lots of text here",
        "title": "Joe",
        "type": "Article"
    }, {
        "id": "title3",
        "image": "https://url-to-image3.jpg",
        "permalink": "/attorneys/jim/",
        "text": "lots of text here",
        "title": "Jim",
        "type": "Blog"
    }]
};

var filteredView = function(data,type,divclass){
  var filteredResults = $.grep(data, function(d){ return d.type == type; });
  var container = $("<div class='"+divclass+"'></div>").appendTo("#results");
  for(i in filteredResults){
     container.append("<div><h3>" + filteredResults[i].title + "</h3><p>" + filteredResults[i].text + "</p></div>");
  }
};

filteredView(result["data"],"Article","article");
filteredView(result["data"],"Blog","blog");
filteredView(result["data"],"User","user");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div>


问:
Javascript Regex: Replace under score and letter
I would like to create a efficient javascript regex to get the following result:

```<code>"first_name" => "firstName"
"user_address_id" => "userAddressId"
</code>```

So i want to replace every underscore and the following character with the character in upper case.

答:
try something like this </p>

```<code>var myString = 'first_name'
var camel = myString.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });
</code>```

Body:
I would like to create a efficient javascript regex to get the following result:

"first_name" => "firstName"
"user_address_id" => "userAddressId"

So i want to replace every underscore and the following character with the character in upper case.

Body:
try something like this

var myString = 'first_name'
var camel = myString.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });


问:
Send multiple data using href in Aurelia
How to send multiple data using href in Aurelia? </p>

```<code>This works: <a href="#/candidate/upload/${cid}?t=${item.heading}">
</code>```

<p>Just need the syntax. </p>

```<code>Not working:<a href="#/candidate/upload/${cid}?t=${item.heading};s=${item.sw_casedocumentid}">
</code>```

答:
This can be done using the route-href custom attribute. I'm guessing you have a route configuration that looks something like this:

```<code>{ route: 'candidate/upload/:cid', name: 'upload', ... }
</code>```

The cool thing with the router is that if you pass it parameters that don't exist on a route, it will just add them to the query string:

```<code><a route-href="route: 'upload',
               params.bind: { cid: cid; t: item.heading; s: item.sw_casedocumentid }"></a>
</code>```

This will produce a link that looks how you want it to look.

Body:
How to send multiple data using href in Aurelia?

This works:

Just need the syntax.

Not working:

Body:
This can be done using the route-href custom attribute. I'm guessing you have a route configuration that looks something like this:

{ route: 'candidate/upload/:cid', name: 'upload', ... }

The cool thing with the router is that if you pass it parameters that don't exist on a route, it will just add them to the query string:

<a route-href="route: 'upload',
               params.bind: { cid: cid; t: item.heading; s: item.sw_casedocumentid }"></a>

This will produce a link that looks how you want it to look.


问:
Reading specific column from file when last few rows are not equivalent in python
I have a problem during the reading of a text file in python. Basically what I need is to get the 4th column in a list.

With this small function I achieve it without any great issues:

```<code>def load_file(filename):

    f = open(filename, 'r')

   # skip the first useless row
   line = list(f.readlines()[1:])

   total_sp = []

    for i in line:
        t = i.strip().split()
        total_sp.append(int(t[4]))

    return total_sp
</code>```

but now I have to manage files, that in the last row(s) have any random number that don't respect the text format. An example of the not working text file is:

```<code>#generated file
well10_1         3        18         6         1         2  -0.01158   0.01842       142
well5_1         1        14         6         1         2  0.009474   0.01842       141
well4_1         1        13         4         1         2  -0.01842  -0.03737       125
well7_1         3        10         1         1         2 -0.002632  0.009005       101
well3_1         1        10         9         1         2  -0.03579  -0.06368       157
well8_1         3        10        10         1         2  -0.06895   -0.1021       158
well9_1         3        10        18         1         2   0.03053   0.02158       176
well2_1         1         4         4         1         2  -0.03737  -0.03737       128
well6_1         3         4         5         1         2  -0.07053   -0.1421       127
well1_1        -2         3         1         1         2  0.006663  -0.02415       128
         1    0.9259
         2   0.07407
</code>```

where 1    0.9259 and 2   0.07407 have to be dumped.

In fact, using the function of above with this text file, I get the following error because of the 2 additional last rows:

```<code>Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/tmp/tmpqi8Ktw.py", line 21, in load_obh
    total_sp.append(int(t[4]))
IndexError: list index out of range
</code>```

How can I get rid of the last lines in the line variable?

Thanks to all

答:
f.readlines already returns a list. Just as you provide a start index to slice from, you can specify "2 before the end" using negative indexing as below:

```<code>line = f.readlines()[1:-2]
</code>```

Should do the trick.

EDIT: To handle an arbitrary number of lines at the end:

```<code>def load_file(filename):
    f = open(filename, 'r')

    # skip the first useless row
    line = f.readlines()[1:]

    total_sp = []
    for i in line:
        t = i.strip().split()
        # check if enough columns were found
        if len(t) >= 5:
            total_sp.append(int(t[4]))

    return total_sp
</code>```

Body:
I have a problem during the reading of a text file in python. Basically what I need is to get the 4th column in a list.

With this small function I achieve it without any great issues:

def load_file(filename):

    f = open(filename, 'r')

   # skip the first useless row
   line = list(f.readlines()[1:])

   total_sp = []

    for i in line:
        t = i.strip().split()
        total_sp.append(int(t[4]))

    return total_sp

but now I have to manage files, that in the last row(s) have any random number that don't respect the text format. An example of the not working text file is:

#generated file
well10_1         3        18         6         1         2  -0.01158   0.01842       142
well5_1         1        14         6         1         2  0.009474   0.01842       141
well4_1         1        13         4         1         2  -0.01842  -0.03737       125
well7_1         3        10         1         1         2 -0.002632  0.009005       101
well3_1         1        10         9         1         2  -0.03579  -0.06368       157
well8_1         3        10        10         1         2  -0.06895   -0.1021       158
well9_1         3        10        18         1         2   0.03053   0.02158       176
well2_1         1         4         4         1         2  -0.03737  -0.03737       128
well6_1         3         4         5         1         2  -0.07053   -0.1421       127
well1_1        -2         3         1         1         2  0.006663  -0.02415       128
         1    0.9259
         2   0.07407

where 1    0.9259 and 2   0.07407 have to be dumped.

In fact, using the function of above with this text file, I get the following error because of the 2 additional last rows:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/tmp/tmpqi8Ktw.py", line 21, in load_obh
    total_sp.append(int(t[4]))
IndexError: list index out of range

How can I get rid of the last lines in the line variable?

Thanks to all

Body:
f.readlines already returns a list. Just as you provide a start index to slice from, you can specify "2 before the end" using negative indexing as below:

line = f.readlines()[1:-2]

Should do the trick.

EDIT: To handle an arbitrary number of lines at the end:

def load_file(filename):
    f = open(filename, 'r')

    # skip the first useless row
    line = f.readlines()[1:]

    total_sp = []
    for i in line:
        t = i.strip().split()
        # check if enough columns were found
        if len(t) >= 5:
            total_sp.append(int(t[4]))

    return total_sp


问:
Enabling github pre commit hooks in origin for all collaborators
first: We use a github repository in the team for some projects.
I'm using scripts defined in the pre-commit hook directory, locally (works perfect for my commits).

What I need is for every user (collaborator) to use the hooks without using symlinks or asking them to put them on their home folders.

Is there a way to set them up so the users can't commit if the scripts don't exit 0?.

Thanks.

答:
As Henrik alluded to, in the Enterprise version, there is such a thing as the pre-receive hook.  It runs server side and so you would not need to install it on each collaborator's local machine.  But you are using github.com actual, and they don't allow pre receive hooks , nor do I expect they plan to; allowing indivduals to run scripts on their server isn't likely in their business plan. So that likely won't help you unless you are in a position to go to the enterprise product

There are some remedies you do have, however, but it won't be equivalent.  You can , for example, set a protected branch . You could thereby make it only you can check into that branch, and you of course would be using the local hook, every one else would be using a pull request.

Additionally, you could look into LGTM (Looks Good To Me) or similar automated pull request approval system.  I don't believe the official server is up but the source code is there and it could be run by someone else.  LGTM allows you to set a number of different conditions that would be closer to an equivalent to your pre-op hook.

Setting up such a system might well be more effort than it is worth to you, understandable; but it is do-able.

The main problem with using pre-commit hooks that come with git is that they  are local to your repos and don't get pushed to github.com.  I believe under the hood, those hooks aren't even transferred up to the repo on github, and that the pre-commit hook directory itself is not available like it is on the local copy of a git repo.

(I would say more on that architecture of the pre-commit hook dir except A. I am not sure if it is covered by NDA and B. I only saw the way it was on the Enterprise product, not github actual, and C. I don't know if the structure is still exactly the same)

OwnerDisplayName: Rancor


问:
$wpdb return empty with date selection
I'm working on a WordPress calendar plugin, with possibility to add events attached to one date. Events are stored in a custom database that works fine.

But I've got troubles with a function in wich I use a '$wpdb->get_results'
This function need a date as parameter.
This is my code :

```<code>function get_events_list($day) {

    global $wpdb
    $table = $wpdb->prefix . "mytable";

    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = $day)", ARRAY_A );

    var_dump($events_list);

}
</code>```

'var_dump($events_list)' returns an empty array, but I've got entries in the table.

I tried the function with no paramater, entering a well-formated date directly in the sql request, like that :

```<code>function get_events_list() {
    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = '2017-03-30')", ARRAY_A );
}
</code>```

This works great.

I also did a 'var_dump($wpdb->last_query)', trying to find what happen.

Tested with no parameter (hard-coded '2017-03-30'), wich is working fine, the last_query returns :

```<code>'SELECT * FROM wp_mytable WHERE date = '2017-03-30')'
</code>```

With dynamic paramater, it returns the date without quote :

```<code>'SELECT * FROM wp_mytable WHERE date = 2017-03-30)'
</code>```

I think I'm pointing the problem but cannot resolve it (I tried a lot of things).
Could Someone help me please ? Thank you :)

答:
Use quotes man -

```<code>$events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = '$day')", ARRAY_A );
</code>```

without those quotes it is becoming  WHERE date = 2017-03-30

Title: $wpdb return empty with date selection

Body:
I'm working on a WordPress calendar plugin, with possibility to add events attached to one date. Events are stored in a custom database that works fine.

But I've got troubles with a function in wich I use a '$wpdb->get_results'
This function need a date as parameter.
This is my code :

function get_events_list($day) {

    global $wpdb
    $table = $wpdb->prefix . "mytable";

    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = $day)", ARRAY_A );

    var_dump($events_list);

}

'var_dump($events_list)' returns an empty array, but I've got entries in the table.

I tried the function with no paramater, entering a well-formated date directly in the sql request, like that :

function get_events_list() {
    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = '2017-03-30')", ARRAY_A );
}

This works great.

I also did a 'var_dump($wpdb->last_query)', trying to find what happen.

Tested with no parameter (hard-coded '2017-03-30'), wich is working fine, the last_query returns :

'SELECT * FROM wp_mytable WHERE date = '2017-03-30')'

With dynamic paramater, it returns the date without quote :

'SELECT * FROM wp_mytable WHERE date = 2017-03-30)'

I think I'm pointing the problem but cannot resolve it (I tried a lot of things).
Could Someone help me please ? Thank you :)

Body:
Use quotes man -

$events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = '$day')", ARRAY_A );

without those quotes it is becoming  WHERE date = 2017-03-30


问:
.NET / Entity Framework - System.Data.UpdateException not precise enough?
i got thrown into a small .NET migration project that is using the Entity Framework and MS SQL Server 2005. when persisting data that is not working with db schema (e.g. a string is too long), I am getting an exception System.Data.UpdateException that says "String or binary data would be truncated". But there is no information to which field it relates. does someone has a clue how to get this?

thx

here the stacktrace:

```<code>   at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
   at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
   at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Objects.ObjectContext.SaveChanges()
   at HAM.Inventory.Data.Repository.DocumentRepository.Save(Document document) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.Data\Repository\DocumentRepository.cs:line 177
   at HAM.Inventory.Business.Managers.DocumentManager.Save(Document document) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.Business\Managers\DocumentManager.cs:line 75
   at HAM.Inventory.MigrationClient.Common.Migration.SaveItem(ItemBase item) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.MigrationClient\Common\Migration.cs:line 143
   at HAM.Inventory.MigrationClient.Common.Migration.SaveAndClearItems(List`1 items) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.MigrationClient\Common\Migration.cs:line 76
</code>```

and the inner exception:

```<code>at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
</code>```

答: Look at the StateEntries property. It should have all the failing objects.

ContentLicense: CC BY-SA 2.5

Body:
i got thrown into a small .NET migration project that is using the Entity Framework and MS SQL Server 2005. when persisting data that is not working with db schema (e.g. a string is too long), I am getting an exception System.Data.UpdateException that says "String or binary data would be truncated". But there is no information to which field it relates. does someone has a clue how to get this?

thx

here the stacktrace:

   at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
   at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
   at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Objects.ObjectContext.SaveChanges()
   at HAM.Inventory.Data.Repository.DocumentRepository.Save(Document document) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.Data\Repository\DocumentRepository.cs:line 177
   at HAM.Inventory.Business.Managers.DocumentManager.Save(Document document) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.Business\Managers\DocumentManager.cs:line 75
   at HAM.Inventory.MigrationClient.Common.Migration.SaveItem(ItemBase item) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.MigrationClient\Common\Migration.cs:line 143
   at HAM.Inventory.MigrationClient.Common.Migration.SaveAndClearItems(List`1 items) in D:\ludewigg\Documents\Projects\HAM\src\VBS-HAM-Inventory\Main\HAM.Inventory.MigrationClient\Common\Migration.cs:line 76

and the inner exception:

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)


问:
Correct use of pivot in Cholesky decomposition of positive semi-definite matrix
I don't understand how to use the chol function in R to factor a positive semi-definite matrix. (Or I do, and there's a bug.) The documentation states:

If pivot = TRUE, then the Choleski decomposition of a positive semi-definite x can be computed. The rank of x is returned as attr(Q, "rank"), subject to numerical errors. The pivot is returned as attr(Q, "pivot"). It is no longer the case that t(Q) %*% Q equals x. However, setting pivot <- attr(Q, "pivot") and oo <- order(pivot), it is true that t(Q[, oo]) %*% Q[, oo] equals x ...

The following example seems to belie this description.

```<code>> x <- matrix(1, nrow=3, ncol=3)
> Q <- chol(x, pivot=TRUE)
> oo <- order(attr(Q, 'pivot'))
> t(Q[, oo]) %*% Q[, oo]
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    3
</code>```

The result is not x. Am I using the pivot incorrectly?

答:
For full rank input, i.e., a positive-definite matrix x, we need

```<code>Q <- chol(x, TRUE)
oo <- order(attr(Q, 'pivot'))
unpivQ <- Q[, oo]
all.equal(crossprod(unpivQ), x)
</code>```

For a valid rank-deficient input, i.e., a positive semi-definite matrix x (indefinite matrix with negative eigen values are illegal, but not checked in chol), remember to zero deficient trailing diagonal block:

```<code>Q <- chol(x, TRUE)
r <- attr(Q, 'rank')
if (r < nrow(x)) Q[(r+1):nrow(x), (r+1):nrow(x)] <- 0
oo <- order(attr(Q, 'pivot'))
unpivQ <- Q[, oo]
all.equal(crossprod(unpivQ), x)
</code>```

Some people call this a 'bug' of chol, but actually it is a feature of the underlying LAPACK routine dpstrf. The factorization proceeds till the first diagonal element which is below a tolerance, leaving the trailing matrix simply untouched on exit.

Thanks to Ian for the following observation:

You could use R's negative indexing in Q[-(1:r), -(1:r)] <- 0 to skip the if statement.

OwnerDisplayName: Ian

Body:
I don't understand how to use the chol function in R to factor a positive semi-definite matrix. (Or I do, and there's a bug.) The documentation states:

If pivot = TRUE, then the Choleski decomposition of a positive semi-definite x can be computed. The rank of x is returned as attr(Q, "rank"), subject to numerical errors. The pivot is returned as attr(Q, "pivot"). It is no longer the case that t(Q) %*% Q equals x. However, setting pivot <- attr(Q, "pivot") and oo <- order(pivot), it is true that t(Q[, oo]) %*% Q[, oo] equals x ...

The following example seems to belie this description.

> x <- matrix(1, nrow=3, ncol=3)
> Q <- chol(x, pivot=TRUE)
> oo <- order(attr(Q, 'pivot'))
> t(Q[, oo]) %*% Q[, oo]
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    3

The result is not x. Am I using the pivot incorrectly?

Body:
For full rank input, i.e., a positive-definite matrix x, we need

Q <- chol(x, TRUE)
oo <- order(attr(Q, 'pivot'))
unpivQ <- Q[, oo]
all.equal(crossprod(unpivQ), x)

For a valid rank-deficient input, i.e., a positive semi-definite matrix x (indefinite matrix with negative eigen values are illegal, but not checked in chol), remember to zero deficient trailing diagonal block:

Q <- chol(x, TRUE)
r <- attr(Q, 'rank')
if (r < nrow(x)) Q[(r+1):nrow(x), (r+1):nrow(x)] <- 0
oo <- order(attr(Q, 'pivot'))
unpivQ <- Q[, oo]
all.equal(crossprod(unpivQ), x)

Some people call this a 'bug' of chol, but actually it is a feature of the underlying LAPACK routine dpstrf. The factorization proceeds till the first diagonal element which is below a tolerance, leaving the trailing matrix simply untouched on exit.

Thanks to Ian for the following observation:

You could use R's negative indexing in Q[-(1:r), -(1:r)] <- 0 to skip the if statement.

ContentLicense: CC BY-SA 4.0


问:
Existing name code (java)
I have problem with my school assignment (java code) i would like an warrning message with name that it is already exsits! everything is working fine but i just want to add a code in the brackets.</p>

```<code> public void add (Wapen index)
    {
        if (wapen.contains(index)){
            wapen.add(index);
            System.out.println(" message");

    }else {
        System.out.println("message ");

    }
}
</code>```

答:
you should also pass the name as parameter and then use this parameter where you want to display name.

Method signature should be like this.

```<code>public void addWapen (SuperWapen index, String name)
{ your code  }
</code>```

Title: Existing name code (java)

Body:
I have problem with my school assignment (java code) i would like an warrning message with name that it is already exsits! everything is working fine but i just want to add a code in the brackets.

 public void add (Wapen index)
    {
        if (wapen.contains(index)){
            wapen.add(index);
            System.out.println(" message");

    }else {
        System.out.println("message ");

    }
}

Body:
you should also pass the name as parameter and then use this parameter where you want to display name.

Method signature should be like this.

public void addWapen (SuperWapen index, String name)
{ your code  }


问:
jtable data getting replaced with previous result when double clicked
I am developing one application in Swing in which I scan data from some files and show it in JTable on UI and when I double click on row respective file gets opened. Code of 'Scan' button is as follows,

```<code>JButton btnStart = new JButton("Scan");
    btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

                File dir = new File(chooser.getSelectedFile(), chooser.getSelectedFile().getAbsolutePath());
                System.out.println("dir " + dir);
                File[] firstLevelFiles = chooser.getSelectedFile().listFiles();
                if (firstLevelFiles != null && firstLevelFiles.length > 0) {
                    for (File aFile : firstLevelFiles) {
                        if (aFile.isDirectory()) {
                            listDirectory(aFile.getAbsolutePath(), level + 1);
                        } else {
                            fileExt=aFile.getName().substring(aFile.getName().lastIndexOf(".")+1);
                            for (String string : selectedExt) {
                                if(string.equals(fileExt)){
                                    fileList.add(aFile);
                                }
                            }
                        }
                    }
                }

                MyFileReader myFileReader=new MyFileReader();

                new Thread(new Runnable(){
                    @Override
                    public void run(){

                        fileMap=myFileReader.fileReader(fileList, filepath);
                       if(!fileMap.isEmpty()){
                         SwingUtilities.invokeLater(new Runnable(){
                             @Override public void run(){

                                    int tableSize=myFileReader.getTableSize();

                                    tableData=new String[tableSize][4];
                                    Iterator it = fileMap.entrySet().iterator();
                                    int j=0;
                                    int k=0;
                                    while (it.hasNext()) {
                                        Map.Entry pair = (Map.Entry) it.next();
                                        List<String> ls = (List<String>) pair.getValue();
                                        for (int i = 1; i <= ls.size(); i++) {
                                            if(k==1){
                                                k++;
                                                i--;
                                                continue;
                                            }

                                            tableData[j][1]=pair.getKey().toString();
                                            tableData[j][k]=ls.get(i-1).toString();
                                            k++;
                                            if(k==4){
                                                k=0;
                                                j++;
                                            }
                                        }
                                    }
                                     model = new DefaultTableModel(tableData, columns)
                                      {
                                        public boolean isCellEditable(int row, int column)
                                        {
                                          return false;//This causes all cells to be not editable
                                        }
                                      };

                                    table = new JTable(model);
                                    table.setEnabled(true);
                                    JTableHeader header = table.getTableHeader();
                                    header.setBackground(Color.LIGHT_GRAY);
                                    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                                    table.setCellSelectionEnabled(true);
                                    table.getColumnModel().getColumn(0).setPreferredWidth(5);
                                    table.getColumnModel().getColumn(1).setPreferredWidth(400);
                                    table.getColumnModel().getColumn(2).setPreferredWidth(5);
                                    table.getColumnModel().getColumn(3).setPreferredWidth(5);

                                    pane = new JScrollPane(table);
                                    pane.setBounds(70,250,1000,300);
                                    pane.setVisible(true);
                                    contentPane.add(pane,BorderLayout.CENTER);

                                    table.addMouseListener(new MouseAdapter() {
                                         public void mouseClicked(MouseEvent e) {
                                            if (e.getClickCount() == 2) {
                                                int columnChk=table.getSelectedColumn();
                                                if (columnChk == 1) {
                                                    String fpath = getSelectedData(table);

                                                    try {
                                                        Runtime runtime = Runtime.getRuntime();
                                                        runtime.exec("explorer " + fpath);

                                                    } catch (IOException e1) {
                                                        // TODO Auto-generated catch block
                                                        e1.printStackTrace();
                                                    }
                                                }
                                            }
                                         }
                                      });
                                 scanProg.setText("Scanning Completed");
                           }
                          });
                       }else {
                            scanProg.setText("No codebase found");
                       }
                    }
                    }).start();
            }

        }
    });
    btnStart.setBounds(324, 154, 89, 23);
    contentPane.add(btnStart);
</code>```

Now, when I rescan files without closing frame new data is getting filled in JTable but once I double click on any row it's data is getting replaced with previous one which is not desired.I want to clear data from table from privious scan. Already have tried JTable.removeall() but it didnt helped.
Screenshot of table is here
Any idea?

答:
```<code>table = new JTable(model);
</code>```

Don't keep creating new components. Instead you can update the data of the existing table by using:

```<code>table.setModel( model );
</code>```

.I want to clear data from table from privious scan

Or instead of creating a completely new DefaultTableModel you can use the exiting model.

You clear the data by using:

```<code>model.setRowCount( 0 );
</code>```

and you add rows of data by using:

```<code>model.addRow(...);
</code>```

Body:
I am developing one application in Swing in which I scan data from some files and show it in JTable on UI and when I double click on row respective file gets opened. Code of 'Scan' button is as follows,

JButton btnStart = new JButton("Scan");
    btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

                File dir = new File(chooser.getSelectedFile(), chooser.getSelectedFile().getAbsolutePath());
                System.out.println("dir " + dir);
                File[] firstLevelFiles = chooser.getSelectedFile().listFiles();
                if (firstLevelFiles != null && firstLevelFiles.length > 0) {
                    for (File aFile : firstLevelFiles) {
                        if (aFile.isDirectory()) {
                            listDirectory(aFile.getAbsolutePath(), level + 1);
                        } else {
                            fileExt=aFile.getName().substring(aFile.getName().lastIndexOf(".")+1);
                            for (String string : selectedExt) {
                                if(string.equals(fileExt)){
                                    fileList.add(aFile);
                                }
                            }
                        }
                    }
                }

                MyFileReader myFileReader=new MyFileReader();

                new Thread(new Runnable(){
                    @Override
                    public void run(){

                        fileMap=myFileReader.fileReader(fileList, filepath);
                       if(!fileMap.isEmpty()){
                         SwingUtilities.invokeLater(new Runnable(){
                             @Override public void run(){

                                    int tableSize=myFileReader.getTableSize();

                                    tableData=new String[tableSize][4];
                                    Iterator it = fileMap.entrySet().iterator();
                                    int j=0;
                                    int k=0;
                                    while (it.hasNext()) {
                                        Map.Entry pair = (Map.Entry) it.next();
                                        List<String> ls = (List<String>) pair.getValue();
                                        for (int i = 1; i <= ls.size(); i++) {
                                            if(k==1){
                                                k++;
                                                i--;
                                                continue;
                                            }

                                            tableData[j][1]=pair.getKey().toString();
                                            tableData[j][k]=ls.get(i-1).toString();
                                            k++;
                                            if(k==4){
                                                k=0;
                                                j++;
                                            }
                                        }
                                    }
                                     model = new DefaultTableModel(tableData, columns)
                                      {
                                        public boolean isCellEditable(int row, int column)
                                        {
                                          return false;//This causes all cells to be not editable
                                        }
                                      };

                                    table = new JTable(model);
                                    table.setEnabled(true);
                                    JTableHeader header = table.getTableHeader();
                                    header.setBackground(Color.LIGHT_GRAY);
                                    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                                    table.setCellSelectionEnabled(true);
                                    table.getColumnModel().getColumn(0).setPreferredWidth(5);
                                    table.getColumnModel().getColumn(1).setPreferredWidth(400);
                                    table.getColumnModel().getColumn(2).setPreferredWidth(5);
                                    table.getColumnModel().getColumn(3).setPreferredWidth(5);

                                    pane = new JScrollPane(table);
                                    pane.setBounds(70,250,1000,300);
                                    pane.setVisible(true);
                                    contentPane.add(pane,BorderLayout.CENTER);

                                    table.addMouseListener(new MouseAdapter() {
                                         public void mouseClicked(MouseEvent e) {
                                            if (e.getClickCount() == 2) {
                                                int columnChk=table.getSelectedColumn();
                                                if (columnChk == 1) {
                                                    String fpath = getSelectedData(table);

                                                    try {
                                                        Runtime runtime = Runtime.getRuntime();
                                                        runtime.exec("explorer " + fpath);

                                                    } catch (IOException e1) {
                                                        // TODO Auto-generated catch block
                                                        e1.printStackTrace();
                                                    }
                                                }
                                            }
                                         }
                                      });
                                 scanProg.setText("Scanning Completed");
                           }
                          });
                       }else {
                            scanProg.setText("No codebase found");
                       }
                    }
                    }).start();
            }

        }
    });
    btnStart.setBounds(324, 154, 89, 23);
    contentPane.add(btnStart);

Now, when I rescan files without closing frame new data is getting filled in JTable but once I double click on any row it's data is getting replaced with previous one which is not desired.I want to clear data from table from privious scan. Already have tried JTable.removeall() but it didnt helped.
Screenshot of table is here
Any idea?

Body:
table = new JTable(model);

Don't keep creating new components. Instead you can update the data of the existing table by using:

table.setModel( model );

.I want to clear data from table from privious scan

Or instead of creating a completely new DefaultTableModel you can use the exiting model.

You clear the data by using:

model.setRowCount( 0 );

and you add rows of data by using:

model.addRow(...);


问:
Alpha options for Azure ACS (Kubernetes)
Is it possible to enabled Alpha API options for Azure ACS Kubernetes instances? If so how?

For example

```<code>--enable-custom-metrics=true
</code>```

For horizontal auto scaling based on custom metrics

答: To maintain an SLA, clusters created by ACS limit the default use of alpha or beta features within Kubernetes.  To use more advanced features of ACS, visit https://github.com/Azure/acs-engine, and modify the kubelet yaml within the /parts directory. </p>

Body:
Is it possible to enabled Alpha API options for Azure ACS Kubernetes instances? If so how?

For example

--enable-custom-metrics=true

For horizontal auto scaling based on custom metrics


问:
Replace last character in sql column
I have data in table this way. If the ; is at the end I would like that replaced with a blank string if not I would leave data same way.

```<code>abc;
123;ghi;789
test123;
thisowns;
wer;567;457;test
</code>```

Result should be

```<code>abc
123;ghi;789
test123
thisowns
wer;567;457;test
</code>```

答:
You can use RIGHT() function like

```<code>case when RIGHT(col1, 1) = ';' then LEFT(col1, LEN(col1) - 1) end
</code>```

Title: Replace last character in sql column

Body:
I have data in table this way. If the ; is at the end I would like that replaced with a blank string if not I would leave data same way.

abc;
123;ghi;789
test123;
thisowns;
wer;567;457;test

Result should be

abc
123;ghi;789
test123
thisowns
wer;567;457;test

Body:
You can use RIGHT() function like

case when RIGHT(col1, 1) = ';' then LEFT(col1, LEN(col1) - 1) end


答:
Simply , replace _(.{1}) with \U\1\E

\Uturn upper every following char, then \E turns it off.

Title: Javascript Regex: Replace under score and letter

Body:
I would like to create a efficient javascript regex to get the following result:

"first_name" => "firstName"
"user_address_id" => "userAddressId"

So i want to replace every underscore and the following character with the character in upper case.


问:
Contact Form 7 Issue
I tested the contact form on my website and it doesn't work. On the back end, it tells my I have the following issue "Unavailable names (name) are used for form controls."
I couldn't figure out how to solve it after looking at their FAQs. My website address is www.garagedoormadisonwi.com and the code for my contact form is:

```<code><div class="our-form">
<div class="row">
    <div class="col-sm-6 col-md-6">
        <div class="form-group">
            [text* name class:form-control placeholder "Name"]
            <div class="input-bottom-line"></div>
        </div>
    </div>
    <div class="col-md-6 col-sm-6">
        <div class="form-group">
            [email* email class:form-control placeholder "Eamil"]
            <div class="input-bottom-line"></div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-6 col-sm-6">
        <div class="form-group">
            [text* address class:form-control placeholder "Address"]
            <div class="input-bottom-line"></div>
        </div>
    </div>
    <div class="col-md-6 col-sm-6">
        <div class="form-group">
            [tel* phone class:form-control placeholder "Phone"]
            <div class="input-bottom-line"></div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-sm-12 col-md-12">
        <div class="form-group">
            [textarea message class:form-control placeholder "Message"]
            <div class="input-bottom-line"></div>
        </div>
    </div>
</div>
<button type="submit" class="red-button bgcolor">
    [submit "submit"]
</button>
</code>```

I'd appreciate if you can help me change it so it works.

Thank you in advance!

答:
Let's consider the error message you provide:

```<code>"Unavailable names (name) are used for form controls."
</code>```

It cleary tells us that there's something wrong with your form controls (i.e. input field) naming. Next step is to look how you've named those element.

What I would assume is that the problem appear due to simplictic naming convention you're using for your form elements. Quick search through CF7 documentation gives us a possible solution:

The followings are parameter names that WordPress uses in a query: m, p, posts, w, cat, withcomments, withoutcomments, s, search, exact, sentence, calendar, page, paged, more, tb, pb, author, order, orderby, year, monthnum, day, hour, minute, second, name, category_name, tag, feed, author_name, static, pagename, page_id, error, attachment, attachment_id, subpost, subpost_id, preview, robots, taxonomy, term, cpage, post_type, and embed.

Soure: https://contactform7.com/faq/are-there-any-reserved-or-unavailable-words-for-the-name-of-an-input-field/

You can see that you cannot name your input control as "name".

Title: Contact Form 7 Issue

Body:
I tested the contact form on my website and it doesn't work. On the back end, it tells my I have the following issue "Unavailable names (name) are used for form controls."
I couldn't figure out how to solve it after looking at their FAQs. My website address is www.garagedoormadisonwi.com and the code for my contact form is:

            [text* name class:form-control placeholder "Name"]

            [email* email class:form-control placeholder "Eamil"]

            [text* address class:form-control placeholder "Address"]

            [tel* phone class:form-control placeholder "Phone"]

            [textarea message class:form-control placeholder "Message"]

<button type="submit" class="red-button bgcolor">
    [submit "submit"]
</button>

I'd appreciate if you can help me change it so it works.

Thank you in advance!

Body:
Let's consider the error message you provide:

"Unavailable names (name) are used for form controls."

It cleary tells us that there's something wrong with your form controls (i.e. input field) naming. Next step is to look how you've named those element.

What I would assume is that the problem appear due to simplictic naming convention you're using for your form elements. Quick search through CF7 documentation gives us a possible solution:

The followings are parameter names that WordPress uses in a query: m, p, posts, w, cat, withcomments, withoutcomments, s, search, exact, sentence, calendar, page, paged, more, tb, pb, author, order, orderby, year, monthnum, day, hour, minute, second, name, category_name, tag, feed, author_name, static, pagename, page_id, error, attachment, attachment_id, subpost, subpost_id, preview, robots, taxonomy, term, cpage, post_type, and embed.

Soure: https://contactform7.com/faq/are-there-any-reserved-or-unavailable-words-for-the-name-of-an-input-field/

You can see that you cannot name your input control as "name".


问:
Hyperledger peer creation error
I'm trying to create a genesis block with the command:

```<code>peer channel create -c myc
</code>```

following the install_instantiate.md file.

However I keep getting an error-message that there is no ordering service endpoint created. Somebody who can help me with this please?

答:
Have you tried to specifiy the orderer address ?

If you are using docker :

```<code>CORE_PEER_COMMITTER_LEDGER_ORDERER=orderer:7050 peer channel create -c myc
</code>```

If it doesn't work, try the Getting Setup, or see the Troubleshooting section

Title: Hyperledger peer creation error

Body:
I'm trying to create a genesis block with the command:

peer channel create -c myc

following the install_instantiate.md file.

However I keep getting an error-message that there is no ordering service endpoint created. Somebody who can help me with this please?

Body:
Have you tried to specifiy the orderer address ?

If you are using docker :

CORE_PEER_COMMITTER_LEDGER_ORDERER=orderer:7050 peer channel create -c myc

If it doesn't work, try the Getting Setup, or see the Troubleshooting section


问:
surrounding a pattern in python string with brackets
I have a string looks like this:

```<code>oldString="this is my {{string-d}}" => "this is my {{(string-d)}}"
oldString2="this is my second{{ new_string-d }}" => "this is my second{{ (new_string-d) }}"
oldString2="this is my second new_string-d " => "this is my second (new_string-d) "
oldString2="this is my second new[123string]-d " => "this is my second (new[123string]-d) "
</code>```

I want to add brackets whenever I see "-d" right after it and before the word that is attached to it.

I wrote a code that looks for the pattern "-d" in strings and partition the string after finding the pattern to 3 partitions before "-d", after "-d" and "-d" itself then I check the block before "-d" until I find whitespace or "{" and stop and add brackets. my code looks like this:
P.S. I have many files that I read from them and try to modify the string there the example above is just for demonstrating what I'm trying to do.

```<code>   if ('-d') in oldString:
    p = oldString.partition('-d')
    v = p[p.index('-d')-1]
    beforeString=''
    for i in reversed(v):
        if i != ' ' or i != '{':
            beforeString=i+beforeString
            indexNew = v.index(i)
    outPutLine = v[:indexNew]+'('+v[indexNew:]
    newString = outPutLine + '-d' + ' )'
    print newString
</code>```

the result of running the code will be:

```<code>newString = "(this is my {{string-d )"
</code>```

as you can see that the starting bracket is before "this" instead of before "string" why is this happening? also, I'm not sure if this is the best way to do this kind of find and replace any suggestions would be much appreciated.

答:
If you want the bracketing to only take place inside double curly braces, you need something like this:

re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)
```

<p>Breaking that down a bit:</p>

<pre class="lang-py prettyprint-override"><code># the target pattern
r'({{\s*)([^}]*-d)(\s*}})'
# ^^^^^^^ capture group 1, opening {{ plus optional space
#        ^^^^^^^^^ capture group 2, non-braces plus -d
#                 ^^^^^^^ capture 3, spaces plus closing }}
</code>```

The replacement r'\1(\2)\3' just assembles the groups, with
parenthesis around the middle one.

Putting it together:

import re

def quote_string_d(s):
    return re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)

print(quote_string_d("this is my {{string-d}}"))
print(quote_string_d("this is my second{{ new_string-d }}"))
print(quote_string_d("this should not be quoted other_string-d "))
```

<p>Output:</p>

<pre class="lang-py prettyprint-override"><code>this is my {{(string-d)}}
this is my second{{ (new_string-d) }}
this should not be quoted other_string-d
</code>```

Note the third instance does not get the parentheses, because it's not inside {{ }}.

Body:
I have a string looks like this:

oldString="this is my {{string-d}}" => "this is my {{(string-d)}}"
oldString2="this is my second{{ new_string-d }}" => "this is my second{{ (new_string-d) }}"
oldString2="this is my second new_string-d " => "this is my second (new_string-d) "
oldString2="this is my second new[123string]-d " => "this is my second (new[123string]-d) "

I want to add brackets whenever I see "-d" right after it and before the word that is attached to it.

I wrote a code that looks for the pattern "-d" in strings and partition the string after finding the pattern to 3 partitions before "-d", after "-d" and "-d" itself then I check the block before "-d" until I find whitespace or "{" and stop and add brackets. my code looks like this:
P.S. I have many files that I read from them and try to modify the string there the example above is just for demonstrating what I'm trying to do.

   if ('-d') in oldString:
    p = oldString.partition('-d')
    v = p[p.index('-d')-1]
    beforeString=''
    for i in reversed(v):
        if i != ' ' or i != '{':
            beforeString=i+beforeString
            indexNew = v.index(i)
    outPutLine = v[:indexNew]+'('+v[indexNew:]
    newString = outPutLine + '-d' + ' )'
    print newString

the result of running the code will be:

newString = "(this is my {{string-d )"

as you can see that the starting bracket is before "this" instead of before "string" why is this happening? also, I'm not sure if this is the best way to do this kind of find and replace any suggestions would be much appreciated.

Body:
If you want the bracketing to only take place inside double curly braces, you need something like this:

re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)

Breaking that down a bit:

# the target pattern
r'({{\s*)([^}]*-d)(\s*}})'
# ^^^^^^^ capture group 1, opening {{ plus optional space
#        ^^^^^^^^^ capture group 2, non-braces plus -d
#                 ^^^^^^^ capture 3, spaces plus closing }}

The replacement r'\1(\2)\3' just assembles the groups, with
parenthesis around the middle one.

Putting it together:

import re

def quote_string_d(s):
    return re.sub(r'({{\s*)([^}]*-d)(\s*}})', r'\1(\2)\3', s)

print(quote_string_d("this is my {{string-d}}"))
print(quote_string_d("this is my second{{ new_string-d }}"))
print(quote_string_d("this should not be quoted other_string-d "))

Output:

this is my {{(string-d)}}
this is my second{{ (new_string-d) }}
this should not be quoted other_string-d

Note the third instance does not get the parentheses, because it's not inside {{ }}.


问:
Check if element has CSS class. If not add it
How can I convert my jQuery lines below into Javascript. I'd like to check if this element has a class. If it doesn't have the CSS class I want to add it to the element. The lines are in asterisks below.

Jquery

```<code>    var slides = document.querySelectorAll('#slides .slide');
    var currentSlide = 0;

  function goToSlide(n){

  //Remove showing from the current slide
    var thisSlide = slides[currentSlide];

    thisSlide.classList.remove("showing");

  //get position of next slide.
    currentSlide = (n+slides.length)%slides.length;

  //Add current to next slide
    var nextSlide = slides[currentSlide];

 //Check if nextSlide has showing class. If not, add it.
  **
   if (!($(nextSlide).hasClass('showing'))) {
           $(nextSlide).addClass('showing');
    }
  **

    }
</code>```

答:
check this function

```<code>function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
</code>```

DEMO

Body:
How can I convert my jQuery lines below into Javascript. I'd like to check if this element has a class. If it doesn't have the CSS class I want to add it to the element. The lines are in asterisks below.

Jquery

    var slides = document.querySelectorAll('#slides .slide');
    var currentSlide = 0;

  function goToSlide(n){

  //Remove showing from the current slide
    var thisSlide = slides[currentSlide];

    thisSlide.classList.remove("showing");

  //get position of next slide.
    currentSlide = (n+slides.length)%slides.length;

  //Add current to next slide
    var nextSlide = slides[currentSlide];

 //Check if nextSlide has showing class. If not, add it.
  **
   if (!($(nextSlide).hasClass('showing'))) {
           $(nextSlide).addClass('showing');
    }
  **

    }

Body:
check this function

function hasClass(element, cls) {
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

DEMO


问:
Two conditions in the same case, one of them check if contains substring in SQL Server 2012
I have a post deployment script in my .NET project.

At deployment I want to update some rows based on some conditions.

This is what I have so far:

```<code>DECLARE @BRANDS NVARCHAR(500) = 'http://example.com/';

UPDATE [ServiceVersion]
SET [ExternalUrl] as = CASE
        WHEN (
                SELECT [ExternalUrl]
                FROM [ServiceVersion]
                WHERE [GatewayPath] = '/proxy/brands'
                ) != @BRANDS
            THEN @BRANDS
        END
WHERE [GatewayPath] = '/proxy/brands'
</code>```

If the row is not equal to my variable, than it updates it. Else it does nothing.

What I want to do more than that, is to add another condition, like x !=BRAND && string does not contain "abc" update.

But how do you add another condition in a CASE that checks for substring?

答:
Try this...

```<code>DECLARE @BRANDS NVARCHAR(500) = 'http://example.com/';

UPDATE [ServiceVersion]
SET [ExternalUrl] = @BRANDS
WHERE
      [ExternalUrl] != @BRANDS
      AND [ExternalUrl] not like '%abc%'
      AND [GatewayPath] = '/proxy/brands'
</code>```

Hope this help!

Body:
I have a post deployment script in my .NET project.

At deployment I want to update some rows based on some conditions.

This is what I have so far:

DECLARE @BRANDS NVARCHAR(500) = 'http://example.com/';

UPDATE [ServiceVersion]
SET [ExternalUrl] as = CASE
        WHEN (
                SELECT [ExternalUrl]
                FROM [ServiceVersion]
                WHERE [GatewayPath] = '/proxy/brands'
                ) != @BRANDS
            THEN @BRANDS
        END
WHERE [GatewayPath] = '/proxy/brands'

If the row is not equal to my variable, than it updates it. Else it does nothing.

What I want to do more than that, is to add another condition, like x !=BRAND && string does not contain "abc" update.

But how do you add another condition in a CASE that checks for substring?

Body:
Try this...

DECLARE @BRANDS NVARCHAR(500) = 'http://example.com/';

UPDATE [ServiceVersion]
SET [ExternalUrl] = @BRANDS
WHERE
      [ExternalUrl] != @BRANDS
      AND [ExternalUrl] not like '%abc%'
      AND [GatewayPath] = '/proxy/brands'

Hope this help!


问:
Javascript function in loop
I need to show on page many hidden blocks, that are displayed by functions:

```<code>function show() {
    document.getElementById('info').style.display = 'block';
}

function hide() {
    document.getElementById('info').style.display = 'none';
}

function show_x() {
    document.getElementById('info_x').style.display = 'block';
}

function hide_x() {
    document.getElementById('info_x').style.display = 'none';
}
</code>```

How to hide all those functions in one loop?
Why my loop doesn't work?

```<code>function show() {
    document.getElementById('info').style.display = 'block';
}

function hide() {
    document.getElementById('info').style.display = 'none';
}

for (var i = 1; i++; i <= 50) {

    function show + i + () {
        document.getElementById('info' + i + '').style.display = 'block';
    }

    function hide + i + () {
        document.getElementById('info' + i + '').style.display = 'none';
    }
}
</code>```

Thanks!

答:
You cannot write like this:

```<code>function show+i+()
</code>```

You should pass i as parameter into your function show or hide:

```<code>function show(idAppend) {
    document.getElementById('info' + idAppend).style.display='block';
}

for (var i=1; i++; i<=50){
    show(i);
}
</code>```

This will show all blocks with id infoX, where X is the number from 1 to 50.

How to call function by its name

If you want to call function by its name from variable, your should use this syntax (depending on the context):

```<code>window[functionName](arguments)
</code>```

For example, let's call function with the name show5 with the single parameter message:

```<code>function show5(message){
    alert(message);
}

// store name of the function in variable
var functionName = 'show5';

// call function with parameter "Hello!" by its name
window[functionName]('Hello!')
</code>```

Title: Javascript function in loop

Body:
I need to show on page many hidden blocks, that are displayed by functions:

function show() {
    document.getElementById('info').style.display = 'block';
}

function hide() {
    document.getElementById('info').style.display = 'none';
}

function show_x() {
    document.getElementById('info_x').style.display = 'block';
}

function hide_x() {
    document.getElementById('info_x').style.display = 'none';
}

How to hide all those functions in one loop?
Why my loop doesn't work?

function show() {
    document.getElementById('info').style.display = 'block';
}

function hide() {
    document.getElementById('info').style.display = 'none';
}

for (var i = 1; i++; i <= 50) {

    function show + i + () {
        document.getElementById('info' + i + '').style.display = 'block';
    }

    function hide + i + () {
        document.getElementById('info' + i + '').style.display = 'none';
    }
}

Thanks!

Body:
You cannot write like this:

function show+i+()

You should pass i as parameter into your function show or hide:

function show(idAppend) {
    document.getElementById('info' + idAppend).style.display='block';
}

for (var i=1; i++; i<=50){
    show(i);
}

This will show all blocks with id infoX, where X is the number from 1 to 50.

How to call function by its name

If you want to call function by its name from variable, your should use this syntax (depending on the context):

window[functionName](arguments)

For example, let's call function with the name show5 with the single parameter message:

function show5(message){
    alert(message);
}

// store name of the function in variable
var functionName = 'show5';

// call function with parameter "Hello!" by its name
window[functionName]('Hello!')


问:
read txt file line by line java using eclipe
Code:

```<code>    try {
    FileReader reader = new FileReader("rn.txt");
    BufferedReader bufferedReader = new BufferedReader(reader);

    String line;

    while ((line = bufferedReader.readLine()) != null) {
     System.out.println(line);
    }
    reader.close();

   } catch (IOException e) {
    e.printStackTrace();
   }
</code>```

rn.txt file contents:

```<code>12
45
78
23
45
</code>```

Console output:

```<code>0
/
N
K
M
^

.
:
P
/
G
0

?

8
W
3
</code>```

Question:
How can I read the actual data in the .txt file? Is there an issue with the code I have written?

EDIT:

this my console output and where i put my txt file

答:
Your code works absolutely fine, check your .txt file is in the correct place and you don't have duplicate .txt files.

Output using your code:

```<code>run:
12
45
78
23
45
BUILD SUCCESSFUL (total time: 0 seconds)
</code>```

Body:
Code:

    try {
    FileReader reader = new FileReader("rn.txt");
    BufferedReader bufferedReader = new BufferedReader(reader);

    String line;

    while ((line = bufferedReader.readLine()) != null) {
     System.out.println(line);
    }
    reader.close();

   } catch (IOException e) {
    e.printStackTrace();
   }

rn.txt file contents:

12
45
78
23
45

Console output:

0
/
N
K
M
^

.
:
P
/
G
0

?

8
W
3

Question:
How can I read the actual data in the .txt file? Is there an issue with the code I have written?

EDIT:

this my console output and where i put my txt file

Body:
Your code works absolutely fine, check your .txt file is in the correct place and you don't have duplicate .txt files.

Output using your code:

run:
12
45
78
23
45
BUILD SUCCESSFUL (total time: 0 seconds)


问:
Why to use JPA with Hibernate?
I work to a project that it has installed Spring, Hibernate and JPA.

I have read tutorials about Hibernate and JPA and the big picture is that JPA is an interface, and Hibernate is the implementation of JPA.

But why to use JPA, with what it helps me? What are the differences between JPA and Hibernate. First, i thought that annotations in POJO classes are from JPA, but no, they are from Hibernate Annotations.

So, the big question is, for what is good JPA?
Thanks!

答:
Java Persistence Architecture (JPA) is a standard for Java object-relational mapping solution like Hibernate, TopLink, etc.  Hibernate is a particular implementation of JPA.

You should be using JPA annotations so you aren't locked into Hibernate.

Make sure you are using JPA for a good reason.  You might not need it.  JDBC might be enough for your needs.

Title: Why to use JPA with Hibernate?


问:
PHP regex for admin, admin/ and admin/more/ etc
I'm currently building a CMS for my projects and I'm trying to route to my 'Admin' controller. Now my regexp is:

```<code>'admin(.*)'
</code>```

But with this everything that start with 'admin' will be matched. I would like to match the route when 'admin', 'admin/foo' and 'admin/foo/bar' etc, is present. Not when 'adminn' or something like that.

Hope you understand what I'm after. Thx / Tobias

答:
Two approaches could work without regular expressions at all

Search for the longest substring first, that way you won't match admin first.  So, with your examples, check for admin/foo/bar first, then admin/foo, then admin.

explode() the string on the slash, then work your way down the bits to figure out what matches, e.g. explode('/', $request) then check the parts; if the first result is admin, pass it to the admin controller, which can figure out the route from the rest.

Body:
I'm currently building a CMS for my projects and I'm trying to route to my 'Admin' controller. Now my regexp is:

'admin(.*)'

But with this everything that start with 'admin' will be matched. I would like to match the route when 'admin', 'admin/foo' and 'admin/foo/bar' etc, is present. Not when 'adminn' or something like that.

Hope you understand what I'm after. Thx / Tobias


问:
Per-thread initializers for twisted reactor's getThreadPool (or alternative ThreadPool implementation)
TL;DR: Is there a way in Twisted to influence thread creation with custom initializers or replace the ThreadPool implementation used by the reactor? Alternatively, can a task be reliably queued to all threads in the reactor thread pool?

Details:

I'm running a Flask application within a Twisted app, using this pattern:

```<code>resource = WSGIResource(reactor, reactor.getThreadPool(), the_app)
site = server.Site(resource)
reactor.listenTCP(port, site, interface=bind_ip)
</code>```

For XML parsing I use lxml, which occasionally generates an entry to its internal error log, which effectively leaks memory. As I see it there are two ways around this: Periodically clear the error log with etree.clear_error_log() or set a global log with etree.useGlobalPythonLog().

Unfortunately each method requires to be run on every single thread, at least once. Therefore I need to have every thread in the ThreadPool run some code once (during initialization) or periodically (conceptually something like "reactor.callFromEveryThread()").

答: There's no good public interface for accomplishing this.  You should file a feature request in the Twisted issue tracker.  There has been some effort to develop a new threadpool interface.  It is not yet publicly available in any release of Twisted (nor in trunk@HEAD).  Now would be a good time to get new requirements recognized, prior to the initial introduction of the public interface.

Body:
TL;DR: Is there a way in Twisted to influence thread creation with custom initializers or replace the ThreadPool implementation used by the reactor? Alternatively, can a task be reliably queued to all threads in the reactor thread pool?

Details:

I'm running a Flask application within a Twisted app, using this pattern:

resource = WSGIResource(reactor, reactor.getThreadPool(), the_app)
site = server.Site(resource)
reactor.listenTCP(port, site, interface=bind_ip)

For XML parsing I use lxml, which occasionally generates an entry to its internal error log, which effectively leaks memory. As I see it there are two ways around this: Periodically clear the error log with etree.clear_error_log() or set a global log with etree.useGlobalPythonLog().

Unfortunately each method requires to be run on every single thread, at least once. Therefore I need to have every thread in the ThreadPool run some code once (during initialization) or periodically (conceptually something like "reactor.callFromEveryThread()").


问:
iPhone SDK: Orientation (Landscape and Portrait views)
Okay, I've got my normal app which is in portrait mode. I can force my app to go to landscape mode for a view (using navigationcontroller and viewcontroller) like this:

```<code>- (void)viewWillAppear:(BOOL)animated {
    [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];
}
</code>```

But then when I go back to the main menu (tableview) it goes straight back to portrait. I try this code:

```<code>- (void)viewWillAppear:(BOOL)animated {
    [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait];
}
</code>```

But that doesn't work..

Any ideas?

答: You need to edit your Info.plist file to add the UIInterfaceOrientation key with the appropriate value (UIInterfaceOrientationLandscapeRight or UIInterfaceOrientationLandscapeLeft).</p>

Body:
Okay, I've got my normal app which is in portrait mode. I can force my app to go to landscape mode for a view (using navigationcontroller and viewcontroller) like this:

- (void)viewWillAppear:(BOOL)animated {
    [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];
}

But then when I go back to the main menu (tableview) it goes straight back to portrait. I try this code:

- (void)viewWillAppear:(BOOL)animated {
    [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait];
}

But that doesn't work..

Any ideas?

LastEditorDisplayName: Chris Hanson


问:
Free VBscript obfuscator
Hi all

I have a reasonably large (2k lines) vbScript file which i need to obfuscate. It is a customised QTP function library so must be distributed with the product. Is there any free VBscript obfuscators out there that do a decent job?

Thanks!

EDIT:

Encryption is not suitable for use with QTP so Windows Scripting Encryption tools will not work, QTP has to be able to understand the output. I'm not trying to make the output hacker proof, just so the casual programmer cant be bothered to put the effort in to de-obfuscate it

答:
Here's a Little script i whipped up for you that will obfuscate any vbs file....

The obfuscation is pretty simple, so anyone familiar with vbs can prolly de-obfuscate it in 1 min.

If you want higher level of obfuscation, well you need to pay me... :) but for this i'll take your votes! :D

The resulting script obfuscated.vbs will remain a valid vbs file.

I could've made a self decrypting vbs, but chances are that will cause a red-flag with an antivirus...and if your anti-virus is any good, it should flag this as suspicious.

Please note, Standard disclaimer applies...I'm not responsible for any damage that maybe occur due to the script, use at own risk. I don't guarantee it'll work all the time

```<code>'VBS Obfuscator by st0le

Randomize
set fso = CreateObject("Scripting.FileSystemObject")
fileName = Inputbox("Enter Path of the File to scramble : ")
set src = fso.OpenTextfile(fileName,1)
body = src.readall
set rep  = fso.createtextfile("Obfuscated.vbs",true)
rep.writeline "Execute(" & Obfuscate(body) & " ) "

Function Obfuscate(txt)
enc = ""
for i = 1 to len(txt)
enc = enc & "chr( " & form( asc(mid(txt,i,1)) ) & " ) & "
next
Obfuscate = enc & " vbcrlf "
End Function

Function form(n)

r = int(rnd * 10000)
k = int(rnd * 3)
if( k = 0) then ret = (r+n) & "-" & r
if( k = 1) then ret = (n-r) & "+" & r
if( k = 2) then ret = (n*r) & "/" & r
form = ret
End Function
</code>```

Title: Free VBscript obfuscator

Body:
Here's a Little script i whipped up for you that will obfuscate any vbs file....

The obfuscation is pretty simple, so anyone familiar with vbs can prolly de-obfuscate it in 1 min.

If you want higher level of obfuscation, well you need to pay me... :) but for this i'll take your votes! :D

The resulting script obfuscated.vbs will remain a valid vbs file.

I could've made a self decrypting vbs, but chances are that will cause a red-flag with an antivirus...and if your anti-virus is any good, it should flag this as suspicious.

Please note, Standard disclaimer applies...I'm not responsible for any damage that maybe occur due to the script, use at own risk. I don't guarantee it'll work all the time

'VBS Obfuscator by st0le

Randomize
set fso = CreateObject("Scripting.FileSystemObject")
fileName = Inputbox("Enter Path of the File to scramble : ")
set src = fso.OpenTextfile(fileName,1)
body = src.readall
set rep  = fso.createtextfile("Obfuscated.vbs",true)
rep.writeline "Execute(" & Obfuscate(body) & " ) "

Function Obfuscate(txt)
enc = ""
for i = 1 to len(txt)
enc = enc & "chr( " & form( asc(mid(txt,i,1)) ) & " ) & "
next
Obfuscate = enc & " vbcrlf "
End Function

Function form(n)

r = int(rnd * 10000)
k = int(rnd * 3)
if( k = 0) then ret = (r+n) & "-" & r
if( k = 1) then ret = (n-r) & "+" & r
if( k = 2) then ret = (n*r) & "/" & r
form = ret
End Function


问:
Git - Find authors who changed a file
Is there a way in git to list out authors who changed a specific file?

For now all I could do was git log [filename] | grep "Author"

答: Depending on your specific need, you could use git blame to see who added lines on the file. Deleted lines are more trycky because git blame --reverse does not tell you where the lines were actually deleted.... I've been working on a tool that mixes the output of git diff with git blame (with a litlle bit of analysis of deleted lines) that might come handy. https://github.com/eantoranz/difflame

Title: Git - Find authors who changed a file


问:
Jquery each and visible - Unknown Pseudoclass or Pseudoelement 'visible'

i have a problem with jquery/visible. Hope somebody can help me.

This code works, but i get an error in firebug

```<code>$('.fse:visible').each(function (i)
</code>```

-> Unknown Pseudoclass or Pseudoelement 'visible'.

second try

```<code>$('.fse').is(':visible').each(function (i)
</code>```

->  $(".fse").is(":visible").each is not a function

Whats wrong?

Thanks in advance!

Peter

答: The first error is a bit mysterious, based on the information you have provided. The second makes perfect sense since .is(":visible") returns a boolean, not a jQuery object.

Body:
i have a problem with jquery/visible. Hope somebody can help me.

This code works, but i get an error in firebug

$('.fse:visible').each(function (i)

-> Unknown Pseudoclass or Pseudoelement 'visible'.

second try

$('.fse').is(':visible').each(function (i)

->  $(".fse").is(":visible").each is not a function

Whats wrong?

Thanks in advance!

Peter


问:
Accessing Android Studio properties window?
I have recently started using Android Studio and cannot work out how to access the properties window.

The following screenshot was taken from Google and shows exactly what I'm trying to access denoted by the red rectangle around the properties window.

Can anyone please tell me how I can access this?

答:
Follow the doc.

Instead of editing your view properties in XML, you can do so from the Properties window (on the right side of the Layout Editor). This window is available only when the design editor is open, so be sure you've selected the Design tab at the bottom of the window.

When you select a view, the Properties window shows the following, as indicated in figure 5:

View inspector with controls for width/height style, margins, and bias (available only for views in a ConstraintLayout). For more information, see Build a Responsive UI with ConstraintLayout.


问:
How to unregister all ProgressBars?
The dask documentation explains that a ProgressBar can be unregistered by calling pbar.unregister(), where pbar is the respective ProgressBar instance.

However, this method only works, if the user has access to that ProgressBar instance. Using IPython I was in a situation where I've lost that reference.

Is there a way to find all instances of globally registered ProgressBar objects?

答:
This should work:</p>

```<code>dask.set_options(callbacks=set())
</code>```

Title: How to unregister all ProgressBars?

Body:
This should work:

dask.set_options(callbacks=set())


问:
Replace last character in sql column
I have data in table this way. If the ; is at the end I would like that replaced with a blank string if not I would leave data same way.

```<code>abc;
123;ghi;789
test123;
thisowns;
wer;567;457;test
</code>```

Result should be

```<code>abc
123;ghi;789
test123
thisowns
wer;567;457;test
</code>```

答:
Hope this helps.</p>

```<code>;WITH cte_TestData (String)
AS
(
SELECT 'abc;' UNION ALL
SELECT '123;ghi;789' UNION ALL
SELECT 'test123;' UNION ALL
SELECT 'thisowns;' UNION ALL
SELECT 'wer;567;457;test'
)
SELECT CASE
        WHEN RIGHT(String, 1) = ';'
            AND LEN(String) >= 1
            THEN SUBSTRING(String, 1, LEN(String) - 1)
        ELSE String
        END
FROM cte_TestData
</code>```

Title: Replace last character in sql column

Body:
I have data in table this way. If the ; is at the end I would like that replaced with a blank string if not I would leave data same way.

abc;
123;ghi;789
test123;
thisowns;
wer;567;457;test

Result should be

abc
123;ghi;789
test123
thisowns
wer;567;457;test

Body:
Hope this helps.

;WITH cte_TestData (String)
AS
(
SELECT 'abc;' UNION ALL
SELECT '123;ghi;789' UNION ALL
SELECT 'test123;' UNION ALL
SELECT 'thisowns;' UNION ALL
SELECT 'wer;567;457;test'
)
SELECT CASE
        WHEN RIGHT(String, 1) = ';'
            AND LEN(String) >= 1
            THEN SUBSTRING(String, 1, LEN(String) - 1)
        ELSE String
        END
FROM cte_TestData


问:
Pass a range as an argument in a formula using VBA
I'm really REALLY new using VBA, so I apologize for this question in advance:

Basically, I'm trying to write a sub that will calculate IRR on a range of numbers that is dynamic. So I tried to create a variable which would select the range of numbers, and then using a named range for the output cell(IRR), have the result of the formula show. Below is the code I have:

```<code>Sub irrCalc()

Dim calcrange As Range

Set calcrange = Range("B55").End(xlToRight).Select

Range("IRR").Formula = "IRR(calcrange)"

End Sub
</code>```

The error I'm getting is 'Object required', and its pointing to the center line of code "Set calcrange".

I have been looking for an answer but I can't seem to find (or understand) what the problem is...Again I know this is probably ridiculously easy but I'm a bit stumped. Thanks in advance

答:
I can't be sure. But maybe you're looking for something like this:</p>

```<code>Sub irrCalc()

Dim calcrange As Range

Set calcrange = Range(Range("B55"), Range("B55").End(xlToRight))

Range("IRR").Formula = "=IRR(" & calcrange.Address & ")"

End Sub
</code>```

Body:
I'm really REALLY new using VBA, so I apologize for this question in advance:

Basically, I'm trying to write a sub that will calculate IRR on a range of numbers that is dynamic. So I tried to create a variable which would select the range of numbers, and then using a named range for the output cell(IRR), have the result of the formula show. Below is the code I have:

Sub irrCalc()

Dim calcrange As Range

Set calcrange = Range("B55").End(xlToRight).Select

Range("IRR").Formula = "IRR(calcrange)"

End Sub

The error I'm getting is 'Object required', and its pointing to the center line of code "Set calcrange".

I have been looking for an answer but I can't seem to find (or understand) what the problem is...Again I know this is probably ridiculously easy but I'm a bit stumped. Thanks in advance

Body:
I can't be sure. But maybe you're looking for something like this:

Sub irrCalc()

Dim calcrange As Range

Set calcrange = Range(Range("B55"), Range("B55").End(xlToRight))

Range("IRR").Formula = "=IRR(" & calcrange.Address & ")"

End Sub


问:
Changing Windows 7 Wallpaper Remotely
I am trying to remotely change the wallpaper on about 50 computers that are running Win 7 in a WORKGROUP environment.

I have local admin rights to all of them plus they are running an agent (Faronics) that lets me push .bat .exe .msi .vbs and .ps1 to them remotely.

Just wondering if there was any application that lets me do that remotely or if not, what is the easiest way to get my image to these machines and set it as default wallpaper?

答: You can use intelliadmin network administrator to change the desktop pictures remotely on all computers at once</p>

Title: Changing Windows 7 Wallpaper Remotely