问:
error in json function saving data into database
I have tried a lot but I have not been able to find out what is wrong with this function to save two values into database. It has been working fine for another function to save one value. It behaves very strange here. Sometimes send 'parent' value & sometimes stop sending it but never send msg value. Here is function. It works fine for one input i.e. parent but problems start with the addition of 2nd input.

```<code><script>
function ADDLISITEM(form)
{
var parent = form.txtInput.value;
    var msg    = form.msgInput.value;
    form.txtInput.value = "";
    form.msgInput.value = "";
    var url = "send_mysql.php"
var request = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
request=new XMLHttpRequest();
 }
else
{// code for IE6, IE5
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function(){
    if (request.readyState == 4) {
        if (request.status == 200) {
            //alert('POST');
    } else {
        alert(request.status); // fails here
    }
    }
}
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" +
    encodeURIComponent(msg).replace(/%20/g, '+'));
}
</script>
</code>```

This is send.php

      $username = "babar";

      $password = "k4541616";

      $hostname = "localhost";

      $dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect

      to MySQL");

      $selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");

```<code>  //die(var_export($_POST,TRUE));

  $parent = $_POST['parent'];
  $msg = $_POST['msg'];
  $name   = 'Akhtar Nutt';
  //$parent2 = json_decode($parent);
  $msg_ID = '2q7b2sfwwe';
  //$msg2    = json_decode($msg);
  $query  =  "INSERT INTO msg2_Qualities(id,name,msg,msg_id,parent) VALUES
  ('','$name','$msg','$msg_ID','$parent')";
    if(!mysql_query($query, $dbh))
        {die('error:' .mysql_error())
      ;}
</code>```

?>

答:
Alter

```<code>request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
</code>```

to:

```<code>request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
</code>```

You're missing the argument separator & in your query string...

You also might want to refrain from using values in $_REQUEST as they aren't reliable. If your script expects data from a POST then retrieve these values from $_POST.

Body:
I have tried a lot but I have not been able to find out what is wrong with this function to save two values into database. It has been working fine for another function to save one value. It behaves very strange here. Sometimes send 'parent' value & sometimes stop sending it but never send msg value. Here is function. It works fine for one input i.e. parent but problems start with the addition of 2nd input.

This is send.php

      $username = "babar";

      $password = "k4541616";

      $hostname = "localhost";

      $dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect

      to MySQL");

      $selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");

  //die(var_export($_POST,TRUE));

  $parent = $_POST['parent'];
  $msg = $_POST['msg'];
  $name   = 'Akhtar Nutt';
  //$parent2 = json_decode($parent);
  $msg_ID = '2q7b2sfwwe';
  //$msg2    = json_decode($msg);
  $query  =  "INSERT INTO msg2_Qualities(id,name,msg,msg_id,parent) VALUES
  ('','$name','$msg','$msg_ID','$parent')";
    if(!mysql_query($query, $dbh))
        {die('error:' .mysql_error())
      ;}

?>

Body:
Alter

request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));

to:

request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));

You're missing the argument separator & in your query string...

You also might want to refrain from using values in $_REQUEST as they aren't reliable. If your script expects data from a POST then retrieve these values from $_POST.


来源: stackexchange

问:
Python's pyparsing: Implementing grammar to parse logical AND expression
I am trying to parse and evaluate expressions, given to me as input from a file, of the form:

```<code>var[3] = 0 and var[2] = 1
var[0] = 1 and var[2] = 0 and var[3] = 1
...
</code>```

