问:
Not hitting controller in MVC
In my submit of my login form which is in pop-up it is not hitting the controller even though I provided the code in beginform with post method. I need to send the username and password to my controller for verification. Unable to figure out why it is not hitting.

```<code>[HttpPost]
    public ActionResult LoginUser(UserInfo objUser)
    {

        int res = udaObj.CheckUser(objUser.UserName, objUser.Password);
        if (res >= 1)
        {
           return RedirectToAction("Appointment", "Home");
        }
        else
        {
            //For testing purpose
            return RedirectToAction("Appointment", "Home");
        }
    }
</code>```

My view is as follows:

```<code> @using (Html.BeginForm("LoginUser", "Home", FormMethod.Post, new { id = "loginForm" }))
                {
                    <div class="tab-pane fade active in" id="signin">
                        <fieldset>
                            <!-- Sign In Form -->
                            <!-- Text input-->
                            <div class="control-group">
                                <label class="control-label" for="userid">Alias:</label>
                                <div class="controls">
                                   @* <input required="" id="userid" name="userid" type="text" class="form-control" placeholder="JoeSixpack" class="input-medium" required="">*@
                                     @Html.TextBoxFor(x => x.UserName, new { @class = "form-control input-large", @placeholder = "Joek@irawath.com", @required = "" , @id="userid" })
                                </div>
                            </div>

                            <!-- Password input-->
                            <div class="control-group">
                                <label class="control-label" for="passwordinput">Password:</label>
                                <div class="controls">
                                    @*<input required="" id="passwordinput" name="passwordinput" class="form-control" type="password" placeholder="********" class="input-medium">*@
                                     @Html.TextBoxFor(x => x.Password, new { @class = "form-control input-large", @placeholder = "********", @required = "", @type = "password" , @id="passwordinput" })
                                </div>
                            </div>

                            <!-- Multiple Checkboxes (inline) -->
                            <div class="control-group">
                                <label class="control-label" for="rememberme"></label>
                                <div class="controls">
                                    <label class="checkbox inline" for="rememberme-0">
                                        <input type="checkbox" name="rememberme" id="rememberme-0" value="Remember me" style="margin-left: 0px">
                                        Remember me
                                    </label>
                                </div>
                            </div>
                            <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>
                            <!-- Button -->
                            <div class="control-group">
                                <label class="control-label" for="signin"></label>
                                <div class="controls">
                                    @* <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>*@
                                </div>
                            </div>
                        </fieldset>
                    </div>
                }
</code>```

答: Check if the object UserInfo is the same model you are using in your view. Try using a FormCollection instead and check.</p>

Title: Not hitting controller in MVC

Body:
In my submit of my login form which is in pop-up it is not hitting the controller even though I provided the code in beginform with post method. I need to send the username and password to my controller for verification. Unable to figure out why it is not hitting.

[HttpPost]
    public ActionResult LoginUser(UserInfo objUser)
    {

        int res = udaObj.CheckUser(objUser.UserName, objUser.Password);
        if (res >= 1)
        {
           return RedirectToAction("Appointment", "Home");
        }
        else
        {
            //For testing purpose
            return RedirectToAction("Appointment", "Home");
        }
    }

My view is as follows:

 @using (Html.BeginForm("LoginUser", "Home", FormMethod.Post, new { id = "loginForm" }))
                {

                        <fieldset>

                                Alias:

                                   @* <input required="" id="userid" name="userid" type="text" class="form-control" placeholder="JoeSixpack" class="input-medium" required="">*@
                                     @Html.TextBoxFor(x => x.UserName, new { @class = "form-control input-large", @placeholder = "Joek@irawath.com", @required = "" , @id="userid" })

                                Password:

                                    @*<input required="" id="passwordinput" name="passwordinput" class="form-control" type="password" placeholder="********" class="input-medium">*@
                                     @Html.TextBoxFor(x => x.Password, new { @class = "form-control input-large", @placeholder = "********", @required = "", @type = "password" , @id="passwordinput" })

                                        <input type="checkbox" name="rememberme" id="rememberme-0" value="Remember me" style="margin-left: 0px">
                                        Remember me

                            <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>

                                    @* <button id="btnsignin" type="submit" name="signin" class="btn btn-success">Sign In</button>*@

                        </fieldset>

                }


来源: stackexchange

问:
Getting lowest values in GROUP BY
```<code>WITH test_data AS (
  SELECT 1 key, 1 a, 2 b FROM dual UNION ALL  --# Lowest a for key=1
  SELECT 1 key, 2 a, 1 b FROM dual UNION ALL
  SELECT 2 key, 3 a, 3 b FROM dual UNION ALL  --# Lowest a for key=2, lowest b
  SELECT 2 key, 3 a, 4 b FROM dual UNION ALL
  SELECT 2 key, 4 a, 5 b FROM dual
)
</code>```

I'm trying to group by key, and retrieve the lowest a and the corresponding b (lowest b in case of ties), plus the SUM of its bs:

```<code>       KEY          A    FIRST_B      SUM_B
---------- ---------- ---------- ----------
         1          1          2          3
         2          3          3         12
</code>```

I can realize this with a sub-select

```<code>SELECT key, MIN(a) AS a, first_b, SUM(b) AS sum_b
FROM (
  SELECT key, a, b,
         FIRST_VALUE(b) OVER (PARTITION BY key ORDER BY a, b) AS first_b
  FROM test_data
)
GROUP BY key, first_b
</code>```

but I wonder if there is a way to avoid the sub-select, something like

```<code>SELECT key, a, SUM(b) AS sum_b,
       MIN( FIRST_VALUE(b) OVER (PARTITION BY key ORDER BY a, b) ) AS first_b
FROM test_data
GROUP BY key, a
</code>```

which raises ORA-30483: window  functions are not allowed here

Thanks in advance, Peter

答:
I think you'd probably also call the idea below a sub-select (or 2 subselects), but try it anyway.

Otherwise you're out of luck, as what you want requires that you perform two different group by aggregations, one on the key alone, and one on the key and on the a attribute.  And you cannot do two different group by aggregations in the same SQL statement.  So, you need at least two different SQL statements, which must then obviously be combined in some way.  And there is no way to combine two resultsets from two different SQL statments into one without treating one or the other (or both) as a sub-select of one kind or another)

```<code>   Select X.key, X.a, y.firstBm X.sum_b
   From
    (SELECT tda.key, MIN(tda.a) a,
        Min(case tdb.b) firstB,
        SUM(tda.b) sum_b
       FROM test_data tda
       Group By key) X
    Left Join
      (Select tda.key, a,
        Min(b) firstB
       FROM test_data
       Group By key, a) Y
    On Y.key = X.key
       And Y.a = X.a
</code>```

ContentLicense: CC BY-SA 2.5

Title: Getting lowest values in GROUP BY

Body:
WITH test_data AS (
  SELECT 1 key, 1 a, 2 b FROM dual UNION ALL  --# Lowest a for key=1
  SELECT 1 key, 2 a, 1 b FROM dual UNION ALL
  SELECT 2 key, 3 a, 3 b FROM dual UNION ALL  --# Lowest a for key=2, lowest b
  SELECT 2 key, 3 a, 4 b FROM dual UNION ALL
  SELECT 2 key, 4 a, 5 b FROM dual
)

I'm trying to group by key, and retrieve the lowest a and the corresponding b (lowest b in case of ties), plus the SUM of its bs:

       KEY          A    FIRST_B      SUM_B
---------- ---------- ---------- ----------
         1          1          2          3
         2          3          3         12

I can realize this with a sub-select

SELECT key, MIN(a) AS a, first_b, SUM(b) AS sum_b
FROM (
  SELECT key, a, b,
         FIRST_VALUE(b) OVER (PARTITION BY key ORDER BY a, b) AS first_b
  FROM test_data
)
GROUP BY key, first_b

but I wonder if there is a way to avoid the sub-select, something like

SELECT key, a, SUM(b) AS sum_b,
       MIN( FIRST_VALUE(b) OVER (PARTITION BY key ORDER BY a, b) ) AS first_b
FROM test_data
GROUP BY key, a

which raises ORA-30483: window  functions are not allowed here

Thanks in advance, Peter

Body:
I think you'd probably also call the idea below a sub-select (or 2 subselects), but try it anyway.

Otherwise you're out of luck, as what you want requires that you perform two different group by aggregations, one on the key alone, and one on the key and on the a attribute.  And you cannot do two different group by aggregations in the same SQL statement.  So, you need at least two different SQL statements, which must then obviously be combined in some way.  And there is no way to combine two resultsets from two different SQL statments into one without treating one or the other (or both) as a sub-select of one kind or another)

   Select X.key, X.a, y.firstBm X.sum_b
   From
    (SELECT tda.key, MIN(tda.a) a,
        Min(case tdb.b) firstB,
        SUM(tda.b) sum_b
       FROM test_data tda
       Group By key) X
    Left Join
      (Select tda.key, a,
        Min(b) firstB
       FROM test_data
       Group By key, a) Y
    On Y.key = X.key
       And Y.a = X.a


问:
Regex to end match after four sets of initials
I have a regular expression with a variant that is used in javascript code to find words together as follows:

```<code>var re = new RegExp(firstWord+"\\s\\d{1,2}\\.\\d{1,2}\\.\\d{2,4}\\s\\w+(?:\\s+\\w+){1,8}\\s([A-Z]{2,5})\\s([A-Z]{2,5})\\s([A-Z]{2,5})\\s([A-Z]{2,5})");
</code>```

result with a match is as :

0 17.07.17 APPROVED FOR CONSTRUCTION SB SB GM TW DA MEA,GM,TW,DA,MEA

The regex matches but includes extra characters at the end. In this example it is DA MEA,GM,TW,DA,MEA

Can anyone please advise how to modify the regex to end the match after the four sets of initials?

答:
Here is a regex that would match and capture DA MEA,GM,TW,DA,MEA from the input:

0 17.07.17 APPROVED FOR CONSTRUCTION SB SB GM TW DA MEA,GM,TW,DA,MEA

```<code>\d\s\d{2}\.\d{2}\.\d{2}\s(?:.*?)(?:\s[a-zA-z]{2}){4}\s(.*)
</code>```

EDIT

From what I understand what you actually want to match is the first part, here is a modified version of the regex to ignore the last part of the string.

```<code>\d\s\d{2}\.\d{2}\.\d{2}\s(?:.*?)(?:\s[a-zA-z]{2}){4}
</code>```

This will match

