text:
Q: Deserializing an array with System.Text.Json It is possible to deserialize an array with Json.NET. How can I deserialize the following JSON using System.Text.Json?
JSON
[340,{"a":["21040.00000",0,"0.00500000"],"b":["21037.70000",0,"0.49900000"],"c":["21039.00000","0.06009660"],"v":["660.49276224","3641.23932460"],"p":["20783.06665","20853.16080"],"t":[6207,22883],"l":["20500.10000","20500.10000"],"h":["21052.40000","21528.70000"],"o":["20716.30000","21416.30000"]},"ticker","XBT/USD"]

Json.NET way
[JsonConverter(typeof(ArrayConverter))]
public class KrakenSocketEvent<T>
{
    [ArrayProperty(0)]
    public int ChannelId { get; set; }

    [ArrayProperty(1)]
    [JsonConversion]
    public T Data { get; set; } = default!;

    [ArrayProperty(2)]
    public string Topic { get; set; } = string.Empty;

    [ArrayProperty(3)]
    public string Symbol { get; set; } = string.Empty;
}

Edit
What I currently have is the following. The issue is with the typeparam. I'm getting a compile time error.
[JsonConverter(typeof(JsonNumberHandlingPlainArrayConverter<KrakenSocketEvent<T>>))] // Attribute argument cannot use type parameters
public record KrakenSocketEvent<T> where T : new()
{
    [JsonPlainArrayIndex(0)]
    public int ChannelId { get; init; }

    [JsonPlainArrayIndex(1)]
    public T Data { get; init; } = default!;

    [JsonPlainArrayIndex(2)]
    public string Topic { get; init; } = null!;

    [JsonPlainArrayIndex(3)]
    public string Symbol { get; init; } = null!;
}

public sealed class JsonNumberHandlingPlainArrayConverter<T> : JsonPlainArrayConverter<T> where T : new()
{
    protected override JsonSerializerOptions CustomizePropertyOptions(PropertyInfo info, JsonSerializerOptions options)
    {
        return new JsonSerializerOptions(options)
        {
            NumberHandling = JsonNumberHandling.AllowReadingFromString
        };
    }
}

[AttributeUsage(AttributeTargets.Property)]
public sealed class JsonPlainArrayIndexAttribute : Attribute
{
    public JsonPlainArrayIndexAttribute(int index)
    {
        Index = index;
    }

    public int Index { get; }
}

public class JsonPlainArrayConverter<T> : JsonConverter<T> where T : new()
{
    protected virtual JsonSerializerOptions CustomizePropertyOptions(PropertyInfo info, JsonSerializerOptions options)
    {
        return options;
    }

    public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        Debug.Assert(typeof(T) == typeToConvert);

        var props = typeToConvert.GetProperties();
        var linq = from prop in props
            let attr = prop.GetCustomAttributes(typeof(JsonPlainArrayIndexAttribute), true)
            where prop.CanWrite && attr.Length is 1
            orderby ((JsonPlainArrayIndexAttribute)attr[0]).Index
            select prop;

        var arr = JsonSerializer.Deserialize<IEnumerable<JsonElement>>(ref reader, options);
        if (arr is null)
        {
            return default;
        }

        var result = new T();
        foreach (var (prop, value) in linq.Zip(arr))
        {
            prop.SetValue(result, value.Deserialize(prop.PropertyType, CustomizePropertyOptions(prop, options)));
        }

        return result;
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        var type = typeof(T);
        var props = type.GetProperties();
        var linq = from prop in props
            let attr = prop.GetCustomAttributes(typeof(JsonPlainArrayIndexAttribute), true)
            where prop.CanRead && attr.Length is 1
            orderby ((JsonPlainArrayIndexAttribute)attr[0]).Index
            select prop.GetValue(value);
        JsonSerializer.Serialize<IEnumerable<object>>(writer, linq, options);
    }
}

A: You can't use the generic T in your converter declaration, it's an unknown value. For this scenario, you would have to create a JsonConverterFactory instead so you can determine the type T then instantiate your real converter.
It would be easier to write if you had an interface to detect or some attribute  to tag with. Then you could write the factory to expect that. Then in your converter, let the serializer deal with how to handle serialization, just direct it on how to read/write values.
[JsonPlainArray(4)]
public record KrakenSocketEvent<T> where T : new()
{
    [JsonPlainArrayIndex(0)]
    public int ChannelId { get; init; }

    [JsonPlainArrayIndex(1)]
    public T Data { get; init; } = default!;

    [JsonPlainArrayIndex(2)]
    public string Topic { get; init; } = null!;

    [JsonPlainArrayIndex(3)]
    public string Symbol { get; init; } = null!;
}

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)]
public sealed class JsonPlainArrayAttribute : Attribute
{
    public JsonPlainArrayAttribute(int length) => Length = length;
    public int Length { get; }
}

[AttributeUsage(AttributeTargets.Property)]
public sealed class JsonPlainArrayIndexAttribute : Attribute
{
    public JsonPlainArrayIndexAttribute(int index) => Index = index;
    public int Index { get; }
}

public class JsonPlainArrayConverter : JsonConverterFactory
{
    public override bool CanConvert(Type typeToConvert)
    {
        return typeToConvert.GetConstructor(Type.EmptyTypes) != null // has default ctor
            && typeToConvert.GetCustomAttribute<JsonPlainArrayAttribute>() != null;
    }

    public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
    {
        var converterType = typeof(_JsonPlainArrayConverter<>).MakeGenericType(typeToConvert)!;
        var length = typeToConvert.GetCustomAttribute<JsonPlainArrayAttribute>()?.Length;
        var properties = typeToConvert.GetProperties()
            .Select((p, i) => (i, prop: p, attr: p.GetCustomAttribute<JsonPlainArrayIndexAttribute>()))
            .Where(x => x.i == x.attr?.Index)
            .OrderBy(x => x.i)
            .Select(x => x.prop)
            .ToArray();
        if (length is null || properties.Length != length)
            throw new Exception("bad configuration");
        return Activator.CreateInstance(converterType, (object)properties) as JsonConverter;
    }

    private class _JsonPlainArrayConverter<T> : JsonConverter<T>
        where T: new()
    {
        private readonly PropertyInfo[] properties;
        public _JsonPlainArrayConverter(PropertyInfo[] properties) => this.properties = properties;

        public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var arr = JsonSerializer.Deserialize<JsonElement[]>(ref reader, options);
            if (arr is null)
                return default;
            var result = new T();
            foreach (var x in properties.Zip(arr))
            {
                var value = x.Second.Deserialize(x.First.PropertyType, options);
                x.First.SetValue(result, value);
            }
            return result;
        }

        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            if (value is null)
            {
                writer.WriteNullValue();
                return;
            }
            writer.WriteStartArray();
            foreach (var prop in properties)
            {
                var val = prop.GetValue(value);
                JsonSerializer.Serialize(writer, val, prop.PropertyType, options);
            }
            writer.WriteEndArray();
        }
    }
}

Usage:
var options = new JsonSerializerOptions
{
    Converters =
    {
        new JsonPlainArrayConverter(),
    },
};
var obj = JsonSerializer.Deserialize<KrakenSocketEvent<YourType>>(json, options);


text:
Q: Azure storage REST API response includes BOM (" ) at that start of the XML file I am developing a custom vsts extension for a release task which have a picklist which has values populated from the REST endpoint data source ( my storage account ). I am following this blow link as reference.
https://learn.microsoft.com/en-us/vsts/extend/develop/service-endpoints?view=vsts
I have uploaded my extension but the picklist is not populating with values in the task.
Below are the configurations that I have done.
vss-extension.json:
    {
  "manifestVersion": 1,
  "id": "build-release-task",
  "name": "My Custom release task",
  "version": "0.0.1",
  "publisher": "custext",
  "public": false,
   "targets": [
  {
    "id": "Microsoft.VisualStudio.Services"
  }
  ],
  "description": "A picklist which has values populated from the REST
   endpoint data source. Includes one build/release task.",
   "categories": [
   "Build and release"
  ],
  "icons": {
  "default": "images/extension-icon.png"
  },
  "files": [
 {
 "path": "buildAndReleaseTask"
    }
   ],
 "contributions": [
   {
   "id": "service-endpoint",
   "description": "Service Endpoint type for custom Storage connection",
   "type": "ms.vss-endpoint.service-endpoint-type",
    "targets": [ "ms.vss-endpoint.endpoint-types" ],
   "properties": {
  "name": "custom",
  "displayName": "Custom server connection",
  "url": {
   "displayName": "Server Url",
   "helpText": "storage end point url."
   },
   "dataSources": [
   {
    "name": "Storage Account",
    "endpointUrl": "{{endpoint.url}}test/?restype=container&comp=list",
    "resultSelector": "xpath://EnumerationResults/Blobs/Blob/Name"
     }
    ],

   ]
   }

    ],
   "helpMarkDown": "Learn More"
   }

   },
    {
    "id": "custom-build-release-task",
    "type": "ms.vss-distributed-task.task",
    "description": "Task with a dynamic property getting data from an
   endpoint REST data source",
   "targets": [
   "ms.vss-distributed-task.tasks"
   ],
    "properties": {
     "name": "buildAndReleaseTask"
     }
   }
   ]

   }

task.json:
       {
        "id": "325958a0-63b7-11e6-88a5-f7c7f66e6264",
        "name": "dropdownlist",
        "friendlyName": "Drop down list",
        "description": "Lists the db files",
        "helpMarkDown": "Custom release task.Drop down list",
        "category": "Utility",
        "visibility": [
        "Release"
        ],
      "author": "satyam",
      "version": {
      "Major": 0,
      "Minor": 1,
      "Patch": 0
      },
        "instanceNameFormat": "dropdownlist $(message)",
        "groups": [
          {
           "name": "advanced",
           "displayName": "Advanced",
           "isExpanded": false
         }
       ],
        "inputs": [
           {
             "name": "CustomService",
              "type": "connectedService:custom",
              "label": "Storage end point",
              "defaultValue": "",
              "required": true,
              "helpMarkDown": "Select the storage account to use. If needed,
               click on 'manage', and add a new Service Endpoint of type
                 'Custom server connection'"
                },
             {
                 "name": "Scripts",
                 "type": "pickList",
                  "label": "saasscripts",
                  "required": true,
                 "helpMarkDown": "Select the name of the saas script.",
                 "properties": {
                 "EditableOptions": "True"
                    }
                  }
                 ],
                 "dataSourceBindings": [
                   {
                    "target": "Scripts",
                    "endpointId": "$(CustomService)",
                    "dataSourceName": "Storage Account"
                  }
                  ],
                 "outputVariables": [
                    {
                      "name": "dbfile",
                      "description": "Application URL of the selected App
                       Service."
                     }
                ],
                "execution": {
                "Node": {
                   "target": "powershell.js"
               }
             }
          }

endpointUrl: I tried with following ways in endpointUrl in datasources (vss-extension.json)

*

