问:
Date Range Intersection Splitting in SQL
I have a SQL Server 2005 database which contains a table called Memberships.

The table schema is:

```<code>PersonID int, Surname nvarchar(30), FirstName nvarchar(30), Description nvarchar(100), StartDate datetime, EndDate datetime</code>```

I'm currently working on a grid feature which shows a break-down of memberships by person. One of the requirements is to split membership rows where there is an intersection of date ranges. The intersection must be bound by the Surname and FirstName, ie splits only occur with membership records of the same Surname and FirstName.

Example table data:

```18  Smith  John  Poker Club  01/01/2009  NULL
18  Smith  John  Library     05/01/2009  18/01/2009
18  Smith  John  Gym         10/01/2009  28/01/2009
26  Adams  Jane  Pilates     03/01/2009  16/02/2009```

Expected result set:

```18  Smith  John  Poker Club                  01/01/2009  04/01/2009
18  Smith  John  Poker Club / Library        05/01/2009  09/01/2009
18  Smith  John  Poker Club / Library / Gym  10/01/2009  18/01/2009
18  Smith  John  Poker Club / Gym            19/01/2009  28/01/2009
18  Smith  John  Poker Club                  29/01/2009  NULL
26  Adams  Jane  Pilates                     03/01/2009  16/02/2009```

Does anyone have any idea how I could write a stored procedure that will return a result set which has the break-down described above.

答:
[Only many, many years later.]

I created a stored procedure that will align and break segments by a partition within a single table, and then you can use those aligned breaks to pivot the description into a ragged column using a subquery and XML PATH.

See if the below help:

Documentation: https://github.com/Quebe/SQL-Algorithms/blob/master/Temporal/Date%20Segment%20Manipulation/DateSegments_AlignWithinTable.md

Stored Procedure: https://github.com/Quebe/SQL-Algorithms/blob/master/Temporal/Date%20Segment%20Manipulation/DateSegments_AlignWithinTable.sql

For example, your call might look like:

```<code>EXEC dbo.DateSegments_AlignWithinTable
@tableName = 'tableName',
@keyFieldList = 'PersonID',
@nonKeyFieldList = 'Description',
@effectivveDateFieldName = 'StartDate',
@terminationDateFieldName = 'EndDate'
</code>```

You will want to capture the result (which is a table) into another table or temporary table (assuming it is called "AlignedDataTable" in below example). Then, you can pivot using a subquery.

```<code>SELECT
    PersonID, StartDate, EndDate,

    SUBSTRING ((SELECT ',' + [Description] FROM AlignedDataTable AS innerTable
        WHERE
            innerTable.PersonID = AlignedDataTable.PersonID
            AND (innerTable.StartDate = AlignedDataTable.StartDate)
            AND (innerTable.EndDate = AlignedDataTable.EndDate)
        ORDER BY id
        FOR XML PATH ('')), 2, 999999999999999) AS IdList

 FROM AlignedDataTable
 GROUP BY PersonID, StartDate, EndDate
 ORDER BY PersonID, StartDate
</code>```

Body:
I have a SQL Server 2005 database which contains a table called Memberships.

The table schema is:

PersonID int, Surname nvarchar(30), FirstName nvarchar(30), Description nvarchar(100), StartDate datetime, EndDate datetime

I'm currently working on a grid feature which shows a break-down of memberships by person. One of the requirements is to split membership rows where there is an intersection of date ranges. The intersection must be bound by the Surname and FirstName, ie splits only occur with membership records of the same Surname and FirstName.

Example table data:

18  Smith  John  Poker Club  01/01/2009  NULL
18  Smith  John  Library     05/01/2009  18/01/2009
18  Smith  John  Gym         10/01/2009  28/01/2009
26  Adams  Jane  Pilates     03/01/2009  16/02/2009

Expected result set:

18  Smith  John  Poker Club                  01/01/2009  04/01/2009
18  Smith  John  Poker Club / Library        05/01/2009  09/01/2009
18  Smith  John  Poker Club / Library / Gym  10/01/2009  18/01/2009
18  Smith  John  Poker Club / Gym            19/01/2009  28/01/2009
18  Smith  John  Poker Club                  29/01/2009  NULL
26  Adams  Jane  Pilates                     03/01/2009  16/02/2009

Does anyone have any idea how I could write a stored procedure that will return a result set which has the break-down described above.

Body:
[Only many, many years later.]

I created a stored procedure that will align and break segments by a partition within a single table, and then you can use those aligned breaks to pivot the description into a ragged column using a subquery and XML PATH.

See if the below help:

Documentation: https://github.com/Quebe/SQL-Algorithms/blob/master/Temporal/Date%20Segment%20Manipulation/DateSegments_AlignWithinTable.md

Stored Procedure: https://github.com/Quebe/SQL-Algorithms/blob/master/Temporal/Date%20Segment%20Manipulation/DateSegments_AlignWithinTable.sql

For example, your call might look like:

EXEC dbo.DateSegments_AlignWithinTable
@tableName = 'tableName',
@keyFieldList = 'PersonID',
@nonKeyFieldList = 'Description',
@effectivveDateFieldName = 'StartDate',
@terminationDateFieldName = 'EndDate'

You will want to capture the result (which is a table) into another table or temporary table (assuming it is called "AlignedDataTable" in below example). Then, you can pivot using a subquery.

SELECT
    PersonID, StartDate, EndDate,

    SUBSTRING ((SELECT ',' + [Description] FROM AlignedDataTable AS innerTable
        WHERE
            innerTable.PersonID = AlignedDataTable.PersonID
            AND (innerTable.StartDate = AlignedDataTable.StartDate)
            AND (innerTable.EndDate = AlignedDataTable.EndDate)
        ORDER BY id
        FOR XML PATH ('')), 2, 999999999999999) AS IdList

 FROM AlignedDataTable
 GROUP BY PersonID, StartDate, EndDate
 ORDER BY PersonID, StartDate


来源: stackexchange

问:
Read comma separated string in Sql server in loop
I have nvarchar data like this:

'20030,20031,20033,20034,20065,20045,20044'

I want to read all this by spliting into array or read one by one in spliting process and do further process.

I have tried this good article but not able to do it.

答:
Try this article uses function to read the comma separated values and return the table

```<code>CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (Items nvarchar(4000))
AS
BEGIN
DECLARE @INDEX INT
DECLARE @SLICE nvarchar(4000)
-- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
--     ERO FIRST TIME IN LOOP
SELECT @INDEX = 1
WHILE @INDEX !=0
BEGIN
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF @INDEX !=0
SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
ELSE
SELECT @SLICE = @STRING
-- PUT THE ITEM INTO THE RESULTS SET
INSERT INTO @Results(Items) VALUES(@SLICE)
-- CHOP THE ITEM REMOVED OFF THE MAIN STRING
SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
-- BREAK OUT IF WE ARE DONE
IF LEN(@STRING) = 0 BREAK
END
RETURN
END
</code>```

just call the function from stored procedure or just call function like below:

```<code>SELECT items FROM [dbo].[Split] ('20030,20031,20033,20034,20065,20045,20044', ',')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try this article uses function to read the comma separated values and return the table

CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (Items nvarchar(4000))
AS
BEGIN
DECLARE @INDEX INT
DECLARE @SLICE nvarchar(4000)
-- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
--     ERO FIRST TIME IN LOOP
SELECT @INDEX = 1
WHILE @INDEX !=0
BEGIN
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF @INDEX !=0
SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
ELSE
SELECT @SLICE = @STRING
-- PUT THE ITEM INTO THE RESULTS SET
INSERT INTO @Results(Items) VALUES(@SLICE)
-- CHOP THE ITEM REMOVED OFF THE MAIN STRING
SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
-- BREAK OUT IF WE ARE DONE
IF LEN(@STRING) = 0 BREAK
END
RETURN
END

just call the function from stored procedure or just call function like below:

SELECT items FROM [dbo].[Split] ('20030,20031,20033,20034,20065,20045,20044', ',')


问:
CSS Block Ignored/Overwritten by Browser
So I have two style blocks:

```<code>._bordercols {

border-right-style: solid;
border-right: 1px solid #DCDCDC;
height: 35px !important;
border-bottom-style: solid;
border-bottom: 1px solid #DCDCDC;
color: #3f8bbf !important;
}

._display_title {

text-overflow: hidden !important;
white-space: nowrap !important;
overflow: hidden !important;

}
</code>```

Now I call them the following way:

```<code><?php
printf(" <div class='row entrystyle ".$css_class."'>
                                    <div class='col-sm-1 _bordercols' style='color: #397dad;'>%s</div>
                                    <div class='col-sm-1 _bordercols' style='color: #397dad;'>%s</div>
                                    <div class='col-sm-2 _bordercols'><a href='./index.php'><center>%s</a></div>
                                    <div class='col-sm-6 _bordercols _display_title'>%s</div>
                                    <div class='col-sm-2 _bordercols'><center><b>%s</b></div>
                                </div>", $row['blah1'], $row['blah2'], $row['blah3'], $row['blah4'], $row['blah5']);

                    }
