问:
Overflow error when trying to read drive properties with ioctl in python
When trying to extract a vendor-specific feature for one of my drives (cmd = 0x89), I get an overflow error: OverflowError: signed integer is greater than maximum. The error is thrown immediately after ioctl is called. The traceback is not very informative either:

```<code>Traceback (most recent call last):
  File "lockbx/atacmd.py", line 148, in <module>
    GetDriveIdSgIo("/dev/sda")
  File "lockbx/atacmd.py", line 134, in GetDriveIdSgIo
    ret = fcntl.ioctl(fd.fileno(), SG_IO, ctypes.addressof(sgio))
OverflowError: signed integer is greater than maximum
</code>```

ATA Command Pass-Through Reference: http://www.t10.org/ftp/t10/document.04/04-262r8.pdf

```<code>class AtaCmd(ctypes.Structure):

    _fields_ = [
        ('opcode', ctypes.c_ubyte),
        ('protocol', ctypes.c_ubyte),
        ('flags', ctypes.c_ubyte),
        ('features', ctypes.c_ubyte),
        ('sector_count', ctypes.c_ubyte),
        ('lba_low', ctypes.c_ubyte),
        ('lba_mid', ctypes.c_ubyte),
        ('lba_high', ctypes.c_ubyte),
        ('device', ctypes.c_ubyte),
        ('command', ctypes.c_ubyte),
        ('reserved', ctypes.c_ubyte),
        ('control', ctypes.c_ubyte)]

class SgioHdr(ctypes.Structure):
    """<scsi/sg.h> sg_io_hdr_t."""

    _fields_ = [
        ('interface_id', ctypes.c_int),
        ('dxfer_direction', ctypes.c_int),
        ('cmd_len', ctypes.c_ubyte),
        ('mx_sb_len', ctypes.c_ubyte),
        ('iovec_count', ctypes.c_ushort),
        ('dxfer_len', ctypes.c_uint),
        ('dxferp', ctypes.c_void_p),
        ('cmdp', ctypes.c_void_p),
        ('sbp', ctypes.c_void_p),
        ('timeout', ctypes.c_uint),
        ('flags', ctypes.c_uint),
        ('pack_id', ctypes.c_int),
        ('usr_ptr', ctypes.c_void_p),
        ('status', ctypes.c_ubyte),
        ('masked_status', ctypes.c_ubyte),
        ('msg_status', ctypes.c_ubyte),
        ('sb_len_wr', ctypes.c_ubyte),
        ('host_status', ctypes.c_ushort),
        ('driver_status', ctypes.c_ushort),
        ('resid', ctypes.c_int),
        ('duration', ctypes.c_uint),
        ('info', ctypes.c_uint)]

def GetDriveIdSgIo(dev):
    ata_cmd = AtaCmd(opcode=0xA1,  # ATA PASS-THROUGH (12)
                     protocol=3 << 1,  # PIO Data-In
                     flags=0x06,
                     features=0xF5,
                     sector_count=1,
                     lba_low=0, lba_mid=0, lba_high=0,
                     device=0,
                     command=0x89,  # IDENTIFY
                     reserved=0,
                     control=0)

    SG_DXFER_FROM_DEV = -3
    sense = ctypes.c_buffer(64)
    identify = ctypes.c_buffer(512)

    sgio = SgioHdr(
        interface_id=ord('S'),
        dxfer_direction=SG_DXFER_FROM_DEV,
        cmd_len=ctypes.sizeof(ata_cmd),
        mx_sb_len=ctypes.sizeof(sense),
        iovec_count=0,
        dxfer_len=ctypes.sizeof(identify),
        dxferp=0,
        cmdp=ctypes.addressof(ata_cmd),
        sbp=ctypes.addressof(sense),
        timeout=3000,
        flags=0,
        pack_id=0,
        usr_ptr=None,
        # Set values
        status=0, masked_status=0, msg_status=0, sb_len_wr=0, host_status=0,
        driver_status=0, resid=0, duration=0, info=0
    )

    SG_IO = 0x2285  # <scsi/sg.h>
    with open(dev, 'r') as fd:
        ret = fcntl.ioctl(fd.fileno(), SG_IO, ctypes.addressof(sgio))  # fails here

    # some other stuff returns endian swapped buffer info but not relevant

GetDriveIdSgIo("/dev/sda")
</code>```

Where have I gone wrong?

答:
Do you receive 32-bit or 64-bit?
By default it's 32-bit value in ctypes, if I'm not mistaken.</p>

Body:
When trying to extract a vendor-specific feature for one of my drives (cmd = 0x89), I get an overflow error: OverflowError: signed integer is greater than maximum. The error is thrown immediately after ioctl is called. The traceback is not very informative either:

Traceback (most recent call last):
  File "lockbx/atacmd.py", line 148, in <module>
    GetDriveIdSgIo("/dev/sda")
  File "lockbx/atacmd.py", line 134, in GetDriveIdSgIo
    ret = fcntl.ioctl(fd.fileno(), SG_IO, ctypes.addressof(sgio))
OverflowError: signed integer is greater than maximum

ATA Command Pass-Through Reference: http://www.t10.org/ftp/t10/document.04/04-262r8.pdf

class AtaCmd(ctypes.Structure):

    _fields_ = [
        ('opcode', ctypes.c_ubyte),
        ('protocol', ctypes.c_ubyte),
        ('flags', ctypes.c_ubyte),
        ('features', ctypes.c_ubyte),
        ('sector_count', ctypes.c_ubyte),
        ('lba_low', ctypes.c_ubyte),
        ('lba_mid', ctypes.c_ubyte),
        ('lba_high', ctypes.c_ubyte),
        ('device', ctypes.c_ubyte),
        ('command', ctypes.c_ubyte),
        ('reserved', ctypes.c_ubyte),
        ('control', ctypes.c_ubyte)]

class SgioHdr(ctypes.Structure):
    """<scsi/sg.h> sg_io_hdr_t."""

    _fields_ = [
        ('interface_id', ctypes.c_int),
        ('dxfer_direction', ctypes.c_int),
        ('cmd_len', ctypes.c_ubyte),
        ('mx_sb_len', ctypes.c_ubyte),
        ('iovec_count', ctypes.c_ushort),
        ('dxfer_len', ctypes.c_uint),
        ('dxferp', ctypes.c_void_p),
        ('cmdp', ctypes.c_void_p),
        ('sbp', ctypes.c_void_p),
        ('timeout', ctypes.c_uint),
        ('flags', ctypes.c_uint),
        ('pack_id', ctypes.c_int),
        ('usr_ptr', ctypes.c_void_p),
        ('status', ctypes.c_ubyte),
        ('masked_status', ctypes.c_ubyte),
        ('msg_status', ctypes.c_ubyte),
        ('sb_len_wr', ctypes.c_ubyte),
        ('host_status', ctypes.c_ushort),
        ('driver_status', ctypes.c_ushort),
        ('resid', ctypes.c_int),
        ('duration', ctypes.c_uint),
        ('info', ctypes.c_uint)]

def GetDriveIdSgIo(dev):
    ata_cmd = AtaCmd(opcode=0xA1,  # ATA PASS-THROUGH (12)
                     protocol=3 << 1,  # PIO Data-In
                     flags=0x06,
                     features=0xF5,
                     sector_count=1,
                     lba_low=0, lba_mid=0, lba_high=0,
                     device=0,
                     command=0x89,  # IDENTIFY
                     reserved=0,
                     control=0)

    SG_DXFER_FROM_DEV = -3
    sense = ctypes.c_buffer(64)
    identify = ctypes.c_buffer(512)

    sgio = SgioHdr(
        interface_id=ord('S'),
        dxfer_direction=SG_DXFER_FROM_DEV,
        cmd_len=ctypes.sizeof(ata_cmd),
        mx_sb_len=ctypes.sizeof(sense),
        iovec_count=0,
        dxfer_len=ctypes.sizeof(identify),
        dxferp=0,
        cmdp=ctypes.addressof(ata_cmd),
        sbp=ctypes.addressof(sense),
        timeout=3000,
        flags=0,
        pack_id=0,
        usr_ptr=None,
        # Set values
        status=0, masked_status=0, msg_status=0, sb_len_wr=0, host_status=0,
        driver_status=0, resid=0, duration=0, info=0
    )

    SG_IO = 0x2285  # <scsi/sg.h>
    with open(dev, 'r') as fd:
        ret = fcntl.ioctl(fd.fileno(), SG_IO, ctypes.addressof(sgio))  # fails here

    # some other stuff returns endian swapped buffer info but not relevant

GetDriveIdSgIo("/dev/sda")

Where have I gone wrong?


来源: stackexchange

问:
Validate user and redirect to login or home in php
I have a scenario in which I want to validate user on page load.
I want same script for all pages including Login and Home pages, in which if user is logged In redirect to Home else redirect to login.
In my code it fails due to too many redirects. need simple solution for that.
here is my code:

session.php

```<code><?php
   define('DB_SERVER', 'localhost');
   define('DB_USERNAME', '');
   define('DB_PASSWORD', '');
   define('DB_DATABASE', 'auth');
   $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

   session_start();

   $checkId = ''; $checkUser = ''; $checkPass = '';

   if(isset($_SESSION['login_userId'])){ $checkId = $_SESSION['login_userId']; };
   if(isset($_SESSION['login_userName'])){ $checkUser = $_SESSION['login_userName']; };
   if(isset($_SESSION['login_userPass'])){ $checkPass = $_SESSION['login_userPass']; };

   $sessionResult = mysqli_query($db, "select * from users where id='$checkId' AND username='$checkUser' AND password='$checkPass'");
   $getSessionRow = mysqli_fetch_array($sessionResult, MYSQLI_ASSOC);
   $sessionRowcount = mysqli_num_rows($sessionResult);

   if(isset($getSessionRow['username']) && $checkUser == $getSessionRow['username']){
      header("location:home.php");
   }
   else {
      header("location:login.php");
   }
?>
</code>```

login.php

```<code><?php
include('session.php');
?>
<html>
   <head>
      <title>Login</title>
   </head>
   <body>
      <h1>Login page with login Form</h1>
   </body>
</html>
</code>```

home.php

```<code><?php
include('session.php');
?>
<html>
   <head>
      <title>Welcome</title>
   </head>
   <body>
      <h1>Welcome to Home page</h1>
   </body>
</html>
</code>```

答: You are using same session page in both pages of course it will redirect to much. You have to delete session php from login and home. In login create a form after button click post it to session php so it can redirect. In home php on top create an if statement check if session login is logged in else send it to session php that will stop all loops.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a scenario in which I want to validate user on page load.
I want same script for all pages including Login and Home pages, in which if user is logged In redirect to Home else redirect to login.
In my code it fails due to too many redirects. need simple solution for that.
here is my code:

session.php

<?php
   define('DB_SERVER', 'localhost');
   define('DB_USERNAME', '');
   define('DB_PASSWORD', '');
   define('DB_DATABASE', 'auth');
   $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

   session_start();

   $checkId = ''; $checkUser = ''; $checkPass = '';

   if(isset($_SESSION['login_userId'])){ $checkId = $_SESSION['login_userId']; };
   if(isset($_SESSION['login_userName'])){ $checkUser = $_SESSION['login_userName']; };
   if(isset($_SESSION['login_userPass'])){ $checkPass = $_SESSION['login_userPass']; };

   $sessionResult = mysqli_query($db, "select * from users where id='$checkId' AND username='$checkUser' AND password='$checkPass'");
   $getSessionRow = mysqli_fetch_array($sessionResult, MYSQLI_ASSOC);
   $sessionRowcount = mysqli_num_rows($sessionResult);

   if(isset($getSessionRow['username']) && $checkUser == $getSessionRow['username']){
      header("location:home.php");
   }
   else {
      header("location:login.php");
   }
