问:
Need to put the output of below selenium code to a Json file

need to parse the output data and dump it into a json file. Any help will be appreciated.

```<code>executable_path = "/usr/local/share/chromedriver"
chrome_options = Options()
os.environ["webdriver.chrome.driver"] = executable_path
driver = webdriver.Chrome(executable_path=executable_path,
chrome_options=chrome_options)
driver.get("http://environment.netronline.com/api/viewers//env-
app.php?addr=gilbert")
time.sleep(5)
listOfElements = driver.find_elements_by_xpath("//div[@id='pinBox']//div[@class='pin']")
for element in listOfElements:
    hover = ActionChains(driver).move_to_element(element)
    hover.perform()
    time.sleep(5)
    targetTooltip = driver.find_elements_by_xpath("//*[@id='tooltip']")
    print targetTooltip.text
    print "**********************"
</code>```

output is :
Emergency Response Notification System (ERNS)
Left click the pin for more info.

Incident: CALLER STATED THAT A WEST BOUND FREIGHT TRAIN STRUCK A TRESPASSER ON THE TRACKS.
Incident Date: 7/3/2012 6:20
Incident location: MP: 926.96
Year Reported: 2012
City: GILBERT
State: AZ
County: MARICOPA

US RCRA Generators (CESQG, SQG, LQG)
Left click the pin for more info.

Info URL: http://ofmpub.epa.gov/enviro/fii_query_detail.disp_program_facility?p_registry_id=110045500757
EPA Identifier: 110045500757
Primary Name: CVS PHARMACY #3268
Address: 765 S LINDSAY RD
City: GILBERT
County: MARICOPA
State: AZ
Zipcode: 85296-3063
Programs: AZURITE, BR, RCRAINFO
Program Interests: HAZARDOUS WASTE BIENNIAL REPORTER, LQG, STATE MASTER
Updated On: 27-JAN-2015 13:51:45
Recorded On: 10-MAY-2012 16:46:54

Required json format is :
[
      {
         "source":"Emergency Response Notification System (ERNS)",
     "Incident":"CALLER STATED THAT A WEST BOUND FREIGHT TRAIN STRUCK A TRESPASSER ON THE TRACKS.",
         "Incident Date":"7/3/2012 6:20",
         "Incident location":"MP: 926.96",
         "Year Reported":"2012",
         "City":"GILBERT",
         "State":"AZ",
         "County":"MARICOPA"
      }
]

答:
I found the logic

```<code>driver.get("http://environment.netronline.com/api/viewers//env-app.php?addr=gilbert")
time.sleep(5)
listOfElements = driver.find_elements_by_xpath("//div[@id='pinBox']//div[@class='pin']")
for element in listOfElements:
    hover = ActionChains(driver).move_to_element(element)
    hover.perform()
    time.sleep(5)
    targetTooltip = driver.find_elements_by_xpath("//*[@id='tooltip']")
    for li in targetTooltip:
        lines = str(li.text)
        lines = str(lines).split('\n')
        lines.remove('Left click the pin for more info.')
        lines.remove('')
        lines.insert(0,'Environmental Concern')
        lines = [i.split(':', 1) for i in lines]
        flat_list = flatten(lines)
    r = dict(zip(flat_list[::2], flat_list[1::2]))
print json.dumps(r)
</code>```

Body:
need to parse the output data and dump it into a json file. Any help will be appreciated.

executable_path = "/usr/local/share/chromedriver"
chrome_options = Options()
os.environ["webdriver.chrome.driver"] = executable_path
driver = webdriver.Chrome(executable_path=executable_path,
chrome_options=chrome_options)
driver.get("http://environment.netronline.com/api/viewers//env-
app.php?addr=gilbert")
time.sleep(5)
listOfElements = driver.find_elements_by_xpath("//div[@id='pinBox']//div[@class='pin']")
for element in listOfElements:
    hover = ActionChains(driver).move_to_element(element)
    hover.perform()
    time.sleep(5)
    targetTooltip = driver.find_elements_by_xpath("//*[@id='tooltip']")
    print targetTooltip.text
    print "**********************"

output is :
Emergency Response Notification System (ERNS)
Left click the pin for more info.

Incident: CALLER STATED THAT A WEST BOUND FREIGHT TRAIN STRUCK A TRESPASSER ON THE TRACKS.
Incident Date: 7/3/2012 6:20
Incident location: MP: 926.96
Year Reported: 2012
City: GILBERT
State: AZ
County: MARICOPA

US RCRA Generators (CESQG, SQG, LQG)
Left click the pin for more info.

Info URL: http://ofmpub.epa.gov/enviro/fii_query_detail.disp_program_facility?p_registry_id=110045500757
EPA Identifier: 110045500757
Primary Name: CVS PHARMACY #3268
Address: 765 S LINDSAY RD
City: GILBERT
County: MARICOPA
State: AZ
Zipcode: 85296-3063
Programs: AZURITE, BR, RCRAINFO
Program Interests: HAZARDOUS WASTE BIENNIAL REPORTER, LQG, STATE MASTER
Updated On: 27-JAN-2015 13:51:45
Recorded On: 10-MAY-2012 16:46:54

Required json format is :
[
      {
         "source":"Emergency Response Notification System (ERNS)",
     "Incident":"CALLER STATED THAT A WEST BOUND FREIGHT TRAIN STRUCK A TRESPASSER ON THE TRACKS.",
         "Incident Date":"7/3/2012 6:20",
         "Incident location":"MP: 926.96",
         "Year Reported":"2012",
         "City":"GILBERT",
         "State":"AZ",
         "County":"MARICOPA"
      }
]

Body:
I found the logic

driver.get("http://environment.netronline.com/api/viewers//env-app.php?addr=gilbert")
time.sleep(5)
listOfElements = driver.find_elements_by_xpath("//div[@id='pinBox']//div[@class='pin']")
for element in listOfElements:
    hover = ActionChains(driver).move_to_element(element)
    hover.perform()
    time.sleep(5)
    targetTooltip = driver.find_elements_by_xpath("//*[@id='tooltip']")
    for li in targetTooltip:
        lines = str(li.text)
        lines = str(lines).split('\n')
        lines.remove('Left click the pin for more info.')
        lines.remove('')
        lines.insert(0,'Environmental Concern')
        lines = [i.split(':', 1) for i in lines]
        flat_list = flatten(lines)
    r = dict(zip(flat_list[::2], flat_list[1::2]))
print json.dumps(r)


来源: stackexchange

问:
How to assign column names to a table
I am working with the following data in Rstudio. I am trying to assign column names to the data. I have employed the following commands:

```<code>nlsdata -> read.table("C:/Users/perdue/Desktop/Adv.MicroEconometrics/HA 3/data/nls.dat",
                       header = FALSE, dec = ".")
</code>```

This command returns as a first row column names 'v1 v2 v3... v52'. When I follow with

```<code>colnames(nlsdata)
</code>```

I get a list of names: v1, v2, ..., v52. Then

```<code>col.names(nlsdata) <- c("inputid","nearc2","nearc4","nearc4a","nearc4b","ed76","ed66","age76",
                        "daded","nodaded","momed","nomomed","weight","momdad14","sinmom14",
                        "step14","reg661","reg662","reg663","reg664","reg665","reg666","reg667",
                        "reg668","reg669","south66","work76","work78","lwage76","lwage78",
                        "famed","black","smsa76r","smsa78r","reg76r","reg78r","reg80r",
                        "smsa66r","wage76","wage78","wage80","noint78","enroll76","enroll78",
                        "enroll80","kww","iq","marsta76","marsta78","marsta80","libcrd14")

where newname[i] is the ith column name of dataframe nlsdata`
</code>```

```<code>Error: unexpected symbol in ""south66","work76","work78","lwage76","lwage78","famed","black","smsa76r","smsa78r","reg76r","reg78r","reg80r","smsa66r","wage76","wage78","wage80", "noint78","enroll76","enroll78","enroll80","
</code>```

The error messages seem to suggest a syntax error. I have loooked – more than once – and can't find/recognize one.

答:
The proper code is

```<code>nlsdata<-read.table("C:/Users/name/Desktop/nls.dat", header = FALSE, skip = 1, dec = ".")
</code>```

then add column names with colnames

```<code>colnames(nlsdata)<-c("inputid","nearc2","nearc4","nearc4a","nearc4b","ed76","ed66","age76","daded","nodaded","momed","nomomed","weight","momdad14","sinmom14","step14","reg661","reg662","reg663","reg664","reg665","reg666","reg667","reg668","reg669","south66","work76","work78","lwage76","lwage78","famed","black","smsa76r","smsa78r","reg76r","reg78r","reg80r","smsa66r","wage76","wage78","wage80","noint78","enroll76","enroll78","enroll80","kww","iq","marsta76","marsta78","marsta80","libcrd14")
</code>```

and check with

```<code>head(nlsdata)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to assign column names to a table

Body:
I am working with the following data in Rstudio. I am trying to assign column names to the data. I have employed the following commands:

nlsdata -> read.table("C:/Users/perdue/Desktop/Adv.MicroEconometrics/HA 3/data/nls.dat",
                       header = FALSE, dec = ".")

This command returns as a first row column names 'v1 v2 v3... v52'. When I follow with

colnames(nlsdata)

I get a list of names: v1, v2, ..., v52. Then

col.names(nlsdata) <- c("inputid","nearc2","nearc4","nearc4a","nearc4b","ed76","ed66","age76",
                        "daded","nodaded","momed","nomomed","weight","momdad14","sinmom14",
                        "step14","reg661","reg662","reg663","reg664","reg665","reg666","reg667",
                        "reg668","reg669","south66","work76","work78","lwage76","lwage78",
                        "famed","black","smsa76r","smsa78r","reg76r","reg78r","reg80r",
                        "smsa66r","wage76","wage78","wage80","noint78","enroll76","enroll78",
                        "enroll80","kww","iq","marsta76","marsta78","marsta80","libcrd14")

where newname[i] is the ith column name of dataframe nlsdata`

Error: unexpected symbol in ""south66","work76","work78","lwage76","lwage78","famed","black","smsa76r","smsa78r","reg76r","reg78r","reg80r","smsa66r","wage76","wage78","wage80", "noint78","enroll76","enroll78","enroll80","

The error messages seem to suggest a syntax error. I have loooked – more than once – and can't find/recognize one.

Body:
The proper code is

nlsdata<-read.table("C:/Users/name/Desktop/nls.dat", header = FALSE, skip = 1, dec = ".")

then add column names with colnames

colnames(nlsdata)<-c("inputid","nearc2","nearc4","nearc4a","nearc4b","ed76","ed66","age76","daded","nodaded","momed","nomomed","weight","momdad14","sinmom14","step14","reg661","reg662","reg663","reg664","reg665","reg666","reg667","reg668","reg669","south66","work76","work78","lwage76","lwage78","famed","black","smsa76r","smsa78r","reg76r","reg78r","reg80r","smsa66r","wage76","wage78","wage80","noint78","enroll76","enroll78","enroll80","kww","iq","marsta76","marsta78","marsta80","libcrd14")

and check with

head(nlsdata)

ContentLicense: CC BY-SA 3.0


问:
returning a boolean in one line for a ball that has crashed into another ball
I've just started learning java this quarter and on a sample quiz, this is a question. I have no idea where to begin save for the fact that it has to return a boolean type.

Fill in the blank so that this function returns true if the circle at x1, y1, with radius r1, has collided with the circle at x2, y2, with radius r2.

```<code>boolean collided(int x1, int y1, int r1, int x2, int y2, int r2) {
    return ___________________________________________________________;
}
</code>```

Appreciate the comments and kind help. Like I said above, if you had read it, I've just started learning java this quarter and on a sample quiz, this is a question I had no idea where to begin. If anyone is willing to direct me to another learning resource that is better suited for a complete beginner, that would be great.

答:
In terms of code this is:

```<code>boolean collided(int x1, int y1, int r1, int x2, int y2, int r2) {
  return Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)) < r1+r2;
}
</code>```

That statement consists of the calculcation of the distance between the two circles's centers and checking if that distance is less than the sum of the two radiuses. That check returns a boolean value, true if the circles "collided"

Body:
I've just started learning java this quarter and on a sample quiz, this is a question. I have no idea where to begin save for the fact that it has to return a boolean type.

Fill in the blank so that this function returns true if the circle at x1, y1, with radius r1, has collided with the circle at x2, y2, with radius r2.

boolean collided(int x1, int y1, int r1, int x2, int y2, int r2) {
    return ___________________________________________________________;
}

Appreciate the comments and kind help. Like I said above, if you had read it, I've just started learning java this quarter and on a sample quiz, this is a question I had no idea where to begin. If anyone is willing to direct me to another learning resource that is better suited for a complete beginner, that would be great.

Body:
In terms of code this is:

boolean collided(int x1, int y1, int r1, int x2, int y2, int r2) {
  return Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)) < r1+r2;
}

That statement consists of the calculcation of the distance between the two circles's centers and checking if that distance is less than the sum of the two radiuses. That check returns a boolean value, true if the circles "collided"


问:
Multi associate array to single array using php
This is may array and i want to make a single array from it.

Following is my current array and i want array in single array.

```<code>Array
(
    [0] => Array
        (
            [item_name1] => First Name
            [quantity1] => 1
            [mc_gross1] => 189.00
        )

    [1] => Array
        (
            [item_name2] => Last Name
            [quantity2] => 1
            [mc_gross2] => 22.00
        )

    [2] => Array
        (
            [item_name3] => Email Addres
            [quantity3] => 3
            [mc_gross3] => 21.00
        )

)
</code>```

ANd i Want like

```<code> Array
(

    [item_name1] => First Name
    [quantity1] => 1
    [mc_gross1] => 189.00

    [item_name2] => Last Name
    [quantity2] => 1
    [mc_gross2] => 22.00

    [item_name3] => Email Addres
    [quantity3] => 3
    [mc_gross3] => 21.00

    )