*{{endpoint.url}}test/?restype=container&comp=list
2.https://mycontainername.blob.core.windows.net/test/restype=container&comp=list
The picklist is not populated with the blob contents.
I guess problem in above issue might be unable to parse the azure storage blob list response type. the rest api response includes BOM (" ) at that start of the XML file which might be cause of the parsing.

Is there any way or workaround to change the azure blob rest api response to exclude BOM (" ) or changing the response to JSON format.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The order could not be processed with the reference code [xxx], PayU Laravel I am trying to get my signature for payu webcheckout implementation
I think the error is in the signature field, I have the api key defined in the controller
<form method="post" action="https://sandbox.checkout.payulatam.com/ppp-web-gateway-payu/">
  <input name="merchantId" type="text" value="508029">
  <input name="accountId" type="text" value="512321">
  <input name="description" type="text" value="{{ $plans->description }}">
  <input name="referenceCode" type="text" value="{{ $plans->id }}">
  <input name="amount" type="text" value="{{ $plans->price }}">
  <input name="tax" type="text" value="0">
  <input name="taxReturnBase" type="text" value="0">
  <input name="currency" type="text" value="COP">
  <input name="signature" type="text" value="md5($apy_key." ~ "."508029 "."~ ".$plans->id."~ ".$plans->price."~ "."COP ")">
  <input name="test" type="text" value="1">
  <input name="buyerEmail" type="text" value="test@test.com">
  <input name="responseUrl" type="text" value="https://poligonourbano.soluttolabs.com/">
  <input name="confirmationUrl" type="text" value="http:// www.test.com/confirmation">
  <input name="Submit" type="submit" value="Enviar">
</form>

Controller function:
public function planView() {
  $apy_key = "4Vj8eK4rloUd272L48hsrarnUA";
  $plans = Plan::findOrFail(2);

  return view('plans', compact('plans', 'apy_key'));
}

A: The problem is indeed coming from the way you are creating the signature
when you put md5($apy_key."~"."508029"."~".$plans->id."~".$plans->price."~"."COP") in "" it is considered as a string you should wrap the md5 with {{ }}.
Please try to create the signature in the controller and pass it as a value to the view, it is not a best practice to handle any logic in the view.


text:
Q: Using Cases for currency conversion in oracle I have two tables
Payments_history

CREATE TABLE payments_history(payment_date , account_id , currency, amount) AS
SELECT  TO_DATE ('05/01/2022','DD/MM/YYYY'), 2291969088, 'GBP', 10.00  FROM DUAL UNION ALL
SELECT TO_DATE ('05/01/2022','DD/MM/YYYY'), 7851880663, 'USD', 20  FROM DUAL UNION ALL
SELECT  TO_DATE ('06/01/2022','DD/MM/YYYY'), 5326844767, 'USD', 3.000  FROM DUAL UNION ALL
SELECT  TO_DATE ('05/01/2022','DD/MM/YYYY'), 3668657617, 'EUR', 40  FROM DUAL UNION ALL
SELECT  TO_DATE ('06/01/2022','DD/MM/YYYY'), 9040142052, 'GBP', 30.000  FROM DUAL

Historics_rates

Create TABLE Historics_rates(t_date,from_ccy,to_ccy,rate) AS
SELECT  TO_DATE ('06/01/2022','DD/MM/YYYY'),'GBP','EUR',1.1832 FROM DUAL UNION ALL
SELECT  TO_DATE ('06/01/2022','DD/MM/YYYY'),'AUD','GBP',0.5263 FROM DUAL UNION ALL
SELECT  TO_DATE ('06/01/2022','DD/MM/YYYY'),'EUR','GBP',0.8452 FROM DUAL UNION ALL
SELECT  TO_DATE ('05/01/2022','DD/MM/YYYY'),'USD','GBP',0.7388 FROM DUAL UNION ALL
SELECT  TO_DATE ('05/01/2022','DD/MM/YYYY'),'EUR','USD',1.1441 FROM DUAL

what I am trying to find is the 'daily amount GBP Equivalent per day for the last three months'. For example on date '05/01/2022 ' check the given amount in Payments_history table if the currency is GBP add it into total and move on to the next payment, next if the currency is in USD check for its equivalent in GBP rate and convert it into GBP and print the result. If the amount is in some currency whose from_ccy is not GBP skip that transaction
Date           Amount in GBP
2022-01-05        24.78

This is what I have done so far
DECLARE

total NUMBER;

BEGIN
select PH.PAYMENT_DATE,
CASE
            WHEN PH.CURRENCY = 'GBP' THEN total = total + PH.AMOUNT
            WHEN PH.CURRENCY = 'USD' AND HR.from_ccy = 'USD' AND HR.to_ccy = 'GBP' THEN total = total + (PH.AMOUNT*HR."rate")
            WHEN PH.CURRENCY = 'AUD' AND HR.from_ccy = 'AUD' AND HR.to_ccy = 'GBP' THEN total = total + (PH.AMOUNT*HR."rate")
            WHEN PH.CURRENCY = 'EUR' AND HR.from_ccy = 'EUR' AND HR.to_ccy = 'GBP' THEN total = total + (PH.AMOUNT*HR."rate")
            ELSE 'CURRENCY NOT FOUND'
            END AS total
FROM "historic_rates" AS HR RIGHT JOIN PAYMENTS_HISTORY AS PH on HR."date" = PH.payment_date AND PH.Currency = HR."from_ccy"
WHERE Extract(Month from PH.payment_date) = Extract(month from add_months( sysdate, -3 )) GROUP BY PH.PAYMENT_DATE;

but it's giving me error
[Err] ORA-06550: line 8, column 40:
PL/SQL: ORA-00905: missing keyword
ORA-06550: line 6, column 1:
PL/SQL: SQL Statement ignored
ORA-06550: line 15, column 117:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:

   ( begin case declare end exception exit for goto if loop mod
   null pragma raise return select update while with
   <an identifier> <a double-quot

A: Your errors include:

*

*Using = inside the THEN clause of a CASE expression is invalid syntax.

*You cannot refer to a column alias inside the sub-query where it is defined (except in an ORDER BY clause) so you cannot use total inside the CASE expression.

*A CASE expression needs to have the same data type in all of its outputs so you cannot mix numbers and strings.

*You GROUP BY PH.PAYMENT_DATE but you do not have any aggregation function around the CASE expression.

*If you do aggregate then 'CURRENCY NOT FOUND' is not something you can total.

*In Oracle, AS before a table alias is invalid syntax.

*You have a mix of quoted identifiers HR."from_ccy" and unquoted identifiers HR.from_ccy. While it is possible to have both in a table, one of them is almost certainly wrong (and using quoted identifiers is bad practice) and your DDL statements do not use quotes.

*Unless you really do intend to get rows from December of any year, do not compare only months. Compare on a range from the start of the month 3-months ago until before the start of the month two-months ago.

*Your PL/SQL block does not have an END statement.

*You are using a SELECT statement in PL/SQL without using SELECT ... INTO.

*You probably don't want to use PL/SQL.

*None of your sample data is from 3 months ago (December 2021).

Something like this:
select PH.PAYMENT_DATE,
       SUM(
         CASE
         WHEN PH.CURRENCY = 'GBP'
         THEN PH.AMOUNT
         WHEN PH.CURRENCY IN ('USD', 'AUD', 'EUR')
         AND  HR.from_ccy = PH.CURRENCY
         AND  HR.to_ccy = 'GBP'
         THEN PH.AMOUNT*HR.rate
         END
       ) As total
FROM   historics_rates HR
       RIGHT JOIN PAYMENTS_HISTORY PH
       on     HR.t_date = PH.payment_date
          AND PH.Currency = HR.from_ccy
WHERE  PH.payment_date >= ADD_MONTHS(TRUNC(SYSDATE, 'MM'), -3)
AND    PH.payment_date <  ADD_MONTHS(TRUNC(SYSDATE, 'MM'), -2)
GROUP BY PH.PAYMENT_DATE;

Which, for the sample data:
CREATE TABLE payments_history(payment_date , account_id , currency, amount) AS
SELECT TO_DATE ('05/12/2021','DD/MM/YYYY'), 2291969088, 'GBP', 10.00  FROM DUAL UNION ALL
SELECT TO_DATE ('05/12/2021','DD/MM/YYYY'), 7851880663, 'USD', 20  FROM DUAL UNION ALL
SELECT TO_DATE ('06/12/2021','DD/MM/YYYY'), 5326844767, 'USD', 3.000  FROM DUAL UNION ALL
SELECT TO_DATE ('05/12/2021','DD/MM/YYYY'), 3668657617, 'EUR', 40  FROM DUAL UNION ALL
SELECT TO_DATE ('06/12/2021','DD/MM/YYYY'), 9040142052, 'GBP', 30.000  FROM DUAL;

Create TABLE Historics_rates(t_date,from_ccy,to_ccy,rate) AS
SELECT  TO_DATE ('06/12/2021','DD/MM/YYYY'),'GBP','EUR',1.1832 FROM DUAL UNION ALL
SELECT  TO_DATE ('06/12/2021','DD/MM/YYYY'),'AUD','GBP',0.5263 FROM DUAL UNION ALL
SELECT  TO_DATE ('06/12/2021','DD/MM/YYYY'),'EUR','GBP',0.8452 FROM DUAL UNION ALL
SELECT  TO_DATE ('05/12/2021','DD/MM/YYYY'),'USD','GBP',0.7388 FROM DUAL UNION ALL
SELECT  TO_DATE ('05/12/2021','DD/MM/YYYY'),'EUR','USD',1.1441 FROM DUAL;

Outputs:

PAYMENT_DATE
TOTAL

06-DEC-21
30

05-DEC-21
24.776

db<>fiddle here


text:
Q: Retrieve value from dictionary from another class in swift Im trying to get the value from the following Dictionary in another Class, I tried "Getter.UserData", I keep getting "Getter.Type does not have member called UserData". How can I retrieve for example the value in UserData["username"] in another class?
Im trying to get my User details from php through Json, and to display it at the profile for the user's page. Is this the right approach?
class Getter{
var UserData: [String: String] = ["Username":"",
    "Profile Pic":"default.png",
    "Followers":"1",
    "Following":"2",
    "Glimps":"3"]

func ProfileDetails(){
DataManager.getJson{(Data) -> Void in
    let json = JSON(data: Data)
    self.UserData["Username"]=toString((json[0]["username"])) }
    }
}

A: You either need to make UserData a Type Property
static var UserData: [String: String] = [...]

so you can access it with
Getter.UserData["Username"]

or make an instance of the class and access its values:
let getter = Getter()
getter.UserData["Username"]


text:
Q: ActiveRecord many_to_many association instantiation returns uninitialized constant I have a list of categories in my database (validations not listed for brevity).
class Category < ActiveRecord::Base
  has_many :crimes_categories
  has_many :crimes, through: :crime_categories
end

I am seeding my database with crimes, some of which have multiple categories (validations not listed for brevity).
class Crime < ActiveRecord::Base
  belongs_to :team
  has_many :crime_categories
  has_many :categories, through: :crime_categories
end

These models are joined by a CrimeCategory model
class CrimeCategory < ActiveRecord::Base
  belongs_to :category
  belongs_to :crime
end

The seed file is iterating over a list of crime objects to format and add them to my database. I have tried a few different approaches. The first approach was to create CrimeCategory row.
seed.rb
count = 1
teamCrimeList.each do |crime|
  ...
  categories.each do |cat|
    ...
  end
  category_object = Category.where(name: category)
    crime_category_objects << category_object
    CrimeCategory.create(category_id: category_object.id, crime_id: count)

That last line would throw the following error
NameError: uninitialized constant CrimeCategory

Another strategy I tried was the following
seed.rb
teamCrimeList.each do |crime|
  ...
  categories.each do |cat|
    ...
  end
  category_object = Category.where(name: category)
    crime_category_objects << category_object
end
date = Date.parse(crime['Date'])
crime_object = Crime.create(team_id: team.id, date: date, name: crime['Name'], position: crime['Position'], encounter: crime['Encounter'], description: crime['Description'], outcome: crime['Outcome'])
crime_object.categories = crime_category_objects

which returns the same error
I also tried this approach
seed.rb
teamCrimeList.each do |crime|
  ...
  categories.each do |cat|
    ...
  end
  category_object = Category.where(name: category)
    crime_category_objects << category_object
end

date = Date.parse(crime['Date'])
Crime.create(team_id: team.id, categories: crime_category_objects.flatten, date: date, name: crime['Name'], position: crime['Position'], encounter: crime['Encounter'], description: crime['Description'], outcome: crime['Outcome'])

I threw in some pry's and tried calling crime.categories, all of which returns the same error.
I scoured stack overflow and nearly all the entries I came across on this issue have to do with naming errors but insofar as I can tell, there is no naming error.

A: @Glyoko had the right idea. I had named my CrimeCategory model file as
app/models/crimecategory.rb instead of app/models/crime_category.rb


text:
Q: jQuery child of clicked element I've got a list of links which have a click event attached to them, I need to get the ID from the child A link. So in the example below if I clicked the first list element I'd need google retuned.
I've tried '$this a' but can't quite work out the syntax.
$("ul li").click(function(event){
  $("input").val($(this).html());
});

Google

A: I don't see the sample HTML but
$(this).find('a:first').attr('id')

would do it (fix a:first selector if it's not what you meant)
this refer to the element that fired your event

A: To make your code a little neater, lets bind triggers with functions like so:
(i suggest you give your UL an ID so it is specific to only elements within that UL)
$('ul li').bind('click', getAnchorId);

The function that is called (getAnchorId) gets the ID attribute of the children element (a) of the clicked element (ul li) and applies it to a variable (anchorId), and to show its getting the correct info I put the result in an alert.
function getAnchorId() {
    var anchorId = $(this).children('a').attr('id');
    alert(anchorId);
}

Now u can do what ever u wish with that variable :)
hope this helps :)

A: You could use the children method:
$(this).children('a').eq(0).attr('id');

I'm not sure about the syntax, but something like this should work.


text:
Q: Correct syntax to check multiple strings while user agent check Is my syntax for checking multiple strings (existing of one of both strings) in a user agent correct?
I mean the part 'google|lighthouse'. If not, what should be the correct kind of writing?
<?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'google|lighthouse') === false): ?>
// code
<?php endif; ?>