```<code>0 17.07.17 APPROVED FOR CONSTRUCTION SB SB GM TW
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a regular expression with a variant that is used in javascript code to find words together as follows:

var re = new RegExp(firstWord+"\\s\\d{1,2}\\.\\d{1,2}\\.\\d{2,4}\\s\\w+(?:\\s+\\w+){1,8}\\s([A-Z]{2,5})\\s([A-Z]{2,5})\\s([A-Z]{2,5})\\s([A-Z]{2,5})");

result with a match is as :

0 17.07.17 APPROVED FOR CONSTRUCTION SB SB GM TW DA MEA,GM,TW,DA,MEA

The regex matches but includes extra characters at the end. In this example it is DA MEA,GM,TW,DA,MEA

Can anyone please advise how to modify the regex to end the match after the four sets of initials?

Body:
Here is a regex that would match and capture DA MEA,GM,TW,DA,MEA from the input:

0 17.07.17 APPROVED FOR CONSTRUCTION SB SB GM TW DA MEA,GM,TW,DA,MEA

\d\s\d{2}\.\d{2}\.\d{2}\s(?:.*?)(?:\s[a-zA-z]{2}){4}\s(.*)

EDIT

From what I understand what you actually want to match is the first part, here is a modified version of the regex to ignore the last part of the string.

\d\s\d{2}\.\d{2}\.\d{2}\s(?:.*?)(?:\s[a-zA-z]{2}){4}

This will match

0 17.07.17 APPROVED FOR CONSTRUCTION SB SB GM TW


问:
ClassNotFound error for Ignite User Defined Function in Flink Cluster
I am trying to cache the data, streamed by Apache flink, into Apache Ignite cache. I also want to run the query which uses a User Defined Function. As per Ignite, I am using cacheConf.setSqlFunctionClasses(GetCacheKey.class) setting while declaring the cache. The class declaration is as follows,

```<code>public static class GetCacheKey implements Serializable{

   @QuerySqlFunction
    public static long getCacheKey(int mac, long local) {
        long key=(local << 5) + mac;
        return key;
    }
</code>```

}

When I run the code locally with Apache Flink, it works. But when I go for cluster execution of the code in Flink Cluster, I got an error that GetCacheKey class is not found. What will be the reason behind this?

答:
The Flink directory must be available on every worker under the same path. You can use a shared NFS directory, or copy the entire Flink directory to every worker node.

Also ensure the Ignite libs are present in worker nodes classpath.

Body:
I am trying to cache the data, streamed by Apache flink, into Apache Ignite cache. I also want to run the query which uses a User Defined Function. As per Ignite, I am using cacheConf.setSqlFunctionClasses(GetCacheKey.class) setting while declaring the cache. The class declaration is as follows,

public static class GetCacheKey implements Serializable{

   @QuerySqlFunction
    public static long getCacheKey(int mac, long local) {
        long key=(local << 5) + mac;
        return key;
    }

}

When I run the code locally with Apache Flink, it works. But when I go for cluster execution of the code in Flink Cluster, I got an error that GetCacheKey class is not found. What will be the reason behind this?


问:
Facebook messenger bot Persistent Menu button
I need to have a Facebook Messenger Bot persistent menu item "Send Message" which should not trigger a postback. Instead place the cursor on the messenger textbox. Is there a way to create the menu item without having the menu item type as "postback" or "web_url" </p>

答:
Check the code from https://developers.facebook.com/docs/messenger-platform/messenger-profile/persistent-menu

```<code>curl -X POST -H "Content-Type: application/json" -d '{
  "persistent_menu":[
    {
      "locale":"default",
      "composer_input_disabled":true,
      "call_to_actions":[
        {...
</code>```

Change composer_input_disabled to false.

Body:
Check the code from https://developers.facebook.com/docs/messenger-platform/messenger-profile/persistent-menu

curl -X POST -H "Content-Type: application/json" -d '{
  "persistent_menu":[
    {
      "locale":"default",
      "composer_input_disabled":true,
      "call_to_actions":[
        {...

Change composer_input_disabled to false.


问:
So I'm trying to create a door that opens or slides away without an animation
For the class I am in I'm trying to make a door that opens but without an animation, it plays through well in visual studios and when testing in unity the door does nothing. I'm not sure how to do this , so please  I implore any help whatsoever.</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OpenDoor : MonoBehaviour
{
    float smooth = 2.0f;
    float DoorOpenAngle = 90.0f;
    float DoorCloseAngle = 0.0f;
    bool open;
    bool enter;

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            enter = true;
            print("open");
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            enter = false;
            print("close");
        }
    }

    void update()
    {
        if (open == true)
        {
            print("if(open)");
            var target = Quaternion.Euler(0, DoorOpenAngle, 0);
            transform.localRotation = Quaternion.Slerp(transform.localRotation, target, Time.deltaTime * smooth);
        }

        if (open == false)
        {
            print("if(!open)");
            var target1 = Quaternion.Euler(0, DoorCloseAngle, 0);
            transform.localRotation = Quaternion.Slerp(transform.localRotation, target1, Time.deltaTime * smooth);
        }

        if (enter == true)
        {
            print("if(enter)");
            if (Input.GetKeyDown("f"))
            {
                open = !open;
            }
        }
    }
}
</code>```

答:
that code should work even if it is not very safe...
Make sure that both Player and door has colliders. and the door's collider's IsTrigger option is true.</p>

Body:
For the class I am in I'm trying to make a door that opens but without an animation, it plays through well in visual studios and when testing in unity the door does nothing. I'm not sure how to do this , so please  I implore any help whatsoever.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OpenDoor : MonoBehaviour
{
    float smooth = 2.0f;
    float DoorOpenAngle = 90.0f;
    float DoorCloseAngle = 0.0f;
    bool open;
    bool enter;

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            enter = true;
            print("open");
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            enter = false;
            print("close");
        }
    }

    void update()
    {
        if (open == true)
        {
            print("if(open)");
            var target = Quaternion.Euler(0, DoorOpenAngle, 0);
            transform.localRotation = Quaternion.Slerp(transform.localRotation, target, Time.deltaTime * smooth);
        }

        if (open == false)
        {
            print("if(!open)");
            var target1 = Quaternion.Euler(0, DoorCloseAngle, 0);
            transform.localRotation = Quaternion.Slerp(transform.localRotation, target1, Time.deltaTime * smooth);
        }

        if (enter == true)
        {
            print("if(enter)");
            if (Input.GetKeyDown("f"))
            {
                open = !open;
            }
        }
    }
}


问:
Functor type variables for Flip data type
I have following type definition:

```<code>newtype Flip f a b =
  Flip (f b a) deriving (Eq, Show)
</code>```

Does the Flip data constructor has one or three arguments?

Consinder following implementation:

```<code>data K a b = K a

newtype Flip f a b =
  Flip (f b a) deriving (Eq, Show)

instance Functor (Flip K a) where
  fmap f (Flip (K b)) = Flip (K (f b))
</code>```

What is the type of (Flip K a)?

答:
The future is now, when you (use ghc 8 and) switch on a flag or two

```<code>Prelude> :set -XPolyKinds -XFlexibleInstances
</code>```

Let us declare

```<code>Prelude> newtype Flip f a b = MkFlip (f b a)
</code>```

and then enquire

```<code>Prelude> :kind Flip
Flip :: (k1 -> k -> *) -> k -> k1 -> *

Prelude> :type MkFlip
MkFlip
  :: forall k k1 (b :: k) (f :: k -> k1 -> *) (a :: k1).
     f b a -> Flip f a b
</code>```

The type constructor Flip takes two implicit arguments, being k and k1, and three explicit arguments, being a binary function producing a type, then its two arguments in reverse order. The arguments to this function are of unconstrained type (old people can say "kind" if they like), but it certainly returns a type (in the strict sense of "thing in *", rather than the uselessly vague sense of "any old rubbish right of ::") because it is certainly used as a type in the declaration of MkFlip.

The data constructor, MkFlip, takes five implicit arguments (exactly the arguments of Flip) and one explicit argument, being some data in f b a.

What's going on is Hindley-Milner type inference one level up. Constraints are collected (e.g., f b a must inhabit * because a constructor argument must inhabit f b a) but otherwise a most general type is delivered: a and b could be anything, so their types are generalised as k1 and k.

Let's play the same game with the constant type constructor:

```<code>Prelude> newtype K a b = MkK a

Prelude> :kind K
K :: * -> k -> *

Prelude> :type MkK
MkK :: forall k (b :: k) a. a -> K a b
</code>```

We see that a :: * but b can be any old rubbish (and for that matter, k :: *, as these days, * :: *). Clearly, a is actually used as the type of a thing, but b is not used at all, hence unconstrained.

We may then declare

```<code>Prelude> instance Functor (Flip K b) where fmap f (MkFlip (MkK a)) = MkFlip (MkK (f a))
</code>```

and ask

```<code>Prelude> :info Flip
...
instance [safe] forall k (b :: k). Functor (Flip K b)
</code>```

which tells us that the unused b can still be any old rubbish. Because we had

```<code>K    ::   * -> k -> *
Flip :: (k1 -> k -> *) -> k -> k1 -> *
</code>```

we can unify k1 = * and get

```<code>Flip K :: k -> * -> *
</code>```

and so

```<code>Flip K b :: * -> *
</code>```

for any old b. A Functor instance is thus plausible, and indeed deliverable, with the function acting on the packed up a element, corresponding to the argument of Flip K b which becomes the first argument of K, hence the type of the stored element.

Unification-based type inference is alive and (fairly) well, right of ::.

Body:
I have following type definition:

newtype Flip f a b =
  Flip (f b a) deriving (Eq, Show)

Does the Flip data constructor has one or three arguments?

Consinder following implementation:

data K a b = K a

newtype Flip f a b =
  Flip (f b a) deriving (Eq, Show)

instance Functor (Flip K a) where
  fmap f (Flip (K b)) = Flip (K (f b))

What is the type of (Flip K a)?

Body:
The future is now, when you (use ghc 8 and) switch on a flag or two

Prelude> :set -XPolyKinds -XFlexibleInstances

Let us declare

Prelude> newtype Flip f a b = MkFlip (f b a)

and then enquire

Prelude> :kind Flip
Flip :: (k1 -> k -> *) -> k -> k1 -> *

Prelude> :type MkFlip
MkFlip
  :: forall k k1 (b :: k) (f :: k -> k1 -> *) (a :: k1).
     f b a -> Flip f a b

The type constructor Flip takes two implicit arguments, being k and k1, and three explicit arguments, being a binary function producing a type, then its two arguments in reverse order. The arguments to this function are of unconstrained type (old people can say "kind" if they like), but it certainly returns a type (in the strict sense of "thing in *", rather than the uselessly vague sense of "any old rubbish right of ::") because it is certainly used as a type in the declaration of MkFlip.

The data constructor, MkFlip, takes five implicit arguments (exactly the arguments of Flip) and one explicit argument, being some data in f b a.

What's going on is Hindley-Milner type inference one level up. Constraints are collected (e.g., f b a must inhabit * because a constructor argument must inhabit f b a) but otherwise a most general type is delivered: a and b could be anything, so their types are generalised as k1 and k.

Let's play the same game with the constant type constructor:

Prelude> newtype K a b = MkK a

Prelude> :kind K
K :: * -> k -> *

Prelude> :type MkK
MkK :: forall k (b :: k) a. a -> K a b

We see that a :: * but b can be any old rubbish (and for that matter, k :: *, as these days, * :: *). Clearly, a is actually used as the type of a thing, but b is not used at all, hence unconstrained.

We may then declare

Prelude> instance Functor (Flip K b) where fmap f (MkFlip (MkK a)) = MkFlip (MkK (f a))

and ask

Prelude> :info Flip
...
instance [safe] forall k (b :: k). Functor (Flip K b)

which tells us that the unused b can still be any old rubbish. Because we had

K    ::   * -> k -> *
Flip :: (k1 -> k -> *) -> k -> k1 -> *

we can unify k1 = * and get

Flip K :: k -> * -> *

and so

Flip K b :: * -> *

for any old b. A Functor instance is thus plausible, and indeed deliverable, with the function acting on the packed up a element, corresponding to the argument of Flip K b which becomes the first argument of K, hence the type of the stored element.

Unification-based type inference is alive and (fairly) well, right of ::.


问:
Reference generated primary key in SQL script
I'm trying to create a bunch of entries in a database with a single script and the problem I'm encountering is how to reference the generated primary key of the previous entry I created.

For example if I created a customer, then tried to create an order for that customer, how do I get the primary key generated for the customer?

I'm using SQLServer.

答: If available in your version, use SCOPE_IDENTITY() instead.  Safer than @@IDENTITY.</p>

OwnerDisplayName: Kenny

OwnerDisplayName: beach


问:
Jquery ajax get xml parse error
I want get a XML from this url usin Jquery ajax https://sisa.msal.gov.ar/sisa/services/rest/puco/44003375

Via browser I can see this:

```<code>This XML file does not appear to have any style information associated with it. The document tree is shown below.
<puco>
 <resultado>OK</resultado>
 <coberturaSocial>O.S.P. CIUDAD AUT</coberturaSocial>
<denominacion>AGOSTINO RODRIGO LEONARDO</denominacion>
<nrodoc>44003375</nrodoc>
<rnos>901001</rnos>
<tipodoc>DNI</tipodoc>
</puco>
</code>```

But when doing:

```<code>var id=44003375;
$.ajax({
    type : "GET",
    url  : 'https://sisa.msal.gov.ar/sisa/services/rest/puco/'+id,
    dataType :"JSONP",
    jsonp: true,
    success : function(xhr){
      alert(JSON.stringify(xhr));
    },
    error : function(httpReq,status,exception){
      var clientid = $(httpReq).text();
      alert(JSON.stringify(httpReq));
    }
 });
</code>```

Return "Parse error"... how I can get via ajax what the browser shows?

答: Use  JavaScript .load() and then parse the XML to JSON as detailed here

Title: Jquery ajax get xml parse error

Body:
I want get a XML from this url usin Jquery ajax https://sisa.msal.gov.ar/sisa/services/rest/puco/44003375

Via browser I can see this:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<puco>
 <resultado>OK</resultado>
 <coberturaSocial>O.S.P. CIUDAD AUT</coberturaSocial>
<denominacion>AGOSTINO RODRIGO LEONARDO</denominacion>
<nrodoc>44003375</nrodoc>
<rnos>901001</rnos>
<tipodoc>DNI</tipodoc>
</puco>

But when doing:

var id=44003375;
$.ajax({
    type : "GET",
    url  : 'https://sisa.msal.gov.ar/sisa/services/rest/puco/'+id,
    dataType :"JSONP",
    jsonp: true,
    success : function(xhr){
      alert(JSON.stringify(xhr));
    },
    error : function(httpReq,status,exception){
      var clientid = $(httpReq).text();
      alert(JSON.stringify(httpReq));
    }
 });

Return "Parse error"... how I can get via ajax what the browser shows?


问:
iOS app will not launch until restart phone
I'm not entirely sure where to start with this. I have an iOS app in Swift for iOS 10.3 that uses Crashlytics and Realm, and several times a day, when I launch my app, it just sits at the launch screen, and then promptly closes. I get no logs when this happens (through crashlytics, or on the device), and the only way this solves itself is if I restart my phone, reinstall the app, or if I try again several hours later. I don't know how to debug this issue.

My application launching function is as follows:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    Fabric.with([Crashlytics.self])
    // Override point for customization after application launch.
    self.createDirectories()
    var performShortcutDelegate = true
    let dir: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.BackloggerSharing")!
    let realmPath = dir.appendingPathComponent("db.realm")

    let config = Realm.Configuration(fileURL: realmPath, schemaVersion: 1, migrationBlock: {
        migration, oldSchemaVersion in
        if oldSchemaVersion < 1 {
            // auto migrate
        }
    })
    Realm.Configuration.defaultConfiguration = config
    self.compactRealm(at: realmPath)

    (UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])).tintColor = Util.appColor
    UISlider.appearance().tintColor = Util.appColor
    self.window?.tintColor = Util.appColor

    if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
        self.shortcutItem = shortcutItem
        performShortcutDelegate = false
    }

    return performShortcutDelegate
}

