问:
Getting amount of active trips via postgresql loop
I am searching for a way to get the amount of active trips in a GTFS feed for each minute of a day through a postgresql query.

For every trip I have the start and endtimes (in seconds) in a denormalized table. It looks something like this:

The query to give me trips that are active for a given timeframe (e.g. here 43000 to 43600 seconds) looks like this:

SELECT
COUNT(trips.trip_id)
FROM denormalized_trips AS trips

LEFT JOIN gtfs_calendar_dates AS calendar_dates
ON calendar_dates.service_id = trips.service_id
AND calendar_dates.agency_key = trips.agency_key
AND date = '2017-07-03'
AND exception_type = 1

INNER JOIN gtfs_calendar AS calendar
  ON trips.service_id = calendar.service_id
  AND calendar.agency_key = trips.agency_key
  AND calendar.wednesday = 1

WHERE (
  trip_start_time BETWEEN 46800 AND 47100
  AND '2017-07-03' BETWEEN calendar.start_date AND calendar.end_date
)
AND NOT EXISTS (
  SELECT 0
  FROM gtfs_calendar_dates AS date_exceptions
  WHERE date = '2017-07-03'
  AND date_exceptions.agency_key = trips.agency_key
  AND date_exceptions.service_id = calendar.service_id
  AND exception_type = 2
);
```

<p>This will result in 12 trips that will start between 13:00pm and 13:05pm.</p>

<p>Now I want to do that for the whole day. I want to get the amount of trips that get active in an interval of e.g. 1 minute or maybe more like 5 minutes.
I tried it with a loop but this seems to just give me 1 result back.
Here is what I came up with for now:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION get_active_trips(n int)
RETURNS INTEGER AS
$BODY$
DECLARE
 count INTEGER;
BEGIN
  FOR counter IN 43130..50000 BY 60 LOOP
    SELECT
    COUNT(trips.trip_id)
    INTO count
    FROM denormalized_trips AS trips

    LEFT JOIN gtfs_calendar_dates AS calendar_dates
    ON calendar_dates.service_id = trips.service_id
    AND calendar_dates.agency_key = trips.agency_key
    AND date = '2017-07-03'
    AND exception_type = 1

    INNER JOIN gtfs_calendar AS calendar
      ON trips.service_id = calendar.service_id
      AND calendar.agency_key = trips.agency_key
      AND calendar.wednesday = 1

    WHERE (
      trip_start_time BETWEEN counter AND counter + 60
      AND '2017-07-03' BETWEEN calendar.start_date AND calendar.end_date
    )
    AND NOT EXISTS (
      SELECT 0
      FROM gtfs_calendar_dates AS date_exceptions
      WHERE date = '2017-07-03'
      AND date_exceptions.agency_key = trips.agency_key
      AND date_exceptions.service_id = calendar.service_id
      AND exception_type = 2
    );
  END LOOP;
  RETURN count;
END;
$BODY$ LANGUAGE plpgsql STABLE;
</code>```

The result of calling SELECT get_active_trips(1);

Now I would like to get something like a table or an array of results back instead of just 1 entry. How would I do that?

Any help is highly appreciated.

答:
There are two syntaxes to create function returning set of values: returns setof <type> and returns table(<columns definition>). Documentation.

There are also several ways to return those values from the plpgsql function: return next or return query. Documentation.

So if you want just get the series of integers you could to rewrite your function in that way:

```<code>CREATE OR REPLACE FUNCTION get_active_trips(n int)
RETURNS SETOF INTEGER AS
$BODY$
DECLARE
 count INTEGER;
BEGIN
  FOR counter IN 43130..50000 BY 60 LOOP
    SELECT
    COUNT(trips.trip_id)
    INTO count
    FROM denormalized_trips AS trips
    <rest of query here>
    ;
    RETURN NEXT count;
  END LOOP;
  RETURN;
END;
$BODY$ LANGUAGE plpgsql STABLE;
</code>```

or, using RETURN QUERY:

```<code>CREATE OR REPLACE FUNCTION get_active_trips(n int)
RETURNS SETOF INTEGER AS
$BODY$
BEGIN
  FOR counter IN 43130..50000 BY 60 LOOP
    RETURN QUERY
      SELECT
      COUNT(trips.trip_id)
      FROM denormalized_trips AS trips
      <rest of query here>
      ;
  END LOOP;
  RETURN;
END;
$BODY$ LANGUAGE plpgsql STABLE;
</code>```

In case if you want to return more then one column:

```<code>CREATE OR REPLACE FUNCTION get_active_trips(n int)
RETURNS TABLE (counter_value int, active_trips_count int) AS
$BODY$
BEGIN
  FOR counter IN 43130..50000 BY 60 LOOP
    SELECT
    COUNT(trips.trip_id)
    INTO active_trips_count
    FROM denormalized_trips AS trips
    <rest of query here>
    ;
    counter_value := counter;
    RETURN NEXT; -- There is no parameters, current values of counter_value and active_trips_count will be returned
  END LOOP;
  RETURN;
END;
$BODY$ LANGUAGE plpgsql STABLE;
</code>```

or, using RETURN QUERY:

```<code>CREATE OR REPLACE FUNCTION get_active_trips(n int)
RETURNS TABLE (counter_value int, active_trips_count int) AS
$BODY$
BEGIN
  FOR counter IN 43130..50000 BY 60 LOOP
    RETURN QUERY
      SELECT
        counter,
        COUNT(trips.trip_id)
      FROM denormalized_trips AS trips
      <rest of query here>
      ;
  END LOOP;
  RETURN;
END;
$BODY$ LANGUAGE plpgsql STABLE;
</code>```

Finally there is alternative declaration for returns table:

```<code>CREATE OR REPLACE FUNCTION get_active_trips(
  n int,
  out counter_value int,
  out active_trips_count int)
RETURNS SETOF RECORD AS
</code>```

Update

But(!) I feeling that it is possible to simplify your task using single query, without loop.