A: I think you are not doing what you want to do. you are search for string 'google|lighthouse' inside the $_SERVER['HTTP_USER_AGENT'], I guess you want something like
<?php if (!isset($_SERVER['HTTP_USER_AGENT']) || (stripos($_SERVER['HTTP_USER_AGENT'], 'google') === false) || (stripos($_SERVER['HTTP_USER_AGENT'], 'lighthouse') === false): ?>
// code
<?php endif; ?>

A: You need to use regular expression for that, otherwise you are just looking for literal sequence of google|lighthouse:
<?php if (preg_match('/google|lighthouse/', $_SERVER['HTTP_USER_AGENT'] ?? '') !== 1): ?>
// code
<?php endif; ?>


text:
Q: Sorting Dictionary by value of key within a key I want to sort a dictionary by descending order by a value of a key within a key.
In my sample, I want to sort by little 'c'
Here is what I looks like now:
sample = {'A': {'a':22, 'b':24, 'c':80},
 'B': {'a':12, 'b':13, 'c':55},
 'C': {'a':44, 'b':33, 'c':99}
}

and here is my desired output:
sample = {'C': {'a':44, 'b':33, 'c':99},
 'A': {'a':22, 'b':24, 'c':80},
 'B': {'a':12, 'b':13, 'c':55}
}

I tried this bit of code by clearly its not right:
newdict = {}
for key, value in sorted(sample.items(), key=lambda item: item['c'], reverse=True):
     newdict[key] = value
sample = newdict

Thank you all for the help in solving this little puzzle!

A: You're close, the key function should be:
key=lambda item: item[1]['c']

Rewritten to be more Pythonic:
sample = dict(sorted(sample.items(), key=lambda item: item[1]['c'], reverse=True))

(The dict constructor can take an iterable of item tuples)


text:
Q: How to collectively send the parameter to a Python function and collect the result in list? I try to write a function func_apply(func_name, **kwargs) that receive the func_name and parameter values in list, then apply the parameter one by one to func_name , collect the result and return as a list. I need this high order function func_apply mainly to abstract the syntax, for my application often need to apply different parameter values to various functions and collect the result in a batch.
def my_minus(x,y):
    return x-y

def my_divd(a,b):
    return a/b

def func_apply(func_name, **kwargs):
    '''apply the parameter in kwargs one by one to func_name,
       collect and return result in a list.
       for example:
         func_apply(my_minus, x=[2, 4, 5, 7], y=[1, 4, 3, 9]) will return [1,0,2,-2],
         func_apply(my_divd,  a=[2, 4, 5, 7], b=[1, 4, 3, 9]) will return [2,1,1.66,0.77]
    '''
    # the codes

So, how to write the func_apply ?

A: You can use zip and a list comprehension:
kwargs is a dict here, as dicts don't have any fixed order so you may have to get a sorted list of values first based on the keys.
>>> from __future__ import  division   # not required in py3.x
def func_apply(func_name, **kwargs):
    vals = [kwargs[key] for key in sorted(kwargs)] #sort the keys lexicographically
    return [func_name(*x) for x in  zip(*vals)]
...
>>> func_apply(my_minus, x=[2, 4, 5, 7], y=[1, 4, 3, 9])
[1, 0, 2, -2]
>>> func_apply(my_divd,  a=[2, 4, 5, 7], b=[1, 4, 3, 9])
[2.0, 1.0, 1.6666666666666667, 0.7777777777777778]


text:
Q: Why do I get a 403 error when attempting to access AWS S3 from EC2 I am wanting to access S3 from a Spring Boot application using Spring Cloud AWS.  My access to S3 works fine from my desktop, but when I bundle the app up as a WAR file and deploy to an EC2 Tomcat container, I get an 403 exception:
Caused by: com.amazonaws.services.s3.model.AmazonS3Exception: Forbidden (Service: Amazon S3; Status Code: 403; Error Code: 403 Forbidden; Request ID: 4F0EBE3A853C6D99)
    at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1078) ~[aws-java-sdk-core-1.9.27.jar:na]
    at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:726) ~[aws-java-sdk-core-1.9.27.jar:na]
    at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:461) ~[aws-java-sdk-core-1.9.27.jar:na]
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:296) ~[aws-java-sdk-core-1.9.27.jar:na]
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3737) ~[aws-java-sdk-s3-1.9.27.jar:na]
    at com.amazonaws.services.s3.AmazonS3Client.getObjectMetadata(AmazonS3Client.java:1028) ~[aws-java-sdk-s3-1.9.27.jar:na]
    at org.springframework.cloud.aws.core.io.s3.SimpleStorageResource.getObjectMetadata(SimpleStorageResource.java:182) ~[spring-cloud-aws-core-1.0.2.RELEASE.jar:1.0.2.RELEASE]
    at org.springframework.cloud.aws.core.io.s3.SimpleStorageResource.exists(SimpleStorageResource.java:112) ~[spring-cloud-aws-core-1.0.2.RELEASE.jar:1.0.2.RELEASE]

I have an application.yml where I define access to AWS:
cloud:
    aws:
        region:
            static: eu-west-1
            auto: false
        credentials:
            accessKey: myaccesskey
            secretKey: somereallylongkeyhere
            instanceProfile: true

This works fine from my desktop.  What see do I need to do to make this work?  I have tried turning on every permission I can see within S3 but I can't seem to get around this.

A: I had a similar problem where the culprit was an outdated system clock. EC2 instances can sometimes drift and IAM API is very sensitive to it. Relevant information can be found here: https://github.com/boto/boto/issues/2885.


text:
Q: Cannot select sink for Oracle linked service from data flow I have a linked service that connects to an on-prem Oracle database through a self hosted integration runtime.
I am able to access this from a data factory pipeline - the dataset that uses the linked service is called pc_payinitil.

However, the pc_payinitial dataset is not available to select from the sink tab of a sink shape of a data flow:

Am I trying to do something that's not possible - or did I just go wrong somewhere?

A: Currently, the Oracle dataset is not supported in mapping data flow in the Azure data factory. It is only supported in copy activity source/sink and lookup activity.
There are only limited datasets that are supported in mapping data flow as of now. You can go through this MS document for more information on supported data stores in the Azure data factory.


text:
Q: SharePoint 2013 - calculated columns I want to know if there are any ressources from them I can take some functions for calculated columns in SharePoint. I found this article MS Site there are some functions, but not the functions NOW(), TODAY(). So my question is, is there a complete list of functions I can use for calculated columns?
Thanks!

A: Danny Engelman has a very good list for tested and tried functions for calculated column.
You can view the list here: http://www.viewmaster365.com/365coach/#/Calculated_Column_Functions_List

A: You cann't work with columns like Today() or Now() in calculated columns.
But calculated columns can be handy in many scenarios,
i.e. If you have fields like lets say, red, green, yellow indicators, you can easily use HTML in calculated columns to show, red, yellow or green images based on categories.
Also, you can play around with mathematical calculations based on other columns but one point to note that calculated columns only work with current row/ list item. they do not work with the values of different rows, it means you can't get summation or aggregations of values for calculated columns.

A: There's a great Dev Center resource that provides a list of Calculated Field Formulas. I've used it to calculate date values, do basic math, and concatenation.

A:
Calculated columns cannot contain volatile functions like Today and Me.

You can use Excel to built the formulas and use it in SharePoint.
Here is a walkthrough http://techtrainingnotes.blogspot.in/2010/08/sharepoint-creating-calculated-column.html?m=1


text:
Q: Create full mobile app vs Create app that goes to a server which handles mobile I have been playing around with PhoneGap for a little while, and getting it set up to work correctly with Google Drive API is proving to be far more difficult than setting up a website which does the same.
I am wondering if it would be more to my advantage to cease trying to make the full app work with phonegap, and instead use phonegap to access a hosted site.
Note that I do not wish to open the site in the default browser. The goal would be to make it appear to be an application (no borders, url, back button, etc), but have the web server handle everything behind the scenes.
I know PhoneGap has an In-App-Browser available. Is this something that is possible with it? Or does it only function for more limited use?
Thanks

A: You can definitely use a WebView for your app, which display the webpage but give you the ability to control the layout around it. Running a WebView instead of native code may cost some performance but it's doable.


text:
Q: want to schedule a job in windows slave for android project by using gradle as build tool In my Jenkins environment Linux as master and windows as slave. I want to build a job in windows slave machine for android project. I have installed android sdk and git and java and downloaded gradle in windows slave machine. How we can configure a build job and where we can provide that gradle path and android sdk path?

A: Use the Gradle Wrapper with your Gradle project, then you never need to install Gradle anywhere, as the Gradle wrapper bootstraps the Gradle distribution automatically.