?>
</code>```

Nothing happens to the div I want to format when I do it this way. If I add this style as an inline style attribute to the div, then it works like I need it to. In the Chrome inspector it doesn't even list _display_title as a rendered class but it does list _bordercols.

答:
You using this property wrong

text-overflow: hidden !important;

It should be like this

clip  Default value. Clips the text

ellipsis  Render an ellipsis ("...") to represent clipped text

string    Render the given string to represent clipped text

initial   Sets this property to its default value.

inherit   Inherits this property from its parent element.

So you can use text-overflow: clip or ellipsis or string or initial or inherit.

Hope it will helps you.

Body:
So I have two style blocks:

._bordercols {

border-right-style: solid;
border-right: 1px solid #DCDCDC;
height: 35px !important;
border-bottom-style: solid;
border-bottom: 1px solid #DCDCDC;
color: #3f8bbf !important;
}

._display_title {

text-overflow: hidden !important;
white-space: nowrap !important;
overflow: hidden !important;

}

Now I call them the following way:

<?php
printf("

%s

%s

%s

%s

%s

", $row['blah1'], $row['blah2'], $row['blah3'], $row['blah4'], $row['blah5']);

                    }
?>

Nothing happens to the div I want to format when I do it this way. If I add this style as an inline style attribute to the div, then it works like I need it to. In the Chrome inspector it doesn't even list _display_title as a rendered class but it does list _bordercols.


问:
use string as function name - golang
Is theere a way to use a string as a function name and call it?

I have a map of strings to function names

stuff := map[string]string{'keyword','function'}

and when the keyword is used, i want to call function with 2 arguments

stuff['keyword'](arg1,arg2)

But it gives me this error:

```<code>cannot call non-function key (type string)
</code>```

Is there a way to keep my string to string map and still achieve this?

答:
The map you're using isn't syntactically valid. You probably want something like this:

```<code>stuff := map[string]func(string, string)
</code>```

You would then be able to use your string key to pull out a function from the map and call it:

```<code>stuff["keyword"]("foo", "goo")
</code>```

GoPlay:

https://play.golang.org/p/DNALJOmoiZ

Title: use string as function name - golang

Body:
Is theere a way to use a string as a function name and call it?

I have a map of strings to function names

stuff := map[string]string{'keyword','function'}

and when the keyword is used, i want to call function with 2 arguments

stuff['keyword'](arg1,arg2)

But it gives me this error:

cannot call non-function key (type string)

Is there a way to keep my string to string map and still achieve this?

Body:
The map you're using isn't syntactically valid. You probably want something like this:

stuff := map[string]func(string, string)

You would then be able to use your string key to pull out a function from the map and call it:

stuff["keyword"]("foo", "goo")

GoPlay:

https://play.golang.org/p/DNALJOmoiZ


问:
What code for a table with colors instead of values
I have the following table on python:

What I want to do is see the table in a nicer looking way, with the cells going from red to blue depending on their value, a bit like this:

Does anyone know how to do that?

I've done this so far but don't know what to put in the vars options to make it work, nor how to make the color dependant of the values.

```<code>import numpy as np

from bokeh.plotting import figure, show, output_file #outils graphiques

import pandas as pd
df = pd.read_excel("C:/Users/a873469/Documents/Bundles/Bundles mini.xlsx")
pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 200)
print df.iloc[:20, :20]

options=

colormap = ["#2166ac", "#67a9cf", "#d1e5f0", "#fddbc7", "#ef8a62", "#b2182b"]
xname = []
yname = []
color = []

color.append(colormap)

p = figure(title="Bundles", #table title
           x_axis_location="above", # x axis on top, hover tool
           x_range=list(reversed(options)), y_range=options) # definition of x et y

p.plot_width = 800 #table size
p.plot_height = 800
p.grid.grid_line_color = None # uncolored grid
p.axis.axis_line_color = None # uncolored axis
p.axis.major_tick_line_color = None #no tick lines on axis
p.axis.major_label_text_font_size = "5pt" #label police
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = np.pi/3 #label orientation

p.rect(0.9, 0.9, #rectangles
       color='colors', line_color=None) # rectangle color

output_file("bundles.html", title="bundles.py example") # fichier d'affichage

show(p) # show the plot'
</code>```

答:
Edit: Kacper Wolkowski's hint on Pandas capabilities is certainly the better way of proceeding here. I'll still leave the answer.

Not sure what you are doing this for, but a first quick solution (approaching the desired example) would be to plot the matrix of values using the imshow() function of matplotlib and add the values in the squares.

```<code>import numpy as np
import matplotlib.pyplot as plt

# generate some example data
matrix = np.random.uniform(0,1,(5,5))

# plot the matrix as an image with an appropriate colormap
plt.imshow(matrix.T, aspect='auto', cmap="bwr")

# add the values
for (i, j), value in np.ndenumerate(matrix):
    plt.text(i, j, "%.3f"%value, va='center', ha='center')

plt.axis('off')
plt.show()
</code>```

Body:
I have the following table on python:

What I want to do is see the table in a nicer looking way, with the cells going from red to blue depending on their value, a bit like this:

Does anyone know how to do that?

I've done this so far but don't know what to put in the vars options to make it work, nor how to make the color dependant of the values.

import numpy as np

from bokeh.plotting import figure, show, output_file #outils graphiques

import pandas as pd
df = pd.read_excel("C:/Users/a873469/Documents/Bundles/Bundles mini.xlsx")
pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 200)
print df.iloc[:20, :20]

options=

colormap = ["#2166ac", "#67a9cf", "#d1e5f0", "#fddbc7", "#ef8a62", "#b2182b"]
xname = []
yname = []
color = []

color.append(colormap)

p = figure(title="Bundles", #table title
           x_axis_location="above", # x axis on top, hover tool
           x_range=list(reversed(options)), y_range=options) # definition of x et y

p.plot_width = 800 #table size
p.plot_height = 800
p.grid.grid_line_color = None # uncolored grid
p.axis.axis_line_color = None # uncolored axis
p.axis.major_tick_line_color = None #no tick lines on axis
p.axis.major_label_text_font_size = "5pt" #label police
p.axis.major_label_standoff = 0
p.xaxis.major_label_orientation = np.pi/3 #label orientation

p.rect(0.9, 0.9, #rectangles
       color='colors', line_color=None) # rectangle color

output_file("bundles.html", title="bundles.py example") # fichier d'affichage

show(p) # show the plot'

Body:
Edit: Kacper Wolkowski's hint on Pandas capabilities is certainly the better way of proceeding here. I'll still leave the answer.

Not sure what you are doing this for, but a first quick solution (approaching the desired example) would be to plot the matrix of values using the imshow() function of matplotlib and add the values in the squares.

import numpy as np
import matplotlib.pyplot as plt

# generate some example data
matrix = np.random.uniform(0,1,(5,5))

# plot the matrix as an image with an appropriate colormap
plt.imshow(matrix.T, aspect='auto', cmap="bwr")

# add the values
for (i, j), value in np.ndenumerate(matrix):
    plt.text(i, j, "%.3f"%value, va='center', ha='center')

plt.axis('off')
plt.show()


问:
Using own source code on slx.cloud?
I created an account on slx.cloud and tested the available sample applications. Is there a place where I can upload my own source code though?</p>

答:
First of all, thanks for trying it out! I am the product manager of SLX.cloud (a free online version of our multicore optimization tools), so if you have any further questions you can ask me directly.

SLX.cloud currently offers two ways to import your own source code:

1. Importing via version control (recommended)

SLX.cloud allows you to import your code via git, github and SVN. You can start by creating a workspace using the usermake or usercmake template projects and after starting the workspace you can go to Workspace -> Import Project within the IDE.

It is also possible to import private repositories via Github. For that just go to Preferences -> VCS within the IDE and click the Github button in the bottom right corner to set up the SSH key for Github.

2. Importing via ZIP files

You can upload your source code as a ZIP file into the workspace, by going to Workspace -> Import ZIP

NOTE: The files will persist within the /projects folder if you stop the workspace, but not outside of it. Make sure to download your changes via Workspace -> Export ZIP. All files outside the /projects folder are updated on each start as we are loading the latest docker image for our tooling on startup.

NOTE: If you plan on sharing your workspace with coworkers and friends via the factory functionality, you will need to use version control to import the source code into the factory.

3. Tutorial from importing to analyzing your code

If you are interested in more details on analyzing your own code, I have created a tutorial on our documentation which includes importing your own code, but goes much further than that.

Title: Using own source code on slx.cloud?


问:
Blender creates screenshot using python script but not when running in background
Am I crazy or is there some bug with this feature (using python script with blender running in background) ?

1/ Copy / paste the following code (from screenshot.py) inside Blender (switch to Scripting view) and it will take a screenshot but ...

2/ Call this script from command line : (so you can automatize screenshots while you're modifying the scene with your script(s) ... for your blog, a tutorial, etc.)

```<code>blender --background --python screenshot.py
</code>```

And it will crash without giving informations about what is "incorrect" in the context

screenshot.py :

```<code>import os, sys

#FIXME: Blender creates screenshot using python but not when running in background
#
# Same result from Ubuntu stock version (2.76) and from ppa (2.78)
#
# Within Blender : unable to fix this last warning but screenshot is generated !
#
#Traceback (most recent call last):
#  File "/usr/share/blender/2.78/scripts/startup/bl_ui/space_text.py", line 32, in draw
#    text = st.text
#AttributeError: 'SpaceView3D' object has no attribute 'text'
#
# From command line (crash) : blender --background --python screenshot.py
# Unable to determine what's wrong in the context
#
#Traceback (most recent call last):
#(...)
#File "/usr/share/blender/2.78/scripts/modules/bpy/ops.py", line 187, in __call__
#    ret = op_call(self.idname_py(), C_dict, kw, C_exec, C_undo)
#RuntimeError: Operator bpy.ops.screen.screenshot.poll() failed, context is incorrect