Consider the following query (i'v used your simplified query from sqlfiddle):

```<code>select
  counter,
  count(trips.trip_id)
from
  generate_series(43130, 50000, 60) as counter left join
    denormalized_trips as trips on (trip_start_time between counter and counter + 60)
group by counter
order by counter;
</code>```

Body:
I am searching for a way to get the amount of active trips in a GTFS feed for each minute of a day through a postgresql query.

For every trip I have the start and endtimes (in seconds) in a denormalized table. It looks something like this:

The query to give me trips that are active for a given timeframe (e.g. here 43000 to 43600 seconds) looks like this:

SELECT
COUNT(trips.trip_id)
FROM denormalized_trips AS trips

LEFT JOIN gtfs_calendar_dates AS calendar_dates
ON calendar_dates.service_id = trips.service_id
AND calendar_dates.agency_key = trips.agency_key
AND date = '2017-07-03'
AND exception_type = 1

INNER JOIN gtfs_calendar AS calendar
  ON trips.service_id = calendar.service_id
  AND calendar.agency_key = trips.agency_key
  AND calendar.wednesday = 1

WHERE (
  trip_start_time BETWEEN 46800 AND 47100
  AND '2017-07-03' BETWEEN calendar.start_date AND calendar.end_date
)
AND NOT EXISTS (
  SELECT 0
  FROM gtfs_calendar_dates AS date_exceptions
  WHERE date = '2017-07-03'
  AND date_exceptions.agency_key = trips.agency_key
  AND date_exceptions.service_id = calendar.service_id
  AND exception_type = 2
);

This will result in 12 trips that will start between 13:00pm and 13:05pm.

Now I want to do that for the whole day. I want to get the amount of trips that get active in an interval of e.g. 1 minute or maybe more like 5 minutes.
I tried it with a loop but this seems to just give me 1 result back.
Here is what I came up with for now:

CREATE OR REPLACE FUNCTION get_active_trips(n int)
RETURNS INTEGER AS
$BODY$
DECLARE
 count INTEGER;
BEGIN
  FOR counter IN 43130..50000 BY 60 LOOP
    SELECT
    COUNT(trips.trip_id)
    INTO count
    FROM denormalized_trips AS trips

    LEFT JOIN gtfs_calendar_dates AS calendar_dates
    ON calendar_dates.service_id = trips.service_id
    AND calendar_dates.agency_key = trips.agency_key
    AND date = '2017-07-03'
    AND exception_type = 1

    INNER JOIN gtfs_calendar AS calendar
      ON trips.service_id = calendar.service_id
      AND calendar.agency_key = trips.agency_key
      AND calendar.wednesday = 1

    WHERE (
      trip_start_time BETWEEN counter AND counter + 60
      AND '2017-07-03' BETWEEN calendar.start_date AND calendar.end_date
    )
    AND NOT EXISTS (
      SELECT 0
      FROM gtfs_calendar_dates AS date_exceptions
      WHERE date = '2017-07-03'
      AND date_exceptions.agency_key = trips.agency_key
      AND date_exceptions.service_id = calendar.service_id
      AND exception_type = 2
    );
  END LOOP;
  RETURN count;
END;
$BODY$ LANGUAGE plpgsql STABLE;

The result of calling SELECT get_active_trips(1);

Now I would like to get something like a table or an array of results back instead of just 1 entry. How would I do that?

Any help is highly appreciated.

Body:
There are two syntaxes to create function returning set of values: returns setof <type> and returns table(<columns definition>). Documentation.

There are also several ways to return those values from the plpgsql function: return next or return query. Documentation.

So if you want just get the series of integers you could to rewrite your function in that way:

CREATE OR REPLACE FUNCTION get_active_trips(n int)
RETURNS SETOF INTEGER AS
$BODY$
DECLARE
 count INTEGER;
BEGIN
  FOR counter IN 43130..50000 BY 60 LOOP
    SELECT
    COUNT(trips.trip_id)
    INTO count
    FROM denormalized_trips AS trips
    <rest of query here>
    ;
    RETURN NEXT count;
  END LOOP;
  RETURN;
END;
$BODY$ LANGUAGE plpgsql STABLE;

or, using RETURN QUERY:

CREATE OR REPLACE FUNCTION get_active_trips(n int)
RETURNS SETOF INTEGER AS
$BODY$
BEGIN
  FOR counter IN 43130..50000 BY 60 LOOP
    RETURN QUERY
      SELECT
      COUNT(trips.trip_id)
      FROM denormalized_trips AS trips
      <rest of query here>
      ;
  END LOOP;
  RETURN;
END;
$BODY$ LANGUAGE plpgsql STABLE;

In case if you want to return more then one column:

CREATE OR REPLACE FUNCTION get_active_trips(n int)
RETURNS TABLE (counter_value int, active_trips_count int) AS
$BODY$
BEGIN
  FOR counter IN 43130..50000 BY 60 LOOP
    SELECT
    COUNT(trips.trip_id)
    INTO active_trips_count
    FROM denormalized_trips AS trips
    <rest of query here>
    ;
    counter_value := counter;
    RETURN NEXT; -- There is no parameters, current values of counter_value and active_trips_count will be returned
  END LOOP;
  RETURN;
END;
$BODY$ LANGUAGE plpgsql STABLE;

or, using RETURN QUERY:

CREATE OR REPLACE FUNCTION get_active_trips(n int)
RETURNS TABLE (counter_value int, active_trips_count int) AS
$BODY$
BEGIN
  FOR counter IN 43130..50000 BY 60 LOOP
    RETURN QUERY
      SELECT
        counter,
        COUNT(trips.trip_id)
      FROM denormalized_trips AS trips
      <rest of query here>
      ;
  END LOOP;
  RETURN;
END;
$BODY$ LANGUAGE plpgsql STABLE;

Finally there is alternative declaration for returns table:

CREATE OR REPLACE FUNCTION get_active_trips(
  n int,
  out counter_value int,
  out active_trips_count int)
RETURNS SETOF RECORD AS

Update

But(!) I feeling that it is possible to simplify your task using single query, without loop.

Consider the following query (i'v used your simplified query from sqlfiddle):

select
  counter,
  count(trips.trip_id)
from
  generate_series(43130, 50000, 60) as counter left join
    denormalized_trips as trips on (trip_start_time between counter and counter + 60)
group by counter
order by counter;


来源: stackexchange

问:
How to attach a jQuery event to a grid view that is not visible on document ready?
I am trying to hook into a link in a gridview with jquery but the grid is in an update panel and not visible until the user runs a report. If I add the class ".myLink" to any other "a" tag it works fine, but as the gridview is not there at document.ready I am not sure where to call this from</p>

```<code>              $(document).ready(function(){
                $('a .myLink').click(function(){
                  var link = $(this).attr('href');
                  alert(link);
                  return false;
                });
              });
</code>```

答:
The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation.

Reference

ContentLicense: CC BY-SA 2.5

Body:
I am trying to hook into a link in a gridview with jquery but the grid is in an update panel and not visible until the user runs a report. If I add the class ".myLink" to any other "a" tag it works fine, but as the gridview is not there at document.ready I am not sure where to call this from

              $(document).ready(function(){
                $('a .myLink').click(function(){
                  var link = $(this).attr('href');
                  alert(link);
                  return false;
                });
              });


问:
Drupal 8 override Theme Hook Page file suggestion
I know there are some tutorials online about how to do this, but for some reason I doesn't work.

I would like to add a file theme suggestion on the "Theme Hook: Page" level of the template with the name of the content type (this way I can let all items of this content type use this template).

So, I add this to my MYTHEME.theme.php file:

```<code>function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
   if ($node = \Drupal::request()->attributes->get('node')) {
       array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
    }
}
</code>```

So you would expect the following output:

page--node--19.html.twig

page--node--%.html.twig

page--node--dish.html.twig // Gets not added

page--node.html.twig

page.html.twig

I already tried clearing the cache. I'm using Drupal 8.1

What am I missing here?

答:
My mistake was not with the function but with the filename. My file name was MYTHEME.theme.php but it should have been MYTHEME.theme.

That's why the code didn't work.

ContentLicense: CC BY-SA 3.0

Body:
I know there are some tutorials online about how to do this, but for some reason I doesn't work.

I would like to add a file theme suggestion on the "Theme Hook: Page" level of the template with the name of the content type (this way I can let all items of this content type use this template).

So, I add this to my MYTHEME.theme.php file:

function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
   if ($node = \Drupal::request()->attributes->get('node')) {
       array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
    }
}

So you would expect the following output:

page--node--19.html.twig

page--node--%.html.twig

page--node--dish.html.twig // Gets not added

page--node.html.twig

page.html.twig

I already tried clearing the cache. I'm using Drupal 8.1

What am I missing here?


问:
Deserialise JSON and get the datatypes
I am a begginer in C# and have been struggling to solve this issue.

I have a Json file.

I need to deserialise it and insert the data into SQL.

The Json file looks something like this:

```<code>{
    "records": [
    {
        "class": "Abc",
        "id": "7720170378514849999",
        "fields": {
            "name": "xyz",
            "created_at": "2015-02-26 15:06:48 UTC",
            "updated_at": "2017-05-08 15:31:45 UTC",
            "domain": "domainname",
            "month": null,
            "secure": true,
            "filters": null,
            "users_counter": 373
        },
        "links": {
        }
    },
    {
        "class": "User",
        "id": "7765907511856219999",
        "fields": {
            "first_name": "aaa",
            "last_name": "bbb",
            "email": "aaa@domain.com",
            "timezone": null,
            "local": null,
            "unsubscribe": false,
            "address_verified": false
        },
        "links": {
            "Abc_id": "7720170378514849999"
        }
    },
}
</code>```

My code so far:

```<code>public void doConvert()
{
    string unzippedFileName = "c:\\tar\\finish\\UnzippedFile.json";

    List<dynamic> allEntities = new List<dynamic>();

    try
    {
        var deserialisedJson = JsonConvert.DeserializeObject<dynamic>
        (System.IO.File.ReadAllText(@unzippedFileName));
        var records = deserialisedJson.records;

        foreach (var item in records)
        {
            string itemString = item.ToString();
            var deserialisedItem =
            JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>
          (itemString);
            var className = deserialisedItem["class"];
            var classId = deserialisedItem["id"];
            dynamic classFields = deserialisedItem["fields"];

            var deserialisedClassFields =
            JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>
            (classFields.ToString());

            dynamic classLinks = deserialisedItem["links"];
            var deserialisedClassLinks = JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>(classLinks.ToString());

            ParseIntoType(className);
            ParseIntoType(classId);

            foreach (KeyValuePair<dynamic, dynamic> entry in deserialisedClassFields)
            {
                ParseIntoType(entry.Key);
            }

            foreach (KeyValuePair<dynamic, dynamic> entry in deserialisedClassLinks)
            {
                ParseIntoType(entry.Key);
            }

            buildsqlstatements() // My issue is here

        }

    }
    catch (Exception ee)
    {
        Log.ErrorFormat("Exception:{0}", ee.ToString());
    }
}

public void ParseIntoType(dynamic itemTobeParsed)
{

    new Dictionary<Type, Action>{
       {typeof(bool), () =>  boolEntityList.Add(itemTobeParsed)},
       {typeof(int),  () => intEntityList.Add(itemTobeParsed)},
       {typeof(BigInteger),  () => bigIntEntityList.Add(itemTobeParsed)},
       {typeof(double),  () => doubleEntityList.Add(itemTobeParsed)},
       {typeof(DateTime),  () => dateTimeEntityList.Add(itemTobeParsed)},
       {typeof(string),  () => stringEntityList.Add(itemTobeParsed)},
       {typeof(TextReader),  () => textEntityList.Add(itemTobeParsed)},

       }[itemTobeParsed.GetType()]();

}
</code>```

Details:

The idea is to delete everything that is in the database and re-create everything on each run. So it will delete/drop the tables and recreate the same table with the latest data.

For example for Users table, I will first drop if any (from yesterday's run) Users_temp table is there, then create Users_temp table, insert the latest data into this table, then drop Users table and then rename Users_temp to Users table. My issue here is that in order to create the Users_temp table I have to define its column types. So I have to get the data type of first_name, which would come in as string and then I will have to somehow map it to varchar(255) and then build the sql statement.

Create table Users(
first_name varchar(255)
lastname varchar(255)
timezone datetime
);

```<code>         //string createTmpTable = "create table "+className+" ((column = deserialised key from fields, datatype = its datatype))";
</code>```

Right now what happens is everything gets parsed as string. Even the timezone or any int data also gets parsed as string. So I am unable to build the sql statement because I am not getting the correct datatype.  I am assuming this is because of these lines:

```<code>    foreach (var item in records)
            {
                string itemString = item.ToString();
                var deserialisedItem =
   JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>(itemString);
</code>```

because I am converting the item to itemString, everything becomes a string. JsonConvert.DeserializeObject only takes in String parameter so I cannot pass anything else there. Is there any way I can recover the original data type there?

答:
You can use a typed model and tell JsonConvert to leave fields as null if it can't find them in the json string. You can leverage that and provide all possible fields in a typed model structure. You gain the benefit of verifing the data is correctly typed before it goes into the database.

```<code>public class Record
{
    public string @class {get; set;}
    public string id { get; set; }
    public List<RecordField> fields { get; set; }
    public Dictionary<string,string> links { get; set; }
}

public class RecordField
{
    // fields from first object in the array
    public string name { get; set; }
    public DateTime created_at { get; set; }
    public DateTime updated_at { get; set; }
    public string domain { get; set; }
    public int month { get; set; }
    public bool secure { get; set; }
    public List<string> filters { get; set; }
    public int user_count { get; set; }

    // fields from second object in the array
    public int first_name { get; set; }
    //...
}
</code>```

To make JsonConvert aware of possible missing fields this you need to set the following settings before the conversion:

```<code>var settings =
    new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore,
        MissingMemberHandling = MissingMemberHandling.Ignore
    };
var records = JsonConvert.DeserializeObject<List<Record>>(json, settings);
</code>```

Title: Deserialise JSON and get the datatypes

Body:
I am a begginer in C# and have been struggling to solve this issue.

I have a Json file.

I need to deserialise it and insert the data into SQL.

The Json file looks something like this:

{
    "records": [
    {
        "class": "Abc",
        "id": "7720170378514849999",
        "fields": {
            "name": "xyz",
            "created_at": "2015-02-26 15:06:48 UTC",
            "updated_at": "2017-05-08 15:31:45 UTC",
            "domain": "domainname",
            "month": null,
            "secure": true,
            "filters": null,
            "users_counter": 373
        },
        "links": {
        }
    },
    {
        "class": "User",
        "id": "7765907511856219999",
        "fields": {
            "first_name": "aaa",
            "last_name": "bbb",
            "email": "aaa@domain.com",
            "timezone": null,
            "local": null,
            "unsubscribe": false,
            "address_verified": false
        },
        "links": {
            "Abc_id": "7720170378514849999"
        }
    },
}

My code so far:

public void doConvert()
{
    string unzippedFileName = "c:\\tar\\finish\\UnzippedFile.json";

    List<dynamic> allEntities = new List<dynamic>();

    try
    {
        var deserialisedJson = JsonConvert.DeserializeObject<dynamic>
        (System.IO.File.ReadAllText(@unzippedFileName));
        var records = deserialisedJson.records;

        foreach (var item in records)
        {
            string itemString = item.ToString();
            var deserialisedItem =
            JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>
          (itemString);
            var className = deserialisedItem["class"];
            var classId = deserialisedItem["id"];
            dynamic classFields = deserialisedItem["fields"];

            var deserialisedClassFields =
            JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>
            (classFields.ToString());

            dynamic classLinks = deserialisedItem["links"];
            var deserialisedClassLinks = JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>(classLinks.ToString());

            ParseIntoType(className);
            ParseIntoType(classId);

            foreach (KeyValuePair<dynamic, dynamic> entry in deserialisedClassFields)
            {
                ParseIntoType(entry.Key);
            }

            foreach (KeyValuePair<dynamic, dynamic> entry in deserialisedClassLinks)
            {
                ParseIntoType(entry.Key);
            }

            buildsqlstatements() // My issue is here

        }

    }
    catch (Exception ee)
    {
        Log.ErrorFormat("Exception:{0}", ee.ToString());
    }
}

public void ParseIntoType(dynamic itemTobeParsed)
{

    new Dictionary<Type, Action>{
       {typeof(bool), () =>  boolEntityList.Add(itemTobeParsed)},
       {typeof(int),  () => intEntityList.Add(itemTobeParsed)},
       {typeof(BigInteger),  () => bigIntEntityList.Add(itemTobeParsed)},
       {typeof(double),  () => doubleEntityList.Add(itemTobeParsed)},
       {typeof(DateTime),  () => dateTimeEntityList.Add(itemTobeParsed)},
       {typeof(string),  () => stringEntityList.Add(itemTobeParsed)},
       {typeof(TextReader),  () => textEntityList.Add(itemTobeParsed)},

       }[itemTobeParsed.GetType()]();

}

Details:

The idea is to delete everything that is in the database and re-create everything on each run. So it will delete/drop the tables and recreate the same table with the latest data.

For example for Users table, I will first drop if any (from yesterday's run) Users_temp table is there, then create Users_temp table, insert the latest data into this table, then drop Users table and then rename Users_temp to Users table. My issue here is that in order to create the Users_temp table I have to define its column types. So I have to get the data type of first_name, which would come in as string and then I will have to somehow map it to varchar(255) and then build the sql statement.

Create table Users(
first_name varchar(255)
lastname varchar(255)
timezone datetime
);

         //string createTmpTable = "create table "+className+" ((column = deserialised key from fields, datatype = its datatype))";

Right now what happens is everything gets parsed as string. Even the timezone or any int data also gets parsed as string. So I am unable to build the sql statement because I am not getting the correct datatype.  I am assuming this is because of these lines:

    foreach (var item in records)
            {
                string itemString = item.ToString();
                var deserialisedItem =
   JsonConvert.DeserializeObject<Dictionary<dynamic, dynamic>>(itemString);

because I am converting the item to itemString, everything becomes a string. JsonConvert.DeserializeObject only takes in String parameter so I cannot pass anything else there. Is there any way I can recover the original data type there?

Body:
You can use a typed model and tell JsonConvert to leave fields as null if it can't find them in the json string. You can leverage that and provide all possible fields in a typed model structure. You gain the benefit of verifing the data is correctly typed before it goes into the database.

public class Record
{
    public string @class {get; set;}
    public string id { get; set; }
    public List<RecordField> fields { get; set; }
    public Dictionary<string,string> links { get; set; }
}

public class RecordField
{
    // fields from first object in the array
    public string name { get; set; }
    public DateTime created_at { get; set; }
    public DateTime updated_at { get; set; }
    public string domain { get; set; }
    public int month { get; set; }
    public bool secure { get; set; }
    public List<string> filters { get; set; }
    public int user_count { get; set; }

    // fields from second object in the array
    public int first_name { get; set; }
    //...
}

To make JsonConvert aware of possible missing fields this you need to set the following settings before the conversion:

var settings =
    new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore,
        MissingMemberHandling = MissingMemberHandling.Ignore
    };
var records = JsonConvert.DeserializeObject<List<Record>>(json, settings);


问:
MenuItem bitmaps raises an assert failure …
I am trying to have a nice bitmap of a gear in front of the Preferences menu item. This is how I think it should be coded:

```<code>    menubar = wx.MenuBar()
    fileMenu = wx.Menu()
    preferences = wx.MenuItem(text="Preferences",
                              helpString="Opens preferences dialog.",
                              kind=wx.ITEM_NORMAL)
    gear = wx.Bitmap(os.path.join(os.path.dirname(__file__), 'gear.png'))
    preferences.SetBitmap(gear)
    self.shcfg = fileMenu.Append(preferences)
</code>```

However, this is wrong as I get a

```<code>Traceback (most recent call last):
  File "gui.py", line 193, in <module>
    GUI(None)
  File "gui.py", line 117, in __init__
    self.InitUI()
  File "gui.py", line 129, in InitUI
    preferences.SetBitmap(gear)
wx._core.wxAssertionError: C++ assertion "Assert failure" failed at /tmp/pip-build-sc_vd1aj/wxPython/ext/wxWidgets/src/gtk/menu.cpp(729) in SetBitmap(): only normal menu items can have bitmaps
</code>```

What am I doing wrong?

答:
You are using Append rather than AppendItem

I suppose that there any number of ways to put a menu together but I have found that, all menu items require an Id.

For predefined wx id's it is straight forward as you can simply append them as they come not only with an in-built Id but also an image.

For custom images I use the method below, which has consistently worked for me.

Note that I have used both predefined Id's and custom Id's in this sample code.

I have included a variant of your code below

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import os
class MainWindow(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(200, 100))
        self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)

        # Create Statusbar
        self.CreateStatusBar()

        # Set up the menus
        filemenu = wx.Menu()
        infomenu = wx.Menu()

        # file menu
        filemenu.Append(wx.ID_NEW, "New") # Id of wx.ID_NEW (5002) which picks up an automatic image
        filemenu.Append(wx.ID_SAVE, "Save")

        m1 = wx.MenuItem(filemenu, 100, "Manual Bitmap") #A manual id of 100
        m1.SetBitmap(wx.Bitmap('./myimage1.png'))
        filemenu.AppendItem(m1)

        m2 = wx.MenuItem(filemenu, 101, "Manual Bitmap 2") #A manual id of 101
        m2.SetBitmap(wx.Bitmap('./myimage2.png'))
        filemenu.AppendItem(m2)
        #----------------------------------------------#
        preferences = wx.MenuItem()
        preferences.SetId(102)
        preferences.SetText("Preferences")
        preferences.SetHelp("Preferences Help")
        preferences.SetKind(wx.ITEM_NORMAL)
        gear = wx.Bitmap(os.path.join(os.path.dirname(__file__), 'myimage2.png'))
        preferences.SetBitmap(gear)
        filemenu.AppendItem(preferences)
        #----------------------------------------------#
        filemenu.AppendSeparator()

        filemenu.Append(wx.ID_EXIT, "Exit")

        # info menu
        infomenu.Append(wx.ID_ABOUT, "About")

        # bind file menu
        self.Bind(wx.EVT_MENU, self.OnManualBitmap, id=100) # Bind to the Id
        self.Bind(wx.EVT_MENU, self.OnManualBitmap, id=101) # Bind to the Id
        self.Bind(wx.EVT_MENU, self.OnManualBitmap, id=102) # Bind to the Id
        self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)

        # Creating the menubar.
        menuBar = wx.MenuBar()

        # Add menus
        menuBar.Append(filemenu, "&Preferences")
        menuBar.Append(infomenu, "&Help")

        # Add the MenuBar to the Frame content.
        self.SetMenuBar(menuBar)
        self.Show(True)

    def OnManualBitmap(self, event):
        print event.EventObject.GetLabel(event.Id)
        print event.Id

    def OnExit(self, event):
        self.Destroy()

app = wx.App()
frame = MainWindow(None, "Menu Image Test")
app.MainLoop()
</code>```

Body:
I am trying to have a nice bitmap of a gear in front of the Preferences menu item. This is how I think it should be coded:

    menubar = wx.MenuBar()
    fileMenu = wx.Menu()
    preferences = wx.MenuItem(text="Preferences",
                              helpString="Opens preferences dialog.",
                              kind=wx.ITEM_NORMAL)
    gear = wx.Bitmap(os.path.join(os.path.dirname(__file__), 'gear.png'))
    preferences.SetBitmap(gear)
    self.shcfg = fileMenu.Append(preferences)

However, this is wrong as I get a

Traceback (most recent call last):
  File "gui.py", line 193, in <module>
    GUI(None)
  File "gui.py", line 117, in __init__
    self.InitUI()
  File "gui.py", line 129, in InitUI
    preferences.SetBitmap(gear)
wx._core.wxAssertionError: C++ assertion "Assert failure" failed at /tmp/pip-build-sc_vd1aj/wxPython/ext/wxWidgets/src/gtk/menu.cpp(729) in SetBitmap(): only normal menu items can have bitmaps

What am I doing wrong?

Body:
You are using Append rather than AppendItem

I suppose that there any number of ways to put a menu together but I have found that, all menu items require an Id.

For predefined wx id's it is straight forward as you can simply append them as they come not only with an in-built Id but also an image.

For custom images I use the method below, which has consistently worked for me.

Note that I have used both predefined Id's and custom Id's in this sample code.

I have included a variant of your code below

#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import os
class MainWindow(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(200, 100))
        self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)

        # Create Statusbar
        self.CreateStatusBar()

        # Set up the menus
        filemenu = wx.Menu()
        infomenu = wx.Menu()

        # file menu
        filemenu.Append(wx.ID_NEW, "New") # Id of wx.ID_NEW (5002) which picks up an automatic image
        filemenu.Append(wx.ID_SAVE, "Save")

        m1 = wx.MenuItem(filemenu, 100, "Manual Bitmap") #A manual id of 100
        m1.SetBitmap(wx.Bitmap('./myimage1.png'))
        filemenu.AppendItem(m1)

        m2 = wx.MenuItem(filemenu, 101, "Manual Bitmap 2") #A manual id of 101
        m2.SetBitmap(wx.Bitmap('./myimage2.png'))
        filemenu.AppendItem(m2)
        #----------------------------------------------#
        preferences = wx.MenuItem()
        preferences.SetId(102)
        preferences.SetText("Preferences")
        preferences.SetHelp("Preferences Help")
        preferences.SetKind(wx.ITEM_NORMAL)
        gear = wx.Bitmap(os.path.join(os.path.dirname(__file__), 'myimage2.png'))
        preferences.SetBitmap(gear)
        filemenu.AppendItem(preferences)
        #----------------------------------------------#
        filemenu.AppendSeparator()

        filemenu.Append(wx.ID_EXIT, "Exit")

        # info menu
        infomenu.Append(wx.ID_ABOUT, "About")

        # bind file menu
        self.Bind(wx.EVT_MENU, self.OnManualBitmap, id=100) # Bind to the Id
        self.Bind(wx.EVT_MENU, self.OnManualBitmap, id=101) # Bind to the Id
        self.Bind(wx.EVT_MENU, self.OnManualBitmap, id=102) # Bind to the Id
        self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)

        # Creating the menubar.
        menuBar = wx.MenuBar()

        # Add menus
        menuBar.Append(filemenu, "&Preferences")
        menuBar.Append(infomenu, "&Help")

        # Add the MenuBar to the Frame content.
        self.SetMenuBar(menuBar)
        self.Show(True)

    def OnManualBitmap(self, event):
        print event.EventObject.GetLabel(event.Id)
        print event.Id

    def OnExit(self, event):
        self.Destroy()

app = wx.App()
frame = MainWindow(None, "Menu Image Test")
app.MainLoop()


问:
how to add android drm plugin
i'm trying to add kClearKey DRM plugin in my android phone(LG nexus 4). I tried following solution,but it doesn't work for me:

1)build the kClearPlugin from source code provided by google source code tree.

2)put libkClearPlugin.so shared library in /system/lib/drm/plugins/native

3)reboot phone

what i'm trying to do is run an exploit for android mediaserver(CVE-2015-6612). when i run the exploit, it throws an UnsupportedSchemeexception,which means kCkearPlugin is not installed on my android phone.

My specific question is: How can i add this plugin to my android phone?

Thanks in advance

答:
On an non-rooted Android device /system/lib is read only - i.e. you can't simply add a new DRM system in as you would like.

The Android documentation is still a little ambiguous on this as it says:

For device manufacturers, content owners, and Internet digital media providers the DRM framework’s plugin architecture provides a means of adding support for a specific DRM scheme to the Android system.

This may give the impression that you anyone can add it but the DRMs are typically added by the device manufacturers.

In theory this stops someone coming along and overwriting the DRM with their own one to try to copy the content, but in practice DRM solutions will have protection against this anyway even if someone did this.

Title: how to add android drm plugin


问:
Error messages combining group_by and as.numeric in R
I have a dataset

```<code>Gene Sample  Ctmean

Chr1 0.0032 38.30534

Chr1  0.016 38.05460

Chr2 0.0032 34.96991
</code>```

and so on, wherein the sample names "Sample" were initially defined as characters (some are names, some numbers). I have filtered for just the ones which are numbers so I can use these for one analysis, with the named ones for later separate analysis, but when trying to group them by another column for this analysis I am running into the error message

Error in function_list[k] :
   (list) object cannot be coerced to type 'double'

after using

```<code>group_by(forstandardcurve,Gene) %>% as.numeric(forstandardcurve$Sample)
</code>```

Conversely if I use

```<code>as.numeric(forstandardcurve$Sample) %>% group_by(forstandardcurve,Gene)
</code>```

I get

Error in UseMethod("group_by_") :
   no applicable method for 'group_by_' applied to an object of class >"c('double', 'numeric')"

although the "Gene" column should still be 'character' too.
Each command looks like it is working as I expect when run by itself. I am very new to R so sorry if this is a basic error I have made - how do I fix this so I can use the numbers in "Sample" to plug into equations, with separate equations for each group in the "Gene" column?

答:
You're trying to convert class in your example as a stand-alone command, but it makes more sense to convert class in the context of another R verb. For instance, let's say you want to calculate the mean of Sample grouped by Gene.

Starting with your data, where Sample is a character:

```<code>df <- data.frame( Gene = c("Chr1","Chr1","Chr2"),
              Sample = c("0.0032","0.016","0.0032"),
              Ctmean = c(38.3, 38.0, 34.9))
</code>```

You can do:

```<code>df %>%
   group_by(Gene) %>%
   summarise( Sample = mean( as.numeric(as.character(Sample)) ) )
</code>```

Note that I had to change from factor to character first, before cnverting to numeric. This gives:

```<code>1   Chr1 0.0096
2   Chr2 0.0032
</code>```

Body:
I have a dataset

Gene Sample  Ctmean

Chr1 0.0032 38.30534

Chr1  0.016 38.05460

Chr2 0.0032 34.96991

and so on, wherein the sample names "Sample" were initially defined as characters (some are names, some numbers). I have filtered for just the ones which are numbers so I can use these for one analysis, with the named ones for later separate analysis, but when trying to group them by another column for this analysis I am running into the error message

Error in function_list[k] :
   (list) object cannot be coerced to type 'double'

after using

group_by(forstandardcurve,Gene) %>% as.numeric(forstandardcurve$Sample)

Conversely if I use

as.numeric(forstandardcurve$Sample) %>% group_by(forstandardcurve,Gene)

I get

Error in UseMethod("group_by_") :
   no applicable method for 'group_by_' applied to an object of class >"c('double', 'numeric')"

although the "Gene" column should still be 'character' too.
Each command looks like it is working as I expect when run by itself. I am very new to R so sorry if this is a basic error I have made - how do I fix this so I can use the numbers in "Sample" to plug into equations, with separate equations for each group in the "Gene" column?

Body:
You're trying to convert class in your example as a stand-alone command, but it makes more sense to convert class in the context of another R verb. For instance, let's say you want to calculate the mean of Sample grouped by Gene.

Starting with your data, where Sample is a character:

df <- data.frame( Gene = c("Chr1","Chr1","Chr2"),
              Sample = c("0.0032","0.016","0.0032"),
              Ctmean = c(38.3, 38.0, 34.9))

You can do:

df %>%
   group_by(Gene) %>%
   summarise( Sample = mean( as.numeric(as.character(Sample)) ) )

Note that I had to change from factor to character first, before cnverting to numeric. This gives:

1   Chr1 0.0096
2   Chr2 0.0032


问:
How can I add together the values of an array in CoffeeScript?
I have an array of numbers.
How can I add them together the easiest way in CoffeeScript?</p>

答:
The easiest way is probably to use Array.prototype.reduce just like you'd do in JavaScript:

```<code>numbers = [1..11]
sum     = numbers.reduce (m, n) -> m + n
# sum is now 66
</code>```

Body:
The easiest way is probably to use Array.prototype.reduce just like you'd do in JavaScript:

numbers = [1..11]
sum     = numbers.reduce (m, n) -> m + n
# sum is now 66


问:
Get a whole column in a struct field in MATLAB
I have a struct in MATLAB with the size 46x6, the fields are:

```<code>name, folder, date, bytes, isdir, datenum
</code>```

Now I want all 46 entries of name. However, the MATLAB function getfield(structname, 'name') only returns the first entry.

How can I get all elements of the struct?

Name holds strings

答:
If you want the results as a cell array you can call {structname(:).name}.
To return an array you can call [structname(:).name].

Body:
I have a struct in MATLAB with the size 46x6, the fields are:

name, folder, date, bytes, isdir, datenum

Now I want all 46 entries of name. However, the MATLAB function getfield(structname, 'name') only returns the first entry.

How can I get all elements of the struct?

Name holds strings


问:
Execute icacls in PowerShell to grant access to a file share for domain computer
I wonder how to uses icacls within a PowerShell script for setting up permissions on a fileshare for a computeraccount for e.g. Domain\myServer$.

This is what I'm trying:

```<code>$ComputerAccount = "domain\myServer$"
$Folder = "\\TestServer\TestShare\folder1"
$rule = $ComputerAccount+':(M),(OI),(CI)'
$resICacls = Invoke-Expression "icacls $folder /grant $rule"
</code>```

I got this error message:

```
Invoke-Expression : At line:1 char:83
+ ... ant Domain\myServer$:(M),(OI),(CI)
+                    ~~

Variable reference is not valid. '$' was not followed by a valid variable name
character. Consider using ${} to delimit the name.
At c:\Binary\testacl.ps1:12 char:26
+             $resICacls = Invoke-Expression "icacls $folder /grant $rule"
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Invoke-Expression], ParseException
    + FullyQualifiedErrorId : InvalidVariableReference,Microsoft.PowerShell.Commands.InvokeExpressionCommand
```

I tried different variants of escaping the $ but found no solution.
Anyone haves a hint how to do this?

答:
Invoke-Expression -Command:icacls foldername /grant groupName:"(CI)(OI)M"

This works fine. So I guess that if you will put the command into single quote (i.e. '') it will work. For example:

```<code>$ComputerAccount = "domain\myServer$"
Invoke-Expression -Command:"icacls $ComputerAccount /grant GroupName:'(CI)(OI)M'"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wonder how to uses icacls within a PowerShell script for setting up permissions on a fileshare for a computeraccount for e.g. Domain\myServer$.

This is what I'm trying:

$ComputerAccount = "domain\myServer$"
$Folder = "\\TestServer\TestShare\folder1"
$rule = $ComputerAccount+':(M),(OI),(CI)'
$resICacls = Invoke-Expression "icacls $folder /grant $rule"

I got this error message:

Invoke-Expression : At line:1 char:83
+ ... ant Domain\myServer$:(M),(OI),(CI)
+                    ~~

Variable reference is not valid. '$' was not followed by a valid variable name
character. Consider using ${} to delimit the name.
At c:\Binary\testacl.ps1:12 char:26
+             $resICacls = Invoke-Expression "icacls $folder /grant $rule"
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Invoke-Expression], ParseException
    + FullyQualifiedErrorId : InvalidVariableReference,Microsoft.PowerShell.Commands.InvokeExpressionCommand