func createDirectories() {
    let playlistsFolder = Util.getPlaylistImagesDirectory()

    if !FileManager.default.fileExists(atPath: playlistsFolder.absoluteString) {
        do {
            try FileManager.default.createDirectory(at: playlistsFolder, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog(error.localizedDescription)
        }
    }
}

func compactRealm(at realmPath: URL) {
    let defaultParentURL = realmPath.deletingLastPathComponent()
    let compactedURL = defaultParentURL.appendingPathComponent("default-compact.realm")
    autoreleasepool {
        let realm = try? Realm()
        try! realm?.writeCopy(toFile: compactedURL)
    }
    try! FileManager.default.removeItem(at: realmPath)
    try! FileManager.default.moveItem(at: compactedURL, to: realmPath)
}
</code>```

Any help on the matter would be greatly appreciated!

答:
Turns out it was that I had a realm opening in my Today Extension that was not closing the realm instance. When I would load my application, I would attempt to open another realm (now in a second process which is unsupported), and perform migration and compaction. I have updated the Today Extension to close realm instances while they are not needed.

This debugging was determined from my app not saving logs because I reached the max allowed for an application (25). I cleared the logs, found them, symbolicated them, and found that Realm struggled upon opening.

Body:
I'm not entirely sure where to start with this. I have an iOS app in Swift for iOS 10.3 that uses Crashlytics and Realm, and several times a day, when I launch my app, it just sits at the launch screen, and then promptly closes. I get no logs when this happens (through crashlytics, or on the device), and the only way this solves itself is if I restart my phone, reinstall the app, or if I try again several hours later. I don't know how to debug this issue.

My application launching function is as follows:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    Fabric.with([Crashlytics.self])
    // Override point for customization after application launch.
    self.createDirectories()
    var performShortcutDelegate = true
    let dir: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.BackloggerSharing")!
    let realmPath = dir.appendingPathComponent("db.realm")

    let config = Realm.Configuration(fileURL: realmPath, schemaVersion: 1, migrationBlock: {
        migration, oldSchemaVersion in
        if oldSchemaVersion < 1 {
            // auto migrate
        }
    })
    Realm.Configuration.defaultConfiguration = config
    self.compactRealm(at: realmPath)

    (UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])).tintColor = Util.appColor
    UISlider.appearance().tintColor = Util.appColor
    self.window?.tintColor = Util.appColor

    if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
        self.shortcutItem = shortcutItem
        performShortcutDelegate = false
    }

    return performShortcutDelegate
}

func createDirectories() {
    let playlistsFolder = Util.getPlaylistImagesDirectory()

    if !FileManager.default.fileExists(atPath: playlistsFolder.absoluteString) {
        do {
            try FileManager.default.createDirectory(at: playlistsFolder, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog(error.localizedDescription)
        }
    }
}

func compactRealm(at realmPath: URL) {
    let defaultParentURL = realmPath.deletingLastPathComponent()
    let compactedURL = defaultParentURL.appendingPathComponent("default-compact.realm")
    autoreleasepool {
        let realm = try? Realm()
        try! realm?.writeCopy(toFile: compactedURL)
    }
    try! FileManager.default.removeItem(at: realmPath)
    try! FileManager.default.moveItem(at: compactedURL, to: realmPath)
}

Any help on the matter would be greatly appreciated!


问:
Make sure Java will not close OutputStream before PrinWriter.print() finishes
I'm developing a distributed system that receives requests via Socket and writes the results back using OutputStream.

I'm facing problems because I have to return a very large string, but Java just keeps the execution of the code after I call the method print() without it finished printing:

```<code>public void attendRequisition(Socket clientSocket) {
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());

    pw.print(getResults());

    pw.close()
}
</code>```

Some information:

I need to close the connection after sending the results.

Without the close() instruction, the whole printing process takes about 3~5 seconds to finishes

I'm using telnet to test this method, and I can see the message coming and being cut becase of Java running the close() instruction

I can't count with receiving client's feedback

I believe this is happening because Java thinks the method print() finished executing, but what might be happening is that Java sends the message to the JVM, and JVM send it to the network adapter, and since the message is very large, close() method is called before the network adapter is able to send the entire message.

What I need is a way to make sure Java will only run the instruction close() after the printing process finished and the client received the entire message.

UPDATE: I was able to get it working properly by adding a Thread.sleep(). By doing this, the SO has enough time to send the message before Java closes the connection. But I don't want to use this solution, it implicates on too many problems.

答:
I'll bet that if you use another constructor (i.e., the one whose 2nd argument is a boolean to indicate your desire to flush) then your example will work. The way you're constructing the object, autoflush is disabled.

If your real code is more complex, then you can call pw.flush() at the appropriate moments.

Body:
I'm developing a distributed system that receives requests via Socket and writes the results back using OutputStream.

I'm facing problems because I have to return a very large string, but Java just keeps the execution of the code after I call the method print() without it finished printing:

public void attendRequisition(Socket clientSocket) {
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());

    pw.print(getResults());

    pw.close()
}

Some information:

I need to close the connection after sending the results.

Without the close() instruction, the whole printing process takes about 3~5 seconds to finishes

I'm using telnet to test this method, and I can see the message coming and being cut becase of Java running the close() instruction

I can't count with receiving client's feedback

I believe this is happening because Java thinks the method print() finished executing, but what might be happening is that Java sends the message to the JVM, and JVM send it to the network adapter, and since the message is very large, close() method is called before the network adapter is able to send the entire message.

What I need is a way to make sure Java will only run the instruction close() after the printing process finished and the client received the entire message.

UPDATE: I was able to get it working properly by adding a Thread.sleep(). By doing this, the SO has enough time to send the message before Java closes the connection. But I don't want to use this solution, it implicates on too many problems.


问:
How to get permission to edit the file apache2.conf? [Ubuntu]
I'm a beginner Ruby on Rails Programmer and I'm trying to install Apache2 + Passenger(That's for Rails Deployment).. and at the end of the installation process, Passenger gave me a few lines to add to the file apache2.conf at /etc/apache2/ but I can't override this file.. I have no permission =( I've also uploaded an image showing me the error.

P.S => I'm logged into Ubuntu with my username and password.

Please help! and thanks,
Rodrigo.

答:
Or you can use the following chmod 777 usr/local/apache2/conf/httpd.conf
this will enable you to read/write the config file but be warned if you are planning on putting apache2 online you must revert it back to the old permissions chmod 640 usr/local/apache2/conf/httpd.conf


答: You will need to use any xml to json converter or parser. Have a look at  http://goessner.net/download/prj/jsonxml/</p>

Title: Jquery ajax get xml parse error


问:
The method put(Character, Integer) in the type HashMap<Character,Integer> is not applicable for the arguments (char, int)
I am getting this error and I don't know why.

Here is my code:

```<code>char a[]=str.toCharArray();
    HashMap <Character,Integer> hm=new HashMap<Character,Integer>();
    for(int i=0;i<a.length;i++){
        if(hm.containsKey(a[i])){
            hm.put(a[i], hm.get(a[i])+1);
        }
    }