?>

login.php

<?php
include('session.php');
?>

      <title>Login</title>

Login page with login Form

home.php

<?php
include('session.php');
?>

      <title>Welcome</title>

Welcome to Home page


问:
Pivot row values matching a pattern into column names
I have data that look like this:

```<code>OH_IDNR  OCV_VNAME                              OCV_VALUE
8420518  response_part_0_script_0_code_0        $[*].id
8420518  response_part_0_script_0_queryType     JSONPath
8420518  response_part_0_script_0_resourceName  profileIds#
8420518  response_part_0_script_0_saveTo        variable
8420518  response_part_0_script_0_useArray      TRUE
8420518  response_part_0_script_1_code_0        $[*].name
8420518  response_part_0_script_1_queryType     JSONPath
8420518  response_part_0_script_1_resourceName  profileNames#
8420518  response_part_0_script_1_saveTo        variable
8420518  response_part_0_script_1_useArray      TRUE
8420518  response_part_0_script_2_code_0        $[*].environment
8420518  response_part_0_script_2_queryType     JSONPath
8420518  response_part_0_script_2_resourceName  profileEnvironments#
8420518  response_part_0_script_2_saveTo        variable
8420518  response_part_0_script_2_useArray      TRUE
8420518  response_part_0_script_3_code_0        $[*].description
8420518  response_part_0_script_3_queryType     JSONPath
8420518  response_part_0_script_3_resourceName  profileDescriptions#
8420518  response_part_0_script_3_saveTo        variable
8420518  response_part_0_script_3_useArray      TRUE

</code>```

I would like to pivot these data so that for each set of rows with the same OH_IDNR and with the same common/non-unique part of OCV_VNAME, these columns are returned:

OH_IDNR

The common part of OCV_VNAME (e.g., 'response_part_0_script_0_')

– n. One column for each unique part of OCV_Name (e.g.,' resourceName'), with OCV_VALUE as the value.

E.g.,

```<code>OH_IDNR  OCV_VNAME_common           code_0            queryType  resourceName          saveTo    useArray
8420518  response_part_0_script_0_  $[*].id           JSONPath   profileIds#           variable  TRUE
8420518  response_part_0_script_1_  $[*].name         JSONPath   profileNames#         variable  TRUE
8420518  response_part_0_script_2_  $[*].environment  JSONPath   profileEnvironments#  variable  TRUE
8420518  response_part_0_script_3_  $[*].description  JSONPath   profileDescriptions#  variable  TRUE

</code>```

This obviously assumes that the unique part of OCV_VNAME is a string suitable for use as a column name. I’ve tried a few things, but the elegant solution eludes me.

答:
To me, this looks like an aggregation:

```<code>select OH_IDNR,
       substr(OCV_VNAME, 1, 25) as OCV_VNAME_common,
       max(case when OCV_VNAME_common like '%code_0' then OCV_VALUE end) as code_0,
       max(case when OCV_VNAME_common like '%queryType' then OCV_VALUE end) as queryType,
       max(case when OCV_VNAME_common like '%resourceName' then OCV_VALUE end) as resourceName,
       max(case when OCV_VNAME_common like '%saveTo' then OCV_VALUE end) as saveTo,
       max(case when OCV_VNAME_common like '%useArray' then OCV_VALUE end) as useArray
from t
group by OH_IDNR, substr(OCV_VNAME, 1, 25);
</code>```

I would emphasize the this is based on your sample data.  It is unclear if there is a better method to assign the prefix.  One idea is to use regular expressions:

```<code>select OH_IDNR,
       regexp_replace(OCV_VNAME, '^(.*)(code_0|queryType|resourceName|saveTo|useArray)$', '\1'),
       max(case when OCV_VNAME_common like '%code_0' then OCV_VALUE end) as code_0,
       max(case when OCV_VNAME_common like '%queryType' then OCV_VALUE end) as queryType,
       max(case when OCV_VNAME_common like '%resourceName' then OCV_VALUE end) as resourceName,
       max(case when OCV_VNAME_common like '%saveTo' then OCV_VALUE end) as saveTo,
       max(case when OCV_VNAME_common like '%useArray' then OCV_VALUE end) as useArray
from t
group by OH_IDNR,
         regexp_replace(OCV_VNAME, '^(.*)(code_0|queryType|resourceName|saveTo|useArray)$', '\1');
</code>```

Body:
I have data that look like this:

OH_IDNR  OCV_VNAME                              OCV_VALUE
8420518  response_part_0_script_0_code_0        $[*].id
8420518  response_part_0_script_0_queryType     JSONPath
8420518  response_part_0_script_0_resourceName  profileIds#
8420518  response_part_0_script_0_saveTo        variable
8420518  response_part_0_script_0_useArray      TRUE
8420518  response_part_0_script_1_code_0        $[*].name
8420518  response_part_0_script_1_queryType     JSONPath
8420518  response_part_0_script_1_resourceName  profileNames#
8420518  response_part_0_script_1_saveTo        variable
8420518  response_part_0_script_1_useArray      TRUE
8420518  response_part_0_script_2_code_0        $[*].environment
8420518  response_part_0_script_2_queryType     JSONPath
8420518  response_part_0_script_2_resourceName  profileEnvironments#
8420518  response_part_0_script_2_saveTo        variable
8420518  response_part_0_script_2_useArray      TRUE
8420518  response_part_0_script_3_code_0        $[*].description
8420518  response_part_0_script_3_queryType     JSONPath
8420518  response_part_0_script_3_resourceName  profileDescriptions#
8420518  response_part_0_script_3_saveTo        variable
8420518  response_part_0_script_3_useArray      TRUE

I would like to pivot these data so that for each set of rows with the same OH_IDNR and with the same common/non-unique part of OCV_VNAME, these columns are returned:

OH_IDNR

The common part of OCV_VNAME (e.g., 'response_part_0_script_0_')

– n. One column for each unique part of OCV_Name (e.g.,' resourceName'), with OCV_VALUE as the value.

E.g.,

OH_IDNR  OCV_VNAME_common           code_0            queryType  resourceName          saveTo    useArray
8420518  response_part_0_script_0_  $[*].id           JSONPath   profileIds#           variable  TRUE
8420518  response_part_0_script_1_  $[*].name         JSONPath   profileNames#         variable  TRUE
8420518  response_part_0_script_2_  $[*].environment  JSONPath   profileEnvironments#  variable  TRUE
8420518  response_part_0_script_3_  $[*].description  JSONPath   profileDescriptions#  variable  TRUE

This obviously assumes that the unique part of OCV_VNAME is a string suitable for use as a column name. I’ve tried a few things, but the elegant solution eludes me.

Body:
To me, this looks like an aggregation:

select OH_IDNR,
       substr(OCV_VNAME, 1, 25) as OCV_VNAME_common,
       max(case when OCV_VNAME_common like '%code_0' then OCV_VALUE end) as code_0,
       max(case when OCV_VNAME_common like '%queryType' then OCV_VALUE end) as queryType,
       max(case when OCV_VNAME_common like '%resourceName' then OCV_VALUE end) as resourceName,
       max(case when OCV_VNAME_common like '%saveTo' then OCV_VALUE end) as saveTo,
       max(case when OCV_VNAME_common like '%useArray' then OCV_VALUE end) as useArray
from t
group by OH_IDNR, substr(OCV_VNAME, 1, 25);

I would emphasize the this is based on your sample data.  It is unclear if there is a better method to assign the prefix.  One idea is to use regular expressions:

select OH_IDNR,
       regexp_replace(OCV_VNAME, '^(.*)(code_0|queryType|resourceName|saveTo|useArray)$', '\1'),
       max(case when OCV_VNAME_common like '%code_0' then OCV_VALUE end) as code_0,
       max(case when OCV_VNAME_common like '%queryType' then OCV_VALUE end) as queryType,
       max(case when OCV_VNAME_common like '%resourceName' then OCV_VALUE end) as resourceName,
       max(case when OCV_VNAME_common like '%saveTo' then OCV_VALUE end) as saveTo,
       max(case when OCV_VNAME_common like '%useArray' then OCV_VALUE end) as useArray
from t
group by OH_IDNR,
         regexp_replace(OCV_VNAME, '^(.*)(code_0|queryType|resourceName|saveTo|useArray)$', '\1');


问:
Check how many of the same chars line op in list
I have a python list,

```<code>l=[0,1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
</code>```

for example,
I want to check if the list contain at least 7 1's next to each other.

I'm not sure how to check this.

to clarify:

```<code>a=[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ] #should return True
b=[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0 ] #should return False
</code>```

Any ideas?

答:
This is one approach using itertools.groupby.

Ex:

```<code>from itertools import groupby

data = [[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0]]
for i in data:
    if any((k==1 and len(list(v)) >=7) for k, v in groupby(i) ):
        print("Ok", i)
</code>```

Body:
I have a python list,

l=[0,1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]

for example,
I want to check if the list contain at least 7 1's next to each other.

I'm not sure how to check this.

to clarify:

a=[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ] #should return True
b=[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0 ] #should return False

Any ideas?

Body:
This is one approach using itertools.groupby.

Ex:

from itertools import groupby

data = [[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0]]
for i in data:
    if any((k==1 and len(list(v)) >=7) for k, v in groupby(i) ):
        print("Ok", i)


问:
Python: concatenate an integer array with 1 empty array
I have one simple one-dimensional array and an empty array in NumPy. I try to concatenate them, but I get an array in float.

```<code>from numpy import *
a = zeros(5,'i')
a += 1
b = []
c = hstack((a,b))
d = concatenate((a, b))
print("a",a)
print("b",b)
print("c",c)
print("d",d)
</code>```

I got:

```<code>a [1 1 1 1 1]

b []

c [1. 1. 1. 1. 1.]

d [1. 1. 1. 1. 1.]
</code>```

But I am looking for an integer array

```<code>[1 1 1 1 1]
</code>```

How? And what is the most efficient way?

答:
I think numpy assumes the empty array as float64 data type.
If you run the following

```<code>np.array([]).dtype
</code>```

it returns dtype('float64')
so you should initilize the empty array as follows

```<code> b=[]
 b=np.array(b,dtype="int32")
</code>```

Body:
I have one simple one-dimensional array and an empty array in NumPy. I try to concatenate them, but I get an array in float.

from numpy import *
a = zeros(5,'i')
a += 1
b = []
c = hstack((a,b))
d = concatenate((a, b))
print("a",a)
print("b",b)
print("c",c)
print("d",d)

I got:

a [1 1 1 1 1]

b []

c [1. 1. 1. 1. 1.]

d [1. 1. 1. 1. 1.]

But I am looking for an integer array

[1 1 1 1 1]

How? And what is the most efficient way?

Body:
I think numpy assumes the empty array as float64 data type.
If you run the following

np.array([]).dtype

it returns dtype('float64')
so you should initilize the empty array as follows

 b=[]
 b=np.array(b,dtype="int32")


问:
Implement Database(MySQL) in a Restlet application
I'm building a restlet webservice with lots of connections(1000 users) from the clients to a MySQL database.