I tried different variants of escaping the $ but found no solution.
Anyone haves a hint how to do this?

Body:
Invoke-Expression -Command:icacls foldername /grant groupName:"(CI)(OI)M"

This works fine. So I guess that if you will put the command into single quote (i.e. '') it will work. For example:

$ComputerAccount = "domain\myServer$"
Invoke-Expression -Command:"icacls $ComputerAccount /grant GroupName:'(CI)(OI)M'"


问:
VMSS scale up with booting executable after launch
I have VM scale set for my Azure ServiceFabric Application deployed in Azure. I need to run RabbitMQ server on each virtual machine in my VM scale set when it starts (especially actual when I am going to scale up my cluster and new VM is going to be created). In other words I want make queue run automatically. Are there any possibilities to do the next steps after VM has been launched:

Check if RabbitMQ is already installed.

Download and install if not from specified URL.

If it has been installed just run it.

I guess this issue can be solved with virtual machine scale set Automation Script, but I am not sure. Any ideas and suggestions?

答:
You could do this using a VM custom script extension. An extension runs on every new VM when a scale set is deployed or when it scales out.
Your extension could do the checks, install and run, and perhaps create a service so RabbitMQ runs if the VM is rebooted etc.
The following articles provide more details on deploying apps with scale sets:
Deploy your application on virtual machine scale sets
How are Applications deployed on VM Scale Sets?</p>