text:
Q: How can I filter the domains served by a CDN from a list of domain names? I have a list of domains and I need to filter the domains served by a CDN(Content Delivery Network). I am going to use python script to do that.
At the first I was thinking I can identify them from the domain name. But not all of the domain names have cdn keyword.
Is there any reason or any feature in the CDN served domains which I use that for identifying CDN served domains?

A: First of all, you can't do it with 100% accuracy.
But you can identify domains using popular cloud providers in many cases by tracking CNAME records which would lead the respective provider's servers.
I.e. here's a doc on Amazon CloudFront http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html

In CloudFront, an alternate domain name, also known as a CNAME, lets
  you use your own domain name (for example, www.example.com) for links
  to your objects instead of using the domain name that CloudFront
  assigns to your distribution

Example:
dig -t CNAME c.amazon-adsystem.com
c.amazon-adsystem.com.  896     IN      CNAME   d1ykf07e75w7ss.cloudfront.net.


text:
Q: Pipelining setTimeout in node.js I am writing a node.js console application. I have two setTimeout functions as follows.
setTimeout(function(){
    process.stdout.write('\n\nJokes Apart !!!\n\n');
}, 2000);

setTimeout(function(){
    process.stdout.write('\n\nLet\'s play a game !!!\n\n');
}, 1000);

What I actually intend is, the first message should come after 2 seconds. After that, the second message should appear after 1 second. But what's happening is, the second message appears after 1 second and then the first message appears. Both the functions are being called at once as they are asynchronous. Is there any way to pipeline them?

A: setTimout() is not blocking in Javascript.  So, what you did is you scheduled two timers to run in the future.  One runs 1 second from now.  The other runs two seconds from now.  Thus, you get the behavior you observed.
You can either schedule the first one to run 2 seconds from now and then for one to go 1 second after that, you schedule it for 3 seconds from now.
setTimeout(function(){
    process.stdout.write('\n\nJokes Apart !!!\n\n');
}, 2000);

// schedule this one to be 3 seconds from now, which will be 1 second after the prior one
// since that one fired in 2 seconds
setTimeout(function(){
    process.stdout.write('\n\nLet\'s play a game !!!\n\n');
}, 3000);

Or, you can schedule the first one to run 2 seconds from now and then in that callback, you then schedule the next one to run 1 second from when the first one fires.
setTimeout(function(){
    process.stdout.write('\n\nJokes Apart !!!\n\n');
        // when the first timer fires, set a new timer to run the second
        // part one second from when the first one fired
        setTimeout(function(){
            process.stdout.write('\n\nLet\'s play a game !!!\n\n');
        }, 1000);
}, 2000);

This non-blocking characteristic is what gives Javascript it's asynchronous behavior.  When you call the first setTimeout(), the Javascript interpreter doesn't just stop and wait for the timer to fire.  Instead, it schedules that timer to run sometime in the future and then it keeps on executing the rest of your Javascript.  In your code, the next line of code is another setTimeout() so it immediately schedules that timer too.  Since they were both scheduled at the same time, it makes sense that the one scheduled for 2 seconds from now comes after the one scheduled for 1 second from now.
Thus, you end up with two choices.  You can either change the time on the second time to make it fire when you want it to fire (given that the code to schedule both timers is run at basically the same time) or you can change when you schedule the second timer until after the first timer has fired.

A: To understand what's happening, you should first understand the JS event loop and its non-blocking nature. You can read about it here: https://blog.risingstack.com/node-js-at-scale-understanding-node-js-event-loop/, or if you prefer video form, this is a great talk: https://youtu.be/8aGhZQkoFbQ
In a nutshell, the engine goes through the code - when it encounters the first setTimeout, it schedules it (for 2 seconds later), and keeps going. It then sees the second setTimeout and schedules it as well. When a second passes, the callback from the second setTimeout is triggered and executed, and only a second later, the callback from the first one is triggered. This is why you see them in that order.
Now to fixing it - all you need to do is just nest them:
setTimeout(function(){
   process.stdout.write('\n\nJokes Apart !!!\n\n');

   setTimeout(function(){
       process.stdout.write('\n\nLet\'s play a game !!!\n\n');
   }, 1000);
}, 2000);

This causes the second setTimeout to get scheduled only when the callback from the first one is run.


text:
Q: Use of unassigned local variable 'folderPath' I have error:

Use of unassigned local variable 'folderPath'

When I use this code:
string folderPath = folderPath.Substring(folderPath.IndexOf(@"\") + 1) + @"C:\test\" + "_converted";

How to resolve it?

A: You are creating a string, and in that process you are trying to access it. That doesn't make sense.
If folderPath is an existing variable, either reuse the variable:
folderPath = folderPath ...

Or create a variable with another name:
string folderPath2 = folderPath ...


text:
Q: Factory method and generics I have the following interface and implementation:
public interface IRepository<T>
{
    IList<T> GetAll();
}

internal class TrendDataRepository : IRepository<TrendData>
{
    public IList<TrendData> GetAll()
    {
        //.. returns some specific data via Entity framework
    }
}

I'm going to have multiple implementations that all return different data by Entity Framework. At some point I want to represent the user a list of classes that implement the IRepository interface. I do this with the following code. This works great for me.
    public static IEnumerable<string> GetAvailableRepositoryClasses()
    {
        var repositories = from t in Assembly.GetExecutingAssembly().GetTypes()
                           where t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof (IRepository<>))
                           select t.Name;

        return repositories;
    }

However, I would also like to create a factory method that given a specific string will return a concrete Repository type and allow me to call the 'GetAll' method on it. In pseudo-code:
someObject = Factory.CreateInstance("TrendData");
someObject.GetAll();

(I know this won't work because I have to specify a concrete type in the factory method).
I desire this functionality because I want to give a user the ability to bind a report to a specific datasource. This way they can start a new report where the datasource of the report is bound to (for example) the TrendDataRepository.GetAll() method.
However, maybe because the end of the world is getting near ;-) or it's Friday afternoon and I just can't think clearly any more, I don't know how to realise this.
Some pointers would be really welcomed.

A: I'd suggest returning the collection of repository types instead of the names and just displaying the names in the UI:
public static IEnumerable<Type> GetAvailableRepositoryClasses()
{
    return Assembly.GetExecutingAssembly().GetTypes()
        .Where(t => t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof (IRepository<>)));
}

Then when a user selects the source you can do:
object repository = Activator.CreateInstance(selectedType);

This method requires each repository to have a default constructor.
Activator.CreateInstance return an object, and you can't cast it to your IRepository<T> interface unless you know the generic type T you're expecting. The best solution is probably to create a non-generic IRepository interface which your repository classes also implement:
public interface IRepository
{
    IList<object> GetAll();
}

Now you can cast your created repositories to IRepository:
IRepository repository = (IRepository)Activator.CreateInstance(selectedType);

you might to create a repository base class which implements both:
public abstract class RepositoryBase<T> : IRepository<T>, IRepository
{
    public abstract IList<T> GetAll();
    IList<object> IRepository.GetAll()
    {
        return this.GetAll().Cast<object>().ToList();
    }
}


text:
Q: Load two controllers in the same view I'm developing an mvc 4 application and I'm just about done. I have two controllers are there.
 public ActionResult Index()
    {
           return View(new Resources());
    }

    public ActionResult ResourceDetails(int id = 1)
    {
        ResourceItems re = new Resources().GetResDetails(id);
        return View(re);
    }

ResourceDetails is a partial viewpage .it contains
 @model ....Models.ResourceItems

   @Html.Raw(@Model.Res_Details)

and index page contains
 @model IEnumerable<.....Models.ResourceItems>

   @foreach(var Item in Model)
    {

@Item.Res_NA

    }

I want load the partial page in to the div "rescontent" based on Id. Defaultly Id is 1. how it possible

A: You could use AJAX:
@model IEnumerable<Puthencruz.Rotary.Club.Models.ResourceItems>

    @foreach(var item in Model)
    {

            @Html.ActionLink(
                item.Res_NA,
                "ResourceDetails",
                "Resources",
                new { id = item.Id },
                new { @class = "detail" }
            )

    }

and then in a separate javascript file you could use jQuery to subscribe to the .click event of the anchors and send an AJAX request to the Details controller action sending the current item id and then render the results in the #rescontent div:
$(function() {
    $('.detail').click(function() {
        $('#rescontent').load(this.href);
        return false;
    });
});

Also from your controller action make sure you are returning a partial view:
public ActionResult ResourceDetails(int id = 1)
{
    ResourceItems re = new Resources().GetResDetails(id);
    return PartialView(re);
}


text:
Q: How to select values by the count of a filed? How to select values in MySQL table by the count of a field in the same table ?
Example:
Table users has id, name, password, country

I want to select all ids of only top 3 countries with highest users count to look like this:
country, id

When I try this
WHERE country IN (SELECT country FROM USERS GROUP BY country ORDER BY COUNT(id) DESC LIMIT 3)
I get This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
Server version: 5.6.33-79.0 Percona Server

A:
How to select values in MySQL table by the count of a field in the
  same table?

Use the GROUP BY field HAVING COUNT(*)=123 aggregation expression after the WHERE clause if there is.

A: Try this:
SELECT country, id
FROM
      (
         SELECT country,count(Id) as [NumberofUsers]
         FROM USERS
         GROUP BY country
                           ) X
INNER JOIN USERS U ON X.Country=U.Country
ORDER BY X.[NumberofUsers] DESC LIMIT 3

A: Join with a subquery that gets the top 3 countries.
SELECT u.country, u.id
FROM users AS u
JOIN (SELECT country
      FROM users
      GROUP BY country
      ORDER BY COUNT(*) DESC
      LIMIT 3) AS u1
ON u.country = u1.country

Practically any use of WHERE column IN (SELECT ...) can be changed to a JOIN like this, and in many cases the performance is better.


text:
Q: Additional information: Ссылка на объект не указывает на экземпляр объекта При создании Поста возникает ошибка
Вот сама реализация поста
[Authorize]
    [HttpGet]
    public ActionResult AddNewPost()
    {
        List<int> numlist = new List<int>();
        int num = 0;
        var posts = _blogRepository.GetPosts();
        if (posts.Count != 0)
        {
            foreach (var post in posts)
            {
                var postid = post.Id;
                Int32.TryParse(postid, out num);
                numlist.Add(num);
            }
            numlist.Sort();
            num = numlist.Last();
            num++;
        }
        else
        {
            num = 1;
        }
        var newid = num.ToString();
        PostViewModel model = new PostViewModel();
        model.ID = newid;
        return View(model);
    }

    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    [ValidateInput(false)]
    public ActionResult AddNewPost(PostViewModel model)
    {
        var post = new Post
        {
            Id = model.ID,
            Body = model.Body,
            Meta = model.Meta,
            PostedOn = DateTime.Now,
            Published = true,
            ShortDescription = model.ShortDescription,
            Title = model.Title,
            UrlSeo = model.UrlSeo
        };
        _blogRepository.AddNewPost(post);
        return RedirectToAction("EditPost", "Blog", new { slug = model.UrlSeo });
    }

A: Не нашлось объекта, удовлетворяющего условию в Where. Проверяйте результат FirstOrDefault на null.
var found = _context.Posts.Where(...).FirstOrDefault();
return (found == null)? null : found.Id;