Should I use a framework like Hibernate to handle data(I figure I could hack out what i need using JDBC)?

What are the memory issues i should be considering(what exactly should i be able to do in memory and what should't i do)?

Any good tutorial on using Restlets and MySQL?

Thanks in advance

答:
Here are my 2 cents of advice

1) Hiberate+ehcache to avoid hitting the database too often would be the way to go

2) Use ehcache and configure it properly depending on your application needs, it is a very flexible framework

3) I never used restlet but I used RESTEasy from jboss that was very well documented and well suited for my rest needs.

ContentLicense: CC BY-SA 3.0


问:
Native geolocation ionic watch position working on background but not when phone is locked
I'm using this code:

```<code>this.watchID = navigator.geolocation.watchPosition((localizacion) => {
  console.log("En el enviarPos", localizacion);
}, (err) => {
  console.log(err);
}, { enableHighAccuracy: true });
</code>```

It works in background, but only doesn't work when the phone is locked.

Error:

```<code>GeolocationPositionError {code: 3, message: "Timeout expired"}
</code>```

答:
I was facing same issue but I switched to Geocoder, and it's working fine for me, also it gives lot of info,

=> For Ionic 3

```<code>ionic cordova plugin add cordova-plugin-nativegeocoder

npm install --save @ionic-native/native-geocoder@4
</code>```

=> For Ionic 4

```<code>ionic cordova plugin add cordova-plugin-nativegeocoder

npm install --save @ionic-native/native-geocoder
</code>```

Body:
I'm using this code:

this.watchID = navigator.geolocation.watchPosition((localizacion) => {
  console.log("En el enviarPos", localizacion);
}, (err) => {
  console.log(err);
}, { enableHighAccuracy: true });

It works in background, but only doesn't work when the phone is locked.

Error:

GeolocationPositionError {code: 3, message: "Timeout expired"}

Body:
I was facing same issue but I switched to Geocoder, and it's working fine for me, also it gives lot of info,

=> For Ionic 3

ionic cordova plugin add cordova-plugin-nativegeocoder

npm install --save @ionic-native/native-geocoder@4

=> For Ionic 4

ionic cordova plugin add cordova-plugin-nativegeocoder

npm install --save @ionic-native/native-geocoder


问:
Characters matrix rotation in python
I wanna to make Tetris game and I need function, to rotate tetramino figure to 90 degrees. The tetramino figure is string array 4x4:

```<code>figure  = [
    "..#.",
    "..#.",
    "..#.",
    "..#."
];
figure = rotateFigure(figure);
</code>```

After searches I find something like this :

```<code>def rotateFigure(figure):

    if not len(figure):
        return
    """
        top : starting row index
        bottom : ending row index
        left : starting column index
        right : ending column index
    """
    top = 0
    bottom = len(figure)-1

    left = 0
    right = len(figure[0])-1

    while left < right and top < bottom:
        # Store the first element of next row,
        # this element will replace first element of
        # current row
        prev = figure[top+1][left]

        # Move elements of top row one step right
        for i in range(left, right+1):
            curr = figure[top][i]
            figure[top][i] = prev
            prev = curr

        top += 1

        # Move elements of rightmost column one step downwards
        for i in range(top, bottom+1):
            curr = figure[i][right]
            figure[i][right] = prev
            prev = curr

        right -= 1

        # Move elements of bottom row one step left
        for i in range(right, left-1, -1):
            curr = figure[bottom][i]
            figure[bottom][i] = prev
            prev = curr

        bottom -= 1

        # Move elements of leftmost column one step upwards
        for i in range(bottom, top-1, -1):
            curr = figure[i][left]
            figure[i][left] = prev
            prev = curr

        left += 1

    return figure
</code>```

but it doesn't work for string array and give typeError:

```<code>File "Tetris.py", line 85, in rotateFigure
    figure[top][i] = prev
TypeError: 'str' object does not support item assignment
</code>```

How can I rotate the string array?

答:
This solution makes use of the fact that zip() can be used to transpose an array (list of lists):

```<code>figure = list(zip(*reversed(figure)))       # 90° clockwise
figure = list(reversed(list(zip(*figure)))) # 90° counterclockwise
</code>```

Title: Characters matrix rotation in python

Body:
I wanna to make Tetris game and I need function, to rotate tetramino figure to 90 degrees. The tetramino figure is string array 4x4:

figure  = [
    "..#.",
    "..#.",
    "..#.",
    "..#."
];
figure = rotateFigure(figure);

After searches I find something like this :

def rotateFigure(figure):

    if not len(figure):
        return
    """
        top : starting row index
        bottom : ending row index
        left : starting column index
        right : ending column index
    """
    top = 0
    bottom = len(figure)-1

    left = 0
    right = len(figure[0])-1

    while left < right and top < bottom:
        # Store the first element of next row,
        # this element will replace first element of
        # current row
        prev = figure[top+1][left]

        # Move elements of top row one step right
        for i in range(left, right+1):
            curr = figure[top][i]
            figure[top][i] = prev
            prev = curr

        top += 1

        # Move elements of rightmost column one step downwards
        for i in range(top, bottom+1):
            curr = figure[i][right]
            figure[i][right] = prev
            prev = curr

        right -= 1

        # Move elements of bottom row one step left
        for i in range(right, left-1, -1):
            curr = figure[bottom][i]
            figure[bottom][i] = prev
            prev = curr

        bottom -= 1

        # Move elements of leftmost column one step upwards
        for i in range(bottom, top-1, -1):
            curr = figure[i][left]
            figure[i][left] = prev
            prev = curr

        left += 1

    return figure

but it doesn't work for string array and give typeError:

File "Tetris.py", line 85, in rotateFigure
    figure[top][i] = prev
TypeError: 'str' object does not support item assignment

How can I rotate the string array?

Body:
This solution makes use of the fact that zip() can be used to transpose an array (list of lists):

figure = list(zip(*reversed(figure)))       # 90° clockwise
figure = list(reversed(list(zip(*figure)))) # 90° counterclockwise


问:
I want to print the dictionary in python
```<code>l = {}
name = [(str, input().split()) for i in range(0, 15)]
dob = [(int, input().split()) for i in range(0, 15)]
print({name[i]:dob[i] for i in range(len(dob))})
</code>```

I want to print 15 items in a dictionary format of name as key and dateofbirth(dob) as value.What wrong I am doing?
    .....................................................................................

```<code>the error is:
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print({name[i]:dob[i] for i in range(len(dob))})
  File "main.py", line 4, in <dictcomp>
    print({name[i]:dob[i] for i in range(len(dob))})
TypeError: unhashable type: 'list'
</code>```

答:
I would do it like this (this returns a generator):

```<code>name = map(str, input().split())
dob = map(int, input().split())
print({n: d for n, d in zip(name, dob)})
</code>```

If you want it to return a list instead:

```<code>name = list(map(str, input().split()))
dob = list(map(int, input().split()))
print({n: d for n, d in zip(name, dob)})
</code>```

Body:
l = {}
name = [(str, input().split()) for i in range(0, 15)]
dob = [(int, input().split()) for i in range(0, 15)]
print({name[i]:dob[i] for i in range(len(dob))})

I want to print 15 items in a dictionary format of name as key and dateofbirth(dob) as value.What wrong I am doing?
    .....................................................................................

the error is:
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print({name[i]:dob[i] for i in range(len(dob))})
  File "main.py", line 4, in <dictcomp>
    print({name[i]:dob[i] for i in range(len(dob))})
TypeError: unhashable type: 'list'

Body:
I would do it like this (this returns a generator):

name = map(str, input().split())
dob = map(int, input().split())
print({n: d for n, d in zip(name, dob)})

If you want it to return a list instead:

name = list(map(str, input().split()))
dob = list(map(int, input().split()))
print({n: d for n, d in zip(name, dob)})


问:
Pass two variable to method in Laravel
i want to find post by slug also in url ..
but the comments must be found by post_id

Controller

```<code>public function post($slug,$id)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$id)->get();
    return view('content.post',compact('post','comments'));
}
</code>```

Route

```<code>Route::get('post/{slug}', 'PagesController@post')->name('post.show');
</code>```

答:
```<code>Route::get('post/{slug}', 'PagesController@post')->name('post.show');
</code>```

```<code>public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get();
    return view('content.post',compact('post','comments'));
}
</code>```

Title: Pass two variable to method in Laravel

Body:
i want to find post by slug also in url ..
but the comments must be found by post_id

Controller

public function post($slug,$id)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$id)->get();
    return view('content.post',compact('post','comments'));
}

Route

Route::get('post/{slug}', 'PagesController@post')->name('post.show');

Body:
Route::get('post/{slug}', 'PagesController@post')->name('post.show');

public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get();
    return view('content.post',compact('post','comments'));
}


问:
Connecting to an ASP.Net web service from PHP and retrieving data as JSON
I'm having issues connecting to an ASP.Net web service using PHP.

The web service is known to be operational, since it's returning data when we connect using Javascript from the same domain, but when I attempt to connect using PHP I receive the following error:

```
HTTP/1.1 500 Internal Server Error Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/7.5 jsonerror: true X-Powered-By: ASP.NET Date: Tue, 17 May 2011 03:40:17 GMT Connection: close Content-Length: 819

{"Message":"Invalid JSON primitive: birthday.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\

[etc]
```

The Content-Type is set to "application/json; charset=utf-8" in PHP, and we are trying to send a parameter called "birthday" using the following POST data in PHP:

```
$post_data = array(
    'birthday' => 'none'
);
```

I think the ASP web service is not able to parse the 'birthday' parameter for some reason, but I'm not sure why.

Do I need to explicitly encode the POST data as JSON from PHP before calling the web service?

Thanks.

答:
May be this web service takes the post data in Json format. If it is then you should use

```<code>$post_data = array( 'birthday' => 'none' );
$jsonData =  json_encode ($post_data );
</code>```

for details json_encode

Body:
I'm having issues connecting to an ASP.Net web service using PHP.

The web service is known to be operational, since it's returning data when we connect using Javascript from the same domain, but when I attempt to connect using PHP I receive the following error:

HTTP/1.1 500 Internal Server Error Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/7.5 jsonerror: true X-Powered-By: ASP.NET Date: Tue, 17 May 2011 03:40:17 GMT Connection: close Content-Length: 819

{"Message":"Invalid JSON primitive: birthday.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\

[etc]

The Content-Type is set to "application/json; charset=utf-8" in PHP, and we are trying to send a parameter called "birthday" using the following POST data in PHP:

$post_data = array(
    'birthday' => 'none'
);

I think the ASP web service is not able to parse the 'birthday' parameter for some reason, but I'm not sure why.

Do I need to explicitly encode the POST data as JSON from PHP before calling the web service?

Thanks.

Body:
May be this web service takes the post data in Json format. If it is then you should use

$post_data = array( 'birthday' => 'none' );
$jsonData =  json_encode ($post_data );

for details json_encode


问:
Set text size of menu items in popup menu
I have created options using customized popup menu.

Now, I want to set the text size of menu items. I am getting default text size this time.

How can I achieve this? I don't want to use popup window.
 Is it possible to achive this using popup menu only?

答:
You can use something like the below in the manifest file</p>

```<code> <activity
  android:name=".ActivityName"
  android:theme="@style/styleName"/>
</code>```

Body:
You can use something like the below in the manifest file

 <activity
  android:name=".ActivityName"
  android:theme="@style/styleName"/>


问:
Find a regex call in R to return first and last name or full team name only
I'm trying to clean a column by retaining only first and last names (or full team name: ex "New England Patriots".

Here is a set of names with differing styles that need to be matched. I need a capture group around the first and last name together or full team name:

```<code>Matt Schaub QB - ATL
Phillip Andersen K
Cleveland Browns DEF
San Francisco 49ers DEF
New England Patriots DEF
J.T. Barrett QB - PIT
Tre McBride WR
N'Keal Harry WR - NE
MyCole Pruitt TE - TEN
J.J. Arcega-Whiteside WR - PHI
Tre'Quan Smith WR - NO
</code>```

This is as far as I got in a regex engine before I started getting lost. Not even sure how close it even was:

```<code>[A-Z](\\.|[a-z]+)([A-Z]|\\s)
</code>```

答:
It seems like you have two different possible patterns, We'll use the package unglue to test them both and use the first that matches. (using Tim's data).