问:
PHP performance question
Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.

//OPTION ONE

```<code>if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.
</code>```

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.

答:
The second option is negligibly more performance heavy, but is your better option as it produces less code duplication.

Also, if you cache the result of isLoggedIn() in a static var, you do not have to perform all your checks with every call of the method. You can check your static var and jump out early.

```<code>function isLoggedIn() {
    static $is_logged_in = null;

    if(!is_null($is_logged_in)) {
        return $is_logged_in;
    }

    //... user is known not to have valid credentials

    $is_logged_in = false;

    // ... User has been validated

    $is_logged_in = true;

    //...

}
</code>```

Title: PHP performance question

Body:
Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.

//OPTION ONE

if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.

Body:
The second option is negligibly more performance heavy, but is your better option as it produces less code duplication.

Also, if you cache the result of isLoggedIn() in a static var, you do not have to perform all your checks with every call of the method. You can check your static var and jump out early.

function isLoggedIn() {
    static $is_logged_in = null;

    if(!is_null($is_logged_in)) {
        return $is_logged_in;
    }

    //... user is known not to have valid credentials

    $is_logged_in = false;

    // ... User has been validated

    $is_logged_in = true;

    //...

}


问:
AngularJS web.xml for tomcat servlet config <error-page>
Currently, we are deploying an AngularJS webapp using a tomcat servlet.
that uses a standard Web Application deployment descriptor, web.xml located in the  WEB-INF directory. The webapp directly handles URL mapping and error codes internally, so we would not like to have 404 error code when a resource is not found (Specially REST resources).