Update
Еще раз - объект Post не найден. GetPostIdBySlug вернул null в качестве postid.  По этому  postid никакой Post не нашелся. Переменная post - null.


text:
Q: How to command Python not to count True as 1? count([5,2,1,'5',9,5,True],1) will show 2 as it treat Trueas 1.How do i change my main code so that when I want to check how many 1 is in the sequence,it will only return 1.
this is my main code
def count(L,x):
    k = 0
    for i in L:
        if x == i :
            k+= 1

    return k

A: You can change x == i to x is i.
>>> x = True
>>> y = 1
>>> x == y
True
>>> x is y
False

A: Just add an isinstance to your check:
def count(L,x):
    k = 0
    for i in L:
        if not isinstance(i, bool) and i == x:
            k+= 1
    return k

or, explicitly filter with i is not True. I.e if i is not True and i == x:


text:
Q: Is there a match on incoming interface in DHCPd classes? (Note, the title of the question Is there a way to classify DHCP requests based on the interface they're coming from? is what I want answered, but it doesn't actually ask that question for a non-dhcp relay situation, and the answer doesn't help here since I can't rely on a relay to set options for me).
I have a hypervisor (KVM) with isc-dhcpd at dom0, and I need to be able to PXE boot client VMs.  This works fine for any one interface, but I can't seem to make it work for multiple interfaces - I have the following class for PXE:
class "pxeclients" {
  match if substring(option vendor-class-identifier, 0, 9) = "PXEClient";
  filename "pxelinux.0";
  next-server 10.71.0.1;
}

The problem is that I have to pick which tftp interface I want to use for next-server.  I need clients to pick the tftp server on their own subnet or they can't boot (but otherwise they all look the same, unless I can find some kind of match discriminant).  Is there a way to create a class which matches on both PXE and the subnet I'm about to lease, or the interface the packet came in on?

A: Why not specify a tftp server that's a hop away?  As long as your clients are receiving the appropriate default gateway this might be the easiest way to go.
That said, if you must support multiple interfaces -
It's possible to run multiple instances of dhcpd.  Each would have its own configuration that would include entries to specifically bind said instance to a particular interface.  To ease administration each config file could be set to include an additional configuration file that might contain other common settings.  This would probably be fine for a relatively small number of interfaces (i.e. <= 10-20) but if it needs to scale much larger then I'd look into a proper L3 infrastructure with helper addresses/relays.


text:
Q: Powershell script to establish connectivity to remote server I have a requirement wherein I have to test the connectivity to the destination server (which sometimes goes down due to network issues).
So basically, I need to check that if it goes down due to any reason, the PowerShell script should be able to bring it back up.
I am able to write a script which will test the connectivity to the destination server which has been listed below. But do not know how to re-establish the connectivity when the network goes down.
Can anyone help me add the "Establish connectivity" part of it.
$servers = "server name"

Clear-Content c:\myprocesses.txt

foreach ($s in $servers) {
  if (!(Test-Connection -Cn $s -BufferSize 16 -Count 1 -EA 0 -Quiet)) {
    "Problem connecting to $s"
    "Flushing DNS"
    ipconfig /flushdns | Out-Null

    "Registering DNS"
    ipconfig /registerdns | Out-Null

    "doing a NSLookup for $s"
    nslookup $s >> C:\myprocesses.txt
    "Re-pinging $s"

    if (!(Test-Connection -Cn $s -BufferSize 16 -Count 1 -ea 0 -quiet)) {
      "Problem still exists in connecting to $s"
    } else {
      "Resolved problem connecting to $s"
    } # end if

    tracert $s >> c:\myprocesses.txt
  } else {
    Enable-PSRemoting -Force
    Restart-Service WinRM

    if (Test-Connection -ComputerName $s -Quiet) {
      New-PSSession $s
    }

    "No Problem connecting to $s"
    "Writing the Traceroute to the destination server $s"
    tracert $s >> c:\myprocesses.txt

    "c:\myprocesses.txt ready"
  } # end if
} # end foreach`


text:
Q: Entity Framework 6 does not store child object I have added a prop to my class and added a new DbSet but when saving, it does not store my child objects.
My house class:
[Table("Houses")]
public class House
{
    [Key]
    public int ID { get; set; }
    public List<Price> Prices { get; set; } // <-- new prop
}

my dbcontext has a Prices prop now: public DbSet<Price> Prices { get; set; } and I enabled migrations, added the migration and updated the database. So the prices table is created.
When I update a House object, it does not insert anything in the Prices table.
var h = new House(); // with prices etc filled
if (db.Houses.Any(hc => hc.Code.Equals(h.Code, StringComparison.InvariantCultureIgnoreCase)))
{
    var original = db.Houses.First(k => k.Code.Equals(h.Code, StringComparison.InvariantCultureIgnoreCase));
    h.ID = original.ID; // workaround for The property 'ID' is part of the object's key information and cannot be modified.
    h.CountryId = original.CountryId;

    db.Entry(original).CurrentValues.SetValues(h);
    db.SaveChanges(); // does update House fields, but no prices
} else { // add new
    db.Houses.Add(h);
    db.SaveChanges();
}

I did add public virtual House House { get; set; } to my Price class. But I do not fill it, because when populating the house object, I do not know the ID in the db yet. Maybe that is causing it? I have also read https://stackoverflow.com/a/26572122/169714 and added this to my Price class:
[ForeignKey("HouseId")]
public virtual House House { get; set; }
public int HouseId { get; set; }

but still no entries in the prices table. I am probably doing something wrong storing/updating the database.
edit current store method:
using (var db = new MyCommon.HouseContext())
{
    var l = db.Countries.First(tmpC => tmpC.Code.Equals(h.Country.Code));
    h.OperatorId = op.ID;
    h.CountryId = l.ID;
    h.Country = l;

    var existingHouse = db.Houses.Where(p => p.Code.Equals(h.Code, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();

    if (existingHouse != null)
    {
        // update
        h.ID = existingHouse.ID; // workaround for The property 'ID' is part of the object's key information and cannot be modified.
        h.CountryId = existingHouse.CountryId;
        h.OperatorId = existingHouse.OperatorId;

        db.Entry(existingHouse).CurrentValues.SetValues(h);
        db.Entry(existingHouse).State = System.Data.Entity.EntityState.Modified;
        //db.SaveChanges(); // moved to bottom for perf.
    }
    else
    {
        existingHouse = h;
        db.Houses.Add(h);            // insert
    }

    foreach (var ft in existingHouse.Prices)
    {
        var existingFt = existingHouse.Prices.SingleOrDefault(f => f.ID == ft.ID);

        if (existingFt != null)
        {
            db.Entry(existingFt).CurrentValues.SetValues(ft);
            db.Entry(existingFt).State = System.Data.Entity.EntityState.Modified;
        }
        else
        {
            existingHouse.Prices.Add(ft);
        }
    }
    db.SaveChanges();
}

A: Check the EntityState of your objects. Attach the object to your context, and iterate through these Prices to mark the EntityState.Modified. If the Price objects are new, you can use EntityState.Added. You can see here for an 'upsert' pattern example.


text:
Q: Having troubles with base case in a proof by induction show that if n is a positive integer and x is a real number larger than $-1$, then $(1+x)^{ n }\geq 1+nx\\ $
Proof by induction
Base case n=1
so $1+x = 1+x$
Inductive Hypothesis: Assume $(1+x)^n \geq 1+nx$ for n>0 and x>-1
NTS $(1+x)^{n+1} \geq 1+(n+1)x=1+nx+x$
$(1+x)^n \geq 1+nx$
$(1+x)^{n+1} \geq (1+nx)(1+x)$ because $1+x$ is positive
$(1+x)^{n+1} \geq (1+nx^2+nx+x)$ but $nx^2$ is positive
so $1+nx^2+nx+x \geq 1+nx+x$
This implies that $(1+x)^{n+1} \geq 1+nx+x$

A: Note that only in case $x=0,\forall n>1$ we can get equation.
Now  it must be shown that in case $n>1\quad x>-1$ there is a strict inequality $${ \left( 1+x \right)  }^{ n }>1+nx$$
in case $n=2$ it is obvious that $\\ { \left( 1+x \right)  }^{ 2 }=1+2x+{ x }^{ 2 }>1+2x$
Further,consider it is true for $n$,then

$$\\ { \left( 1+x \right)  }^{ n+1 }={ \left( 1+x \right)  }^{ n }\left( 1+x \right) >\left( 1+nx \right) \left( 1+x \right) =\\ =1+x+nx+n{ x }^{ 2 }>1+nx+x=\left( n+1 \right) x\\ $$

P.S sorry for my bad english


text:
Q: Fast and scalable RPC between C# and CPython I need some feedback on C# - cPython integration for scientific application.
The scenario is the following: C# for data acquisition and visualization - CPython for data manipulation using several and changing third part library to implement domain specific tasks.
General use case:

*

*C# code get realtime data from device

*C# code pass data to cPython code and ask for elaboration

*Cpython code does the magic

*Cpython code pass result back to c# code

*C# visualizes data in a WPF application

Both c# and cPython code (item 1),3) and 5)) have already been optimized  for speed.
Data to be passed in both direction (item 2) and 4)) are essentially arrays of 10E6 double
(no complex data structure involved).
I'd like to find an interfacing solution with good performance (speed in going from 1 to 5)
and decoupling capabilities who also minimizes the development on client (c# code)
side.
Actually both side run on the same machine, but I'd like the solution to scale out.
Solutions I've tried - issues:

*

*a) C# + porting python algorithm on .NET - too many code to write/rewrite
on domain side, lack of specialized library cPython provide for almost everything on scientific side

*b) C# embedding ironpython + wrapping/porting c++ extension on managed code (with and without ironclad) -  borderline performance caused by the marshaling of structures used during algorithms execution - dll hell when upgrading version of subcomponents.

*c) C# embedding ironpython + rpc between ironpython and python - issues in maintainability,
not satisfied by having to "pass" data between the three C#/ironpython/python .

*d) XML-RPC, JSON-RPC - not satisfied by performance (speed).

Solutions not already tried which I plan to evaluate:

*

*e) Apache Thrift

*f) ZeroRPC
Thanks in advance for any criticism, comments and suggestions.