```<code>library(unglue)
patterns <- c(
  "{team_name} {=[A-Z]+} - {=[A-Z]+}",
  "{team_name} {=[A-Z]+}")

unglue::unglue_vec(input, patterns)
#>  [1] "Matt Schaub"           "Phillip Andersen"      "Cleveland Browns"
#>  [4] "San Francisco 49ers"   "New England Patriots"  "J.T. Barrett"
#>  [7] "Tre McBride"           "N'Keal Harry"          "MyCole Pruitt"
#> [10] "J.J. Arcega-Whiteside" "Tre'Quan Smith"
</code>```

Body:
I'm trying to clean a column by retaining only first and last names (or full team name: ex "New England Patriots".

Here is a set of names with differing styles that need to be matched. I need a capture group around the first and last name together or full team name:

Matt Schaub QB - ATL
Phillip Andersen K
Cleveland Browns DEF
San Francisco 49ers DEF
New England Patriots DEF
J.T. Barrett QB - PIT
Tre McBride WR
N'Keal Harry WR - NE
MyCole Pruitt TE - TEN
J.J. Arcega-Whiteside WR - PHI
Tre'Quan Smith WR - NO

This is as far as I got in a regex engine before I started getting lost. Not even sure how close it even was:

[A-Z](\\.|[a-z]+)([A-Z]|\\s)

Body:
It seems like you have two different possible patterns, We'll use the package unglue to test them both and use the first that matches. (using Tim's data).

library(unglue)
patterns <- c(
  "{team_name} {=[A-Z]+} - {=[A-Z]+}",
  "{team_name} {=[A-Z]+}")

unglue::unglue_vec(input, patterns)
#>  [1] "Matt Schaub"           "Phillip Andersen"      "Cleveland Browns"
#>  [4] "San Francisco 49ers"   "New England Patriots"  "J.T. Barrett"
#>  [7] "Tre McBride"           "N'Keal Harry"          "MyCole Pruitt"
#> [10] "J.J. Arcega-Whiteside" "Tre'Quan Smith"


问:
bash: pip: command not found
I downloaded pip and ran python setup.py install and everything worked just fine. The very next step in the tutorial is to run pip install <lib you want> but before it even tries to find anything online I get an error "bash: pip: command not found".

This is on Mac OS X. I'm assuming there's some kind of path setting that was not set correctly when I ran setup.py. How can I investigate further? What do I need to check to get a better idea of the exact cause of the problem?

EDIT: I also tried installing Python 2.7 for Mac in the hopes that the friendly install process would do any housekeeping like editing PATH and whatever else needs to happen for everything to work according to the tutorials, but this didn't work. After installing, running 'python' still ran Python 2.6 and PATH was not updated.

答:
assuming you have internet see:
https://pip.pypa.io/en/stable/installing/

basically run:

```<code>curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
</code>```

and

```<code>python get-pip.py
</code>```

Title: bash: pip: command not found

Body:
assuming you have internet see:
https://pip.pypa.io/en/stable/installing/

basically run:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

and

python get-pip.py


问:
How can I get the date after clicking on calender in yearly view in dhtmlx scheduler?
When i click on a date i need to take the selected date, it's working fine on daily, weekly and monthly view by using code below :

scheduler.attachEvent("onEmptyClick", function(date , event){
    alert(date);
});

but, the date variable don't return a correct value in case of yearly view

Does anyone have a solution for this issue?

答:
A little late but here is the solution, since i ran into the same issue</p>

```<code>scheduler.attachEvent("onClick", function (id, e){
  var clickedDate = scheduler.getActionData(e);
  console.log("clickedDate", clickedDate.date);
});
</code>```

Body:
A little late but here is the solution, since i ran into the same issue

scheduler.attachEvent("onClick", function (id, e){
  var clickedDate = scheduler.getActionData(e);
  console.log("clickedDate", clickedDate.date);
});


问:
Conditional Upsert in Couchbase
I have documents that would look like this:

```<code>{
"name": "n",
"age": 22
//other properties

"hash": "XyRZHDJJD6738..." //This property contains the hash of the object (calculated by the client)
}
</code>```

From the client, I should whether:

Update the document using its key (known), ONLY if the hash is different (=> The stored object and the new object are not the same)

Insert the document if the Key doesn't exist

This operation is done in a bulk mode on a relatively large dataset, with concurrent access => So fetching the document then updating is not an option.

Is there a way to do this in Couchbase (5.1+)?

答:
With a tweak to the document model, you could have something like this:

```<code>{
    "name": "n",
    "age": 22,
    "applied_hashes": {
        "XyRZHDJJD6738": null,
        "AB2343DCxdsAd": null,
        // ... other hashes
    }
}
</code>```

Now you can do each update as a Sub-Document operation, with the first spec being to try and insert the hash of the update into applied_hashes.  If that hash/update has previously been applied, then this insert will fail, and as Sub-Document is atomic no changes will be made to the document.

With Java SDK 3.x this looks like:

```<code>try {
  collection.mutateIn("id",
          Arrays.asList(
                  MutateInSpec.insert("applied_hashes.XyRZHDJJD6738", null).createPath(),
                  MutateInSpec.upsert("age", 24)
                  // .. other parts of update XyRZHDJJD6738 here
          ));
}
catch (PathExistsException err) {
  // Update XyRZHDJJD6738 has already been applied
  // No changes have been made to the document
}
</code>```

Title: Conditional Upsert in Couchbase

Body:
I have documents that would look like this:

{
"name": "n",
"age": 22
//other properties

"hash": "XyRZHDJJD6738..." //This property contains the hash of the object (calculated by the client)
}

From the client, I should whether:

Update the document using its key (known), ONLY if the hash is different (=> The stored object and the new object are not the same)

Insert the document if the Key doesn't exist

This operation is done in a bulk mode on a relatively large dataset, with concurrent access => So fetching the document then updating is not an option.

Is there a way to do this in Couchbase (5.1+)?

Body:
With a tweak to the document model, you could have something like this:

{
    "name": "n",
    "age": 22,
    "applied_hashes": {
        "XyRZHDJJD6738": null,
        "AB2343DCxdsAd": null,
        // ... other hashes
    }
}

Now you can do each update as a Sub-Document operation, with the first spec being to try and insert the hash of the update into applied_hashes.  If that hash/update has previously been applied, then this insert will fail, and as Sub-Document is atomic no changes will be made to the document.

With Java SDK 3.x this looks like:

try {
  collection.mutateIn("id",
          Arrays.asList(
                  MutateInSpec.insert("applied_hashes.XyRZHDJJD6738", null).createPath(),
                  MutateInSpec.upsert("age", 24)
                  // .. other parts of update XyRZHDJJD6738 here
          ));
}
catch (PathExistsException err) {
  // Update XyRZHDJJD6738 has already been applied
  // No changes have been made to the document
}


问:
Simple JS menu toggle
I am pretty new to JavaScript and decided to code a menu that opens/expands when you click a button and closes when you click the button again.

I got everything to work but I cannot seem to find why the menu isn't closing.

Here is my code:

Any help or guidance is much appreciated!
I have included my HTML, CSS and JS files.

let toggleNavStatus = false;