</code>```

I have tried by following way but i can not get result that i want.

```<code><?php
$result = array();

foreach($result as $inner) {
       $result[key($inner)] = current($inner);

}
?>
</code>```

Someone please help me how could i resolve this ?

答:
Try like below</p>

```<code><?php
$final_result = array();
foreach($result as $inner) {
   $final_result = array_merge($final_result,$inner);
}
?>
</code>```

Body:
This is may array and i want to make a single array from it.

Following is my current array and i want array in single array.

Array
(
    [0] => Array
        (
            [item_name1] => First Name
            [quantity1] => 1
            [mc_gross1] => 189.00
        )

    [1] => Array
        (
            [item_name2] => Last Name
            [quantity2] => 1
            [mc_gross2] => 22.00
        )

    [2] => Array
        (
            [item_name3] => Email Addres
            [quantity3] => 3
            [mc_gross3] => 21.00
        )

)

ANd i Want like

 Array
(

    [item_name1] => First Name
    [quantity1] => 1
    [mc_gross1] => 189.00

    [item_name2] => Last Name
    [quantity2] => 1
    [mc_gross2] => 22.00

    [item_name3] => Email Addres
    [quantity3] => 3
    [mc_gross3] => 21.00

    )

I have tried by following way but i can not get result that i want.

<?php
$result = array();

foreach($result as $inner) {
       $result[key($inner)] = current($inner);

}
?>

Someone please help me how could i resolve this ?

Body:
Try like below

<?php
$final_result = array();
foreach($result as $inner) {
   $final_result = array_merge($final_result,$inner);
}
?>


问:
Not able to effectively remove strings before ‘v’ or deleting strings v and after
I am removing strings before ‘v’ or deleting strings v and after

```<code>My data looks like:
Potato onions v carrot pickles
Chocolate cake v orange cake
Chicken breasts v Vegan Quinoa
Vienna sauvsage v velovute vegetvable
Etc,,
</code>```

My desired output is:

```<code>Potato onions
Chocolate cake
Chicken breasts
Vienna sauvsage
</code>```

The common feature is they have a ‘v’
I have tried something like

```<code>data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))
</code>```

This seems to be useful for static data, and removing specific parts of a string where as my data is dynamic and constantly being updated and changed.  I am wanting to make it look like:
Vienna sauvsage v velovute vegetvable  to Vienna sauvsage
The below tends to work unrealiably and with a later trim.

```<code>df['result'] = df.result.str.extract('((?=).* v(=?))', expand=True).astype(int)
</code>```

答:
Try this:</p>

```<code>In [6]: df['result'] = df.result.str.split('\s+v\s+').str[0]

In [7]: df
Out[7]:
            result
0    Potato onions
1   Chocolate cake
2  Chicken breasts
3  Vienna sauvsage
</code>```

Body:
I am removing strings before ‘v’ or deleting strings v and after

My data looks like:
Potato onions v carrot pickles
Chocolate cake v orange cake
Chicken breasts v Vegan Quinoa
Vienna sauvsage v velovute vegetvable
Etc,,

My desired output is:

Potato onions
Chocolate cake
Chicken breasts
Vienna sauvsage

The common feature is they have a ‘v’
I have tried something like

data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))

This seems to be useful for static data, and removing specific parts of a string where as my data is dynamic and constantly being updated and changed.  I am wanting to make it look like:
Vienna sauvsage v velovute vegetvable  to Vienna sauvsage
The below tends to work unrealiably and with a later trim.

df['result'] = df.result.str.extract('((?=).* v(=?))', expand=True).astype(int)

Body:
Try this:

In [6]: df['result'] = df.result.str.split('\s+v\s+').str[0]

In [7]: df
Out[7]:
            result
0    Potato onions
1   Chocolate cake
2  Chicken breasts
3  Vienna sauvsage


问:
Finding the height of a binary tree in Haskell
I have the folloing "height" function which returns the height of a tree. When I try to use it, however, I get this exception. How can I fix it? I also have the function "isBalancedTree" which checks if a given tree is balanced.

```<code>data Tree = Node Tree Int Tree | Leaf Int deriving Show

height :: Tree -> Integer
height (Node left x right) = 1 + max (height left) (height right)

isBalancedTree :: Tree -> Bool
isBalancedTree (Node left x right) =
    let diff = abs (height left - height right) in
    diff <= 1 && isBalancedTree left && isBalancedTree right
</code>```

*Main> height (Node (Node (Leaf 3) 4 (Leaf 2)) 5 (Node (Leaf 4) 7 (Leaf 6)))

*** Exception: Non-exhaustive patterns in function height

答:
Your recursive implementation of height is nice, but you have forgotten the base case of a single leaf:

```<code>height (Leaf _) = 1
</code>```

This is the missing pattern that the exception is complaining about. The same applies to your second function isBalanced - you need a case for a Leaf, too:

```<code>isBalanced (Leaf _) = True -- assuming a single-leaf tree is trivially balanced
</code>```

Body:
I have the folloing "height" function which returns the height of a tree. When I try to use it, however, I get this exception. How can I fix it? I also have the function "isBalancedTree" which checks if a given tree is balanced.

data Tree = Node Tree Int Tree | Leaf Int deriving Show

height :: Tree -> Integer
height (Node left x right) = 1 + max (height left) (height right)

isBalancedTree :: Tree -> Bool
isBalancedTree (Node left x right) =
    let diff = abs (height left - height right) in
    diff <= 1 && isBalancedTree left && isBalancedTree right

*Main> height (Node (Node (Leaf 3) 4 (Leaf 2)) 5 (Node (Leaf 4) 7 (Leaf 6)))

*** Exception: Non-exhaustive patterns in function height

Body:
Your recursive implementation of height is nice, but you have forgotten the base case of a single leaf:

height (Leaf _) = 1

This is the missing pattern that the exception is complaining about. The same applies to your second function isBalanced - you need a case for a Leaf, too:

isBalanced (Leaf _) = True -- assuming a single-leaf tree is trivially balanced


问:
Compiling custom package for Linux Embedded Development Environment (LEDE) (same as OpenWRT)
Hi all,

Platform: x86_64

I successfully installed a Linux Embedded Development Environment (LEDE) x86/64 (same as OpenWRT) to my virtual machine.

I developed a custom package "Hello World" for Linux Embedded Development Environment (LEDE) with SDK and cross-compiled it . Then, tested it on my virtual machine and it worked.
But, then I have my own code to port that is, for raw packet sniffer in c and I want to port that code. So, I copied same code under that same file that I used for "Hello world" (helloworld.c). Again, I successfully cross-compiled new binary "*.ipk format" then send it on my LEDE virtual machine and did opkg install xxxxxx.ipk. It installed, but same output. I mean "Hello world".

I don't know how. Because, code changed this time. Then, again for testing a wrote a simple factorial code and again . During testing in virtual machine. I found that it didn't work because same output again that is, "Hello world".

Documentation:Hello world package for LEDE using LEDE Source
I am developing using SDK instead of source.I followed every thing in Documentation excluding source compiling and all.

Documentation for SDK: Compile custom package using SDK

Makefile for Hello World code:

```<code>include $(TOPDIR)/rules.mk

# Name, version and release number
# The name and version of your package are used to define the variable to point to the build directory of your package: $(PKG_BUILD_DIR)
PKG_NAME:=helloworld
PKG_VERSION:=1.0
PKG_RELEASE:=1

# Source settings (i.e. where to find the source codes)
# This is a custom variable, used below
SOURCE_DIR:=/home/buildbot/helloworld

include $(INCLUDE_DIR)/package.mk

# Package definition; instructs on how and where our package will appear in the overall configuration menu ('make menuconfig')
define Package/helloworld
  SECTION:=examples
  CATEGORY:=Examples
  TITLE:=Hello, World!
endef

# Package description; a more verbose description on what our package does
define Package/helloworld/description
  A simple "Hello, world!" -application.
endef