</code>```

答:
The code complies and executes correctly (I've just added an initialization for missing characters  hm.put(a[i], 1);).

```<code>char a[]=str.toCharArray();
HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
for(int i=0;i<a.length;i++){
    if(hm.containsKey(a[i])){
        hm.put(a[i], hm.get(a[i])+1);
    }else{
        hm.put(a[i], 1);
    }
}
</code>```

Strictly speaking the compiler is right because char is not Character and int is not Integer, but autoboxing should take care of this.

So we are missing some context.

The only way I could reproduce the same error was adding a mock Character class in the test class like this:

```<code>public class OneTest {

    private class Character{
    }
    @Test
    public void test() {
        String str = "AABcDD";
        char a[]=str.toCharArray();
        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
        for(int i=0;i<a.length;i++){
            if(hm.containsKey(a[i])){
                hm.put(a[i], hm.get(a[i])+1);
            }else{
                hm.put(a[i], 1);
            }
        }
        System.out.println(hm);
    }

}
</code>```

Body:
I am getting this error and I don't know why.

Here is my code:

char a[]=str.toCharArray();
    HashMap <Character,Integer> hm=new HashMap<Character,Integer>();
    for(int i=0;i<a.length;i++){
        if(hm.containsKey(a[i])){
            hm.put(a[i], hm.get(a[i])+1);
        }
    }

Body:
The code complies and executes correctly (I've just added an initialization for missing characters  hm.put(a[i], 1);).

char a[]=str.toCharArray();
HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
for(int i=0;i<a.length;i++){
    if(hm.containsKey(a[i])){
        hm.put(a[i], hm.get(a[i])+1);
    }else{
        hm.put(a[i], 1);
    }
}

Strictly speaking the compiler is right because char is not Character and int is not Integer, but autoboxing should take care of this.

So we are missing some context.

The only way I could reproduce the same error was adding a mock Character class in the test class like this:

public class OneTest {

    private class Character{
    }
    @Test
    public void test() {
        String str = "AABcDD";
        char a[]=str.toCharArray();
        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
        for(int i=0;i<a.length;i++){
            if(hm.containsKey(a[i])){
                hm.put(a[i], hm.get(a[i])+1);
            }else{
                hm.put(a[i], 1);
            }
        }
        System.out.println(hm);
    }

}


问:
Reading a JSON string | TypeError: string indices must be integers
I'm trying to create a program that will read in a JSON string through the GUI and then use this to perform additional functions, in this case breaking down a mathematical equation. At the moment I am getting the error:

"TypeError: string indices must be integers"

and I have no idea why.

The JSON I am trying to read in is as follows:

```<code>{
"rightArgument":{
"cell":"C18",
"value":9.5,
"type":"cell"
},
"leftArgument":{
"rightArgument":{
"cell":"C3",
"value":135,
"type":"cell"
},
"leftArgument":{
"rightArgument":{
"cell":"C4",
"value":125,
"type":"cell"
},
"leftArgument":{
"cell":"C5",
"value":106,
"type":"cell"
},
"type":"operation",
"operator":"*"
},
"type":"operation",
"operator":"+"
},
"type":"operation",
"operator":"+"
}
</code>```

```<code>import json
import tkinter
from tkinter import *

data = ""
list = []

def readText():
    mtext=""
    mtext = strJson.get()
    mlabel2 = Label(myGui,text=mtext).place(x=180,y=200)
    data = mtext

def mhello():
    _getCurrentOperator(data)

def _getCurrentOperator(data):
    if data["type"] == "operation":

        _getCurrentOperator(data["rightArgument"])
        _getCurrentOperator(data["leftArgument"])
        list.append(data["operator"])
    elif data["type"] == "group":
        _getCurrentOperator(data["argument"])
    elif data["type"] == "function":
        list.append(data["name"]) # TODO do something with arguments
        for i in range(len(data["arguments"])):
            _getCurrentOperator(data["arguments"][i])
    else:
        if (data["value"]) == '':
            list.append(data["cell"])
        else:
            list.append(data["value"])

print(list)

myGui = Tk()
strJson = StringVar()

myGui.title("Simple Gui")
myGui.geometry("400x300")

label = Label(text = 'Welcome!').place(x=170,y=40)
btnStart = Button(myGui,text='Start',command=mhello).place(x=210,y=260)
btnRead = Button(myGui,text='Read text',command=readText).place(x=210,y=200)
txtEntry = Entry(myGui, textvariable=strJson).place(x=150,y=160)
btnOptions = Button(myGui, text = "Options").place(x=150,y=260)

myGui.mainloop()
</code>```

答:
sometimes you need to use json.loads again..
this worked for me..

```<code>jsonn_forSaleSummary_string = json.loads(forSaleSummary)  //still string
jsonn_forSaleSummary        = json.loads(jsonn_forSaleSummary_string)
</code>```

finally!! json

Body:
I'm trying to create a program that will read in a JSON string through the GUI and then use this to perform additional functions, in this case breaking down a mathematical equation. At the moment I am getting the error:

"TypeError: string indices must be integers"

and I have no idea why.

The JSON I am trying to read in is as follows:

{
"rightArgument":{
"cell":"C18",
"value":9.5,
"type":"cell"
},
"leftArgument":{
"rightArgument":{
"cell":"C3",
"value":135,
"type":"cell"
},
"leftArgument":{
"rightArgument":{
"cell":"C4",
"value":125,
"type":"cell"
},
"leftArgument":{
"cell":"C5",
"value":106,
"type":"cell"
},
"type":"operation",
"operator":"*"
},
"type":"operation",
"operator":"+"
},
"type":"operation",
"operator":"+"
}

import json
import tkinter
from tkinter import *

data = ""
list = []

def readText():
    mtext=""
    mtext = strJson.get()
    mlabel2 = Label(myGui,text=mtext).place(x=180,y=200)
    data = mtext

def mhello():
    _getCurrentOperator(data)

def _getCurrentOperator(data):
    if data["type"] == "operation":

        _getCurrentOperator(data["rightArgument"])
        _getCurrentOperator(data["leftArgument"])
        list.append(data["operator"])
    elif data["type"] == "group":
        _getCurrentOperator(data["argument"])
    elif data["type"] == "function":
        list.append(data["name"]) # TODO do something with arguments
        for i in range(len(data["arguments"])):
            _getCurrentOperator(data["arguments"][i])
    else:
        if (data["value"]) == '':
            list.append(data["cell"])
        else:
            list.append(data["value"])

print(list)

myGui = Tk()
strJson = StringVar()

myGui.title("Simple Gui")
myGui.geometry("400x300")

label = Label(text = 'Welcome!').place(x=170,y=40)
btnStart = Button(myGui,text='Start',command=mhello).place(x=210,y=260)
btnRead = Button(myGui,text='Read text',command=readText).place(x=210,y=200)
txtEntry = Entry(myGui, textvariable=strJson).place(x=150,y=160)
btnOptions = Button(myGui, text = "Options").place(x=150,y=260)

myGui.mainloop()

Body:
sometimes you need to use json.loads again..
this worked for me..

jsonn_forSaleSummary_string = json.loads(forSaleSummary)  //still string
jsonn_forSaleSummary        = json.loads(jsonn_forSaleSummary_string)

finally!! json


问:
Value of stat structure contained structure lost
I'm trying to code the ls function from ground up. In order to do so, I created a linked list of structures containing the information of each file / structure.

Here is the structure :

```<code>typedef struct      s_ls
{
    char            *name;
    struct          stat stat;
    struct          s_ls *next;
}                       t_ls;
</code>```

I then created a linked list :

```<code>t_ls    *ft_store(char *foldername)
{
    t_ls    *stock = NULL;
    DIR *dir;
    struct dirent *dent;
    dir = opendir(foldername);

    if(dir != NULL)
    {
        while((dent = readdir(dir)) != NULL)
        {
            stock = ft_add_elem(dent->d_name, stock);
            stat(stock->name, &(stock->stat));
        }
    }
    return (stock);
}
</code>```

The ft_add_elem function mallocs a new structure, adds a new element in alphabtical order, and returns a pointer to the first element in the following manner :

```<code>t_ls    *ft_new_elem(char *name)
{
    t_ls    *tmp;
    if (!(tmp = malloc(sizeof(t_ls))))
        exit(1);
    tmp->name = ft_strdup(name);
    return (tmp);
}

t_ls    *ft_add_elem(char *name, t_ls *stock)
{
    t_ls *new;
    t_ls *check;

    new = ft_new_elem(name);
    if (!stock)
        return (new);
    check = stock;
    while (check && check->next && ft_strcmp(check->next->name, new->name) < 0)
        check = check->next;
    new->next = check->next;
    check->next = new;
    return (stock);
}
</code>```

My problem is that when I go through the elements to print them out when the -l option is triggered for instance all stat structures are empty, except for the first one. This is however not the case if I print them from the same function that fills them up (ft_store).

答:
The trouble is that ft_add_elem() returns the pointer to the first item in the list, not the item just added.  You're keeping the list in sorted order (via the ft_strcmp() function).  So, you keep running stat() on the first name in the list — which will be . unless you've some unusual files in your (current) directory.

Fixing that is a bit more intricate.  It's probably best to do the stat() operation in ft_add_elem().  Note, however, that you also have to worry about the path to the directory from which you're reading the entries.  If you're processing . (the current directory) only, then it'll work.  If you're processing other directories, you have to create the path to the file by prefixing the directory name to the file name.

It's also worth ensuring that the new element is fully initialized; it avoids accidentally undefined behaviour.

Here's some fixed code.  The functions with names starting err_ are available from Github (https://github.com/jleffler/soq/tree/master/src/libsoq) in stderr.c and stderr.h.  They're used to simplify error reporting.

```<code>#include "stderr.h"
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#define ft_strcmp(s, t) strcmp(s, t)
#define ft_strdup(s)    strdup(s)

typedef struct      s_ls
{
    char            *name;
    struct          stat stat;
    struct          s_ls *next;
}                       t_ls;