let toggleNav = function (){
    let getSideBar = document.querySelector(".nav-sidebar");
    let getSideBarUl = document.querySelector(".nav-sidebar ul");
    let getSideBarUTitle = document.querySelector(".nav-sidebar span");
    let getSideBarLinks = document.querySelectorAll(".nav-sidebar a");

    if(toggleNavStatus === false){
        getSideBarUl.style.visibility = "visible";
        getSideBar.style.width = "295px";
        getSideBarTitle.style.opacity = "0.5";

        let arrayLenght = getSideBarLinks.length;
        for(let i = 0; i < arrayLenght; i++){
            getSideBarLinks[i].style.opacity = "1";
        }
        toggleNavStatus = true;
  } else if(toggleNavStatus === true){
    getSideBarUl.style.visibility = "hidden";
    getSideBar.style.width = "50px";
    getSideBarTitle.style.opacity = "0";

    let arrayLenght = getSideBarLinks.length;
    for(let i = 0; i < arrayLenght; i++){
        getSideBarLinks[i].style.opacity = "0";
    }
    toggleNavStatus = false;
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-color: #F1F1F1;
}

.nav-main{
    width: 100%;
    height: 60px;
    background-color: #FFF;
    display: flex;
    flex-wrap: wrap;
    z-index: 1000;
    position: fixed;
    top: 0;
}

.btn-toggle-nav{
    width: 60px;
    height: 100%;
    background-color: #f98f39;
    background-size: 50%;
    background-position: center;
    cursor: pointer;
    position: fixed;
    left: 0;
}

.btn-toggle-nav:hover{
    opacity: 0.5;
}

.nav-main ul{
    display: flex;
    flex-wrap: wrap;
    padding-left: 60px;
}

.nav-main ul li{
    list-style: none;
    line-height: 30px;
}

.nav-main ul li a{
    display: block;
    height: 100%;
    padding: 0 10px;
    text-transform: uppercase;
    text-decoration: none;
    color: #111;
    font-family: Arial;
    font-size: 16px;
}
 .nav-sidebar{
    position: fixed;
    left: 0;
    bottom: 0;
    width: 50px;
    padding: 0 5px;
    height: calc(100vh - 60px);
    background-color: #1B1B1B;
    z-index: 1000;
 }

 .nav-sidebar ul{
    padding-top: 15px;
    overflow: hidden;
    visibility: hidden;
 }

 .nav-sidebar ul li{
    line-height: 60px;
    list-style: none;
 }

 .nav-sidebar ul li span, ul li a{
    display: block;
    height: 60px;
    padding: 0 10px;
    text-decoration: none;
    text-transform: uppercase;
    color: #FFF;
    font-family: arial;
    font-size: 16px;
    white-space: nowrap;
    opacity: 0.5;
 }

 .nav-sidebar ul li a:hover{
     background-color: #222;
 }</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ZiGi's Toggle Menu</title>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="resetstyle.css">

  Home

  Portfolio

  About Us

  Gallery

  Contact

 Projects

  Making a Website

  SEAO Optimizing Video

  Walking Through The Park

  Just Another Day

```

答:
This is more of an HTML/CSS issue than it is JavaScript. CSS comes with a :hover selector that activates any styling presets made on that element. You can group this up with your classes to all work in sync with each other at the same time.

Give this a try!

https://www.w3schools.com/cssref/sel_hover.asp

Title: Simple JS menu toggle

Body:
I am pretty new to JavaScript and decided to code a menu that opens/expands when you click a button and closes when you click the button again.

I got everything to work but I cannot seem to find why the menu isn't closing.

Here is my code:

Any help or guidance is much appreciated!
I have included my HTML, CSS and JS files.

let toggleNavStatus = false;

let toggleNav = function (){
    let getSideBar = document.querySelector(".nav-sidebar");
    let getSideBarUl = document.querySelector(".nav-sidebar ul");
    let getSideBarUTitle = document.querySelector(".nav-sidebar span");
    let getSideBarLinks = document.querySelectorAll(".nav-sidebar a");

    if(toggleNavStatus === false){
        getSideBarUl.style.visibility = "visible";
        getSideBar.style.width = "295px";
        getSideBarTitle.style.opacity = "0.5";

        let arrayLenght = getSideBarLinks.length;
        for(let i = 0; i < arrayLenght; i++){
            getSideBarLinks[i].style.opacity = "1";
        }
        toggleNavStatus = true;
  } else if(toggleNavStatus === true){
    getSideBarUl.style.visibility = "hidden";
    getSideBar.style.width = "50px";
    getSideBarTitle.style.opacity = "0";

    let arrayLenght = getSideBarLinks.length;
    for(let i = 0; i < arrayLenght; i++){
        getSideBarLinks[i].style.opacity = "0";
    }
    toggleNavStatus = false;
    }
}

body {
    background-color: #F1F1F1;
}

.nav-main{
    width: 100%;
    height: 60px;
    background-color: #FFF;
    display: flex;
    flex-wrap: wrap;
    z-index: 1000;
    position: fixed;
    top: 0;
}

.btn-toggle-nav{
    width: 60px;
    height: 100%;
    background-color: #f98f39;
    background-size: 50%;
    background-position: center;
    cursor: pointer;
    position: fixed;
    left: 0;
}

.btn-toggle-nav:hover{
    opacity: 0.5;
}

.nav-main ul{
    display: flex;
    flex-wrap: wrap;
    padding-left: 60px;
}

.nav-main ul li{
    list-style: none;
    line-height: 30px;
}

.nav-main ul li a{
    display: block;
    height: 100%;
    padding: 0 10px;
    text-transform: uppercase;
    text-decoration: none;
    color: #111;
    font-family: Arial;
    font-size: 16px;
}
 .nav-sidebar{
    position: fixed;
    left: 0;
    bottom: 0;
    width: 50px;
    padding: 0 5px;
    height: calc(100vh - 60px);
    background-color: #1B1B1B;
    z-index: 1000;
 }

 .nav-sidebar ul{
    padding-top: 15px;
    overflow: hidden;
    visibility: hidden;
 }

 .nav-sidebar ul li{
    line-height: 60px;
    list-style: none;
 }

 .nav-sidebar ul li span, ul li a{
    display: block;
    height: 60px;
    padding: 0 10px;
    text-decoration: none;
    text-transform: uppercase;
    color: #FFF;
    font-family: arial;
    font-size: 16px;
    white-space: nowrap;
    opacity: 0.5;
 }

 .nav-sidebar ul li a:hover{
     background-color: #222;
 }

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ZiGi's Toggle Menu</title>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="resetstyle.css">

  Home

  Portfolio

  About Us

  Gallery

  Contact

 Projects

  Making a Website

  SEAO Optimizing Video

  Walking Through The Park

  Just Another Day


问:
How User account be locked for 30 min after 5 unsuccessful login attempts with asp.net?
I am using asp.net membership provider for managing users. I have a requirement to lock user accounts for 30 mins after 5 unsuccessful attempts. How should I do that using asp.net membership provider on the server side?

Also I want that 'Passwords should expire after 3 months', 'Last 10 used passwords should be remembered'. Is there any way to solve these requirements.

答:
For the first requirement, the membership provider offers a MaxInvalidPasswordAttempts property which you can use in conjunction with the PasswordAttemptWindow property.

The 2nd requirement to the best of my knowledge would require you to customize the membership provider. The base membership provider does not retain prior passwords or have a forced password reset to my knowledge. This could be done if you create a custom provider yourself however.

Starter material for creating a custom membership provider


问:
Application Status check using Stackdriver in Google Cloud
I have an application running in google compute instance (ps -ef | grep myapp).
I want to setup an alert if the application goes down and/or comes up in google cloud Stackdriver.
How to achieve this ?</p>

答:
You can create an alert on the Stackdriver monitoring. You will have the option to either have the alert displayed as an incident on the Stackdriver monitoring console or as a notification via an email.

Before configuring your alerts, you will need to choose a metric type in which the alert will be based on.

If you cannot find a metric type that matches your needs, you will need to create your own custom metric.

I also found this approach which will collect and the send the logs from the serial port to the Stackdriver logs. You will then be able to manipulate the data collected as you see fit.


问:
Not able to start kafka in local machine
I have downloaded kafka 2.4.0 binaries for Windows.
When I start kafka from command line using kafka-server-start.bat using server.properties file, I get the following errors :

```<code>[2020-02-04 15:37:33,775] WARN [Controller id=0, targetBrokerId=0] Connection to node 0 (host.docker.internal/10.177.172.141:9092) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2020-02-04 15:37:34,931] WARN [Controller id=0, targetBrokerId=0] Connection to node 0 (host.docker.internal/10.177.172.141:9092) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2020-02-04 15:37:36,122] WARN [Controller id=0, targetBrokerId=0] Connection to node 0 (host.docker.internal/10.177.172.141:9092) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2020-02-04 15:37:37,364] WARN [Controller id=0, targetBrokerId=0] Connection to node 0 (host.docker.internal/10.177.172.141:9092) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2020-02-04 15:37:38,692] WARN [Controller id=0, targetBrokerId=0] Connection to node 0 (host.docker.internal/10.177.172.141:9092) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
</code>```

From the Zookeeper logs I get these errors :

```<code>[2020-02-04 15:37:23,056] INFO Client attempting to establish new session at /127.0.0.1:51457 (org.apache.zookeeper.server.ZooKeeperServer)
[2020-02-04 15:37:23,071] INFO Established session 0x100000298ee0000 with negotiated timeout 6000 for client /127.0.0.1:51457 (org.apache.zookeeper.server.ZooKeeperServer)
[2020-02-04 15:37:23,198] INFO Got user-level KeeperException when processing sessionid:0x100000298ee0000 type:create cxid:0x1 zxid:0x12c txntype:-1 reqpath:n/a Error Path:/consumers Error:KeeperErrorCode = NodeExists for /consumers (org.apache.zookeeper.server.PrepRequestProcessor)
[2020-02-04 15:37:23,214] INFO Got user-level KeeperException when processing sessionid:0x100000298ee0000 type:create cxid:0x2 zxid:0x12d txntype:-1 reqpath:n/a Error Path:/brokers/ids Error:KeeperErrorCode = NodeExists for /brokers/ids (org.apache.zookeeper.server.PrepRequestProcessor)
[2020-02-04 15:37:23,230] INFO Got user-level KeeperException when processing sessionid:0x100000298ee0000 type:create cxid:0x3 zxid:0x12e txntype:-1 reqpath:n/a Error Path:/brokers/topics Error:KeeperErrorCode = NodeExists for /brokers/topics (org.apache.zookeeper.server.PrepRequestProcessor)
</code>```

I have docker installed, but it is not running. The server.properties file is untouched.
I am not able to understand and debug why it is connecting to "host.docker.internal".

Note : Kafka ran successfully once. I remember I did a force shutdown of windows when kafka was running. I do not know whether this can be the issue.
I tried the lower version of kafka, I am still getting the same error.

答:
Windows Hosts file was not looking good to me.

I uninstalled Docker.

Removed all entries of "host.docker.internal", "gateway.docker.internal", "kubernetes.docker.internal".

Restarted my system and Kafka was running properly.

Body:
I have downloaded kafka 2.4.0 binaries for Windows.
When I start kafka from command line using kafka-server-start.bat using server.properties file, I get the following errors :

[2020-02-04 15:37:33,775] WARN [Controller id=0, targetBrokerId=0] Connection to node 0 (host.docker.internal/10.177.172.141:9092) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2020-02-04 15:37:34,931] WARN [Controller id=0, targetBrokerId=0] Connection to node 0 (host.docker.internal/10.177.172.141:9092) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2020-02-04 15:37:36,122] WARN [Controller id=0, targetBrokerId=0] Connection to node 0 (host.docker.internal/10.177.172.141:9092) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2020-02-04 15:37:37,364] WARN [Controller id=0, targetBrokerId=0] Connection to node 0 (host.docker.internal/10.177.172.141:9092) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)
[2020-02-04 15:37:38,692] WARN [Controller id=0, targetBrokerId=0] Connection to node 0 (host.docker.internal/10.177.172.141:9092) could not be established. Broker may not be available. (org.apache.kafka.clients.NetworkClient)

From the Zookeeper logs I get these errors :

[2020-02-04 15:37:23,056] INFO Client attempting to establish new session at /127.0.0.1:51457 (org.apache.zookeeper.server.ZooKeeperServer)
[2020-02-04 15:37:23,071] INFO Established session 0x100000298ee0000 with negotiated timeout 6000 for client /127.0.0.1:51457 (org.apache.zookeeper.server.ZooKeeperServer)
[2020-02-04 15:37:23,198] INFO Got user-level KeeperException when processing sessionid:0x100000298ee0000 type:create cxid:0x1 zxid:0x12c txntype:-1 reqpath:n/a Error Path:/consumers Error:KeeperErrorCode = NodeExists for /consumers (org.apache.zookeeper.server.PrepRequestProcessor)
[2020-02-04 15:37:23,214] INFO Got user-level KeeperException when processing sessionid:0x100000298ee0000 type:create cxid:0x2 zxid:0x12d txntype:-1 reqpath:n/a Error Path:/brokers/ids Error:KeeperErrorCode = NodeExists for /brokers/ids (org.apache.zookeeper.server.PrepRequestProcessor)
[2020-02-04 15:37:23,230] INFO Got user-level KeeperException when processing sessionid:0x100000298ee0000 type:create cxid:0x3 zxid:0x12e txntype:-1 reqpath:n/a Error Path:/brokers/topics Error:KeeperErrorCode = NodeExists for /brokers/topics (org.apache.zookeeper.server.PrepRequestProcessor)

I have docker installed, but it is not running. The server.properties file is untouched.
I am not able to understand and debug why it is connecting to "host.docker.internal".

Note : Kafka ran successfully once. I remember I did a force shutdown of windows when kafka was running. I do not know whether this can be the issue.
I tried the lower version of kafka, I am still getting the same error.


问:
AngularJs $http request stays pending and does not return value from the database
I am currently writing a route which allows me to recieve information from a stored procudre I have in a database. I have written a request in AngularJS and a route in NodeJS but I am just recieving a pending request in the chrome Network developer window. I can see that the console.log in the NodeJs app has the data I require so it has retrieved it but there is nothing coming back in any of the console logs in the the AngularJS app.

Here is the code for the both the angularJS app and the Node App:

AnglaurJS:

```<code>checkForReplenishmentEmptyTrolley = async () => {
        LIBRIS.extensions.openLoadingModal();
        console.log('in checkForReplenishmentEmptyTrolley');
        try {
          const varPromise = await $http.get(`${LIBRIS.config.stockService}stockMovement/checkForUnattachedTrolley`)
            .then((response) => {
            console.log(response);
            // Request completed successfully
            }, (error) => {
            // Request error
            console.log(error);
            });
          console.log(varPromise.data);
          // 1. check that there are no ghost replenish - lines 1-15
          console.log('in try/catch');
          console.log('promise', varPromise);
        } catch (error) {
          console.log(error);
        }
      },