A: I have a similar requirement (C#<->Python RPC) I've just been experimenting with Apache Thrift and I've very impressed. It's very fast: 50% slower than Pyro4/pickle, 5x faster than RPyC. This is for sending numpy arrays around as binary data. The remaining overhead with Thrift is likely the copying of the array data into/out of strings. If Thrift could be refactored to take buffer objects in place of strings, I would expect it to be as fast as Pyro.
The code-generation seems very clean and the API is nice. The main thing it lacks is documentation. Still, I've been able to figure everything out from the basic tutorial, tests and browsing the source.
As far as I can see ZeroRPC doesn't (yet) have a C# implementation.


text:
Q: how should I change this to use CCParallaxNode? Hello I am a beginner to cocos2d and objective c. I am making a cocos2d side scroller. How can I make this code be continuous??
 backgroundNode = [CCParallaxNode node];
    [self addChild:backgroundNode z:-5];
    treeBackground = [CCSprite spriteWithFile:@"thechangedbackgroundcopy.png"];
    CGPoint backgroundSpeed = ccp(0.5, 0.5);
    [backgroundNode addChild:treeBackground z:-5 parallaxRatio:backgroundSpeed positionOffset:ccp(screenWidth/2, screenHeight/2 - 50)];

    [self scheduleUpdate];

-(void)update:(ccTime)delta{
CGPoint backgroundScrollVelocity = ccp(-150, 0);
backgroundNode.position = ccpAdd(backgroundNode.position, ccpMult(backgroundScrollVelocity, delta));
}

A: Check out great series of tutorials on Ray Wenderlich site
The part you ask about is covered in the Adding Parallax Scrolling paragraph.


text:
Q: $2$-vector spaces and algebraic $2$-stacks I am thinking about higher Artin stacks in the sense of Simpson, concretely  I would like to calculate the dimension and compare these two cases:

*

*$\mathfrak{X}_{1}=$ Higher linear stack classifying (over some affine scheme $X$) positively  graded cochain complexes $E$ of length $2$ of vector spaces (being $E$ perfect on $X$)

*$\mathfrak{X}_{2}=$ Moduli stack of $2$-vector bundles over some affine scheme $X$
Let us assume for simplicity (smoothness) that $X$ is a reduced curve.
The tricky thing here is that the categorification of a vector space into a $2$-vector space is somewhat ambiguous: they exist two main versions: Kapranov–Voevodsky and Baez–Crans 2-vector spaces
Baez-Crans $2$-vector space is said to be equivalent to a $2$-term chain complex of vector spaces $E:V_{2}\overset{d_{2}}{\rightarrow} V_{1}$, so we would be in the case $\mathfrak{X}_{1}$.

QUESTION 1.1: In a $2$-stack $\mathfrak{X}_{1}$ of this form what would be the $1$-(iso)morphims and the $2$-(iso)morphisms? Take two complexes $E_{a}:V_{2a}\overset{d_{2a}}{\rightarrow} V_{1a}$ and ake $E_{b}:V_{2b}\overset{d_{2b}}{\rightarrow} V_{1b}$. I guess the $1$-morphisms would be the same that in $1$-stacks (linear transformtions applied on each $V_{i\alpha}$) and the $2$-morphisms are the chain maps $f:E_{a}{\rightarrow}E_{b}$, right?

QUESTION 1.2: What is the stacky dimension of $\mathfrak{X}_{1}$ at a point $x$ in such a case? I expect it to be something like
$\dim_{x}(\mathfrak{X}_{1})=\dim_{x}(H^{-1}(X,End(E)))+\dim_{x}(H^{0}(X,End(E)))+\dim_{x}(H^{1}(X,End(E)))$
where the first two terms are related to $V_{2}$ and $V_{1}$
respectively, But I am not sure about this expression and specially
about which set of automorphisms and/or deformations count each term.

The Kapranov-Voevodsky case would be somehow a wilder space (I expect its stacky  dimension to be bigger). For a quite explicit formulation of it I have followed  this paper. A $2$-vector space $Vect^{k}$ is there a category having   $k$-tuples of vector spaces as objects and   $k$-tuples of linear maps as morphisms. As we are interested in the moduli $2$-stack $\mathfrak{X}_{2}$ we have also to take account of $2$-morphims $T$ :
$Vect^{k} \rightarrow$ $Vect^{l}$ which are $k \times l$ matrices of vector spaces,defined as
$$
\left(\begin{array}{ccc}
T_{1,1} & \ldots & T_{1, k} \\
\vdots & & \vdots \\
T_{l, 1} & \ldots & T_{l, k}
\end{array}\right)\left(\begin{array}{c}
V_{1} \\
\vdots \\
V_{k}
\end{array}\right)=\left(\begin{array}{c}
\oplus_{i=1}^{k} T_{1, i} \otimes V_{i} \\
\vdots \\
\oplus_{i=1}^{k} T_{l, i} \otimes V_{i}
\end{array}\right)
$$
For simplicity we can choose all the $V_{1,...,k}$ equdimensional, say of dimension $n$. It is easy to see that the right hand side of that equation is a $l$-tuple of ($k \times n$)-dimensional vector spaces (not just $n$) so for a sensible $2$-stack we should fix both  $n$ (dimension of the  $1$-vector spaces involved), and $k$ and $l$ (how long are the tuples of vector spaces that we combine in a $2$-morphism) whereas in a usual $1$-stack we would fix $n$.

QUESTION 2: What is the stacky dimension  $\mathfrak{X}_{2}$ at a point $x$  in such a case? I expect that the part coming from the automorphims of the $2$-vector space to be $\left (k\times n \right )\times \left (l\times n \right )$-dimensional but I am unsure about the form of the formula in terms of the homology groups of the cotangent complex.


text:
Q: .htaccess relative mod_rewrite path - simplify deployment of an application Each time it's time to deploy a CodeIgniter application, I find myself struggling with changing the path in the .htaccess. Therefore; I'm looking for a proper, good working solution which works no matter of the location of the actual project.
Obstacle: My local testing enviroment isn't localhost/ but rather localhost/project. This won't, most likely, be the case in the live enviroment (more likely /). Hence, I'd prefer a solution which works anyway.
My current .htaccess:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /project/index.php?/$1 [L]

    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /project/index.php?/$1 [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /project/index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /project/index.php
</IfModule>

Using only index.php as a path won't work. It gives me an 404 not found error.
Have tried a lot of different combinations, and would love to see your suggestions. Thanks!

A: Personally I dont like your denying of system and application folers in .htaccess.
Per the "best practice on CI" guide found here (http://codeigniter.com/forums/viewthread/125687/) - you should move your application and system folders OUT of public_html, leaving only index.php. Then NO MATTER WHAT fancy stuff people try - they cant access your application & system folders from http.
Then meanwhile - here is my .htaccess file that I use on ALL projects - with no modification required for ANY. It just "works" (for me).
Options -Indexes
Options +FollowSymLinks

# Set the default file for indexes
DirectoryIndex index.php

<IfModule mod_rewrite.c>
        # activate URL rewriting
        RewriteEngine on

        # do not rewrite links to the documentation, assets and public files
        RewriteCond $1 !^(files|css|js|assets|uploads|captcha)

        # do not rewrite for php files in the document root, robots.txt
        RewriteCond $1 !^([^\..]+\.php|robots\.txt)

        # but rewrite everything else
        RewriteRule ^(.*)$ index.php/$1 [L]
 </IfModule>

 <IfModule !mod_rewrite.c>
        # If we don't have mod_rewrite installed, all 404's
        # can be sent to index.php, and everything works as normal.
        ErrorDocument 404 index.php
  </IfModule>

Oh - and I use this for my multiple projects on localhost. i.e. localhost/project1 , localhost/project2
just put a copy of the htaccess file in the root of each project. I DONT have this file in my root localhost


text:
Q: Move local copy of git in Github for Mac I have cloned the source of a git repository to /path1/foo/, but I want move the local copy to a new location say /path2/foo/.
How do I do this?

A: In Terminal:
mv /path1/foo /path2/foo

Or, in Finder: drag and drop the git repo folder from one place to another.

A: Working solution:

*

*Clone foo from github to /path2/foo/ in Github for Mac

*If local version is different from the latest at github, move /path1/foo/ to /path2/foo/

A: Open bash terminal and run this command:
mv .* YOUR-NEW-LOCATION-OF-DIRECTORY
Replace YOUR-NEW-LOCATION-OF-DIRECTORY with your new destination directory and this command will move all hidden files/folders such as .git.


text:
Q: How to move indexpath.row to a new view controller I am trying to move this indexPath.row to the view controller pageView
So this is what I have tried:

First off getting the indexPath row from the corresponding button
[cell.nav addTarget:self action:@selector(naviguate:) forControlEvents:UIControlEventTouchUpInside];
    cell.nav.tag=indexPath.row;

Where inside a table cell there is a button nav

Then here is how I navigated to the pageView
-(void)naviguate:(id)sender {
    [UIView animateWithDuration:0.5
                          delay:0
                        options: UIViewAnimationOptionCurveEaseOut
                     animations:^{

                         [_tableView setFrame:CGRectMake(0, 569, _tableView.frame.size.width, _tableView.frame.size.height)];
                     }
                     completion:^(BOOL finished){
                         [self performSegueWithIdentifier:@"link" sender:self];
                     }];

}

Where link is the seague identifier

And this is how I have tried to share it
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    UIButton *theButton=(UIButton *)sender;
    if([segue.identifier isEqualToString:@"link"])
    {
         NSLog(names[theButton.tag]);
         controller.name.text = names[theButton.tag];
    }
}

where name is a label inside pageView

But I am getting the error:
-[ImagesTableViewController tag]: unrecognized selector sent to instance

and nothing is being logged how come? What am I doing wrong?

A: Don't set the control (label) property from the imageViewController, instead you want to pass the a NSString to this new instance of the pageView.
Once the segue is performed, set the label text in viewDidLoad
Add a property to the pageView.h
@property (strong, nonatomic) IBOutlet NSString *blogName;

change the segue code
controller.name.text = names[theButton.tag];

to
 controller.blogName = names[tag];

in Page viewDidLoad
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.name.text = _blogName;
}

A: To carry @bobnoble 's explanation a little further:
In your naviguate method, you call
[self performSegueWithIdentifier:@"link" sender:self];

Note that you pass "self" as the sender. That means that in prepareForSegue, the sender parameter will contain the current view controller.
If your naviguate method is an IBAction, as suggested by the fact that it has a sender parameter, why not change it like this:
-(IBAction) naviguate:(id)sender
{
  [UIView animateWithDuration:0.5
    delay:0
    options: UIViewAnimationOptionCurveEaseOut
    animations:^
    {
      [_tableView setFrame:CGRectMake(0, 569, _tableView.frame.size.width,
      _tableView.frame.size.height)];
    }
    completion:^(BOOL finished)
    {
      [self performSegueWithIdentifier:@"link" sender: sender]; //Changed to pass sender
    }
  ];
}

That way you pass on the sender from your action method to the seque.
I would still change your prepareForSegue method to make sure that the sender responds to the "tag" selector before trying to get a tag value from it:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
  UIButton *theButton=(UIButton *)sender;
  if([segue.identifier isEqualToString:@"link"])
  {
    int tag = -1
    if (![theButton respondsToSelector: @selector(tag)])
      NSLog(@"Sender does not respond to 'tag'!");
    else
    {
      int tag = theButton.tag;

      NSLog(names[tag]);
      controller.name.text = names[theButton.tag];
    }
   }
}


text:
Q: WFP - Reuse DataGrid columns and resources I have an application with two DataGrid controls. And although their ItemsSource are bound to different collections, their item type, columns, styles and event handlers are exactly the same.
As their XAML codes are growing bigger and bigger, how can I create the same "content" and reuse it in both DataGrids?
What I currently have is:
<DataGrid x:Name="LeftGrid"
         ItemsSource="{Binding LeftCollection}"
         Grid.Column="0"
         CanUserAddRows="False" CanUserDeleteRows="False" AutoGenerateColumns="False">

    <!--exactly the same code from this forward-->
    <DataGrid.Resources>
        <Style TargetType="DataGridRow">
            <EventSetter Event="MouseDoubleClick" Handler="DataGridRow_MouseDoubleClick"/>
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Header="Type" Binding="{Binding Type, Mode=OneWay}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Status" Binding="{Binding Status, Mode=OneWay}" IsReadOnly="True"/>
        ...............................
        ................................
        .....................................
    </DataGrid.Columns>