static t_ls *ft_new_elem(char *name)
{
    t_ls    *tmp;
    if (!(tmp = malloc(sizeof(t_ls))))
        err_error("Failed to allocate %zu bytes of memory\n", sizeof(*tmp));
    tmp->name = ft_strdup(name);
    tmp->next = 0;
    tmp->stat = (struct stat){ 0 };
    return(tmp);
}

static t_ls *ft_add_elem(char *name, const char *dirname, t_ls *stock)
{
    t_ls *new;
    t_ls *check;

    new = ft_new_elem(name);
    if (!stock)
        return(new);
    check = stock;
    while (check && check->next && ft_strcmp(check->next->name, new->name) < 0)
        check = check->next;
    new->next = check->next;
    check->next = new;
    char pathname[strlen(dirname) + strlen(name) + 2];
    sprintf(pathname, "%s/%s", dirname, name);
    if (stat(pathname, &new->stat) < 0)
        err_sysrem("Failed to stat '%s': ", pathname);
    return(stock);
}

static t_ls *ft_store(char *foldername)
{
    t_ls    *stock = NULL;
    DIR *dir;
    struct dirent *dent;
    dir = opendir(foldername);

    if (dir != NULL)
    {
        while ((dent = readdir(dir)) != NULL)
        {
            stock = ft_add_elem(dent->d_name, foldername, stock);
        }
    }
    return(stock);
}

int main(int argc, char **argv)
{
    err_setarg0(argv[0]);
    if (argc < 2)
    {
        argc = 2;
        argv = (char *[]){ ".", 0 };
    }
    for (int i = 1; i < argc; i++)
    {
        t_ls *list = ft_store(argv[i]);
        t_ls *node = list;
        while (node != 0)
        {
            printf("Name: %s (size %llu)\n", node->name, node->stat.st_size);
            node = node->next;
        }
    }
    return 0;
}
</code>```

The code uses a couple of compound literals, a feature of C99.  There are other ways to achieve the same effects.

Running the program (rd37) on a directory etc gave:

```<code>$ ./rd37 etc
Name: . (size 0)
Name: .. (size 2448)
Name: .gitignore (size 38)
Name: README.md (size 99)
Name: posix-opt-end.gif (size 65)
Name: posix-opt-start.gif (size 69)
Name: soq-head.mk (size 1618)
Name: soq-tail.mk (size 665)
Name: suppressions (size 16139)
Name: suppressions-macos-10.12.5 (size 4998)
$ ls -l etc
total 88
-rw-r--r--  1 jleffler  staff     99 Jul  9  2016 README.md
-rw-r--r--@ 1 jleffler  staff     65 Nov 10  2016 posix-opt-end.gif
-rw-r--r--@ 1 jleffler  staff     69 Nov 10  2016 posix-opt-start.gif
-rw-r--r--  1 jleffler  staff   1618 Jun 16 23:38 soq-head.mk
-rw-r--r--  1 jleffler  staff    665 Aug 16  2016 soq-tail.mk
-rw-r--r--  1 jleffler  staff  16139 Aug 20  2016 suppressions
-rw-r--r--  1 jleffler  staff   4998 May 21 15:40 suppressions-macos-10.12.5
$
</code>```

Body:
I'm trying to code the ls function from ground up. In order to do so, I created a linked list of structures containing the information of each file / structure.

Here is the structure :

typedef struct      s_ls
{
    char            *name;
    struct          stat stat;
    struct          s_ls *next;
}                       t_ls;

I then created a linked list :

t_ls    *ft_store(char *foldername)
{
    t_ls    *stock = NULL;
    DIR *dir;
    struct dirent *dent;
    dir = opendir(foldername);

    if(dir != NULL)
    {
        while((dent = readdir(dir)) != NULL)
        {
            stock = ft_add_elem(dent->d_name, stock);
            stat(stock->name, &(stock->stat));
        }
    }
    return (stock);
}

The ft_add_elem function mallocs a new structure, adds a new element in alphabtical order, and returns a pointer to the first element in the following manner :

t_ls    *ft_new_elem(char *name)
{
    t_ls    *tmp;
    if (!(tmp = malloc(sizeof(t_ls))))
        exit(1);
    tmp->name = ft_strdup(name);
    return (tmp);
}

t_ls    *ft_add_elem(char *name, t_ls *stock)
{
    t_ls *new;
    t_ls *check;

    new = ft_new_elem(name);
    if (!stock)
        return (new);
    check = stock;
    while (check && check->next && ft_strcmp(check->next->name, new->name) < 0)
        check = check->next;
    new->next = check->next;
    check->next = new;
    return (stock);
}

My problem is that when I go through the elements to print them out when the -l option is triggered for instance all stat structures are empty, except for the first one. This is however not the case if I print them from the same function that fills them up (ft_store).

Body:
The trouble is that ft_add_elem() returns the pointer to the first item in the list, not the item just added.  You're keeping the list in sorted order (via the ft_strcmp() function).  So, you keep running stat() on the first name in the list — which will be . unless you've some unusual files in your (current) directory.

Fixing that is a bit more intricate.  It's probably best to do the stat() operation in ft_add_elem().  Note, however, that you also have to worry about the path to the directory from which you're reading the entries.  If you're processing . (the current directory) only, then it'll work.  If you're processing other directories, you have to create the path to the file by prefixing the directory name to the file name.

It's also worth ensuring that the new element is fully initialized; it avoids accidentally undefined behaviour.

Here's some fixed code.  The functions with names starting err_ are available from Github (https://github.com/jleffler/soq/tree/master/src/libsoq) in stderr.c and stderr.h.  They're used to simplify error reporting.

#include "stderr.h"
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#define ft_strcmp(s, t) strcmp(s, t)
#define ft_strdup(s)    strdup(s)

typedef struct      s_ls
{
    char            *name;
    struct          stat stat;
    struct          s_ls *next;
}                       t_ls;

static t_ls *ft_new_elem(char *name)
{
    t_ls    *tmp;
    if (!(tmp = malloc(sizeof(t_ls))))
        err_error("Failed to allocate %zu bytes of memory\n", sizeof(*tmp));
    tmp->name = ft_strdup(name);
    tmp->next = 0;
    tmp->stat = (struct stat){ 0 };
    return(tmp);
}

static t_ls *ft_add_elem(char *name, const char *dirname, t_ls *stock)
{
    t_ls *new;
    t_ls *check;

    new = ft_new_elem(name);
    if (!stock)
        return(new);
    check = stock;
    while (check && check->next && ft_strcmp(check->next->name, new->name) < 0)
        check = check->next;
    new->next = check->next;
    check->next = new;
    char pathname[strlen(dirname) + strlen(name) + 2];
    sprintf(pathname, "%s/%s", dirname, name);
    if (stat(pathname, &new->stat) < 0)
        err_sysrem("Failed to stat '%s': ", pathname);
    return(stock);
}

static t_ls *ft_store(char *foldername)
{
    t_ls    *stock = NULL;
    DIR *dir;
    struct dirent *dent;
    dir = opendir(foldername);

    if (dir != NULL)
    {
        while ((dent = readdir(dir)) != NULL)
        {
            stock = ft_add_elem(dent->d_name, foldername, stock);
        }
    }
    return(stock);
}

int main(int argc, char **argv)
{
    err_setarg0(argv[0]);
    if (argc < 2)
    {
        argc = 2;
        argv = (char *[]){ ".", 0 };
    }
    for (int i = 1; i < argc; i++)
    {
        t_ls *list = ft_store(argv[i]);
        t_ls *node = list;
        while (node != 0)
        {
            printf("Name: %s (size %llu)\n", node->name, node->stat.st_size);
            node = node->next;
        }
    }
    return 0;
}

The code uses a couple of compound literals, a feature of C99.  There are other ways to achieve the same effects.

Running the program (rd37) on a directory etc gave:

$ ./rd37 etc
Name: . (size 0)
Name: .. (size 2448)
Name: .gitignore (size 38)
Name: README.md (size 99)
Name: posix-opt-end.gif (size 65)
Name: posix-opt-start.gif (size 69)
Name: soq-head.mk (size 1618)
Name: soq-tail.mk (size 665)
Name: suppressions (size 16139)
Name: suppressions-macos-10.12.5 (size 4998)
$ ls -l etc
total 88
-rw-r--r--  1 jleffler  staff     99 Jul  9  2016 README.md
-rw-r--r--@ 1 jleffler  staff     65 Nov 10  2016 posix-opt-end.gif
-rw-r--r--@ 1 jleffler  staff     69 Nov 10  2016 posix-opt-start.gif
-rw-r--r--  1 jleffler  staff   1618 Jun 16 23:38 soq-head.mk
-rw-r--r--  1 jleffler  staff    665 Aug 16  2016 soq-tail.mk
-rw-r--r--  1 jleffler  staff  16139 Aug 20  2016 suppressions
-rw-r--r--  1 jleffler  staff   4998 May 21 15:40 suppressions-macos-10.12.5
$


问:
Coldfusion Looping
I need to use cfloop to insert records.

There's a form a customer fills out. They add an item from a dropdown list, and then enter in a quantity in a text box. Normally, the quantity is only between 1 and 5.

I need to run a loop to insert the records one at a time with a unique Item ID for each with a quantity of 1.

For example, if they add Specific Item 5 with a quantity of 4, I need 4 records inserted into the table  with a qty of 1 each. What I really want more than the answer here is the thought process of how I'd come to that going forward without having to ask.

答:
That's... a weird way of recording things, but alright.

I am going to assume the form field's names are ITEM and QUANTITY. I am also assuming you are using either SQL or MySQL. The code should be nearly identical for either.

Here is what the code on your action page might look like:

```<code><cfloop from="1" to="#FORM.QUANTITY#" index="i">
<cfquery name="insertOrder" datasource="DSN">
INSERT INTO TABLENAME
(
ITEMCOLUMN,
QTYCOLUMN
)
VALUES
(
<cfqueryparam cfsqltype="cf_sql_varchar" value="#FORM.ITEM#">,
1
)
</cfquery>
</cfloop>
</code>```

I added a cfqueryparam tag to declare data types and help prevent SQL injection. I don't know what your data types are in actuality, but you should definitely look into using it for any query that takes stuff from the FORM or URL scope.

Title: Coldfusion Looping

Body:
That's... a weird way of recording things, but alright.

I am going to assume the form field's names are ITEM and QUANTITY. I am also assuming you are using either SQL or MySQL. The code should be nearly identical for either.

Here is what the code on your action page might look like:

<cfloop from="1" to="#FORM.QUANTITY#" index="i">
<cfquery name="insertOrder" datasource="DSN">
INSERT INTO TABLENAME
(
ITEMCOLUMN,
QTYCOLUMN
)
VALUES
(
<cfqueryparam cfsqltype="cf_sql_varchar" value="#FORM.ITEM#">,
1
)
</cfquery>
</cfloop>

I added a cfqueryparam tag to declare data types and help prevent SQL injection. I don't know what your data types are in actuality, but you should definitely look into using it for any query that takes stuff from the FORM or URL scope.


问:
Creating computed Columns, create a view?
I am working with raw adwords data which contains campaigns and marketing performance data.  I need to make calculations based on columns that fit a certain "WHERE" criteria.  As an example; If under the column "Ad Relevance" the row = "Below average" then a column should be returned as "Below Average Ad Relevance Impressions"  the calculation for this occurrence should be Impressions * 1.  I will also be needing to make other calculations that occur throughout every row regardless of at where criteria, as an example; Column "QS" * "Impressions".  I finally will need to concatenate a two columns together that will in turn be looped with another data set.

Does this appear to be possible without creating a view?  I have tried creating one while using "Where" queries however it seems to be limited with how much I can withdraw as it can be based on one and only one condition.

Current table

```<code>Campaign|Adgroup|Expected clickthrough rate|QS|Impressions|
--------+-------+--------------------------+--+-----------+
USA-EN  |watches|Average                   |3 |1000       |
DE-DE   |rings  |Below Average             |5 |1300       |
CH-DE   |belts  |Average                   |6 |1234       |
</code>```

Desired Results (these are the additional / computed columns but the goal is to include the columns at top within the new table as well)

```<code>Key                  |Impressions with average ctr    |Weighted QS       |
**(Campaign and      |(Impressions *1 where "Expected |(QS * Impressions |
adgroup concatenated)|clickthroughrate =average)      |                  |**
---------------------+--------------------------------+------------------+
USA-ENwatches        |1000                            |                  |
DE-DErings           |0                               |                  |
CH-DEbelts           |1234                            |                  |
</code>```

答:
For IF - THEN logic, use case statements.
For concatenation of strings use "||"

Here is an example based on your "Current Table" and "Desired Results":

```<code>Select (Campaign || '-' || Adgroup) AS Key
      ,CASE [Expected clickthrought rate]
            When 'Average' then (Impressions * 1)
            Else 0
        End AS [Impressions with average ctr]
     ,(QS * Impressions) AS [Weighted QS]