</code>```

NodeJS code:

```<code>app.get(`${ROUTE}/attachTrolley`, async function(req, res){
  const newRequest = await DB.newRequest();
  console.log('we have made it to the route');
  try {
    console.log('we have made it to the Try/Catch route');
    newRequest.input();
   const record = await newRequest.execute('dbo.usp_STK_CheckForUnattachedTrolley');
    res.json(record)
    console.log(record, 'record');
  } catch (err){
    handleError(res, err);
    console.log(err);
  }
});
</code>```

答: Solved it! I had no return statement in my route! </p>

Body:
I am currently writing a route which allows me to recieve information from a stored procudre I have in a database. I have written a request in AngularJS and a route in NodeJS but I am just recieving a pending request in the chrome Network developer window. I can see that the console.log in the NodeJs app has the data I require so it has retrieved it but there is nothing coming back in any of the console logs in the the AngularJS app.

Here is the code for the both the angularJS app and the Node App:

AnglaurJS:

checkForReplenishmentEmptyTrolley = async () => {
        LIBRIS.extensions.openLoadingModal();
        console.log('in checkForReplenishmentEmptyTrolley');
        try {
          const varPromise = await $http.get(`${LIBRIS.config.stockService}stockMovement/checkForUnattachedTrolley`)
            .then((response) => {
            console.log(response);
            // Request completed successfully
            }, (error) => {
            // Request error
            console.log(error);
            });
          console.log(varPromise.data);
          // 1. check that there are no ghost replenish - lines 1-15
          console.log('in try/catch');
          console.log('promise', varPromise);
        } catch (error) {
          console.log(error);
        }
      },

NodeJS code:

app.get(`${ROUTE}/attachTrolley`, async function(req, res){
  const newRequest = await DB.newRequest();
  console.log('we have made it to the route');
  try {
    console.log('we have made it to the Try/Catch route');
    newRequest.input();
   const record = await newRequest.execute('dbo.usp_STK_CheckForUnattachedTrolley');
    res.json(record)
    console.log(record, 'record');
  } catch (err){
    handleError(res, err);
    console.log(err);
  }
});


问:
Why files are missing while installing deb file?
I build a deb file for Apache2 from its source, also I was able to install and run successfully in the machine which I used to compile. But when I copy(SCP) that deb file to another machine and installed, log directory (/CloudS/Packages/apache2-cs/var/log/) for apache2 is missing in the newly installed system.in both cases,

Installed using command dpkg -i file_name.deb

Can someone say what will be the reason and how can I solve it?

Compiler:

```<code>root@compiler:/build/result# cd /CloudS/Packages/apache2-cs/
root@compiler:/CloudS/Packages/apache2-cs# ls
usr  var
</code>```

another machine :

```<code>root@ubuntu-1cpu-1gb-de-fra1:~# ls /CloudS/Packages/apache2-cs/
usr
root@ubuntu-1cpu-1gb-de-fra1:~#
</code>```

As you can see the "var" directory is missing when installing the same deb file on another machine. I used following config to build deb file

```<code>./configure --enable-layout=Debian --prefix=/CloudS/Packages/apache2-cs --sysconfdir=/etc/apache2-cs --enable-rewrite=shared --enable-speling=shared --with-pcre --with-include-apr --with-include-aprutils --enable-load-all-modules --with-suexec-caller=cloudS-www --with-suexec-logfile=/var/log/apache2-cs/suexec.log --with-suexec-bin=/usr/lib/apache2-cs/suexec --with-suexec-docroot=/var/www --with-suexec-userdir=public_html --with-suexec-uidmin=100 --enable-suexec=shared --with-program-name=apache2-cs --enable-logio
make clean
make
checkinstall --install=no --pakdir=/build/result/
</code>```

答: checkinstall only examines what make does, and make doesn't create any log files. You can force the addition of a path into the generated package with checkinstall's --include option. See further its manual page.

Body:
I build a deb file for Apache2 from its source, also I was able to install and run successfully in the machine which I used to compile. But when I copy(SCP) that deb file to another machine and installed, log directory (/CloudS/Packages/apache2-cs/var/log/) for apache2 is missing in the newly installed system.in both cases,

Installed using command dpkg -i file_name.deb

Can someone say what will be the reason and how can I solve it?

Compiler:

root@compiler:/build/result# cd /CloudS/Packages/apache2-cs/
root@compiler:/CloudS/Packages/apache2-cs# ls
usr  var

another machine :

root@ubuntu-1cpu-1gb-de-fra1:~# ls /CloudS/Packages/apache2-cs/
usr
root@ubuntu-1cpu-1gb-de-fra1:~#

As you can see the "var" directory is missing when installing the same deb file on another machine. I used following config to build deb file

./configure --enable-layout=Debian --prefix=/CloudS/Packages/apache2-cs --sysconfdir=/etc/apache2-cs --enable-rewrite=shared --enable-speling=shared --with-pcre --with-include-apr --with-include-aprutils --enable-load-all-modules --with-suexec-caller=cloudS-www --with-suexec-logfile=/var/log/apache2-cs/suexec.log --with-suexec-bin=/usr/lib/apache2-cs/suexec --with-suexec-docroot=/var/www --with-suexec-userdir=public_html --with-suexec-uidmin=100 --enable-suexec=shared --with-program-name=apache2-cs --enable-logio
make clean
make
checkinstall --install=no --pakdir=/build/result/


问:
How many tables per MySQL database?
On godaddy it says I get 25 databases. Does that mean that I only get 25 tables or can I have multiple tables in a database? Thanks in advance.</p>

答:
MySQL has no limit on the number of databases. The underlying file system may have a limit on the number of directories.

Ref: https://dev.mysql.com/doc/refman/8.0/en/database-count-limit.html

More info: https://www.quora.com/Is-there-a-maximum-number-of-tables-a-MySQL-database-can-have?share=1

Title: How many tables per MySQL database?


问:
How do i Quickly Process a csproj file in c#
I'm making a Pre-Compiler meaning it will read a load of files and process a few custom preprocessor directives. but no matter how much I look online I can't find a working processor for the .csproj file. I can read them and extract data. but I can't process them to extract state with Configuration and platform parameters.

what I mean is, if I have a csproj that adds a few preprocessor directives if on the DEBUG build and others on the RELEASE build, I want to be able to process the file so that when I build of DEBUG I correctly get all then defined Preprocessors and likewise for the RELEASE build.

I'm going to be processing dotnet core projects to be specific.

答:
I want to get the file state after processing all conditions using the
  Platform and Configuration. this includes stuff like OutputPath,
  AllowUnsafe, BuildTargets and such.

The c# compiler, unlike the c++ compiler, does not have specific precompiled instruction item elements destined for the compiler like PreprocessorDefinitions.

As a suggestion, you can try to add a custom target in xxxx.csproj file to execute some msbuild task to do some preprocessing. And you want to do all of these after pre-build target, you can just set AfterTargets="PrepareForBuild" to this custom target which means it runs after PrepareForBuild target.

Suggesstion

Just like this:

```<code><Target Name="CustomPreprocessor" AfterTargets="PrepareForBuild">

<Message Importance="high" Text="$(OutputPath)--$(AllowUnsafeBlocks)--$(PrepareForBuildDependsOn)" ></Message>

 ........//other msbuild task

 </Target>
</code>```

1)  If you want to use the configuration as a condition and execute different pre-instructions according to Debug or Release, you can use MSBuild conditions.
If you want to use Debug, you can refer to this:

```<code><Target Name="CustomPreprocessor" AfterTargets="PrepareForBuild" Condition=" '$(Configuration)' == 'Debug' ">
</code>```

At the same time, if you also want to add palform as a parallel condition, please try this:

```<code> <Target Name="CustomPreprocessor" AfterTargets="PrepareForBuild" Condition=" '$(Configuration)' == 'Debug' and '$(Platform)' =='Any CPU' ">
</code>```

2) Since outputpath and AllowUnsafe are MSBuild properties, you can use $(outputpath) and $(AllowUnsafeBlocks) to get their values while you can use @(...) to get values of MSBuild items.

3) Basically, to execute a preinstruction in target, you can do it with a task, you can refer to this document to add any task as you want to do any operation.

Body:
I want to get the file state after processing all conditions using the
  Platform and Configuration. this includes stuff like OutputPath,
  AllowUnsafe, BuildTargets and such.

The c# compiler, unlike the c++ compiler, does not have specific precompiled instruction item elements destined for the compiler like PreprocessorDefinitions.

As a suggestion, you can try to add a custom target in xxxx.csproj file to execute some msbuild task to do some preprocessing. And you want to do all of these after pre-build target, you can just set AfterTargets="PrepareForBuild" to this custom target which means it runs after PrepareForBuild target.

Suggesstion

Just like this:

<Target Name="CustomPreprocessor" AfterTargets="PrepareForBuild">

<Message Importance="high" Text="$(OutputPath)--$(AllowUnsafeBlocks)--$(PrepareForBuildDependsOn)" ></Message>

 ........//other msbuild task

 </Target>

1)  If you want to use the configuration as a condition and execute different pre-instructions according to Debug or Release, you can use MSBuild conditions.
If you want to use Debug, you can refer to this:

<Target Name="CustomPreprocessor" AfterTargets="PrepareForBuild" Condition=" '$(Configuration)' == 'Debug' ">

At the same time, if you also want to add palform as a parallel condition, please try this:

 <Target Name="CustomPreprocessor" AfterTargets="PrepareForBuild" Condition=" '$(Configuration)' == 'Debug' and '$(Platform)' =='Any CPU' ">

2) Since outputpath and AllowUnsafe are MSBuild properties, you can use $(outputpath) and $(AllowUnsafeBlocks) to get their values while you can use @(...) to get values of MSBuild items.

3) Basically, to execute a preinstruction in target, you can do it with a task, you can refer to this document to add any task as you want to do any operation.


问:
I am trying to load a CRAN dataset for sp using the read.table function, however I do not know if I have access to the data
I am following the examples in the book "Spatial Analysis with R". I have loaded the sp package and I am trying to read the table using:

```<code> Cran_df<-read.table("CRAN051001a.txt", header = TRUE)
</code>```

I am receiving the errors:

```<code> Error in file(file, "rt") : cannot open the connection
 In addition: Warning message:
 In file(file, "rt") :
 cannot open file 'CRAN051001a.txt': No such file or directory
</code>```

How do I get the required data for this exercise?

答:
By using the full URL:

```<code>Cran_df<-read.table("http://www.asdar-book.org/datasets/CRAN051001a.txt", header = TRUE)
</code>```

Now your object Cran_df should be ok:

```<code>str(Cran_df)