def screenshot(P_filename, P_path = None):
  import bpy

  L_saveAs = P_filename
  L_saveAs = os.path.join(P_path, L_saveAs) if P_path else os.path.join("/tmp", L_saveAs)
  print("Scene saved in " + L_saveAs)

  #XXX: switching to 3D full view = maximize scene in main window
  #bpy.context.window.screen = bpy.data.screens['3D View Full']
  for window in bpy.context.window_manager.windows:
    screen = window.screen
    print("Window : " + str(window.width) + "x" + str(window.height) + ":" + str(window.x) + "," + str(window.y))
    print("Screen : " + str(screen.name) + ", Scene : " + str(screen.scene.name))
    #for area in bpy.context.screen.areas:
    for area in screen.areas:
      print("Area   : " + str(area.type))
      if area.type == 'VIEW_3D':
        for space in area.spaces:
          print("Space  : " + str(space.type))
          if space.type == 'VIEW_3D':
            #space.viewport_shade = 'RENDERED'
            for region in area.regions:
              print("Region  : " + str(region.type))
              if region.type == 'WINDOW':
                L_altBpyCtx = {                        # defining alternative context (allowing modifications without altering real one)
                  'area'      : area                   # our 3D View (first found)
                , 'blend_data': bpy.context.blend_data # just to suppress PyContext warning, doesn't seem to have any effect
                #, 'edit_text' : bpy.context.edit_text  # just to suppress PyContext warning, doesn't seem to have any effect
                , 'region'    : None                   # just to suppress PyContext warning, doesn't seem to have any effect
                #, 'scene'     : bpy.context.scene
                , 'scene'     : screen.scene
                , 'space'     : space
                , 'screen'    : window.screen
                #, 'window'    : bpy.context.window     # current window, could also copy context
                , 'window'    : window                 # current window, could also copy context
                }
                bpy.ops.screen.screenshot(L_altBpyCtx, filepath = L_saveAs, full = False)
                break #XXX: limit to the window of the 3D View
            break #XXX: limit to the corresponding space (3D View)
        break #XXX: limit to the first 3D View (area)

screenshot("screenshot.png", ".")
</code>```

3/ By the way, call it without the "--background" argument and it will generate an empty screenshot (size of your window, full of gray). In the meantime, uncomment

```<code>#bpy.context.window.screen = bpy.data.screens['3D View Full']
</code>```

and/or

```<code>#space.viewport_shade = 'RENDERED'
</code>```

And you'll see your Blender interface being affected (switching layout of your views from 'Default' to '3D Full View' and/or your viewport shading from 'Solid', by default, to 'Rendered') ... so the script is actually interpreted but it does not generate the screenshot !

No matter what, the problem seems coming from calling Blender with "--python somescript.py" directly from the command line

I'm probably missing something ?! Thanks for your help

答:
Got the answer from a Blender guy (thanks sergey). Bottom line : it's a limitation since all the scripts passed via command line argument are executed at command line processing time, prior to any OpenGL draw is done !

The warning is caused by script trying to trick the system and
  override the context, that context is likely in inconsistent state.
  When running screenshot from the interface you don't need to override
  any of the contexts.

All the scripts passed via command line argument are executed at
  command line processing time, prior to any OpenGL draw is done. The
  screenshot operator itself is just reading OpenGL buffer,m without
  doing any actual drawing (it can't draw anything since that'd be
  unsafe).

When running blender in background mode, there is no window created,
  which also means there is no OpenGL context. You can;t use screenshot
  in such configuration.

So thanks for the report, but it's just limitation which can not be
  easily bypassed.

Precision : (since the provided code do not show all the attempts made trying to "trick" Blender)

Sadly, if you are also / still interested in such feature, you'll have to think outside (Blender) box ! Don't waste your time trying to "trick" Blender, like delaying script execution, playing with application handlers, faking script import in a Text editor, etc. ... I've done it for you : it doesn't work, probably for a very similar reason.

Body:
Am I crazy or is there some bug with this feature (using python script with blender running in background) ?

1/ Copy / paste the following code (from screenshot.py) inside Blender (switch to Scripting view) and it will take a screenshot but ...

2/ Call this script from command line : (so you can automatize screenshots while you're modifying the scene with your script(s) ... for your blog, a tutorial, etc.)

blender --background --python screenshot.py

And it will crash without giving informations about what is "incorrect" in the context

screenshot.py :

import os, sys

#FIXME: Blender creates screenshot using python but not when running in background
#
# Same result from Ubuntu stock version (2.76) and from ppa (2.78)
#
# Within Blender : unable to fix this last warning but screenshot is generated !
#
#Traceback (most recent call last):
#  File "/usr/share/blender/2.78/scripts/startup/bl_ui/space_text.py", line 32, in draw
#    text = st.text
#AttributeError: 'SpaceView3D' object has no attribute 'text'
#
# From command line (crash) : blender --background --python screenshot.py
# Unable to determine what's wrong in the context
#
#Traceback (most recent call last):
#(...)
#File "/usr/share/blender/2.78/scripts/modules/bpy/ops.py", line 187, in __call__
#    ret = op_call(self.idname_py(), C_dict, kw, C_exec, C_undo)
#RuntimeError: Operator bpy.ops.screen.screenshot.poll() failed, context is incorrect

def screenshot(P_filename, P_path = None):
  import bpy

  L_saveAs = P_filename
  L_saveAs = os.path.join(P_path, L_saveAs) if P_path else os.path.join("/tmp", L_saveAs)
  print("Scene saved in " + L_saveAs)

  #XXX: switching to 3D full view = maximize scene in main window
  #bpy.context.window.screen = bpy.data.screens['3D View Full']
  for window in bpy.context.window_manager.windows:
    screen = window.screen
    print("Window : " + str(window.width) + "x" + str(window.height) + ":" + str(window.x) + "," + str(window.y))
    print("Screen : " + str(screen.name) + ", Scene : " + str(screen.scene.name))
    #for area in bpy.context.screen.areas:
    for area in screen.areas:
      print("Area   : " + str(area.type))
      if area.type == 'VIEW_3D':
        for space in area.spaces:
          print("Space  : " + str(space.type))
          if space.type == 'VIEW_3D':
            #space.viewport_shade = 'RENDERED'
            for region in area.regions:
              print("Region  : " + str(region.type))
              if region.type == 'WINDOW':
                L_altBpyCtx = {                        # defining alternative context (allowing modifications without altering real one)
                  'area'      : area                   # our 3D View (first found)
                , 'blend_data': bpy.context.blend_data # just to suppress PyContext warning, doesn't seem to have any effect
                #, 'edit_text' : bpy.context.edit_text  # just to suppress PyContext warning, doesn't seem to have any effect
                , 'region'    : None                   # just to suppress PyContext warning, doesn't seem to have any effect
                #, 'scene'     : bpy.context.scene
                , 'scene'     : screen.scene
                , 'space'     : space
                , 'screen'    : window.screen
                #, 'window'    : bpy.context.window     # current window, could also copy context
                , 'window'    : window                 # current window, could also copy context
                }
                bpy.ops.screen.screenshot(L_altBpyCtx, filepath = L_saveAs, full = False)
                break #XXX: limit to the window of the 3D View
            break #XXX: limit to the corresponding space (3D View)
        break #XXX: limit to the first 3D View (area)

screenshot("screenshot.png", ".")

3/ By the way, call it without the "--background" argument and it will generate an empty screenshot (size of your window, full of gray). In the meantime, uncomment

#bpy.context.window.screen = bpy.data.screens['3D View Full']

and/or

#space.viewport_shade = 'RENDERED'

And you'll see your Blender interface being affected (switching layout of your views from 'Default' to '3D Full View' and/or your viewport shading from 'Solid', by default, to 'Rendered') ... so the script is actually interpreted but it does not generate the screenshot !

No matter what, the problem seems coming from calling Blender with "--python somescript.py" directly from the command line

I'm probably missing something ?! Thanks for your help


问:
In Delphi, Is there a way to adjust the line spacing of a TMemo?
I'm working with a TMemo component to display some text in a limited space. Currently it's using a truetype font which doesn't ship with windows and is installed by the app when it runs.

On my PC (Running Windows XP), the spacing between each line of text seems to be about eight pixels. On a different PC running Windows 7, the line spacing seems to be about 14 pixels, which is pushing the bottom row of text out of visibility on the memo.

So, My question is really this:

Is this caused by the different versions of Windows? It's all I could think that was different.

Is there some way I can adjust this value so it would be consistent across all instances of the application, wherever it was running?

Alternatatively, is there a different component I could use which might let me tweak this value?

答:
TMemo is a descendent of Windows Common controls and it's behavior depends on current Windows configuration so it is natural to get different results with it.

If you just want to display some information it's better to use components which let you set texts positions and their style precisely like TRichView. This component is not free but it has it's own text rendering engine and let you style texts with CSS like selectors which look the same in different versions of windows.

ContentLicense: CC BY-SA 2.5


问:
How do you write an error message when an Ajax call is not successful in JavaScript?
I would like to display an error message if my Ajax call is unsuccessful. Simple enough but I cannot modify the Ajax function. I created an onClick listener that does a few things when my AJAX call is successful. I would just like to do something when the call is unsuccessful.

So If I decide to add:

```<code> if (xhr.status !== 200) {
   //Error Message here
   }
</code>```

Where would it be placed?

JSFiddle Example Here

My html is:

```<code><div id="test-form">
      <h2>Add a User:</h2>
      <label for="Username:">
       <input id="username" type="text" name="username" placeholder="Type username here">
     </label>

      <label for="Email:">
      <span id='result'></span>
      <input id="email" type="email" name="email" placeholder="email">
      </label>
      <button id="myButton">add user</button>
      <h2 class="clear">Users:</h2>
      <ul id="users"></ul>
    </div>