From MyTable
</code>```

Body:
I am working with raw adwords data which contains campaigns and marketing performance data.  I need to make calculations based on columns that fit a certain "WHERE" criteria.  As an example; If under the column "Ad Relevance" the row = "Below average" then a column should be returned as "Below Average Ad Relevance Impressions"  the calculation for this occurrence should be Impressions * 1.  I will also be needing to make other calculations that occur throughout every row regardless of at where criteria, as an example; Column "QS" * "Impressions".  I finally will need to concatenate a two columns together that will in turn be looped with another data set.

Does this appear to be possible without creating a view?  I have tried creating one while using "Where" queries however it seems to be limited with how much I can withdraw as it can be based on one and only one condition.

Current table

Campaign|Adgroup|Expected clickthrough rate|QS|Impressions|
--------+-------+--------------------------+--+-----------+
USA-EN  |watches|Average                   |3 |1000       |
DE-DE   |rings  |Below Average             |5 |1300       |
CH-DE   |belts  |Average                   |6 |1234       |

Desired Results (these are the additional / computed columns but the goal is to include the columns at top within the new table as well)

Key                  |Impressions with average ctr    |Weighted QS       |
**(Campaign and      |(Impressions *1 where "Expected |(QS * Impressions |
adgroup concatenated)|clickthroughrate =average)      |                  |**
---------------------+--------------------------------+------------------+
USA-ENwatches        |1000                            |                  |
DE-DErings           |0                               |                  |
CH-DEbelts           |1234                            |                  |

Body:
For IF - THEN logic, use case statements.
For concatenation of strings use "||"

Here is an example based on your "Current Table" and "Desired Results":

Select (Campaign || '-' || Adgroup) AS Key
      ,CASE [Expected clickthrought rate]
            When 'Average' then (Impressions * 1)
            Else 0
        End AS [Impressions with average ctr]
     ,(QS * Impressions) AS [Weighted QS]
From MyTable


问:
Search a word in a string of characters in Python
Hello guys I have two strings in Python:

```<code>str1 = "honey"
str2 = "eeehanoey"
</code>```

I want that the program returns me True if all the letters in str1 are in str2 and False otherwise, I have alredy tried with in but doesn't works, return me False.

Thank you

答:
This will do it:

```<code>def lettersmatch(str1, str2):

    #loop through each letter in str1
    for letter in str1:
        #if this letter is not in the second string, return false
        if not letter in str2:
            return False

    #if we get here, the letters match
    return True
</code>```

Note: This assumes that "aacd" and "acd" should be considered equal. (Basically, this assumes that duplicates are unimportant.)

Body:
Hello guys I have two strings in Python:

str1 = "honey"
str2 = "eeehanoey"

I want that the program returns me True if all the letters in str1 are in str2 and False otherwise, I have alredy tried with in but doesn't works, return me False.

Thank you

Body:
This will do it:

def lettersmatch(str1, str2):

    #loop through each letter in str1
    for letter in str1:
        #if this letter is not in the second string, return false
        if not letter in str2:
            return False

    #if we get here, the letters match
    return True

Note: This assumes that "aacd" and "acd" should be considered equal. (Basically, this assumes that duplicates are unimportant.)


问:
Aggregation of an annotation in GROUP BY in Django
UPDATE

Thanks to the posted answer, I found a much simpler way to formulate the problem. The original question can be seen in the revision history.

The problem

I am trying to translate an SQL query into Django, but am getting an error that I don't understand.

Here is the Django model I have:

```<code>class Title(models.Model):
  title_id = models.CharField(primary_key=True, max_length=12)
  title = models.CharField(max_length=80)
  publisher = models.CharField(max_length=100)
  price = models.DecimalField(decimal_places=2, blank=True, null=True)
</code>```

I have the following data:

```<code>publisher                    title_id      price  title
---------------------------  ----------  -------  -----------------------------------
New Age Books                PS2106         7     Life Without Fear
New Age Books                PS2091        10.95  Is Anger the Enemy?
New Age Books                BU2075         2.99  You Can Combat    Computer Stress!
New Age Books                TC7777        14.99  Sushi, Anyone?
Binnet & Hardley             MC3021         2.99  The Gourmet Microwave
Binnet & Hardley             MC2222        19.99  Silicon Valley   Gastronomic Treats
Algodata Infosystems         PC1035        22.95  But Is It User Friendly?
Algodata Infosystems         BU1032        19.99  The Busy Executive's   Database Guide
Algodata Infosystems         PC8888        20     Secrets of Silicon Valley
</code>```

Here is what I want to do: introduce an annotated field dbl_price which is twice the price, then group the resulting queryset by publisher, and for each publisher, compute the total of all dbl_price values for all titles published by that publisher.

The SQL query that does this is as follows:

```<code>SELECT SUM(dbl_price) AS total_dbl_price, publisher
FROM (
  SELECT price * 2 AS dbl_price, publisher
  FROM title
) AS A
GROUP BY publisher
</code>```

The desired output would be:

```<code>publisher                    tot_dbl_prices
---------------------------  --------------
Algodata Infosystems                 125.88
Binnet & Hardley                      45.96
New Age Books                         71.86
</code>```

Django query

The query would look like:

```<code>Title.objects
 .annotate(dbl_price=2*F('price'))
 .values('publisher')
 .annotate(tot_dbl_prices=Sum('dbl_price'))
</code>```

but gives an error:

```<code>KeyError: 'dbl_price'.
</code>```

which indicates that it can't find the field dbl_price in the queryset.

The reason for the error

Here is why this error happens: the documentation says

You should also note that average_rating has been explicitly included
       in the list of values to be returned. This is required because of the    ordering of the values() and annotate() clause.

If the values() clause precedes the annotate() clause, any annotations
       will be automatically added to the result set. However, if the
       values() clause is applied after the annotate() clause, you need to explicitly include the aggregate column.

So, the dbl_price could not be found in aggregation, because it was created by a prior annotate, but wasn't included in values().

However, I can't include it in values either, because I want to use values (followed by another annotate) as a grouping device, since

If the values() clause precedes the annotate(), the annotation will be computed using the grouping described by the values() clause.

which is the basis of how Django implements SQL GROUP BY. This means that I can't include dbl_price inside values(), because then the grouping will be based on unique combinations of both fields publisher and dbl_price, whereas I need to group by publisher only.

So, the following query, which only differs from the above in that I aggregate over model's price field rather than annotated dbl_price field, actually works:

```<code>Title.objects
 .annotate(dbl_price=2*F('price'))
 .values('publisher')
 .annotate(sum_of_prices=Count('price'))
</code>```

because the price field is in the model rather than being an annotated field, and so we don't need to include it in values to keep it in the queryset.

The question

So, here we have it: I need to include annotated property into values to keep it in the queryset, but I can't do that because values is also used for grouping (which will be wrong with an extra field). The problem essentially is due to the two very different ways that values is used in Django, depending on the context (whether or not values is followed by annotate) - which is (1) value extraction (SQL plain SELECT list) and (2) grouping + aggregation over the groups (SQL GROUP BY) - and in this case these two ways seem to conflict.

My question is: is there any way to solve this problem (without things like falling back to raw sql)?

Please note: the specific example in question can be solved by moving all annotate statements after values, which was noted by several answers. However, I am more interested in solutions (or discussion) which would keep the annotate statement(s) before values(), for three reasons: 1. There are also more complex examples, where the suggested workaround would not work. 2. I can imagine situations, where the annotated queryset has been passed to another function, which actually does GROUP BY, so that the only thing we know is the set of names of annotated fields, and their types. 3. The situation seems to be pretty straightforward, and it would surprise me if this clash of two distinct uses of values() has not been noticed and discussed before.

答:
Update: Since Django 2.1, everything works out of the box. No workarounds needed and the produced query is correct.

This is maybe a bit too late, but I have found the solution (tested with Django 1.11.1).

The problem is, call to .values('publisher'), which is required to provide grouping, removes all annotations, that are not included in .values() fields param.

And we can't include dbl_price to fields param, because it will add another GROUP BY statement.

The solution in to make all aggregation, which requires annotated fields firstly, then call .values() and include that aggregations to fields param(this won't add GROUP BY, because they are aggregations).
Then we should call .annotate() with ANY expression - this will make django add GROUP BY statement to SQL query using the only non-aggregation field in query - publisher.

```<code>Title.objects
    .annotate(dbl_price=2*F('price'))
    .annotate(sum_of_prices=Sum('dbl_price'))
    .values('publisher', 'sum_of_prices')
    .annotate(titles_count=Count('id'))