We have been able to but being able to get rid of the error changing
404 to 200, stills this solution does not convince me 100%.

(Normal use of error-page)

```<code><error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
</code>```

(Is this solution ok?)

```<code><error-page>
<!--Every time 200 is used as error code we stray further from God's Light.-->
<error-code>200</error-code>
<location>/404.html</location>
</error-page>
</code>```

Is this solution the most appropriate or there is something we are missing?

答:
The error codes were related to the first request, using a filter this 404 issue was solved. The following picture clarifies it better:

The filter only works one time, because once the app is loaded, for this case no more requests are done with the servlet. After it is loaded into the client (5) it handles error code as a normal Angular app will do.

Body:
Currently, we are deploying an AngularJS webapp using a tomcat servlet.
that uses a standard Web Application deployment descriptor, web.xml located in the  WEB-INF directory. The webapp directly handles URL mapping and error codes internally, so we would not like to have 404 error code when a resource is not found (Specially REST resources).

We have been able to but being able to get rid of the error changing
404 to 200, stills this solution does not convince me 100%.

(Normal use of error-page)

<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>

(Is this solution ok?)

<error-page>

<error-code>200</error-code>
<location>/404.html</location>
</error-page>

Is this solution the most appropriate or there is something we are missing?


问:
Trigger for Audit Table in Sybase ASE 15.7
I'm trying to create a trigger that records info on insertions, updates, and deletions. To make things simple I'm simply trying to create a trigger for insertions without including info such as user and date.

My referenced table is with columns:

DefaultProperties

-DefaultPropertiesID

-Key_

-Value

-ProcessID_FK (foreign key)

============================

and my audit table is:

DefaultProperties_Audit

-OldDefaultID

-OldKey_

-OldValue

-OldProcessID_FK

The code for my current trigger is:

```<code>create trigger DPTrigger on DefaultProperties
   for insert as
   begin
       insert into DefaultProperties_Audit(OldDefaultID, OldKey_, OldValue, OldPid_FK, Modifier, EntryDate, Operation)
       select DefaultPropertiesID, Key_, Value, ProcessID_FK, user_name(), GETDATE(), 'insertion' from inserted
   end
</code>```

but how do I do something like this?

```<code>create trigger DPTrigger on DefaultProperties
    for insert, update, delete as
    if insert then
        begin
            insert into DefaultProperties_Audit(OldDefaultID, OldKey_, OldValue, OldPid_FK, Modifier, EntryDate, Operation)
            select DefaultPropertiesID, Key_, Value, ProcessID_FK, user_name(), GETDATE(), 'insertion' from inserted
        end
    endif
    if update then
        doSomething()
    endif
    if delete then
        doSomethingElse()
    endif
</code>```

When I try to compile my version of the above, it throws me an error. I understand an alternative is to create three separate triggers for insert, update, and delete. I was just wondering if I can condense it into one?

Also, it seems like I can condense it into one if I explicitly state
    if update(col1) or update(col2) or update(col3)
but that seems to also possibly bring up some errors.

Any tips/hints to make this work and to improve it would be greatly appreciated.

答:
ASE triggers support the update() function; there is no such thing as a insert() function.

While the update() function can be used for insert triggers, update() is typically used in update triggers to determine which columns have been updated.

In this particular case, since you plan on inserting the whole row into your audit table, and obviously (?) all of the columns are new, you'll likely find something like the following to be more useful:

```<code>create trigger dbo.DPTrigger on dbo.DefaultProperties
    for insert as
    begin
        insert into DefaultProperties_Audit(OldDefaultID, OldKey_, OldValue, OldPid_FK)
        select DefaultPropertiesID, Key_, ProcessID_FK, Value from  inserted
    end
</code>```

For create trigger syntax, examples, and some discussion of trigger coding see ASE - Reference Manual: Commands - create trigger

For more discussion on trigger usage as it pertains to RI and transactional control see ASE - TSQL Users Guide - Triggers: Enforcing RI constraints

As for the updated question asking about consolidating the insert/update/delete code into a single trigger ...

The easiest way to determine if the trigger fired on an insert, update or delete is to test for the existence of rows in the pseudo-tables named inserted and deleted; you can either test for the existence every time the trigger needs to know the type of parent DML, or test once and store in a @variable:

```<code>create trigger ...
begin
    declare @operation char(1) -- 'I'nsert, 'U'pdate, 'D'elete
    if exists(select 1 from inserted)
        select @operation = 'I'
    if exists(select 1 from deleted)
        select @operation = case when @operation = 'I' then 'U' else 'D' end

    ... reset of trigger code ...
end
</code>```

Body:
I'm trying to create a trigger that records info on insertions, updates, and deletions. To make things simple I'm simply trying to create a trigger for insertions without including info such as user and date.

My referenced table is with columns:

DefaultProperties

-DefaultPropertiesID

-Key_

-Value

-ProcessID_FK (foreign key)

============================

and my audit table is:

DefaultProperties_Audit

-OldDefaultID

-OldKey_

-OldValue

-OldProcessID_FK

The code for my current trigger is:

create trigger DPTrigger on DefaultProperties
   for insert as
   begin
       insert into DefaultProperties_Audit(OldDefaultID, OldKey_, OldValue, OldPid_FK, Modifier, EntryDate, Operation)
       select DefaultPropertiesID, Key_, Value, ProcessID_FK, user_name(), GETDATE(), 'insertion' from inserted
   end

but how do I do something like this?

create trigger DPTrigger on DefaultProperties
    for insert, update, delete as
    if insert then
        begin
            insert into DefaultProperties_Audit(OldDefaultID, OldKey_, OldValue, OldPid_FK, Modifier, EntryDate, Operation)
            select DefaultPropertiesID, Key_, Value, ProcessID_FK, user_name(), GETDATE(), 'insertion' from inserted
        end
    endif
    if update then
        doSomething()
    endif
    if delete then
        doSomethingElse()
    endif

When I try to compile my version of the above, it throws me an error. I understand an alternative is to create three separate triggers for insert, update, and delete. I was just wondering if I can condense it into one?

Also, it seems like I can condense it into one if I explicitly state
    if update(col1) or update(col2) or update(col3)
but that seems to also possibly bring up some errors.

Any tips/hints to make this work and to improve it would be greatly appreciated.

Body:
ASE triggers support the update() function; there is no such thing as a insert() function.

While the update() function can be used for insert triggers, update() is typically used in update triggers to determine which columns have been updated.

In this particular case, since you plan on inserting the whole row into your audit table, and obviously (?) all of the columns are new, you'll likely find something like the following to be more useful:

create trigger dbo.DPTrigger on dbo.DefaultProperties
    for insert as
    begin
        insert into DefaultProperties_Audit(OldDefaultID, OldKey_, OldValue, OldPid_FK)
        select DefaultPropertiesID, Key_, ProcessID_FK, Value from  inserted
    end

For create trigger syntax, examples, and some discussion of trigger coding see ASE - Reference Manual: Commands - create trigger

For more discussion on trigger usage as it pertains to RI and transactional control see ASE - TSQL Users Guide - Triggers: Enforcing RI constraints

As for the updated question asking about consolidating the insert/update/delete code into a single trigger ...

The easiest way to determine if the trigger fired on an insert, update or delete is to test for the existence of rows in the pseudo-tables named inserted and deleted; you can either test for the existence every time the trigger needs to know the type of parent DML, or test once and store in a @variable:

create trigger ...
begin
    declare @operation char(1) -- 'I'nsert, 'U'pdate, 'D'elete
    if exists(select 1 from inserted)
        select @operation = 'I'
    if exists(select 1 from deleted)
        select @operation = case when @operation = 'I' then 'U' else 'D' end

    ... reset of trigger code ...
end


问:
Passing arguments by reference
I want to ask if it is possible to pass arguments to a script function by reference:

i.e. to do something that would look like this in C++:

void boo(int &myint) { myint = 5; }

int main() {
    int t = 4;
    printf("%d\n", t); // t->4
    boo(t);
    printf("%d\n", t); // t->5
}
```

<p>So then in BASH I want to do something like:</p>

```function boo ()
{

    var1=$1       # now var1 is global to the script but using it outside
                  # this function makes me lose encapsulation

    local var2=$1 # so i should use a local variable ... but how to pass it back?

    var2='new'    # only changes the local copy
    #$1='new'     this is wrong of course ...
    # ${!1}='new' # can i somehow use indirect reference?
}

# call boo
SOME_VAR='old'
echo $SOME_VAR # -> old
boo "$SOME_VAR"
echo $SOME_VAR # -> new
```

Any thoughts would be appreciated.

答:
This is what works for me on Ubuntu bash shell</p>

```<code>#!/bin/sh

iteration=10

increment_count()
{
  local i
  i=$(($1+1))
  eval ${1}=\$i
}

increment_count iteration
echo $iteration #prints 11
increment_count iteration
echo $iteration #prints 12
</code>```

OwnerDisplayName: Roman M

Title: Passing arguments by reference

Body:
I want to ask if it is possible to pass arguments to a script function by reference:

i.e. to do something that would look like this in C++:

void boo(int &myint) { myint = 5; }

int main() {
    int t = 4;
    printf("%d\n", t); // t->4
    boo(t);
    printf("%d\n", t); // t->5
}

So then in BASH I want to do something like:

function boo ()
{

    var1=$1       # now var1 is global to the script but using it outside
                  # this function makes me lose encapsulation

    local var2=$1 # so i should use a local variable ... but how to pass it back?

    var2='new'    # only changes the local copy
    #$1='new'     this is wrong of course ...
    # ${!1}='new' # can i somehow use indirect reference?
}

# call boo
SOME_VAR='old'
echo $SOME_VAR # -> old
boo "$SOME_VAR"
echo $SOME_VAR # -> new

Any thoughts would be appreciated.

Body:
This is what works for me on Ubuntu bash shell

#!/bin/sh

iteration=10

increment_count()
{
  local i
  i=$(($1+1))
  eval ${1}=\$i
}

increment_count iteration
echo $iteration #prints 11
increment_count iteration
echo $iteration #prints 12


问:
jquery touchstart is not working on android device
I created a App with cordova , that uses the jquery touchstart event:

```<code>    $("#jqmbtn").on("touchstart", function (event) {
      alert("touchstart")
      if ($("#Suchfeld").val() != ""){
          startsearch($("#Suchfeld").val());
      }
    })