</code>```

My code is:

```<code> var el = document.getElementById("myButton");
    el.onclick = function() {
      addUser(username, email, onSuccess);
    }

    function onSuccess(result){
      var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

      var username = document.getElementById("username").value;
      var email = document.getElementById("email");
        var message = document.getElementById("result").classList;

      document.getElementById("users").innerHTML+= '<li>' + username +'</li>';

    if (!filter.test(email.value)) {
        document.getElementById('result').innerHTML+='Not a valid email';
        email.focus;
         return false;
     } else {

        message.add("hide");
      }

    }

    // Do not modify this function. Add user service wrapper.
    function addUser(username, email, callback) {
        var xhr = new XMLHttpRequest();
        var response;
        var success = (!!Math.round(Math.random()));

        if (!success){
            response = JSON.stringify({
                success: success,
                error: "Oups, something went wrong!"
            });
        } else {
            response = JSON.stringify({
                success: success,
                user: {
                    username: username,
                    email: email
                }
            });
        }

        xhr.open("POST", "/echo/json/");
        xhr.onload = function () {
                if (xhr.status === 200) {
                    callback(JSON.parse(xhr.responseText));
            }
        }
        xhr.send("json=" + response);
    };
</code>```

答:
You can check xhr status and when it's not 200 then it was not succeed,
Then You can Throw responseText.</p>

```<code>if (xhr.status !== 200)
    throw(xhr.responseText);
</code>```

Body:
I would like to display an error message if my Ajax call is unsuccessful. Simple enough but I cannot modify the Ajax function. I created an onClick listener that does a few things when my AJAX call is successful. I would just like to do something when the call is unsuccessful.

So If I decide to add:

 if (xhr.status !== 200) {
   //Error Message here
   }

Where would it be placed?

JSFiddle Example Here

My html is:

Add a User:

       <input id="username" type="text" name="username" placeholder="Type username here">

      <input id="email" type="email" name="email" placeholder="email">

      <button id="myButton">add user</button>

Users:

My code is:

 var el = document.getElementById("myButton");
    el.onclick = function() {
      addUser(username, email, onSuccess);
    }

    function onSuccess(result){
      var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

      var username = document.getElementById("username").value;
      var email = document.getElementById("email");
        var message = document.getElementById("result").classList;

      document.getElementById("users").innerHTML+= '
' + username +'
';

    if (!filter.test(email.value)) {
        document.getElementById('result').innerHTML+='Not a valid email';
        email.focus;
         return false;
     } else {

        message.add("hide");
      }

    }

    // Do not modify this function. Add user service wrapper.
    function addUser(username, email, callback) {
        var xhr = new XMLHttpRequest();
        var response;
        var success = (!!Math.round(Math.random()));

        if (!success){
            response = JSON.stringify({
                success: success,
                error: "Oups, something went wrong!"
            });
        } else {
            response = JSON.stringify({
                success: success,
                user: {
                    username: username,
                    email: email
                }
            });
        }

        xhr.open("POST", "/echo/json/");
        xhr.onload = function () {
                if (xhr.status === 200) {
                    callback(JSON.parse(xhr.responseText));
            }
        }
        xhr.send("json=" + response);
    };

Body:
You can check xhr status and when it's not 200 then it was not succeed,
Then You can Throw responseText.

if (xhr.status !== 200)
    throw(xhr.responseText);


问:
Java SAM interface created from Kotlin gives ClassCastException
I have a java method:

```<code>addHandler(HttpServiceHandler handler)
</code>```

HttpServiceHandler is

```<code>interface HttpServiceHandler extends Consumer<HttpHandlerContext>
</code>```

The point is to avoid Consumer<HttpHandlerContext> copy-paste across the project, so it's kind of a type alias.

In Java code, this works all right:

```<code>addHandler({ context -> context.blah(); })
</code>```

Now, in Kotlin, I have this method that generates handlers:

```<code>private companion object {
    fun newHandler(notimportant: Long): HttpServiceHandler {
        return HttpServiceHandler { context -> context.blah() }
    }
}
</code>```

HttpServiceHandler {} is important, it doesn't compile if I don't specify HttpServiceHandler for the lambda.

And this compiles:

```<code>addHandler(newHandler(1L))
</code>```

But at runtime, throws:

```<code>java.lang.ClassCastException: blah.BlahTest$Companion$newHandler$1 cannot be cast to kotlin.jvm.functions.Function1