# Package preparation instructions; create the build directory and copy the source code.
# The last command is necessary to ensure our preparation instructions remain compatible with the patching system.
define Build/Prepare
        mkdir -p $(PKG_BUILD_DIR)
        cp $(SOURCE_DIR)/* $(PKG_BUILD_DIR)
        $(Build/Patch)
endef

# Package build instructions; invoke the target-specific compiler to first compile the source file, and then to link the file into the final executable
define Build/Compile
        $(TARGET_CC) $(TARGET_CFLAGS) -o $(PKG_BUILD_DIR)/helloworld.o -c $(PKG_BUILD_DIR)/helloworld.c
        $(TARGET_CC) $(TARGET_LDFLAGS) -o $(PKG_BUILD_DIR)/$1 $(PKG_BUILD_DIR)/helloworld.o
endef

# Package install instructions; create a directory inside the package to hold our executable, and then copy the executable we built previously into the folder
define Package/helloworld/install
        $(INSTALL_DIR) $(1)/usr/bin
        $(INSTALL_BIN) $(PKG_BUILD_DIR)/helloworld $(1)/usr/bin
endef

# This command is always the last, it uses the definitions and variables we give above in order to get the job done
$(eval $(call BuildPackage,helloworld))
</code>```

答:
I added custom package in openwrt successfully and this is my Makefile, hope this helps you</p>

```<code>include $(TOPDIR)/rules.mk

PKG_NAME:=viva
PKG_VERSION:=1.4
PKG_RELEASE=$(PKG_SOURCE_VERSION)
PKG_MAINTAINER:=Vishal <yourname@domain.for.your.name>
PKG_LICENSE:=ISC

include $(INCLUDE_DIR)/package.mk

define Package/viva/default
  CATEGORY:=Network
  SUBMENU:=Web Servers/Proxies
  TITLE:=Webpage for package creation
endef

define Package/viva
  $(Package/viva/default)
  DEPENDS:=+uhttpd
endef

define Package/viva/description
    A web page used for illustrating package creation
endef

define Package/viva/install
    $(CP) ./files/* $(1)/
endef

define Build/Compile
    true
endef

$(eval $(call BuildPackage,viva))
</code>```

Body:
Hi all,

Platform: x86_64

I successfully installed a Linux Embedded Development Environment (LEDE) x86/64 (same as OpenWRT) to my virtual machine.

I developed a custom package "Hello World" for Linux Embedded Development Environment (LEDE) with SDK and cross-compiled it . Then, tested it on my virtual machine and it worked.
But, then I have my own code to port that is, for raw packet sniffer in c and I want to port that code. So, I copied same code under that same file that I used for "Hello world" (helloworld.c). Again, I successfully cross-compiled new binary "*.ipk format" then send it on my LEDE virtual machine and did opkg install xxxxxx.ipk. It installed, but same output. I mean "Hello world".

I don't know how. Because, code changed this time. Then, again for testing a wrote a simple factorial code and again . During testing in virtual machine. I found that it didn't work because same output again that is, "Hello world".

Documentation:Hello world package for LEDE using LEDE Source
I am developing using SDK instead of source.I followed every thing in Documentation excluding source compiling and all.

Documentation for SDK: Compile custom package using SDK

Makefile for Hello World code:

include $(TOPDIR)/rules.mk

# Name, version and release number
# The name and version of your package are used to define the variable to point to the build directory of your package: $(PKG_BUILD_DIR)
PKG_NAME:=helloworld
PKG_VERSION:=1.0
PKG_RELEASE:=1

# Source settings (i.e. where to find the source codes)
# This is a custom variable, used below
SOURCE_DIR:=/home/buildbot/helloworld

include $(INCLUDE_DIR)/package.mk

# Package definition; instructs on how and where our package will appear in the overall configuration menu ('make menuconfig')
define Package/helloworld
  SECTION:=examples
  CATEGORY:=Examples
  TITLE:=Hello, World!
endef

# Package description; a more verbose description on what our package does
define Package/helloworld/description
  A simple "Hello, world!" -application.
endef

# Package preparation instructions; create the build directory and copy the source code.
# The last command is necessary to ensure our preparation instructions remain compatible with the patching system.
define Build/Prepare
        mkdir -p $(PKG_BUILD_DIR)
        cp $(SOURCE_DIR)/* $(PKG_BUILD_DIR)
        $(Build/Patch)
endef

# Package build instructions; invoke the target-specific compiler to first compile the source file, and then to link the file into the final executable
define Build/Compile
        $(TARGET_CC) $(TARGET_CFLAGS) -o $(PKG_BUILD_DIR)/helloworld.o -c $(PKG_BUILD_DIR)/helloworld.c
        $(TARGET_CC) $(TARGET_LDFLAGS) -o $(PKG_BUILD_DIR)/$1 $(PKG_BUILD_DIR)/helloworld.o
endef

# Package install instructions; create a directory inside the package to hold our executable, and then copy the executable we built previously into the folder
define Package/helloworld/install
        $(INSTALL_DIR) $(1)/usr/bin
        $(INSTALL_BIN) $(PKG_BUILD_DIR)/helloworld $(1)/usr/bin
endef

# This command is always the last, it uses the definitions and variables we give above in order to get the job done
$(eval $(call BuildPackage,helloworld))

Body:
I added custom package in openwrt successfully and this is my Makefile, hope this helps you

include $(TOPDIR)/rules.mk

PKG_NAME:=viva
PKG_VERSION:=1.4
PKG_RELEASE=$(PKG_SOURCE_VERSION)
PKG_MAINTAINER:=Vishal <yourname@domain.for.your.name>
PKG_LICENSE:=ISC

include $(INCLUDE_DIR)/package.mk

define Package/viva/default
  CATEGORY:=Network
  SUBMENU:=Web Servers/Proxies
  TITLE:=Webpage for package creation
endef

define Package/viva
  $(Package/viva/default)
  DEPENDS:=+uhttpd
endef

define Package/viva/description
    A web page used for illustrating package creation
endef

define Package/viva/install
    $(CP) ./files/* $(1)/
endef

define Build/Compile
    true
endef

$(eval $(call BuildPackage,viva))


问:
How to validate input when submit without refreshing the page in Laravel?
if I have a unique column it will send a validate notif that indicates that this email already exists When I submit my input. I want to implement it in Laravel. Please, help me to start with this. Thanks</p>

答:
I am using axios for the example but you can you use jQuery Ajax as well

 axios.post('/login', loginParams).then(function (r) {
                   //Do in case of success
                }).catch(function () {
                    new Noty({
                        type: 'Danger',
                        text: '' + r.data.success.name + '',
                    }).show();
 });
```

<p>And in laravel </p>

<pre class="lang-html prettyprint-override"><code>    public function validator(Request $request)
    {
         $this->validate($request, [
            'email' => 'required|email|max:255|unique:users',
        ]);

    }
</code>```

Body:
I am using axios for the example but you can you use jQuery Ajax as well

 axios.post('/login', loginParams).then(function (r) {
                   //Do in case of success
                }).catch(function () {
                    new Noty({
                        type: 'Danger',
                        text: '<b>' + r.data.success.name + '</b>',
                    }).show();
 });

And in laravel

    public function validator(Request $request)
    {
         $this->validate($request, [
            'email' => 'required|email|max:255|unique:users',
        ]);

    }


问:
How to generate libcurl.so.5 with curl 7.56.1 in Yocto?
I have builded previously libcurl.so.5 when I compile curl 7.53.1
Now when I compile curl 7.56.1 the generated librarie is: libcurl.so.4.5 , how can I define the version to build?</p>

答:
The X in libcurl.so.X is ABI version, i.e. version that defines compatibility between application and library. So, you cannot just select whatever you wish to have as it depends on library API and its implementation in library sources. So, you either should rebuild all dependent components (and make them support it) on newer version or set preferred version of curl in local config (or custom distro config):

```<code>PREFERRED_VERSION_curl = "A.B.C"
</code>```

which corresponds to the desired version of libcurl.

Body:
The X in libcurl.so.X is ABI version, i.e. version that defines compatibility between application and library. So, you cannot just select whatever you wish to have as it depends on library API and its implementation in library sources. So, you either should rebuild all dependent components (and make them support it) on newer version or set preferred version of curl in local config (or custom distro config):

PREFERRED_VERSION_curl = "A.B.C"

which corresponds to the desired version of libcurl.


问:
Storing a list of unicode strings in a csv file python 2
I created a function(parse_html(param)) that returns a list like below,

```<code>list = [u'John', u'Muchia', u'Prozessoptimierung Fahrwiderst\xe4nde']
</code>```

if I return print list[2], and in my function, it gives me Prozessoptimierung Fahrwiderstände which is perfect, but it appears differently when in a list

The problem lies when I return the whole list return list I want to avoid the 'u'. I want to store a list of strings and the Unicode characters like ä ö and ü should also appear.

fname[x] is the source of the HTML file where x is the file number which is incremented from 0 to count(file_number)

```<code>list=[]
newlist=[]
list = parse_html(fname[7])
for row in list:
  drow = row.encode('utf-8')
  newlist.append(drow)
print newlist
</code>```

The goal is to save the returned list to a CSV file. Everytime a new file(fname) is selected, the list is created and should add the new list to the csv file previously created.

I am doing something really wrong and I can realize that and my head hurts. Please help.

update:

```<code>for x in range(0,count):
    list = parse_html(fname[x])
    with open('output.csv', 'wb') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(list)
</code>```

error:

```<code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 132: ordinal not in range(1
28)
</code>```

Answer:

```<code>wr.writerow([c.encode('utf-8') for c in list]) # instead `wr.writerow(list)
</code>```

答:
The problem is in your CSV output code. Since you are using Python 2, you should encode directly to utf-8 before writing:

```<code>    wr.writerow([c.encode('utf-8') for c in list])
</code>```

Or, upgrade to Python 3 for more integrated unicode support.

Body:
I created a function(parse_html(param)) that returns a list like below,

list = [u'John', u'Muchia', u'Prozessoptimierung Fahrwiderst\xe4nde']

if I return print list[2], and in my function, it gives me Prozessoptimierung Fahrwiderstände which is perfect, but it appears differently when in a list

The problem lies when I return the whole list return list I want to avoid the 'u'. I want to store a list of strings and the Unicode characters like ä ö and ü should also appear.

fname[x] is the source of the HTML file where x is the file number which is incremented from 0 to count(file_number)

list=[]
newlist=[]
list = parse_html(fname[7])
for row in list:
  drow = row.encode('utf-8')
  newlist.append(drow)
print newlist

The goal is to save the returned list to a CSV file. Everytime a new file(fname) is selected, the list is created and should add the new list to the csv file previously created.

I am doing something really wrong and I can realize that and my head hurts. Please help.

update:

for x in range(0,count):
    list = parse_html(fname[x])
    with open('output.csv', 'wb') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(list)

error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 132: ordinal not in range(1
28)

Answer:

wr.writerow([c.encode('utf-8') for c in list]) # instead `wr.writerow(list)

Body:
The problem is in your CSV output code. Since you are using Python 2, you should encode directly to utf-8 before writing:

    wr.writerow([c.encode('utf-8') for c in list])

Or, upgrade to Python 3 for more integrated unicode support.


问:
putting inline style using ternary operator php
I am trying to add css inline style based on a php variable's value.
I tried doing so with ternary operator, and also I converted the variable value to float. But the css is not being applied as expected.

```<code>       <tbody>
        <?php
        $totalLeaveTaken = 0.00;
        $totalBalance = 0.00;
            foreach ($GetEmployeeLeaveBalance as $member):
                $totalLeaveTaken += $member['usedDays'];
                $totalBalance += $member['Remaining_Leave_Days'];
                $leaveBalance = floatval($member['Remaining_Leave_Days']);
            ?>
            <tr>
                <td><?php echo $member['title']; ?></td>
                <td><?php echo $member['maxDays']; ?></td>
                <td><?php echo $member['usedDays']; ?></td>
                <!-- <td><?php echo gettype($leaveBalance);?></td> -->
                <td
                <?php
                ($leaveBalance < 0) ?
                "style='background-color:red;'" : "style='background-color:green;'"
                ?>
                >
                <?php echo $member['Remaining_Leave_Days']; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        <tr>
            <td></td>
            <td></td>
            <td style="background-color: #33CCFF; font-weight: bold;">Total: <?php echo number_format($totalLeaveTaken, 2); ?></td>
            <td style="background-color: #33CCFF; font-weight: bold;">Total: <?php echo
            number_format($totalBalance, 2); ?></td>
        </tr>
        </tbody>
</code>```

But the simple inline styling is working fine.

答:
You're missing the echo command prior to the condition.
Basically if the condition returns true or false, the statements are being returned and not necessary being echoed.

```<code><?php
echo ($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'"
?>
</code>```

Sidenote, A better practice:

Since both of the returned strings are style, there's no point in repeating it (developers are lazy :] ). So you can simply write:

```<code><td style='background-color: <?php echo ($leaveBalance < 0) ? "red" : "green" ?>'>
</code>```

Body:
I am trying to add css inline style based on a php variable's value.
I tried doing so with ternary operator, and also I converted the variable value to float. But the css is not being applied as expected.

        <?php
        $totalLeaveTaken = 0.00;
        $totalBalance = 0.00;
            foreach ($GetEmployeeLeaveBalance as $member):
                $totalLeaveTaken += $member['usedDays'];
                $totalBalance += $member['Remaining_Leave_Days'];
                $leaveBalance = floatval($member['Remaining_Leave_Days']);
            ?>

                <?php echo $member['title']; ?>
                <?php echo $member['maxDays']; ?>
                <?php echo $member['usedDays']; ?>

                <td
                <?php
                ($leaveBalance < 0) ?
                "style='background-color:red;'" : "style='background-color:green;'"
                ?>
                >
                <?php echo $member['Remaining_Leave_Days']; ?>

        <?php endforeach; ?>

            Total: <?php echo number_format($totalLeaveTaken, 2); ?>
            Total: <?php echo
            number_format($totalBalance, 2); ?>

But the simple inline styling is working fine.

Body:
You're missing the echo command prior to the condition.
Basically if the condition returns true or false, the statements are being returned and not necessary being echoed.

<?php
echo ($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'"
?>

Sidenote, A better practice:

Since both of the returned strings are style, there's no point in repeating it (developers are lazy :] ). So you can simply write:

<td style='background-color: <?php echo ($leaveBalance < 0) ? "red" : "green" ?>'>


问:
c# console application backup mysql
I try to use this code as a console application so that I can back up mydatabase automatics
I am not sure what wrong with it</p>

```<code>static void Main(string[] args)
{
    try
    {
        DateTime backupTime = DateTime.Now;
        int year = backupTime.Year;
        int month = backupTime.Month;
        int day = backupTime.Day;
        int hour = backupTime.Hour;
        int minute = backupTime.Minute;
        int second = backupTime.Second;
        int ms = backupTime.Millisecond;

        String tmestr = backupTime.ToString();
        tmestr = "C:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + ".sql";
        StreamWriter file = new StreamWriter(tmestr);
        ProcessStartInfo proc = new ProcessStartInfo();
        string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");
        proc.FileName = "mysqldump";
        proc.RedirectStandardInput = false;
        proc.RedirectStandardOutput = true;
        proc.Arguments = cmd;//"-u root -p smartdb > testdb.sql";
        proc.UseShellExecute = false;
        Process p = Process.Start(proc);
        string res;
        res = p.StandardOutput.ReadToEnd();
        file.WriteLine(res);
        p.WaitForExit();
        file.Close();

    }

    catch (IOException ex)
    {
        MessageBox.Show("Disk full or other IO error , unable to backup!");
    }
}
</code>```

答:
Since I'm not sure what kind of error you're geting, atleast this could be changed.

```<code>string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");
</code>```

Later you commented it should be -u root -p smartdb > testdb.sql";
except the above, is missing the space after the -u so I'd change it to:

```<code>string cmd = string.Format(@"-u {0} -p {1} -h {2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");
</code>```

ContentLicense: CC BY-SA 2.5

Title: c# console application backup mysql

Body:
I try to use this code as a console application so that I can back up mydatabase automatics
I am not sure what wrong with it

static void Main(string[] args)
{
    try
    {
        DateTime backupTime = DateTime.Now;
        int year = backupTime.Year;
        int month = backupTime.Month;
        int day = backupTime.Day;
        int hour = backupTime.Hour;
        int minute = backupTime.Minute;
        int second = backupTime.Second;
        int ms = backupTime.Millisecond;

        String tmestr = backupTime.ToString();
        tmestr = "C:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + ".sql";
        StreamWriter file = new StreamWriter(tmestr);
        ProcessStartInfo proc = new ProcessStartInfo();
        string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");
        proc.FileName = "mysqldump";
        proc.RedirectStandardInput = false;
        proc.RedirectStandardOutput = true;
        proc.Arguments = cmd;//"-u root -p smartdb > testdb.sql";
        proc.UseShellExecute = false;
        Process p = Process.Start(proc);
        string res;
        res = p.StandardOutput.ReadToEnd();
        file.WriteLine(res);
        p.WaitForExit();
        file.Close();

    }

    catch (IOException ex)
    {
        MessageBox.Show("Disk full or other IO error , unable to backup!");
    }
}

Body:
Since I'm not sure what kind of error you're geting, atleast this could be changed.

string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");

Later you commented it should be -u root -p smartdb > testdb.sql";
except the above, is missing the space after the -u so I'd change it to:

string cmd = string.Format(@"-u {0} -p {1} -h {2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");


问:
How can i merge the two Array JSON nested responses using NODE JS?
1. First response is categories with two fields, category and name.

```<code>categories = [{ category: '1', name: 'category1' },
              { category: '2', name: 'category2' }]
</code>```

2. Second response is commits with three fields, commit, branch and Commit ID.

```<code> commits = [{ commit: '1', branch: '1', Commit ID: 'commitid1' },
            { commit: '1', branch: '2', Commit ID: 'commitid2' }]
</code>```

3. I want to create one merged JSON, based on the category that would have the following structure:

```<code>all = [
       { category: '1', name: 'category1',
             body: [{ commit: '1', branch: '1', Commit ID: 'commitid1' }],
        { category: '2', name: 'category2',
              body: [{ commit: '1', branch: '1', Commit ID: 'commitid2' }]
</code>```

I searched and found several methods of joining or extending two json objects but nothing similar to that.

Any help would be appreciated.

My Actual Code

```<code>exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
  status: Boolean,
  message: String,
  data: String
};
var request = require('request');
var username =
  const.username;
var password =
  const.password;
var options = {
  url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
  auth: {
    username: username,
    password: password
  }
};

request(options, function(error, obj) {
      if (error) {
        response.message = appmsg.DATA_NT_FOUND;
        response.status = false;
        response.data = obj;
        res.send(response);
      } else {
        response.message = appmsg.DATA_FOUND;
        response.status = true;
        response.data = JSON.parse(obj.body);
        //res.send(response);
        var issueKey = response.data.issues;

        // var keyData = issueKey[0].key;
        // console.log(response.data.issues);
        // console.log(keyData);
        var output = [];
        for (var i = 0; i < issueKey.length; i++) {
          var issue = issueKey[i].key;
          //var key = [];
          //key.push(issue);
          console.log(issue);

          var respon = {
            status: Boolean,
            message: String,
            data: String
          };
          var request = require('request'),
            username =
            const.username,
            password =
            const.username,
            url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
            auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

          //console.log(url);
          request({
            url: url,
            headers: {
              "Authorization": auth
            }
          }, function(err, object) {
            if (object) {

              var info = object;
              output.push(info); // this is not working as ouput is undefined at this    point
              //var pout = JSON.parse(output);
              //console.log(info);
              console.log("==============================================================================");
              //console.log(output);
              console.log("******************************************************************************");
              if (issueKey.length === output.length) {
                respon.message = appmsg.DATA_FOUND;
                respon.status = true;
                respon.data = output;
                //console.log(output);
                //res.send(respon);

                var id = issueKey[0].id;
                console.log(id);

                var commitout = [];
                for (var i = 0; i < issueKey.length; i++) {
                  var commits = issueKey[i].id;
                  console.log(commits);

                  var request = require('request'),
                    username =
                    const.username,
                    password =
                    const.password,
                    url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                  //console.log(url);
                  var test = [];
                  request({
                      url: url,
                      headers: {
                        "Authorization": auth
                      }
                    }, function(err, obj1) {
                      if (obj1) {

                        var info1 = obj1.body;
                        commitout.push(info1);
                        if (issueKey.length === commitout.length) {
                          respon.message = appmsg.DATA_FOUND;
                          respon.status = true;
                          respon.data = commitout;
                          // console.log(commitout);
                          //var test = merge(output, commitout);

                          var resultdone = [];
                          request({
                            url: url,
                            headers: {
                              "Authorization": auth
                            }
                          }, function(err, obj1) {
                            if (obj1) {

                              var info1 = obj1.body;
                              commitout.push(info1);
                              if (issueKey.length === commitout.length) {

                                // console.log(commitout);
                                //var test = merge(output, commitout);
                                //var text = output.body[0];
                                //var resultdone = [];
                                resultdone.push(commitout.concat(output));
                                console.log(resultdone);
                                respon.message = appmsg.DATA_FOUND;
                                respon.status = true;
                                respon.data = resultdone;
                                res.send(respon);
                              }
                            }
                          });
                        }

                      }
                    }

                  });

              }
            }

          });
</code>```

答:
What about this??</p>

```<code>var all= categories.map(function(cat){
                           cat.body=commits.filter(x=>x.branch==cat.category);
                           return cat;
         })
</code>```

Body:
1. First response is categories with two fields, category and name.

categories = [{ category: '1', name: 'category1' },
              { category: '2', name: 'category2' }]

2. Second response is commits with three fields, commit, branch and Commit ID.

 commits = [{ commit: '1', branch: '1', Commit ID: 'commitid1' },
            { commit: '1', branch: '2', Commit ID: 'commitid2' }]

3. I want to create one merged JSON, based on the category that would have the following structure:

all = [
       { category: '1', name: 'category1',
             body: [{ commit: '1', branch: '1', Commit ID: 'commitid1' }],
        { category: '2', name: 'category2',
              body: [{ commit: '1', branch: '1', Commit ID: 'commitid2' }]

I searched and found several methods of joining or extending two json objects but nothing similar to that.

Any help would be appreciated.

My Actual Code

exports.getIssues = function(req, res) {
console.log(filename + '>>get Issues>>');
var response = {
  status: Boolean,
  message: String,
  data: String
};
var request = require('request');
var username =
  const.username;
var password =
  const.password;
var options = {
  url: 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
  auth: {
    username: username,
    password: password
  }
};

request(options, function(error, obj) {
      if (error) {
        response.message = appmsg.DATA_NT_FOUND;
        response.status = false;
        response.data = obj;
        res.send(response);
      } else {
        response.message = appmsg.DATA_FOUND;
        response.status = true;
        response.data = JSON.parse(obj.body);
        //res.send(response);
        var issueKey = response.data.issues;

        // var keyData = issueKey[0].key;
        // console.log(response.data.issues);
        // console.log(keyData);
        var output = [];
        for (var i = 0; i < issueKey.length; i++) {
          var issue = issueKey[i].key;
          //var key = [];
          //key.push(issue);
          console.log(issue);

          var respon = {
            status: Boolean,
            message: String,
            data: String
          };
          var request = require('request'),
            username =
            const.username,
            password =
            const.username,
            url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
            auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

          //console.log(url);
          request({
            url: url,
            headers: {
              "Authorization": auth
            }
          }, function(err, object) {
            if (object) {

              var info = object;
              output.push(info); // this is not working as ouput is undefined at this    point
              //var pout = JSON.parse(output);
              //console.log(info);
              console.log("==============================================================================");
              //console.log(output);
              console.log("******************************************************************************");
              if (issueKey.length === output.length) {
                respon.message = appmsg.DATA_FOUND;
                respon.status = true;
                respon.data = output;
                //console.log(output);
                //res.send(respon);

                var id = issueKey[0].id;
                console.log(id);

                var commitout = [];
                for (var i = 0; i < issueKey.length; i++) {
                  var commits = issueKey[i].id;
                  console.log(commits);

                  var request = require('request'),
                    username =
                    const.username,
                    password =
                    const.password,
                    url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                  //console.log(url);
                  var test = [];
                  request({
                      url: url,
                      headers: {
                        "Authorization": auth
                      }
                    }, function(err, obj1) {
                      if (obj1) {

                        var info1 = obj1.body;
                        commitout.push(info1);
                        if (issueKey.length === commitout.length) {
                          respon.message = appmsg.DATA_FOUND;
                          respon.status = true;
                          respon.data = commitout;
                          // console.log(commitout);
                          //var test = merge(output, commitout);

                          var resultdone = [];
                          request({
                            url: url,
                            headers: {
                              "Authorization": auth
                            }
                          }, function(err, obj1) {
                            if (obj1) {

                              var info1 = obj1.body;
                              commitout.push(info1);
                              if (issueKey.length === commitout.length) {

                                // console.log(commitout);
                                //var test = merge(output, commitout);
                                //var text = output.body[0];
                                //var resultdone = [];
                                resultdone.push(commitout.concat(output));
                                console.log(resultdone);
                                respon.message = appmsg.DATA_FOUND;
                                respon.status = true;
                                respon.data = resultdone;
                                res.send(respon);
                              }
                            }
                          });
                        }

                      }
                    }

                  });

              }
            }

          });

Body:
What about this??

var all= categories.map(function(cat){
                           cat.body=commits.filter(x=>x.branch==cat.category);
                           return cat;
         })


答:
Assuming that the spaces either side are fixed then you could use str.split:

```<code>In[90]:
df['result'] = df['str'].str.split(' v ').str[0]
df

Out[90]:
                                     str           result
0         Potato onions v carrot pickles    Potato onions
1           Chocolate cake v orange cake   Chocolate cake
2         Chicken breasts v Vegan Quinoa  Chicken breasts
3  Vienna sauvsage v velovute vegetvable  Vienna sauvsage
</code>```

So this splits the string on ' v ' and returns the first entry in the split

Title: Not able to effectively remove strings before ‘v’ or deleting strings v and after

Body:
Assuming that the spaces either side are fixed then you could use str.split:

In[90]:
df['result'] = df['str'].str.split(' v ').str[0]
df

Out[90]:
                                     str           result
0         Potato onions v carrot pickles    Potato onions
1           Chocolate cake v orange cake   Chocolate cake
2         Chicken breasts v Vegan Quinoa  Chicken breasts
3  Vienna sauvsage v velovute vegetvable  Vienna sauvsage

So this splits the string on ' v ' and returns the first entry in the split


问:
How to return the original collection type from generic method
I have a generic method that should return a collection of the same type as input:

```<code>def removeN[A, C <: Seq[A]](s: C, n: Int): C = {
  s.take(n) ++ s.drop(n + 1) // Sample operation
}
</code>```

But this code does not compile:

Error:(34, 15) type mismatch;  found   : Seq[A]  required: C
      s.take(n) ++ s.drop(n + 1)

How is this possible when C clearly stands for Seq[A]? Does it mean that this kind of concatenation always return an instance of parent type Seq[A], not a subtype C? Could my code be rewritten in order to produce a collection of type C?

Is this a correct way to define a generic method that returns the same collection type (in my case a subtype of Seq) as input in general?

Scala 2.12.4

答:
What you're asking for can be done using one of the most powerful yet controversial features of the collections library, that is CanBuildFrom. Here is how:

```<code>import scala.language.higherKinds
import scala.collection.generic.CanBuildFrom

def removeN[A, C[A] <: Seq[A]](s: C[A], n: Int)
  (implicit cbf: CanBuildFrom[C[A], A, C[A]]): C[A] = {
  val builder = cbf()
  builder.sizeHint(s.size)
  builder ++= s.take(n)
  builder ++= s.drop(n + 1)
  builder.result()
}
</code>```

Let's give it a twist in the REPL:

```<code>scala> removeN(List(4, 5, 6), 2)
res0: List[Int] = List(4, 5)

scala> removeN(Vector(4, 5, 6), 2)
res1: scala.collection.immutable.Vector[Int] = Vector(4, 5)
</code>```

It seems to work.

import scala.language.higherKinds is needed in order to avoid a warning for the higher-kind (C[A]) usage.

Body:
I have a generic method that should return a collection of the same type as input:

def removeN[A, C <: Seq[A]](s: C, n: Int): C = {
  s.take(n) ++ s.drop(n + 1) // Sample operation
}

But this code does not compile:

Error:(34, 15) type mismatch;  found   : Seq[A]  required: C
      s.take(n) ++ s.drop(n + 1)

How is this possible when C clearly stands for Seq[A]? Does it mean that this kind of concatenation always return an instance of parent type Seq[A], not a subtype C? Could my code be rewritten in order to produce a collection of type C?

Is this a correct way to define a generic method that returns the same collection type (in my case a subtype of Seq) as input in general?

Scala 2.12.4

Body:
What you're asking for can be done using one of the most powerful yet controversial features of the collections library, that is CanBuildFrom. Here is how:

import scala.language.higherKinds
import scala.collection.generic.CanBuildFrom

def removeN[A, C[A] <: Seq[A]](s: C[A], n: Int)
  (implicit cbf: CanBuildFrom[C[A], A, C[A]]): C[A] = {
  val builder = cbf()
  builder.sizeHint(s.size)
  builder ++= s.take(n)
  builder ++= s.drop(n + 1)
  builder.result()
}

Let's give it a twist in the REPL:

scala> removeN(List(4, 5, 6), 2)
res0: List[Int] = List(4, 5)

scala> removeN(Vector(4, 5, 6), 2)
res1: scala.collection.immutable.Vector[Int] = Vector(4, 5)

It seems to work.

import scala.language.higherKinds is needed in order to avoid a warning for the higher-kind (C[A]) usage.


答:
Not

```<code><?php
    ($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'"
?>
</code>```

but

```<code><?php
    echo (($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'");
?>
</code>```

or

```<code><?= (($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'"); ?>
</code>```

Title: putting inline style using ternary operator php

Body:
Not

<?php
    ($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'"
?>

but

<?php
    echo (($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'");
?>

or

<?= (($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'"); ?>


问:
WCF exposing generic type 'T'
I write a WCF service for Insert and delete operation here we used generic method but it gives following error
"System.Runtime.Serialization.InvalidDataContractException: Type 'T' cannot be exported as a schema type because it is an open generic type. You can only export a generic type if all its generic parameter types are actual types."

here "EntityBase2" is base class for all entities

```<code>[ServiceContract]
[ServiceKnownType(typeof(EntityBase2))]
public interface IBackupUtility
{
    [OperationContract]
    void Delete<T>(T entity) where T : EntityBase2;

    [OperationContract]
    void InsertORUpdate<T>(T entity) where T : EntityBase2;
}
</code>```

Question is how i can expose generic type 'T'?

答:
I think it is imposible, how could it generate the wsdl that way?

You have two options:

You could send the type as a parameter.

If you want to expose crud operations for entities I would recommend to use a code generator, maybe a T4 template for EF.

Title: WCF exposing generic type 'T'

Body:
I write a WCF service for Insert and delete operation here we used generic method but it gives following error
"System.Runtime.Serialization.InvalidDataContractException: Type 'T' cannot be exported as a schema type because it is an open generic type. You can only export a generic type if all its generic parameter types are actual types."

here "EntityBase2" is base class for all entities

[ServiceContract]
[ServiceKnownType(typeof(EntityBase2))]
public interface IBackupUtility
{
    [OperationContract]
    void Delete<T>(T entity) where T : EntityBase2;

    [OperationContract]
    void InsertORUpdate<T>(T entity) where T : EntityBase2;
}

Question is how i can expose generic type 'T'?


问:
ES6 how to get source code for filter( ) method
I've tried to reproduce the method filter so far I have got:

```<code>function filtre(...[T,x,y]){
let tabPersF = [];
for (let pers of T) {
    if (x(...[pers,y])) {
      tabPersF.push( pers );
     }

}
  return tabPersF;
}
</code>```

How about it?.

答:
So I've tried to reproduce the method filter I got this and I know
  it's not good.

Multiple issues with this code

array2 not initialized

array2 not an array and what is puts

function keyword as parameter

Make it

function filter(array, func) {
  let array2 = [];
  for ( var counter = 0; counter < array.length; counter++) {
    if (func(array[counter], counter, array )) {
      array2.push(array[counter]);
    }
  }
  return array2;
}

console.log( filter( [1,2,3], function(s){ return s>1 } ) );

console.log( filter( ["132","322","23433"], function(s){ return s.length>3 } ) );

var arr = [ {name: "asdasd", age: 10}, {name: "asdasd2", age: 20} ];

console.log( filter( arr , function(s){ return s.age>19 } ) );```

Body:
I've tried to reproduce the method filter so far I have got:

function filtre(...[T,x,y]){
let tabPersF = [];
for (let pers of T) {
    if (x(...[pers,y])) {
      tabPersF.push( pers );
     }

}
  return tabPersF;
}

How about it?.


问:
Route and transform data from Azure IoT Hub
in our usecase, we receive messages on Azure IoT Hub, and would like to route the data to different Event Hubs or Service Bus topics.

IoT Hub routes and endpoints are no option, because the data is binary data (protobuf), and there are only 10 different endpoints possible (we need more).

Our requierements are:

Splitting the message

Transform the data (maybe json)

Routing to different endpoints based on the payload (different parts of message could be routed to different endpoints)

(optional) enrich the data with additional payload

I see different options:

Azure Stream Analytics

Azure Functions

Spark or Flink

Do it yourself (write an Application and run it in Service Fabric or Kubernets)

Which techology would you recommend?

Regards,
Markus

答:
There is also another option for your scenario such as using an Azure Event Grid.  In this case, the telemetry data from the Azure IoT Hub are pushed to the Event Grid via its custom topic endpoint. Note, that there is a limit for the event message such as 64KB, see more details here.

The Event Grid allows to subscribe unlimited number of the Event Hubs, more details about the Event Grid are here and here.

Based on the above, the following screen snippet shows your another option for routing a small telemetry data to more than 10 Event Hubs, basically to any kind of subscriber.


问:
Java: order a JTable according to columns from enum
I have a JTable where several columns contain a number from an enums like the following:

```<code>public static enum IMPORT_CONF_OPERATION_RESULT {
    OK(0, "OK"),
    ERROR(1, "ERROR"),
    WAITING(2, "WAITING");
    /* ... */
}
</code>```

So, I needed to override method getValueAt() of table model looping through enum values in order to decode and return the correspondent String for each row as, in the database from which data come from, the numeric values are stored.
Now, if the user clicks on the correspondent header column, row are sorted according to numeric values but I would like to order them in alphabetical order. Shall I override sort() method of table model? Isn't looping so many times through enum values to get the description inefficient? Would it slow down table rendering?

UPDATE

This could be a solution following to what STaefi suggested, inside my extended DefaultTableModelField:

```<code>@Override
public void sort(int col, boolean ascendest) {
    ColumnProperties columnProperties = this.mapColumn.get(col);
    if (COLUMN_NAME_ENTITY.equals(columnProperties.getInfo()) ||
        COLUMN_OPERATION_TYPE.equals(columnProperties.getInfo()) ||
        COLUMN_OPERATION_RESULT.equals(columnProperties.getInfo()) ||
        COLUMN_ELABORATION_TYPE.equals(columnProperties.getInfo()) ||
        COLUMN_EVENT_STATE.equals(columnProperties.getInfo())) {
        Collections.sort((List<TableImportConfEvent>)this.value, new EnumColumnSorter(ascendest, columnProperties.getInfo()));
        this.fireTableDataChanged();
    }
    else {
        super.sort(col, ascendest);
    }
}