'data.frame':   54 obs. of  6 variables:
$ place: Factor w/ 52 levels "Aalborg","Aizu",..: 9 31 50 15 49 39 36 40 12 46 ...
$ north: Factor w/ 52 levels "20d45'S","22d43'S",..: 8 18 41 7 1 3 2 4 43 29 ...
$ east : Factor w/ 51 levels "0d10'W","118d15'W",..: 19 16 20 35 31 32 34 33 11 39 ...
$ loc  : Factor w/ 30 levels "Australia","Austria",..: 1 1 2 3 3 3 3 3 4 19 ...
$ long : num  153 145 16.3 -49.3 -42.9 ...
$ lat  : num  -27.5 -37.8 48.2 -25.4 -20.8 ...
</code>```

Body:
I am following the examples in the book "Spatial Analysis with R". I have loaded the sp package and I am trying to read the table using:

 Cran_df<-read.table("CRAN051001a.txt", header = TRUE)

I am receiving the errors:

 Error in file(file, "rt") : cannot open the connection
 In addition: Warning message:
 In file(file, "rt") :
 cannot open file 'CRAN051001a.txt': No such file or directory

How do I get the required data for this exercise?

Body:
By using the full URL:

Cran_df<-read.table("http://www.asdar-book.org/datasets/CRAN051001a.txt", header = TRUE)

Now your object Cran_df should be ok:

str(Cran_df)

'data.frame':   54 obs. of  6 variables:
$ place: Factor w/ 52 levels "Aalborg","Aizu",..: 9 31 50 15 49 39 36 40 12 46 ...
$ north: Factor w/ 52 levels "20d45'S","22d43'S",..: 8 18 41 7 1 3 2 4 43 29 ...
$ east : Factor w/ 51 levels "0d10'W","118d15'W",..: 19 16 20 35 31 32 34 33 11 39 ...
$ loc  : Factor w/ 30 levels "Australia","Austria",..: 1 1 2 3 3 3 3 3 4 19 ...
$ long : num  153 145 16.3 -49.3 -42.9 ...
$ lat  : num  -27.5 -37.8 48.2 -25.4 -20.8 ...


问:
getting value error when tried to make subplots for list of dataframe with matplotlib?
I have a list of dataframe that I want to render a line chart where making subplots for each dataframe. whereas two different dataframes in the list share same column structures. I want to make subplots (line chart) with minimal code possible. To do so, I referenced this post on SO but didn't get correct subplots. Below is my current approach for one dataframe:

reproducible data:

here is the minimal list of dataframe on gist file which concatenated from list of dataframes. each of dataframe looks like this:

[![enter image description here][3]][3]

my initial approach

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

df1=list_of_df[1]
fig, ax=plt.subplots(figsize=(14,8))
plt.plot(df1.index, df['2014'], label="2014")
plt.plot(df1.index, df['2015'], label="2015")
plt.plot(df1.index, df['2016'], label="2016")
plt.plot(df1.index,df['2017'], label="2017")
plt.plot(df1.index,df['2018'], label="2018")
plt.plot(df1.index,df['avg'],  "--", label="5-Yr-Avg")
plt.show()
</code>```

my initial output for single dataframe:

here is the output of above attempt:

[![enter image description here][4]][4]

I am trying to loop through this list of dataframe to get subplots so it can be much easier to compare two subplots with different data. I couldn't able to get that. How can I make this happen? any idea? Thanks

if I used SO post solution

```<code>nrow=2
ncol=2
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
    for c in range(ncol):
        list_of_df[count].plot(ax=axes[r,c])
        count=+1
</code>```

the output of this code is not correct. I am expecting two subplots for two dataframe. How to fix this? I think iterating column was wrong, that's why I got 6 subplots, I should iterate by the index of dataframe. Any idea?

my new attempt:

I am trying to reduce line of codes that implemented in my initial attempt. Since I have list of dataframe, I might code as follow:

```<code>fig, ax = plt.subplots(figsize=(10,8))
for x in range(len(df_list)):
    ax.plot(df_list[x].index, df_list[x].columns, kind='line')

plt.show()
</code>```

but this gave me value error as follow:

```<code>ValueError: x and y must have same first dimension, but have shapes (12,) and (6,)
</code>```

why this error raised? Is there any way to generalize my initial implementation to list of dataframe for making subplots? any idea?

答:
```<code>import pandas as pd
import matplotlib.pyplot as plt
df_1 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
df_2 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
df_3 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
list_df = [df_1,df_2,df_3]
for i,j in enumerate(list_df):
    plt.figure(i)
    j.plot(kind = 'line')
</code>```

I find this  to be quite easy way to understand when making subplots.As you can see it can be easily used to match your requirements.

Body:
I have a list of dataframe that I want to render a line chart where making subplots for each dataframe. whereas two different dataframes in the list share same column structures. I want to make subplots (line chart) with minimal code possible. To do so, I referenced this post on SO but didn't get correct subplots. Below is my current approach for one dataframe:

reproducible data:

here is the minimal list of dataframe on gist file which concatenated from list of dataframes. each of dataframe looks like this:

[![enter image description here][3]][3]

my initial approach

import matplotlib.pyplot as plt

df1=list_of_df[1]
fig, ax=plt.subplots(figsize=(14,8))
plt.plot(df1.index, df['2014'], label="2014")
plt.plot(df1.index, df['2015'], label="2015")
plt.plot(df1.index, df['2016'], label="2016")
plt.plot(df1.index,df['2017'], label="2017")
plt.plot(df1.index,df['2018'], label="2018")
plt.plot(df1.index,df['avg'],  "--", label="5-Yr-Avg")
plt.show()

my initial output for single dataframe:

here is the output of above attempt:

[![enter image description here][4]][4]

I am trying to loop through this list of dataframe to get subplots so it can be much easier to compare two subplots with different data. I couldn't able to get that. How can I make this happen? any idea? Thanks

if I used SO post solution

nrow=2
ncol=2
fig, axes = plt.subplots(nrow, ncol)
# plot counter
count=0
for r in range(nrow):
    for c in range(ncol):
        list_of_df[count].plot(ax=axes[r,c])
        count=+1

the output of this code is not correct. I am expecting two subplots for two dataframe. How to fix this? I think iterating column was wrong, that's why I got 6 subplots, I should iterate by the index of dataframe. Any idea?

my new attempt:

I am trying to reduce line of codes that implemented in my initial attempt. Since I have list of dataframe, I might code as follow:

fig, ax = plt.subplots(figsize=(10,8))
for x in range(len(df_list)):
    ax.plot(df_list[x].index, df_list[x].columns, kind='line')

plt.show()

but this gave me value error as follow:

ValueError: x and y must have same first dimension, but have shapes (12,) and (6,)

why this error raised? Is there any way to generalize my initial implementation to list of dataframe for making subplots? any idea?

Body:
import pandas as pd
import matplotlib.pyplot as plt
df_1 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
df_2 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
df_3 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
list_df = [df_1,df_2,df_3]
for i,j in enumerate(list_df):
    plt.figure(i)
    j.plot(kind = 'line')

I find this  to be quite easy way to understand when making subplots.As you can see it can be easily used to match your requirements.


问:
Can you do this using jquery?
Is it possible to do this from within a class?

```<code>   $("#" + field).click(this.validate);
</code>```

So basically I want to pass a function of the object that should be executed whenever something is clicked. Also, if there are more than 1 instances of this object, then the correct instance (i.e the one which runs this code for the given field) should be executed.

答:
I am not sure about an easy way, but you can always go the closure route:</p>

```<code>var that = this;
$("#" + field).click(function() {
    that.validate();
});
</code>```

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

Title: Can you do this using jquery?

Body:
Is it possible to do this from within a class?

   $("#" + field).click(this.validate);

So basically I want to pass a function of the object that should be executed whenever something is clicked. Also, if there are more than 1 instances of this object, then the correct instance (i.e the one which runs this code for the given field) should be executed.

Body:
I am not sure about an easy way, but you can always go the closure route:

var that = this;
$("#" + field).click(function() {
    that.validate();
});

OwnerDisplayName: Andrey Shchekin


问:
Python: concatenate an integer array with 1 empty array
I have one simple one-dimensional array and an empty array in NumPy. I try to concatenate them, but I get an array in float.

```<code>from numpy import *
a = zeros(5,'i')
a += 1
b = []
c = hstack((a,b))
d = concatenate((a, b))
print("a",a)
print("b",b)
print("c",c)
print("d",d)
</code>```

I got:

```<code>a [1 1 1 1 1]

b []

c [1. 1. 1. 1. 1.]

d [1. 1. 1. 1. 1.]
</code>```

But I am looking for an integer array

```<code>[1 1 1 1 1]
</code>```

How? And what is the most efficient way?

答:
What is point you willing to have same array as input ?

use numpy.ones to reduce computation instead of numpy.zeros

`

```<code>import numpy
a = numpy.ones(5,dtype=int)
b = []
b = numpy.array([],dtype=int)
d = concatenate((a, b))
</code>```

`

Body:
I have one simple one-dimensional array and an empty array in NumPy. I try to concatenate them, but I get an array in float.

from numpy import *
a = zeros(5,'i')
a += 1
b = []
c = hstack((a,b))
d = concatenate((a, b))
print("a",a)
print("b",b)
print("c",c)
print("d",d)

I got:

a [1 1 1 1 1]

b []

c [1. 1. 1. 1. 1.]

d [1. 1. 1. 1. 1.]

But I am looking for an integer array

[1 1 1 1 1]

How? And what is the most efficient way?

Body:
What is point you willing to have same array as input ?

use numpy.ones to reduce computation instead of numpy.zeros

`

import numpy
a = numpy.ones(5,dtype=int)
b = []
b = numpy.array([],dtype=int)
d = concatenate((a, b))

`


问:
nginx conf express and assets returning 404
Have been at this all day and so far not getting to where I'd a liked to have been.

Running pretty much the latest version of everything as just building a new server to move off IIS/IISNode.

I have nginx installed and some conf going that serves only my main index file from a sub dir of /vra/www/. However it does not load any assets or sub-dir pages.

If I call the assets directly, using lowercase URL it returns 404 but uppercase URLs where needed work fine.

My conf example can be seen here: pastebin.com/a12TqP6w

答: Needed to drop some extra things I had inside my conf file</p>


问:
F# XmlProvider and parsing collection
I have a question. I have a simple configuation in a file that looks:

```<code><configuration>
  <Protocol Version="1" />
  <RequestParameters>
    <ModuleIdentyfication Interval="500" />
    <SectionIdentification Interval="500" />
  </RequestParameters>
</configuration>
</code>```

Config file is in the same folder as app so my reading module looks like:

```<code>[<Literal>]
let private cabinetConfigFilename : string = "cabinet.config";

type Communication = XmlProvider<cabinetConfigFilename>

let GetConnectionConfiguration : Async<Option<ServiceConfiguration>> =
    async {
        let assemblyPathInfo = FileInfo(Assembly.GetEntryAssembly().Location);
        let configurationFilePath = Path.Combine(assemblyPathInfo.DirectoryName, cabinetConfigFilename);
        let root = Communication.Parse((File.ReadAllTextAsync(configurationFilePath) |> Async.AwaitTask |> Async.RunSynchronously))

        try
            let protocolVersion : uint8 = uint8 root.Protocol.Version
            let requestParameters = Communication.Parse (string root.RequestParameters)
            for param in requestParameters do printf " - "

            return Some (ServiceConfiguration(protocolVersion))
        with
            | :? ArgumentNullException -> logger.Error("No IP address was given"); return None;
            | :? FormatException -> logger.Error("IP address incorrect format was given"); return None
    }
</code>```