</code>```

The touchstart event fires at any of the Simulate in Browser options provided by visual Studio 2017 and it also fires at multiple AndroidVirtualDevice(AVD) provided by Android Studio.
But when I run the app on my device the touchstart event doesn t trigger.
My device has Android 4.2.2 installed and I also tryed the to get a bug report from the Developer Options of my device , but all I got is a 5MB text file where I can t find any usefull information.
Is there a option I could use to debug the app on my device or does anyone have a Idea what the reason for this could be ? I really don t know what i can do as I don t get any errors when I run on a emulator.
Thank you for your help !

答:
I came across something similar a couple of years ago that I think was was related to touch events being lost on objects that had had transform:translate applied to them. The fix for this was to add a dummy touchstart event listener for the whole document:</p>

```<code>document.body.addEventListener('touchstart', function () { });
</code>```

Body:
I created a App with cordova , that uses the jquery touchstart event:

    $("#jqmbtn").on("touchstart", function (event) {
      alert("touchstart")
      if ($("#Suchfeld").val() != ""){
          startsearch($("#Suchfeld").val());
      }
    })

The touchstart event fires at any of the Simulate in Browser options provided by visual Studio 2017 and it also fires at multiple AndroidVirtualDevice(AVD) provided by Android Studio.
But when I run the app on my device the touchstart event doesn t trigger.
My device has Android 4.2.2 installed and I also tryed the to get a bug report from the Developer Options of my device , but all I got is a 5MB text file where I can t find any usefull information.
Is there a option I could use to debug the app on my device or does anyone have a Idea what the reason for this could be ? I really don t know what i can do as I don t get any errors when I run on a emulator.
Thank you for your help !

Body:
I came across something similar a couple of years ago that I think was was related to touch events being lost on objects that had had transform:translate applied to them. The fix for this was to add a dummy touchstart event listener for the whole document:

document.body.addEventListener('touchstart', function () { });


问:
change the view controller title color in objective c
I want to change the view controller title color like that this one in black!

答:
Try this add this code in viewWillAppear function:-

pass the font name according to your font

```<code>[self.navigationController.navigationBar setTitleTextAttributes:
 @{NSForegroundColorAttributeName:[UIColor blackColor],
NSFontAttributeName:[UIFont fontWithName:@"Helvetica-regular" size:17]}];
</code>```

Body:
Try this add this code in viewWillAppear function:-

pass the font name according to your font

[self.navigationController.navigationBar setTitleTextAttributes:
 @{NSForegroundColorAttributeName:[UIColor blackColor],
NSFontAttributeName:[UIFont fontWithName:@"Helvetica-regular" size:17]}];


问:
Matlab get all possible combinations less than a value
I have a matrix as follows:

```<code>id      value
=============
 1       0.5
 2       0.5
 3       0.8
 4       0.3
 5       0.2
</code>```

From this array, I wish to find all the possible combinations that have a sum less than or equal to 1. That is,

```<code>result
======
1 2
1 4 5
2 4 5
3 5
1 5
1 4
2 4
2 5
...
</code>```

In order to get the above result, my idea has been to initially compute all the possibilities of finding sum of elements in the array, like so:

```<code>for ii = 1 : length(a) % compute number of possibilities
     no_of_possibilities = no_of_possibilities + nchoosek(length(a),ii);
end
</code>```

Once this is done, then loop through all possible combinations.
I would like to know if there's an easier way of doing this.

答:
```<code>data = [0.5, 0.5, 0.8, 0.3, 0.2];
required = cell(1, length(data));
subsets = cell(1, length(data));
for k = 2:length(data)-1 % removes trivial cases (all numbers or one number at a time)
    % generate all possible k-pairs (if k = 3, then all possible triplets
    % will be generated)
    combination = nchoosek(1:length(data), k);
    % for every triplet generated, this function sums the corresponding
    % values and then decides whether then sum is less than equal to 1 or
    % not
    findRequired = @(x) sum(data(1, combination(x, :))) <= 1;
    % generate a logical vector for all possible combinations like [0 1 0]
    % which denotes that the 2nd combination satisfies the condition while
    % the others do not
    required{k} = arrayfun(findRequired, 1:size(combination, 1));
    % access the corresponding combinations from the entire set
    subsets{k} = combination(required{k}, :);
end
</code>```

This produces the following subsets:

```<code>1     2
1     4
1     5
2     4
2     5
3     5
4     5
1     4     5
2     4     5
</code>```

Body:
I have a matrix as follows:

id      value
=============
 1       0.5
 2       0.5
 3       0.8
 4       0.3
 5       0.2

From this array, I wish to find all the possible combinations that have a sum less than or equal to 1. That is,

result
======
1 2
1 4 5
2 4 5
3 5
1 5
1 4
2 4
2 5
...

In order to get the above result, my idea has been to initially compute all the possibilities of finding sum of elements in the array, like so:

for ii = 1 : length(a) % compute number of possibilities
     no_of_possibilities = no_of_possibilities + nchoosek(length(a),ii);
end

Once this is done, then loop through all possible combinations.
I would like to know if there's an easier way of doing this.

Body:
data = [0.5, 0.5, 0.8, 0.3, 0.2];
required = cell(1, length(data));
subsets = cell(1, length(data));
for k = 2:length(data)-1 % removes trivial cases (all numbers or one number at a time)
    % generate all possible k-pairs (if k = 3, then all possible triplets
    % will be generated)
    combination = nchoosek(1:length(data), k);
    % for every triplet generated, this function sums the corresponding
    % values and then decides whether then sum is less than equal to 1 or
    % not
    findRequired = @(x) sum(data(1, combination(x, :))) <= 1;
    % generate a logical vector for all possible combinations like [0 1 0]
    % which denotes that the 2nd combination satisfies the condition while
    % the others do not
    required{k} = arrayfun(findRequired, 1:size(combination, 1));
    % access the corresponding combinations from the entire set
    subsets{k} = combination(required{k}, :);
end

This produces the following subsets:

1     2
1     4
1     5
2     4
2     5
3     5
4     5
1     4     5
2     4     5


问:
wordpress pagination ads extra slashes to url
Working with custom post types I cant seem to get the pagination to work correct. All is working but when I click to the next page the url will get a extra slash in the url, not sure why this is happening but when using the pagination a lot will add every time a new slash to the url.

// out

```<code>site.com/projects/ ,
site.com/projects//page/2,
site.com/projects///page/3,
site.com/projects////page/4

...and so on.
</code>```

// the code used

```<code>    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

    $query = new WP_Query( array(
        'post_type'      => 'projects',
        'posts_per_page' => 5,
        'paged'          => $paged

    ) );

    if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

       the_title();

    endwhile;

        $total_pages = $query->max_num_pages;

        if ($total_pages > 1){

            $current_page = max(1, get_query_var('paged'));

            echo paginate_links(array(
                'base'      => get_pagenum_link(1) . '%_%',
                'format'    => '/page/%#%',
                'current'   => $current_page,
                'total'     => $total_pages,
                'prev_text' =>  esc_html__('volgende »', 'infrafocus'),
                'next_text' =>  esc_html__('« vorige' , 'infrafocus'),
            ));
        }

    }

    wp_reset_postdata();

    endif;