private class EnumColumnSorter implements Comparator<TableImportConfEvent> {

    private int ascending;
    private String columnName;
    public EnumColumnSorter(boolean ascendest, String columnName) {
        this.ascending = ascendest ? 1 : -1;
        this.columnName = columnName;
    }
    @Override
    public int compare(TableImportConfEvent o1, TableImportConfEvent o2) {
        String decodedString1 = "";
        String decodedString2 = "";
        if (COLUMN_NAME_ENTITY.equals(this.columnName)) {
            decodedString1 = getEntityName(o1.getEntityType());
            decodedString2 = getEntityName(o2.getEntityType());
        }
        else if (COLUMN_OPERATION_TYPE.equals(this.columnName)) {
            decodedString1 = getOperationName(o1.getOperationType());
            decodedString2 = getOperationName(o2.getOperationType());
        }
        else if (COLUMN_OPERATION_RESULT.equals(this.columnName)) {
            decodedString1 = getResultName(o1.getOperationResult());
            decodedString2 = getResultName(o2.getOperationResult());
        }
        else if (COLUMN_ELABORATION_TYPE.equals(this.columnName)) {
            decodedString1 = getResultName(o1.getOperationResult());
            decodedString2 = getResultName(o2.getOperationResult());
        }
        else if (COLUMN_EVENT_STATE.equals(this.columnName)) {
            decodedString1 = getStateName(o1.getEventState());
            decodedString2 = getStateName(o2.getEventState());
        }
        return (decodedString1.compareTo(decodedString2)) * this.ascending;
    }
}
</code>```

答:
To avoid looping over the enum values for each row, you may want to create a static final HashMap<Integer,IMPORT_CONF_OPERATION_RESULT> to cache the map of values to corresponding labels and initialize it in a static block inside of your enum. Then you can have a public static String getLabelByValue(int value) to use cache and avoid O(n) for looking up the label each time.

For controlling the sort orders and sort actions you may want to go after TableRowSorter but when you have overriden the getValueAt for your model the default sorting should be sufficient. Other way is use a custom Comparator in your table model to manage the logic of sorting.

Body:
I have a JTable where several columns contain a number from an enums like the following:

public static enum IMPORT_CONF_OPERATION_RESULT {
    OK(0, "OK"),
    ERROR(1, "ERROR"),
    WAITING(2, "WAITING");
    /* ... */
}

So, I needed to override method getValueAt() of table model looping through enum values in order to decode and return the correspondent String for each row as, in the database from which data come from, the numeric values are stored.
Now, if the user clicks on the correspondent header column, row are sorted according to numeric values but I would like to order them in alphabetical order. Shall I override sort() method of table model? Isn't looping so many times through enum values to get the description inefficient? Would it slow down table rendering?

UPDATE

This could be a solution following to what STaefi suggested, inside my extended DefaultTableModelField:

@Override
public void sort(int col, boolean ascendest) {
    ColumnProperties columnProperties = this.mapColumn.get(col);
    if (COLUMN_NAME_ENTITY.equals(columnProperties.getInfo()) ||
        COLUMN_OPERATION_TYPE.equals(columnProperties.getInfo()) ||
        COLUMN_OPERATION_RESULT.equals(columnProperties.getInfo()) ||
        COLUMN_ELABORATION_TYPE.equals(columnProperties.getInfo()) ||
        COLUMN_EVENT_STATE.equals(columnProperties.getInfo())) {
        Collections.sort((List<TableImportConfEvent>)this.value, new EnumColumnSorter(ascendest, columnProperties.getInfo()));
        this.fireTableDataChanged();
    }
    else {
        super.sort(col, ascendest);
    }
}

private class EnumColumnSorter implements Comparator<TableImportConfEvent> {

    private int ascending;
    private String columnName;
    public EnumColumnSorter(boolean ascendest, String columnName) {
        this.ascending = ascendest ? 1 : -1;
        this.columnName = columnName;
    }
    @Override
    public int compare(TableImportConfEvent o1, TableImportConfEvent o2) {
        String decodedString1 = "";
        String decodedString2 = "";
        if (COLUMN_NAME_ENTITY.equals(this.columnName)) {
            decodedString1 = getEntityName(o1.getEntityType());
            decodedString2 = getEntityName(o2.getEntityType());
        }
        else if (COLUMN_OPERATION_TYPE.equals(this.columnName)) {
            decodedString1 = getOperationName(o1.getOperationType());
            decodedString2 = getOperationName(o2.getOperationType());
        }
        else if (COLUMN_OPERATION_RESULT.equals(this.columnName)) {
            decodedString1 = getResultName(o1.getOperationResult());
            decodedString2 = getResultName(o2.getOperationResult());
        }
        else if (COLUMN_ELABORATION_TYPE.equals(this.columnName)) {
            decodedString1 = getResultName(o1.getOperationResult());
            decodedString2 = getResultName(o2.getOperationResult());
        }
        else if (COLUMN_EVENT_STATE.equals(this.columnName)) {
            decodedString1 = getStateName(o1.getEventState());
            decodedString2 = getStateName(o2.getEventState());
        }
        return (decodedString1.compareTo(decodedString2)) * this.ascending;
    }
}


问:
Seo url doens't work with homepage in OpenCart 3
I've enabled the option (Use SEO URLs) in settings (Opencart 3). All links such as contact, about, etc are working, except the homepage!

I have added this to the SEO URL page:

Query: common/home

Keyword: home

But it still appears as: index.php?route=common/home

How can I fix that?

答:
I hope it will help you as

Please make changes in catalog/controller/startup/seo_url.php

```<code>if `(($data['route'] == 'product/product' && $key == 'product_id') ||
    (($data['route'] == 'product/manufacturer/info' ||
    $data['route'] == 'product/product') && $key == 'manufacturer_id') ||
    ($data['route'] == 'information/information' && $key == 'information_id'))
{
</code>```