So I have no problem, with getting Protocol.Version, but problem is with parsing that RequestParameters, I am getting a whole XProvider object but I can not use it as seq. I tried to do it as is written in https://fsharp.github.io/FSharp.Data/library/XmlProvider.html in Types for multiple simple elements section. Is there a way to cast it to sequence.

答:
The easiest (read: laziest) way if you just have these two types, is to simply double up the sample:

```<code><RequestParameters>
  <ModuleIdentification Interval="500" />
  <ModuleIdentification Interval="500" />
  <SectionIdentification Interval="500" />
  <SectionIdentification Interval="500" />
</RequestParameters>
</code>```

Now you can access the array of elements using:
RequestParameters.ModuleIdentifications and RequestParameters.SectionIdentifications.

A better way to go about this is to generate an XSD for your XML,
and use the type provider with

```<code>FSharp.Data.XmlProvider<Schema = ...>
</code>```

Title: F# XmlProvider and parsing collection

Body:
I have a question. I have a simple configuation in a file that looks:

<configuration>
  <Protocol Version="1" />
  <RequestParameters>
    <ModuleIdentyfication Interval="500" />
    <SectionIdentification Interval="500" />
  </RequestParameters>
</configuration>

Config file is in the same folder as app so my reading module looks like:

[<Literal>]
let private cabinetConfigFilename : string = "cabinet.config";

type Communication = XmlProvider<cabinetConfigFilename>

let GetConnectionConfiguration : Async<Option<ServiceConfiguration>> =
    async {
        let assemblyPathInfo = FileInfo(Assembly.GetEntryAssembly().Location);
        let configurationFilePath = Path.Combine(assemblyPathInfo.DirectoryName, cabinetConfigFilename);
        let root = Communication.Parse((File.ReadAllTextAsync(configurationFilePath) |> Async.AwaitTask |> Async.RunSynchronously))

        try
            let protocolVersion : uint8 = uint8 root.Protocol.Version
            let requestParameters = Communication.Parse (string root.RequestParameters)
            for param in requestParameters do printf " - "

            return Some (ServiceConfiguration(protocolVersion))
        with
            | :? ArgumentNullException -> logger.Error("No IP address was given"); return None;
            | :? FormatException -> logger.Error("IP address incorrect format was given"); return None
    }

So I have no problem, with getting Protocol.Version, but problem is with parsing that RequestParameters, I am getting a whole XProvider object but I can not use it as seq. I tried to do it as is written in https://fsharp.github.io/FSharp.Data/library/XmlProvider.html in Types for multiple simple elements section. Is there a way to cast it to sequence.

Body:
The easiest (read: laziest) way if you just have these two types, is to simply double up the sample:

<RequestParameters>
  <ModuleIdentification Interval="500" />
  <ModuleIdentification Interval="500" />
  <SectionIdentification Interval="500" />
  <SectionIdentification Interval="500" />
</RequestParameters>

Now you can access the array of elements using:
RequestParameters.ModuleIdentifications and RequestParameters.SectionIdentifications.

A better way to go about this is to generate an XSD for your XML,
and use the type provider with

FSharp.Data.XmlProvider<Schema = ...>


问:
Error when trying to create my table in sqlalchemy => sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: dht_new
It cant find my db even tho i have created it wite create_table? I have tried to put the function
create_Table" in diffrent places with no result? However i get the error,

```<code>sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: dht_new
[SQL: INSERT INTO dht_new (name) VALUES (?)]
[parameters: (None,)]
</code>```

app.py

```<code>import os
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from flask_sqlalchemy import SQLAlchemy
from db import db

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///newdata.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

@app.before_first_request
def create_tables():
    db.create_all()

class fixdb(db.Model):
    __tablename__ = 'dht_new'

    id = db.Column(db.Integer, primary_key =True)
    name = db.Column(db.String(80))

    def __init__(self, temp):
        self.temp = temp

    def add_to_db(self):
        db.session.add(self)
        db.session.commit()

@app.route('/get', methods=['GET'])
def postrandom():
    temp = {'temperature': '23'}
    test_temp = fixdb(temp)

    test_temp.add_to_db()
    return jsonify(temp)

if __name__ == '__main__':
    from db import db
    db.init_app(app)
    app.run(port=5000, debug=True)
</code>```

答:
run.py</p>

```<code>from app import app
from db import db

db.init_app(app)

@app.before_first_request
def create_tables():
    db.create_all()
</code>```

Body:
It cant find my db even tho i have created it wite create_table? I have tried to put the function
create_Table" in diffrent places with no result? However i get the error,

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: dht_new
[SQL: INSERT INTO dht_new (name) VALUES (?)]
[parameters: (None,)]

app.py

import os
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from flask_sqlalchemy import SQLAlchemy
from db import db

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///newdata.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

@app.before_first_request
def create_tables():
    db.create_all()

class fixdb(db.Model):
    __tablename__ = 'dht_new'

    id = db.Column(db.Integer, primary_key =True)
    name = db.Column(db.String(80))

    def __init__(self, temp):
        self.temp = temp

    def add_to_db(self):
        db.session.add(self)
        db.session.commit()

@app.route('/get', methods=['GET'])
def postrandom():
    temp = {'temperature': '23'}
    test_temp = fixdb(temp)

    test_temp.add_to_db()
    return jsonify(temp)

if __name__ == '__main__':
    from db import db
    db.init_app(app)
    app.run(port=5000, debug=True)

Body:
run.py

from app import app
from db import db

db.init_app(app)

@app.before_first_request
def create_tables():
    db.create_all()


问:
Containerized kubelet and local disk volume lifecycle
Platform: OEL 7.7 + kube 1.15.5 + docker 19.03.1

We're building an erasure-coded object store on k8s using a containerized kubelet approach. We're having a tough time coming up with a viable disk life cycle approach. As it is now, we must provide an "extra_binds" argument to the kubelet which specifies the base mount point where our block devices are mounted. (80 SSDs per node, formatted as ext4)

That all works fine. Creating PV's and deploying apps works fine. Our problem comes when a PVC is deleted and we want to scrub the disk(s) that were used and make the disk(s) available again.

So far the only thing that works is to cordon that node, remove the extra binds from kubelet, bounce the node, reconfigure the block device, re-add the kubelet binds. Obviously this is too clunky for production. For starters, bouncing kubelet is not an option.

Once a PV gets used, something is locking this block device, even though checking lsof on the bare metal system shows non open handles. I can't unmount or create a new filesystem on the device. Merely bouncing kubelet doesn't free up the "lock".

Anyone using a containerized kubernetes control plane with an app using local disks in a similar fashion? Anyone found a viable way to work around this issue?

Our long term plan is to write an operator that manages disks but even with an operator I don't see how it can mitigate this problem.

Thanks for any help,

答:
First look at your Finalizers:

```<code>$ kubectl describe pvc <PVC_NAME> | grep Finalizers
$ kubectl describe pv <PV_NAME> | grep Finalizers
</code>```

if they are set to Finalizers:    [kubernetes.io/pvc-protection] (explained here) that mean they are protected and you need to edit that, for example using:

$ kubectl patch pvc <PVC_NAME> -p '{"metadata":{"finalizers":null}}'

As for forcefully removing PersistentVolumes you can try

$ kubectl delete pv <PV_NAME> --force --grace-period=0

Also please check VolumeAttachment do still exist $ kubectl get volumeattachment as they might be blocked.

I also remember there was as issue on stack Kubernetes PV refuses to bind after delete/re-create stating that pv holds uid of pvc that was claimed by.
You can check that by displaying whole yaml of the pv:

$ kubectl get pv <PV_NAME> -o yaml and looking for:

```<code>  claimRef:
    apiVersion: v1
    kind: PersistentVolumeClaim
    name: packages-pvc
    namespace: default
    resourceVersion: "10218121"
    uid: 1aede3e6-eaa1-11e9-a594-42010a9c0005
</code>```

You would need to provide more information regarding your k8s cluster and pv, pvc configuration so I could go deeper into to or even test it.

Body:
First look at your Finalizers:

$ kubectl describe pvc <PVC_NAME> | grep Finalizers
$ kubectl describe pv <PV_NAME> | grep Finalizers

if they are set to Finalizers:    [kubernetes.io/pvc-protection] (explained here) that mean they are protected and you need to edit that, for example using:

$ kubectl patch pvc <PVC_NAME> -p '{"metadata":{"finalizers":null}}'

As for forcefully removing PersistentVolumes you can try

$ kubectl delete pv <PV_NAME> --force --grace-period=0

Also please check VolumeAttachment do still exist $ kubectl get volumeattachment as they might be blocked.

I also remember there was as issue on stack Kubernetes PV refuses to bind after delete/re-create stating that pv holds uid of pvc that was claimed by.
You can check that by displaying whole yaml of the pv:

$ kubectl get pv <PV_NAME> -o yaml and looking for:

  claimRef:
    apiVersion: v1
    kind: PersistentVolumeClaim
    name: packages-pvc
    namespace: default
    resourceVersion: "10218121"
    uid: 1aede3e6-eaa1-11e9-a594-42010a9c0005

You would need to provide more information regarding your k8s cluster and pv, pvc configuration so I could go deeper into to or even test it.


问:
Nightwatch: Basic auth with access_key not working
I created nightwatch.json file like below (with username and access_key properties):

```<code>"test_settings": {
        "default": {
            "launch_url": "http://localhost",
            "selenium_port": 4444,
            "selenium_host": "localhost",
            "silent": true,
            "cli_args": {
                "webdriver.firefox.profile": "testprofile"
            },
            "screenshots": {
                "enabled": false,
                "path": "screenshots/"
            },
            "desiredCapabilities": {
                "browserName": "firefox",
                "javascriptEnabled": true,
                "acceptSslCerts": true
            },
            "username": "examplelogin",
            "access_key": "password"
        }
</code>```

but basic auth don't work and I get login window to fill my password and login after running tests. I looked at packets in fiddler and no authorization header was present. Any ideas what I'm doing wrong?

Nightwatch v0.9.6

答:
You can do this in globals.js. It will preserve credentials and skip basic auth prompt.

```<code>beforeEach: function (browser, cb) {
  if (browser.globals.basic_auth_url) {
    browser.url(browser.globals.basic_auth_url, cb);
  } else {
    cb();
  }
},
</code>```

basic_auth_url - add full URL with credentials.

Do not add credentials to launch_url

Body:
I created nightwatch.json file like below (with username and access_key properties):

"test_settings": {
        "default": {
            "launch_url": "http://localhost",
            "selenium_port": 4444,
            "selenium_host": "localhost",
            "silent": true,
            "cli_args": {
                "webdriver.firefox.profile": "testprofile"
            },
            "screenshots": {
                "enabled": false,
                "path": "screenshots/"
            },
            "desiredCapabilities": {
                "browserName": "firefox",
                "javascriptEnabled": true,
                "acceptSslCerts": true
            },
            "username": "examplelogin",
            "access_key": "password"
        }

but basic auth don't work and I get login window to fill my password and login after running tests. I looked at packets in fiddler and no authorization header was present. Any ideas what I'm doing wrong?

Nightwatch v0.9.6

Body:
You can do this in globals.js. It will preserve credentials and skip basic auth prompt.

beforeEach: function (browser, cb) {
  if (browser.globals.basic_auth_url) {
    browser.url(browser.globals.basic_auth_url, cb);
  } else {
    cb();
  }
},

basic_auth_url - add full URL with credentials.

Do not add credentials to launch_url