(actually I also allow "multibit access" (i.e. var[X:Y]) but let's ignore it for now...)

Where var is an integer, and the [] indicates bit access.

For example, for var = 0x9, the first expression above should be evaluated to False, and the second should be evaluated to True since 0x9 = b1001.

and and = are the only binary operators I allow, and for the = operator, the left operand is always var[X] and the right operand is always a number.

I tried to look around a bit and found that this could be achieved with Python's pyparsing, but I ran into some difficulties trying to implement it.

Here's what I've tried so far, based roughly on this example (which is one of many examples provided here):

```<code>#!/usr/bin/env python
from pyparsing import Word, alphas, nums, infixNotation, opAssoc

class BoolAnd():
    def __init__(self, pattern):
        self.args = pattern[0][0::2]

    def __bool__(self):
        return all(bool(a) for a in self.args)

    __nonzero__ = __bool__

class BoolEqual():
    def __init__(self, pattern):
        self.bit_offset = int(pattern[0][1])
        self.value = int(pattern[0][-1])

    def __bool__(self):
        return True if (0xf >> self.bit_offset) & 0x1 == self.value else False # for now, let's assume var == 0xf

    __nonzero__ = __bool__

variable_name   = 'var'
bit_access      = variable_name + '[' + Word(nums) + ']'
multibit_access = variable_name + '[' + Word(nums) + ':' + Word(nums) + ']'
value = Word(nums)

operand = bit_access | multibit_access | value

expression = infixNotation(operand,
    [
    ('=',   2, opAssoc.LEFT,  BoolEqual),
    ('AND', 2, opAssoc.LEFT,  BoolAnd),
    ])

p = expression.parseString('var[3] = 1 AND var[1] = 0', True)

print 'SUCCESS' if bool(p) else 'FAIL'
</code>```

I have three problems I need help with.

For multibit access of the form var[X:Y] = Z, how do I enforce that:

a. X > Y

b. Z < 2^{X - Y + 1}

I assume this can't be enforced by the grammar itself (for example, for single-bit access of the form var[X] = Y, I can enforce by the grammar that Y will be either 0 or 1, and this will cause the expression.parseString() to fail with exception if Y != 0/1).

Most importantly: Why does it always print SUCCESS? What am I doing wrong?

For the input var[3] = 1 AND var[1] = 0 it should be print FAIL (you can see in my example that I hardcoded var to be 0xf, so var[3] = 1 is True but var[1] = 0 is False).

Which brings me to my third problem: var is not a class member of BoolEqual nor is it global... is there a way to somehow send it to BoolEqual's __init__ function?

答:
Before getting to the problem solving, I suggest some minor changes to your grammar, primarily the inclusion of results names. Adding these names will make your resulting code much cleaner and robust. I'm also using some of the expressions that were added in recent pyparsing versions, in the pyparsing_common namespace class:

```<code>from pyparsing import pyparsing_common

variable_name   = pyparsing_common.identifier.copy()
integer = pyparsing_common.integer.copy()
bit_access      = variable_name('name') + '[' + integer('bit') + ']'
multibit_access = variable_name('name') + '[' + integer('start_bit') + ':' + integer('end_bit') + ']'
</code>```

Part 1a: Enforcing valid values in "var[X:Y]"

This kind of work is best done using parse actions and conditions. Parse actions are parse-time callbacks that you can attach to your pyparsing expressions to modify, enhance, filter the results, or raise an exception if a validation rule fails. These are attached using the method:

```<code>expr.addParseAction(parse_action_fn)
</code>```

And parse_action_fn can have any of the following signatures:

```<code>def parse_action_fn(parse_string, parse_location, matched_tokens):
def parse_action_fn(parse_location, matched_tokens):
def parse_action_fn(matched_tokens):
def parse_action_fn():
</code>```

(See more at https://pythonhosted.org/pyparsing/pyparsing.ParserElement-class.html#addParseActio)n)

Parse actions can return None, return new tokens, modify the given tokens, or raise an exception.

If all the parse action does is evaluate some condition based on the input tokens, you can write it as a simple function that returns True or False, and pyparsing will raise an exception if False is returned. In your case, your first validation rule could be implemented as:

```<code>def validate_multibit(tokens):
    return tokens.end_bit > tokens.start_bit
multibit_access.addCondition(validate_multibit,
                            message="start bit must be less than end bit",
                            fatal=True)
</code>```

Or even just as a Python lambda function:

```<code>multibit_access.addCondition(lambda t: t.end_bit > t.start_bit,
                            message="start bit must be less than end bit",
                            fatal=True)
</code>```

Now you can try this with:

```<code>multibit_access.parseString("var[3:0]")
</code>```

And you will get this exception:

```<code>pyparsing.ParseFatalException: start bit must be less than end bit (at char 0), (line:1, col:1)
</code>```

Part 1b: Enforcing valid values in "var[X:Y] = Z"

Your second validation rule deals not only with the var bit ranges but also the value it is being compared to. This will require a parse action that is attached to the complete BoolEqual. We could put this in BoolEqual's __init__ method, but I prefer to separate independent functions when possible. And since we will be adding our validation by attaching to the infixNotation level, and infixNotation only accepts parse actions, we will need to write your second validation rule as a parse action that raises an exception. (We will also use a new feature that was only recently released in pyparsing 2.2.0, attaching multiple parse actions at a level in infixNotation.)

Here is the validation that we will wish to perform:

if single bit expression, value must be 0 or 1

if multibit expression var[X:Y], value must be < 2**(Y-X+1)

```def validate_equality_args(tokens):
    tokens = tokens[0]
    z = tokens[-1]
    if 'bit' in tokens:
        if z not in (0,1):
            raise ParseFatalException("invalid equality value - must be 0 or 1")
    else:
        x = tokens.start_bit
        y = tokens.end_bit
        if not z < 2**(y - x + 1):
            raise ParseFatalException("invalid equality value")</p></li>
</ul>

<p>And we attach this parse action to <code>infixNotation</code> using:</p>

```expression = infixNotation(operand,
    [
    ('=',   2, opAssoc.LEFT,  (validate_equality_args, BoolEqual)),
    ('AND', 2, opAssoc.LEFT,  BoolAnd),
    ])
```

<p>Part 3: Supporting other var names and values than 0xf</p>

<p>To deal with vars of various names, you can add a class-level dict to BoolEqual:</p>

```class BoolEqual():
    var_names = {}
```

<p>and set this ahead of time:</p>

```BoolEqual.var_names['var'] = 0xf
```

<p>And then implement your <code>__bool__</code> method as just:</p>

<code>return (self.var_names[self.var_name] >> self.bit_offset) & 0x1 == self.value
</code>```

(This will need to be extended to support multibit, but the general idea is the same.)

ContentLicense: CC BY-SA 4.0

Body:
I am trying to parse and evaluate expressions, given to me as input from a file, of the form:

var[3] = 0 and var[2] = 1
var[0] = 1 and var[2] = 0 and var[3] = 1
...

(actually I also allow "multibit access" (i.e. var[X:Y]) but let's ignore it for now...)

Where var is an integer, and the [] indicates bit access.

For example, for var = 0x9, the first expression above should be evaluated to False, and the second should be evaluated to True since 0x9 = b1001.

and and = are the only binary operators I allow, and for the = operator, the left operand is always var[X] and the right operand is always a number.

I tried to look around a bit and found that this could be achieved with Python's pyparsing, but I ran into some difficulties trying to implement it.

Here's what I've tried so far, based roughly on this example (which is one of many examples provided here):

#!/usr/bin/env python
from pyparsing import Word, alphas, nums, infixNotation, opAssoc

class BoolAnd():
    def __init__(self, pattern):
        self.args = pattern[0][0::2]

    def __bool__(self):
        return all(bool(a) for a in self.args)

    __nonzero__ = __bool__

class BoolEqual():
    def __init__(self, pattern):
        self.bit_offset = int(pattern[0][1])
        self.value = int(pattern[0][-1])

    def __bool__(self):
        return True if (0xf >> self.bit_offset) & 0x1 == self.value else False # for now, let's assume var == 0xf

    __nonzero__ = __bool__

variable_name   = 'var'
bit_access      = variable_name + '[' + Word(nums) + ']'
multibit_access = variable_name + '[' + Word(nums) + ':' + Word(nums) + ']'
value = Word(nums)

operand = bit_access | multibit_access | value

expression = infixNotation(operand,
    [
    ('=',   2, opAssoc.LEFT,  BoolEqual),
    ('AND', 2, opAssoc.LEFT,  BoolAnd),
    ])

p = expression.parseString('var[3] = 1 AND var[1] = 0', True)

print 'SUCCESS' if bool(p) else 'FAIL'

I have three problems I need help with.

For multibit access of the form var[X:Y] = Z, how do I enforce that:

a. X > Y

b. Z < 2^{X - Y + 1}

I assume this can't be enforced by the grammar itself (for example, for single-bit access of the form var[X] = Y, I can enforce by the grammar that Y will be either 0 or 1, and this will cause the expression.parseString() to fail with exception if Y != 0/1).

Most importantly: Why does it always print SUCCESS? What am I doing wrong?

For the input var[3] = 1 AND var[1] = 0 it should be print FAIL (you can see in my example that I hardcoded var to be 0xf, so var[3] = 1 is True but var[1] = 0 is False).

Which brings me to my third problem: var is not a class member of BoolEqual nor is it global... is there a way to somehow send it to BoolEqual's __init__ function?

Body:
Before getting to the problem solving, I suggest some minor changes to your grammar, primarily the inclusion of results names. Adding these names will make your resulting code much cleaner and robust. I'm also using some of the expressions that were added in recent pyparsing versions, in the pyparsing_common namespace class:

from pyparsing import pyparsing_common

variable_name   = pyparsing_common.identifier.copy()
integer = pyparsing_common.integer.copy()
bit_access      = variable_name('name') + '[' + integer('bit') + ']'
multibit_access = variable_name('name') + '[' + integer('start_bit') + ':' + integer('end_bit') + ']'

Part 1a: Enforcing valid values in "var[X:Y]"

This kind of work is best done using parse actions and conditions. Parse actions are parse-time callbacks that you can attach to your pyparsing expressions to modify, enhance, filter the results, or raise an exception if a validation rule fails. These are attached using the method:

expr.addParseAction(parse_action_fn)

And parse_action_fn can have any of the following signatures:

def parse_action_fn(parse_string, parse_location, matched_tokens):
def parse_action_fn(parse_location, matched_tokens):
def parse_action_fn(matched_tokens):
def parse_action_fn():

(See more at https://pythonhosted.org/pyparsing/pyparsing.ParserElement-class.html#addParseActio)n)

Parse actions can return None, return new tokens, modify the given tokens, or raise an exception.

If all the parse action does is evaluate some condition based on the input tokens, you can write it as a simple function that returns True or False, and pyparsing will raise an exception if False is returned. In your case, your first validation rule could be implemented as:

def validate_multibit(tokens):
    return tokens.end_bit > tokens.start_bit
multibit_access.addCondition(validate_multibit,
                            message="start bit must be less than end bit",
                            fatal=True)

Or even just as a Python lambda function:

multibit_access.addCondition(lambda t: t.end_bit > t.start_bit,
                            message="start bit must be less than end bit",
                            fatal=True)

Now you can try this with:

multibit_access.parseString("var[3:0]")

And you will get this exception:

pyparsing.ParseFatalException: start bit must be less than end bit (at char 0), (line:1, col:1)

Part 1b: Enforcing valid values in "var[X:Y] = Z"

Your second validation rule deals not only with the var bit ranges but also the value it is being compared to. This will require a parse action that is attached to the complete BoolEqual. We could put this in BoolEqual's __init__ method, but I prefer to separate independent functions when possible. And since we will be adding our validation by attaching to the infixNotation level, and infixNotation only accepts parse actions, we will need to write your second validation rule as a parse action that raises an exception. (We will also use a new feature that was only recently released in pyparsing 2.2.0, attaching multiple parse actions at a level in infixNotation.)

Here is the validation that we will wish to perform:

if single bit expression, value must be 0 or 1

if multibit expression var[X:Y], value must be < 2**(Y-X+1)

def validate_equality_args(tokens):
    tokens = tokens[0]
    z = tokens[-1]
    if 'bit' in tokens:
        if z not in (0,1):
            raise ParseFatalException("invalid equality value - must be 0 or 1")
    else:
        x = tokens.start_bit
        y = tokens.end_bit
        if not z < 2**(y - x + 1):
            raise ParseFatalException("invalid equality value")

And we attach this parse action to infixNotation using:

expression = infixNotation(operand,
    [
    ('=',   2, opAssoc.LEFT,  (validate_equality_args, BoolEqual)),
    ('AND', 2, opAssoc.LEFT,  BoolAnd),
    ])

Part 3: Supporting other var names and values than 0xf

To deal with vars of various names, you can add a class-level dict to BoolEqual:

class BoolEqual():
    var_names = {}

and set this ahead of time:

BoolEqual.var_names['var'] = 0xf

And then implement your __bool__ method as just:

return (self.var_names[self.var_name] >> self.bit_offset) & 0x1 == self.value

(This will need to be extended to support multibit, but the general idea is the same.)

ContentLicense: CC BY-SA 3.0


问:
Limit output of `adb shell dumpsys alarm`
I want to use the adb shell dumpsys alarm to debug some alarms I'm setting but it is producing a huge amount of data is there any way to limit the output to just a certain app?

I tried this to no avail: adb shell dumpsys com.mypackage

答:
For me putting the whole shell command in quotes worked
something like this :

```<code>adb shell "dumpsys alarm | grep my.packagename"
</code>```

or

```<code>adb shell "dumpsys alarm | fgrep my.packagename"
</code>```

Body:
For me putting the whole shell command in quotes worked
something like this :

adb shell "dumpsys alarm | grep my.packagename"

or

adb shell "dumpsys alarm | fgrep my.packagename"


问:
Not using forms and not doing a submit and yet page refreshes - why?
The code below does not use a form and does not do a submit and yet on click of a button the page is reloaded.  A reload should not occur based on everything I have read.  I don't understand why.  Can anyone help?

I also tried adding event function to the button (see updated source code) and have updated the source below.  It did now work

```<code><SCRIPT>
    $( document ).ready(function() {

    $('input[type=button]').hover(function() {
        $(this).toggleClass('ui-state-hover');
    });

    // get the php vars into local vars
    var req_status = '<?=$req_status?>';
    var member_id  = '<?=$mbr_id?>';
    var group_id   = '<?=$grp_id?>';

    if (req_status == 'member-is-grp-ldr') {
        $("#ok").prop('value', 'Unsubscribe');
        $('#ok').prop('disabled',true);
        $('#ok').addClass('ui-state-disabled');
    } else if (req_status == 'member-not-in-group') {
        $("#ok").prop('value', 'Resubscribe');
        $('#ok').prop('disabled',false);
    } else if (req_status == 'member-removed') {
        $("#ok").prop('value', 'Resubscribe');
        $('#ok').prop('disabled',false);
        $("#close").prop('value', 'Close');
    } else {
        $("#ok").prop('value', 'Unsubscribe');
        $('#ok').prop("disabled",false);
    }

   $('#ok').on('click', function(e) {
        e.preventDefault();
        if ($('#ok').val() == "Unsubscribe") {
            $.post('./ajax_group_unsubscribe.php', {function:'unsubscribe', member_id:member_id, group_id:group_id}, function(status) {
                if (status = 'true') {
                    $("#ok").prop('value', 'Resubscribe');
                    $('#ok').prop('disabled',false);
                    $('#ok').removeClass('ui-state-disabled');
                    $("#close").prop('value', 'Close');
                    document.getElementById('remark').innerHTML = "You have been removed from the group:";
                };
            });
        } else if ($('#ok').val() == "Resubscribe") {
            $.post('./ajax_group_unsubscribe.php', {function:'subscribe', member_id:member_id, group_id:group_id }, function(status) {
                if (status = 'true') {
                    $("#ok").prop('value', 'Unsubscribe');
                    $('#ok').prop('disabled',false);
                    $('#ok').removeClass('ui-state-disabled');
                    $("#close").prop('value', 'Close');
                    document.getElementById('remark').innerHTML = "You have been added to the group:";
                };
            });
        }
    });
});

</SCRIPT>
</HEAD>

<BODY>
    <div id="page-wrap">
        <div id="header_wrapper">
            Group Unsubscribe Request
        </div>
        <div id="groups_bg">
            <?php
                if ($req_status == "member-in-group") {
                    echo "<p id='remark'>Confirm you no longer want to receive messages for the group:</p>";
                    echo "<p><em>" . $grp_name . "</em></p>";
                } else if ($req_status == "member-not-in-group") {
                    echo "<p id='remark'>You are not currently in the group:</p>";
                    echo "<p><em>" . $grp_name . "</em></p>";
                } else if ($req_status == "member-removed") {
                    echo "<p id='remark'>You will no longer receive messages for the group:</p>";
                    echo "<p><em>" . $grp_name . "</em></p>";
                } else {
                    echo "<p id='remark'>You are the group leader and may not unsubscribe from the group:</p>";
                    echo "<p><em>" . $grp_name . "</em></p>";
                }
            ?>
            <br>
            <div style="text-align:center;">
            <input type="button" id="ok" name="ok" class='ui-button ui-widget ui-state-default ui-corner-all' value="Unsubscribe">
            <input type="button" id="close"  name="close"  class='ui-button ui-widget ui-state-default ui-corner-all' value="Cancel" onclick="window.open('', '_self', ''); window.close();">
            </div>
        </div>
    </div>
</BODY>
</HTML>
</code>```

Here is the ajax code:

```<code>/* get a database object */
$db = new DatabaseA();

/* get the member id and group id */
$function  = $_POST['function'];
$member_id = $_POST['member_id'];
$group_id  = $_POST['group_id'];

/* initialize the return status - booleans not returned */
$ret_status = 'false';

/* if the member id and group id were provided then */
if ( ! empty($member_id) && ! empty($group_id) ) {

    /* get organization id for the group */
    $group_info = get_group_info($db, $group_id, "org_id, group_name");
    $org_id = $group_info['org_id'];
    $grp_name = $group_info['group_name'];

    /* get the group leader */
    $grp_ldr_id = get_group_leader($db, $group_id);

    /* if the member is not the group leader then */
    if ($member_id <> $grp_ldr_id) {

        /* if the member is unsubscribing then */
        if ( $function = "Unsubscribe" && ! empty($org_id) ) {

            /* delete the member from the group */
            remove_member_from_group($db, $member_id, $group_id, $org_id);

            /* notify the group leader */
            send_member_email($db, $grp_ldr_id, "Group Member Update", "Member " . $mbrfirst_name . " " . $mbrlast_name . " has unsubscribed from your group: " . $grp_name);

            /* indicate the member was unsubscribed */
            $ret_status = 'true';

        /* else if the member is resubscribing then */
        } else if ($function = "Resubscribe" && ! empty($org_id) ) {

            /* add the member to the group */
            add_member_to_group($db, $member_id, $group_id, $org_id);

            /* notify the group leader */
            send_member_email($db, $grp_ldr_id, "Group Member Update", "Member " . $mbrfirst_name . " " . $mbrlast_name . " has resubscribed to your group: " . $grp_name);

            /* indicate the member was subscribed */
            $ret_status = 'true';
        }
    }
}

/* return to the caller */
return ($ret_status);
</code>```

答:
You are using single = in your else statement and you have missing closing curly braces in your inner if statements.

```<code>$('#ok').on('click', function() {
    if ($('#ok').value == "Unsubscribe") {
        $.post('./ajax_group_unsubscribe.php', {function:'unsubscribe', member_id:member_id, group_id:group_id}, function(status) {
            if (status = 'true') {
                $("#ok").prop('value', 'Resubscribe');
                $('#ok').prop('disabled',false);
                $('#ok').removeClass('ui-state-disabled');
                $("#close").prop('value', 'Close');
                document.getElementById('remark').innerHTML = "You have been removed from the group:";
            }
        });
    } else if ($('#ok').value == "Resubscribe") {
        $.post('./ajax_group_unsubscribe.php', {function:'subscribe', member_id:member_id, group_id:group_id }, function(status) {
            if (status = 'true') {
                $("#ok").prop('value', 'Unsubscribe');
                $('#ok').prop('disabled',false);
                $('#ok').removeClass('ui-state-disabled');
                $("#close").prop('value', 'Close');
                document.getElementById('remark').innerHTML = "You have been added to the group:";
            }
        });
    }
});
</code>```

Body:
The code below does not use a form and does not do a submit and yet on click of a button the page is reloaded.  A reload should not occur based on everything I have read.  I don't understand why.  Can anyone help?

I also tried adding event function to the button (see updated source code) and have updated the source below.  It did now work

            Group Unsubscribe Request

            <?php
                if ($req_status == "member-in-group") {
                    echo "
Confirm you no longer want to receive messages for the group:
";
                    echo "
" . $grp_name . "
";
                } else if ($req_status == "member-not-in-group") {
                    echo "
You are not currently in the group:
";
                    echo "
" . $grp_name . "
";
                } else if ($req_status == "member-removed") {
                    echo "
You will no longer receive messages for the group:
";
                    echo "
" . $grp_name . "
";
                } else {
                    echo "
You are the group leader and may not unsubscribe from the group:
";
                    echo "
" . $grp_name . "
";
                }
            ?>

            <input type="button" id="ok" name="ok" class='ui-button ui-widget ui-state-default ui-corner-all' value="Unsubscribe">
            <input type="button" id="close"  name="close"  class='ui-button ui-widget ui-state-default ui-corner-all' value="Cancel" onclick="window.open('', '_self', ''); window.close();">

Here is the ajax code:

/* get a database object */
$db = new DatabaseA();

/* get the member id and group id */
$function  = $_POST['function'];
$member_id = $_POST['member_id'];
$group_id  = $_POST['group_id'];

/* initialize the return status - booleans not returned */
$ret_status = 'false';

/* if the member id and group id were provided then */
if ( ! empty($member_id) && ! empty($group_id) ) {

    /* get organization id for the group */
    $group_info = get_group_info($db, $group_id, "org_id, group_name");
    $org_id = $group_info['org_id'];
    $grp_name = $group_info['group_name'];

    /* get the group leader */
    $grp_ldr_id = get_group_leader($db, $group_id);

    /* if the member is not the group leader then */
    if ($member_id <> $grp_ldr_id) {

        /* if the member is unsubscribing then */
        if ( $function = "Unsubscribe" && ! empty($org_id) ) {

            /* delete the member from the group */
            remove_member_from_group($db, $member_id, $group_id, $org_id);

            /* notify the group leader */
            send_member_email($db, $grp_ldr_id, "Group Member Update", "Member " . $mbrfirst_name . " " . $mbrlast_name . " has unsubscribed from your group: " . $grp_name);

            /* indicate the member was unsubscribed */
            $ret_status = 'true';

        /* else if the member is resubscribing then */
        } else if ($function = "Resubscribe" && ! empty($org_id) ) {

            /* add the member to the group */
            add_member_to_group($db, $member_id, $group_id, $org_id);

            /* notify the group leader */
            send_member_email($db, $grp_ldr_id, "Group Member Update", "Member " . $mbrfirst_name . " " . $mbrlast_name . " has resubscribed to your group: " . $grp_name);

            /* indicate the member was subscribed */
            $ret_status = 'true';
        }
    }
}

/* return to the caller */
return ($ret_status);

Body:
You are using single = in your else statement and you have missing closing curly braces in your inner if statements.

$('#ok').on('click', function() {
    if ($('#ok').value == "Unsubscribe") {
        $.post('./ajax_group_unsubscribe.php', {function:'unsubscribe', member_id:member_id, group_id:group_id}, function(status) {
            if (status = 'true') {
                $("#ok").prop('value', 'Resubscribe');
                $('#ok').prop('disabled',false);
                $('#ok').removeClass('ui-state-disabled');
                $("#close").prop('value', 'Close');
                document.getElementById('remark').innerHTML = "You have been removed from the group:";
            }
        });
    } else if ($('#ok').value == "Resubscribe") {
        $.post('./ajax_group_unsubscribe.php', {function:'subscribe', member_id:member_id, group_id:group_id }, function(status) {
            if (status = 'true') {
                $("#ok").prop('value', 'Unsubscribe');
                $('#ok').prop('disabled',false);
                $('#ok').removeClass('ui-state-disabled');
                $("#close").prop('value', 'Close');
                document.getElementById('remark').innerHTML = "You have been added to the group:";
            }
        });
    }
});


问:
Laravel: Validation unique on update
I know this question has been asked many times before but no one explains how to get the id when you're validating in the model.

```<code>'email' => 'unique:users,email_address,10'
</code>```

My validation rule is in the model so how do I pass the ID of the record to the validation rule.

Here is my models/User

```<code>protected $rules_update = [
    'email_address' => 'required|email|unique:users,email_address,'.$id,
    'first_name' => "required",
    'last_name' => "required",
    'password' => "required|min:6|same:password_confirm",
    'password_confirm' => "required:min:6|same:password",
    'password_current' => "required:min:6"
];
</code>```

models/BaseModel

```<code>    protected $rules = array();

public $errors;

/*
    * @data: array, Data to be validated
    * @rules: string, rule name in model
*/

public function validate($data, $rules = "rules") {

    $validation  = Validator::make($data, $this->$rules);

    if($validation->passes()) {
        return true;
    }

    $this->errors = $validation->messages();

    return false;
}
</code>```

答:
While updating any Existing Data Write validator as following:

```<code>'email' => ['required','email', Rule::unique('users')->ignore($user->id)]
</code>```

This will skip/ignore existing user's id's unique value matching for the specific column.

Title: Laravel: Validation unique on update

Body:
I know this question has been asked many times before but no one explains how to get the id when you're validating in the model.

'email' => 'unique:users,email_address,10'

My validation rule is in the model so how do I pass the ID of the record to the validation rule.

Here is my models/User

protected $rules_update = [
    'email_address' => 'required|email|unique:users,email_address,'.$id,
    'first_name' => "required",
    'last_name' => "required",
    'password' => "required|min:6|same:password_confirm",
    'password_confirm' => "required:min:6|same:password",
    'password_current' => "required:min:6"
];

models/BaseModel

    protected $rules = array();

public $errors;

/*
    * @data: array, Data to be validated
    * @rules: string, rule name in model
*/

public function validate($data, $rules = "rules") {

    $validation  = Validator::make($data, $this->$rules);

    if($validation->passes()) {
        return true;
    }

    $this->errors = $validation->messages();

    return false;
}

Body:
While updating any Existing Data Write validator as following:

'email' => ['required','email', Rule::unique('users')->ignore($user->id)]

This will skip/ignore existing user's id's unique value matching for the specific column.


问:
disable button untill form filled with specific length
i am trying to create a form which needs to be filled with 9 numeric digits. I would like the submit button to be disabled untill the form is filled exactly with 9 digits. I have found many scripts with button disabled untill form is filled but not with specific length. Could you please help me?

```<code><form name="form1">
    <input type="text" name='text1' maxlength="9" class="phone-input">
    <input type="button" value="submit" onclick="phonenumber(document.form1.text1); changeDiv();"/>
    </form>
</code>```

Thank You!

答:
As suggested by Markus, you can use the pattern attribute to validate the input (specify \d to allow only digits), in addition to required. The validity.valid property of the text field can then be used to enable/disable the button in the input event handler:

```<code><form name="form1">
    <input id="txtPhone" type="text" name='text1' pattern="\d{9}" required maxlength="9" class="phone-input" >
    <input id="btnSubmit" type="button" value="submit" disabled="disabled" />
</form>
<script>
    document.getElementById("txtPhone").addEventListener("input", function () {
        document.getElementById("btnSubmit").disabled = !this.validity.valid;
    });
</script>
</code>```

document.getElementById("txtPhone").addEventListener("input", function () {
    document.getElementById("btnSubmit").disabled = !this.validity.valid;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="form1">
    <input id="txtPhone" type="text" name='text1' pattern="\d{9}" required maxlength="9" class="phone-input" >
    <input id="btnSubmit" type="button" value="submit" onclick="alert('Submit!');" disabled="disabled" />
</form></code>```

Body:
i am trying to create a form which needs to be filled with 9 numeric digits. I would like the submit button to be disabled untill the form is filled exactly with 9 digits. I have found many scripts with button disabled untill form is filled but not with specific length. Could you please help me?

<form name="form1">
    <input type="text" name='text1' maxlength="9" class="phone-input">
    <input type="button" value="submit" onclick="phonenumber(document.form1.text1); changeDiv();"/>
    </form>

Thank You!

Body:
As suggested by Markus, you can use the pattern attribute to validate the input (specify \d to allow only digits), in addition to required. The validity.valid property of the text field can then be used to enable/disable the button in the input event handler:

<form name="form1">
    <input id="txtPhone" type="text" name='text1' pattern="\d{9}" required maxlength="9" class="phone-input" >
    <input id="btnSubmit" type="button" value="submit" disabled="disabled" />
</form>
<script>
    document.getElementById("txtPhone").addEventListener("input", function () {
        document.getElementById("btnSubmit").disabled = !this.validity.valid;
    });
</script>

document.getElementById("txtPhone").addEventListener("input", function () {
    document.getElementById("btnSubmit").disabled = !this.validity.valid;
});

<form name="form1">
    <input id="txtPhone" type="text" name='text1' pattern="\d{9}" required maxlength="9" class="phone-input" >
    <input id="btnSubmit" type="button" value="submit" onclick="alert('Submit!');" disabled="disabled" />
</form>


问:
Using numpy reshape and the "array must be unchanged" error
I am receiving the error:

```<code>ValueError: total size of new array must be unchanged
</code>```

And I cannot seem to figure out how my array is being changed to throw this error, and pointing to the last line:

```<code>      1 data = hourlyElectricityForVisualization.values
----> 2 data = data.reshape((len(data)/24/7),24*7))
</code>```

Note that:

```<code>data.shape = (2137,)
len(data) = 2137
</code>```

My code that precipitates this error is as follows:

```<code>hourlyElectricity = pd.read_excel('D:/hourlyElectricity.xlsx')

index = (hourlyElectricity['startTime'] >= np.datetime64('2016-01-01')) & (hourlyElectricity['startTime'] < np.datetime64('2016-03-31'))
hourlyElectricityForVisualization = hourlyElectricity.loc[index,'electricity-kWh']

print ("Data length: ", len(hourlyElectricityForVisualization)/24/7, " weeks")
data = hourlyElectricityForVisualization.values
data = data.reshape((len(data)/24/7,24*7)
</code>```

It is difficult for me to supply a dataset; so any suggestions without my inclusion of data are greatly appreciated!

答:
You have to delete some data points to make it possible to fit into new matrix of size N-to-24*7. You can do the following:

data = data[:(np.shape(data)[0] - np.shape(data)[0]%(24*7))]
data = np.reshape(data, (len(data)/24/7, 24*7))

This code will delete last 121 points to make result of division of length of data to (24*7) integer.

Body:
I am receiving the error:

ValueError: total size of new array must be unchanged

And I cannot seem to figure out how my array is being changed to throw this error, and pointing to the last line:

      1 data = hourlyElectricityForVisualization.values
----> 2 data = data.reshape((len(data)/24/7),24*7))

Note that:

data.shape = (2137,)
len(data) = 2137

My code that precipitates this error is as follows:

hourlyElectricity = pd.read_excel('D:/hourlyElectricity.xlsx')

index = (hourlyElectricity['startTime'] >= np.datetime64('2016-01-01')) & (hourlyElectricity['startTime'] < np.datetime64('2016-03-31'))
hourlyElectricityForVisualization = hourlyElectricity.loc[index,'electricity-kWh']

print ("Data length: ", len(hourlyElectricityForVisualization)/24/7, " weeks")
data = hourlyElectricityForVisualization.values
data = data.reshape((len(data)/24/7,24*7)

It is difficult for me to supply a dataset; so any suggestions without my inclusion of data are greatly appreciated!


问:
Hibernate: Multiple FK relationships
I'm kinda stuck defining a Hibernate Entity:

Assuming I have the following two tables in a database:

(A)

fromCompany

toCompany

viaCompany

(B)

companyID (PK)

description

where the elements of (A) point to the primary key of (B); so there are 3 one-to-one relationships between the FKs and the PK.
I assume 3 OneToOne statements with different mappedBy conditions are not the way to go, mh? Has been a long day - I probably just don't get it ;)

Thanks for your help!

答:
If I understood correctly, you want your database to look like this:

```<code>tableA
- id
- fromCompanyId (references tableB.id)
- toCompanyId (references tableB.id)
- viaCompanyId (references tableB.id)

tableB
- id
- description
</code>```

If so, you can certainly have this. You just need to override the default column name for the relationship, so that each association have it's own column name instead of falling back to the default name, which would render the three associations with the same name, causing problems.

I don't really agree with OneToOne, but I assume this was a conscious decision.

See this:
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association

ContentLicense: CC BY-SA 2.5

Title: Hibernate: Multiple FK relationships

Body:
If I understood correctly, you want your database to look like this:

tableA
- id
- fromCompanyId (references tableB.id)
- toCompanyId (references tableB.id)
- viaCompanyId (references tableB.id)

tableB
- id
- description

If so, you can certainly have this. You just need to override the default column name for the relationship, so that each association have it's own column name instead of falling back to the default name, which would render the three associations with the same name, causing problems.

I don't really agree with OneToOne, but I assume this was a conscious decision.

See this:
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association


问:
how to check if a string contains only lower case letters and numbers?
How can I check if a string contains only numbers and lower case letters?

I only managed to check if it contains numbers and lower case letters and doesn't contain upper case letters but I don't know how to check that it doesn't contain any symbols as ^&*(% etc..

```<code>if(any(i.islower() for i in password) and any(i.isdigit() for i in password) and not any(i.isupper() for i in password)):
</code>```

EDIT:
so apparently I need to do this without using any loops and mainly using functions like .islower() , .isdigit() , isalnum() etc.. and I have no idea how I can check if a string contains lower case letters and numbers only , without using loops or something that will check every single char in the string . we only started to learn the basics in python so they told us we can't use "for" and all that even if I know what it does.. now I can check if an entire string is only digits or lower/upper case letters but I don't know how to check the two conditions mentioned above in the simplest way possible

答:
Another solution is to count the letters of each type and make sure they're not zero (in this context True equates to 1 and False to 0):</p>

```<code>def validate_password(password):
    """
    Return True if password contains digits and lowercase letters
    but nothing else and is at least 8 characters long; otherwise
    return False.

    """

    ndigits = sum(c.isdigit() for c in password)
    nlower = sum(c.islower() for c in password)
    password_length = len(password)
    return (password_length > 7 and ndigits and nlower and
            (ndigits+nlower)==password_length)
</code>```

Body:
How can I check if a string contains only numbers and lower case letters?

I only managed to check if it contains numbers and lower case letters and doesn't contain upper case letters but I don't know how to check that it doesn't contain any symbols as ^&*(% etc..

if(any(i.islower() for i in password) and any(i.isdigit() for i in password) and not any(i.isupper() for i in password)):

EDIT:
so apparently I need to do this without using any loops and mainly using functions like .islower() , .isdigit() , isalnum() etc.. and I have no idea how I can check if a string contains lower case letters and numbers only , without using loops or something that will check every single char in the string . we only started to learn the basics in python so they told us we can't use "for" and all that even if I know what it does.. now I can check if an entire string is only digits or lower/upper case letters but I don't know how to check the two conditions mentioned above in the simplest way possible

Body:
Another solution is to count the letters of each type and make sure they're not zero (in this context True equates to 1 and False to 0):

def validate_password(password):
    """
    Return True if password contains digits and lowercase letters
    but nothing else and is at least 8 characters long; otherwise
    return False.

    """

    ndigits = sum(c.isdigit() for c in password)
    nlower = sum(c.islower() for c in password)
    password_length = len(password)
    return (password_length > 7 and ndigits and nlower and
            (ndigits+nlower)==password_length)


问:
JavaScript Dynamic JSON
Need to dynamically select JSON key from the JSON Object itself.

var text =
    '{"employees":[' + '{"firstName":"lastName", "lastName":"Doe" }]}';

var obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;

document.getElementById("demo").innerHTML =
     firstName + " " + obj.employees[0].lName;
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="demo"></div></code>```

Output Obtained: "lastName undefined".

Desired Output: "lastName Doe"

答:
You need to change the code like follows

```<code>var text = '{"employees":[' +
'{"firstName":"lastName","lastName":"Doe" }]}';

obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;
document.getElementById("demo").innerHTML =
firstName + " " + obj.employees[0][lName];
</code>```

Here is the working code:http://jsfiddle.net/NJMyD/5349/

Title: JavaScript Dynamic JSON

Body:
Need to dynamically select JSON key from the JSON Object itself.

var text =
    '{"employees":[' + '{"firstName":"lastName", "lastName":"Doe" }]}';

var obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;

document.getElementById("demo").innerHTML =
     firstName + " " + obj.employees[0].lName;

Output Obtained: "lastName undefined".

Desired Output: "lastName Doe"

Body:
You need to change the code like follows

var text = '{"employees":[' +
'{"firstName":"lastName","lastName":"Doe" }]}';

obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;
document.getElementById("demo").innerHTML =
firstName + " " + obj.employees[0][lName];

Here is the working code:http://jsfiddle.net/NJMyD/5349/


问:
How to access classes with on one instance?
I have multiple classes in the service layer of my app.
Let's say I need to access some method from AbcService.cs in my controller. Then, I need to access some method from XyzService.cs in the same controller. Then another.......For this, I would need to create an object of each Service class separately in the constructor. Also, if I needed to access these methods in another cntroller I would again have to create objects of AbcService, XyzService, etc. I want to have one instance that can give me access to methods of all service classes.
Something like:

```<code>generalService.AbcService.MethodName();
generalService.AbcService.MethodName();
</code>```

How do I do this in the best possible way?

答:
It somewhat depends how you choose to implement your services, but generally speaking you want some layer that encapsulate your services which is a singleton or that you inject\produce a single instance of it.

Encapsulation:

First try to look at a facade design pattern.
http://www.dofactory.com/net/facade-design-pattern

And btw if you don't need something complex and don't mind have an extra level of indirection then you can have some version of the facade like

```<code>KindOfSimpleFacade
{
    public IServiceA ServiceA { get; }
    public IServiceB ServiceB { get; }
}
</code>```

Regarding the singleton there are a few ways to get it:

inject the facade object to the (just provide the same instance to each one of the controllers as an input).

(Facade) Factory -http://tutorialspoint.com/design_pattern/factory_pattern.htm
The factory will produce a single instance of the facade.

use static members inside the facade for example:

public class KindOfSimpleFacade

```<code>{
    private static readonly serviceA = new ServiceA();
    private static readonly serviceB = new ServiceB();

    public IServiceA ServiceA { get { return serviceA; } }
    public IServiceB ServiceB { get { return serviceB; } }
}
</code>```

Body:
I have multiple classes in the service layer of my app.
Let's say I need to access some method from AbcService.cs in my controller. Then, I need to access some method from XyzService.cs in the same controller. Then another.......For this, I would need to create an object of each Service class separately in the constructor. Also, if I needed to access these methods in another cntroller I would again have to create objects of AbcService, XyzService, etc. I want to have one instance that can give me access to methods of all service classes.
Something like:

generalService.AbcService.MethodName();
generalService.AbcService.MethodName();

How do I do this in the best possible way?

Body:
It somewhat depends how you choose to implement your services, but generally speaking you want some layer that encapsulate your services which is a singleton or that you inject\produce a single instance of it.

Encapsulation:

First try to look at a facade design pattern.
http://www.dofactory.com/net/facade-design-pattern

And btw if you don't need something complex and don't mind have an extra level of indirection then you can have some version of the facade like

KindOfSimpleFacade
{
    public IServiceA ServiceA { get; }
    public IServiceB ServiceB { get; }
}

Regarding the singleton there are a few ways to get it:

inject the facade object to the (just provide the same instance to each one of the controllers as an input).

(Facade) Factory -http://tutorialspoint.com/design_pattern/factory_pattern.htm
The factory will produce a single instance of the facade.

use static members inside the facade for example:

public class KindOfSimpleFacade

{
    private static readonly serviceA = new ServiceA();
    private static readonly serviceB = new ServiceB();

    public IServiceA ServiceA { get { return serviceA; } }
    public IServiceB ServiceB { get { return serviceB; } }
}


答:
You should consider using a dependency injection container like Autofac. Register your service classes as Single Instance scope. You will get only one instance of a service class whenever you request it in every individual controller and even you do not need to create instance of it on your own.All is done by Ioc Container.

```<code>var builder = new ContainerBuilder();
builder.RegisterType<SomeService>().SingleInstance();
</code>```

Title: How to access classes with on one instance?

Body:
You should consider using a dependency injection container like Autofac. Register your service classes as Single Instance scope. You will get only one instance of a service class whenever you request it in every individual controller and even you do not need to create instance of it on your own.All is done by Ioc Container.

var builder = new ContainerBuilder();
builder.RegisterType<SomeService>().SingleInstance();


问:
Sync with iCal through Sync Services
I'm looking for sample code on how to sync with ical through sync services. Or anything that can point me to the right direction on how to do it. I've already gotten sync services up and running for my own core data schema, but I am not sure on how to do it with iCal.

I found the calendar schema on apple docs on the link below, but have no idea on how to start implementing it with sync services.

http://developer.apple.com/library/mac/#documentation/AppleApplications/Reference/SyncServicesSchemaRef/Articles/Calendars.html%23//apple_ref/doc/uid/TP40001540-CJBEHAAG

Thank you,
Jose.

答: If you're syncing with iCal, why not sync with the CalCalendarStore and let SyncServices sync iCal as it's likely already doing? </p>

Title: Sync with iCal through Sync Services


问:
Do I need to install anything for `import glob` to work under Windows 10?
I am a total novice with Raspberry Pi, I'm importing and combining a couple of programs together, working with Python 3 and VIM.  One of the programs has a code line that reads:

```<code>import os, glob, date, time.
</code>```

How do I import GLOB for Windows 10 so I can work on my laptop?  I'm sure I will have a few hundred more questions but this is where I think I have to start.
Thanks Gaggle,
Barry

答: glob is part of the Python Standard Library, it thus comes pre-installed with Python, whether you run Python on Windows, macOS, Linux, or whatever.. </p>

Body:
I am a total novice with Raspberry Pi, I'm importing and combining a couple of programs together, working with Python 3 and VIM.  One of the programs has a code line that reads:

import os, glob, date, time.

How do I import GLOB for Windows 10 so I can work on my laptop?  I'm sure I will have a few hundred more questions but this is where I think I have to start.
Thanks Gaggle,
Barry


问:
A weird error when passing a struct pointer to a function in C
I've written a simple C test program to practice using structs. However I can't understand what's wrong with the code; it seems that the first printout of either the integer or the double field clears both fields. What's my mistake here?

the code:

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

struct Dummy {
    int i;
    double d;
    char s[8];
};

void print(struct Dummy *dummy) {
    printf("%lf ", dummy->d);
    printf("%lf ", dummy->d);
    printf("%d ", dummy->i);
    printf("%s\n", dummy->s);
}

void set(struct Dummy **dummy) {
    struct Dummy duh;
    duh.i = 1;
    duh.d = 3.14;
    strcpy(duh.s, "Hello!");
    *dummy = &duh;
}

int main(int argc, char **argv) {
    struct Dummy *dummy;
    set(&dummy);
    print(dummy);
    return 0;
}
</code>```

its output:

```<code>3.140000 0.000000 0 Hello!
</code>```

Thanks a lot!

答:
You've invoked undefined behavior by assigning the address of a local variable in set and returning it.

```<code>*dummy = &duh;
</code>```

duh is no longer valid after set returns.

Body:
I've written a simple C test program to practice using structs. However I can't understand what's wrong with the code; it seems that the first printout of either the integer or the double field clears both fields. What's my mistake here?

the code:

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

struct Dummy {
    int i;
    double d;
    char s[8];
};

void print(struct Dummy *dummy) {
    printf("%lf ", dummy->d);
    printf("%lf ", dummy->d);
    printf("%d ", dummy->i);
    printf("%s\n", dummy->s);
}

void set(struct Dummy **dummy) {
    struct Dummy duh;
    duh.i = 1;
    duh.d = 3.14;
    strcpy(duh.s, "Hello!");
    *dummy = &duh;
}

int main(int argc, char **argv) {
    struct Dummy *dummy;
    set(&dummy);
    print(dummy);
    return 0;
}

its output:

3.140000 0.000000 0 Hello!

Thanks a lot!

Body:
You've invoked undefined behavior by assigning the address of a local variable in set and returning it.

*dummy = &duh;

duh is no longer valid after set returns.


问:
Why did Neo4j change it's name to Neo5j?
They just announced, they changed their name to Neo5j.

I always thought that 4j meant for-Java.
And as Neo4j is implemented in Java and Scala and the ~4j suffix has been highly popular (in the 90's) it never occurred to me that the 4j and now 5j is actually a version denomination.

But it seems common in database circles to use that number + letter versioning scheme, like Oracle does with 9i, 11g and 12c.

Now the question is what does the 5j stand for? The article doesn't answer it. Can anyone help me resolve this?

答:
The Neo series of databases was developed in Sweden and attracted the 'j' suffix with the release of version 4 of the graph database. The 'j' is from the word 'jätteträd', literally "giant tree", and was used to indicate the huge data structures that could now be stored.

Incidentally the 'neo' portion of the name is a nod to a Swedish pop artist Linus Ingelsbo, who goes by the name NEO. In Neo1 the example graph was singers and bands and featured the favourite artists of the developers, including NEO. This was changed to the movie data set in the version 4 release.


问:
Xamarin testing with TestComplete
I've asked the same questions in the TestComplete forum already but I hope to find someone here who knows Xamarin well as most of my questions are more related to Xamarin than to TestComplete.

We are about to switch all of our apps to Xamarin and wish to continue UI Testing with TestComplete. Previously (when testing native Android apps), we used the object id to identify ui controls that was specified in the Android View xmls. This was very handy as the ids were

human-readable

unique

constant across app runs

On Xamarin, controls seem to have ids, too, but we have some issues with them:

Most objects have no id, some have an md5-hash as their id. It was so convenient on Android to have unique ids for most controls and this seems to be gone on Xamarin. Three questions concerning that: What are those md5-hashes based on, when do they change and is there any possibility to still set our own control id?

Some objects appear twice with the same id but a different ObjectIndex. I know this phenomenon only from iOS, where the UI is created during runtime and sometimes UI controls don't get recycled properly so if you reopen the same view again, you might end up with to identical controls, one of them beeing invisible and the other one being visible. This is a pain in the bum on iOS since it can be quite hard sometimes to determine in TestComplete the instance that is currently visible. My hope is now that we can somehow get rid of that too, but I have no idea how.

Screenshot of object ids: (1): md5-hashes, (2) Some objects appear twice

Objects are only accessible to a certain level. For instance, we can access and interact with md52....MasterDetailContainer but its only child View("NO_ID") is inaccessible. TestComplete cannot show a screenshot of it in the ObjectBrowser and any interaction with it (including "Highlight on screen") results in an error. This applies to all of its children, too. This is especially important to solve as all of our UI controls are children of that MasterDetailContainer and having no access to its children renders the tests useless.

TestComplete, the Xamarin Forms Designer and the Android UI Automator Viewer show a very different object hierarchy of the same view in the app. How can this be explained?

I've been talking to the dev team about all this but as they are new to Xamarin, too, they don't know the answers neither. I would be glad if someone here who knows Xamarin coudl help us out as some of the issues are blocking issues.

答:
set our own control id?

The control id that you are referring in that screenshot is showing that Java class name of the View. Xamarin creates Android Callable Wrappers(ACW) during that build process for each of the Java objects that you are creating/accessing from C#.

The default package names for ACW will be based on the MD5SUM of the assembly-qualified name of the type being exported.

You can control the generated name by using class attributes:

RegisterAttribute

BroadcastReceiverAttribute.Name

ContentProviderAttribute.Name

ActivityAttribute.Name

ServiceAttribute.Name

ApplicationAttribute.Name

i.e. If you had a subclassed EditView and want to override the default ACW name generation:

```<code>[Register("com.sushihangover.SOApplication.AVeryCustomEditView")]
public class CustomEditView : EditView
{
   ~~~
}
</code>```

But, since you referenced Xamarins.Forms, I assuming you are not using AXML (Xamarin.Android) but XAML (Xamarin.Forms) to create your UIs. Forms programmatically creates the view hierarchy via unique platform-based renderers and its own layout manager and thus you will not have a one-to-one mapping of the XAML you are visualizing via Xamarin Forms Designer to what is created and viewed via the Android UI Automator Viewer nor will you have those view classes available to apply the Register attribute to.

Since SmartBear says they support Xamarin.iOS and Xamarin.Android, you should create a support case with SmartBear to understand how and if they also support Xamarin.Forms based UIs.

Title: Xamarin testing with TestComplete

Body:
set our own control id?

The control id that you are referring in that screenshot is showing that Java class name of the View. Xamarin creates Android Callable Wrappers(ACW) during that build process for each of the Java objects that you are creating/accessing from C#.

The default package names for ACW will be based on the MD5SUM of the assembly-qualified name of the type being exported.

You can control the generated name by using class attributes:

RegisterAttribute

BroadcastReceiverAttribute.Name

ContentProviderAttribute.Name

ActivityAttribute.Name

ServiceAttribute.Name

ApplicationAttribute.Name

i.e. If you had a subclassed EditView and want to override the default ACW name generation:

[Register("com.sushihangover.SOApplication.AVeryCustomEditView")]
public class CustomEditView : EditView
{
   ~~~
}

But, since you referenced Xamarins.Forms, I assuming you are not using AXML (Xamarin.Android) but XAML (Xamarin.Forms) to create your UIs. Forms programmatically creates the view hierarchy via unique platform-based renderers and its own layout manager and thus you will not have a one-to-one mapping of the XAML you are visualizing via Xamarin Forms Designer to what is created and viewed via the Android UI Automator Viewer nor will you have those view classes available to apply the Register attribute to.

Since SmartBear says they support Xamarin.iOS and Xamarin.Android, you should create a support case with SmartBear to understand how and if they also support Xamarin.Forms based UIs.


问:
Move scrollview to original state
I want to move up the view when the keyboard appears and move the view back when the keyboard disappears. I use an scrollview for this.

I have this almost working. The bug that I have is this:

You trigger the keyboard to show

You trigger the keyboard to hide

Things are going great so far.

You trigger the keyboard to show

You trigger the keyboard to hide <-- This doesn't work anymore, but the first time it works perfectly.

The code when the keyboard shows up (this works overtime):

```<code>func keyboardWasShown(notification: NSNotification) {
    var userInfo = notification.userInfo!
    let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    let buttonOrigin: CGPoint = btn.frame.origin
    let buttonHeight: CGFloat = btn.frame.size.height
    var visibleRect: CGRect = view.frame

    visibleRect.size.height -= keyboardFrame.size.height
    if !visibleRect.contains(buttonOrigin) {
        let scrollPoint = CGPoint(x: CGFloat(0.0), y: CGFloat(buttonOrigin.y - visibleRect.size.height + (buttonHeight + 8)))
        scrollView.setContentOffset(scrollPoint, animated: true)
    }
}
</code>```

The code when the keyboard is going to hide (This code works the first time, it doesn't work the second time):

```<code>func keyboardWillBeHidden(notification: NSNotification){
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size

    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}
</code>```

This is how my view looks like:

Everything needs to move up when the keyboard is showing. Moving up works:

But when the keyboard disappears it doesn't work:

答:
Just change this Line

 let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)

with

let contentInsets : UIEdgeInsets = .zero

or try This

//MARK:- Keyboard Methods

```<code>  func keyboardWillOpen(sender:Notification) {

        if let info = sender.userInfo{

            if let keyboardSize = info[UIKeyboardFrameBeginUserInfoKey] as? CGRect{
                let contentInsets = UIEdgeInsetsMake(0, 0, -keyboardSize.height, 0)

            self.scrollView.contentInset = contentInsets
            self.scrollView.scrollIndicatorInsets = contentInsets
            }
        }
    }

    func keyboardWillHide(notification:Notification) {

        if let info = notification.userInfo {

            if let keyboardSize = info[UIKeyboardFrameBeginUserInfoKey] as? CGRect {

            self.scrollView.contentInset = .zero
            self.scrollView.scrollIndicatorInsets = .zero

            }
        }
    }
</code>```

Title: Move scrollview to original state

Body:
I want to move up the view when the keyboard appears and move the view back when the keyboard disappears. I use an scrollview for this.

I have this almost working. The bug that I have is this:

You trigger the keyboard to show

You trigger the keyboard to hide

Things are going great so far.

You trigger the keyboard to show

You trigger the keyboard to hide <-- This doesn't work anymore, but the first time it works perfectly.

The code when the keyboard shows up (this works overtime):

func keyboardWasShown(notification: NSNotification) {
    var userInfo = notification.userInfo!
    let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    let buttonOrigin: CGPoint = btn.frame.origin
    let buttonHeight: CGFloat = btn.frame.size.height
    var visibleRect: CGRect = view.frame

    visibleRect.size.height -= keyboardFrame.size.height
    if !visibleRect.contains(buttonOrigin) {
        let scrollPoint = CGPoint(x: CGFloat(0.0), y: CGFloat(buttonOrigin.y - visibleRect.size.height + (buttonHeight + 8)))
        scrollView.setContentOffset(scrollPoint, animated: true)
    }
}

The code when the keyboard is going to hide (This code works the first time, it doesn't work the second time):

func keyboardWillBeHidden(notification: NSNotification){
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size

    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

This is how my view looks like:

Everything needs to move up when the keyboard is showing. Moving up works:

But when the keyboard disappears it doesn't work:

Body:
Just change this Line

 let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)

with

let contentInsets : UIEdgeInsets = .zero

or try This

//MARK:- Keyboard Methods

  func keyboardWillOpen(sender:Notification) {

        if let info = sender.userInfo{

            if let keyboardSize = info[UIKeyboardFrameBeginUserInfoKey] as? CGRect{
                let contentInsets = UIEdgeInsetsMake(0, 0, -keyboardSize.height, 0)

            self.scrollView.contentInset = contentInsets
            self.scrollView.scrollIndicatorInsets = contentInsets
            }
        }
    }

    func keyboardWillHide(notification:Notification) {

        if let info = notification.userInfo {

            if let keyboardSize = info[UIKeyboardFrameBeginUserInfoKey] as? CGRect {

            self.scrollView.contentInset = .zero
            self.scrollView.scrollIndicatorInsets = .zero

            }
        }
    }


问:
php weird file_exists bug
Has anyone got any idea to why doesn't the following work ?

```<code>$file = 'images/thumbs/1%20-%20Copy.jpg';
if(!file_exists($file)){
 die('NOT THERE');
}

echo 'Yes its there.';
</code>```

The problem is with the spaces. I have checked the file exists,dbl checked n triple checked im going nuts. :(

Help

答:
try these two</p>

```<code>$file = 'images/thumbs/1\ -\ Copy.jpg';
$file = 'images/thumbs/1 - Copy.jpg';
</code>```

Title: php weird file_exists bug

Body:
Has anyone got any idea to why doesn't the following work ?

$file = 'images/thumbs/1%20-%20Copy.jpg';
if(!file_exists($file)){
 die('NOT THERE');
}

echo 'Yes its there.';

The problem is with the spaces. I have checked the file exists,dbl checked n triple checked im going nuts. :(

Help

Body:
try these two

$file = 'images/thumbs/1\ -\ Copy.jpg';
$file = 'images/thumbs/1 - Copy.jpg';


问:
Is there a way to specify default values for null in Lodash or Underscore?
I know the _.defaults function works to put default values for an object with keys that are undefined. However it doesn't work with keys that are null. Is there way to achieve this?

答:
Thanks to @Jacque for the explanation about null values. However due to unfortunate inherited code, the object I'm working on returns null values even though it's intended for undefined. Here's my approach in achieving this in a more declarative way by omitting the null properties which will result into undefined, as a result will create defaults for its values.

const alphabet = {
  a: 'A is for apple',
  // b: undefined,
  c: 'C is for cake',
  d: null,
}
const nonNulls = _.omitBy(alphabet, _.isNull) // Omitting null values.
const longer = _.defaults(nonNulls, {
  b: 'B is for boy',
})

console.info('Longer Way', longer)

// Or even shorter
const shorter = _.defaults(_.omitBy(alphabet, _.isNull), {
  b: 'B is for boy',
})

console.info('Shorter Way', shorter)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Body:
Thanks to @Jacque for the explanation about null values. However due to unfortunate inherited code, the object I'm working on returns null values even though it's intended for undefined. Here's my approach in achieving this in a more declarative way by omitting the null properties which will result into undefined, as a result will create defaults for its values.

const alphabet = {
  a: 'A is for apple',
  // b: undefined,
  c: 'C is for cake',
  d: null,
}
const nonNulls = _.omitBy(alphabet, _.isNull) // Omitting null values.
const longer = _.defaults(nonNulls, {
  b: 'B is for boy',
})

console.info('Longer Way', longer)

// Or even shorter
const shorter = _.defaults(_.omitBy(alphabet, _.isNull), {
  b: 'B is for boy',
})

console.info('Shorter Way', shorter)

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


问:
Why does Microsoft SQL Server check columns but not tables in stored procs?
Microsoft SQL Server seems to check column name validity, but not table name validity when defining stored procedures.  If it detects that a referenced table name exists currently, it validates the column names in a statement against the columns in that table.  So, for example, this will run OK:

```<code>CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        Col1, Col2, Col3
    FROM
        NonExistentTable
END
GO
</code>```

... as will this:

```<code>CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        ExistentCol1, ExistentCol2, ExistentCol3
    FROM
        ExistentTable
END
GO
</code>```

... but this fails, with 'Invalid column name':

```<code>CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        NonExistentCol1, NonExistentCol2, NonExistentCol3
    FROM
        ExistentTable
END
GO
</code>```

Why does SQL Server check columns, but not tables, for existence?  Surely it's inconsistent; it should do both, or neither.  It's useful for us to be able to define SPs which may refer to tables AND/OR columns which don't exist in the schema yet, so is there a way to turn off SQL Server's checking of column existence in tables which currently exist?

答:
This is called deferred name resolution.

There is no way of turning it off. You can use dynamic SQL or (a nasty hack!) add a reference to a non existent table so that compilation of that statement is deferred.

```<code>CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN

CREATE TABLE #Dummy (c int)

    SELECT
        NonExistantCol1, NonExistantCol2, NonExistantCol3
    FROM
        ExistantTable
    WHERE NOT EXISTS(SELECT * FROM #Dummy)

DROP TABLE #Dummy

END
GO
</code>```

Body:
Microsoft SQL Server seems to check column name validity, but not table name validity when defining stored procedures.  If it detects that a referenced table name exists currently, it validates the column names in a statement against the columns in that table.  So, for example, this will run OK:

CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        Col1, Col2, Col3
    FROM
        NonExistentTable
END
GO

... as will this:

CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        ExistentCol1, ExistentCol2, ExistentCol3
    FROM
        ExistentTable
END
GO

... but this fails, with 'Invalid column name':

CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN
    SELECT
        NonExistentCol1, NonExistentCol2, NonExistentCol3
    FROM
        ExistentTable
END
GO

Why does SQL Server check columns, but not tables, for existence?  Surely it's inconsistent; it should do both, or neither.  It's useful for us to be able to define SPs which may refer to tables AND/OR columns which don't exist in the schema yet, so is there a way to turn off SQL Server's checking of column existence in tables which currently exist?

Body:
This is called deferred name resolution.

There is no way of turning it off. You can use dynamic SQL or (a nasty hack!) add a reference to a non existent table so that compilation of that statement is deferred.

CREATE PROCEDURE [dbo].[MyProcedure]
AS
BEGIN

CREATE TABLE #Dummy (c int)

    SELECT
        NonExistantCol1, NonExistantCol2, NonExistantCol3
    FROM
        ExistantTable
    WHERE NOT EXISTS(SELECT * FROM #Dummy)

DROP TABLE #Dummy

END
GO


问:
What should I do with plugin-created migrations?
I have, as usual the <project>/<app>/migrations folder that I added to the version control for deployment. Since recently I am also using django-auditlog, which creates its own migrations in <project>/env/Lib/site-packages/auditlog/migrations. These migrations are applied just like my own ones. So I wonder: should I also add them to VCS and deploy them?

答:
No. You shouldn't deploy these migrations. In general you shouldn't deploy any third-party migrations.

The reason is simple. Third-party packages have their initial migrations inside their migrations directory. Each time you create a migration that depends on a third-party package, this migration will live in your app's migrations dir (not inside the package one).

So, when you first deploy your code and run pip install -r requirements.txt on your server, then all 3rd party packages will be installed and when you do ./manage.py migrate then Django will look at your INSTALLED_APPS and execute all migrations for each one in this list.

The same thing happens with any third-party package, just like Django itself. Suppose you have in your requirements.txt file only Django==1.10.6. When you deploy this to the server and do pip install -r requirements.txt, django-admin createproject myproject and then ./manage.py migrate, then your database will be "filled" with all Django-specific tables that has built-in (i.e auth, sessions, contenttypes etc) and are enabled in the INSTALLED_APPS setting list.

The one and only that you should deploy is everything under your project directory (requirements.txt, manage.py, robots.txt etc) and not your 3rd party apps which may live either inside your project (under a .virtualenv dir, probably) or in a separate .virtualenv dir outside of your project.

An analogous to your question is node_modules for nodejs. node_modules directory is never deployed to VCS (because it can get quite large in size etc), instead only the package.json is, because knowing what dependencies (package.json/requirements.txt) your project needs, then your project can "reconstruct" itself from zero.


答:
@kjhughes is right, there is no integrated output scheme. And you are also right, you can use python. You can see some infos about xml and minidom here:
https://docs.python.org/2/library/xml.dom.minidom.html

However, XML is a model-file. That means you describe a structure with it, not a primitive set of data.

Here you see an example for a website:
https://pubs.vmware.com/vfabric52/index.jsp?topic=/com.vmware.vfabric.tc-server.2.8/getting-started/tutwebapp-web-xml-file.html

Or see here the maven file for compiling a java program (4th code block):
https://spring.io/guides/gs/maven/

So, you can do it by deciding what is your strucutre, but you have to decide it for yourself because there is no standard for it concerning the top result. Thus, we come up with the question ...why should you choose this format ?

As a direkt answer to your question:
How do add nodes, childnodes, and childnodes to childnodes ... you can find here:
https://wiki.python.org/moin/MiniDom

Title: How to save the output of top command in XML format?

Body:
top -o %MEM -b > file.txt

The file.txt is like:

top - 15:49:36 up 32 min,  2 users,  load average: 1.56, 1.40, 1.01
Tasks:  83 total,   2 running,  79 sleeping,   2 stopped,   0 zombie
%Cpu(s): 24.4 us,  8.1 sy,  0.0 ni, 55.0 id,  0.0 wa,  0.0 hi, 12.5 si,  0.0 st
KiB Mem:    195252 total,   191568 used,     3684 free,     3200 buffers
KiB Swap:   901116 total,       44 used,   901072 free.    66940 cached Mem

  PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND
  485 root      20   0   68160  61420   4552 R 58.7 31.5   5:06.10 python3
  712 www-data  20   0  230940   4436   2044 S 26.1  2.3   3:54.04 apache2
  819 root      20   0    8488   4400   3856 S  6.5  2.3   1:06.85 tcpdump
  713 www-data  20   0  230780   4344   2044 S 13.0  2.2   2:34.97 apache2
  868 root      20   0    6352   3976   2720 S  0.0  2.0   0:00.07 bash
  785 root      20   0    6340   3876   2636 S  0.0  2.0   0:00.06 bash
  707 root      20   0    6056   3704   2580 S  0.0  1.9   0:00.59 apache2
  137 root      20   0    8284   3256   2996 S  0.0  1.7   0:00.34 systemd-journal
    1 root      20   0    5476   3112   2072 S  0.0  1.6   0:01.04 systemd
  456 ntp       20   0    5820   3012   2576 S  0.0  1.5   0:00.71 ntpd
  865 root      20   0    4008   2792   2360 S  0.0  1.4   0:00.04 login
  938 nobody    20   0    5244   2756   2404 S  0.0  1.4   0:00.04 vsftpd
  941 nobody    20   0    5244   2756   2404 S  0.0  1.4   0:00.03 vsftpd
  457 root      20   0   31220   2740   2080 S  0.0  1.4   0:00.01 rsyslogd
  484 root      20   0    4008   2692   2268 S  0.0  1.4   0:00.05 login
  944 root      20   0    5076   2620   2352 R  0.0  1.3   0:00.00 top
  903 root      20   0    5080   2580   2236 T  0.0  1.3   0:00.00 top
  908 root      20   0    5052   2560   2288 T  0.0  1.3   0:00.08 top
  425 root      20   0    5416   2420   2100 S  0.0  1.2   0:00.00 cron
  406 root      20   0    5012   2348   2120 S  0.0  1.2   0:00.00 cron
  148 root      20   0   12272   2320   1856 S  0.0  1.2   0:00.09 systemd-udevd
  414 message+  20   0    5244   2268   1960 S  0.0  1.2   0:00.00 dbus-daemon
  390 statd     20   0    4576   2264   1764 S  0.0  1.2   0:00.00 rpc.statd

I should save the information in XML format instead of txt file! How to do it?

I would like to read file.txt and convert it to XML.

I think I could use Python but I dont know how:

#coding:utf-8

from xml.dom.minidom import Document

doc = Document()
root = doc.createElement('InfoMemoria')


问:
Avoid collision in importing data in R
I faced an error trying to import a CSV into R which had multiple duplicate columns, is there a way I can ignore those columns?
It's easy to do that in case of small files and small number of columns but mine is a big one ~3k columns and 10M rows.</p>

答: Read in the first row, I.e. the column headers, with readLines. strsplit to parse to vector. Rename duplicated elements. Then you can call read.csv with a col.names arg.</p>

Title: Avoid collision in importing data in R


问:
How to learn CouchDB API without documentation?
Since CouchDB has very few API documentation (at least I can not find it), I would like to inspect some JavaScript objecs myself. What is the best way to do this?

For example, show functions recive the request object req as argument. How to find out, which properties (cookies, requested url,...) this request object precisely has?

答:
I'm not happy with the couchdb documentation either.

In the CouchDB Guide there is some information about the req object that is passed to the list function: http://guide.couchdb.org/editions/1/en/transforming.html

I guess it will look quite the same in show functions.

But you should also be able to use toJSON(req) in order to get its content.


问:
store foreach results in multi dimensional array
im trying to store values from foreach loop in array

```<code>$result_itemid = array();
foreach($resp->searchResult->item as $item) {
   $itemid = $item->itemId;
   $title = $item->title;
   $result_itemid[] .= $itemid;
}

print_r($result_itemid);
</code>```

i try it and it works: output

[0] => 7048668, [1] => 5651831 etc..

but i want more option like:

[0][0] => 7048668 [0][1] => Black
  -- [1][0] => 5651831 [1][1] => white

Thank you :)

答:
Try this:</p>

```<code>$result_itemid = [];
$ids = [];
$titles = [];
foreach($resp->searchResult->item as $item) {
   $ids[] = $item->itemId;
   $titles[] = $item->title;
}

array_multisort($ids, $titles);

foreach( $ids as $i => $id ) {
    $result_itemid[] = [ $id , $titles[$i] ];
}

print_r($result_itemid);
</code>```

Body:
im trying to store values from foreach loop in array

$result_itemid = array();
foreach($resp->searchResult->item as $item) {
   $itemid = $item->itemId;
   $title = $item->title;
   $result_itemid[] .= $itemid;
}

print_r($result_itemid);

i try it and it works: output

[0] => 7048668, [1] => 5651831 etc..

but i want more option like:

[0][0] => 7048668 [0][1] => Black
  -- [1][0] => 5651831 [1][1] => white

Thank you :)

Body:
Try this:

$result_itemid = [];
$ids = [];
$titles = [];
foreach($resp->searchResult->item as $item) {
   $ids[] = $item->itemId;
   $titles[] = $item->title;
}

array_multisort($ids, $titles);

foreach( $ids as $i => $id ) {
    $result_itemid[] = [ $id , $titles[$i] ];
}

print_r($result_itemid);


问:
React-Native: Application has not been registered error
I am currently going through the React-Native tutorials. I began with the Getting Started tutorial, where I made a new react native project and successfully managed to run the project on my device.

I then started the Props tutorial, I copied the code snippet and tried to run the project again and had the following error message show up on my screen:

答:
First of all you must start your application:

```<code>react-native start
</code>```

Then, you must set your application name as the first argument of registerComponent.

It works fine.

```<code>AppRegistry.registerComponent('YourProjectName', () => YourComponentName);
</code>```

Body:
First of all you must start your application:

react-native start

Then, you must set your application name as the first argument of registerComponent.

It works fine.

AppRegistry.registerComponent('YourProjectName', () => YourComponentName);


问:
Continue PHP Operation After User Exits Early
I'm using Laravel, PHP7, PHP-FPM, APCu and NGINX.

I have an HTML form where a user can upload a file, it connects to Upload.php.

File Process:

validate

name

move from /tmp to /media

create thumbnail

create database record

Once the PHP script reaches a certain point, how can I have it continue running even if the user exits the upload page early? Or else a rogue file will be left in the directory without a database entry.

```<code>// Move uploaded file from /tmp to /media
Input::file('file')->move("/var/www/mysite/media", $image);

// Continue even if user exits early
// prevent a file in /media from not having a database record

// Thumbnail creation and other operations here
// May take several seconds

// Save database record
$image = new Gallery();
$image->name = $name;
$image->created_at = $date;
$image->save();
</code>```

Should I use ignore_user_abort(true) and wrap the operations in a while(true)?

I have other bools in the script such as $upload = true. How does the while(true) know to represent ignore_user_about(true) and not another bool I have set?

答:
User abort is not an easy thing to catch in PHP... Typically, your script will run until it actually detects the client has baled out by trying to send something back to the browser... In your case, since you are not sending anything back while processing, you should run to completion... even if the user closes the connection... To make sure, you can use the register_shutdown_function() which will be called when PHP shuts down... now be careful, as Laravel has hooks there too... so any timeout will trigger Laravel error first, yours second... However, you can know in that function if it shut down properly or if it aborted...

To play with the function I created a route like this:

```<code> use Illuminate\Support\Facades\Log;

 Route::get('/abort', function(){
    Log::info('Entering abort route...');
    set_time_limit(5);
    register_shutdown_function(function(){
        Log::info('Entering shutdown function... status: ' . connection_status());
        switch(connection_status()){
            case CONNECTION_ABORTED:
                Log::info('Connection Aborted');
                break;
            case CONNECTION_TIMEOUT:
                echo 'Connection Timeout';
                break;
            default:
                echo 'All ok, user did not abort and function did not time out.';
        }
    });

    while(1){
        echo 'Ping<br />';
    };
});
</code>```

Here you can catch (I used the Laravel logger for the abort... find the log in storage/logs/laravel.log) ...

Now interestingly, if you abort this, you will get an abord call in the shutdown function, because the while(1) echoes 'Ping' to the browser, detecting the connection loss before the time out... however, if you remove the echo in the while and replace it with non buffer work $cnt++; or something, Then even if you abort, you will only get the timeout... the script did not detect the connection closing...

Note that your handler runs after all other handlers...

Also, it runs every time the script shuts down... so even when all is good... as in the default: switch above... naturally, this script will not run to completion because of the while(1)... just remove it if you want to see the normal completion behaviour...

I think this is probably the easiest way to do the clean up... catch it in there and do any clean up you need to...

Hope this helps...

Body:
I'm using Laravel, PHP7, PHP-FPM, APCu and NGINX.

I have an HTML form where a user can upload a file, it connects to Upload.php.

File Process:

validate

name

move from /tmp to /media

create thumbnail

create database record

Once the PHP script reaches a certain point, how can I have it continue running even if the user exits the upload page early? Or else a rogue file will be left in the directory without a database entry.

// Move uploaded file from /tmp to /media
Input::file('file')->move("/var/www/mysite/media", $image);

// Continue even if user exits early
// prevent a file in /media from not having a database record

// Thumbnail creation and other operations here
// May take several seconds

// Save database record
$image = new Gallery();
$image->name = $name;
$image->created_at = $date;
$image->save();

Should I use ignore_user_abort(true) and wrap the operations in a while(true)?

I have other bools in the script such as $upload = true. How does the while(true) know to represent ignore_user_about(true) and not another bool I have set?

Body:
User abort is not an easy thing to catch in PHP... Typically, your script will run until it actually detects the client has baled out by trying to send something back to the browser... In your case, since you are not sending anything back while processing, you should run to completion... even if the user closes the connection... To make sure, you can use the register_shutdown_function() which will be called when PHP shuts down... now be careful, as Laravel has hooks there too... so any timeout will trigger Laravel error first, yours second... However, you can know in that function if it shut down properly or if it aborted...

To play with the function I created a route like this:

 use Illuminate\Support\Facades\Log;

 Route::get('/abort', function(){
    Log::info('Entering abort route...');
    set_time_limit(5);
    register_shutdown_function(function(){
        Log::info('Entering shutdown function... status: ' . connection_status());
        switch(connection_status()){
            case CONNECTION_ABORTED:
                Log::info('Connection Aborted');
                break;
            case CONNECTION_TIMEOUT:
                echo 'Connection Timeout';
                break;
            default:
                echo 'All ok, user did not abort and function did not time out.';
        }
    });

    while(1){
        echo 'Ping<br />';
    };
});

Here you can catch (I used the Laravel logger for the abort... find the log in storage/logs/laravel.log) ...

Now interestingly, if you abort this, you will get an abord call in the shutdown function, because the while(1) echoes 'Ping' to the browser, detecting the connection loss before the time out... however, if you remove the echo in the while and replace it with non buffer work $cnt++; or something, Then even if you abort, you will only get the timeout... the script did not detect the connection closing...

Note that your handler runs after all other handlers...

Also, it runs every time the script shuts down... so even when all is good... as in the default: switch above... naturally, this script will not run to completion because of the while(1)... just remove it if you want to see the normal completion behaviour...

I think this is probably the easiest way to do the clean up... catch it in there and do any clean up you need to...

Hope this helps...


问:
Modifiying an APK file to make minor changes
First, I'm not a developer, just a guy who knows some basic programming and who wants to make a -seemingly- easy task. I have an APK file which was originally created for an android TV receiver. It's an app that manages TV channels. Now, since the team working on the receiver's updates seems not very picky about some details, I thought maybe I have to do the changes I need myself.

So first, some of the text involves some french characters, namely accents, which are not displayed the right way, they are replaced by random characters such as "Ȼ", "Ø" .... I thought that was an encoding problem, so I decompiled the apk using Apktool and checked some XML files but found UTF-8 in the header of all them.

Second, some text zones are somehow "shifted", they aren't in their right positions. I'm willing to adjust the positionning of these text zones.

So, do you think there is any possibility I can solve these two problems ? How can I identify which part in the apk file treats a specific zone in the app in order to reduce my "search zone" ?

答:
To put it simple: No you can't. There is not really a way to modify an apk.

You could recreate the app. You can take the decompiled code, read some android dev tutorials and write your own app with the old one as a base.

But there is also a problem with that. The decompiled code is probably obfuscated, to prevent such practicies, and to secure their code.

Again: But if you just want to reposition some text fields, it's probably possible. If you open an APK like a zip file (basically it's just that) you have the res folder. In it, there are the layout files. You just have to modify some of them and then you can repack the zip and rename it to an apk. I'm very confident that this method should work.


问:
Which one is the best PDF-API for PHP?
Which one of these is the best PDF-API for PHP?

ApacheFOP

dompdf

FPDF

html2ps

mPDF

PDFlib

TCPDF

wkhtmltopdf

Zend_Pdf

答:
From the mpdf site:
"mPDF is a PHP class which generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF, with a number of enhancements."

mpdf is superior to FPDF for language handling and UTF-8 support.  For CJK support it not only supports font embedding, but font subsetting (so your CJK PDFs are not oversized).  TCPDF and FPDF have nothing on the UTF-8 and Font support of mpdf.  It even comes with some open source fonts as of version 5.0.

Title: Which one is the best PDF-API for PHP?


问:
java: jGrasp unchecked or unsafe operations
Please, before pitching this into the duplicate bucket, have mercy and help a Java 'newbie'...my code is:

```<code>//at top of class
List<String> faceStrList             = new ArrayList<String>(cardsPerSuit);
</code>```

Then, the line (in another method) that uses the offending other method:

```<code>faceStrList = readInfo( cardValueFileStr, faceStrList );
</code>```

and the problem-child:

```<code>public static List readInfo( String inputFile, List<String> dataArrayOfStr )
{
    String word = 'dummy';
    dataArrayOfStr.add(word);
    return dataArrayOfStr;
}
</code>```

Again, please look kindly.

答:
You just need to tell compiler that you are returning a list of String

```<code>public static List<String> readInfo(String inputFile, List<String> dataArrayOfStr)
{
    String word = "dummy";
    dataArrayOfStr.add(word);
    return dataArrayOfStr;
}
</code>```

The java.util.List interface is a subtype of the java.util.Collection interface. It represents an ordered list of objects, meaning you can access the elements of a List in a specific order, and by an index too

You have already defined faceStrList is a list of String. Then you are assigning a list of any type to the variable.

It won't create any compiler error, but it would be better if you can specify that you are returning a list of string to the compiler.

Body:
Please, before pitching this into the duplicate bucket, have mercy and help a Java 'newbie'...my code is:

//at top of class
List<String> faceStrList             = new ArrayList<String>(cardsPerSuit);

Then, the line (in another method) that uses the offending other method:

faceStrList = readInfo( cardValueFileStr, faceStrList );

and the problem-child:

public static List readInfo( String inputFile, List<String> dataArrayOfStr )
{
    String word = 'dummy';
    dataArrayOfStr.add(word);
    return dataArrayOfStr;
}

Again, please look kindly.

Body:
You just need to tell compiler that you are returning a list of String

public static List<String> readInfo(String inputFile, List<String> dataArrayOfStr)
{
    String word = "dummy";
    dataArrayOfStr.add(word);
    return dataArrayOfStr;
}

The java.util.List interface is a subtype of the java.util.Collection interface. It represents an ordered list of objects, meaning you can access the elements of a List in a specific order, and by an index too

You have already defined faceStrList is a list of String. Then you are assigning a list of any type to the variable.

It won't create any compiler error, but it would be better if you can specify that you are returning a list of string to the compiler.


问:
PostgreSQL internals- using GUC in an Operator?
I am creating my own index method in PostgreSQL based on GiST as extension. I want one of my functions (check out Examples section) in my operator to behave differently based on a value defined by the user- I want to avoid the user having to drop and create operators again.

So, I was looking at introducing a GUC variable. However, I am not so sure how to implement this appropriately. Right now in my implementation, the operator is being created with the value of GUC and is not behaving differently once GUC value changes at runtime.

I am not sure if I have to somehow change the signature of the function to use GUC or if I must introduce some pointer to the GUC. I cannot find any helpful material and I do not fully understand the internals to achieve this goal.

What best practices must I use for introducing an operator which changes behaviour at runtime? Unfortunately, I cannot find much information on writing internal functions/ operators/GUC in this context and so it would be great to hear any kind of feedback at all.

答:
A “GUC” (Grand Unified Configuration) is simply a global C variable in your program code, so changing its value will take effect as soon as your code reads the variable.

Your function will be in a shared object that is loaded into PostgreSQL, and you can use the _PG_init() function that is called at load time to register a new GUC with the DefineCustomXXXVariable() functions.

Your GUC can then be set like any other GUC.

I recommend that you look at contrib modules like auto_explain to see how they do it.