to

```<code>if (($data['route'] == 'product/product' && $key == 'product_id') ||
    (($data['route'] == 'product/manufacturer/info' ||
    $data['route'] == 'product/product') && $key == 'manufacturer_id') ||
    ($data['route'] == 'information/information' && $key == 'information_id') ||
    $data['route'] == 'common/home')
{
</code>```

Body:
I hope it will help you as

Please make changes in catalog/controller/startup/seo_url.php

if `(($data['route'] == 'product/product' && $key == 'product_id') ||
    (($data['route'] == 'product/manufacturer/info' ||
    $data['route'] == 'product/product') && $key == 'manufacturer_id') ||
    ($data['route'] == 'information/information' && $key == 'information_id'))
{

to

if (($data['route'] == 'product/product' && $key == 'product_id') ||
    (($data['route'] == 'product/manufacturer/info' ||
    $data['route'] == 'product/product') && $key == 'manufacturer_id') ||
    ($data['route'] == 'information/information' && $key == 'information_id') ||
    $data['route'] == 'common/home')
{


问:
Angularjs Using Same Directive Multiple Times as Element Execution order
I'm using a directive multiple times as a element in a view.

the execution of this directives is not starts from the parent. it first executes the children directives and then parent. so when parent executes at last, by compiling it the childs are getting executed two times.

Code as follows:

```<code><custom-directive dir-type="1">
   <custom-directive dir-type="2"></custom-directive>
   <custom-directive dir-type="3"></custom-directive>
   <custom-directive dir-type="4"></custom-directive>