at blah.BlahTest.test(BlahTest.kt:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

And I can't figure out why. Help please?

Update: The class cast exception is gone if I write it like this:

```<code>addHandler(
    object : HttpServiceHandler {
        override fun accept(c: HttpHandlerContext) {
            c.complete()
        }
    }
)
</code>```

But still throws the exception when written like this:

```<code>fun newHandler(blah: Long): HttpServiceHandler {
    return object : HttpServiceHandler {
        override fun accept(c: HttpHandlerContext) {
            c.complete()
        }
    }
}

addHandler(newHandler(1L))
</code>```

And I have no idea why.

Update2: Test code at https://github.com/wilem82/testcases/tree/master/kotlinsam1 . Does not reproduce the problem, sadly.

答:
the error has already said exactly:

java.lang.ClassCastException: blah.BlahTest$Companion$newHandler$1 cannot be cast to kotlin.jvm.functions.Function1

you try to cast a Consumer<HttpHandlerContext> to  a Function1 in addHandler method or somewhere, for example:

```<code>fun addHandler(handler: Consumer<HttpHandlerContext>) {
    val it: Function1<*, *> = handler as Function1<*, *>
    //                        ^
    // ClassCastException was thrown since it is not a Function1
}
</code>```

you should using method reference expression in java / function reference expression in kotlin to convert a SAM interface to  another SAM interface, for example:

```<code>fun addHandler(handler: Consumer<HttpHandlerContext>) {
    val it: Function1<HttpHandlerContext, Unit> = handler::accept
    //     using function reference expression here     ---^
   //...
}
</code>```

IF you call java method addHandler in kotlin, you needn't to create such a bridge method newHandler, you can just call it with lambda in kotlin, for example:

```<code>addHandler{context->
    context.blah()
    // additional works ...
}
</code>```

Body:
I have a java method:

addHandler(HttpServiceHandler handler)

HttpServiceHandler is

interface HttpServiceHandler extends Consumer<HttpHandlerContext>

The point is to avoid Consumer<HttpHandlerContext> copy-paste across the project, so it's kind of a type alias.

In Java code, this works all right:

addHandler({ context -> context.blah(); })

Now, in Kotlin, I have this method that generates handlers:

private companion object {
    fun newHandler(notimportant: Long): HttpServiceHandler {
        return HttpServiceHandler { context -> context.blah() }
    }
}

HttpServiceHandler {} is important, it doesn't compile if I don't specify HttpServiceHandler for the lambda.

And this compiles:

addHandler(newHandler(1L))

But at runtime, throws:

java.lang.ClassCastException: blah.BlahTest$Companion$newHandler$1 cannot be cast to kotlin.jvm.functions.Function1

at blah.BlahTest.test(BlahTest.kt:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

And I can't figure out why. Help please?

Update: The class cast exception is gone if I write it like this:

addHandler(
    object : HttpServiceHandler {
        override fun accept(c: HttpHandlerContext) {
            c.complete()
        }
    }
)

But still throws the exception when written like this:

fun newHandler(blah: Long): HttpServiceHandler {
    return object : HttpServiceHandler {
        override fun accept(c: HttpHandlerContext) {
            c.complete()
        }
    }
}

addHandler(newHandler(1L))

And I have no idea why.

Update2: Test code at https://github.com/wilem82/testcases/tree/master/kotlinsam1 . Does not reproduce the problem, sadly.

Body:
the error has already said exactly:

java.lang.ClassCastException: blah.BlahTest$Companion$newHandler$1 cannot be cast to kotlin.jvm.functions.Function1

you try to cast a Consumer<HttpHandlerContext> to  a Function1 in addHandler method or somewhere, for example:

fun addHandler(handler: Consumer<HttpHandlerContext>) {
    val it: Function1<*, *> = handler as Function1<*, *>
    //                        ^
    // ClassCastException was thrown since it is not a Function1
}

you should using method reference expression in java / function reference expression in kotlin to convert a SAM interface to  another SAM interface, for example:

fun addHandler(handler: Consumer<HttpHandlerContext>) {
    val it: Function1<HttpHandlerContext, Unit> = handler::accept
    //     using function reference expression here     ---^
   //...
}

IF you call java method addHandler in kotlin, you needn't to create such a bridge method newHandler, you can just call it with lambda in kotlin, for example:

addHandler{context->
    context.blah()
    // additional works ...
}


问:
I am learning selenium framework while creating framework with testing and pagefactory I am getting followed error
My files and error which iI am getting are as follows:

url_title.properties

```<code>username=rakeshm@techved.com
password=123456
chrome_driver_path=D://rakesh//software//selenium browser//chrome 2.28//chromedriver.exe
</code>```

BrowserFactory class file

```<code>package utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class BrowserFactory
{
    static Properties browserfactory_properties_obj;
    static WebDriver driver;
public static WebDriver browser_factory_getter(String browser, String url) throws IOException
{
    File browserfactory_file_obj = new  File(".\\src\\property_folder\\url_title.properties");
    FileInputStream browserfactory_fileinput_obj = new FileInputStream(browserfactory_file_obj);
    browserfactory_properties_obj = new Properties();
    browserfactory_properties_obj.load(browserfactory_fileinput_obj);
    if(browser.equalsIgnoreCase("firefox"))
    {
        ProfilesIni profile = new ProfilesIni();
        FirefoxProfile fire_profile = profile.getProfile("selenium_browser");
        driver = new  FirefoxDriver(fire_profile);
    }
    else if(browser.equalsIgnoreCase("chrome"))
    {
        System.setProperty("webdriver.chrome.driver",browserfactory_properties_obj.getProperty("chrome_driver_path"));
        driver = new ChromeDriver();
    }
    driver.manage().window().maximize();
    driver.get(url);
    return driver;
}
}
</code>```

home_login_elements class file

```<code>package utilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class home_login_elements
{
    WebDriver driver;
    @FindBy(how=How.CLASS_NAME, using="login")
    WebElement login_link_ele;

    @FindBy(how=How.ID, using="email")
    WebElement username_ele;

    @FindBy(how=How.ID, using="passwd")
    WebElement password_ele;

    @FindBy(how=How.ID, using="SubmitLogin")
    WebElement login_submint_ele;

public WebElement login_link()
{
    login_link_ele.click();
    return login_link_ele;
}

public void login_fun(String username, String password)
{
    username_ele.sendKeys(username);
    password_ele.sendKeys(password);
    login_link_ele.submit();
}
}
</code>```

login_class class file

```<code>package utilities;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;

public class login_class
{
WebDriver driver;
Properties login_class_url_title;
public login_class() throws Exception
{
    File login_class_url_title_file = new File(".\\src\\property_folder\\url_title.properties");
    FileInputStream login_class_url_title_fis = new FileInputStream(login_class_url_title_file);
    login_class_url_title = new Properties();
    login_class_url_title.load(login_class_url_title_fis);
    home_login_elements home_login_elements_login_class_obj = PageFactory.initElements(driver, home_login_elements.class);
    home_login_elements_login_class_obj.login_fun(login_class_url_title.getProperty("username"), login_class_url_title.getProperty("password"));
}
}
</code>```

Add_to_wishlist testng file(executable file)

```<code>package wishlist;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import utilities.BrowserFactory;
import utilities.home_login_elements;
import utilities.login_class;

public class Add_to_wishlist extends home_login_elements
{
WebDriver driver;
@Test
public void first_testcase() throws Exception
{
    driver = BrowserFactory.browser_factory_getter("chrome", "http://automationpractice.com/index.php");
    login_class obj =new login_class();
    driver.findElement(By.xpath("//ul[@class='sf-menu clearfix menu-content sf-js-enabled sf-arrows']/li[3]")).click();
}
}
</code>```

After executing Add_to_wishlist testng file i am getting following error

```<code>Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 6905
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
FAILED: first_testcase
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy5.sendKeys(Unknown Source)
at utilities.home_login_elements.login_fun(home_login_elements.java:36)
at utilities.login_class.<init>(login_class.java:20)
at wishlist.Add_to_wishlist.first_testcase(Add_to_wishlist.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774)
at org.testng.TestRunner.run(TestRunner.java:624)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
</code>```

答:
I don't see the in the class you have initialize your element. </p>

```<code>public class home_login_elements {
    public home_login_elements(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }
}
</code>```

Body:
My files and error which iI am getting are as follows:

url_title.properties

username=rakeshm@techved.com
password=123456
chrome_driver_path=D://rakesh//software//selenium browser//chrome 2.28//chromedriver.exe

BrowserFactory class file

package utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class BrowserFactory
{
    static Properties browserfactory_properties_obj;
    static WebDriver driver;
public static WebDriver browser_factory_getter(String browser, String url) throws IOException
{
    File browserfactory_file_obj = new  File(".\\src\\property_folder\\url_title.properties");
    FileInputStream browserfactory_fileinput_obj = new FileInputStream(browserfactory_file_obj);
    browserfactory_properties_obj = new Properties();
    browserfactory_properties_obj.load(browserfactory_fileinput_obj);
    if(browser.equalsIgnoreCase("firefox"))
    {
        ProfilesIni profile = new ProfilesIni();
        FirefoxProfile fire_profile = profile.getProfile("selenium_browser");
        driver = new  FirefoxDriver(fire_profile);
    }
    else if(browser.equalsIgnoreCase("chrome"))
    {
        System.setProperty("webdriver.chrome.driver",browserfactory_properties_obj.getProperty("chrome_driver_path"));
        driver = new ChromeDriver();
    }
    driver.manage().window().maximize();
    driver.get(url);
    return driver;
}
}

home_login_elements class file

package utilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class home_login_elements
{
    WebDriver driver;
    @FindBy(how=How.CLASS_NAME, using="login")
    WebElement login_link_ele;

    @FindBy(how=How.ID, using="email")
    WebElement username_ele;

    @FindBy(how=How.ID, using="passwd")
    WebElement password_ele;

    @FindBy(how=How.ID, using="SubmitLogin")
    WebElement login_submint_ele;

public WebElement login_link()
{
    login_link_ele.click();
    return login_link_ele;
}

public void login_fun(String username, String password)
{
    username_ele.sendKeys(username);
    password_ele.sendKeys(password);
    login_link_ele.submit();
}
}

login_class class file

package utilities;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;

public class login_class
{
WebDriver driver;
Properties login_class_url_title;
public login_class() throws Exception
{
    File login_class_url_title_file = new File(".\\src\\property_folder\\url_title.properties");
    FileInputStream login_class_url_title_fis = new FileInputStream(login_class_url_title_file);
    login_class_url_title = new Properties();
    login_class_url_title.load(login_class_url_title_fis);
    home_login_elements home_login_elements_login_class_obj = PageFactory.initElements(driver, home_login_elements.class);
    home_login_elements_login_class_obj.login_fun(login_class_url_title.getProperty("username"), login_class_url_title.getProperty("password"));
}
}

Add_to_wishlist testng file(executable file)

package wishlist;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import utilities.BrowserFactory;
import utilities.home_login_elements;
import utilities.login_class;

public class Add_to_wishlist extends home_login_elements
{
WebDriver driver;
@Test
public void first_testcase() throws Exception
{
    driver = BrowserFactory.browser_factory_getter("chrome", "http://automationpractice.com/index.php");
    login_class obj =new login_class();
    driver.findElement(By.xpath("//ul[@class='sf-menu clearfix menu-content sf-js-enabled sf-arrows']/li[3]")).click();
}
}

After executing Add_to_wishlist testng file i am getting following error

Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 6905
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
FAILED: first_testcase
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy5.sendKeys(Unknown Source)
at utilities.home_login_elements.login_fun(home_login_elements.java:36)
at utilities.login_class.<init>(login_class.java:20)
at wishlist.Add_to_wishlist.first_testcase(Add_to_wishlist.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774)
at org.testng.TestRunner.run(TestRunner.java:624)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)

Body:
I don't see the in the class you have initialize your element.

public class home_login_elements {
    public home_login_elements(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }
}


问:
WPF app debuging - visual studio exits debug, running .exe is fine
I start debugging WPF app,
I get several The thread 0xab5c has exited with code 0 (0x0).
finally The program '[24388] MyApp.dgdg.exe ' has exited with code 0 (0x0).

When I run MyApp.dgdg.exe from bin/Debug it runs fine.

Please help :)

答:
This is just a harmless Visual Studio debugging message that you can safely ignore or switch off by simply right-clicking in the output window and uncheck the "Thread Exit Messages" option.

It's not an error.


问:
jQuery target id inside iframe and alert
My code is like below.

```<code><!DOCTYPE html>
<html>

  <head>
    <title>TODO</title>
  </head>

  <body>
    <div id="btn">
      <button id="clickme">Click Me</button>
    </div>
    <div class="iframebox">
      <iframe id="messageiframe">
        <html>

        <head>
          <title>test</title>
        </head>

        <body>
          <div id="textpreview">
            <p id="pre">some text</p>
          </div>
        </body>

        </html>
      </iframe>
    </div>
  </body>

</html>
</code>```

I am trying to target id="textpreview" inside iframe using jQuery. I can successfully target any id outside iframe but unable to target inside iframe.

My jQuery code is:

```<code>$('#clickme').on('click', function() {
  if ($("#textpreview").length > 0) {
    alert("success");
  }
});
</code>```

How can I achieve this?

Thanks in advance.

答:
Use "contents()"

```<code>$("#messageiframe").contents().find("#textpreview")
</code>```

https://api.jquery.com/contents/

Body:
My code is like below.

<!DOCTYPE html>

    <title>TODO</title>

      <button id="clickme">Click Me</button>

          <title>test</title>

some text

I am trying to target id="textpreview" inside iframe using jQuery. I can successfully target any id outside iframe but unable to target inside iframe.

My jQuery code is:

$('#clickme').on('click', function() {
  if ($("#textpreview").length > 0) {
    alert("success");
  }
});

How can I achieve this?

Thanks in advance.

Body:
Use "contents()"

$("#messageiframe").contents().find("#textpreview")

https://api.jquery.com/contents/


问:
Mapping json data to java objects in a proper way-LibGdx
I am working on an endless running game with levels.I want to place obstacles for the first level.I want do it with json,but having difficulties because I am trying json parsing for the first time.

I created a json file like this:

```<code>{
"screen1":
[
{"name":"rock","position":"middle","distance":"400","speed":"0"}
],
"screen2":
[
      {"name":"snake","position":"up","distance":"100","speed":"0"},
      {"name":"watersnake","position":"up","distance":"800","speed":"0"}
],
"screen3":
 [
      {"name":"rock","position":"middle","distance":"400","speed":"0"},
      {"name":"gorilla","position":"middle","distance":"500","speed ":"0"},
      {"name":"crow","position":"up","distance":"200","speed":"0"}

],

"screen4":
[
    {"name":"crocodile","position":"up","distance":"600","speed":"0"},
    {"name":"gap","position":"up","distance":"700","speed":"0"},
    {"name":"cloud","position":"up","distance":"300","speed":"0"}

],
"screen5":
[
{"name":"gorilla","position":"middle","distance":"500","speed ":"0"}
]
}
</code>```