</DataGrid>

Then I have "exaclty" the same datagrid copied whose only changes are Name, Grid.Column and ItemsSource (only the three first rows of the XAML):
<DataGrid x:Name="RightGrid"
         ItemsSource="{Binding RightCollection}"
         Grid.Column="1"
         CanUserAddRows="False" CanUserDeleteRows="False" AutoGenerateColumns="False">

    <!--exactly the same code from this forward-->
    <DataGrid.Resources>
        <Style TargetType="DataGridRow">
            <EventSetter Event="MouseDoubleClick" Handler="DataGridRow_MouseDoubleClick"/>
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Header="Type" Binding="{Binding Type, Mode=OneWay}" IsReadOnly="True"/>
        <DataGridTextColumn Header="Status" Binding="{Binding Status, Mode=OneWay}" IsReadOnly="True"/>
        ...............................
        ................................
        .....................................
    </DataGrid.Columns>
</DataGrid>

A: The easiest way at the first glance is to put it to the UserControl and use it in the main view.
<UserControl x:Class="YourNameSpace.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
    </UserControl.Resources>
    <Grid>
        <DataGrid ItemsSource="{Binding}">
            <!-- ... -->
        </DataGrid>
    </Grid>
</UserControl>

Which you can use then:
xmlns:local="clr-namespace:YourNameSpace"
<local:UserControl1 x:Name="LeftGrid" DataContext="{Binding LeftCollection}" Grid.Column="0"/>
<local:UserControl1 x:Name="RightGrid" DataContext="{Binding RightCollection}" Grid.Column="1"/>

If you don't want to use a collection as DataContext for the whole UserControl, then you can of course create a dedicated dependency property for collection in the UserControl and bind it to the DataGrid.ItemsSource.


text:
Q: Can file size be a negative number? Why? On /coreutils-8.12/src/ls.c, I've found this comment:
/* POSIX requires that a file size be printed without a sign, even
when negative.  Assume the typical case where negative sizes are
actually positive values that have wrapped around.  */

on line 2639.
My questions are:
- What is this typical case they refer to?
- Can file size be a negative number, other than in overflowing problems with BIG files and old systems?
- If yes, why?(and why should I care like they are doing in the comment above?)
I'm interested also in other systems, not only POSIX

A: It may well mean that file sizes in POSIX should be treated as unsigned integers, not signed. A file size of > 2GB if represented as a 32-bit integer would appear negative, though it obviously isn't.

A: Look at the code below the comment:
static uintmax_t
unsigned_file_size (off_t size)
{
  return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
}

If size is negative, it will be changed to a positive number by adding some defined value (most likely something near 2^31 for 32 bit datatypes etc.).
This prevents typical errors like assigning a filesize of 2-4 GB to a signed integer which will result in a negative number which ls should display as the correct positive filesize instead.


text:
Q: How I can access DOM element by selector In Angular2 is there way to get element by it's selector NOT in a template but inside whole DOM?

A: It is not recommended to access the DOM directly in angular2, since your are bypassing the Angular2 renderer
You can use other angular 2 features to do that, for example: adding reference to this element.
Check out this issue, it can help you:
How to get dom element in angular 2

A: Sure, window.document.querySelector, or window.document.querySelectorAll.

A: Today there is an "Angular" way of using the Document to query for Elements:
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

class DOMService {
  constructor(@Inject(DOCUMENT) private document) {}

  getElementsByClass(clazz: string): HTMLCollection[] {
    return this.document.getElementsByClassName(clazz);
  }
}

Especially with Server-Side rendering Features for example its not recommended to access window directly (window && window.document..). In case you are also manipulating the Elements you should consider using Angulars Renderer2
In case you just need access to an Element inside your current Component you can use @ViewChild or ElementRef features.

A: I'm going to post this as another answer, instead of editing the old one, because IMHO both approaches are useful. But this is most definitely a much more "Angularish" one.
There's two Angularish-2 ways to get a reference to a template DOM element; ElementRef, and ViewChild. There may be more, but these are the two that get mentioned everywhere.
ElementRef is probably best to avoid. Evidently it opens you up to potential XSS attacks. There's all kinds of red "beware" around the docs.
So I settled on something that works really well, that being ViewChild.
My template:
<input #myinput type="text" />

Notice that wonky looking #myInput. It serves as an ID, but not a plain ol' DOM id=''. I assume this gets you around the unique IDs problem, as well as the ugly hack of tagging elements with empty CSS classes in lieu of IDs.
In your code: Note I use ES6 without annotations. but to get the same effect, you would use the @ViewChild annotation. It's well doc'd in TS (not in ES6 at all, it took me quite a while to piece it together).
FYI I had to figure out a clean way to do this because I wanted to implement an RxJS stream to do some debouncing and whatnot.
import { Component, ngOnInit, ViewChild } from '@angular/core';

class HomeComponent {
    constructor( ) {}

    ngOnInit ( ) {
        // .nativeElement console.log's out to what you'd expect.
        var inputBox = this.myInputRef.nativeElement;
        // left this in to demonstrate it works as plain ol' DOM elem,
        // if it didn't, this wouldn't work.
        var source = Rx.Observable.fromEvent(inputBox, 'click');
        ...
    }
}

HomeComponent.annotations = [
    new Component ( {
       templateUrl: './views/home/home.component.html',
       queries: { 'myInputRef': new ViewChild ( 'myinput' ) }
    } )
];
export { HomeComponent }

Works like a charm. About time we had something like this in Angular. JQLite really never cut it.