</custom-directive>
</code>```

Here the Type 1 Directive comes to execution after all childs execution completed. so when parent directive type 1 executes i'm compiling it custom html (say uib-set). so these child directives also again compiling.

So please Help me How can i execute parent directive first then childs next...

答:
It doesnt look very pretty, but it can easily be solved by using:

```<code><custom-directive dir-type="1" ng-init="myTurn = true">
   <custom-directive dir-type="2" ng-if="myTurn"></custom-directive>
   <custom-directive dir-type="3" ng-if="myTurn"></custom-directive>
   <custom-directive dir-type="4" ng-if="myTurn"></custom-directive>
</custom-directive>
</code>```

Now the child directives will be triggered/compiled after the parent is compiled and ready.

However, I think this can be solved by using transclusion.

Maybe you can try adding this to your directive:

```<code>app.directive('customDirective', function() {
    return {
        //
        transclude: true,
        //
    }
});
</code>```

By using transclusion, you are 'telling' the parent element: "Hey, you have child elements". So Angular knows that the children belong to the parent, and they will (I think) wait for the parent element to be compiled.

If this transclusion works, please do not use the first solution. It's best to avoid ng-init: it makes debugging harder.

Documentation on transclusion

Body:
I'm using a directive multiple times as a element in a view.

the execution of this directives is not starts from the parent. it first executes the children directives and then parent. so when parent executes at last, by compiling it the childs are getting executed two times.

Code as follows:

<custom-directive dir-type="1">
   <custom-directive dir-type="2"></custom-directive>
   <custom-directive dir-type="3"></custom-directive>
   <custom-directive dir-type="4"></custom-directive>
</custom-directive>

Here the Type 1 Directive comes to execution after all childs execution completed. so when parent directive type 1 executes i'm compiling it custom html (say uib-set). so these child directives also again compiling.

So please Help me How can i execute parent directive first then childs next...

Body:
It doesnt look very pretty, but it can easily be solved by using:

<custom-directive dir-type="1" ng-init="myTurn = true">
   <custom-directive dir-type="2" ng-if="myTurn"></custom-directive>
   <custom-directive dir-type="3" ng-if="myTurn"></custom-directive>
   <custom-directive dir-type="4" ng-if="myTurn"></custom-directive>
</custom-directive>

Now the child directives will be triggered/compiled after the parent is compiled and ready.

However, I think this can be solved by using transclusion.

Maybe you can try adding this to your directive:

app.directive('customDirective', function() {
    return {
        //
        transclude: true,
        //
    }
});

By using transclusion, you are 'telling' the parent element: "Hey, you have child elements". So Angular knows that the children belong to the parent, and they will (I think) wait for the parent element to be compiled.

If this transclusion works, please do not use the first solution. It's best to avoid ng-init: it makes debugging harder.

Documentation on transclusion


问:
Date/time in input field
I want to fill the input field with the data in my database but i am getting the following error:

Can't convert date time object to string

Here is the code:

```<code>ll.LeerlingGeboortedatum = (string)(DT.Rows[0]["LeerlingGeboortedatum"]);
txtLeerlingGeboortedatum.Text = ll.LeerlingGeboortedatum;
</code>```

Thanks for your time!

答:
Try using this please:</p>

```<code>ll.LeerlingGeboortedatum = DT.Rows[0]["LeerlingGeboortedatum"].ToString();
txtLeerlingGeboortedatum.Text = ll.LeerlingGeboortedatum;
</code>```

Title: Date/time in input field

Body:
I want to fill the input field with the data in my database but i am getting the following error:

Can't convert date time object to string

Here is the code:

ll.LeerlingGeboortedatum = (string)(DT.Rows[0]["LeerlingGeboortedatum"]);
txtLeerlingGeboortedatum.Text = ll.LeerlingGeboortedatum;

Thanks for your time!

Body:
Try using this please:

ll.LeerlingGeboortedatum = DT.Rows[0]["LeerlingGeboortedatum"].ToString();
txtLeerlingGeboortedatum.Text = ll.LeerlingGeboortedatum;


问:
Any way to achieve fulltext-like search on InnoDB
I have a very simple query:

```<code>SELECT ... WHERE row LIKE '%some%' OR row LIKE '%search%' OR  row LIKE '%string%'
</code>```

to search for some search string, but as you can see, it searches for each string individually and it's also not good for performance.

Is there a way to recreate a fulltext-like search using LIKE on an InnoDB table. Of course, I know I can use something like Sphinx to achieve this but I'm looking for a pure MySQL solution.

答:
Using PHP to construct the query. This is an horrible hack. Once seen, it can't be unseen...

```<code>$words=dict($userQuery);
$numwords = sizeof($words);
$innerquery="";
for($i=0;$i<$numwords;$i++) {
    $words[$i] = mysql_real_escape_string($words[$i]);
    if($i>0) $innerquery .= " AND ";
    $innerquery .= "
        (
            field1 LIKE \"%$words[$i]%\" OR
            field2 LIKE \"%$words[$i]%\" OR
            field3 LIKE \"%$words[$i]%\" OR
            field4 LIKE \"%$words[$i]%\"
        )
    ";
}