Actually I divided entire moving background to 5 screens.For each screen,I want to place obstacles as specified in the json file.

For that I want to map parsed json to java object.

So I created a method like this for parsing:

```<code> public void loadLevelJson(String fileName,String entryName)
{
        JsonValue jsonValue = new JsonReader().parse(Gdx.files.internal(fileName));
        JsonValue objList = jsonValue.get(entryName);
            //  System.out.println("name:" + objList);
                if (entryName.equals("screen2")){
                    System.out.println("____________"+entryName);
                for(JsonValue value : objList.iterator())
                {
                      if(value.getString("name").equals("rock"))
                      {
                          rockSpeed=value.getFloat("speed");
                          rockpos=value.getString("position");
                          rockX=value.getFloat("distance");

                          if(value.getString("position").equals("middle"))
                              rockY=Constants.BIG_ROCK_Y;
                      }

                      if(value.getString("name").equals("snake"))
                      {
                          snakeSpeed=value.getFloat("speed");
                          snakePos=value.getString("position");
                          snakeX=value.getFloat("distance");
                          if(value.getString("position").equals("up"))
                              snakeY=Constants.SNAKE_Y;
                      }
                      if(value.getString("name").equals("watersnake"))
                      {
                          w_snakeSpeed=value.getFloat("speed");
                          w_snakePos=value.getString("position");
                          w_snakeX=value.getFloat("distance");
                          if(value.getString("position").equals("down"))
                              w_snakeY=Constants.W_SNAKE_Y;
                      }
                      if(value.getString("name").equals("gorilla"))
                      {
                          gorillaSpeed=value.getFloat("speed");
                          gorillaPos=value.getString("position");
                          gorillaX=value.getFloat("distance");
                          if(value.getString("position").equals("middle"))
                              gorillaY=Constants.GORILLA_Y;
                      }
                      if(value.getString("name").equals("crow"))
                      {
                          crowSpeed=value.getFloat("speed");
                          crowPos=value.getString("position");
                          crowX=value.getFloat("distance");
                          if(value.getString("position").equals("up"))
                              crowY=Constants.CROW_Y;
                      }

                      if(value.getString("name").equals("gap"))
                      {
                          gapSpeed=value.getFloat("speed");
                          gapPos=value.getString("position");
                          gapX=value.getFloat("distance");
                          if(value.getString("position").equals("down"))
                              gapY=Constants.GAP_Y;
                      }
                      if(value.getString("name").equals("cloud"))
                      {
                          cloudSpeed=value.getFloat("speed");
                          cloudPos=value.getString("position");
                          cloudX=value.getFloat("distance");
                          if(value.getString("position").equals("up"))
                              cloudY=Constants.CLOUD_Y;
                      }
                      if(value.getString("name").equals("cloud"))
                      {
                          crocodileSpeed=value.getFloat("speed");
                          crocodilePos=value.getString("position");
                          crocodileX=value.getFloat("distance");
                          if(value.getString("position").equals("down"))
                              crocodileY=Constants.CROCODILE_Y;
                      }
                }
}

}
</code>```

But I am really getting a hard time on how to parse these things with each screen and obstacles to map to screen and object classes created.Fully confused because I am using json for the first time.

It would be very helpful if someone gives some idea to proceed.

Thanks in advance.

答:
There are many different ways to achieve this. Maybe do some research into libgdx json using java collections. How you end up structuring your code is really up to you. We don't know the details of your code or how you'll need to use the data.

Maybe start simpler, get something working and then expand from there once you're more comfortable. Perhaps break your json obstacles into individual files per screen to start. What you're then left with could (just an example) utilize the List interface.

