问:
Get axis info from Logitech racing wheel via Python
Recently, I have been playing a bus driving simulator. I have a racing wheel, which doesn't have a clutch pedal, so I searched for a way to adapt the mouse to act as a joystick with clutch, brake and gas. I found a solution with vJoy and FreePIE - Programmable Input Emulator. I found an example, which works perfectly for the mouse:

```<code>#Title         :OMSI 2 Freepie Mouse (Edited Mjoy vJoy FreePIE python script)
#Version       :0.1 (2016-03-22)
#Author        :snp, NEMOROSUS
#Description   :FreePIE python script for OMSI 2 mouse controls such as acceleration, steering and clutch control that is more accurate that the built-in one.

import time
from System import Int16
from ctypes import windll, Structure, c_ulong, byref, CDLL

class POINT(Structure):
_fields_ = [("x", c_ulong), ("y", c_ulong)]

if starting:
vJoy0_stat = 1
vJoy[0].x = 0
vJoy[0].y = 0
vJoy[0].z = 0
x = 0
y = 0
z = 0
mouse_x = 0
mouse_y = 0
mouse_z = 0
mouse_x_locked = 0
mouse_y_locked = 0
x_m = 0
y_m = 0
axis_max = 16448
screen_x = windll.user32.GetSystemMetrics(0)
screen_y = windll.user32.GetSystemMetrics(1)
pt = POINT()
sequence = 0
system.setThreadTiming(TimingTypes.HighresSystemTimer)
system.threadExecutionInterval = 1

z += mouse.wheel * 10

# X/Y axis centering

#if keyboard.getKeyDown(Key.Space):
#windll.user32.SetCursorPos((screen_x / 2),(screen_y / 2))

# Mjoy vJoy

# Turn VJoy on/off

if keyboard.getPressed(Key.K):
if sequence == 0:
  vJoy0_stat = 0
elif sequence == 1:
  vJoy0_stat = 1

sequence = sequence + 1
if sequence > 1:
  sequence = 0

if vJoy0_stat == 1:
windll.user32.GetCursorPos(byref(pt))
mouse_x = pt.x
mouse_y = pt.y

sensitivity = 28
x_m = (mouse_x - (screen_x / 2)) * sensitivity
y_m = (mouse_y - (screen_y / 2)) * sensitivity / 0.66
x_both = x_m + x
y_both = y_m + y
x_keyb_sensitivity = 350
y_keyb_sensitivity = 350

if x_m > axis_max:
  x_m = axis_max

if x_m < - axis_max:
  x_m = - axis_max

if y_m > axis_max:
  y_m = axis_max

if y_m < - axis_max:
  y_m = - axis_max

if x > axis_max:
  x = axis_max

if x < - axis_max:
  x = - axis_max

if y > axis_max:
  y = axis_max

if y < - axis_max:
  y = - axis_max

if z > axis_max:
  z = axis_max

if z < - axis_max:
  z = - axis_max

if x_both > axis_max:
  x_both = axis_max

if x_both < - axis_max:
  x_both = - axis_max

if y_both > axis_max:
  y_both = axis_max

if y_both < - axis_max:
  y_both = - axis_max

vJoy[0].x = x_m + x
vJoy[0].y = y_m + y
vJoy[0].z = z

# Diag

diagnostics.watch(screen_x)
diagnostics.watch(screen_y)
diagnostics.watch(mouse_x)
diagnostics.watch(mouse_y)
diagnostics.watch(mouse_x_locked)
diagnostics.watch(mouse_y_locked)
diagnostics.watch(vJoy[0].x)
diagnostics.watch(vJoy[0].y)
diagnostics.watch(vJoy[0].z)
</code>```

I am very new to Python so I started googling for a solution in terms of how to convert the two-pedal Logitech wheel into a three-pedal wheel. I came up with the idea to use vJoy as my "final" joystick. I planned to feed it up with all the axis from the wheel and the Y-axe from the mouse, which will act as the clutch. So, after searching for a solution, I added this piece of Python code:

```<code>from ctypes import CDLL

_glfw = CDLL("path_to_FreePIE_installation\\plugins\\lib-mingw-w64\\glfw3.dll")
joyNum = 0
isHere = _glfw.glfwJoystickPresent(joyNum)
diagnostics.watch(isHere)
joyName = _glfw.glfwGetJoystickName(joyNum)
diagnostics.watch(joyName)
#joy = _glfw.glfwGetJoystickAxes(0)
#joy = _glfw.glfwGetJoystickButtons(0)
#diagnostics.watch(joy)
</code>```

I took the idea from this documentation and this documentation. They say, that joyNum should be between 0 and 15. I tried every single number between 0 and 15 and even with 16 and 17. Every time, isHere is 0 although I have connected the wheel to one of the three USB-ports of my laptop. I tried to attach it to all them three with the same result. _glfw.glfwGetJoystickName(joyNum) is also giving me 0 every time. Can somebody help me to debug this? I don't understand why it can't find the wheel. It is not a problem with the driver because I can play games with no problem right now - the wheel is working normally.

When I try to call _glfw.glfwGetJoystickAxes(0) or _glfw.glfwGetJoystickButtons(0) - FreePIE crashes and when I debug it with VS2010, the exception message is: "Attempted to read or write protected memory. This is often an indication that another memory is corrupt."

EDIT:

I took a closer look at another documentation and replaced the code I added with this one:

```<code>from ctypes import CDLL, POINTER, c_float, c_int

glfw = CDLL("path_to_FreePIE_installation\\plugins\\lib-mingw-w64\\glfw3.dll")
joyNum = 0
isHere = _glfw.glfwJoystickPresent(joyNum)
diagnostics.watch(isHere)
joyName = _glfw.glfwGetJoystickName(joyNum)
diagnostics.watch(joyName)
cnt = c_int(0)
_glfw.glfwGetJoystickAxes.restype = POINTER(c_float)
joy = _glfw.glfwGetJoystickAxes(0, byref(cnt))
diagnostics.watch(joy)
axes = [joy[i].value for i in range(cnt)]
diagnostics.watch(cnt)
diagnostics.watch(axes)
</code>```

Now the script is not run at all and I see the following error in FreePIE's console:

range() integer end argument expected, got c_long.
The error occurs on this line:
axes = [joy[i].value for i in range(cnt)]

I am confused. Here they have shown an example on how to get the axes values. This is the snippet from their site:

```<code>def glfwGetJoystickAxes(joy):
count = c_int(0)
_glfw.glfwGetJoystickAxes.restype = POINTER(c_float)
c_axes = _glfw.glfwGetJoystickAxes(joy, byref(count))
axes = [c_axes[i].value for i in range(count)]
</code>```

As you can see here, the count is of type c_int and they give it to range() and they say it should work. Or maybe joy[i].value in my code snippet is of type c_long and that is the case?

Any help will be greatly appreciated! Thanks!

EDIT2:

For anyone, who may fall into such a situation. This is the code, which did the job for me:

```<code>if starting:
    # ...
    _glfw.glfwInit() # this is VERY important!
    joyNum = 1 # not 0, because the mouse appears to be joystick No 0
    # ...
if vJoy0_stat == 1: # the main loop
    # ...
    isHere = _glfw.glfwJoystickPresent(joyNum)
    diagnostics.watch(isHere)
    if isHere == 1:
        cnt = c_int(0) # must be of type c_int!
        _glfw.glfwGetJoystickAxes.restype = POINTER(c_float) # VERY important!
        joy = _glfw.glfwGetJoystickAxes(joyNum, byref(cnt))
        diagnostics.watch(joy[0]) # this appears to be the steering axe
        diagnostics.watch(joy[1]) # this appears to be the two pedals combined in one axe
    # from here I will do sth like:
    windll.user32.GetCursorPos(byref(pt))
    mouse_y = pt.y
    y_m = (mouse_y - (screen_y / 2)) * sensitivity / 0.66
    vJoy[0].x = joy[0]
    vJoy[0].y = joy[1]
    vJoy[0].z = y_m
</code>```

答:
Not a solution to your problem but :

A python module is available for GLFW : glfw 1.4.0

As explained in the documentation, GLFW should be initialized by calling glfwInit before using glfwJoystickPresent. Maybe it would help

Body:
Recently, I have been playing a bus driving simulator. I have a racing wheel, which doesn't have a clutch pedal, so I searched for a way to adapt the mouse to act as a joystick with clutch, brake and gas. I found a solution with vJoy and FreePIE - Programmable Input Emulator. I found an example, which works perfectly for the mouse:

#Title         :OMSI 2 Freepie Mouse (Edited Mjoy vJoy FreePIE python script)
#Version       :0.1 (2016-03-22)
#Author        :snp, NEMOROSUS
#Description   :FreePIE python script for OMSI 2 mouse controls such as acceleration, steering and clutch control that is more accurate that the built-in one.

import time
from System import Int16
from ctypes import windll, Structure, c_ulong, byref, CDLL

class POINT(Structure):
_fields_ = [("x", c_ulong), ("y", c_ulong)]

if starting:
vJoy0_stat = 1
vJoy[0].x = 0
vJoy[0].y = 0
vJoy[0].z = 0
x = 0
y = 0
z = 0
mouse_x = 0
mouse_y = 0
mouse_z = 0
mouse_x_locked = 0
mouse_y_locked = 0
x_m = 0
y_m = 0
axis_max = 16448
screen_x = windll.user32.GetSystemMetrics(0)
screen_y = windll.user32.GetSystemMetrics(1)
pt = POINT()
sequence = 0
system.setThreadTiming(TimingTypes.HighresSystemTimer)
system.threadExecutionInterval = 1

z += mouse.wheel * 10

# X/Y axis centering

#if keyboard.getKeyDown(Key.Space):
#windll.user32.SetCursorPos((screen_x / 2),(screen_y / 2))

# Mjoy vJoy

# Turn VJoy on/off

if keyboard.getPressed(Key.K):
if sequence == 0:
  vJoy0_stat = 0
elif sequence == 1:
  vJoy0_stat = 1