text:
Q: Pinterest mimic js (jquery) not recalculating unless refreshing Im hoping someone will be able to shed some light and help me solve this problem.
Using the following js: http://isotope.metafizzy.co/ we are mimicking the pinterest style of grid layout.
We have this loading on multiple pages and an issue occurs where say im on the homepage and then navigate to a portfolio which has the same effect the grid system is overlapped slightly - as if there is a cache in the calculation somewhere which is causing this, it resolves itself with a refresh of the page but then the homepage is then thrown out and a refresh is needed to sort this out and round and round and round.
I have tried to avoid a cache using several methods (adding a php timestamp variable onto the end of the js file where it is being loaded in. I have tried loading in different files on different pages using modules (we are building on joomla) - if count module-a show isotope.pkgd.min.1.js else if count module-b show isotope.pkgd.min.2.js and this still doesnt work.
Any ideas as to why this would be happening and how I can get round this?
Thanks in advance.
EDIT: code is too long to post, here is a link to js file: https://www.dropbox.com/s/3oghom32961chrl/isotope.pkgd.min.js?dl=0
It is being called in: <div id="containerNew" class="js-isotope" data-isotope-options='{ "columnWidth": 200, "itemSelector": ".row" }'>
The itemSelector changes per page.
Any other information required let me know.
EDIT: I actually worked this out. The boxes needed a height to be specified if on multiple pages as for the script to recalculate positions.


text:
Q: In REST API, How to restrict URL access from browser using Nodejs & Expressjs I have a MEAN stack application and using  Node.js and Express.js as back-end API.
Assuming I have a 'comments' route as follow
/* GET /comments listing. */
router.get("/", function(req, res, next) {
    Comment.find(function(err, comments) {
        if (err) return next(err);
        res.json(comments);
    });
});

And use it in my server like this:
var commentsRouter = require('./routes/comments');
...
app.use('/comments', commentsRouter);

My question is: Is there a way to prevent users to access http://mrUrl/comments in browser and deny the request with probably 403 Forbidden message but at the same time JavaScript file tries to access the same URL will receive a content message (in the example should be res.json(comments);)
Also, would it be possible to enable such a restriction for all routes once, not for each.

A: Yes, you can use a middleware.
A middleware is a function you can pass before or after the main function you are executing (in this case, GET comments)
the order of the function location matters, what comes first - executes first, and you implement it like so:
app.use(myBrowsingRestrictionMiddlewareFunction) // Runs

app.use('/comments', commentsRouter);

app.use('/account', accountRouter);

You can also use within a route handler:
app.post('/comments', myMakeSureDataIsAlrightFunction, myMainCreateCommentFunction, myAfterStatusWasSentToClientAndIWishToMakeAnotherInternalActionMiddleware);

The properties req, res, next are passed into the function automatically.
which means, myBrowsingRestrictionMiddlewareFunction receives them and you can use them like so:
export function myBrowsingRestrictionMiddlewareFunction(req, res, next) {
  if (req.headers['my-special-header']) {
     // custom header exists, then call next() to pass to the next function
     next();

  } else {

    res.sendStatus(403);

  }
}

EDIT
Expanding regards to where to place the middleware in the FS structure (personal suggestion):
What I like to do is to separate the router from app.js like so:
app.js
app.use('/', mainRouter);

router.js
const router = express.Router();

router.use(middlewareForAllRoutes);

router.use('/comments', commentsRouter);

router.use(middlewareForOnlyAnyRouteBelow);

router.use('/account', accountRouter);

router.use(middlewareThatWillBeFiredLast); // To activate this, remember to call next(); on the last function handler in your route.

commentsRouter.js
const router = express.Router();

router.use(middlewareForAllRoutesONLYFORWithinAccountRoute);

route.get('/', middlewareOnlyForGETAccountRoute, getAccountFunction);

router.post('/', createAccount);


text:
Q: Making an @Entity persist itself Given a typical JPA example such as this one, we have code like this:
@Entity
public class Company {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    //...etc...
}

and:
public class CompanyDaoImpl implements CompanyDao {
    @PersistenceContext(unitName = "custdb")
    private EntityManager em;

    public void createCompany(final Company c) {
        em.persist(c);
    }
    //...etc...
}

(Let's ignore the @Stateless attribute for this example)
Reading other sites about anaemic domain models and this Q&A on why shouldn't JPA Entities contain business logic, why shouldn't I be able to say:
@Entity
public class Company {
    @PersistenceContext(unitName = "custdb")
    private EntityManager em;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public void create() {
        em.persist(this);
    }
    //...etc...
}

Am I going to get myself into a world of hurt doing this?

A: One possible reason is that instead of duplicating the CRUD (create, read, update, delete) operations in every class you may be able to create more generic solution allowing you to work with instances of multiple classes.
Have a look at this question. The accepted answer gives an example of generic DAO parametrized with the type of object it operates on. This is quite a common pattern to use.

A: Using JPA(Hibernate) with a Spring test, I was able to show that it is possible.
Assuming this is your rather enlightened entity:
models.so.haum.IntropectiveEntity.java
@Entity
public class IntrospectiveEntity {

    @Transient
    private EntityManager em;

    protected IntrospectiveEntity() { }

    public IntrospectiveEntity(final EntityManager em) {
        this.em = em;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public void create() {
        em.persist(this);
    }

    public List<IntrospectiveEntity> all() {
        TypedQuery<IntrospectiveEntity> query = em.createQuery("SELECT ie FROM IntrospectiveEntity ie", IntrospectiveEntity.class);
        return query.getResultList();
    }
}

note that you must mark your EntityManager as @Transient otherwise JPA will try map it as a column. Also note that I couldn't get the EntityManager instance injected, so had to pass that as a constructor arg.
and this is your test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class IntrospectiveEntityTest {

    @PersistenceContext
    private EntityManager em;

    @Test
    @Transactional
    public void namaste() {
        IntrospectiveEntity introspectiveEntity = new IntrospectiveEntity(em);
        introspectiveEntity.create();

        assertThat(introspectiveEntity.all().size(), IsEqual.equalTo(1));
    }

    @Configuration
    @ComponentScan(basePackages = "so")
    static class IntrospectiveEntityConfiguration {

        @Bean
        public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
            JpaTransactionManager transactionManager = new JpaTransactionManager();
            transactionManager.setEntityManagerFactory(entityManagerFactory);
            return transactionManager;
        }

        @Bean
        public LocalContainerEntityManagerFactoryBean entityManager(DataSource dataSource) {
            LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();

            HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
            jpaVendorAdapter.setGenerateDdl(true);
            jpaVendorAdapter.setShowSql(true);
            entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);

            entityManagerFactory.setDataSource(dataSource);
            entityManagerFactory.setPackagesToScan("so.models.haum");
            return entityManagerFactory;
        }

        @Bean
        public DataSource dataSource() {
            EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
            EmbeddedDatabase dataSource = builder.setType(EmbeddedDatabaseType.H2).build();
            return dataSource;
        }
    }
}

it successfully passes. Persisting and finding itself.
So if you really want to do it this way, it is possible. Obviously the EntityManager not being injected is probably not what you wanted but there you have it.


text:
Q: Samba: permission denied I have a server with a host and a Virtualbox VM.The host is running CentOS 7 and it is updated. Indeed the VM is running CentOS 5 and I know this OS is not supported by several years but I can't update it now.
The alert of the problem is too generic and it's shown when I try to mount on the VM the samba folder that is living on the host:

mount error 13 = permission denied

I just followed this guide: Install and configure samba CentOS 7
Samba version:Host -> samba 5VM -> samba 3
I tried:Disabling firewalld and SELinuxUsing NFSChange password of users and use several users
But all this got nothing changed.
Hope y'all got tips and solutions for me.
Thanks in advance


text:
Q: What is the equivalent of Set X = Nothing in PHP? Is:
<%
Set Mail = Server.CreateObject("SomeCOMObject")

Set Mail = Nothing
%>

the same as:
<?php
$Mail = new COM("SomeCOMObject");

$Mail->Close(); // <---- Not sure about this
?>

A: $mail = new Mail; //hello
unset($mail); //goodbye

A: You can set $var to equal nothing like this:
$var = null;

To completely release the variable from memory, you do this:
unset($var);

A: I beleive
$Mail = null;
unset($Mail);

Although I am likely mistaken.


text:
Q: Make Tor use Unique IP for each instance open How can I get Tor to use a unique IP for each instance of Tor open in C++, Python or Perl? Is there a command to force it to use a unique IP that I can just call using subprocess?
*cheers

A: You'll need to connect to ToR's control port and issue certain signals to have it create a new connection.  You might have to manually check what the end IP is.
This document has some example code in Java and Python for interfacing with ToR along with some of the signals and how to use them.  The one you're looking for is probably NEWNYM, but it's not brought up in the linked document.  With a little bit of googling, you may be able to find more info on controlling ToR via its control port.

A: Use this in bash:
(echo authenticate '""'; echo signal newnym; echo quit) | nc localhost 9051

Use this in PHP:
// flush Tor circuit, obtain new IP
$password = '""'; // replace with your Tor password (if any)
exec("(echo authenticate $password; echo signal newnym; echo quit) | nc localhost 9051", $out);
print_r($out);


text:
Q: Find all directories containing semicolon ( ; ) How can I search for all directories/folders which contain the character ;.
From this question I see I can search for any other character using, e.g. to find all directories containing a
dir /S *a* /AD

However, ; acts as a delimiter, so doing *;* is telling it to find * or *, i.e. Anything or anything, and returning every subdirectory rather than just those containing ;.
This would be great if I wanted to find, e.g. x or y as I could *x*;*y*, but how do I match ;?

A: You should quote the pattern:
dir /s /ad "*;*"

This way DIR will treat *;* as a single token. This is also useful for other special characters, like space, comma, caret (^), etc.


text:
Q: Django. Cancel button for form in admin site Is there any functionality in admin site that allow to implement for every add/change form cancel button, that redirects me to list of that form objects. I mean some general solution for any form.

A: Add admin/submit_line.html in your project's templates directory. Use the code from the default submit_line.html, and add your cancel button. You can link it to just "../" to make it always just go up one level. Then do any necessary CSS styling to make it look right.

A: Create a file: yourapp/templates/admin/submit_line.html
I use Bootstrap, but you can change this easily
{% extends "admin/submit_line.html" %}

{% block submit-row %}

{{ block.super }}

Cancel

{% endblock %}

Be sure that your application is above "admin" in INSTALLED_APPS.
Looks like this in German locale:

A: <input type="button" name="Cancel" value="Cancel">

You can this line anywhere inside admin/submit_line.html


text:
Q: hover over tooltip? cant get it to work with a list in a top navbar? I have been using W3schools to figure this out but i cant see what i have done wrong?
I have added the  text to the image icons in the top left which is what i want to appear as a tooltip when hovered over. I have only tried to style the first one (location tooltip) but i can't for the life of me figure out where i have gone wrong. An explanation would be great because as far as i can see it should work?

body {
  margin: 0;
}

/* Top NAVBAR */

.topbar {
  background-color: #17D8C7;
  height: 35px;
  overflow: hidden;
  align-items: center;
  padding: 0 2% 0 2%;
}

.topbar nav {
  display: flex;
  justify-content: space-between;
  padding-top: 5px;
}

.topbar ul {
  margin: 0;
  padding-left: 0;
  list-style: none;
  position: relative;
  display: inline-block;
}

.topbar ul li {
  display: inline-block;
  vertical-align: middle;
}

.topbar ul li a {
  display: inline-block;
  text-align: center;
  text-decoration: none;
}

.topbar ul li img {
  height: 24px;
  padding: 0px 5px 0px 0px;
  vertical-align: middle;
}

.topbar ul li a span {
  vertical-align: middle;
}

.topright span {
  padding: 10px;
  color: #ffffff;
}

.topbar a {
  color: rgba(255, 255, 255, 0.8);
}

.topbar a:hover {
  color: white;
}

.location-pin {
  position: relative;
  display: inline-block;
}

.location-pin .locationtooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 1;
  top: 150%;
  left: 50%;
  margin-left: -60px;
}

.location-pin .locationtooltiptext::after {
  content: "";
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent black transparent;
}

.location-pin:hover .locationtooltiptext {
  visibility: visible;
}

  <link rel="stylesheet" type="text/css" href="style.css" />
  <title>Complete Suites</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

        EN11 0LB

        contact@completesuites.co.uk

        8:30 - 16:00

          Email Promotions

Blog|

About Us|

Contact

A: Just replace
.location-pin .locationtooltiptext

with
.location-pin + .locationtooltiptext

Also, all the other instances.
Explanation:
The selector .location-pin .locationtooltiptext means element with class .locationtooltiptext which in .location-pin.
You want .locationtooltiptext which is just next to .location-pin you need the selector .location-pin + .locationtooltiptext

The adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element

https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors

html, body {
  height: 100%;
}

body {
  margin: 0;
}

/* Top NAVBAR */

.topbar {
  background-color: #17D8C7;
  height: 35px;
  align-items: center;
  padding: 0 2% 0 2%;
}

.topbar nav {
  display: flex;
  justify-content: space-between;
  padding-top: 5px;
}

.topbar ul {
  margin: 0;
  padding-left: 0;
  list-style: none;
  position: relative;
  display: inline-block;
}

.topbar ul li {
  display: inline-block;
  vertical-align: middle;
}

.topbar ul li a {
  display: inline-block;
  text-align: center;
  text-decoration: none;
}

.topbar ul li img {
  height: 24px;
  padding: 0px 5px 0px 0px;
  vertical-align: middle;
}

.topbar ul li a span {
  vertical-align: middle;
}

.topright span {
  padding: 10px;
  color: #ffffff;
}

.topbar a {
  color: rgba(255, 255, 255, 0.8);
}

.topbar a:hover {
  color: white;
}

.location-pin {
  position: relative;
  display: inline-block;
}

.location-pin .locationtooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 1;
  top: 150%;
  left: 50%;
  margin-left: -60px;
}

.location-pin .locationtooltiptext::after {
  content: "";
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent black transparent;
}

.location-pin:hover .locationtooltiptext {
  visibility: visible;
}

  <link rel="stylesheet" type="text/css" href="style.css" />
  <title>Complete Suites</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

          EN11 0LB

        contact@completesuites.co.uk

        8:30 - 16:00

          Email Promotions

Blog|

About Us|

Contact


text:
Q: Malware in old website - how to migrate? I was hired to build a new website for a company who's old website has turned into a dumpster fire.  I was then asked to migrate over 1000 blog posts from the old website to the new website. This has come with its own problems as everything is running on ancient versions of everything and the export is massive. During all of this troubleshooting I was informed that the old website has something called a "zeus" virus.  So my question is,  is it likely that importing the database to a new site will also import that malware and if so is there a way to ensure that I am only copying the required info?
Thanks!

A: There is more to do to clean up a site than export/import posts data. The malware can be anywhere. And it could have gotten into your site via many paths.
Before you export/import posts, you need to ensure that the current posts are not the source of malware. I'd do a whole cleaning of the existing site before an export/import into a brand new site.
From a similar question, I answered this:
I would recommend a de-hacking inspection. If you think your site got hacked, there are several (many) things you must do to 'de-hack' it. Including:

*

*changing all passwords (WP admins, FTP, hosting, database)

*reinstalling WP (via the Updates page) and then reinstalling all themes (from the repository) and plugins manually.

*checking for unknown files (via your hosting File Manager; if you sort by date, invalid ones should stick out because you updated everything).

There are lots of help in the googles (or bings or ducks) on how to de-hack a site. I wrote a set of procedures that I use. It can be done, though, just takes a bit of work. My process is detailed here: https://securitydawg.com/recovering-from-a-hacked-wordpress-site/
(Added: if you do my cleaning process, you may not need to create a new site. I've cleaned sites successfully using that process.)
(Although this question is not within scope of this place, hacking questions happen often enough here that the answer might be helpful to you and others.)


text:
Q: Is there a way to schedule sending an e-mail through Google App Engine Mail API (Python)? I want to be able to schedule an e-mail or more of them to be sent on a specific date, preferably using GAE Mail API if possible (so far I haven't found the solution).
Would using Cron be an acceptable workaround and if so, would I even be able to create a Cron task with Python? The dates are various with no specific pattern so I can't use the same task over and over again.
Any suggestions how to solve this problem? All help appreciated

A: You can easily accomplish what you need with Task API. When you create a task, you can set an ETA parameter (when to execute). ETA time can be up to 30 days into the future.
If 30 days is not enough, you can store a "send_email" entity in the Datastore, and set one of the properties to the date/time when this email should be sent. Then you create a cron job that runs once a month (week). This cron job will retrieve all "send_email" entities that need to be send the next month (week), and create tasks for them, setting ETA to the exact date/time when they should be executed.

A: Yes, sending emails from cron jobs is fairly common, exactly for the scheduling reason.
Unfortunately controlling cron jobs programatically is not (yet) possible. You may want to star Issue 3638: Cron jobs to be scheduled programatically
Meanwhile you could check this answer for a couple of alternatives: https://stackoverflow.com/a/37079488/4495081