</code>```

The only minus with this approach - if you don't need any other aggregations except that one with annotated field - you would have to include some anyway. Without last call to .annotate() (and it should include at least one expression!), Django will not add GROUP BY to SQL query. One approach to deal with this is just to create a copy of your field:

```<code>Title.objects
    .annotate(dbl_price=2*F('price'))
    .annotate(_sum_of_prices=Sum('dbl_price')) # note the underscore!
    .values('publisher', '_sum_of_prices')
    .annotate(sum_of_prices=F('_sum_of_prices')
</code>```

Also, mention, that you should be careful with QuerySet ordering. You'd better call .order_by() either without parameters to clear ordering or with you GROUP BY field. If the resulting query will contain ordering by any other field, the grouping will be wrong.
https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#interaction-with-default-ordering-or-order-by

Also, you might want to remove that fake annotation from your output, so call .values() again.
So, final code looks like:

```<code>Title.objects
    .annotate(dbl_price=2*F('price'))
    .annotate(_sum_of_prices=Sum('dbl_price'))
    .values('publisher', '_sum_of_prices')
    .annotate(sum_of_prices=F('_sum_of_prices'))
    .values('publisher', 'sum_of_prices')
    .order_by('publisher')
</code>```

Body:
UPDATE

Thanks to the posted answer, I found a much simpler way to formulate the problem. The original question can be seen in the revision history.

The problem

I am trying to translate an SQL query into Django, but am getting an error that I don't understand.

Here is the Django model I have:

class Title(models.Model):
  title_id = models.CharField(primary_key=True, max_length=12)
  title = models.CharField(max_length=80)
  publisher = models.CharField(max_length=100)
  price = models.DecimalField(decimal_places=2, blank=True, null=True)

I have the following data:

publisher                    title_id      price  title
---------------------------  ----------  -------  -----------------------------------
New Age Books                PS2106         7     Life Without Fear
New Age Books                PS2091        10.95  Is Anger the Enemy?
New Age Books                BU2075         2.99  You Can Combat    Computer Stress!
New Age Books                TC7777        14.99  Sushi, Anyone?
Binnet & Hardley             MC3021         2.99  The Gourmet Microwave
Binnet & Hardley             MC2222        19.99  Silicon Valley   Gastronomic Treats
Algodata Infosystems         PC1035        22.95  But Is It User Friendly?
Algodata Infosystems         BU1032        19.99  The Busy Executive's   Database Guide
Algodata Infosystems         PC8888        20     Secrets of Silicon Valley

Here is what I want to do: introduce an annotated field dbl_price which is twice the price, then group the resulting queryset by publisher, and for each publisher, compute the total of all dbl_price values for all titles published by that publisher.

The SQL query that does this is as follows:

SELECT SUM(dbl_price) AS total_dbl_price, publisher
FROM (
  SELECT price * 2 AS dbl_price, publisher
  FROM title
) AS A
GROUP BY publisher

The desired output would be:

publisher                    tot_dbl_prices
---------------------------  --------------
Algodata Infosystems                 125.88
Binnet & Hardley                      45.96
New Age Books                         71.86

Django query

The query would look like:

Title.objects
 .annotate(dbl_price=2*F('price'))
 .values('publisher')
 .annotate(tot_dbl_prices=Sum('dbl_price'))

but gives an error:

KeyError: 'dbl_price'.

which indicates that it can't find the field dbl_price in the queryset.

The reason for the error

Here is why this error happens: the documentation says

You should also note that average_rating has been explicitly included
       in the list of values to be returned. This is required because of the    ordering of the values() and annotate() clause.

If the values() clause precedes the annotate() clause, any annotations
       will be automatically added to the result set. However, if the
       values() clause is applied after the annotate() clause, you need to explicitly include the aggregate column.

So, the dbl_price could not be found in aggregation, because it was created by a prior annotate, but wasn't included in values().

However, I can't include it in values either, because I want to use values (followed by another annotate) as a grouping device, since

If the values() clause precedes the annotate(), the annotation will be computed using the grouping described by the values() clause.

which is the basis of how Django implements SQL GROUP BY. This means that I can't include dbl_price inside values(), because then the grouping will be based on unique combinations of both fields publisher and dbl_price, whereas I need to group by publisher only.

So, the following query, which only differs from the above in that I aggregate over model's price field rather than annotated dbl_price field, actually works:

Title.objects
 .annotate(dbl_price=2*F('price'))
 .values('publisher')
 .annotate(sum_of_prices=Count('price'))

because the price field is in the model rather than being an annotated field, and so we don't need to include it in values to keep it in the queryset.

The question

So, here we have it: I need to include annotated property into values to keep it in the queryset, but I can't do that because values is also used for grouping (which will be wrong with an extra field). The problem essentially is due to the two very different ways that values is used in Django, depending on the context (whether or not values is followed by annotate) - which is (1) value extraction (SQL plain SELECT list) and (2) grouping + aggregation over the groups (SQL GROUP BY) - and in this case these two ways seem to conflict.

My question is: is there any way to solve this problem (without things like falling back to raw sql)?

Please note: the specific example in question can be solved by moving all annotate statements after values, which was noted by several answers. However, I am more interested in solutions (or discussion) which would keep the annotate statement(s) before values(), for three reasons: 1. There are also more complex examples, where the suggested workaround would not work. 2. I can imagine situations, where the annotated queryset has been passed to another function, which actually does GROUP BY, so that the only thing we know is the set of names of annotated fields, and their types. 3. The situation seems to be pretty straightforward, and it would surprise me if this clash of two distinct uses of values() has not been noticed and discussed before.

Body:
Update: Since Django 2.1, everything works out of the box. No workarounds needed and the produced query is correct.

This is maybe a bit too late, but I have found the solution (tested with Django 1.11.1).

The problem is, call to .values('publisher'), which is required to provide grouping, removes all annotations, that are not included in .values() fields param.

And we can't include dbl_price to fields param, because it will add another GROUP BY statement.

The solution in to make all aggregation, which requires annotated fields firstly, then call .values() and include that aggregations to fields param(this won't add GROUP BY, because they are aggregations).
Then we should call .annotate() with ANY expression - this will make django add GROUP BY statement to SQL query using the only non-aggregation field in query - publisher.

Title.objects
    .annotate(dbl_price=2*F('price'))
    .annotate(sum_of_prices=Sum('dbl_price'))
    .values('publisher', 'sum_of_prices')
    .annotate(titles_count=Count('id'))

The only minus with this approach - if you don't need any other aggregations except that one with annotated field - you would have to include some anyway. Without last call to .annotate() (and it should include at least one expression!), Django will not add GROUP BY to SQL query. One approach to deal with this is just to create a copy of your field:

Title.objects
    .annotate(dbl_price=2*F('price'))
    .annotate(_sum_of_prices=Sum('dbl_price')) # note the underscore!
    .values('publisher', '_sum_of_prices')
    .annotate(sum_of_prices=F('_sum_of_prices')

Also, mention, that you should be careful with QuerySet ordering. You'd better call .order_by() either without parameters to clear ordering or with you GROUP BY field. If the resulting query will contain ordering by any other field, the grouping will be wrong.
https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#interaction-with-default-ordering-or-order-by

Also, you might want to remove that fake annotation from your output, so call .values() again.
So, final code looks like:

Title.objects
    .annotate(dbl_price=2*F('price'))
    .annotate(_sum_of_prices=Sum('dbl_price'))
    .values('publisher', '_sum_of_prices')
    .annotate(sum_of_prices=F('_sum_of_prices'))
    .values('publisher', 'sum_of_prices')
    .order_by('publisher')

ContentLicense: CC BY-SA 4.0


问:
Python pandas: pad rows with missing/skipped date
I have the following data frame:

```<code> date        my_count
--------------------------
2017-01-01         6
2017-01-04         5
2017-01-05         3
2017-01-08         8
</code>```

I would like to pad the skipped date with my_count = 0, so the padded data frame will look like:

```<code> date        my_count
--------------------------
2017-01-01         6
2017-01-02         0
2017-01-03         0
2017-01-04         5
2017-01-05         3
2017-01-06         0
2017-01-07         0
2017-01-08         8
</code>```

Except checking the data frame line by line, is there a more elegant way to do this? Thanks!

Body:
I have the following data frame:

 date        my_count
--------------------------
2017-01-01         6
2017-01-04         5
2017-01-05         3
2017-01-08         8

I would like to pad the skipped date with my_count = 0, so the padded data frame will look like:

 date        my_count
--------------------------
2017-01-01         6
2017-01-02         0
2017-01-03         0
2017-01-04         5
2017-01-05         3
2017-01-06         0
2017-01-07         0
2017-01-08         8

Except checking the data frame line by line, is there a more elegant way to do this? Thanks!

Body:
1st option resample,

df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')

print(df.resample('D').sum().fillna(0).reset_index())

        date  my_count
0 2017-01-01       6.0
1 2017-01-02       0.0
2 2017-01-03       0.0
3 2017-01-04       5.0
4 2017-01-05       3.0
5 2017-01-06       0.0
6 2017-01-07       0.0
7 2017-01-08       8.0

2nd option reindex by date_range,

df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')

print(df.reindex(pd.date_range('2017-01-01', '2017-01-08')).fillna(0))

            my_count
2017-01-01       6.0
2017-01-02       0.0
2017-01-03       0.0
2017-01-04       5.0
2017-01-05       3.0
2017-01-06       0.0
2017-01-07       0.0
2017-01-08       8.0


答:
Here's an approach with sets, if duplicate counts don't matter.

```<code>>>> s1 = set(str1)
>>> s2 = set(str2)
>>> s1.intersection(s2) == s1
True
</code>```

Alternatively (slower)...

```<code>>>> s1 = ''.join(sorted(str1))
>>> s2 = ''.join(sorted(str2))
>>> s1 in s2
True
</code>```

Update: Adding a method to handle duplicates too.

```<code>from collections import Counter

def match(str1, str2):
    c1 = Counter(str1)
    c2 = Counter(str2)

    for c in c1:
        if c not in c2 or c1[c] > c2[c]:
            return False

    return True
</code>```

Output:

```<code>>>> match("honey", "eeehanoey")
True
>>> match("rapture", "aaepprut")
False
</code>```

Title: Search a word in a string of characters in Python

Body:
Here's an approach with sets, if duplicate counts don't matter.

>>> s1 = set(str1)
>>> s2 = set(str2)
>>> s1.intersection(s2) == s1
True

Alternatively (slower)...

>>> s1 = ''.join(sorted(str1))
>>> s2 = ''.join(sorted(str2))
>>> s1 in s2
True

Update: Adding a method to handle duplicates too.

from collections import Counter

def match(str1, str2):
    c1 = Counter(str1)
    c2 = Counter(str2)

    for c in c1:
        if c not in c2 or c1[c] > c2[c]:
            return False

    return True

Output:

>>> match("honey", "eeehanoey")
True
>>> match("rapture", "aaepprut")
False


问:
Explanation of Azul's "pauseless" garbage collector
I've just read this:

http://www.artima.com/lejava/articles/azul_pauseless_gc.html

Although I've some experience with compilers, I've done nothing related with garbage collection; is a big black box to me.

I've struggled to understand the issues mentioned by the article. I understand the problem (there's a pause when executing most garbage collectors), and I understand that they claim that their implementation doesn't have that problem. But I don't understand why/how the problem happens in the first place (that much seems to be assumed to be understood on the original text), and in consequence I don't get why their solution might work.

Can someone explain to me:

why garbage collectors have that pause in general

why Azul's gc doesn't have that problem?

I tend to understand this kind of things better when explained graphically - probably a small memory schema done with the code editor would suffice.

Thanks!

答:
They talk about the pause that inevitably occurs when compacting the heap. You see, when you allocate and deallocate lots of objects of different sizes as you go, you fragment the heap (much like you fragment your harddrive). When fragmentation becomes too extreme, you have to clean up/defragment/compact the heap by reserving a huge chunk of memory, moving all objects there (without any fragmentation) and use their former locations as a fresh chunk of memory without any objects in it, i.e. without fragmentation.

When you do that, you invalidate all references to all objects you moved around. To prevent this, you must prevent that a reference that refers to a pre-compaction object location is used. The by far easiest way to do so is to pause the whole application, move the objects around and then go and update all references. Of course this can incur a significant overhead.

So the solution Azul proposes goes like this: They establish a "read barrier" that allows the GC to intercept dereferencing, and this way they can lazily update the references that are actually used.


问:
VB.NET Update existing XML with new section
I am working in a vb.net project, I would like to update an existing XML with a new section,

```<code><BookUpdateable Action="Renew">
    <BookOption>Book</BookOption>
    <BookMaster Action="None">
        <Key>
          <MasterReference>7678812382</MasterReference>
        </Key>
        <Assured Action="Update" xsi:type="OrgDataUpdateable">
          <Key>
            <CaptionCode>BOOKINTRO</CaptionCode>
            <PrevTransaction>0</PrevTransaction>
          </Key>
          <Addresses>
            <IsDeleted>true</IsDeleted>
          </Addresses>
        </Assured>
        <Units>
          <IsDeleted>true</IsDeleted>
        </Units>
        <Sections>
          <SectionDataUpdateable Action="Update" SectionTypeCode="NEW" SubSectionTypeCode="ONE">
            <Key>
              <SectionSequence>10</SectionSequence>
            </Key>
            <IsDeleted>true</IsDeleted>
          </SectionDataUpdateable>
  /*************************************************
  NEW  SECTION TO BE ADDED HERE
  *************************************************/
        </Sections>
        <BookDataExts>
          <MasterStatusCode>BOOKEXTN</MasterStatusCode>
          <EffectiveDate>2017-07-28</EffectiveDate>
        </BookDataExts>
    </BookMaster>
    <ReturnFields>false</ReturnFields>
</BookUpdateable>
</code>```

I have tried like this, but not working,

```<code>nameCodeSections = xDoc.SelectSingleNode("/r:BookUpdateable[1]/r:BookMaster", xNsMgr)
Dim childNode As XmlNode = xDoc.CreateNode(XmlNodeType.Element, "Sections", "")
Dim newAttribute As XmlAttribute = xDoc.CreateAttribute("SectionDataUpdateable", Str, "")
childNode.Attributes.Append(newAttribute)
nameCodeSections.AppendChild(childNode)
</code>```

I need to insert another section under sections element like this

```<code><SectionDataUpdateable Action="Update" SectionTypeCode="OLD"     SubSectionTypeCode="TWO">
<Key>
<SectionSequence>05</SectionSequence>
</Key>
<IsDeleted>true</IsDeleted>
</SectionDataUpdateable>
</code>```

答:
Consider XSLT, the special-purpose language designed to transform XML files such as your update section needs. Like most general-purpose languages including Java, Python, C#, PHP, VB.Net can run XSLT 1.0 scripts with various libraries. Here, no looping, parsing, or conditional logic is needed.

I have been known to advocate XSLT across several programming threads. So, while I know nothing of VB.Net, I do include code below from provided MSDN source. Please adjust as needed.

XSLT (save as .xsl file which is a well-formed .xml file and can be loaded from file or string)

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <!-- Identity Transform -->
    <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
    </xsl:template>

    <!-- Add New SectiondataUdpateable -->
    <xsl:template match="Sections">
     <xsl:copy>
       <xsl:copy-of select="*"/>
       <SectionDataUpdateable Action="Update" SectionTypeCode="OLD" SubSectionTypeCode="TWO">
       <Key>
         <SectionSequence>05</SectionSequence>
       </Key>
       <IsDeleted>true</IsDeleted>
       </SectionDataUpdateable>
     </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

VB.NET (see MSDN implementation)

'Create the XslTransform object.
Dim xslt as XslTransform = new XslTransform()

'Load the stylesheet.
xslt.Load("XSLTScript.xsl")

'Transform the file.
xslt.Transform("Input.xml", "Output.xml")
```

<p><strong>XML</strong> Output <em>(xmlns:xsi="www.example.com" declaration added in input)</em></p>

```<BookUpdateable xmlns:xsi="www.example.com" Action="Renew">
  <BookOption>Book</BookOption>
  <BookMaster Action="None">
    <Key>
      <MasterReference>7678812382</MasterReference>
    </Key>
    <Assured Action="Update" xsi:type="OrgDataUpdateable">
      <Key>
        <CaptionCode>BOOKINTRO</CaptionCode>
        <PrevTransaction>0</PrevTransaction>
      </Key>
      <Addresses>
        <IsDeleted>true</IsDeleted>
      </Addresses>
    </Assured>
    <Units>
      <IsDeleted>true</IsDeleted>
    </Units>
    <Sections>
      <SectionDataUpdateable Action="Update" SectionTypeCode="NEW" SubSectionTypeCode="ONE">
        <Key>
          <SectionSequence>10</SectionSequence>
        </Key>
        <IsDeleted>true</IsDeleted>
      </SectionDataUpdateable>
      <SectionDataUpdateable Action="Update" SectionTypeCode="OLD" SubSectionTypeCode="TWO">
        <Key>
          <SectionSequence>05</SectionSequence>
        </Key>
        <IsDeleted>true</IsDeleted>
      </SectionDataUpdateable>
    </Sections>
    <BookDataExts>
      <MasterStatusCode>BOOKEXTN</MasterStatusCode>
      <EffectiveDate>2017-07-28</EffectiveDate>
    </BookDataExts>
  </BookMaster>
  <ReturnFields>false</ReturnFields>
</BookUpdateable>
```

Body:
I am working in a vb.net project, I would like to update an existing XML with a new section,

<BookUpdateable Action="Renew">
    <BookOption>Book</BookOption>
    <BookMaster Action="None">
        <Key>
          <MasterReference>7678812382</MasterReference>
        </Key>
        <Assured Action="Update" xsi:type="OrgDataUpdateable">
          <Key>
            <CaptionCode>BOOKINTRO</CaptionCode>
            <PrevTransaction>0</PrevTransaction>
          </Key>
          <Addresses>
            <IsDeleted>true</IsDeleted>
          </Addresses>
        </Assured>
        <Units>
          <IsDeleted>true</IsDeleted>
        </Units>
        <Sections>
          <SectionDataUpdateable Action="Update" SectionTypeCode="NEW" SubSectionTypeCode="ONE">
            <Key>
              <SectionSequence>10</SectionSequence>
            </Key>
            <IsDeleted>true</IsDeleted>
          </SectionDataUpdateable>
  /*************************************************
  NEW  SECTION TO BE ADDED HERE
  *************************************************/
        </Sections>
        <BookDataExts>
          <MasterStatusCode>BOOKEXTN</MasterStatusCode>
          <EffectiveDate>2017-07-28</EffectiveDate>
        </BookDataExts>
    </BookMaster>
    <ReturnFields>false</ReturnFields>
</BookUpdateable>

I have tried like this, but not working,

nameCodeSections = xDoc.SelectSingleNode("/r:BookUpdateable[1]/r:BookMaster", xNsMgr)
Dim childNode As XmlNode = xDoc.CreateNode(XmlNodeType.Element, "Sections", "")
Dim newAttribute As XmlAttribute = xDoc.CreateAttribute("SectionDataUpdateable", Str, "")
childNode.Attributes.Append(newAttribute)
nameCodeSections.AppendChild(childNode)

I need to insert another section under sections element like this

<SectionDataUpdateable Action="Update" SectionTypeCode="OLD"     SubSectionTypeCode="TWO">
<Key>
<SectionSequence>05</SectionSequence>
</Key>
<IsDeleted>true</IsDeleted>
</SectionDataUpdateable>

Body:
Consider XSLT, the special-purpose language designed to transform XML files such as your update section needs. Like most general-purpose languages including Java, Python, C#, PHP, VB.Net can run XSLT 1.0 scripts with various libraries. Here, no looping, parsing, or conditional logic is needed.

I have been known to advocate XSLT across several programming threads. So, while I know nothing of VB.Net, I do include code below from provided MSDN source. Please adjust as needed.

XSLT (save as .xsl file which is a well-formed .xml file and can be loaded from file or string)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <!-- Identity Transform -->
    <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
    </xsl:template>

    <!-- Add New SectiondataUdpateable -->
    <xsl:template match="Sections">
     <xsl:copy>
       <xsl:copy-of select="*"/>
       <SectionDataUpdateable Action="Update" SectionTypeCode="OLD" SubSectionTypeCode="TWO">
       <Key>
         <SectionSequence>05</SectionSequence>
       </Key>
       <IsDeleted>true</IsDeleted>
       </SectionDataUpdateable>
     </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

VB.NET (see MSDN implementation)

'Create the XslTransform object.
Dim xslt as XslTransform = new XslTransform()

'Load the stylesheet.
xslt.Load("XSLTScript.xsl")

'Transform the file.
xslt.Transform("Input.xml", "Output.xml")

XML Output (xmlns:xsi="www.example.com" declaration added in input)

<BookUpdateable xmlns:xsi="www.example.com" Action="Renew">
  <BookOption>Book</BookOption>
  <BookMaster Action="None">
    <Key>
      <MasterReference>7678812382</MasterReference>
    </Key>
    <Assured Action="Update" xsi:type="OrgDataUpdateable">
      <Key>
        <CaptionCode>BOOKINTRO</CaptionCode>
        <PrevTransaction>0</PrevTransaction>
      </Key>
      <Addresses>
        <IsDeleted>true</IsDeleted>
      </Addresses>
    </Assured>
    <Units>
      <IsDeleted>true</IsDeleted>
    </Units>
    <Sections>
      <SectionDataUpdateable Action="Update" SectionTypeCode="NEW" SubSectionTypeCode="ONE">
        <Key>
          <SectionSequence>10</SectionSequence>
        </Key>
        <IsDeleted>true</IsDeleted>
      </SectionDataUpdateable>
      <SectionDataUpdateable Action="Update" SectionTypeCode="OLD" SubSectionTypeCode="TWO">
        <Key>
          <SectionSequence>05</SectionSequence>
        </Key>
        <IsDeleted>true</IsDeleted>
      </SectionDataUpdateable>
    </Sections>
    <BookDataExts>
      <MasterStatusCode>BOOKEXTN</MasterStatusCode>
      <EffectiveDate>2017-07-28</EffectiveDate>
    </BookDataExts>
  </BookMaster>
  <ReturnFields>false</ReturnFields>
</BookUpdateable>