sequence = sequence + 1
if sequence > 1:
  sequence = 0

if vJoy0_stat == 1:
windll.user32.GetCursorPos(byref(pt))
mouse_x = pt.x
mouse_y = pt.y

sensitivity = 28
x_m = (mouse_x - (screen_x / 2)) * sensitivity
y_m = (mouse_y - (screen_y / 2)) * sensitivity / 0.66
x_both = x_m + x
y_both = y_m + y
x_keyb_sensitivity = 350
y_keyb_sensitivity = 350

if x_m > axis_max:
  x_m = axis_max

if x_m < - axis_max:
  x_m = - axis_max

if y_m > axis_max:
  y_m = axis_max

if y_m < - axis_max:
  y_m = - axis_max

if x > axis_max:
  x = axis_max

if x < - axis_max:
  x = - axis_max

if y > axis_max:
  y = axis_max

if y < - axis_max:
  y = - axis_max

if z > axis_max:
  z = axis_max

if z < - axis_max:
  z = - axis_max

if x_both > axis_max:
  x_both = axis_max

if x_both < - axis_max:
  x_both = - axis_max

if y_both > axis_max:
  y_both = axis_max

if y_both < - axis_max:
  y_both = - axis_max

vJoy[0].x = x_m + x
vJoy[0].y = y_m + y
vJoy[0].z = z

# Diag

diagnostics.watch(screen_x)
diagnostics.watch(screen_y)
diagnostics.watch(mouse_x)
diagnostics.watch(mouse_y)
diagnostics.watch(mouse_x_locked)
diagnostics.watch(mouse_y_locked)
diagnostics.watch(vJoy[0].x)
diagnostics.watch(vJoy[0].y)
diagnostics.watch(vJoy[0].z)

I am very new to Python so I started googling for a solution in terms of how to convert the two-pedal Logitech wheel into a three-pedal wheel. I came up with the idea to use vJoy as my "final" joystick. I planned to feed it up with all the axis from the wheel and the Y-axe from the mouse, which will act as the clutch. So, after searching for a solution, I added this piece of Python code:

from ctypes import CDLL

_glfw = CDLL("path_to_FreePIE_installation\\plugins\\lib-mingw-w64\\glfw3.dll")
joyNum = 0
isHere = _glfw.glfwJoystickPresent(joyNum)
diagnostics.watch(isHere)
joyName = _glfw.glfwGetJoystickName(joyNum)
diagnostics.watch(joyName)
#joy = _glfw.glfwGetJoystickAxes(0)
#joy = _glfw.glfwGetJoystickButtons(0)
#diagnostics.watch(joy)

I took the idea from this documentation and this documentation. They say, that joyNum should be between 0 and 15. I tried every single number between 0 and 15 and even with 16 and 17. Every time, isHere is 0 although I have connected the wheel to one of the three USB-ports of my laptop. I tried to attach it to all them three with the same result. _glfw.glfwGetJoystickName(joyNum) is also giving me 0 every time. Can somebody help me to debug this? I don't understand why it can't find the wheel. It is not a problem with the driver because I can play games with no problem right now - the wheel is working normally.

When I try to call _glfw.glfwGetJoystickAxes(0) or _glfw.glfwGetJoystickButtons(0) - FreePIE crashes and when I debug it with VS2010, the exception message is: "Attempted to read or write protected memory. This is often an indication that another memory is corrupt."

EDIT:

I took a closer look at another documentation and replaced the code I added with this one:

from ctypes import CDLL, POINTER, c_float, c_int

glfw = CDLL("path_to_FreePIE_installation\\plugins\\lib-mingw-w64\\glfw3.dll")
joyNum = 0
isHere = _glfw.glfwJoystickPresent(joyNum)
diagnostics.watch(isHere)
joyName = _glfw.glfwGetJoystickName(joyNum)
diagnostics.watch(joyName)
cnt = c_int(0)
_glfw.glfwGetJoystickAxes.restype = POINTER(c_float)
joy = _glfw.glfwGetJoystickAxes(0, byref(cnt))
diagnostics.watch(joy)
axes = [joy[i].value for i in range(cnt)]
diagnostics.watch(cnt)
diagnostics.watch(axes)

Now the script is not run at all and I see the following error in FreePIE's console:

range() integer end argument expected, got c_long.
The error occurs on this line:
axes = [joy[i].value for i in range(cnt)]

I am confused. Here they have shown an example on how to get the axes values. This is the snippet from their site:

def glfwGetJoystickAxes(joy):
count = c_int(0)
_glfw.glfwGetJoystickAxes.restype = POINTER(c_float)
c_axes = _glfw.glfwGetJoystickAxes(joy, byref(count))
axes = [c_axes[i].value for i in range(count)]

As you can see here, the count is of type c_int and they give it to range() and they say it should work. Or maybe joy[i].value in my code snippet is of type c_long and that is the case?

Any help will be greatly appreciated! Thanks!

EDIT2:

For anyone, who may fall into such a situation. This is the code, which did the job for me:

if starting:
    # ...
    _glfw.glfwInit() # this is VERY important!
    joyNum = 1 # not 0, because the mouse appears to be joystick No 0
    # ...
if vJoy0_stat == 1: # the main loop
    # ...
    isHere = _glfw.glfwJoystickPresent(joyNum)
    diagnostics.watch(isHere)
    if isHere == 1:
        cnt = c_int(0) # must be of type c_int!
        _glfw.glfwGetJoystickAxes.restype = POINTER(c_float) # VERY important!
        joy = _glfw.glfwGetJoystickAxes(joyNum, byref(cnt))
        diagnostics.watch(joy[0]) # this appears to be the steering axe
        diagnostics.watch(joy[1]) # this appears to be the two pedals combined in one axe
    # from here I will do sth like:
    windll.user32.GetCursorPos(byref(pt))
    mouse_y = pt.y
    y_m = (mouse_y - (screen_y / 2)) * sensitivity / 0.66
    vJoy[0].x = joy[0]
    vJoy[0].y = joy[1]
    vJoy[0].z = y_m


来源: stackexchange

问:
input (a+b)**2 , output a*a + a*b + b*a + b*b
Is it possible to calculate (a+b)**2 such that the output is a*a + a*b + b*a + b*b (instead of a*a + 2*a*b + b*b)?

I tried it with:

```<code>a, b = sympy.symbols('a, b')

expr = sympy.expand((a + b)**2)
</code>```

but then the output is a*a + 2*a*b + b*b.

答:
Make your symbols non-commutative:</p>

```<code>>>> a, b = sympy.symbols('a, b', commutative=False)
>>> sympy.expand((a + b)**2)
a*b + a**2 + b*a + b**2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to calculate (a+b)**2 such that the output is a*a + a*b + b*a + b*b (instead of a*a + 2*a*b + b*b)?

I tried it with:

a, b = sympy.symbols('a, b')

expr = sympy.expand((a + b)**2)

but then the output is a*a + 2*a*b + b*b.

Body:
Make your symbols non-commutative:

>>> a, b = sympy.symbols('a, b', commutative=False)
>>> sympy.expand((a + b)**2)
a*b + a**2 + b*a + b**2


问:
Suggestions for speeding up LEFT JOIN in MySQL
I have a tabled named usr_data with 40,000 or so records that I want to left join with the user's organization data (roughly 1000 records) via a select in a join, obviously this is really slow (up to 150 seconds).

I was wondering if there were any ways to speed this up? Unfortunately this is the speediest query for the sub-select in the join.

My Query

```<code>    SELECT  usr_data.usr_id,usr_data.login,orgus.title FROM usr_data
    LEFT JOIN (
        SELECT object_reference.ref_id,rbac_ua.usr_id,object_data.obj_id,object_data.title
        FROM rbac_ua
        JOIN rbac_fa ON rbac_fa.rol_id = rbac_ua.rol_id
        JOIN object_reference ON rbac_fa.parent = object_reference.ref_id
        JOIN object_data ON object_data.obj_id = object_reference.obj_id
        JOIN object_data role ON role.obj_id = rbac_ua.rol_id
        WHERE object_data.type = 'orgu') as orgus on orgus.usr_id = usr_data.usr_id
    WHERE usr_data.usr_id > 0 AND usr_data.login <> "anonymous"