SELECT fields FROM table WHERE $innerquery AND whatever;
</code>```

dict is a dictionary function

Body:
I have a very simple query:

SELECT ... WHERE row LIKE '%some%' OR row LIKE '%search%' OR  row LIKE '%string%'

to search for some search string, but as you can see, it searches for each string individually and it's also not good for performance.

Is there a way to recreate a fulltext-like search using LIKE on an InnoDB table. Of course, I know I can use something like Sphinx to achieve this but I'm looking for a pure MySQL solution.

Body:
Using PHP to construct the query. This is an horrible hack. Once seen, it can't be unseen...

$words=dict($userQuery);
$numwords = sizeof($words);
$innerquery="";
for($i=0;$i<$numwords;$i++) {
    $words[$i] = mysql_real_escape_string($words[$i]);
    if($i>0) $innerquery .= " AND ";
    $innerquery .= "
        (
            field1 LIKE \"%$words[$i]%\" OR
            field2 LIKE \"%$words[$i]%\" OR
            field3 LIKE \"%$words[$i]%\" OR
            field4 LIKE \"%$words[$i]%\"
        )
    ";
}

SELECT fields FROM table WHERE $innerquery AND whatever;

dict is a dictionary function


问:
BDD with Specflow in Visual Studio 2017 -featurefile Error CS1029
I am trying out BDD with Specflow in Visual Studio 2017. Previously I had created a new project and added Specflow and Nunit using NuGet Package Manager. From the Solution Explorer, I right click and select Add New Item. From the Add New Item window, I could see SpecFlow feature File and Feature.cs file

But I open the Feature.cs it's showing empty with the message

<#error Generation error: The element  may only appear once in this section.>

Then I try to build the solution then  I'm getting error on Output

Error CS1029

error: 'Generation error: The element  may only appear once in this section.'

The references I can see from Solution Explorer are: SpecRun.SpecFlowPlugin TechTalk.SpecFlow TechTalk.SpecRun NUnit.VisualStudio.TestAdapter

Am I missing something?

Thanks, Mohammed

答:
If you have a scenario outline, but you for get to write the Examples-Keyword, you will get the following error during the build process:

CS1029 #error: 'Generation error: Sequence contains no elements' in Line 1 of MyFeature.feature

It took me some hours in my large created feature file to locate my error. I deleted the temp files, restarted visual studio several times, but it was difficult to figure out why it occurs.

Could you somehow improve the error messages e.g. with a better location, a simple syntax check before or something similar?

As far as I understand, the ScenarioOutline, followed by a will allways need at least an Examples keyword and a table with this varname, before an other Tag like Scenario, etc. is allowed again. I would appreciate to have such markup


答:
As Mentioned in the comment, use the ToString() Method instead of casting it.
Have a look at this answer for more information. Using the paramters in the ToString method you can also specify how the dateString should look like, and which information it holds.

Here are some examples how these paramters work.

```<code>ll.LeerlingGeboortedatum = DT.Rows[0]["LeerlingGeboortedatum"].ToString();
txtLeerlingGeboortedatum.Text = ll.LeerlingGeboortedatum;
</code>```

Quote token from http://www.csharp-examples.net/string-format-datetime/.
  quotet it in case the site gets down in the future.

```<code>// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone
</code>```

Title: Date/time in input field

Body:
As Mentioned in the comment, use the ToString() Method instead of casting it.
Have a look at this answer for more information. Using the paramters in the ToString method you can also specify how the dateString should look like, and which information it holds.

Here are some examples how these paramters work.

ll.LeerlingGeboortedatum = DT.Rows[0]["LeerlingGeboortedatum"].ToString();
txtLeerlingGeboortedatum.Text = ll.LeerlingGeboortedatum;

Quote token from http://www.csharp-examples.net/string-format-datetime/.
  quotet it in case the site gets down in the future.

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone


答:
Use this instead of your code :</p>

```<code>ll.LeerlingGeboortedatum = DT.Rows[0]["LeerlingGeboortedatum"];
txtLeerlingGeboortedatum.Text = ll.LeerlingGeboortedatum.ToString();
</code>```

Title: Date/time in input field

Body:
Use this instead of your code :

ll.LeerlingGeboortedatum = DT.Rows[0]["LeerlingGeboortedatum"];
txtLeerlingGeboortedatum.Text = ll.LeerlingGeboortedatum.ToString();


问:
How to get the search box value in
 tag - HTML,JS
Am new to javascript i foud this one in w3schools.com -  Entering pincode in search box will show in
 tag !! How to do ? any help appreciated. Thanks in advance

HTML :

```<code><form class="form1" role="search" method="get" action="search-pincode.html">
<input class="pincode1" type="number" placeholder="Enter Postcode" id="user-pincode">
<button class="submit" type="submit" formaction="search-pincode.html" onclick="myFunction()">Check</button>
</form>
</code>```

JS SCRIPT :

```<code>    <script>
    function myFunction() {
    var x = document.getElementById("user-pincode").value;
    document.getElementById("user-pincode-show").innerHTML = x;
    }
    </script>
</code>```

OUTPUT : search-pincode.html

```<code>                <h1 class="search-h1-contact">
                Yes, we install CCTV in <p id="user-pincode-show"></p>
                </h1>
</code>```

答:
If you want to avoid redirecting on form submition you can declare an event listener using EventTarget.addEventListener() to handle the click event and call e.preventDefault in the function handler..

Also notice that there is no need to add formaction="search-pincode.html" in the button element because the form has the attribute action="search-pincode.html"

And last thing: With in the h1 element you can better use a span element instead of p.

```<code><h1>Yes, we install CCTV in <span id="user-pincode-show"></span></h1>
</code>```

Code example:

document
  .querySelector('button.submit')
  .addEventListener('click', function (e) {
    e.preventDefault();
    var x = document.querySelector('#user-pincode');
    document.querySelector('#user-pincode-show').innerHTML = x.value;
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="form1" role="search" method="get" action="search-pincode.html">
  <input class="pincode1" type="number" placeholder="Enter Postcode" id="user-pincode">
  <button class="submit" type="submit">Check</button>
</form>

<h1>Yes, we install CCTV in <span id="user-pincode-show"></span></h1></code>```

Title: How to get the search box value in <p> tag - HTML,JS