</code>```

答:
Sometimes in the case of Custom post type pagination, you have to add the rewrite rule in your function.php
Add Function like:

```<code>function custom_rewrite_basic() {
  add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php/projects?page=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');
</code>```

Please Refer this link for more information : https://codex.wordpress.org/Rewrite_API/add_rewrite_rule

Body:
Working with custom post types I cant seem to get the pagination to work correct. All is working but when I click to the next page the url will get a extra slash in the url, not sure why this is happening but when using the pagination a lot will add every time a new slash to the url.

// out

site.com/projects/ ,
site.com/projects//page/2,
site.com/projects///page/3,
site.com/projects////page/4

...and so on.

// the code used

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

    $query = new WP_Query( array(
        'post_type'      => 'projects',
        'posts_per_page' => 5,
        'paged'          => $paged

    ) );

    if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

       the_title();

    endwhile;

        $total_pages = $query->max_num_pages;

        if ($total_pages > 1){

            $current_page = max(1, get_query_var('paged'));

            echo paginate_links(array(
                'base'      => get_pagenum_link(1) . '%_%',
                'format'    => '/page/%#%',
                'current'   => $current_page,
                'total'     => $total_pages,
                'prev_text' =>  esc_html__('volgende »', 'infrafocus'),
                'next_text' =>  esc_html__('« vorige' , 'infrafocus'),
            ));
        }

    }

    wp_reset_postdata();

    endif;

Body:
Sometimes in the case of Custom post type pagination, you have to add the rewrite rule in your function.php
Add Function like:

function custom_rewrite_basic() {
  add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php/projects?page=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');

Please Refer this link for more information : https://codex.wordpress.org/Rewrite_API/add_rewrite_rule


问:
How can I get an album URL from the Picasa API?
I really don't like the Picasa feed-oriented API. Why couldn't they create a REST interface?

Does anyone know how I can get the URL for a particular album? For example, say I have:

```<code>gd_client = gdata.photos.service.PhotosService()
albums = gd_client.GetUserFeed(user="user@gmail.com")
album = albums.entry[0]
</code>```

How can I find its URL? I am looking for something like:

```<code>http://picasaweb.google.com/username/AlbumTitle
</code>```

so that when I click on it, it will take me to Picasa to view that album!

PS: Note that you cannot just put the album.title there because it might contain spaces, and it's not really the same.

答: Get the album URL by going to http://picasaweb.google.com/[username]/[album title].

Body:
I really don't like the Picasa feed-oriented API. Why couldn't they create a REST interface?

Does anyone know how I can get the URL for a particular album? For example, say I have:

gd_client = gdata.photos.service.PhotosService()
albums = gd_client.GetUserFeed(user="user@gmail.com")
album = albums.entry[0]

How can I find its URL? I am looking for something like:

http://picasaweb.google.com/username/AlbumTitle

so that when I click on it, it will take me to Picasa to view that album!

PS: Note that you cannot just put the album.title there because it might contain spaces, and it's not really the same.


问:
Writing content into txt file python
Here I am writing some content to text file in python,when I try running this without writing a function, it runs well and I get the desired result but when I try applying a def function(): the same doesn't happen.Any help would be useful to learn.</p>

```<code>def fu(self):
    self.xmldoc = minidom.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.tree = ET.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.root = self.tree.getroot()
    self.validate_model = self.xmldoc.getElementsByTagName('MODEL')
    self.extract_model = self.validate_model[0].firstChild.nodeValue
    # print("hi "+extract_model[len(extract_model)-1:])
    self.headerlist = self.xmldoc.getElementsByTagName('HW_VERSION')
    self.validate_header = self.headerlist[0].firstChild.nodeValue
    # print("HW_VERSION: " + validate_header)
    # print("Length of HW_VERSION: " + str(len(validate_header)))
    if re.match('^[A-Za-z][A-Za-z0-9.]*$', self.validate_header):
        print("The HW_VERSION is valid")
    else:
        print("Sorry")
        self.save_path = "C:\\Users\\c\\Downloads\\errors"
        self.name_of_file = "Error_log1"
        self.completeName = os.path.join(self.save_path,
        self.name_of_file + ".txt")
        file1 = open(self.completeName, 'rw')
        file1.write("Error Log file created at " + "\n")
        file1.write(str(datetime.datetime.now()) + "\n")
        file1.write("-------------------------------------" + "\n")
    file1.close()
</code>```

答: If you have self as a parameter, that means you are in a python class, since you didn't actually pass in a value for self when you called fu. You should either declare a class object and call the fu method from that, or pass in a value for the self parameter (most likely your file/directory/path).</p>

Title: Writing content into txt file python

Body:
Here I am writing some content to text file in python,when I try running this without writing a function, it runs well and I get the desired result but when I try applying a def function(): the same doesn't happen.Any help would be useful to learn.

def fu(self):
    self.xmldoc = minidom.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.tree = ET.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.root = self.tree.getroot()
    self.validate_model = self.xmldoc.getElementsByTagName('MODEL')
    self.extract_model = self.validate_model[0].firstChild.nodeValue
    # print("hi "+extract_model[len(extract_model)-1:])
    self.headerlist = self.xmldoc.getElementsByTagName('HW_VERSION')
    self.validate_header = self.headerlist[0].firstChild.nodeValue
    # print("HW_VERSION: " + validate_header)
    # print("Length of HW_VERSION: " + str(len(validate_header)))
    if re.match('^[A-Za-z][A-Za-z0-9.]*$', self.validate_header):
        print("The HW_VERSION is valid")
    else:
        print("Sorry")
        self.save_path = "C:\\Users\\c\\Downloads\\errors"
        self.name_of_file = "Error_log1"
        self.completeName = os.path.join(self.save_path,
        self.name_of_file + ".txt")
        file1 = open(self.completeName, 'rw')
        file1.write("Error Log file created at " + "\n")
        file1.write(str(datetime.datetime.now()) + "\n")
        file1.write("-------------------------------------" + "\n")
    file1.close()


问:
jQuery Alert if paragraph is selected and has specific class
I have html code like below.

```<code><div id='p1' class='thread'>
<p>First Paragraph</p>
<p>Abbot and Costello - Africa Screams</p>
</div>

<div id='p2' class='thread selected'>
<p>Second Paragraph</p>
<p class='flag'>Abbot and Costello - Frank/Meet</p>
</div>

<div id='p3' class='thread'>
<p>Third Paragraph</p>
<p>addin</p>
</div>

<div id='p4' class='thread'>
<p>Forth Paragraph</p>
<p>Begins</p>
</div>
</code>```

Every time user clicks on paragraph new class "selected" is added and previous one is removed.

I want to alert('flag'); if a
 has class selected and
 has class flag like in Second Paragraph.

how can I achieve this using "jQuery".

any help is appreciated, Thanks.

答:
In the click handler you need to check if the clicked div.thread has selected class and test if it contains a paragraph with class="flag" using .find('p.flag').

This is how should be your code:

```<code>$('div.thread').on('click', function() {
  if($(this).hasClass("selected") && $(this).find('p.flag')) {
    alert('flag');
  }
});
</code>```

Demo:

$('div.thread').on('click', function() {
  if($(this).hasClass("selected") && $(this).find('p.flag')) {
    alert('flag');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected{
  color:orange;
}</code>```

First Paragraph

Abbot and Costello - Africa Screams

Second Paragraph

Abbot and Costello - Frank/Meet

Third Paragraph

addin

Forth Paragraph

Begins

```

Body:
I have html code like below.

First Paragraph

Abbot and Costello - Africa Screams

Second Paragraph

Abbot and Costello - Frank/Meet

Third Paragraph

addin

Forth Paragraph

Begins

Every time user clicks on paragraph new class "selected" is added and previous one is removed.

I want to alert('flag'); if a
 has class selected and
 has class flag like in Second Paragraph.

how can I achieve this using "jQuery".

any help is appreciated, Thanks.

Body:
In the click handler you need to check if the clicked div.thread has selected class and test if it contains a paragraph with class="flag" using .find('p.flag').

This is how should be your code:

$('div.thread').on('click', function() {
  if($(this).hasClass("selected") && $(this).find('p.flag')) {
    alert('flag');
  }
});

Demo:

$('div.thread').on('click', function() {
  if($(this).hasClass("selected") && $(this).find('p.flag')) {
    alert('flag');
  }
});

.selected{
  color:orange;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='p1' class='thread'>
  <p>First Paragraph</p>
  <p>Abbot and Costello - Africa Screams</p>
</div>

<div id='p2' class='thread selected'>
  <p>Second Paragraph</p>
  <p class='flag'>Abbot and Costello - Frank/Meet</p>
</div>

<div id='p3' class='thread'>
  <p>Third Paragraph</p>
  <p>addin</p>
</div>

<div id='p4' class='thread'>
  <p>Forth Paragraph</p>
  <p>Begins</p>
</div>


问:
How to match payload in POST request
I've got a GET request like this:

```<code><FORM action='vieweto0.php' method='POST'>
  <SELECT name='ID_Profil'>
    <OPTION value=3> blank3</OPTION>
    <OPTION value=2> blank2</OPTION>
    <OPTION value=4>blank4</OPTION>
  </SELECT>
  <br><input type='submit' type=hidden name='OK' value='choose this one'>
</FORM>
</code>```

How my POST request should look like if I want to choose OPTION 'blank4'?

Where I can read more about POST request like this?

答:
If you use python requests:

```<code>import requests
res = requests.post("http://hostaddress/vieweto0.php", data={"ID_Profil":4})
</code>```

POST or GET requests are basically sending key-value pairs to the server.

Learn more about http POST on https://www.w3schools.com/html/default.asp and how requests work on this: http://docs.python-requests.org/en/master/user/quickstart/. If you are interested in the details of POST, you can read this: https://www.rfc-editor.org/rfc/rfc7231#section-4.3.3.

Title: How to match payload in POST request

Body:
I've got a GET request like this:

<FORM action='vieweto0.php' method='POST'>
  <SELECT name='ID_Profil'>
    <OPTION value=3> blank3</OPTION>
    <OPTION value=2> blank2</OPTION>
    <OPTION value=4>blank4</OPTION>
  </SELECT>

<input type='submit' type=hidden name='OK' value='choose this one'>
</FORM>

How my POST request should look like if I want to choose OPTION 'blank4'?

Where I can read more about POST request like this?

Body:
If you use python requests:

import requests
res = requests.post("http://hostaddress/vieweto0.php", data={"ID_Profil":4})

POST or GET requests are basically sending key-value pairs to the server.

Learn more about http POST on https://www.w3schools.com/html/default.asp and how requests work on this: http://docs.python-requests.org/en/master/user/quickstart/. If you are interested in the details of POST, you can read this: https://www.rfc-editor.org/rfc/rfc7231#section-4.3.3.


问:
Android jTreeMap visual
I need something special.

http://prefuse.org/gallery/treemap/

i need this, for android, is there a way to do it? how?

答:
Port it from Swing to Android's UI framework, using the Android 2D drawing API (Canvas). The whole prefuse framework is large and would take quite some time to port.

An even better approach is to generate your treemap on a server, sending the resulting PNG file down to the Android app. Depending on how much data you are processing, building a treemap on an Android phone could take quite some time, longer than the user wants to sit there.

Also, bear in mind that a traditional treemap is really designed for larger screens than most Android devices have, and so usability may be a problem.

Title: Android jTreeMap visual


问:
Python Importing with OOP
This question concerns when you should have imports for Python modules and how it all interacts when you are trying to take an OOP approach to what you're making.

Let's say we have the following Modules:

ClassA.py:

```<code>class Class_A:

    def doSomething(self):
        #doSomething
</code>```

ClassB.py

```<code>class Class_B:

    def doSomethingElse(self):
        #doSomethingElse
</code>```

ClassC.py

```<code>class Class_C:

    def __init__(self, ClassAobj, ClassBobj):
        self.a = ClassAobj
        self.b = ClassBobj

    def doTheThing(self):
        self.a.doSomething()
        self.b.doSomethingElse()
</code>```

Main.py:

```<code>from ClassA import Class_A
from ClassB import Class_B
from ClassC import Class_C

a = Class_A()
b = Class_B()
c = Class_C(a,b)
</code>```

In here Class_C uses objects of Class_A and Class_B however it does not have import statements for those classes.  Do you see this creating errors down the line, or is this fine?  Is it bad practice to do this?

Would having imports for Class_A and Class_B inside of Class_C cause the program as a whole to use more memory since it would be importing them for both Main.py and ClassC.py?  Or will the Python compiler see that those modules have already been imported and just skip over them?

I'm just trying to figure out how Python as a language ticks with concerns to importing and using modules.  Basically, if at the topmost level of your program (your Main function) if you import everything there, would import statements in other modules be redundant?

答:
C does not need the import statements; all it uses is a pair of object handles (i.e. pointers).  As long as it does not try to access any method or attribute of those objects, the pure assignment is fine.  If you do need such additions, then you need the import statements.

This will not cause additional memory usage in Main: Python checks (as do most languages) packages already imported, and will not import one multiple times.  Note that this sometimes means that you have to be careful of package dependencies and importation order.

Title: Python Importing with OOP

Body:
This question concerns when you should have imports for Python modules and how it all interacts when you are trying to take an OOP approach to what you're making.

Let's say we have the following Modules:

ClassA.py:

class Class_A:

    def doSomething(self):
        #doSomething

ClassB.py

class Class_B:

    def doSomethingElse(self):
        #doSomethingElse

ClassC.py

class Class_C:

    def __init__(self, ClassAobj, ClassBobj):
        self.a = ClassAobj
        self.b = ClassBobj

    def doTheThing(self):
        self.a.doSomething()
        self.b.doSomethingElse()

Main.py:

from ClassA import Class_A
from ClassB import Class_B
from ClassC import Class_C

a = Class_A()
b = Class_B()
c = Class_C(a,b)

In here Class_C uses objects of Class_A and Class_B however it does not have import statements for those classes.  Do you see this creating errors down the line, or is this fine?  Is it bad practice to do this?

Would having imports for Class_A and Class_B inside of Class_C cause the program as a whole to use more memory since it would be importing them for both Main.py and ClassC.py?  Or will the Python compiler see that those modules have already been imported and just skip over them?

I'm just trying to figure out how Python as a language ticks with concerns to importing and using modules.  Basically, if at the topmost level of your program (your Main function) if you import everything there, would import statements in other modules be redundant?


问:
GDB/LLDB break at all functions of specified module/shared library
In lldb, I got help breakpoint set:

```<code>       -a <address-expression> ( --address <address-expression> )
        Set the breakpoint at the specified address.  If the address maps uniquely to a particular binary, then the address will be converted to a "file" address, so that the
        breakpoint will track that binary+offset no matter where the binary eventually loads.  Alternately, if you also specify the module - with the -s option - then the
        address will be treated as a file address in that module, and resolved accordingly.  Again, this will allow lldb to track that offset on subsequent reloads.  The
        module need not have been loaded at the time you specify this breakpoint, and will get resolved when the module is loaded.
</code>```

and

```<code>       -r <regular-expression> ( --func-regex <regular-expression> )
        Set the breakpoint by function name, evaluating a regular-expression to find the function name(s).
</code>```

and

```<code>   -s <shlib-name> ( --shlib <shlib-name> )
        Set the breakpoint only in this shared library.  Can repeat this option multiple times to specify multiple shared libraries.
</code>```

Now I want to set breakpoints at every function of specified module/dylib that you can find in the results of command image list -f.

Take libobjc.A.dylib and MyOwn.dylib as examples. I tried following commands but failed:

```<code>(lldb) breakpoint set -r libobjc.A.dylib
Breakpoint 1: no locations (pending).
WARNING:  Unable to resolve breakpoint to any actual locations.

(lldb) b +[ThunderManager load]
Breakpoint 2: where = MyOwn.dylib`+[ThunderManager load] +16 at ThunderManager.m:20, address = 0x000000010489f274

(lldb) breakpoint set -r MyOwn.dylib`*
Breakpoint 3: no locations (pending).
WARNING:  Unable to resolve breakpoint to any actual locations.
</code>```

I want lldb get break at all functions of module libobjc.A.dylib or MyOwn.dylib, or any other specified loaded module/shared library. How to set the breakpoints in lldb?

答:
```<code>(lldb) break set -r . -s libobjc.A.dylib
</code>```

The -s option takes a shared library as its value, and that limits the breakpoint to the specified shared library.  You can specify the -s option more than once to specify more than one shared library for inclusion in the breakpoint search.

The -r option's value is a regular expression; if the symbol name matches that expression, it will be included in the breakpoint.  . matches everything.

The lldb tutorial:

http://lldb.llvm.org/tutorial.html

starts with a description of the structure of lldb commands that you might find helpful.

Body:
In lldb, I got help breakpoint set:

       -a <address-expression> ( --address <address-expression> )
        Set the breakpoint at the specified address.  If the address maps uniquely to a particular binary, then the address will be converted to a "file" address, so that the
        breakpoint will track that binary+offset no matter where the binary eventually loads.  Alternately, if you also specify the module - with the -s option - then the
        address will be treated as a file address in that module, and resolved accordingly.  Again, this will allow lldb to track that offset on subsequent reloads.  The
        module need not have been loaded at the time you specify this breakpoint, and will get resolved when the module is loaded.

and

       -r <regular-expression> ( --func-regex <regular-expression> )
        Set the breakpoint by function name, evaluating a regular-expression to find the function name(s).

and

   -s <shlib-name> ( --shlib <shlib-name> )
        Set the breakpoint only in this shared library.  Can repeat this option multiple times to specify multiple shared libraries.

Now I want to set breakpoints at every function of specified module/dylib that you can find in the results of command image list -f.

Take libobjc.A.dylib and MyOwn.dylib as examples. I tried following commands but failed:

(lldb) breakpoint set -r libobjc.A.dylib
Breakpoint 1: no locations (pending).
WARNING:  Unable to resolve breakpoint to any actual locations.

(lldb) b +[ThunderManager load]
Breakpoint 2: where = MyOwn.dylib`+[ThunderManager load] +16 at ThunderManager.m:20, address = 0x000000010489f274

(lldb) breakpoint set -r MyOwn.dylib`*
Breakpoint 3: no locations (pending).
WARNING:  Unable to resolve breakpoint to any actual locations.

I want lldb get break at all functions of module libobjc.A.dylib or MyOwn.dylib, or any other specified loaded module/shared library. How to set the breakpoints in lldb?

Body:
(lldb) break set -r . -s libobjc.A.dylib

The -s option takes a shared library as its value, and that limits the breakpoint to the specified shared library.  You can specify the -s option more than once to specify more than one shared library for inclusion in the breakpoint search.

The -r option's value is a regular expression; if the symbol name matches that expression, it will be included in the breakpoint.  . matches everything.

The lldb tutorial:

http://lldb.llvm.org/tutorial.html

starts with a description of the structure of lldb commands that you might find helpful.


问:
Compute intersection coordinates of two vectors moving on different speeds
The red dot is moving at speed 400 in direction of the green dot.

I want to move the yellow dot to the coordinates of the red dot after the time needed for the yellow dot to reach the position.

In other words, I want the yellow dot to intercept the red one to make them overlap before the red dot reaches the green dot coordinates.

I'm using this function to get the distance between dots:

```<code>function getDistance(a, b) {
    return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}
</code>```

And this one to normalize the distances taking into account the speeds:

```<code>function normalizeDistance(distance, speed) {
    return distance / speed;
}
</code>```

But I can't find out how to obtain the information I need.

I logically know the coordinates of the 3 dots and I know that the red dot is going to head in the coordinates of the green one.

The green dot is static.

How can I do?

Edit:

To clarify, here's simpler examples for the same problem:

答:
One option is to narrow it down until you get a "close enough" answer.

First figure out how long it takes for Yellow to get to where Red is. In that time, Red will of course have travelled towards Green, but that's fine.

Figure out how long it will take if Yellow had gone for where Red ended up.

This might be longer (if Red is moving generally away from Yellow) or it might be shorter (if Red is moving generally towards Yellow).

Either way, use this to figure out where Red ended up and get a new target. Keep adjusting towards the new target until you get "close enough" to Red that's acceptable.

Demo with configuration options available

The general idea will be (pseudocode):

```<code>epsilon = 0.01
red_angle = Math.atan2(green.y - red.y, green.x - red.x)

target = {x:red.x, y:red.y}
distance = pythagoras(target.x - yellow.x, target.y - yellow.y)
time = distance / yellow.speed
redmoved = time * red.speed
newtarget = {
  x: red.x + redmoved * Math.cos(red_angle),
  y: red.y + redmoved * Math.sin(red_angle)
}
delta = pythagoras(target.x - newtarget.x, target.y - newtarget.y)
// repeat while delta > epsilon or after a reasonable maximum number of steps
</code>```

Body:
The red dot is moving at speed 400 in direction of the green dot.

I want to move the yellow dot to the coordinates of the red dot after the time needed for the yellow dot to reach the position.

In other words, I want the yellow dot to intercept the red one to make them overlap before the red dot reaches the green dot coordinates.

I'm using this function to get the distance between dots:

function getDistance(a, b) {
    return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}

And this one to normalize the distances taking into account the speeds:

function normalizeDistance(distance, speed) {
    return distance / speed;
}

But I can't find out how to obtain the information I need.

I logically know the coordinates of the 3 dots and I know that the red dot is going to head in the coordinates of the green one.

The green dot is static.

How can I do?

Edit:

To clarify, here's simpler examples for the same problem:

Body:
One option is to narrow it down until you get a "close enough" answer.

First figure out how long it takes for Yellow to get to where Red is. In that time, Red will of course have travelled towards Green, but that's fine.

Figure out how long it will take if Yellow had gone for where Red ended up.

This might be longer (if Red is moving generally away from Yellow) or it might be shorter (if Red is moving generally towards Yellow).

Either way, use this to figure out where Red ended up and get a new target. Keep adjusting towards the new target until you get "close enough" to Red that's acceptable.

Demo with configuration options available

The general idea will be (pseudocode):

epsilon = 0.01
red_angle = Math.atan2(green.y - red.y, green.x - red.x)

target = {x:red.x, y:red.y}
distance = pythagoras(target.x - yellow.x, target.y - yellow.y)
time = distance / yellow.speed
redmoved = time * red.speed
newtarget = {
  x: red.x + redmoved * Math.cos(red_angle),
  y: red.y + redmoved * Math.sin(red_angle)
}
delta = pythagoras(target.x - newtarget.x, target.y - newtarget.y)
// repeat while delta > epsilon or after a reasonable maximum number of steps


Title: Pandas: divide data to 15min period

Body:
I have dataframe and date looks like

event_time
2017-01-17 00:12:50
2016-12-05 01:00:21
2016-12-04 01:14:36
2016-12-04 01:04:03
2016-12-04 02:28:23
2016-12-04 02:46:49
2016-12-04 01:58:04

I need to get column period, where 15 min starts from 00:00:00 and day, month and year don't important.
time in 00:00:00 - 00:15:00 - period 1
00:15:01 - 00:50:00 - period 2, etc.
If I use df = df.groupby(pd.TimeGrouper(freq='15Min')) it works wrong, because it use also day. But I need to use only time.

Desire output

event_time            period
2017-01-17 00:12:50   1
2016-12-05 01:00:21   4
2016-12-04 01:14:36   4
2016-12-04 01:04:03   4
2016-12-04 02:28:23   10
2016-12-04 02:46:49   12
2016-12-04 01:58:04   8

How can I do that?

Body:
df = pd.DataFrame(pd.to_datetime([
    "2017-01-17 00:12:50",
    "2016-12-05 01:00:21",
    "2016-12-04 01:14:36",
    "2016-12-04 01:04:03",
    "2016-12-04 02:28:23",
    "2016-12-04 02:46:49",
    "2016-12-04 01:58:04"]),
    columns=['timestamp']
    )

and then period column

df['period'] = df.timestamp.apply(lambda ts: 1 + ts.hour * 4 + ts.minute // 15)

which gives following input:

            timestamp  period
0 2017-01-17 00:12:50       1
1 2016-12-05 01:00:21       5
2 2016-12-04 01:14:36       5
3 2016-12-04 01:04:03       5
4 2016-12-04 02:28:23      10
5 2016-12-04 02:46:49      12
6 2016-12-04 01:58:04       8

There is small discrepancy between your and mine output - rows 1, 2 and 3: for example 01:00:21 should be 5 because there are four periods in first hour and 5th just begun.


问:
How to shut down the host from within the container?
I'm writing a UPS monitoring console application that will automatically shut down the server when the UPS battery reaches a predefined level of charge during a power outage.

I'd like to run this within a container if possible, as NUT (Network UPS Tools) is notoriously difficult to get working on a Windows system. I've configured it once, on bare metal, and I wish not to have to endure that pain a second time, or worse, a third. (But that's another discussion for another day.)

Back to today: how may I send a system shutdown command to the container's host? I've tried simply shutdown /s /t 0, but that shuts down the container. I need to reach the host.

--NOTE TO CLOSE VOTERS--

This question is not off-topic. Note this Q&A, for one example, which currently bears upvotes numbering well over 2,000. There isn't a single programming concept mentioned in the question.

Docker is a tool used by developers. So its subject matter is very relevant on this forum. Run a quick query on the docker tag and you'll see what I mean.

答:
An approach that involves a little bit of programming would be to create a small service that sits on the host and waits for incoming connections.

That service could then either execute the shutdown command or call the appropriate Windows API call.

I suggest giving this service a minimal http endpoint with a single URL and protect it with user / password and SSL/TLS.

You would then call this from the container using curl --user user:pass  https://host/shutdown

It should be fairly easy to implement this with golang and nssm.


答: Importing a module does two things: it executes the code stored in the module, and it adds name bindings to the module doing the importing. ClassC.py doesn't need to import ClassA or ClassB because it doesn't know or care what types the arguments to ClassC.__init__ have, as long as they behave properly when used. Any references to code needed by either object is stored in the object itself.

Title: Python Importing with OOP