</code>```

Describe of Query

```<code>+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+
| id   | select_type | table            | type   | possible_keys         | key     | key_len | ref                            | rows | Extra                    |
+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+
|    1 | SIMPLE      | usr_data         | range  | PRIMARY,i1_idx        | PRIMARY | 4       | NULL                           | 8148 | Using where              |
|    1 | SIMPLE      | rbac_ua          | ref    | PRIMARY,i1_idx,i2_idx | PRIMARY | 4       | ildCPC.usr_data.usr_id         |    2 | Using where; Using index |
|    1 | SIMPLE      | rbac_fa          | ref    | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.rbac_ua.rol_id          |    1 | Using where; Using index |
|    1 | SIMPLE      | role             | eq_ref | PRIMARY               | PRIMARY | 4       | ildCPC.rbac_ua.rol_id          |    1 | Using index              |
|    1 | SIMPLE      | object_reference | eq_ref | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.rbac_fa.parent          |    1 | Using where              |
|    1 | SIMPLE      | object_data      | eq_ref | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.object_reference.obj_id |    1 | Using where              |
+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+
</code>```

usr_data table

```<code>+----------------------+---------------+------+-----+---------+-------+
| Field                | Type          | Null | Key | Default | Extra |
+----------------------+---------------+------+-----+---------+-------+
| usr_id               | int(11)       | NO   | PRI | 0       |       |
| login                | varchar(80)   | YES  | MUL | NULL    |       |
| passwd               | varchar(80)   | YES  |     | NULL    |       |
| firstname            | varchar(32)   | YES  |     | NULL    |       |
| lastname             | varchar(32)   | YES  |     | NULL    |       |
| title                | varchar(32)   | YES  |     | NULL    |       |
| gender               | char(1)       | YES  |     | m       |       |
| email                | varchar(80)   | YES  |     | NULL    |       |
</code>```

usr_data indexes

```<code>+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table    | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| usr_data |          0 | PRIMARY  |            1 | usr_id      | A         |       29354 |     NULL | NULL   |      | BTREE      |         |               |
| usr_data |          1 | i1_idx   |            1 | login       | A         |       29354 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i1_idx   |            2 | passwd      | A         |       29354 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i2_idx   |            1 | ext_account | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i2_idx   |            2 | auth_mode   | A         |           4 |     NULL | NULL   | YES  | BTREE      |         |               |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
</code>```

I've tried to make a temp-table for that SELECT in the LEFT JOIN but it didn't really speed it up any, the query takes up to 150 seconds currently, with a right join it brings it down to about 1 second. (It's the smaller table).

```<code>select * from object_data where type = 'orgu' returns 1058 rows.
</code>```

SHOW CREATE TABLE rbac_ua

```<code>+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| rbac_ua | CREATE TABLE `rbac_ua` (
  `usr_id` int(11) NOT NULL DEFAULT '0',
  `rol_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`usr_id`,`rol_id`),
  KEY `i1_idx` (`usr_id`),
  KEY `i2_idx` (`rol_id`),
  KEY `rol_id` (`rol_id`,`usr_id`),
  KEY `rol_usr` (`rol_id`,`usr_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
</code>```

SHOW CREATE TABLE rbac_fa

```<code>+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| rbac_fa | CREATE TABLE `rbac_fa` (
  `rol_id` int(11) NOT NULL DEFAULT '0',
  `parent` int(11) NOT NULL DEFAULT '0',
  `assign` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `protected` char(1) COLLATE utf8_unicode_ci DEFAULT 'n',
  PRIMARY KEY (`rol_id`,`parent`),
  KEY `i1_idx` (`parent`),
  KEY `parent` (`parent`,`rol_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
</code>```

SHOW CREATE TABLE object_data

```<code>+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                |
+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| object_data | CREATE TABLE `object_data` (
  `obj_id` int(11) NOT NULL DEFAULT '0',
  `type` char(4) COLLATE utf8_unicode_ci DEFAULT 'none',
  `title` char(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` char(128) COLLATE utf8_unicode_ci DEFAULT NULL,
  `owner` int(11) NOT NULL DEFAULT '0',
  `create_date` datetime DEFAULT NULL,
  `last_update` datetime DEFAULT NULL,
  `import_id` char(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`obj_id`),
  KEY `i1_idx` (`type`),
  KEY `i2_idx` (`title`),
  KEY `i4_idx` (`import_id`),
  FULLTEXT KEY `i3_idx` (`title`,`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
</code>```

SHOW CREATE TABLE object_reference

```<code>+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table            | Create Table                                                                                |
+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| object_reference | CREATE TABLE `object_reference` (
  `ref_id` int(11) NOT NULL DEFAULT '0',
  `obj_id` int(11) NOT NULL DEFAULT '0',
  `deleted` datetime DEFAULT NULL,
  PRIMARY KEY (`ref_id`),
  KEY `i1_idx` (`obj_id`),
  KEY `i2_idx` (`deleted`),
  KEY `obj_id` (`obj_id`,`ref_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
</code>```

If i'm missing any useful information, please let me know.

Thanks in Advance.

答:
From the EXPLAIN, I see that the Optimizer decided that "LEFT" had no impact.  So it removed it.  Then it decided that the "derived table" could be turned into a JOIN.  You could have done all that.

But the real problem in performance is that the important part of the filtering is on type = 'orgu', but that is buried in the 'last' table.

(Henceforth I am guessing due to the lack of SHOW CREATE TABLE for every table.  And DESCRIBE is not as descriptive ad SHOW CREATE.)

Let's look at this:

```<code>SELECT  ud.usr_id, ud.login, od.title
    FROM  object_data AS od
    JOIN  object_reference AS r  ON od.obj_id = r.obj_id
    JOIN  rbac_fa AS rfa  ON rfa.parent = r.ref_id
    JOIN  rbac_ua AS rua  ON rfa.rol_id = rua.rol_id
    JOIN  usr_data AS ud  ON ud.usr_id = rua.usr_id
     -- unnec?:  JOIN  object_data role  ON role.obj_id = rua.rol_id
    WHERE  od.type = 'orgu'
      AND  ud.usr_id > 0
      AND  ud.login <> "anonymous"
</code>```

I proffer it as being more efficient after adding the indexes below.  This is likely to be the case if type = 'orgu' is sufficiently selective.

Note that role adds nothing to the query other than verifying that a role does exist for the given obj_id.

Indexes needed so that it can start with type = 'orgu':

```<code>object_data: INDEX(type)
object_reference:  INDEX(obj_id, ref_id)  -- (covering, too)
rbac_fa:  INDEX(parent, rol_id)  -- (covering, too)
rbac_ua:  INDEX(rol_id, usr_id)  -- (covering, too)
</code>```

If that does not help, please provide EXPLAIN SELECT ... of the result.  And tell us how many rows of object_data have type=orgu.

Body:
I have a tabled named usr_data with 40,000 or so records that I want to left join with the user's organization data (roughly 1000 records) via a select in a join, obviously this is really slow (up to 150 seconds).

I was wondering if there were any ways to speed this up? Unfortunately this is the speediest query for the sub-select in the join.

My Query

    SELECT  usr_data.usr_id,usr_data.login,orgus.title FROM usr_data
    LEFT JOIN (
        SELECT object_reference.ref_id,rbac_ua.usr_id,object_data.obj_id,object_data.title
        FROM rbac_ua
        JOIN rbac_fa ON rbac_fa.rol_id = rbac_ua.rol_id
        JOIN object_reference ON rbac_fa.parent = object_reference.ref_id
        JOIN object_data ON object_data.obj_id = object_reference.obj_id
        JOIN object_data role ON role.obj_id = rbac_ua.rol_id
        WHERE object_data.type = 'orgu') as orgus on orgus.usr_id = usr_data.usr_id
    WHERE usr_data.usr_id > 0 AND usr_data.login <> "anonymous"

Describe of Query

+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+
| id   | select_type | table            | type   | possible_keys         | key     | key_len | ref                            | rows | Extra                    |
+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+
|    1 | SIMPLE      | usr_data         | range  | PRIMARY,i1_idx        | PRIMARY | 4       | NULL                           | 8148 | Using where              |
|    1 | SIMPLE      | rbac_ua          | ref    | PRIMARY,i1_idx,i2_idx | PRIMARY | 4       | ildCPC.usr_data.usr_id         |    2 | Using where; Using index |
|    1 | SIMPLE      | rbac_fa          | ref    | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.rbac_ua.rol_id          |    1 | Using where; Using index |
|    1 | SIMPLE      | role             | eq_ref | PRIMARY               | PRIMARY | 4       | ildCPC.rbac_ua.rol_id          |    1 | Using index              |
|    1 | SIMPLE      | object_reference | eq_ref | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.rbac_fa.parent          |    1 | Using where              |
|    1 | SIMPLE      | object_data      | eq_ref | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.object_reference.obj_id |    1 | Using where              |
+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+

usr_data table

+----------------------+---------------+------+-----+---------+-------+
| Field                | Type          | Null | Key | Default | Extra |
+----------------------+---------------+------+-----+---------+-------+
| usr_id               | int(11)       | NO   | PRI | 0       |       |
| login                | varchar(80)   | YES  | MUL | NULL    |       |
| passwd               | varchar(80)   | YES  |     | NULL    |       |
| firstname            | varchar(32)   | YES  |     | NULL    |       |
| lastname             | varchar(32)   | YES  |     | NULL    |       |
| title                | varchar(32)   | YES  |     | NULL    |       |
| gender               | char(1)       | YES  |     | m       |       |
| email                | varchar(80)   | YES  |     | NULL    |       |

usr_data indexes

+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table    | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| usr_data |          0 | PRIMARY  |            1 | usr_id      | A         |       29354 |     NULL | NULL   |      | BTREE      |         |               |
| usr_data |          1 | i1_idx   |            1 | login       | A         |       29354 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i1_idx   |            2 | passwd      | A         |       29354 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i2_idx   |            1 | ext_account | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i2_idx   |            2 | auth_mode   | A         |           4 |     NULL | NULL   | YES  | BTREE      |         |               |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

I've tried to make a temp-table for that SELECT in the LEFT JOIN but it didn't really speed it up any, the query takes up to 150 seconds currently, with a right join it brings it down to about 1 second. (It's the smaller table).

select * from object_data where type = 'orgu' returns 1058 rows.

SHOW CREATE TABLE rbac_ua

+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| rbac_ua | CREATE TABLE `rbac_ua` (
  `usr_id` int(11) NOT NULL DEFAULT '0',
  `rol_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`usr_id`,`rol_id`),
  KEY `i1_idx` (`usr_id`),
  KEY `i2_idx` (`rol_id`),
  KEY `rol_id` (`rol_id`,`usr_id`),
  KEY `rol_usr` (`rol_id`,`usr_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

SHOW CREATE TABLE rbac_fa

+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| rbac_fa | CREATE TABLE `rbac_fa` (
  `rol_id` int(11) NOT NULL DEFAULT '0',
  `parent` int(11) NOT NULL DEFAULT '0',
  `assign` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `protected` char(1) COLLATE utf8_unicode_ci DEFAULT 'n',
  PRIMARY KEY (`rol_id`,`parent`),
  KEY `i1_idx` (`parent`),
  KEY `parent` (`parent`,`rol_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

SHOW CREATE TABLE object_data

+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                |
+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| object_data | CREATE TABLE `object_data` (
  `obj_id` int(11) NOT NULL DEFAULT '0',
  `type` char(4) COLLATE utf8_unicode_ci DEFAULT 'none',
  `title` char(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` char(128) COLLATE utf8_unicode_ci DEFAULT NULL,
  `owner` int(11) NOT NULL DEFAULT '0',
  `create_date` datetime DEFAULT NULL,
  `last_update` datetime DEFAULT NULL,
  `import_id` char(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`obj_id`),
  KEY `i1_idx` (`type`),
  KEY `i2_idx` (`title`),
  KEY `i4_idx` (`import_id`),
  FULLTEXT KEY `i3_idx` (`title`,`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

SHOW CREATE TABLE object_reference

+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table            | Create Table                                                                                |
+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| object_reference | CREATE TABLE `object_reference` (
  `ref_id` int(11) NOT NULL DEFAULT '0',
  `obj_id` int(11) NOT NULL DEFAULT '0',
  `deleted` datetime DEFAULT NULL,
  PRIMARY KEY (`ref_id`),
  KEY `i1_idx` (`obj_id`),
  KEY `i2_idx` (`deleted`),
  KEY `obj_id` (`obj_id`,`ref_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

If i'm missing any useful information, please let me know.

Thanks in Advance.

Body:
From the EXPLAIN, I see that the Optimizer decided that "LEFT" had no impact.  So it removed it.  Then it decided that the "derived table" could be turned into a JOIN.  You could have done all that.

But the real problem in performance is that the important part of the filtering is on type = 'orgu', but that is buried in the 'last' table.

(Henceforth I am guessing due to the lack of SHOW CREATE TABLE for every table.  And DESCRIBE is not as descriptive ad SHOW CREATE.)

Let's look at this:

SELECT  ud.usr_id, ud.login, od.title
    FROM  object_data AS od
    JOIN  object_reference AS r  ON od.obj_id = r.obj_id
    JOIN  rbac_fa AS rfa  ON rfa.parent = r.ref_id
    JOIN  rbac_ua AS rua  ON rfa.rol_id = rua.rol_id
    JOIN  usr_data AS ud  ON ud.usr_id = rua.usr_id
     -- unnec?:  JOIN  object_data role  ON role.obj_id = rua.rol_id
    WHERE  od.type = 'orgu'
      AND  ud.usr_id > 0
      AND  ud.login <> "anonymous"

I proffer it as being more efficient after adding the indexes below.  This is likely to be the case if type = 'orgu' is sufficiently selective.

Note that role adds nothing to the query other than verifying that a role does exist for the given obj_id.

Indexes needed so that it can start with type = 'orgu':

object_data: INDEX(type)
object_reference:  INDEX(obj_id, ref_id)  -- (covering, too)
rbac_fa:  INDEX(parent, rol_id)  -- (covering, too)
rbac_ua:  INDEX(rol_id, usr_id)  -- (covering, too)

If that does not help, please provide EXPLAIN SELECT ... of the result.  And tell us how many rows of object_data have type=orgu.


问:
Multidimensional associative array of arrays
Why will this not push back or add to the end?

I have tried both methods.

```<code>class Router
{
    public function __construct()
    {
        $this->routes['GET'] = [];
        $this->routes['POST'] = [];
    }

    public function handle($request)
    {
        echo count($this->routes['GET']) . "<br/>";  // outputs '0'.. why??
    }

    protected function addRoute($methods, $uri, $action)
    {
        #array_push($this->routes['GET'], 'TEST'); // Tried this as well
        $this->routes['GET'][] = 'test';
        echo count($this->routes['GET']) . "<br/>";  // outputs '1'
    }

    private $routes = [];
}
</code>```

After I execute addRoute and then check the size of $this->routes[$methods] using count() in handle($request), it indicates 0.

答:
Solved...

Ahh, the dreaded Singleton got me.  For some reason, the same object was not being used.  I have removed the Singleton pattern from my application.

Body:
Why will this not push back or add to the end?

I have tried both methods.

class Router
{
    public function __construct()
    {
        $this->routes['GET'] = [];
        $this->routes['POST'] = [];
    }

    public function handle($request)
    {
        echo count($this->routes['GET']) . "
";  // outputs '0'.. why??
    }

    protected function addRoute($methods, $uri, $action)
    {
        #array_push($this->routes['GET'], 'TEST'); // Tried this as well
        $this->routes['GET'][] = 'test';
        echo count($this->routes['GET']) . "
";  // outputs '1'
    }

    private $routes = [];
}

After I execute addRoute and then check the size of $this->routes[$methods] using count() in handle($request), it indicates 0.


问:
Telnet is not recognized command when cmd.exe is started from Process.Start in C#
I have already switch on the telnet option on control panel - program/features.
Though telnet worked fine manually, but when I run below from my C# library, I am getting this error :

"'telnet' is not recognized as an internal or external command,
  operable program or batch file."

This is the code I use to start Telnet:

```<code>Process.Start("cmd", "/k telnet")
</code>```

What makes the difference between this and running it from the command prompt manually and how do I overcome this difference?

答:
On installing Telnet Client via Control Panel - Programs and Features - Turn Windows features on or off there is installed telnet.exe into directory %SystemRoot%\System32.

The directory %SystemRoot%\System32 is for 64-bit applications on 64-bit Windows. Therefore the installed executable telnet.exe is also the 64-bit version. This directory contains also the 64-bit version of cmd.exe.

System environment variable PATH contains %SystemRoot%\System32 which is responsible for finding %SystemRoot%\System32\cmd.exe and %SystemRoot%\System32\telnet.exe when being executed without file extension and without path.

But there is additionally the directory %SystemRoot%\SysWOW64 for 32-bit applications containing the 32-bit versions of the executables.

Microsoft explains with the documentation pages WOW64 Implementation Details and File System Redirector how a file system access to %SystemRoot%\System32 by a 32-bit application is redirected automatically to %SystemRoot%\SysWOW64.

There is no 32-bit version of telnet.exe installed into %SystemRoot%\SysWOW64 on installing Telnet Client.

So what happens on:

```<code>Process.Start("cmd", "/k telnet")
</code>```

When the C# library is compiled as 64-bit library used by a 64-bit application, 64-bit Windows finds and starts %SystemRoot%\System32\cmd.exe which finds and then starts %SystemRoot%\System32\telnet.exe.

But when the C# library is compiled as 32-bit library used by a 32-bit application, 64-bit Windows finds and starts via file system redirector %SystemRoot%\SysWOW64\cmd.exe which cannot find telnet.* with a file extension listed in environment variable PATHEXT in current directory or any directory of environment variable PATH because there is no file telnet.exe in directory %SystemRoot%\SysWOW64.

The best solution is definitely to use a static (or dynamic) telnet library in the C# library to be independent on telnet.exe as suggested by Panagiotis Kanavos. In my point of view it is a shame for every C# programmer using external executables via a process call for which C# code can be quite easily also written by the programmer. Using any world wide web search engine with the search term C# telnet returns lots of pages with solutions, for example C# Telnet Library on Stack Overflow.

Of course it is also possible to get first value of environment variable SystemRoot using GetEnvironmentVariable method to get path to Windows directory, or even better using GetWindowsDirectory or GetSystemWindowsDirectory method.

Then concatenate this string value with "\\System32\\telnet.exe" to a new string and check if the file with that full path exists using File.Exists method. If that file exists on 32-bit Windows with 32-bit version of telnet.exe installed if C# application is also a 32-bit application or on 64-bit Windows with 64-bit telnet.exe installed if C# application is a 64-bit application, then this file name with full path and file extension can be used in a process call.

Otherwise concatenate the Windows directory path with "\\Sysnative\\telnet.exe" and check if file with that full path exists. If this is true on 64-bit Windows with 64-bit version of telnet.exe installed if C# application is a 32-bit application, it would be possible to run from within 32-bit application the 64-bit telnet client executable using this path.

But if that fails also, telnet.exe is not installed at all which is the reason why usage of telnet.exe from within a C# code application is in general not advisable.

Honestly, I don't understand why to have code in a C# library which just starts a command process executing telnet.exe without options and therefore requiring user input and which keeps the command process running after telnet client session terminated. The C# library function can be replaced by a shortcut to telnet.exe on Windows desktop or in Windows start menu of the user.

Body:
I have already switch on the telnet option on control panel - program/features.
Though telnet worked fine manually, but when I run below from my C# library, I am getting this error :

"'telnet' is not recognized as an internal or external command,
  operable program or batch file."

This is the code I use to start Telnet:

Process.Start("cmd", "/k telnet")

What makes the difference between this and running it from the command prompt manually and how do I overcome this difference?

Body:
On installing Telnet Client via Control Panel - Programs and Features - Turn Windows features on or off there is installed telnet.exe into directory %SystemRoot%\System32.

The directory %SystemRoot%\System32 is for 64-bit applications on 64-bit Windows. Therefore the installed executable telnet.exe is also the 64-bit version. This directory contains also the 64-bit version of cmd.exe.

System environment variable PATH contains %SystemRoot%\System32 which is responsible for finding %SystemRoot%\System32\cmd.exe and %SystemRoot%\System32\telnet.exe when being executed without file extension and without path.

But there is additionally the directory %SystemRoot%\SysWOW64 for 32-bit applications containing the 32-bit versions of the executables.

Microsoft explains with the documentation pages WOW64 Implementation Details and File System Redirector how a file system access to %SystemRoot%\System32 by a 32-bit application is redirected automatically to %SystemRoot%\SysWOW64.

There is no 32-bit version of telnet.exe installed into %SystemRoot%\SysWOW64 on installing Telnet Client.

So what happens on:

Process.Start("cmd", "/k telnet")

When the C# library is compiled as 64-bit library used by a 64-bit application, 64-bit Windows finds and starts %SystemRoot%\System32\cmd.exe which finds and then starts %SystemRoot%\System32\telnet.exe.

But when the C# library is compiled as 32-bit library used by a 32-bit application, 64-bit Windows finds and starts via file system redirector %SystemRoot%\SysWOW64\cmd.exe which cannot find telnet.* with a file extension listed in environment variable PATHEXT in current directory or any directory of environment variable PATH because there is no file telnet.exe in directory %SystemRoot%\SysWOW64.

The best solution is definitely to use a static (or dynamic) telnet library in the C# library to be independent on telnet.exe as suggested by Panagiotis Kanavos. In my point of view it is a shame for every C# programmer using external executables via a process call for which C# code can be quite easily also written by the programmer. Using any world wide web search engine with the search term C# telnet returns lots of pages with solutions, for example C# Telnet Library on Stack Overflow.

Of course it is also possible to get first value of environment variable SystemRoot using GetEnvironmentVariable method to get path to Windows directory, or even better using GetWindowsDirectory or GetSystemWindowsDirectory method.

Then concatenate this string value with "\\System32\\telnet.exe" to a new string and check if the file with that full path exists using File.Exists method. If that file exists on 32-bit Windows with 32-bit version of telnet.exe installed if C# application is also a 32-bit application or on 64-bit Windows with 64-bit telnet.exe installed if C# application is a 64-bit application, then this file name with full path and file extension can be used in a process call.

Otherwise concatenate the Windows directory path with "\\Sysnative\\telnet.exe" and check if file with that full path exists. If this is true on 64-bit Windows with 64-bit version of telnet.exe installed if C# application is a 32-bit application, it would be possible to run from within 32-bit application the 64-bit telnet client executable using this path.

But if that fails also, telnet.exe is not installed at all which is the reason why usage of telnet.exe from within a C# code application is in general not advisable.

Honestly, I don't understand why to have code in a C# library which just starts a command process executing telnet.exe without options and therefore requiring user input and which keeps the command process running after telnet client session terminated. The C# library function can be replaced by a shortcut to telnet.exe on Windows desktop or in Windows start menu of the user.

ContentLicense: CC BY-SA 4.0


问:
Spring MVC using hibernate Sequence doesn't exist
UserBean Class

```<code>@Entity
@Table(name="users")
public class UserBean {

    @Id
    @GeneratedValue(strategy =GenerationType.AUTO)
    @Column(name="ID")
    private Integer id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "EMAIL")
    private String email;

    @Column(name = "AGE")
    private int age;

    /**
     * @return the id
     */
    public Integer getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }

    /**
     * @param age the age to set
     */
    public void setAge(int age) {
        this.age = age;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("UserBean [id=").append(id).append(", name=")
                .append(name).append(", email=").append(email).append(", age=")
                .append(age).append("]");
        return builder.toString();
    }

}
</code>```

I am getting  ORA:02289 Sequence doesn't exist

Here is hibernate.cfg.xml

```<code><hibernate-configuration>
    <session-factory>
        <mapping class="com.abc.bean.UserBean" />
    </session-factory>
</hibernate-configuration>
</code>```

Dispatcher package scan

```<code><context:component-scan base-package="com.abc.controller" />
<context:component-scan base-package="com.abc.dao.impl" />
<mvc:annotation-driven />
</code>```

I have tried the same thing in another laptop and it worked, what is causing the problem? Earlier, I tried to generate a sequence but it didn't worked well

Sql command executed:
create table users(id int primary key,name varchar(20),email varchar(20),age int);

答:
hibernate use sequence for oracle db if you use GenerationType.AUTO (default global sequence name hibernate_sequence) . You should create sequence and configure it in entity mapping , like :

```<code>@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_generator")
@SequenceGenerator(name="user_generator", sequenceName = "user_seq")
@Column(name="ID",allocationSize = 1)
private Integer id;
</code>```

Body:
UserBean Class

@Entity
@Table(name="users")
public class UserBean {

    @Id
    @GeneratedValue(strategy =GenerationType.AUTO)
    @Column(name="ID")
    private Integer id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "EMAIL")
    private String email;

    @Column(name = "AGE")
    private int age;

    /**
     * @return the id
     */
    public Integer getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }

    /**
     * @param age the age to set
     */
    public void setAge(int age) {
        this.age = age;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("UserBean [id=").append(id).append(", name=")
                .append(name).append(", email=").append(email).append(", age=")
                .append(age).append("]");
        return builder.toString();
    }

}

I am getting  ORA:02289 Sequence doesn't exist

Here is hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>
        <mapping class="com.abc.bean.UserBean" />
    </session-factory>
</hibernate-configuration>

Dispatcher package scan

<context:component-scan base-package="com.abc.controller" />
<context:component-scan base-package="com.abc.dao.impl" />
<mvc:annotation-driven />

I have tried the same thing in another laptop and it worked, what is causing the problem? Earlier, I tried to generate a sequence but it didn't worked well

Sql command executed:
create table users(id int primary key,name varchar(20),email varchar(20),age int);

Body:
hibernate use sequence for oracle db if you use GenerationType.AUTO (default global sequence name hibernate_sequence) . You should create sequence and configure it in entity mapping , like :

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_generator")
@SequenceGenerator(name="user_generator", sequenceName = "user_seq")
@Column(name="ID",allocationSize = 1)
private Integer id;


问:
Reduce execution time of prime number generator
I have to print numbers between two limits n and m, t times.

I created t variable, and two pointers n, m that points to reserved blocks of memory for t integer values.

I use pointers instead of array to do faster operations.

Outer for loop iterates for every test cases and increasing m and n pointers.

Inner for loop prints primes from m[i] to n[i].

Code

```<code>#include <stdio.h>
#include <stdlib.h>

int is_prime(int);

int main(void) {

    int t;
    int *n = malloc(sizeof(int) * t);
    int *m = malloc(sizeof(int) * t);

    scanf("%d", &t);
    for (int i = 0; i < t; i++, m++, n++) {
        scanf("%d %d", &m[i], &n[i]);
        for (int j = m[i]; j <= n[i]; j++) {
            if (is_prime(j)) {
                printf("%d\n", j);
            }
        }
        if (i < t - 1) printf("\n");
    }

    return 0;
}

int is_prime(int num)
{

    if (num <= 1) return 0;
    if (num % 2 == 0 && num > 2) return 0;

    for(int i = 3; i < num / 2; i+= 2){
         if (num % i == 0)
             return 0;
    }

    return 1;
}
</code>```

Problem: http://www.spoj.com/problems/PRIME1/

Code is correctly compiling on http://ideone.com but I'm giving "time limit exceeded" error when I'm trying submit this code on SPOJ. How can I reduce execution time of this prime number generator?

答:
You can even do it without using pointers or arrays    </p>

```<code>#include <stdio.h>
#include<math.h>

int is_prime(long n){
    if (n == 1 || n % 2 == 0)
        return 0;
    if (n == 2)
        return 1;
    for (long i = 3; i <= sqrt(n); i += 2) {
        if(n % i == 0)
            return 0;
    }
    return 1;
}
int main() {
    int t;
    scanf("%d",&t);
    while(t--) {
        long n, m;
        scanf("%ld %ld",&n,&m);

        for (long i = n; i <= m; i++) {
            if (is_prime(i) == 1)
            printf("%ld\n",i);
        }
    }
    return 0;
}
</code>```

Body:
I have to print numbers between two limits n and m, t times.

I created t variable, and two pointers n, m that points to reserved blocks of memory for t integer values.

I use pointers instead of array to do faster operations.

Outer for loop iterates for every test cases and increasing m and n pointers.

Inner for loop prints primes from m[i] to n[i].

Code

#include <stdio.h>
#include <stdlib.h>

int is_prime(int);

int main(void) {

    int t;
    int *n = malloc(sizeof(int) * t);
    int *m = malloc(sizeof(int) * t);

    scanf("%d", &t);
    for (int i = 0; i < t; i++, m++, n++) {
        scanf("%d %d", &m[i], &n[i]);
        for (int j = m[i]; j <= n[i]; j++) {
            if (is_prime(j)) {
                printf("%d\n", j);
            }
        }
        if (i < t - 1) printf("\n");
    }

    return 0;
}

int is_prime(int num)
{

    if (num <= 1) return 0;
    if (num % 2 == 0 && num > 2) return 0;

    for(int i = 3; i < num / 2; i+= 2){
         if (num % i == 0)
             return 0;
    }

    return 1;
}

Problem: http://www.spoj.com/problems/PRIME1/

Code is correctly compiling on http://ideone.com but I'm giving "time limit exceeded" error when I'm trying submit this code on SPOJ. How can I reduce execution time of this prime number generator?

Body:
You can even do it without using pointers or arrays

#include <stdio.h>
#include<math.h>

int is_prime(long n){
    if (n == 1 || n % 2 == 0)
        return 0;
    if (n == 2)
        return 1;
    for (long i = 3; i <= sqrt(n); i += 2) {
        if(n % i == 0)
            return 0;
    }
    return 1;
}
int main() {
    int t;
    scanf("%d",&t);
    while(t--) {
        long n, m;
        scanf("%ld %ld",&n,&m);

        for (long i = n; i <= m; i++) {
            if (is_prime(i) == 1)
            printf("%ld\n",i);
        }
    }
    return 0;
}


问:
Notice: Undefined offset: 1 in when making an array from $_post from checkbox being cheked
I have been struggling for days on this issue.  I have simplified my code to try and get the root issue. I am checking boxes on another page and returning post value into this one.

```<code><?php
if(!empty($_POST['checkbox'])){

            $selected=array($_POST['checkbox']);
                $count = count($_POST['checkbox']);
           echo "There are ".$count." checkboxe(s) are checked<br>";

            for ($q=0;$q<$count;$q++){

                print_r($selected[$q]);

}
}

?>
</code>```

I am getting this error:

```<code>  There are 5 checkboxe(s) are checked
 501
 Notice: Uninitialized string offset: 3 in F:\HTML\write to HTML table.php      on line 19

 Notice: Uninitialized string offset: 4 in F:\HTML\write to HTML table.php on line 19
 505
 Notice: Uninitialized string offset: 3 in F:\HTML\write to HTML table.php on line 19

 Notice: Uninitialized string offset: 4 in F:\HTML\write to HTML table.php on line 19
 516
 Notice: Uninitialized string offset: 3 in F:\HTML\write to HTML table.php on line 19

 Notice: Uninitialized string offset: 4 in F:\HTML\write to HTML table.php on line 19
 518
 Notice: Uninitialized string offset: 3 in F:\HTML\write to HTML table.php on line 19

 Notice: Uninitialized string offset: 4 in F:\HTML\write to HTML table.php on line 19
 529
 Notice: Uninitialized string offset: 3 in F:\HTML\write to HTML table.php on line 19

 Notice: Uninitialized string offset: 4 in F:\HTML\write to HTML table.php on line 19
</code>```

答:
You are putting $_POST['checkbox'] into another array, you need to parse It or you need to assign well $selected variable

try to change this:

```<code>print_r($selected[$q]);
</code>```

to this:

```<code>print_r($_POST['checkbox'][$q]);
</code>```

or you need to change how you set $selected editing into this:

```<code>$selected = $_POST['checkbox'];
</code>```

Body:
I have been struggling for days on this issue.  I have simplified my code to try and get the root issue. I am checking boxes on another page and returning post value into this one.

<?php
if(!empty($_POST['checkbox'])){

            $selected=array($_POST['checkbox']);
                $count = count($_POST['checkbox']);
           echo "There are ".$count." checkboxe(s) are checked
";

            for ($q=0;$q<$count;$q++){

                print_r($selected[$q]);

}
}

?>

I am getting this error:

  There are 5 checkboxe(s) are checked
 501
 Notice: Uninitialized string offset: 3 in F:\HTML\write to HTML table.php      on line 19

 Notice: Uninitialized string offset: 4 in F:\HTML\write to HTML table.php on line 19
 505
 Notice: Uninitialized string offset: 3 in F:\HTML\write to HTML table.php on line 19

 Notice: Uninitialized string offset: 4 in F:\HTML\write to HTML table.php on line 19
 516
 Notice: Uninitialized string offset: 3 in F:\HTML\write to HTML table.php on line 19

 Notice: Uninitialized string offset: 4 in F:\HTML\write to HTML table.php on line 19
 518
 Notice: Uninitialized string offset: 3 in F:\HTML\write to HTML table.php on line 19

 Notice: Uninitialized string offset: 4 in F:\HTML\write to HTML table.php on line 19
 529
 Notice: Uninitialized string offset: 3 in F:\HTML\write to HTML table.php on line 19

 Notice: Uninitialized string offset: 4 in F:\HTML\write to HTML table.php on line 19

Body:
You are putting $_POST['checkbox'] into another array, you need to parse It or you need to assign well $selected variable

try to change this:

print_r($selected[$q]);

to this:

print_r($_POST['checkbox'][$q]);

or you need to change how you set $selected editing into this:

$selected = $_POST['checkbox'];


问:
React Navigation: Dynamic Title Does Not Change
I am trying to dynamically change the title of my react-navigation navigation bar:

```<code>componentDidMount() {
  InteractionManager.runAfterInteractions(() =>
      this.props.navigation.setParams({ title:"New Title" });
  });
}
</code>```

Although I can verify this function is called, the navigation bar does not change to "New Title."

Am I passing the wrong object into the setParams() function?

答:
react navigation doesn't read the title from the params object. It uses the navigationOptions static property on the component.

You can set that property to a function:

```<code>static navigationOptions = ({navigation}) => {
    title: navigation.state.params.title
}
</code>```

Then when you set the param the title should change.

Body:
I am trying to dynamically change the title of my react-navigation navigation bar:

componentDidMount() {
  InteractionManager.runAfterInteractions(() =>
      this.props.navigation.setParams({ title:"New Title" });
  });
}

Although I can verify this function is called, the navigation bar does not change to "New Title."

Am I passing the wrong object into the setParams() function?

Body:
react navigation doesn't read the title from the params object. It uses the navigationOptions static property on the component.

You can set that property to a function:

static navigationOptions = ({navigation}) => {
    title: navigation.state.params.title
}

Then when you set the param the title should change.


问:
Angular - How can I mock an HTTP request?
I have a simple code which invokes a real HTTP request :

```<code>@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{person?.id}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor(public http: Http) {
     this.http.get('https://jsonplaceholder.typicode.com/posts/1')
     .map(res => res.json()).subscribe(res => {
        this.person = res;
     },()=>{},()=>console.log('complete'));
  }
}
</code>```

But now I want to mock the request so that it will fetch data from a file containing :

```<code>export arrFakeData:any = {id:1};
</code>```

I don't want to use a service . I want to mock the request.

Some examples shows to use XHRBackend and some shows how to extend the HTTP class,  but they doesn't say how can I force the data to retrieve

I know that I should use

```<code>  providers:[ /*{ provide: XHRBackend, useClass: MockBackend }*/]
</code>```

But I don't know how.

Question:

How can I mock http request and return (for GET) the array from arrFakeData ?

PLUNKER

答:
Personally, I would replace the this.http.get method call with an Observable.of so that you can continue programming against the same interface (Observable) without impacting the development of your components.

However, if you really want to do this then you will have to create a service that attaches a listener to all the incoming requests and returns an appropriate mock response using the tools provided by the @angular/http/testing module.

The service will look something as such:

```<code>import {Injectable} from "@angular/core";
import {MockBackend, MockConnection} from "@angular/http/testing";
import {arrFakeData} from "./fakeData";
import {ResponseOptions, Response} from "@angular/http";

@Injectable()
export class MockBackendService {
    constructor(
        private backend: MockBackend
    ) {}

    start(): void {
        this.backend.connections.subscribe((c: MockConnection) => {
            const URL = "https://jsonplaceholder.typicode.com/posts/1";

            if (c.request.url === URL) { // You can also check the method
                c.mockRespond(new Response(new ResponseOptions({
                    body: JSON.stringify(arrFakeData)
                })));
            }
        });
    }
}
</code>```

Once you have done this, you need to register all the services and make sure that the Http module is using the MockBackend instead of the XHRBackend.

```<code>@NgModule({
  imports: [BrowserModule, HttpModule,],
  declarations: [App],
  providers: [
    MockBackend,
    MockBackendService,
    BaseRequestOptions,
    {
      provide: Http,
      deps: [MockBackend, BaseRequestOptions],
      useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
        return new Http(backend, options);
      }
    }
  ],
  bootstrap: [App]
})
export class AppModule {
}
</code>```

Last but not least, you have to actually invoke the start method, which will make sure that you will actually receive the mock data from the MockBackend. In your AppComponent you can do the following.

```<code>constructor(public http: Http, public mockBackendService: MockBackendService) {
  this.mockBackendService.start();

  this.http.get('https://jsonplaceholder.typicode.com/posts/1')
    .map(res => res.json())
    .subscribe(res => {
      this.person = res;
    });
}
</code>```

I hope this helps! See the plunker for the full example. https://plnkr.co/edit/h111to5PxbI97FIyKGJZ?p=preview

Body:
I have a simple code which invokes a real HTTP request :

@Component({
  selector: 'my-app',
  template: `

Hello {{person?.id}}

  `,
})
export class App {
  name:string;
  constructor(public http: Http) {
     this.http.get('https://jsonplaceholder.typicode.com/posts/1')
     .map(res => res.json()).subscribe(res => {
        this.person = res;
     },()=>{},()=>console.log('complete'));
  }
}

But now I want to mock the request so that it will fetch data from a file containing :

export arrFakeData:any = {id:1};

I don't want to use a service . I want to mock the request.

Some examples shows to use XHRBackend and some shows how to extend the HTTP class,  but they doesn't say how can I force the data to retrieve

I know that I should use

  providers:[ /*{ provide: XHRBackend, useClass: MockBackend }*/]

But I don't know how.

Question:

How can I mock http request and return (for GET) the array from arrFakeData ?

PLUNKER

Body:
Personally, I would replace the this.http.get method call with an Observable.of so that you can continue programming against the same interface (Observable) without impacting the development of your components.

However, if you really want to do this then you will have to create a service that attaches a listener to all the incoming requests and returns an appropriate mock response using the tools provided by the @angular/http/testing module.

The service will look something as such:

import {Injectable} from "@angular/core";
import {MockBackend, MockConnection} from "@angular/http/testing";
import {arrFakeData} from "./fakeData";
import {ResponseOptions, Response} from "@angular/http";

@Injectable()
export class MockBackendService {
    constructor(
        private backend: MockBackend
    ) {}

    start(): void {
        this.backend.connections.subscribe((c: MockConnection) => {
            const URL = "https://jsonplaceholder.typicode.com/posts/1";

            if (c.request.url === URL) { // You can also check the method
                c.mockRespond(new Response(new ResponseOptions({
                    body: JSON.stringify(arrFakeData)
                })));
            }
        });
    }
}

Once you have done this, you need to register all the services and make sure that the Http module is using the MockBackend instead of the XHRBackend.

@NgModule({
  imports: [BrowserModule, HttpModule,],
  declarations: [App],
  providers: [
    MockBackend,
    MockBackendService,
    BaseRequestOptions,
    {
      provide: Http,
      deps: [MockBackend, BaseRequestOptions],
      useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
        return new Http(backend, options);
      }
    }
  ],
  bootstrap: [App]
})
export class AppModule {
}

Last but not least, you have to actually invoke the start method, which will make sure that you will actually receive the mock data from the MockBackend. In your AppComponent you can do the following.

constructor(public http: Http, public mockBackendService: MockBackendService) {
  this.mockBackendService.start();

  this.http.get('https://jsonplaceholder.typicode.com/posts/1')
    .map(res => res.json())
    .subscribe(res => {
      this.person = res;
    });
}

I hope this helps! See the plunker for the full example. https://plnkr.co/edit/h111to5PxbI97FIyKGJZ?p=preview


问:
How to return a default value for a generic parameter in a function in Swift?
I'm using generics to dynamically assign the type of the value that the response should be, at the call site of the function.

The function below is the only accessible method my FirebaseClient class has.

It is called in many different places.

To make sure the correct object is in the response, I insert what object I'm expecting at the call site of the function. Here is the catch. If I'm posting a value to database, I dont expect any response, and only care about error, but am forced to put an arbitrary type for param/argument, even though i know it will be nil for such cases.

How can I set a default value for generic parameter, so that no one could hypothetically come along and insert an object as response when they won't get one?

Hopefully the code speaks for itself and makes more sense than I did.

Other info:

Inside the method below, if its a GET request, I initialize T with the json response. As you see the generic has to conform to QueryType protocol, which just contains an initializer, so each object that is T, has an initializer to handle response in its own way.

```<code>func fireRequest<T: QueryType>(_ request: FirebaseRequest, completion: @escaping (_ data: [T]? = [], _ error: FirebaseError?) -> Void ) {

// setting default value to data param throws error.

}
</code>```

Successful use case:

```<code>client.fireRequest(FirebaseRequest.observe(path: path), completion: { (data: [User], error: FirebaseError? ) in

// Since I infer 'T' to be of type User, i can expect a collection of users, or single user as my response. This is what I want.

})
</code>```

Error Use case:

```<code>client.fireRequest(FirebaseRequest.setValue(path: path, value: locationData), completion: { (_, error: FirebaseError? ) in

// error: generic parameter 'T' could not be inferred.

// In this case, I am posting some data to database, so I dont expect a response, but putting underscore throws error.

})
</code>```

答:
I am not exactly sure what you are asking but you can use T() to generate the defualt value for the type.

As for the underscore it is because (_, FirebaseError?)->Void is not the same type as ([T], FirebaseError?)->Void. So your closure should be

```<code>{(_:[AnyObject]?, error: FirebaseError?) in code }
</code>```

If you want this to use generics you would need to define some function like

```<code>func errorCaseCompletetion<T>( _ : [T]?, error: FirebaseError?){
     //code
 }
</code>```

And then you just pass the function name as the completetion block.

Body:
I'm using generics to dynamically assign the type of the value that the response should be, at the call site of the function.

The function below is the only accessible method my FirebaseClient class has.

It is called in many different places.

To make sure the correct object is in the response, I insert what object I'm expecting at the call site of the function. Here is the catch. If I'm posting a value to database, I dont expect any response, and only care about error, but am forced to put an arbitrary type for param/argument, even though i know it will be nil for such cases.

How can I set a default value for generic parameter, so that no one could hypothetically come along and insert an object as response when they won't get one?

Hopefully the code speaks for itself and makes more sense than I did.

Other info:

Inside the method below, if its a GET request, I initialize T with the json response. As you see the generic has to conform to QueryType protocol, which just contains an initializer, so each object that is T, has an initializer to handle response in its own way.

func fireRequest<T: QueryType>(_ request: FirebaseRequest, completion: @escaping (_ data: [T]? = [], _ error: FirebaseError?) -> Void ) {

// setting default value to data param throws error.

}

Successful use case:

client.fireRequest(FirebaseRequest.observe(path: path), completion: { (data: [User], error: FirebaseError? ) in

// Since I infer 'T' to be of type User, i can expect a collection of users, or single user as my response. This is what I want.

})

Error Use case:

client.fireRequest(FirebaseRequest.setValue(path: path, value: locationData), completion: { (_, error: FirebaseError? ) in

// error: generic parameter 'T' could not be inferred.

// In this case, I am posting some data to database, so I dont expect a response, but putting underscore throws error.

})

Body:
I am not exactly sure what you are asking but you can use T() to generate the defualt value for the type.

As for the underscore it is because (_, FirebaseError?)->Void is not the same type as ([T], FirebaseError?)->Void. So your closure should be

{(_:[AnyObject]?, error: FirebaseError?) in code }

If you want this to use generics you would need to define some function like

func errorCaseCompletetion<T>( _ : [T]?, error: FirebaseError?){
     //code
 }

And then you just pass the function name as the completetion block.


问:
Multiple array using vector of vector
I want to insert multiple array using Vector of vector.

For that I/P is like this:

```<code>2   : Number of array ( can be vary )

3  1 2 3  :  3( size of array)  1 2 3( elements in array )

4  4 5 6 7  : 4( size of array) 4 5 6 7 ( elements in array)
</code>```

Then I need to perform some operation on it.

All the I/P is entered by user. Only its range is given.

```<code>2 <= No of array <= 10

1 <= Elements in array <= 1000000
</code>```

For above I tried following ways :

```<code>int main()
{
    int no_of_array, size;
    long int num;
    int j = 0;

    cin >> no_of_array;
</code>```

1st way :

```<code>vector < vector<int> > array_vector[no_of_array];
   while( no_of_array -- )
   {
        cin >>size;
        for( int i = 0; i < size ; i++ )
            {
                cin >> num;
                array_vector[j].push_back({num});
            }
            j++;
    }
  cout<< vector_array[1][2];    // Error
</code>```

2nd way :

```<code>vector< vector<int> > array_vector;
while( no_of_array --)
{
    cin >> size;
    for( int i = 0 ; i < size ; i++ )
    {
        cin >> num;
        array_vector[j].push_back(num);
    }
    j++;
 }
cout<< vector_array[1][2];     // Error
</code>```

3rd way :  ( Working )

```<code>vector<vector<int> > array_vector;
for( int i = 0 ; i < no_of_array ; i++ )
{
    cin >> size;
    vector<int> v;
    for( int j = 0 ; j < size ; j++ )
    {

        cin >> num;
        v.push_back(num);
    }
    array_vector.push_back(v);
}
cout<<array_vector[1][2];    // No Error
</code>```

Somewhere I read 3rd way of vector of vector is not suitable for competitive programming.  Why ??

What mistake I did while traversing the elements with 1st two approach ??

答:
You can try the following code</p>

```<code>int main(int argc,char* argv[])
{
    unsigned int num;
    int elm;
    unsigned int size;

    std::cout << "Enter the number of rows" << std::endl;
    std::cin >> num;
    std::vector<std::vector<int> > a(num,std::vector<int>(0,0));

    for(unsigned int i=0;i<num;i++)
    {
        std::cout  << "Enter the size of " << i+1 << "array:" << std::endl;
        std::cin >> size;

        for(unsigned int j=0;j<size;j++)
        {
            std::cout << "Enter the element" <<std::endl;
            std::cin >> elm;

            a[i].push_back(elm);
        }
    }

    for(unsigned int i=0;i<a.size();i++)
    {
        for(unsigned int j=0;j<a[i].size();j++)
        {
            std::cout << "Element at [" <<i<<"][" <<j <<"] is " << a[i][j] <<std::endl;
        }
    }

    return 0;
}
</code>```

Title: Multiple array using vector of vector

Body:
I want to insert multiple array using Vector of vector.

For that I/P is like this:

2   : Number of array ( can be vary )

3  1 2 3  :  3( size of array)  1 2 3( elements in array )

4  4 5 6 7  : 4( size of array) 4 5 6 7 ( elements in array)

Then I need to perform some operation on it.

All the I/P is entered by user. Only its range is given.

2 <= No of array <= 10

1 <= Elements in array <= 1000000

For above I tried following ways :

int main()
{
    int no_of_array, size;
    long int num;
    int j = 0;

    cin >> no_of_array;

1st way :

vector < vector<int> > array_vector[no_of_array];
   while( no_of_array -- )
   {
        cin >>size;
        for( int i = 0; i < size ; i++ )
            {
                cin >> num;
                array_vector[j].push_back({num});
            }
            j++;
    }
  cout<< vector_array[1][2];    // Error

2nd way :

vector< vector<int> > array_vector;
while( no_of_array --)
{
    cin >> size;
    for( int i = 0 ; i < size ; i++ )
    {
        cin >> num;
        array_vector[j].push_back(num);
    }
    j++;
 }
cout<< vector_array[1][2];     // Error

3rd way :  ( Working )

vector<vector<int> > array_vector;
for( int i = 0 ; i < no_of_array ; i++ )
{
    cin >> size;
    vector<int> v;
    for( int j = 0 ; j < size ; j++ )
    {

        cin >> num;
        v.push_back(num);
    }
    array_vector.push_back(v);
}
cout<<array_vector[1][2];    // No Error

Somewhere I read 3rd way of vector of vector is not suitable for competitive programming.  Why ??

What mistake I did while traversing the elements with 1st two approach ??

Body:
You can try the following code

int main(int argc,char* argv[])
{
    unsigned int num;
    int elm;
    unsigned int size;

    std::cout << "Enter the number of rows" << std::endl;
    std::cin >> num;
    std::vector<std::vector<int> > a(num,std::vector<int>(0,0));

    for(unsigned int i=0;i<num;i++)
    {
        std::cout  << "Enter the size of " << i+1 << "array:" << std::endl;
        std::cin >> size;

        for(unsigned int j=0;j<size;j++)
        {
            std::cout << "Enter the element" <<std::endl;
            std::cin >> elm;

            a[i].push_back(elm);
        }
    }

    for(unsigned int i=0;i<a.size();i++)
    {
        for(unsigned int j=0;j<a[i].size();j++)
        {
            std::cout << "Element at [" <<i<<"][" <<j <<"] is " << a[i][j] <<std::endl;
        }
    }

    return 0;
}


问:
Powershell/selenium Send keys to pop up window
I have written a code that opens a pop up window where i have to select the file path in order to upload it.See link to view popup screen

Now I want this script to run in the background. However, this is not possible with the Wshell command I have used.

Is there a way I can replace the Wshell command?

```<code>#go to the uploadtab
#---------------------
$searchBtnIris2 = $driver.FindElementByXPath('//*[@id="menuFormHome:j_id44_body"]/ul[3]/li[4]/a')
Write-Host "Den ID van de zoekknop is $seachBtnIris2"
$searchBtnIris2.Click();

Start-Sleep -s 15

#click add button and select file to upload
#-------------------------------------------
$searchBtnIris3 = $driver.FindElementByXPath('//*[@id="uploadFormPanel:upload:flashContainer"]')
Write-Host "Den ID van de zoekknop is $seachBtnIris3"
$searchBtnIris3.Click();

Start-Sleep -s 1

$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('title of the application window')
Sleep 1
$wshell.SendKeys('C:\Users\SVan37\Documents\test\EDI_IRIS_UPLOAD.xlsx');

$wshell.SendKeys('~')

Start-Sleep -s 1
</code>```

答:
Here's a quick and dirty method. Paste the entire code block below into your script and call it like so:

Set-OpenFileDialogPath -Path 'C:\Users\SVan37\Documents\test\EDI_IRIS_UPLOAD.xlsx' -OwnerBinaryFileName 'chrome.exe'

```<code><#
.SYNOPSIS
Sets the path of all open file dialogs, optionally filtered by binary file name.

.PARAMETER Path
The file path to use.

.PARAMETER OwnerBinaryFileName
The binary file name to filter by, such as chrome.exe.

.OUTPUTS
System.Boolean. True if at least one open file dialog was found and updated; false otherwise.
#>

function Set-OpenFileDialogPath
{
    Param(
        [Parameter(Mandatory = $true)]
        [string]
        $Path,

        [string]
        $OwnerBinaryFileName
    )

    # Add Win32 window functions, ignoring the exception if they've already been added
    try
    {
        $user32 = Add-Type -Name 'user32' -Namespace 'Win32' -PassThru -MemberDefinition @'
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);

[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);
'@
    }
    catch
    {
    }

    $foundOne = $false
    $lastOpenDialogHwnd = [IntPtr]::Zero

    # Loop over all open file dialogs
    while ($true)
    {
        # Find the open file dialog
        $lastOpenDialogHwnd = $user32::FindWindowEx([IntPtr]::Zero, $lastOpenDialogHwnd, '#32770', 'Open')
        if ($lastOpenDialogHwnd -eq [IntPtr]::Zero)
        {
            break
        }

        # If a binary filter was specified and the found open file dialog doesn't belong, look for the next dialog
        if (![string]::IsNullOrEmpty($OwnerBinaryFileName))
        {
            $processId = 0
            $user32::GetWindowThreadProcessId($lastOpenDialogHwnd, [ref]$processId) | Out-Null
            $process = [Diagnostics.Process]::GetProcessById($processId -as [int])
            if ([IO.Path]::GetFileName($process.MainModule.FileName) -ine $OwnerBinaryFileName)
            {
                continue
            }
            $process.Dispose()
        }

        # Find the Open button
        $buttonHwnd = $user32::FindWindowEx($lastOpenDialogHwnd, [IntPtr]::Zero, 'Button', '&Open')

        # Find the open file dialog's file name textbox
        $comboBoxExHwnd = $user32::FindWindowEx($lastOpenDialogHwnd, [IntPtr]::Zero, 'ComboBoxEx32', $null)
        if ($comboBoxExHwnd -ne [IntPtr]::Zero -and $buttonHwnd -ne [IntPtr]::Zero)
        {
            $comboBoxHwnd = $user32::FindWindowEx($comboBoxExHwnd, [IntPtr]::Zero, 'ComboBox', $null)
            if ($comboBoxHwnd -ne [IntPtr]::Zero)
            {
                $editHwnd = $user32::FindWindowEx($comboBoxHwnd, [IntPtr]::Zero, 'Edit', $null)
                if ($editHwnd -ne [IntPtr]::Zero)
                {
                    # Set the open file dialog's file name textbox to the desired path
                    $user32::SendMessage($editHwnd, 12, [IntPtr]::Zero, $Path) | Out-Null

                    # Click "Open"
                    $user32::SendMessage($buttonHwnd, 245, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null

                    $foundOne = $true
                }
            }
        }
    }

    return $foundOne
}
</code>```

(For clarity given its length, the above code is licensed under the Unlicense license, meaning it's free for any kind of use and modification and has no attribution or license inclusion requirements.)

Notes

The function uses SendMessage rather than SendKeys, so it will work regardless of whether the open file dialog is hidden or inactive. (In fact, it will work even if you're actively typing in another window while it runs.)

Calling the function with chrome.exe as the OwnerBinaryFileName causes it to update the file name textboxes of all open file dialogs that belong to chrome.exe. Thus, if there's the possibility that multiple instances of chrome.exe could be displaying open file dialogs at the same time, you should add a couple lines that check whether the tab name of the dialog's owning process window matches the one you're targeting.

If you need to do more dialog automation through PowerShell in the future, I'd recommend checking out WASP (Windows Automation Snapin for PowerShell). Unfortunately, it's hosted on soon-to-be-defunct CodePlex, and it doesn't seem to have a presence on GitHub yet, so hopefully someone will pick it up before December 15, 2017 (CodePlex's planned date for total shutdown).

Body:
I have written a code that opens a pop up window where i have to select the file path in order to upload it.See link to view popup screen

Now I want this script to run in the background. However, this is not possible with the Wshell command I have used.

Is there a way I can replace the Wshell command?

#go to the uploadtab
#---------------------
$searchBtnIris2 = $driver.FindElementByXPath('//*[@id="menuFormHome:j_id44_body"]/ul[3]/li[4]/a')
Write-Host "Den ID van de zoekknop is $seachBtnIris2"
$searchBtnIris2.Click();

Start-Sleep -s 15

#click add button and select file to upload
#-------------------------------------------
$searchBtnIris3 = $driver.FindElementByXPath('//*[@id="uploadFormPanel:upload:flashContainer"]')
Write-Host "Den ID van de zoekknop is $seachBtnIris3"
$searchBtnIris3.Click();

Start-Sleep -s 1

$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('title of the application window')
Sleep 1
$wshell.SendKeys('C:\Users\SVan37\Documents\test\EDI_IRIS_UPLOAD.xlsx');

$wshell.SendKeys('~')

Start-Sleep -s 1

Body:
Here's a quick and dirty method. Paste the entire code block below into your script and call it like so:

Set-OpenFileDialogPath -Path 'C:\Users\SVan37\Documents\test\EDI_IRIS_UPLOAD.xlsx' -OwnerBinaryFileName 'chrome.exe'

<#
.SYNOPSIS
Sets the path of all open file dialogs, optionally filtered by binary file name.

.PARAMETER Path
The file path to use.

.PARAMETER OwnerBinaryFileName
The binary file name to filter by, such as chrome.exe.

.OUTPUTS
System.Boolean. True if at least one open file dialog was found and updated; false otherwise.
#>

function Set-OpenFileDialogPath
{
    Param(
        [Parameter(Mandatory = $true)]
        [string]
        $Path,

        [string]
        $OwnerBinaryFileName
    )

    # Add Win32 window functions, ignoring the exception if they've already been added
    try
    {
        $user32 = Add-Type -Name 'user32' -Namespace 'Win32' -PassThru -MemberDefinition @'
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);

[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);
'@
    }
    catch
    {
    }

    $foundOne = $false
    $lastOpenDialogHwnd = [IntPtr]::Zero

    # Loop over all open file dialogs
    while ($true)
    {
        # Find the open file dialog
        $lastOpenDialogHwnd = $user32::FindWindowEx([IntPtr]::Zero, $lastOpenDialogHwnd, '#32770', 'Open')
        if ($lastOpenDialogHwnd -eq [IntPtr]::Zero)
        {
            break
        }

        # If a binary filter was specified and the found open file dialog doesn't belong, look for the next dialog
        if (![string]::IsNullOrEmpty($OwnerBinaryFileName))
        {
            $processId = 0
            $user32::GetWindowThreadProcessId($lastOpenDialogHwnd, [ref]$processId) | Out-Null
            $process = [Diagnostics.Process]::GetProcessById($processId -as [int])
            if ([IO.Path]::GetFileName($process.MainModule.FileName) -ine $OwnerBinaryFileName)
            {
                continue
            }
            $process.Dispose()
        }

        # Find the Open button
        $buttonHwnd = $user32::FindWindowEx($lastOpenDialogHwnd, [IntPtr]::Zero, 'Button', '&Open')

        # Find the open file dialog's file name textbox
        $comboBoxExHwnd = $user32::FindWindowEx($lastOpenDialogHwnd, [IntPtr]::Zero, 'ComboBoxEx32', $null)
        if ($comboBoxExHwnd -ne [IntPtr]::Zero -and $buttonHwnd -ne [IntPtr]::Zero)
        {
            $comboBoxHwnd = $user32::FindWindowEx($comboBoxExHwnd, [IntPtr]::Zero, 'ComboBox', $null)
            if ($comboBoxHwnd -ne [IntPtr]::Zero)
            {
                $editHwnd = $user32::FindWindowEx($comboBoxHwnd, [IntPtr]::Zero, 'Edit', $null)
                if ($editHwnd -ne [IntPtr]::Zero)
                {
                    # Set the open file dialog's file name textbox to the desired path
                    $user32::SendMessage($editHwnd, 12, [IntPtr]::Zero, $Path) | Out-Null

                    # Click "Open"
                    $user32::SendMessage($buttonHwnd, 245, [IntPtr]::Zero, [IntPtr]::Zero) | Out-Null

                    $foundOne = $true
                }
            }
        }
    }

    return $foundOne
}

(For clarity given its length, the above code is licensed under the Unlicense license, meaning it's free for any kind of use and modification and has no attribution or license inclusion requirements.)

Notes

The function uses SendMessage rather than SendKeys, so it will work regardless of whether the open file dialog is hidden or inactive. (In fact, it will work even if you're actively typing in another window while it runs.)

Calling the function with chrome.exe as the OwnerBinaryFileName causes it to update the file name textboxes of all open file dialogs that belong to chrome.exe. Thus, if there's the possibility that multiple instances of chrome.exe could be displaying open file dialogs at the same time, you should add a couple lines that check whether the tab name of the dialog's owning process window matches the one you're targeting.

If you need to do more dialog automation through PowerShell in the future, I'd recommend checking out WASP (Windows Automation Snapin for PowerShell). Unfortunately, it's hosted on soon-to-be-defunct CodePlex, and it doesn't seem to have a presence on GitHub yet, so hopefully someone will pick it up before December 15, 2017 (CodePlex's planned date for total shutdown).