Body:
Am new to javascript i foud this one in w3schools.com -  Entering pincode in search box will show in
 tag !! How to do ? any help appreciated. Thanks in advance

HTML :

<form class="form1" role="search" method="get" action="search-pincode.html">
<input class="pincode1" type="number" placeholder="Enter Postcode" id="user-pincode">
<button class="submit" type="submit" formaction="search-pincode.html" onclick="myFunction()">Check</button>
</form>

JS SCRIPT :

OUTPUT : search-pincode.html

                Yes, we install CCTV in

Body:
If you want to avoid redirecting on form submition you can declare an event listener using EventTarget.addEventListener() to handle the click event and call e.preventDefault in the function handler..

Also notice that there is no need to add formaction="search-pincode.html" in the button element because the form has the attribute action="search-pincode.html"

And last thing: With in the h1 element you can better use a span element instead of p.

<h1>Yes, we install CCTV in <span id="user-pincode-show"></span></h1>

Code example:

document
  .querySelector('button.submit')
  .addEventListener('click', function (e) {
    e.preventDefault();
    var x = document.querySelector('#user-pincode');
    document.querySelector('#user-pincode-show').innerHTML = x.value;
  });

<form class="form1" role="search" method="get" action="search-pincode.html">
  <input class="pincode1" type="number" placeholder="Enter Postcode" id="user-pincode">
  <button class="submit" type="submit">Check</button>
</form>

<h1>Yes, we install CCTV in <span id="user-pincode-show"></span></h1>


答:
```<code>txtLeerlingGeboortedatum.Text = DT.Rows[0]["LeerlingGeboortedatum"].ToString();
</code>```

Title: Date/time in input field


答:
Why are you creating a StreamWriter and trying to get the output of mysqldump, Why not just tell mysqldump to write to the backup file itself?

```<code>string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > ""{4}"";",
    "root", "", "localhost", "dbfile", tmestr);
</code>```

Title: c# console application backup mysql

Body:
I try to use this code as a console application so that I can back up mydatabase automatics
I am not sure what wrong with it

static void Main(string[] args)
{
    try
    {
        DateTime backupTime = DateTime.Now;
        int year = backupTime.Year;
        int month = backupTime.Month;
        int day = backupTime.Day;
        int hour = backupTime.Hour;
        int minute = backupTime.Minute;
        int second = backupTime.Second;
        int ms = backupTime.Millisecond;

        String tmestr = backupTime.ToString();
        tmestr = "C:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + ".sql";
        StreamWriter file = new StreamWriter(tmestr);
        ProcessStartInfo proc = new ProcessStartInfo();
        string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > {4};", "root", "", "localhost", "dbfile", "backup.sql");
        proc.FileName = "mysqldump";
        proc.RedirectStandardInput = false;
        proc.RedirectStandardOutput = true;
        proc.Arguments = cmd;//"-u root -p smartdb > testdb.sql";
        proc.UseShellExecute = false;
        Process p = Process.Start(proc);
        string res;
        res = p.StandardOutput.ReadToEnd();
        file.WriteLine(res);
        p.WaitForExit();
        file.Close();

    }

    catch (IOException ex)
    {
        MessageBox.Show("Disk full or other IO error , unable to backup!");
    }
}

Body:
Why are you creating a StreamWriter and trying to get the output of mysqldump, Why not just tell mysqldump to write to the backup file itself?

string cmd = string.Format(@"-u{0} -p{1} -h{2} {3} > ""{4}"";",
    "root", "", "localhost", "dbfile", tmestr);


问:
Adding Suppress automatic scm triggering except for named branches in Jenkins Job DSL?
How do I add default Suppress automatic scm triggering except for named branch - development in Job DSL?

I tried docs
https://jenkinsci.github.io/job-dsl-plugin/#path/multibranchPipelineJob . It doesn't say much. Seems like it is not supported.

So I guess my only way is adding custom properties directly to XML via configure block.

What I want:

```<code>    <strategy class="jenkins.branch.NamedExceptionsBranchPropertyStrategy">
      <defaultProperties class="java.util.Arrays$ArrayList">
        <a class="jenkins.branch.BranchProperty-array">
          <jenkins.branch.NoTriggerBranchProperty/>
        </a>
      </defaultProperties>
      <namedExceptions class="java.util.Arrays$ArrayList">
        <a class="jenkins.branch.NamedExceptionsBranchPropertyStrategy$Named-array">
          <jenkins.branch.NamedExceptionsBranchPropertyStrategy_-Named>
            <props class="empty-list"/>
            <name>development</name>
          </jenkins.branch.NamedExceptionsBranchPropertyStrategy_-Named>
        </a>
      </namedExceptions>
    </strategy>
</code>```

What I've tried:

```<code>multibranchPipelineJob(jobName) {
    branchSources {
        git {
            remote(gitRepo)
            credentialsId(credentials)
            includes('*')
            configure {
             it / "sources  class='jenkins.branch.MultiBranchProject$BranchSourceList'" / 'data' / 'jenkins.branch.BranchSource' / "strategy class='jenkins.branch.DefaultBranchPropertyStrategy'" << name('development')
            }
        }
    }
}
</code>```

This is useful, but keeps crashing http://job-dsl.herokuapp.com/
This is not so useful https://github.com/jenkinsci/job-dsl-plugin/blob/master/docs/The-Configure-Block.md

I have no idea what I'm doing and the docs, manuals and tutorials are not helpful at all.

EDIT:

Now I have this. It works, sort of...

I'm able to generate the job, but Jenkins throws an error when I try to resave the job. The output XML is somehow different.

```<code>multibranchPipelineJob(jobName) {

        configure {
            it / sources(class: 'jenkins.branch.MultiBranchProject$BranchSourceList') / 'data' / 'jenkins.branch.BranchSource' << {
                source(class: 'jenkins.plugins.git.GitSCMSource') {
                  id(randomId)
                  remote(gitRepo)
                  credentialsId(credentials)
                }
                strategy(class: "jenkins.branch.NamedExceptionsBranchPropertyStrategy") {
                    defaultProperties(class: "java.util.Arrays\$ArrayList")  {
                        a(class: "jenkins.branch.BranchProperty-array") {
                            'jenkins.branch.NoTriggerBranchProperty'()
                        }
                    }
                    namedExceptions(class: "java.util.Arrays\$ArrayList") {
                     a(class: "jenkins.branch.NamedExceptionsBranchPropertyStrategy\$Named-array") {
                       'jenkins.branch.NamedExceptionsBranchPropertyStrategy_-Named'() {
                           props(class: "empty-list")
                           name('development')
                       }
                   }
                }

                }

            }
            }
</code>```

}

As you might have noticed, it is extremely ugly. Hopefully someone will fix the plugin in the future.

答:
You can achieve this in two ways

Configuring in UI as explained here, which you said you do not want to do.

Using conditional statements in DSL as explained here

Body:
How do I add default Suppress automatic scm triggering except for named branch - development in Job DSL?

I tried docs
https://jenkinsci.github.io/job-dsl-plugin/#path/multibranchPipelineJob . It doesn't say much. Seems like it is not supported.

So I guess my only way is adding custom properties directly to XML via configure block.

What I want:

    <strategy class="jenkins.branch.NamedExceptionsBranchPropertyStrategy">
      <defaultProperties class="java.util.Arrays$ArrayList">

          <jenkins.branch.NoTriggerBranchProperty/>

      </defaultProperties>
      <namedExceptions class="java.util.Arrays$ArrayList">

          <jenkins.branch.NamedExceptionsBranchPropertyStrategy_-Named>
            <props class="empty-list"/>
            <name>development</name>
          </jenkins.branch.NamedExceptionsBranchPropertyStrategy_-Named>

      </namedExceptions>
    </strategy>

What I've tried:

multibranchPipelineJob(jobName) {
    branchSources {
        git {
            remote(gitRepo)
            credentialsId(credentials)
            includes('*')
            configure {
             it / "sources  class='jenkins.branch.MultiBranchProject$BranchSourceList'" / 'data' / 'jenkins.branch.BranchSource' / "strategy class='jenkins.branch.DefaultBranchPropertyStrategy'" << name('development')
            }
        }
    }
}

This is useful, but keeps crashing http://job-dsl.herokuapp.com/
This is not so useful https://github.com/jenkinsci/job-dsl-plugin/blob/master/docs/The-Configure-Block.md

I have no idea what I'm doing and the docs, manuals and tutorials are not helpful at all.

EDIT:

Now I have this. It works, sort of...

I'm able to generate the job, but Jenkins throws an error when I try to resave the job. The output XML is somehow different.

multibranchPipelineJob(jobName) {

        configure {
            it / sources(class: 'jenkins.branch.MultiBranchProject$BranchSourceList') / 'data' / 'jenkins.branch.BranchSource' << {
                source(class: 'jenkins.plugins.git.GitSCMSource') {
                  id(randomId)
                  remote(gitRepo)
                  credentialsId(credentials)
                }
                strategy(class: "jenkins.branch.NamedExceptionsBranchPropertyStrategy") {
                    defaultProperties(class: "java.util.Arrays\$ArrayList")  {
                        a(class: "jenkins.branch.BranchProperty-array") {
                            'jenkins.branch.NoTriggerBranchProperty'()
                        }
                    }
                    namedExceptions(class: "java.util.Arrays\$ArrayList") {
                     a(class: "jenkins.branch.NamedExceptionsBranchPropertyStrategy\$Named-array") {
                       'jenkins.branch.NamedExceptionsBranchPropertyStrategy_-Named'() {
                           props(class: "empty-list")
                           name('development')
                       }
                   }
                }

                }

            }
            }

}

As you might have noticed, it is extremely ugly. Hopefully someone will fix the plugin in the future.


问:
extjs - How to disable pagination on a store
Whenever a store (Ext.data.Store) reads data from the server, it sends paging parameters like &page=1&start=0&limit=25 in a json proxy or [page:1, start:0, limit:25] using a direct proxy.

I'd like to disable paging in the store or proxy configuration.

I found this workaround, but I'm sure there must be a better method.

```<code>proxy: {
    pageParam: undefined,
    startParam: undefined,
    limitParam: undefined,
    ...
}
</code>```

Does anyone know how to disable paging properly ?

答:
To disable pagination, you have to set the values to empty string, not undefined. Like so:

```<code>pageParam: '',
startParam: '',
limitParam: '',
</code>```

This works for me in Ext JS 6.2

Body:
Whenever a store (Ext.data.Store) reads data from the server, it sends paging parameters like &page=1&start=0&limit=25 in a json proxy or [page:1, start:0, limit:25] using a direct proxy.

I'd like to disable paging in the store or proxy configuration.

I found this workaround, but I'm sure there must be a better method.

proxy: {
    pageParam: undefined,
    startParam: undefined,
    limitParam: undefined,
    ...
}

Does anyone know how to disable paging properly ?

Body:
To disable pagination, you have to set the values to empty string, not undefined. Like so:

pageParam: '',
startParam: '',
limitParam: '',

This works for me in Ext JS 6.2