Again, as an example, if you had an Obstacle class (all code just informational, don't even know if it compiles)

```<code>pulic class Obstacle {

    private String name;
    private String position;
    private int distance;
    private int speed;
}
</code>```

use this to instantiate an object for each obstacle in a level. Then wherever you're doing your json parsing/need the obstacles, have something like

```<code>...
//fileName contains only obstacles for one screen, not all of them
ArrayList<Obstacle> obstacles = json.fromJson(ArrayList.class, Obstacle.class, Gdx.files.internal(fileName));
</code>```

That would give you an ArrayList of obstacles in play for that specific level, but how you use it is up to you. Like I said above, many different options but you'd have to tailor to your requirements. Using the Map interface might make more sense, for example, to use the obstacle name as the key (or maybe not - up to you). To have all obstacles for all screens loaded at once may lend itselfs to Lists of Lists (or List of Map, etc... ). More complex, but if you get the above working, you can then play around with ever increasing complexity and refactor to suit your needs.

Again, just typed the above off the top of my head, so syntax may be a little off.

Edit to add:

Updating after some of your comments: As I said above, there are many ways to go about it, all depending on your data and how you want to use it. The Collections Framework should provide you all you need, and using the example I provided for json, you should be able to parse from files. The more "nesting" you have, the more complex the json. Thus, why I suggest starting slower, or breaking screen obstacles into each individual class.

If you've created classes for the obstacles, then the json in my original answer would automatically read it into an ArrayList for you. One element in the list for each obstacle.

(Again, all this code off the top of my head, could have syntax errors)

Another option may be to use the Map interface, maybe a HashMap. Use the "name" as the key, and the value would be the obstacle object (no need to include the name in the object). Something like

```<code>Map<Obstacle> obstacles = new HashMap<String, Obstacle>().
</code>```

Now to get an individual obstacle, you access the map, asking for the obstacle by name and you'll get your obstacle class (read up on the collections framework API).

You can of course nest your obstacles into another collection, which represents your screens. Something like

```<code>List<HashMap<String, Obstacle>> screenObstacles = new ....
</code>```

So if you read your json obstacles one screen at a time (like in my original example) into variable aVar, you should be able to do

```<code>screenObstacles.add(aVar);
</code>```

Then retrieve as needed.

```<code>Map<Obstacle> obstacles = screenObstacles.get(screenNumber); //screenNumber is screen you are on, ex 0/1/2/...
Obstacle obstacle = obstacles.get(GORILLA_NAME); // GORILLA_NAME is a string "gorilla"

//or loop through all obstacles for a given screen and do something with them

for (Obstacle obstacle : obstacles) {
    //something amazing goes here
}
</code>```

Body:
I am working on an endless running game with levels.I want to place obstacles for the first level.I want do it with json,but having difficulties because I am trying json parsing for the first time.

I created a json file like this:

{
"screen1":
[
{"name":"rock","position":"middle","distance":"400","speed":"0"}
],
"screen2":
[
      {"name":"snake","position":"up","distance":"100","speed":"0"},
      {"name":"watersnake","position":"up","distance":"800","speed":"0"}
],
"screen3":
 [
      {"name":"rock","position":"middle","distance":"400","speed":"0"},
      {"name":"gorilla","position":"middle","distance":"500","speed ":"0"},
      {"name":"crow","position":"up","distance":"200","speed":"0"}

],

"screen4":
[
    {"name":"crocodile","position":"up","distance":"600","speed":"0"},
    {"name":"gap","position":"up","distance":"700","speed":"0"},
    {"name":"cloud","position":"up","distance":"300","speed":"0"}

],
"screen5":
[
{"name":"gorilla","position":"middle","distance":"500","speed ":"0"}
]
}

Actually I divided entire moving background to 5 screens.For each screen,I want to place obstacles as specified in the json file.

For that I want to map parsed json to java object.

So I created a method like this for parsing:

 public void loadLevelJson(String fileName,String entryName)
{
        JsonValue jsonValue = new JsonReader().parse(Gdx.files.internal(fileName));
        JsonValue objList = jsonValue.get(entryName);
            //  System.out.println("name:" + objList);
                if (entryName.equals("screen2")){
                    System.out.println("____________"+entryName);
                for(JsonValue value : objList.iterator())
                {
                      if(value.getString("name").equals("rock"))
                      {
                          rockSpeed=value.getFloat("speed");
                          rockpos=value.getString("position");
                          rockX=value.getFloat("distance");

                          if(value.getString("position").equals("middle"))
                              rockY=Constants.BIG_ROCK_Y;
                      }

                      if(value.getString("name").equals("snake"))
                      {
                          snakeSpeed=value.getFloat("speed");
                          snakePos=value.getString("position");
                          snakeX=value.getFloat("distance");
                          if(value.getString("position").equals("up"))
                              snakeY=Constants.SNAKE_Y;
                      }
                      if(value.getString("name").equals("watersnake"))
                      {
                          w_snakeSpeed=value.getFloat("speed");
                          w_snakePos=value.getString("position");
                          w_snakeX=value.getFloat("distance");
                          if(value.getString("position").equals("down"))
                              w_snakeY=Constants.W_SNAKE_Y;
                      }
                      if(value.getString("name").equals("gorilla"))
                      {
                          gorillaSpeed=value.getFloat("speed");
                          gorillaPos=value.getString("position");
                          gorillaX=value.getFloat("distance");
                          if(value.getString("position").equals("middle"))
                              gorillaY=Constants.GORILLA_Y;
                      }
                      if(value.getString("name").equals("crow"))
                      {
                          crowSpeed=value.getFloat("speed");
                          crowPos=value.getString("position");
                          crowX=value.getFloat("distance");
                          if(value.getString("position").equals("up"))
                              crowY=Constants.CROW_Y;
                      }

                      if(value.getString("name").equals("gap"))
                      {
                          gapSpeed=value.getFloat("speed");
                          gapPos=value.getString("position");
                          gapX=value.getFloat("distance");
                          if(value.getString("position").equals("down"))
                              gapY=Constants.GAP_Y;
                      }
                      if(value.getString("name").equals("cloud"))
                      {
                          cloudSpeed=value.getFloat("speed");
                          cloudPos=value.getString("position");
                          cloudX=value.getFloat("distance");
                          if(value.getString("position").equals("up"))
                              cloudY=Constants.CLOUD_Y;
                      }
                      if(value.getString("name").equals("cloud"))
                      {
                          crocodileSpeed=value.getFloat("speed");
                          crocodilePos=value.getString("position");
                          crocodileX=value.getFloat("distance");
                          if(value.getString("position").equals("down"))
                              crocodileY=Constants.CROCODILE_Y;
                      }
                }
}

}

But I am really getting a hard time on how to parse these things with each screen and obstacles to map to screen and object classes created.Fully confused because I am using json for the first time.

It would be very helpful if someone gives some idea to proceed.

Thanks in advance.

Body:
There are many different ways to achieve this. Maybe do some research into libgdx json using java collections. How you end up structuring your code is really up to you. We don't know the details of your code or how you'll need to use the data.

Maybe start simpler, get something working and then expand from there once you're more comfortable. Perhaps break your json obstacles into individual files per screen to start. What you're then left with could (just an example) utilize the List interface.

Again, as an example, if you had an Obstacle class (all code just informational, don't even know if it compiles)

pulic class Obstacle {

    private String name;
    private String position;
    private int distance;
    private int speed;
}

use this to instantiate an object for each obstacle in a level. Then wherever you're doing your json parsing/need the obstacles, have something like

...
//fileName contains only obstacles for one screen, not all of them
ArrayList<Obstacle> obstacles = json.fromJson(ArrayList.class, Obstacle.class, Gdx.files.internal(fileName));

That would give you an ArrayList of obstacles in play for that specific level, but how you use it is up to you. Like I said above, many different options but you'd have to tailor to your requirements. Using the Map interface might make more sense, for example, to use the obstacle name as the key (or maybe not - up to you). To have all obstacles for all screens loaded at once may lend itselfs to Lists of Lists (or List of Map, etc... ). More complex, but if you get the above working, you can then play around with ever increasing complexity and refactor to suit your needs.

Again, just typed the above off the top of my head, so syntax may be a little off.

Edit to add:

Updating after some of your comments: As I said above, there are many ways to go about it, all depending on your data and how you want to use it. The Collections Framework should provide you all you need, and using the example I provided for json, you should be able to parse from files. The more "nesting" you have, the more complex the json. Thus, why I suggest starting slower, or breaking screen obstacles into each individual class.

If you've created classes for the obstacles, then the json in my original answer would automatically read it into an ArrayList for you. One element in the list for each obstacle.

(Again, all this code off the top of my head, could have syntax errors)

Another option may be to use the Map interface, maybe a HashMap. Use the "name" as the key, and the value would be the obstacle object (no need to include the name in the object). Something like

Map<Obstacle> obstacles = new HashMap<String, Obstacle>().

Now to get an individual obstacle, you access the map, asking for the obstacle by name and you'll get your obstacle class (read up on the collections framework API).

You can of course nest your obstacles into another collection, which represents your screens. Something like

List<HashMap<String, Obstacle>> screenObstacles = new ....

So if you read your json obstacles one screen at a time (like in my original example) into variable aVar, you should be able to do

screenObstacles.add(aVar);

Then retrieve as needed.

Map<Obstacle> obstacles = screenObstacles.get(screenNumber); //screenNumber is screen you are on, ex 0/1/2/...
Obstacle obstacle = obstacles.get(GORILLA_NAME); // GORILLA_NAME is a string "gorilla"

//or loop through all obstacles for a given screen and do something with them

for (Obstacle obstacle : obstacles) {
    //something amazing goes here
}


问:
showmodaldialog polyfill : how to pass value to parent window and dialog closed by calling a function?
There is problem in Google Chrome that showmodaldialog doesn't work so that I use showmodaldialog.js from polyfill.

I have two aspx page, one for parent window page parentpage.aspx and one for pop up in dialog emplsearch.aspx.  The dialog works but I am having problem in passing value from dialog to parent window and the dialog cannot be closed by clicking imbSelect imagebutton on click javascript function on emplsearch.aspx. I try to use something like this:

```<code>function quitBox(cmd, msg) {

    if (cmd == 'quit') {
        open(location, '_self').close(); // this works for firefox, but chrome doesnt work
        dialog.close();  // error in console in here... dialog doesnt closed in chrome

       setValuesToParent(msg); // start to pass value to parent window
    }
    return false;
}

function setValuesToParent(msg) {

    parent.window.document.getElementById('txbPinjamBy').value = msg[2];  // this doesnt work too...  error : Cannot set property 'value' of null
    window.opener.setValues(msg); // this is the important line

};
</code>```

thanks

答:
The problem is that the model dialog doesn't returns the values. below code is used in dialog</p>

```<code>window.returnValue = indexName + "$$" + selArrString;

var agentStr = navigator.userAgent;
if (agentStr.indexOf("Chrome") >- 1) {
    // Based on their suggestion I added this line
    parent.document.getElementsByTagName('dialog')[0].close();
    // (In order to close the dialog from inside of it, invoke
    //     parent.document.getElementsByTagName('dialog')[0].close();
    // provided that both documents have the same origin.)
} else {
    self.close();
}
</code>```

Body:
There is problem in Google Chrome that showmodaldialog doesn't work so that I use showmodaldialog.js from polyfill.

I have two aspx page, one for parent window page parentpage.aspx and one for pop up in dialog emplsearch.aspx.  The dialog works but I am having problem in passing value from dialog to parent window and the dialog cannot be closed by clicking imbSelect imagebutton on click javascript function on emplsearch.aspx. I try to use something like this:

function quitBox(cmd, msg) {

    if (cmd == 'quit') {
        open(location, '_self').close(); // this works for firefox, but chrome doesnt work
        dialog.close();  // error in console in here... dialog doesnt closed in chrome

       setValuesToParent(msg); // start to pass value to parent window
    }
    return false;
}

function setValuesToParent(msg) {

    parent.window.document.getElementById('txbPinjamBy').value = msg[2];  // this doesnt work too...  error : Cannot set property 'value' of null
    window.opener.setValues(msg); // this is the important line

};

thanks

Body:
The problem is that the model dialog doesn't returns the values. below code is used in dialog

window.returnValue = indexName + "$$" + selArrString;

var agentStr = navigator.userAgent;
if (agentStr.indexOf("Chrome") >- 1) {
    // Based on their suggestion I added this line
    parent.document.getElementsByTagName('dialog')[0].close();
    // (In order to close the dialog from inside of it, invoke
    //     parent.document.getElementsByTagName('dialog')[0].close();
    // provided that both documents have the same origin.)
} else {
    self.close();
}


问:
How to get am pm from the date time string using moment js
I have a string as Mon 03-Jul-2017, 11:00 AM/PM and I have to convert this into a string like 11:00 AM/PM using moment js.

The problem here is that I am unable to get AM or PM from the date time string.

I am doing this:

```<code>moment(Mon 03-Jul-2017, 11:00 AM, 'dd-mm-yyyy hh:mm').format('hh:mm A')
</code>```

and it is working fine as I am getting 11:00 AM but if the string has PM in it it is still giving AM in the output.

like this moment(Mon 03-Jul-2017, 11:00 PM, 'dd-mm-yyyy hh:mm').format('hh:mm A') is also giving 11:00 AM in output instead of 11:00 PM

答:
You are using the wrong format tokens when parsing your input. You should use ddd for an abbreviation of the name of day of the week,  DD for day of the month, MMM for an abbreviation of the month's name, YYYY for the year, hh for the 1-12 hour, mm for minutes and A for AM/PM. See moment(String, String) docs.

Here is a working live sample:

console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
I have a string as Mon 03-Jul-2017, 11:00 AM/PM and I have to convert this into a string like 11:00 AM/PM using moment js.

The problem here is that I am unable to get AM or PM from the date time string.

I am doing this:

moment(Mon 03-Jul-2017, 11:00 AM, 'dd-mm-yyyy hh:mm').format('hh:mm A')

and it is working fine as I am getting 11:00 AM but if the string has PM in it it is still giving AM in the output.

like this moment(Mon 03-Jul-2017, 11:00 PM, 'dd-mm-yyyy hh:mm').format('hh:mm A') is also giving 11:00 AM in output instead of 11:00 PM

Body:
You are using the wrong format tokens when parsing your input. You should use ddd for an abbreviation of the name of day of the week,  DD for day of the month, MMM for an abbreviation of the month's name, YYYY for the year, hh for the 1-12 hour, mm for minutes and A for AM/PM. See moment(String, String) docs.

Here is a working live sample:

console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
object-oriented shell for linux?
Is there anything similar to Microsoft Powershell (an object-oriented shell built on the .NET framework) for Linux (possibly built on Java, GObject, or its own object type/nothing)?

edit: especially if similar to bash or powershell or cmd etc. syntax (=''standard'' shell syntax)

答:
Python.  No joking.

Scripting languages are scripting languages, and Python is a particularly nice one that many people find very approachable.

Title: object-oriented shell for linux?


问:
How to make a foreach of an object in javascript?
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

```<code>var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);
</code>```

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

```<code>for(var index in CurrentSelec) {
    console.log(index.qSelected);
}
</code>```

I have tried with jQuery:

```<code>$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});
</code>```

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

答:
You iterate object using javascript for in loop.

For e.g. CurrentSelec is your object.

```<code>for(key in CurrentSelec){
    //key is your object's main query.
    //CurrentSelec is your object's nested array if has.
    console.log(key);
    console.log(CurrentSelec[key]);
}
</code>```

Body:
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

for(var index in CurrentSelec) {
    console.log(index.qSelected);
}

I have tried with jQuery:

$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

Body:
You iterate object using javascript for in loop.

For e.g. CurrentSelec is your object.

for(key in CurrentSelec){
    //key is your object's main query.
    //CurrentSelec is your object's nested array if has.
    console.log(key);
    console.log(CurrentSelec[key]);
}


问:
how to plot 2d random data with imshow method in python
```<code>import numpy as np
C=np.random.rand (500)
S=np.random.rand(500)
def function(s,c):
    return s*2+c
dc=[]
for i in range(len(C)):
    dc.append(function(S[i],C[i])
</code>```

I don't know how to imshow the random result with imshow. I want to get the image like this:

答:
At a test ,I get the scatter map ,but it not better to show all things.

```<code>import numpy as np
import matplotlib.pyplot as plt
def function(C,S):
    return 2*C+S**2
axis=plt.subplot()
Sand=np.random.rand(50)
Clay=np.random.rand(50)
dc=function(C=Clay,S=Sand)
plt.scatter(Clay,Sand,c=dc,cmap='jet')
axis.set_xlabel('Clay')
axis.set_ylabel('Sand')
</code>```

enter image description here

So I want to show it by other method .Pcolor or imshow is better way to realize it.So I ：

```<code>import numpy as np
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
axis=plt.subplot()
def function (C,S):
    return 2*C+S**2
axis=plt.subplot()
dc=np.ones(50*50).reshape(50,50)
Sand=np.random.rand(50)
Clay=np.random.rand(50)
Clay_or=sorted(Clay)
Sand_or=sorted(Sand,reverse=True)
for i in range(50):
    for j in range (50):
        result=function(Clay_or[i],Sand_or[j])
        dc[j][i]=result
plt.imshow(dc,cmap='jet',extent=(0,1,0,1))
axis.set_xlabel('Clay')
axis.set_ylabel('Sand')
</code>```

enter image description here

The result is better .But i have a question,how to set axis ticks if i  use the pcolor function?

Body:
import numpy as np
C=np.random.rand (500)
S=np.random.rand(500)
def function(s,c):
    return s*2+c
dc=[]
for i in range(len(C)):
    dc.append(function(S[i],C[i])

I don't know how to imshow the random result with imshow. I want to get the image like this:

Body:
At a test ,I get the scatter map ,but it not better to show all things.

import numpy as np
import matplotlib.pyplot as plt
def function(C,S):
    return 2*C+S**2
axis=plt.subplot()
Sand=np.random.rand(50)
Clay=np.random.rand(50)
dc=function(C=Clay,S=Sand)
plt.scatter(Clay,Sand,c=dc,cmap='jet')
axis.set_xlabel('Clay')
axis.set_ylabel('Sand')

enter image description here

So I want to show it by other method .Pcolor or imshow is better way to realize it.So I ：

import numpy as np
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
axis=plt.subplot()
def function (C,S):
    return 2*C+S**2
axis=plt.subplot()
dc=np.ones(50*50).reshape(50,50)
Sand=np.random.rand(50)
Clay=np.random.rand(50)
Clay_or=sorted(Clay)
Sand_or=sorted(Sand,reverse=True)
for i in range(50):
    for j in range (50):
        result=function(Clay_or[i],Sand_or[j])
        dc[j][i]=result
plt.imshow(dc,cmap='jet',extent=(0,1,0,1))
axis.set_xlabel('Clay')
axis.set_ylabel('Sand')

enter image description here

The result is better .But i have a question,how to set axis ticks if i  use the pcolor function?


问:
Canvas causes contentcontrol children to spill out over control
I have the following XAML:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*"/>
        <ColumnDefinition Width="11" />
        <ColumnDefinition Width="3*"/>
    </Grid.ColumnDefinitions>
    <ListView ... Grid.Column="2"/>
    <controls:GridSplitter
    Grid.Column="1"
        Width="11"
    ResizeBehavior="BasedOnAlignment"
    ResizeDirection="Auto"
        Background="Gray"
        Foreground="White"
        FontSize="13">
        <controls:GridSplitter.Element>
            <Grid>
                <TextBlock HorizontalAlignment="Center"
                           IsHitTestVisible="False"
                           VerticalAlignment="Center"
                            Text=""
                           Foreground="Black"
                           FontFamily="Segoe MDL2 Assets">
                </TextBlock>
            </Grid>
        </controls:GridSplitter.Element>
    </controls:GridSplitter>
    <Canvas Canvas.ZIndex="1">
        <ContentControl MaxWidth="750" Content="{Binding CAV, Mode=TwoWay}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
    </Canvas>
</Grid>
</code>```

Without the Canvas wrapped around the ContentControl in the first column, the children of the ContentControl properly stay within the content control and I can make it wider to see more of the children horizontally.

When I add the Canvas and set the ZIndex, the children of the content control spill out over the gridsplitter and the ListView without respecting the width of the contentcontrol.

The effect I'm trying to get it to allow expanding the width of the content control with the grid splitter and having that content control expand "over" the listview (instead of reducing the width of the listview).

What am I missing? I'm confused as to why the width of the contentcontrol isn't being respected suddenly just because I wrap it in a Canvas. Or should I not be using Canvas to get the "overlay" effect I want?

答:
As an addendum Canvas tells the layout tree it uses no space. It doesn't care about the size of it's children, despite however many children it might have. For reference, here's the Canvas' MeasureOverride:

```<code>protected override Size MeasureOverride(Size constraint)
{
    Size childConstraint = new Size(Double.PositiveInfinity, Double.PositiveInfinity);

    foreach (UIElement child in InternalChildren)
    {
        if (child == null) { continue; }
        child.Measure(childConstraint);
    }

    return new Size();
}
</code>```

Which effectively says "I'm not taking up any space and my children can use whatever space they want".

Body:
I have the following XAML:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*"/>
        <ColumnDefinition Width="11" />
        <ColumnDefinition Width="3*"/>
    </Grid.ColumnDefinitions>
    <ListView ... Grid.Column="2"/>
    <controls:GridSplitter
    Grid.Column="1"
        Width="11"
    ResizeBehavior="BasedOnAlignment"
    ResizeDirection="Auto"
        Background="Gray"
        Foreground="White"
        FontSize="13">
        <controls:GridSplitter.Element>
            <Grid>
                <TextBlock HorizontalAlignment="Center"
                           IsHitTestVisible="False"
                           VerticalAlignment="Center"
                            Text=""
                           Foreground="Black"
                           FontFamily="Segoe MDL2 Assets">
                </TextBlock>
            </Grid>
        </controls:GridSplitter.Element>
    </controls:GridSplitter>
    <Canvas Canvas.ZIndex="1">
        <ContentControl MaxWidth="750" Content="{Binding CAV, Mode=TwoWay}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" />
    </Canvas>
</Grid>

Without the Canvas wrapped around the ContentControl in the first column, the children of the ContentControl properly stay within the content control and I can make it wider to see more of the children horizontally.

When I add the Canvas and set the ZIndex, the children of the content control spill out over the gridsplitter and the ListView without respecting the width of the contentcontrol.

The effect I'm trying to get it to allow expanding the width of the content control with the grid splitter and having that content control expand "over" the listview (instead of reducing the width of the listview).

What am I missing? I'm confused as to why the width of the contentcontrol isn't being respected suddenly just because I wrap it in a Canvas. Or should I not be using Canvas to get the "overlay" effect I want?

Body:
As an addendum Canvas tells the layout tree it uses no space. It doesn't care about the size of it's children, despite however many children it might have. For reference, here's the Canvas' MeasureOverride:

protected override Size MeasureOverride(Size constraint)
{
    Size childConstraint = new Size(Double.PositiveInfinity, Double.PositiveInfinity);

    foreach (UIElement child in InternalChildren)
    {
        if (child == null) { continue; }
        child.Measure(childConstraint);
    }

    return new Size();
}

Which effectively says "I'm not taking up any space and my children can use whatever space they want".


问:
WITH in BigQuery
Does BigQuery support the WITH clause? I don't like formatting too many subqueries.

For example:

```<code>WITH alias_1 AS (SELECT foo1 c FROM bar)
, alias_2 AS (SELECT foo2 c FROM bar a, alias_1 b WHERE b.c = a.c)
SELECT * FROM alias_2 a;
</code>```

答:
BigQery Standard SQL is supporting WITH clause. The syntax is as shown below

```<code>with table2 as (Select column1,column2 from table1)
    select column1 from table2
</code>```

Title: WITH in BigQuery

Body:
Does BigQuery support the WITH clause? I don't like formatting too many subqueries.

For example:

WITH alias_1 AS (SELECT foo1 c FROM bar)
, alias_2 AS (SELECT foo2 c FROM bar a, alias_1 b WHERE b.c = a.c)
SELECT * FROM alias_2 a;

Body:
BigQery Standard SQL is supporting WITH clause. The syntax is as shown below

with table2 as (Select column1,column2 from table1)
    select column1 from table2

ContentLicense: CC BY-SA 4.0