text:
Q: Create PHP Class or Object from XML Document I'm working with XML documents returned by an API. The XML returns a list of products, with attributes for each project such as inventory, item number, name, price, etc.
I can loop through all of the XML tables creating lists of all the products with the appropriate fields displayed. The problem is, I need to be able to define certain products and their variables.
How can I create classes, or arrays from the XML products, but only for certain ones? For example, there may be 40 products returned, but I may only need 3 of them. The array or class must contain all the relevant information for the product.
Here's a link to an example of the raw XML returned by the API
An example of the XML is
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet xmlns="">

        <ChargeDescID>14249</ChargeDescID>
        <sChgDesc>Cleaning Deposit</sChgDesc>
        <dcPrice>0.0000</dcPrice>
        <dcTax1Rate>0</dcTax1Rate>
        <dcTax2Rate>0</dcTax2Rate>
        <dcInStock>0.0000</dcInStock>

        <ChargeDescID>14251</ChargeDescID>
        <sChgDesc>Utility Knife</sChgDesc>
        <dcPrice>2.9900</dcPrice>
        <dcTax1Rate>9</dcTax1Rate>
        <dcTax2Rate>0</dcTax2Rate>
        <dcInStock>0.0000</dcInStock>

</NewDataSet>

So using the second product in the above code as an example, I'd like a PHP function that will create either a class, or an array like this:
$utility_knife (
  "ChargeDescID" => "14251",
  "dcPrice" => "2.99",
  "dcTax1Rate" => "9",
  "dcTax2Rate" => "0",
  "dcInStock" => "0",
 )

How can I pull out specific diffgr tables and format them into named arrays or classes, ignoring the tables I don't need? How do I get the contents of a table while ignoring the other tables?
Edit to include what I've attempted:
I've already been able to pull them into an array using loadXML() and DOMXPath as follows:
$dom = new DOMDocument;
$dom->loadXML($result);
$xpath = new DOMXPath($dom);
$el = $xpath->query('//Table');

#loop through results
foreach($el as $units) {

    $ChargeDescID = $xpath->query('ChargeDescID', $units)->item(0)->nodeValue;
    $sChgDesc = $xpath->query('sChgDesc', $units)->item(0)->nodeValue;
    $dcPrice = $xpath->query('dcPrice', $units)->item(0)->nodeValue;
    $dcTax1Rate = $xpath->query('dcTax1Rate', $units)->item(0)->nodeValue;
    $dcTax2Rate = $xpath->query('dcTax2Rate', $units)->item(0)->nodeValue;
    $dcInStock = $xpath->query('dcInStock', $units)->item(0)->nodeValue;

    #create oragnized array for results
    $iterate_list = array("ChargeDescID"=>$ChargeDescID,"sChgDesc"=>$sChgDesc, "dcPrice"=>$dcPrice, "dcTax1Rate"=>$dcTax1Rate, "dcTax2Rate"=>$dcTax2Rate, "dcInStock"=>$dcInStock);
    #create/append array of array
    $results_list[] = $iterate_list;

}

So now I have an array named $results_list with sub arrays organized in $key/$value pairs, but the arrays themselves aren't named. I can print out the results in an organized fashion as so:
        foreach($results_list as $key => $value) {

    echo
        "Charge Description ID: " . $results_list[$key]["ChargeDescID"] . "
" .
        "Item Description: " . $results_list[$key]["sChgDesc"] . "
" .
        "Item Price: " . $results_list[$key]["dcPrice"] . "
" .
        "Tax rate 1: " . $results_list[$key]["dcTax1Rate"] . "
" .
        "tax rate 2: " . $results_list[$key]["dcTax2Rate"] . "
" .
        "In Stock: " . $results_list[$key]["dcInStock"] . "
"
        ;
    }

EDIT: This solution I proposed below worked. I'm currently using it, but I'm open to more elegant solutions. Preferably one that selects the node directly without the need of conditional logic. ThW proposed something that may work. I'm waiting for clarification from him.
The problem is that I can't figure out how to get specific products. I know I can use the array index, but the index may change from one pull to the next. I think I need some sort of function that says something similar to:
foreach($results_list as $key => $value){
  if ( $results_list[$key]["sChgDesc"] == "Utility Knife" ) {
    $utility_knife = array(
      "sChgDesc" => $results_list[$key]["sChgDesc"],
      "dcPrice" => $results_list[$key]["dcPrice"],
      "dcTax1Rate" => $results_list[$key]["dcTax1Rate"],
      "dcInStock" => $results_list[$key]["dcInStock"],
  );

and then write out the if statements for each product I need within the array.Is that about right?
I've tried wrapping my head around how to do this so many times now that I'm starting to confuse myself. I wasn't sure if I could call an if statement on one of the sub-array values and then loop back through the rest of the values in that particular sub array if the value exists.
The criteria of what needs to be picked out is that I have to be able to identify which product I'm choosing. So it could be dependent on the ChargeDescID, or the sChgDesc, but not really anything else. I then need to make sure the other relevant fields are populated.

A: You're already using XPath, but it can do a lot more. DOMXpath::query() is limited, too. Use DOMXpath::evaluate() - it can return scalar values.
For example:
$ChargeDescID = $xpath->query('ChargeDescID', $units)->item(0)->nodeValue;

Can be refactored to:
$ChargeDescID = $xpath->evaluate('string(ChargeDescID)', $units);

XPath can contain complex conditions. Let's say you want to fetch the Table element nodes with the diffgr:id attribute Table1:
$xpath->registerNamespace('diffgr', 'urn:schemas-microsoft-com:xml-diffgram-v1');
$el = $xpath->evaluate('//Table[@diffgr:id="Table1"]');

XPath does not have a default namespace so if you want to address nodes in a different namespace then the empty namespace (xmlns="") you need to register a prefix for it. This can be the same prefix like in the document or a different one.
On the other side you can fetch nodes by name or more generic. * represents any element node.
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('diffgr', 'urn:schemas-microsoft-com:xml-diffgram-v1');
$el = $xpath->evaluate('//Table[@diffgr:id="Table1"]');

$results_list = [];
foreach ($el as $units) {
  $iterate_list = [];
  foreach ($xpath->evaluate('*', $units) as $valueNode) {
    $iterate_list[$valueNode->localName] = $valueNode->nodeValue;
  }
  $results_list[] = $iterate_list;
}
var_dump($results_list);

Output:
array(1) {
  [0]=>
  array(6) {
    ["ChargeDescID"]=>
    string(5) "14249"
    ["sChgDesc"]=>
    string(16) "Cleaning Deposit"
    ["dcPrice"]=>
    string(6) "0.0000"
    ["dcTax1Rate"]=>
    string(1) "0"
    ["dcTax2Rate"]=>
    string(1) "0"
    ["dcInStock"]=>
    string(6) "0.0000"
  }
}

A: You already tried something this:
 $xml = simplexml_load_file('file_xml.xml');

 print '
';

 print_r($xml);

The print_r used only for debugging


text:
Q: Rake, how to create a task with multiple inputs and one output? We have a rails app, and we use webpack which takes multiple javascript files and outputs one single javascript file. It takes a long time to run, and I'd like to create a rake task for this. But being new to rake I need some help.
I'd like to use rake's build system so that I can get automatic checking of the time stamps between the input and output .js files. So that if any of the input files are newer than the output file it will execute webpack. Otherwise if the none of the input files are newer than the output file, than the task does nothing.
In MSBuild, this is a cakewalk and lightning fast. But in Ruby I'm kind of lost.
I'm guessing it might consist of writing file tasks, and looping through and making the one output file depend on the inputs. Or should I use a rule, like this?
outputfile = "~/foo.js"
inputfiles = Dir["~/**/*.js"]

rule outputfile => inputfiles do
  bin/webpack bla bla bla
end

A: You can use Rake::FileList to achieve this. Something like this:
file "foo.js" => Rake::FileList["**/*.js"] do
  ...
end

And, I'm not sure whether rake allows to use ~ in paths, I believe a full path is required. Or just use a "#{Dir.home}/foo.js" rule.
Then call it using:
rake ~/foo.js

And when you have multiple outputs:
task :build => Rake::FileList["config1.xml", "config2.xml"] do
  # all that stuff is run only when the FileList above is changed
  touch 'foo1.js'
  touch 'foo2.js'
  sh "compile foo3.js"
  sh "do-anything-else foo4.js"
end

Run it using:
rake build

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP Laravel use helper class in all views I would like to create a helper (function) to avoid repeating code between all views in Laravel 5. The function should be using data from the database (Eloquent), so it cannot be just a simple function or a generic view composer.
Ideally it should be something like:
{!! Helper::addLinks($text) !!}

Where the Helper class uses Eloquent to validate the $value. I would like to avoid changing all Controllers. What is the best practice for this?
Update; I have the following working prototype. This function searches the text and replaces words found from the dictionary with hyperlinks:
function addLinks($text) {
    //retrieve words from database
    $words = Words::all();

    //build dictionary with values that needs replacement
    $patterns = array();
    foreach ($words as $word) {
        $patterns[$word->id] = $word->word_name;
    }

    //build dictionary with values the replacements
    $replacements = array();
    foreach ($words as $word) {
        $replacements[$word->id] = "id . "\">" . $patterns[$word->id] . "";
    }

    //return text, replace words from dictionary with hyperlinks
    return str_replace($patterns, $replacements, $text);
}

I want to use this function in several text blocks and paragraphs in the views. What approach is best?

A: You could create a helper class in your app/ folder? Ex.

namespace App;

use App\Models\User;

class Helper
{
    /**
     * Description...
     *
     * @param mixed $value
     *
     * @return mixed
     */
    public static function lookup($value)
    {
        return User::find($value);
    }
}

You could utilize it by calling {!! App\Helper::lookup($value) !!}
It would be useful to know exactly what you're looking to validate with eloquent using a helper so we could properly determine the most attractive practice for the use case.


text:
Q: How do I force a JOIN to use a specific index in MySQL? I have a query that JOINs 2 tables; lineitem and part,
select
        sum(l_extendedprice* (1 - l_discount)) as revenue
from
        lineitem force index for join (l_pk),
        part
where
        (
                p_partkey = l_partkey
                and p_brand = 'Brand#12'
                and p_container in ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG')
                and l_quantity >= 1 and l_quantity <= 1 + 10
                and p_size between 1 and 5
                and l_shipmode in ('AIR', 'AIR REG')
                and l_shipinstruct = 'DELIVER IN PERSON'
        )
        or
        (
                p_partkey = l_partkey
                and p_brand = 'Brand#23'
                and p_container in ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK')
                and l_quantity >= 10 and l_quantity <= 10 + 10
                and p_size between 1 and 10
                and l_shipmode in ('AIR', 'AIR REG')
                and l_shipinstruct = 'DELIVER IN PERSON'
        )
        or
        (
                p_partkey = l_partkey
                and p_brand = 'Brand#34'
                and p_container in ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG')
                and l_quantity >= 20 and l_quantity <= 20 + 10
                and p_size between 1 and 15
                and l_shipmode in ('AIR', 'AIR REG')
                and l_shipinstruct = 'DELIVER IN PERSON'
        );

I have an index on lineitem and want the query to use this index for the join p_partkey = l_partkey
create index l_pk on tpch.lineitem(l_partkey);

MySQL explain shows:
| id | select_type | table    | type   | possible_keys | key     | key_len | ref                     | rows    | Extra       |
+----+-------------+----------+--------+---------------+---------+---------+-------------------------+---------+-------------+
|  1 | SIMPLE      | lineitem | ALL    | l_pk          | NULL    | NULL    | NULL                    | 5982534 | Using where |
|  1 | SIMPLE      | part     | eq_ref | PRIMARY       | PRIMARY | 4       | tpch.lineitem.L_PARTKEY |       1 | Using where |
+----+-------------+----------+--------+---------------+---------+---------+-------------------------+---------+-------------+

Why is the index l_pk not used?

A: Even though you are using FORCE INDEX the Query Optimizer took over as expected.
The pass through the lineitem table exceeded more than 5% of the total index entries. This is what lead to the Query Optimizer to dismiss using the index. Oracle, MSSQL and PostgreSQL would not have done any different.
Here is my sick attempt at refactoring the query
select sum(l_extendedprice* (1 - l_discount)) as revenue
from
(
    select p_partkey l_partkey,'S' contsize from part
    where p_brand = 'Brand#12'
    and p_container in ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG')
    and p_size between 1 and 5
    union
    select p_partkey,'M' contsize from part
    where p_brand = 'Brand#23'
    and p_container in ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK')
    and p_size between 1 and 10
    union
    select p_partkey,'L' contsize from part
    where p_brand = 'Brand#34'
    and p_container in ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG')
    and p_size between 1 and 15
) partkeys
left join listitem using (l_partkey)
where
    l_shipmode in ('AIR', 'AIR REG') and
    l_shipinstruct = 'DELIVER IN PERSON' and
    IF(contsize='S',IF(l_quantity >= 1 and l_quantity <= 1 + 10,1,0),
        IF(contsize='M',IF(l_quantity >= 10 and l_quantity <= 10 + 10,1,0),
            IF(contsize='L',IF(l_quantity >= 20 and l_quantity <= 20 + 10,1,0),0)
        )
    )
;

You may need to index the tables
ALTER TABLE parts ADD INDEX brand_container_size_ndx
(p_brand,p_container,p_size,p_partkey);
ALTER TABLE listitem ADD INDEX partkey_shipinstruct_shipmode_quantity_ndx
(l_partkey,l_shipinstruct,l_shipmode ,l_quantity);

Give it a Try and let us know if it is fast or if it even works.

A: The index l_pk isn't being used because of the way tables are joined.
To make use an index, we need to have something to look up in that index.
When joining two tables, there's a value in the left table and we need to match it up with corresponding rows in the right table, so we use the index on the right table to find the matching rows  -- OR, there's a value in the right table and we need to match it up with rows in the left table, so we use an index on the left table to find the matching rows.
You don't use an index on both tables to perform the join -- you use one or the other.  In this case the primary key on part is being used for the join.
So, the next question is "why?"
To answer that, we consider what your query is asking the server to do.
Either of these two processes, performed by the server would generate the same result:
You're asking the server to...

*

*find all the rows in lineitem based on values you've supplied for l_quantity, l_shipmode, and l_shipinstruct ... and then join to all the matching rows on part, but only those that also have the expected values for p_brand, p_container, and p_size... OR

*find rows in part based on p_brand, p_container, and p_size and then identify the matching rows in lineitem where there are matching values for l_quantity, l_shipmode, l_shipinstruct.

Your possible_keys contain only one index each, which suggests that none of the columns you're searching ... p_brand, p_container, p_size, l_quantity, l_shipmode, l_shipinstruct ... have indexes on them.
So the server is going to have no choice but to do a full table scan on one table or the other.  It's choosing lineitem because it has concluded that this will be the most cost-effective route.
The real issue appears to be that you're searching on columns that should be indexed.


text:
Q: flutter simple calculation Function error When i call the function one time it run perfectly but if i call it again it will show different value and read the different else block please check the code i am attaching the whole class and driver code and output of the following function
i think there is error in if else condition block i dont undestand why it is giving different values on calling the function 2nd time if i run it again third time it will give correct output
enum ComponentCondition { missing, damaged, good }
class ComponentModel {
  String name;
  ComponentCondition condition;

  double rate;

  double componentPercent;
  double kerbWeight;
  double componentPrice;

  int lifespan;
  int age;
  ComponentModel(
      {this.name,
      @required this.rate,
      @required this.lifespan,
      @required this.kerbWeight,
      @required this.componentPercent,
      @required this.age});

  int calculatePrice() {
    double weight = (componentPercent * kerbWeight) / 100;
    age = DateTime.now().year - age;
    double scrapValue = weight * rate;
    int i = lifespan ~/ 3;

    if ((condition == ComponentCondition.good ||
            condition == ComponentCondition.damaged) &&
        i == 0) {
      componentPrice = scrapValue;
    } else if (condition == ComponentCondition.good && age < lifespan) {
      if (age >= 0 && age <= i) {
        print('bestconditionPrice');
        componentPrice = scrapValue * 3;
      } else if (age > i && age <= i * 2) {
        componentPrice = scrapValue * 2;
      } else if (age > i * 2 && age < lifespan) {
        componentPrice = scrapValue * 1.5;
      }
    } else if ((age >= lifespan) || condition == ComponentCondition.damaged) {
      componentPrice = scrapValue;
      print('why??????');
    } else
      componentPrice = 0;

    return componentPrice.toInt();
  }

  void updateCondition(ComponentCondition partCondition) {
    condition = partCondition;
  }
}

void main(List<String> args) {
  ComponentModel engine = ComponentModel(
      componentPercent: 18, kerbWeight: 695, rate: 17, lifespan: 13, age: 2021);
  engine.updateCondition(ComponentCondition.good);
  int price = engine.calculatePrice();
  int price2 = engine.calculatePrice();
  print(' price1 :$price');
  print("price2 : $price2");

}

A: You are updating the age variable in the class. So, the second calculation will be based on a different age and hence the disparity.
Create a local age variable in the calculatePrice() function and perform calculations based on that for consistency.

A: First, this is a very well asked question, you presented a perfectly reproducable example, so congrats.
As for your question, I'm not entirely sure what you want to happen, but I will show you what to change, so your compiler will tell you where you go wrong:

*

*Use the latest version of Flutter. It supports null-safety.

*Use the final keyword a lot more. Every variable, that you do not expect to change, make them final. That way, when you do change them by accident, your compiler will throw an error and you will immediately notice.

*Initialize all data. Null-safety will help you here because you will again get compile errors when you forget.

*Do not keep instance data, just because you can. If something can be a local variable, make it a local variable.

*Do keep methods short and concise, so do not go into endless if/then chains when you can simply return and be done with it.

So after a few best practice changes, your code looks like this:
enum ComponentCondition { missing, damaged, good }

class ComponentModel {
  String? name;
  ComponentCondition condition = ComponentCondition.good;

  final double rate;
  final double componentPercent;
  final double kerbWeight;
  final int lifespan;
  final int age;

  ComponentModel(
      {this.name,
      required this.rate,
      required this.lifespan,
      required this.kerbWeight,
      required this.componentPercent,
      required this.age });

  int calculatePrice() {
    final weight = (componentPercent * kerbWeight) / 100;
    final double scrapValue = weight * rate;
    final i = lifespan ~/ 3;

    age = DateTime.now().year - age;

    if ((condition == ComponentCondition.good || condition == ComponentCondition.damaged) && i == 0) {
      return scrapValue.toInt();
    }

    if (condition == ComponentCondition.good && age < lifespan) {
      if (age >= 0 && age <= i) {
        print('bestconditionPrice');
        return (scrapValue * 3).toInt();
      }

      if (age > i && age <= i * 2) {
        return (scrapValue * 2).toInt();
      }

      if (age > i * 2 && age < lifespan) {
        return (scrapValue * 1.5).toInt();
      }
    }

    if ((age >= lifespan) || condition == ComponentCondition.damaged) {
      return scrapValue.toInt();
    }

    return 0;
  }

  void updateCondition(ComponentCondition partCondition) {
    condition = partCondition;
  }
}

void main(List<String> args) {
  ComponentModel engine = ComponentModel(componentPercent: 18, kerbWeight: 695, rate: 17, lifespan: 13, age: 2021);
  engine.updateCondition(ComponentCondition.good);
  final price = engine.calculatePrice();
  final price2 = engine.calculatePrice();
  print('price1 :$price');
  print('price2 : $price2');
}

And now you get a glaring compiler error saying:

Error: The setter 'age' isn't defined for the class 'ComponentModel'.

*

*'ComponentModel' is from 'package:dartpad_sample/main.dart' ('lib/main.dart').
age = DateTime.now().year - age;
^^^
Error: Compilation failed.

This is great. The compiler just caught your error. You accidentially reassigned the age variable, instead of using a local variable, lets say something called "years". Maybe you should rename this.age to this.ModelMakeYear then your age local variable would be perfect.
So with this changes, your code should look like this:
enum ComponentCondition { missing, damaged, good }

class ComponentModel {
  String? name;
  ComponentCondition condition = ComponentCondition.good;

  final double rate;
  final double componentPercent;
  final double kerbWeight;
  final int lifespan;
  final int modelMakeYear;

  ComponentModel(
      {this.name,
      required this.rate,
      required this.lifespan,
      required this.kerbWeight,
      required this.componentPercent,
      required this.modelMakeYear });

  int calculatePrice() {
    final weight = (componentPercent * kerbWeight) / 100;
    final double scrapValue = weight * rate;
    final i = lifespan ~/ 3;

    final age = DateTime.now().year - modelMakeYear;

    if ((condition == ComponentCondition.good || condition == ComponentCondition.damaged) && i == 0) {
      return scrapValue.toInt();
    }

    if (condition == ComponentCondition.good && age < lifespan) {
      if (age >= 0 && age <= i) {
        print('bestconditionPrice');
        return (scrapValue * 3).toInt();
      }

      if (age > i && age <= i * 2) {
        return (scrapValue * 2).toInt();
      }

      if (age > i * 2 && age < lifespan) {
        return (scrapValue * 1.5).toInt();
      }
    }

    if ((age >= lifespan) || condition == ComponentCondition.damaged) {
      return scrapValue.toInt();
    }

    return 0;
  }

  void updateCondition(ComponentCondition partCondition) {
    condition = partCondition;
  }
}

void main(List<String> args) {
  final engine = ComponentModel(componentPercent: 18, kerbWeight: 695, rate: 17, lifespan: 13, modelMakeYear: 2021);
  engine.updateCondition(ComponentCondition.good);
  final price = engine.calculatePrice();
  final price2 = engine.calculatePrice();
  print('price1 :$price');
  print('price2 : $price2');
}

Works like a charm:

bestconditionPrice
bestconditionPrice
price1 :6380
price2 : 6380

The important part here is not the fish, but the fishing method: keep to all the best practices and let your compiler do the heavy lifting. It's a great tool, use it.


text:
Q: Solving partial differential equation $u_x + 2xu_y + (2x - 6)u = 0$ I'm trying to solve the differential equation above by separating the variables. Thus, I let $u(x,y) = X(x)Y(y)$. As such, $u_x = X'(x)Y(y)$ and $u_y = Y'(y)X(x)$.
The differential equation above can then be rewritten as:
$X'(x)Y(y) + 2xX(x)Y'(y) + (2x - 6)X(x)Y(y) = 0$
However, I find myself stuck after this step as I'm unable to separate the variables and shift all the functions/variables with x to 1 side of the equation and all the functions/variables with y to the other side of the equation.
Some help will be greatly appreciated. Thanks a lot :)

A: $$u_x + 2xu_y = (6-2x)u$$
Why not the method of characteristics ?
https://en.wikipedia.org/wiki/Method_of_characteristics
The Charpit-Lagrange system of characteristic ODEs is :
$$\frac{dx}{1}=\frac{dy}{2x}=\frac{du}{(6-2x)u}$$
A first characteristic equation comes from solving $\frac{dx}{1}=\frac{dy}{2x}$ :
$$y-x^2=c_1$$
A second characteristic equation comes from solving $\frac{dx}{1}=\frac{dy}{2x}=\frac{6dx-dy}{6-2x}=\frac{du}{(6-2x)u}\quad;\quad d(6x-y)=\frac{du}{u}$
$$u\:e^{y-6x}=c_2$$
The general solution of the PDE expressed on the form of implicit equation $c_2=F(c_1)$ is :
$$u\:e^{y-6x}=F(y-x^2)$$
$F$ is an arbitrary function.
$$\boxed{u(x,y)=e^{6x-y}F(y-x^2)}$$
If some boundary condition was specified in the wording of the problem one could determine the function $F$ in order to find the particular solution satisfying both the PDE and the boundary condition.


text:
Q: c# Find SelectedRow in Dynamically created DataGridView Inside TabControl I have a tabcontrol and datagridview is created dynamically inside the tabpage of tabcontrol . I need to extract the selected row item values from the active datagridview. The name for this grid would also be dynamically set. what can i do to get the column values from selected row ? Below is the code which is executed in form load event
foreach (DataTable dtTable in Ds.Tables)
        {
DataGridView dgv = new DataGridView();
            //dgv.DataSource = dtTable;
            dgv.AllowUserToAddRows = false;
            dgv.AllowUserToDeleteRows = false;
            dgv.ColumnHeadersHeightSizeMode =     System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            dgv.Dock = System.Windows.Forms.DockStyle.Fill;
            dgv.Location = new System.Drawing.Point(3, 3);
            dgv.Name = "dgv_" + dtTable.TableName;
            dgv.ReadOnly = true;
            dgv.Size = new System.Drawing.Size(725, 322);
            dgv.TabIndex = 0;
            dgv.AutoGenerateColumns = false;

            foreach (DataColumn dtCol in dtTable.Columns)
            {
                DataGridViewColumn column = new DataGridViewTextBoxColumn();
                column.FillWeight = 1;
                column.Name = dtCol.ColumnName;
                column.DataPropertyName = dtCol.ColumnName;
                dgv.Columns.Add(column);
            }

            //dgv.Columns.AddRange(columns);
            dgv.DataSource = null;
            dgv.DataSource = dtTable;

            lblInfo.Text = string.Format("Rows : {0} ; Columns : {1}", dtTable.Rows.Count, dtTable.Columns.Count);

            TabPage tpInstdata = new System.Windows.Forms.TabPage();
            tpInstdata.Controls.Add(dgv);
            tpInstdata.Location = new System.Drawing.Point(4, 22);
            tpInstdata.Name = "tp_" + dtTable.TableName;
            tpInstdata.Padding = new System.Windows.Forms.Padding(3);
            tpInstdata.Size = new System.Drawing.Size(725, 322);
            tpInstdata.TabIndex = 1;
            tpInstdata.Text = dtTable.TableName;
            tpInstdata.UseVisualStyleBackColor = true;
            tcInstTab.TabPages.Add(tpInstdata);
}

A: Connect each dgv to the same SelectionChanged eventhandler in your foreach loop:
dgv.SelectionChanged += aDataGridView_SelectionChanged;

The event handler function could look like this:
    private void aDataGridView_SelectionChanged(object sender, System.EventArgs e)
    {
        string aValue = ((DataGridView)sender).SelectedRows[0].Cells["ColumnOfYourInterest"].Value.ToString();
    }


text:
Q: What to pass as parameter in change of model-bound select if anything? If I have a model-bound select and want to handle the change event, do I need to pass anything in my event handler - or should I be able to access the model-bound value eg. program?
    <select [(ngModel)]="changeDetails.program" name="program" #program="ngModel" required
         class="form-control" (change)="HandleChange(???)">
             <option *ngFor="let subProgram of programs" [value]="subProgram.value">
             {{subProgram}}</option>
    </select>

in the component class:
    HandleChange(???) {
       // use model value on class? or parameter?
    }

A: You could handle the ngModelChange event, and pass $event to the event handler. That parameter will have the new selected value:
(ngModelChange)="HandleChange($event)"

If, for some reason, you prefer to handle the change DOM event, you can pass the selected value with $event.target.value (since $event refers to the DOM event object in that case):
(change)="HandleChange($event.target.value)"

In both cases, the event handler would get the new value:
HandleChange(value) {
 console.log("New selected value", value);
}

See this stackblitz for a demo.


text:
Q: scanf reads more chars than the destination var can hold The following code reads up to 10 chars from stdin and output the chars.
When I input more than 10 chars, I expect it to crash because msg has not enough room, but it does NOT! How could that be?
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>

 int main(int argc, char* argv[])
 {
     char* msg = malloc(sizeof(char)*10);
     if (NULL==msg)
         exit(EXIT_FAILURE);
     scanf("%s", msg);
     printf("You said: %s\n", msg);
     if (strlen(msg)<10)
         free(msg);
     return EXIT_SUCCESS;
 }

A: Use fgets instead, scanf is not buffer safe. What you are seeing is Undefined Behavior.

A: You may allocate "safe" big size when using scanf(). On user input it should be 2 lines (cca. 2x80 chars), in case of files some bigger.
Conclusion: scanf() is kinda quick-and-dirty stuff, don't use it in serious projects.

A: You can specify max size in scanf() format string
scanf("%9s", msg);

A: I would imagine that malloc() allocates blocks of memory aligned to word boundaries. On a 32-bit machine, that means whatever you ask for will be rounded up to the nearest multiple of 4. That means you might get away with a string of at least 11 characters (plus a '\0' terminator) without suffering any problems.
But don't ever assume this to be the case. Like everyone else is saying, you should always specify a safe maximum length in your format string if you want to avoid problems.

A: It does not crash because c is very lenient, contrary to popular belief. It is not required for the program to crash or even complain if a buffer is overflown. Say you define
union{
 uint8_t a[3]
 uint32_t b
}

then a[4] is perfectly fine memory and there is no reason to crash (but don't ever do this). Even a[5] or a[100] may be perfectly fine.
On the other hand I may try to access a[-1] which happens to be memory the OS does not allow you to access, causing a segfault.
As to what you should do to fix this:as others have pointed out, scanf is not safe to use with buffers. Use on of their suggetsions.


text:
Q: Executar uma função em um tempo determinado Bom dia, recentemente estou a querer executar um método que faz o envio de mails do tipo newsletter de tempos em tempos. Acredito ter encontrado a solução, porem não consigo por ela em pratica que é a seguinte:
/****************************************************************************
*
*                         Agendador de Tarefas
*
*  Desenvolvido por Lucas Phillip
*
/***************************************************************************/

using System;
using System.Collections.Generic;
using System.Threading;

namespace MyTimers
{
    /// <summary>
    /// Cria uma nova agenda.
    /// </summary>
    /// <param name="horario"></param>
    class Scheduler
    {
        private static Dictionary<string, Scheduler> SchedulePool = new Dictionary<string, Scheduler>();

        private System.Threading.Timer scheculetimer;
        private StartTime start;
        private TimerCallback MethodCallBack;
        private TimeSpan frequencia;
        private int maxexec = 0;

        /// <summary>
        /// Define ou Retorna o ID da tarefa
        /// </summary>
        public String ID { get; set; }
        /// <summary>
        /// Define ou Retorna a frequência com que a tarefa se repete após sua primeira execução.
        /// Utilize timespan(0) para não repetir
        /// </summary>
        public TimeSpan Frequencia { get { return frequencia; } set { frequencia = value; } }
        /// <summary>
        /// Retorna o número de vezes que que o método foi executado
        /// </summary>
        public int CountExec { get; set; }
        /// <summary>
        /// Define ou Retorna o número máximo de vezes para executar a tarefa
        /// </summary>
        public int MaxExec { get { return maxexec; } set { maxexec = value; } }
        /// <summary>
        /// Define ou Retorna o objeto Timer da tarefa
        /// </summary>
        public System.Threading.Timer ScheduleTimer { get { return scheculetimer; } set { scheculetimer = value; } }

        public Scheduler(TimerCallback Method)
        {
            MethodCallBack = Method;
        }

        public class StartTime
        {
            public int Hour { get; set; }
            public int Minutes { get; set; }
        }

        /// <summary>
        /// Adiciona uma nova tarefa que será executada determidado horário
        /// </summary>
        /// <param name="State"></param>
        /// <param name="Execute"></param>
        public void AddSchedule(object State, StartTime horario)
        {
            start = horario;
            if (ID != null)
            {
                TimerCallback method = new TimerCallback(Loop);
                ScheduleTimer = new System.Threading.Timer(method, State, StartDelay(), Frequencia);

                SchedulePool.Add(ID, this);
            }
            else
            {
                throw new Exception("É preciso definir um ID para a tarefa!");
            }
        }

        /// <summary>
        /// Adiciona uma tarefa que será executada depois de um delay
        /// </summary>
        /// <param name="State"></param>
        /// <param name="Delay"></param>
        public void StartWithDelay(object State, TimeSpan Delay)
        {
            if (ID != null)
            {
                TimerCallback method = new TimerCallback(Loop);
                ScheduleTimer = new System.Threading.Timer(method, State, Delay, Frequencia);

                SchedulePool.Add(ID, this);
            }
            else
            {
                throw new Exception("É preciso definir um ID para a tarefa!");
            }
        }

        private void Loop(object State)
        {
            //Adicinona +1 à contagem de vezes que a tarefa foi executada
            CountExec++;
            if (MaxExec > 0)
            {
                if (CountExec > MaxExec)
                {
                    Dispose();
                    return;
                }
            }

            //Invoca o metedo
            MethodCallBack.Invoke(State);

            //Confere se a tarefa se repete. Se não repetir libera a memória
            if (Frequencia.Ticks == 0)
            {
                Dispose();
            }
        }

        /// <summary>
        /// Retorna um TimeSpan com o dalay inicial, baseado na data agendada
        /// </summary>
        /// <returns></returns>
        private TimeSpan StartDelay()
        {
            //Define os minutos antes de definir a hora, pois aqueles podem influenciar nestes
            int waitminute = GetMinutes();
            int waithour = GetHour();
            return new TimeSpan(waithour, waitminute, 0);
        }

        private int GetMinutes()
        {
            if (start.Minutes > DateTime.Now.Minute)
            {
                return start.Minutes - DateTime.Now.Minute;
            }
            else
            {
                start.Hour--;
                return start.Minutes - DateTime.Now.Minute + 60;
            }
        }

        private int GetHour()
        {
            if (start.Hour > DateTime.Now.Hour)
            {
                return start.Hour - DateTime.Now.Hour;
            }
            else if (start.Hour < DateTime.Now.Hour)
            {
                return start.Hour - DateTime.Now.Hour + 24;
            }
            else
            {
                return 0;
            }
        }

        public void Dispose()
        {
            ScheduleTimer.Dispose();
            if (SchedulePool.ContainsKey(ID))
                SchedulePool.Remove(ID);
        }

        public class Control
        {
            /// <summary>
            /// Retorna a referencia para a tarefa
            /// </summary>
            /// <param name="ScheduleId"></param>
            /// <returns></returns>
            public static Scheduler GetTimer(String ScheduleId)
            {
                if (SchedulePool.ContainsKey(ScheduleId))
                {
                    return SchedulePool[ScheduleId];
                }
                else
                {
                    throw new Exception("A tarefa especificada para cancelar não existe");
                }
            }

            /// <summary>
            /// Cancela a tarefa atual
            /// </summary>
            /// <param name="ScheduleId"></param>
            public static void Cancel(String ScheduleId)
            {
                Scheduler schedule = GetTimer(ScheduleId);
                schedule.Dispose();
            }

            /// <summary>
            /// Adiciona um int à quantidade máxima de execuções. Se não houver limite, define um.
            /// </summary>
            /// <param name="ScheduleId"></param>
            /// <param name="Times"></param>
            public static void AddExec(String ScheduleId, int Times)
            {
                Scheduler schedule = GetTimer(ScheduleId);
                schedule.MaxExec += Times;
            }

            /// <summary>
            /// Executa o método agendado.
            /// </summary>
            /// <param name="ScheduleId"></param>
            /// <param name="State"></param>
            public static void Execute(String ScheduleId, object State)
            {
                Scheduler schedule = GetTimer(ScheduleId);
                schedule.MethodCallBack.Invoke(State);
            }
        }
    }
}

Tenho o problema de como fazer o chamado da função que executa o envio dos email. Estou fazendo tentando executar com o código:
Scheduler task = new Scheduler(enviaNewsletter);
            task.ID = "EnviaNewsletter";
            task.Frequencia = new TimeSpan(1, 0, 0, 0);
            task.MaxExec = 2;

Scheduler.ControlScheduler.Execute("EnviaNewsletter",1);

E minha função é a seguinte:
public void enviaNewsletter(Object state)
        {
            Conteúdo...
        }

Alguém consegue me ajudar tentei de varias maneiras mas sem resultado então por enquanto parei por aqui.

A: Eu sei que não é bem o que você quer mas a solução para isto é criar uma tarefa agendada no sistema operacional que execute a aplicação que deseja. Não tem porque ficar reinventando a roda.
Saiba que não é algo trivial e tem uma quantidade enorme de detalhes que programadores não especialistas terão muita dificuldade.
Mas se quer insistir pelo menos use uma biblioteca que faz o grosso o trabalho por você. Algumas delas:

*

*Quartz - acredito ser a mais usada e completa.

*Task Scheduler Managed Wrapper

*A New Task Scheduler Class Library for .NET

*Chroniton
Coloquei no GitHub para referência futura.


text:
Q: ¿Se puede colocar una imagen de gran tamaño como xxhdpi y ajustarla a las densidades menores, o hay que colocar una imagen para cada densidad? Tengo carpetas llenas de imágenes de distintas densidades. Quiero saber si es necesario colocar las 5 imágenes para las distintas densidades (hdpi, mdpi, xhdpi, xxhdpi, xxxhdpi) o simplemente considerar sólo una imagen de gran tamaño, o sea, la xxxhdpi, y ajustarla dentro del layout y la pantalla del teléfono.

A: ¿Se puede colocar una imagen de gran tamaño como xxhdpi y ajustarla a las densidades menores, o hay que colocar una imagen para cada densidad?
Puedes colocar una imagen de "gran tamaño" dentro de /drawable y no necesitarías agregar de otras densidades, pero debes tener cuidado porque podrías tener problemas de consumo de memoria, incluso puedes agregar una sola imagen de tamaño aceptable y esta se desplegaría sin problema en todas las densidades.
Pero definitivamente lo recomendable es agregar la imagen de acuerdo a su densidad para que se despliegue correctamente en todas las densidades:
36x36 (0.75x) : baja densidad.
48x48 (1.0x baseline) media densidad.
72x72 (1.5x) for alta densidad.
96x96 (2.0x) for extra alta densidad.
144x144 (3.0x) for extra-extra alta densidad.
192x192 (4.0x) for extra-extra-extra alta densidad.

Para nuevos desarrollos, puedes generar automáticamente las imágenes de iconos optimas a partir de una imagen de buena calidad,  ve a tu proyecto y selecciona New > Image Asset

Seleccionas Asset Type y escoges la imagen que deseas de buena resolución para generar todas las necesarias:

De esta forma se generarían automáticamente imágenes con las medidas necesarias en los directorio de cada densidad dentro de cada folder /mipmap :

A: Si es necesario tener las 5 resoluciones ya que Android Studio administra de forma "automática" dependiendo del tamaño de la pantalla que icono usar. Si no cumples con esto corres el riesgo de que tu icono se vea borroso.
Nota: Todas las imágenes las vamos a poner en la carpeta drawable y los iconos en la carpeta mipmap.

A: Es necesario incluir imágenes distintas para cada densidad.
El sitio oficial de Android para desarrolladores indica que para admitir varias densidades de pantalla hay que crear recursos en distintos tamaños, uno para cada densidad. Fuente: Cómo admitir varias densidades de pantalla
Además, en esta pregunta de Stack Overflow donde consultan por lo mismo, la respuesta aceptada indica precisamente lo que te digo aquí. También dan links para herramientas que permiten generar imágenes en distintos tamaños para admitir las diferentes densidades.

A: Más que decir si es necesario o no es necesario, yo voy a decir que es "evitable" generar imágenes para distintas densidades. Con una sola imagen y las medidas de la imagen parametrizadas en dimens.xml, en mi caso adapto un fichero dimens.xml para cada densidad (ésto me resulta necesario hacerlo en general, no sólo para las imágenes, así que lo aprovecho para este tema). El único detalle a tener en cuenta es que hay que usar una imagen que quede bien en todas las densidades, pero lo que queda bien para la densidad más amplia en pantalla, me suele quedar bien para las menores.
A mí ésta solución me vale siempre de momento porque no he tenido necesidad de usar grandes gráficos, así que para imágenes de botones, menús, etc. me resulta una opción bastante ágil.


text:
Q: How to insert triples into Parliament Triple Store with Jena Library Hi I want to add spatial based triple
http://www.izmirdeafet.com/Disaster htp://www.opengis.net/ont/geosparql#asWKT> "htp://www.opengis.net/def/crs/OGC/1.3/CRS84 POINT (8.46035239692792 51.48661096320327)"^^<http://www.opengis.net/ont/sf#wktLiteral>
into parliament triple store with jena library in the below java code but ı have taken error in the below. I have spatial based ontology which ı add already into triple store.
public static void main(String[] args) {
    // set to false when running the second time to avoid recreating the graphs/index
    boolean firstTime = true;
    // create spatial index factory and configure for GeoSPARQL. This is used
    // by the GraphStore whenever a new named graph is created.
    SpatialIndexFactory factory = new SpatialIndexFactory();
    Properties properties = new Properties();
    properties.setProperty(Constants.GEOMETRY_INDEX_TYPE,
                     Constants.GEOMETRY_INDEX_RTREE);
    properties.setProperty(Constants.GEOSPARQL_ENABLED,
                     Boolean.TRUE.toString());
    factory.configure(properties);

    // register factory
    IndexFactoryRegistry.getInstance().register(factory);

    // create a Parliament graph and graph store
    //KbGraph graph= KbGraphFactory.createNamedGraph();
    KbGraph graph =
    KbGraphFactory.createDefaultGraph("file:C:\\ParliamentKB\\data\\");
    KbGraphStore graphStore = new KbGraphStore(graph);
    graphStore.initialize();

    if (firstTime) {
        // create spatial index from factory
        SpatialIndex index = factory.createIndex(graph, null);

        // register index with IndexManager
        IndexManager.getInstance().register(graph, null, factory, index);

        // the following tells the graph store that the graph is now an
        // indexing graph. This is necessary so that the next time Parliament
        // loads, the index is read in automatically.
        graphStore.setIndexingEnabled(KbGraphStore.DEFAULT_GRAPH_NODE, true);
    }

    // create a Jena model
    Model model = ModelFactory.createModelForGraph(graph);

    // load data
    String fileName =
    "C:\\Users\\Can\\Desktop\\DisasterOntologyEnglish\\disaster.rdf";
    RDFFormat dataFormat = RDFFormat.parseFilename(fileName);
    FileManager.get().readModel(model, fileName, dataFormat.toString());

    // get index and print size
    System.out.println(IndexManager.getInstance().
        getIndexes(graph).get(0).size());

    // do a spatial query
    String query = ""
    + "\nPREFIX my:  <http://somewhere/ApplicationSchema#>"
    + "\nPREFIX geo: <http://www.opengis.net/ont/OGC-GeoSPARQL/1.0/>"
    + "\nPREFIX geof:
     <http://www.opengis.net/def/queryLanguage/OGC-GeoSPARQL/1.0/function/>"
    + "\nSELECT ?f" + "\nWHERE { my:A my:hasExactGeometry ?aGeom ."
    + "\n        ?aGeom geo:asWKT ?aWKT ."
    + "\n        ?f my:hasExactGeometry ?fGeom ."
    + "\n        ?fGeom geo:asWKT ?fWKT ."
    + "\n        FILTER (geof:sf-contains(?aWKT, ?fWKT) &&"
    + "\n                !sameTerm(?aGeom, ?fGeom)) " + "\n}";

    Query q = QueryFactory.create(query, Syntax.syntaxARQ);
    ResultSet rs = QueryExecutionFactory.create(q, model).execSelect();
    while (rs.hasNext()) {
        System.out.println(rs.nextSolution());
    }
}

ERROR
   Exception in thread "main" java.lang.UnsatisfiedLinkError:
    no Parliament in   java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at com.bbn.parliament.jni.Config.<clinit>(Config.java:184)
    at com.bbn.parliament.jena.graph.KbGraphFactory.getKbConfigForDefaultGraph
         (KbGraphFactory.java:81)
    at com.bbn.parliament.jena.graph.KbGraphFactory.createDefaultGraph
         (KbGraphFactory.java:38)
    at com.disaster.demo.GeoSPARQLTest.main(GeoSPARQLTest.java:46)

I think problem is coming from createdefaultgraph part:
you said dir path taken from ParliamentConfig.txt
  KbGraph graph = KbGraphFactory.createDefaultGraph("file:C:\\ParliamentKB\\data\\");

I coded like this but it didnt work.

A: The unsatisfied link error probably indicates that it can't find Parliament.dll in the java path.
Check this SO for details about dll's in the java path:
java.lang.UnsatisfiedLinkError no *****.dll in java.library.path
Also, are you following the Parliament setup guide?
http://parliament.semwebcentral.org/ParliamentUserGuide.pdf
You also might want to make sure you're using the right dll... it's been a while so I may be wrong, but I think there's 32 and 64 bit builds.

A: In the Parliament User Guide (http://parliament.semwebcentral.org/ParliamentUserGuide.pdf), Section 2.8 on page 26 is devoted to troubleshooting these UnsatisfiedLinkError problems.

A: Your problem as per the exception thrown is due to gaps in cofiguration/establishing the Parliament environment variables. Please follow the ParliamentUserGuide as provided in the answers above. Once that is complete you will get and output like this:
INFO [main] (KbGraphStore.java:163) - Adding named graph: <http://parliament.semwebcentral.org/parliament#MasterGraph> (graphDir = "master")
Apr 07, 2014 2:17:05 PM org.geotools.referencing.factory.epsg.ThreadedEpsgFactory <init>
INFO: Setting the EPSG factory org.geotools.referencing.factory.epsg.ThreadedHsqlEpsgFactory to a 1800000ms timeout
Apr 07, 2014 2:17:05 PM org.geotools.referencing.factory.epsg.ThreadedEpsgFactory <init>
INFO: Setting the EPSG factory org.geotools.referencing.factory.epsg.DefaultFactory to a 1800000ms timeout
Apr 07, 2014 2:17:05 PM org.geotools.referencing.factory.epsg.ThreadedHsqlEpsgFactory createDataSource
INFO: Building new data source for org.geotools.referencing.factory.epsg.ThreadedHsqlEpsgFactory
Apr 07, 2014 2:17:05 PM org.geotools.referencing.factory.epsg.ThreadedHsqlEpsgFactory createBackingStore
INFO: Building backing store for org.geotools.referencing.factory.epsg.ThreadedHsqlEpsgFactory
Apr 07, 2014 2:17:05 PM org.geotools.referencing.factory.epsg.ThreadedHsqlEpsgFactory createBackingStore
INFO: Creating cached EPSG database version 7.5.0. This operation may take a few minutes...
Apr 07, 2014 2:17:06 PM org.geotools.referencing.factory.PropertyAuthorityFactory <init>
WARNING: Axis elements found in a wkt definition, the force longitude first axis order hint might not be respected:
PROJCS["Google Projection",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84", 6378137.0, 298.257223563, AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]],UNIT["degree", 0.017453292519943295],AXIS["Geodetic longitude", EAST],AXIS["Geodetic latitude", NORTH],AUTHORITY["EPSG","4326"]],PROJECTION["Popular Visualisation Pseudo Mercator", AUTHORITY["EPSG","1024"]],PARAMETER["semi_minor", 6378137.0],PARAMETER["latitude_of_origin", 0.0],PARAMETER["central_meridian", 0.0],PARAMETER["scale_factor", 1.0],PARAMETER["false_easting", 0.0],PARAMETER["false_northing", 0.0],UNIT["m", 1.0]]

Only after which you can perform any operations on the model created, like adding triples and query.
Further to a Triple with spatial attribute: say you want to add a spatial co-ordinate to an Individual (eg. individual) you can use the following code snippet:
import com.bbn.parliament.jena.graph.index.spatial.geosparql.datatypes.WKTLiteral;
import com.bbn.parliament.jena.graph.index.spatial.geosparql.vocabulary.*;
.
.
.
WKTLiteral geoLiteral = new WKTLiteral();
String value="Point(22.5 88.5)";// OR "POLYGON((22.5 88.5, 88.5 99.5, 99.5 22.5))"
individual.addLiteral(Geo.asWKT, model.createTypedLiteral(value, geoLiteral));

And the Trick for:
KbGraph graph = KbGraphFactory.createDefaultGraph("file:C:\\ParliamentKB\\data\\");
does not work, I don't know why! so you may need to specify th epath in ParliamentCOnfig.txt itself.


text:
Q: Is there a way that I can set the iOS music app to save my progress during playback? I've noticed since updating to iOS 9 that if I pause music playback in the middle of a song, then return to the music app after a period of time, the song begins playing again from the beginning. Not where I left off. This can get annoying if you are listening to a longer file, like a mix or (I would imagine) an audiobook. Is there a way for me to change the setting so that my position within the song will be remembered?

A: If you set the media type to audiobook or podcast it will give you the option to remember playback position, but it will be moved to the iBooks or Podcast app instead of being able to be played in Music.


text:
Q: laravel schedule protection from sending bulk email multiple times I use mailchimp to send bulk emails once per day.
I use the laravel scheduler to execute the API calls to Mailchimp.
Do I need to protect myself from accidentally executing the scheduled calls multiple times? (i.e. could the scheduled job potentially run multiple times when laravel crashes?)

A: its best practice to protect yourself even if it won't happen , you can add tracking for that schedule, like adding it to the database with the time of the execution and the time of the end of the execution. "Better safe then sorry" because probably you will some subscribers or marked as spam if that happen.
PS : the finish time is just to check if the task finished executing.


text:
Q: Android PopupWindow vs. DialogFragment I'm attempting to make a popup window that inflates on a button click in my application shows a listview populated by an adapter. Currently, I'm using a DialogFragment and it works alright. But I'd like to be able to adjust the size and ideally the position of the dialog.
After doing some research, PopupWindow allows you to adjust the size and position of the box, but it doesn't play nice with instantiating a fragment within its view. DialogFragment works nicely for using a fragment and listview, but to my knowledge you can't control the size and position of it.
Has anyone had a similar situation or experience in creating a dynamic popup?

A: To change the DialogFragment's size, I did the following withing the OnCreateView method
Note: Code in C# for MonoDroid; eaisly translated to Java for raw Android
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    base.OnCreateView(inflater, container, savedInstanceState);

    View thisView = inflater.Inflate(Resource.Layout.NewContactDialog, container, false);

    thisView.Post(() =>
        {
            ViewGroup.LayoutParams lp = thisView.LayoutParameters;

            lp.Width = 500;

            thisView.LayoutParameters = lp;

            thisView.Invalidate();
        }

    );

    return thisView;
}

This code is from experimentation. What I settled on was just using a centered DialogFragment (the default behavior) and undimming the background. You can override the style for the DF, and either base it on the existing theme
<style name="MyDialogFragment" parent="android:Theme.Holo.Dialog">
  <item name="android:windowIsFloating">true</item>
</style>

Or completely style it from the ground up
<style name="MyDialogFragment">
  ... (set all items, check docs)
</style>

For starts try using the MyDialogFragment style above and set windowIsFloating to false
and see the effects (just set your theme to this with the SetStyle member).
Some good links for styles and themes you'll need to do your own styling and overriding the defaults:
http://www.therealjoshua.com/2012/01/styling-android-with-defaults/
http://developer.android.com/guide/topics/ui/themes.html/
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/styles.xml/
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml/
I'll be honest, working with DialogFragments and PopupWindows is a pain, but they are specialized views that solve some real GUI issues, so don't give up. If you need any more info, just ask in the comments below (I realize this is not an answer, I'm just trying to help, b/c I'm working on this stuff right now).


text:
Q: Being unable to update Cookie using php I am using a cookie to save a PHP array(0 => 0, 1=>0,......,99=>0) and I encode the array into JSON in order to be able to save it in the cookie, the problem is that when I decode the JSON to retrieve the array and change the value of a field I am unable to update the cookie and I dont really know why.
This is the code I use to create the cookie:
$carrito=array(0=>0);
            $sql = "SELECT ID FROM productos";
            $ids = $conn->query($sql);
            if ($ids->num_rows > 0){
                while($row = $ids->fetch_assoc()) {
                    array_push($carrito, 0);
                }
            } else {
                echo "0 results";
            }
            $conn->close();//cerramos la conexión
            setcookie("carrito", json_encode($carrito), time()+(86400),"/");

And this is the code I use to decode the JSON and go throught the arrat to modify it:
 if(isset($_POST["id"])){
            $idProducto=$_POST["id"];
            $data = json_decode(stripslashes($_COOKIE["carrito"]),true);
            print_r($data);
            echo "
".$idProducto."
";
            foreach($data as $id => $cantidad){
                if($id == $idProducto){
                    $cantidad++;
                }
            }
            print_r($data);
            setcookie("carrito", json_encode($data), time()+(86400),"/");
        }

The problem is that after decoding the json when I try to go throught the array it doesnt recognize the line $data as $id => $cantidad.
This is what I get when I print_r($data):
Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 [12] => 0 [13] => 0 [14] => 0 [15] => 0 )

A: Already solved this by using:
$data[$idProducto]++;

instead of the foreach loop


text:
Q: Java 7 and and 8 coexisting on Windows 7 Pro x64 - how to fix running old jar files I have a Win7 Pro x64 Box with both JRE 7u80 and 8u60 (both are i586 versions) running since I have two applications that either need the one or the other to run.
I am aware of being able to start JAR-files by calling a batch with the according path to java.exe that's what I tried:
start "c:\Program Files (x86)\Java\jre7\bin\java.exe" "c:\samplepath\some.jar"

(It should be
start "c:\Program Files (x86)\Java\jre7\bin\java.exe" -jar "c:\samplepath\some.jar"

according to the documentation, but the -jar switch leads to an error that -jar couldn't be found)
This call does start the application without problems as long as Java 8 isn't installed which leads me to the conclusion it's probably ok.
While Java 8 is installed this call does "nothing" - well, almost. I can see the java process in task manager for a few seconds, then it disappears without a trace, there is no error message or whatsoever.
I even deleted the Java entry from %path% and rebooted, changed the order of the JRE installations, deactivated Java 8 in the Java control panel, no luck. If Java 8 is installed my jar won't run.
Talking to the developer isn't an option since he is no longer available. I am out of ideas here. Can somebody help with what I could try next?
Right now I keep the installation files on the desktop to install and dump Java 8 on demand which is quite a ridiculous and desperate manner to deal with it :-)

A: But the -jar switch leads to an error that -jar couldn't be found
Your start` syntax is incorrect:

*

*If there is no title and command is surrounded by quotes "..." (because it contains spaces) then it is misinterpreted as a title.

*In your case "c:\Program Files (x86)\Java\jre7\bin\java.exe" is interpreted as the title and -jar as a command (which of course cannot be found).
Your command should be:
start "title" "c:\Program Files (x86)\Java\jre7\bin\java.exe" -jar "c:\samplepath\some.jar"

You can use "" (empty string) as the title if you prefer:
start "" "c:\Program Files (x86)\Java\jre7\bin\java.exe" -jar "c:\samplepath\some.jar"

Syntax

START "title" [/D path] [options] "command" [parameters]

Key:
title       Text for the CMD window title bar (required.)
path        Starting directory.
command     The command, batch file or executable program to run.
parameters  The parameters passed to the command.

...
Always include a TITLE this can be a simple string like "My Script" or
  just a pair of empty quotes ""
According to the Microsoft documentation, the title is optional, but
  depending on the other options chosen you can have problems if it is
  omitted.

Source start
Further Reading

*

*An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

*start - Start a program, command or batch script (opens in a new window).


text:
Q: C++ repeating codes with a loops Im not sure if this is a stupid question, so shoot me if it is!
I am having this "dilemna" which I encounter very often. I have say two overloaded functions in C++
say we have this two overloads of F (just a pseudocode below)
void F(A a, .../*some other parameters*/)
{
  //some code part
  //loop Starts here
  G1(a,.../* some other parameter*/)
  //loop ends here
  //some code part
}

void F(B b, .../*some other parameters*/)
{
  //some code part
  //loop Starts here
  G2(b,.../* some other parameter*/)
  //loop ends here
  //some code part
}

where A and B are different types and G1 and G2 are different functions doing different things. The code part of the overloads except for G1 and G2 lines are the same and they are sometimes very long and extensive. Now the question is.. how can I write my code more efficiently. Naturally I want NOT to repeat the code (even if it's easy to do that, because its just a copy paste routine). A friend suggested macro... but that would look dirty. Is this simple, because if it is Im quite stupid to know right now. Would appreciate any suggestions/help.
Edit: Im sorry for those wanting a code example. The question was really meant to be abstract as I encounter different "similar" situation in which I ask myself how I am able to make the code shorter/cleaner. In most cases codes are long otherwise I wouldn't bother asking this in the first place. As KilianDS pointed out, it's also good to make sure that the function itself isn't very long. But sometimes this is just unavoidable. Many cases where I encounter this, the loop is even nested (i.e. several loops within each other) and the beginning of F we have the start of a loop and the end of F we end that loop.
Jose

A: A simple way to prevent the code duplication in this case would be to use a template. E.g:
void G(A a,.../* some other parameter*/)
{
    G1(a,.../* some other parameter*/);
}
void G(B b,.../* some other parameter*/)
{
    G2(b,.../* some other parameter*/);
}

template <typename T>
void F(T x, .../*some other parameters*/)
{
  //some code part
  //loop Starts here
  G(x,.../* some other parameter*/)
  //loop ends here
  //some code part
}

Note how the overloaded G function is used to determine whether to call G1 or G2.
However, also note that this only prevents the code duplication, not the duplication in the compiled executable (because each template instantiation creates its own code).
Depending on the surrounding architecture there might be a number of other viable options (e.g. virtual methods instead of G1/G2 calls, function pointers, lambda functions if you have C++11...)

A: The most obvious solution is to put the common code parts into separate
functions, and call them:
void F( A a, ... )
{
    commonPrefix(...);
    G1( a, ... );
    commonPostfix(...);
}

void F( B b, ... )
{
    commonPrefix(...);
    G2( a, ... );
    commonPostfix(...);
}

if there is a lot of data shared between the prefix and the postfix, you
could create a class to hold it, and make the functions members.
Alternatively, you could forward to a template, possibly using traits:
template <typename T>
class GTraits;

template<>
class GTraits<A>
{
    static void doG( A a, ... ) { G1( a, ... ); }
};

template <>
class GTraits<B>
{
    static void doG( B b, ... ) { G2( b, ... ): }
};

template <typename T>
void doF( T t, ... )
{
    //  ...
    GTraits<T>::doG( t, ... );
    //  ...
}

void F(A a, ...)
{
    doF( a, ... );
}

void F(B b, ...)
{
    doF( b, ... );
}

This could easily result in the common parts of the code being
duplicated, however.  (Whether this is a problem or not depends.  In
most cases, I suspect that the code bloat would be minimal.)
EDIT:
Since you say that the common code includes the loop logic: you can use
the template method pattern, something like:
class CommonBase
{
    virtual void doG( other_params ) = 0;
public:
    void doF()
    {
        //  prefix
        //  loop start
        doG( other_params );
        //  loop end
        //  suffix
    }
};

You then define a separate derived class in each function:
void F( A a ,... )
{
    class DoG : public CommonBase
    {
        A myA;
        void doG( other_params ) { G1( myA, other_params ); }
    public:
        DoG( A a ) : myA( a ) {}
    } do( a );
    do.doF();
}

The fact that you need the forwarding constructor makes it a bit wordy,
but it does keep all of the common code common.


text:
Q: BIRT Reporting Chart dataset mismatch I am using Birt Designer 4.4+, and BIRT 3.2.23 engine. I have my report attached to an SQLServer datasource, and have most of the report completed. I have a summary section of the report which looks something like the section below...
Date Range  | Category 1 | Category 2
--------------------------------------
At Start    | 203        | 19
At End      | 111        | 29
Open During | 23         | 04

I need to create a pie chart to show the % of category 1 versus the other category(s). My problem is that the BIRT pie charts only allow me to show data based on the left column (the date range) for a specific column (e.g. I could compare date ranges against category 1. It will not allow you to compare say - the values of category 1 against category 2 at end. For note, in this example I am only interested in comparisons at the end of the date range.
I'v decided to attempt to create a new datasource that only queries the values 'at end', however am left with an SQL select that looks similar to this..
Date Range   | Category 1  | Category 2
-----------------------------------------
At End       | 101         | 29

I'd like to swap this on the axis to look similar to this...
Date Range   | At End
-----------------------
Category 1   | 101
Category 2   | 29

I'v looked into pivots, but it does not seem like it will work in my specific case, since I have something similar to the query below. Any advice on this topic is appreciated. Also any workarounds in BIRT is also appreciated if I do not have to change my data set. It looked like it might be an option in later versions of BIRT but sadly I do not have the option of updating currently.
Original Dataset
SELECT
    SUM(
        CASE WHEN itc.category_id=1230 THEN 1
        ELSE 0 END
    ) AS cAtEnd,
    SUM(
        CASE WHEN (itc.category_id=1233 OR itc.category_id=1234) THEN 1
        ELSE 0 END
    ) AS rAtEnd,
    SUM(
        CASE WHEN (itc.category_id=1235 OR itc.category_id=1236) THEN 1
        ELSE 0 END
    ) AS aAtEnd
FROM
    i
JOIN
    itc ON itc.i_id=i.id AND itc.category_id IN (1230, 1233, 1234, 1235, 1236)

I should note that I shortened the SQL considerably - so if it seems like something is missing it is likely because I cut it out (or changed the name for simplicity/etc). The basic idea though is still the same.
Aside - My question is very similar in nature to the question found here: https://www.eclipse.org/forums/index.php/t/62398/

A: I ended up finding an easier way to create the desired result - please note I would still be interested in any other solutions to this (perhaps shorter ones or ones that do not have as many possible issues).
Create a new Data Set, simply UNION ALL to create the desired rows. Since my dataset only involved 3 rows it was not too bad.
SELECT total, 'set one' FROM table
UNION ALL
SELECT total2, 'set two' FROM table2

This will create the desired SQL result set, that can be used in a regular fashion on the BIRT report.
I really hope I did not over-complicate this for no reason.


text:
Q: Question about best way to establish a specific database design I've looked around on the Stack Exchange websites and I've found 2 websites where I can ask this question. https://dba.stackexchange.com/ and https://softwareengineering.stackexchange.com/ . Now normally I think Database administrators would be the best place to put it, but then I looked on the website and saw a lot of questions that don't really relate to my question. So I went looking on Stack Exchangeand and I found Programmers and I read the tour part:

Programmers Stack Exchange is a question and answer site for professionals and students in software development and related fields who are interested in getting expert answers on conceptual questions about software development.

So I was thinking I do need "expert answers on questions about software development and/or related fields," since I need the best way to establish a specific database design.
But my question has so much to do with Databases, that I can't figure out where to ask it.
Where should I ask this question?

A: I understand your uncertainty over this topic, I've found myself in similar situations where the right site won by a tight margin.
The topic does overlap DBA and Programmers SE, but if you consider your design question as conceptual, then Programmers SE sounds like the site you are looking for. Although I dare say that your question would be well received on DBA as well, I still recommend Programmers.
For future reference and readers... Adding a tiny bit of detail about the question you are asking would make it significantly easier to recommend you a proper site. Also it is a great idea what you did, to check the site and get first hand impression of what kind of questions are asked there.


text:
Q: Displaying an image in python from SQLite BLOB I'm getting into some more advanced python stuff and I decided to take on a personal project that involved using a SQLite database. I want to store an image as a BLOB in the SQLite database but any method I've seen creates an image in the root folder and then converts that into binary to put into the BLOB in the SQLite database. The same thing happens when you want to view the image again. The binary is pulled from the database and an image is saved locally to be viewed.
I was wondering if there was a way to strictly view the image without having to save a copy of the image locally.
I know I could immediately delete the file right after the data is uploaded and downloaded from the database but that seems like too many steps. I can also include an option to create a local file if there was ever a need to use one, but the fact of storing an image both locally and in a SQLite database seems wasteful and redundant.


text:
Q: How do I pass an object to the CreateThread function? I want to pass an object of a class as argument to the CreateThread function.
The object is created this way in main:
Connection *connection = new Bluetooth();
Brick *nxt = new Brick(connection);

The function that I pass to CreateThread is:
DWORD WINAPI recieveFunct(Brick nxt)

Finally, CreateThread is called in main:
IDRecieveThread = CreateThread(NULL, 0, recieveFunct, *nxt, 0, NULL);

In main I create the nxt object. This object has read and write functions that I want to call from the thread. However, I can't get it to work.
Do I need it to cast the object to HANDLE? Or am I looking completely wrong?

Thanks for your feedback guys!
I have implemented the solution given above like this:
int main()
{
  HANDLE IDRecieveThread = 0;

  //set up the NXT
 Connection *connection = new Bluetooth(); Brick *nxt = new Brick(connection);

  //Setup connection
  cout << "connecting..." << endl;
  connection->connect(3);
  cout << "connected" << endl;

  cout << "Starting recieve thread...." << endl;
  IDRecieveThread = CreateThread(NULL, 0, recieveFunct, reinterpret_cast<void*>(nxt),  0, NULL);
  cout << "Recieve thread started" << endl;
}

But the compiler gives this error:
C:\Documents and Settings\Eigenaar\Bureaublad\BluetoothTestr\test\main.cpp||In function `int main()':|
C:\Documents and Settings\Eigenaar\Bureaublad\BluetoothTestr\test\main.cpp|39|error: invalid conversion from `void (*)(void*)' to `DWORD (*)(void*)'|
C:\Documents and Settings\Eigenaar\Bureaublad\BluetoothTestr\test\main.cpp|39|error:   initializing argument 3 of `void* CreateThread(_SECURITY_ATTRIBUTES*, DWORD, DWORD (*)(void*), void*, DWORD, DWORD*)'|
C:\Documents and Settings\Eigenaar\Bureaublad\BluetoothTestr\test\recievethread.h|4|warning: 'void recieveFunct(void*)' declared `static' but never defined|
||=== Build finished: 2 errors, 1 warnings ===|

Can someone tell me what is wrong? I'm getting the error when I call the CreateThread function.

A: You need to cast nxt to LPVOID, not HANDLE. MSDN says "LPVOID lpParameter [in, optional] - A pointer to a variable to be passed to the thread." This design pattern for passing data to a callback function or thread is commonly called a "user data" pointer.
http://msdn.microsoft.com/en-us/library/ms682453%28v=vs.85%29.aspx
You can just cast your Brick pointer to LPVOID (i.e. a pointer to void) when you call CreateThread() and uncast it in your recieveFunct thread func:
static void recieveFunct(void* pvBrick)
{
    Brick* brick = reinterpret_cast<Brick*>(pvBrick);
}

Connection *connection = new Bluetooth(); Brick *nxt = new Brick(connection);
IDRecieveThread = CreateThread(NULL, 0, recieveFunct, reinterpret_cast<void*>(nxt), 0, NULL);

Also, you might consider using beginthreadex() instead of CreateThread() if you are using the MSVCRT library. beginthreadex() will ensure that MSVCRT is properly initialized for your thread.

A: Use this signature:
DWORD WINAPI recieveFunct(void* pParam)
{
   Brick* pBrick = (Brick*)pParam; // Or whichever casting you prefer

  // Use the  `pBrick`

  return 0;
}

Create the thread as:
Brick *nxt = new Brick(connection);
CreateThread(NULL, 0, recieveFunct, (void*)nxt, 0, NULL);


text:
Q: Using php explode to iterate through an array from XML Im having trouble getting the type of song in an xml file. First off I am loading in the XML file using
$xmlDoc = file_get_contents('/songs.xml');
once the file has been loaded into a string I explode them into an array using
$songs = explode("<song>", $xmlDoc);
I have tried using a foreach loop to step through each song then exploding the type, however this isn't giving me just the type it's including Rock</type>.
songs.xml
<songs>
    <song>
        <title>Paradise City</title>
        <artist>Guns & Roses</artist>
        <type>Rock</type>
    </song>
    <song>
        <title>One Love</title>
        <artist>Bob Marley</artist>
        <type>Reggae</type>
    </song>
    <song>
        <title>Sweet Child Mine</title>
        <artist>Guns & Roses</artist>
        <type>rock</type>
    </song>
</songs>

A: You need to use a SimpleXMLElement or DomDocument
Example from W3C : https://www.w3schools.com/php/php_xml_simplexml_read.asp
$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
print_r($xml);
SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder [body] => Don't forget me this weekend! )

After that, you can parse the "xml" like an array. Enjoy


text:
Q: Values are incorrect while using String.Format I need to convert a decimal value into something like

0.3 = USDC000000000030

The code i wrote is as below.
   transactionAmount = String.Format("USDC{0}", ((int)(amount*100)).ToString("D12"));

However, it is working for some values perfectly like the example given above. For other some values it is conversion is wrong for example

0.9 = USDC000000000089
1 = USDC000000000099
1.1 USDC000000000109

Any idea why is it happening so?
Thanks in advance

A: You're probably using double, which for financial values is a huge mistake.
Use decimal instead, and wash your troubles away.
To wit:
decimal amount = 0.3m;
string s = String.Format("USDC{0:000000000000}", 100 * amount);
Console.WriteLine(s);

Output:
USDC000000000030

Note that the language specification states:

The decimal type is a 128-bit data type suitable for financial and monetary calculations.

A: Try this instead:
String.Format("USDC{0:D12}", (int)(Convert.ToDecimal(amount) * 100));

Tested with the following:

*

*0.90 = USDC000000000090

*1.00 = USDC000000000100

*0.89 = USDC000000000089

*0.84 = USDC000000000084

*1.10 = USDC000000000110


text:
Q: Code to analyze pcap file I am trying to analyse a file containing packets captured using tcpdump. I first want to categorize the packets into flows using 5-tuple. Then I need to get the size and inter-arrival time of each packet in each flow. I tried Conversation list in wireshark but it gives only the number of packets in the flow not information about each packet in the flow. A suggestion for any code (c++ or shell script) that can do the job? Thank you

A: UmNyobe,
If you haven't heard of Scapy yet I beleive what you are trying to do would be a near perfect fit. For example I wrote this little snippet to parse a pcap field and give me something like what you are talking about using Scapy.
#!/usr/bin/python -tt

from scapy import *
import sys
from datetime import datetime

'''Parse PCAP files into easy to read NETFLOW like output\n
   Usage:\n
   python cap2netflow.py <[ pcap filename or -l ]>\n
   -l is live capture switch\n
   ICMP packets print as source ip, type --> dest ip, code'''

def parse_netflow(pkt):
    # grabs 'netflow-esqe' fields from packets in a PCAP file
    try:
        type = pkt.getlayer(IP).proto
    except:
        pass

    snifftime = datetime.fromtimestamp(pkt.time).strftime('%Y-%m-%d %H:%M:%S').split(' ')[1]

    if type == 6:
        type = 'TCP'
    if type == 17:
        type = 'UDP'
    if type == 1:
        type = 'ICMP'

    if type == 'TCP' or type == 'UDP':
        print( ' '.join([snifftime, type.rjust(4, ' '), str(pkt.getlayer(IP).src).rjust(15, ' ') , str(pkt.getlayer(type).sport).rjust(5, ' ') , '-->' , str(pkt.getlayer(IP).dst).rjust(15, ' ') , str(pkt.getlayer(type).dport).rjust(5, ' ')]))

    elif type == 'ICMP':
        print(' '.join([snifftime, 'ICMP'.rjust(4, ' '),  str(pkt.getlayer(IP).src).rjust(15, ' ') , ('t: '+ str(pkt.getlayer(ICMP).type)).rjust(5, ' '), '-->' , str(pkt.getlayer(IP).dst).rjust(15, ' '), ('c: ' + str(pkt.getlayer(ICMP).code)).rjust(5, ' ')]))

    else:
        pass
if '-l' in sys.argv:
    sniff(prn=parse_netflow)
else:
    pkts = rdpcap(sys.argv[1])
    print(' '.join(['Date: ',datetime.fromtimestamp(pkts[0].time).strftime('%Y-%m-%d %H:%M:%S').split(' ')[0]]))
    for pkt in pkts:
        parse_netflow(pkt)

Install Python and Scapy then use this to get you started. Let me know if you need any assistance figuring it all out, if you know C++ chances are this will already make alot of sense to you.
Get Scapy here
http://www.secdev.org/projects/scapy/
There are tons of links on this page to helpful tutorials, keep in mind Scapy does alot more but hone in on the areas that talk about pcap parsing..
I hope this helps!
dc

A: I worked on a library to analyze tcp dump but it was for a business so I cannot just give to you. if you don't find what you are looking for then my answer can help. A tcpdump is just nested network data like the Matryoshka dolls, where the pcap layer is added by tcpdump.
If you only want to work on the captures, the format of a dump is specified in Libpcap File Format. To get the size and time of arrival of each packet you need to process the dump using this specification.
If you have to go deeper in the analysis these are the following layers in order

*

*the link layer

*the internet layer

*Transport layer

*The application layer

Each layer has a header definition. So you need to find which protocol stack your pcap data contains and to parse the header to get information.

A: What are the members of the 5-tuple?  If the flows are TCP or UDP, the source and destination IP addresses and port numbers, plus, perhaps, a number to distinguish multiple flows over time between the two endpoints would work; for SCTP, it would be similar, although if a flow is a stream, you might need more.
If the members of the 5-tuple are all "named fields" in Wireshark, you could use TShark with the -T fields option, and use the -e option to specify which fields to print, and select a field with the time stamp (frame.time_epoch would give you the time as seconds and fractions of a second since the UN*X epoch), a field the appropriate size (frame.len gives you the raw number of bytes in the link-layer packet PLUS any meta-data such as a radiotap header for 802.11 radio information), and the other fields, and then feed the output of TShark to a script or program that does the processing you want to do.  That lets TShark do the processing of the protocol layers, so that your program only needs to process the resulting data.


text:
Q: Advice on Separation of Schema and Orchestration Assemblies for WCF Generated Items When using the consume WCF / generated items wizard, items generated include the schemas, bindings and also an ODX containing Port Type definitions to consume the service.
And it is common / good practice to separate schemas from orchestrations into separate assemblies.
However, in the case of WCF generated artifacts the effort to separating these is considerable, as each Port Type must then be edited to point to the reference assembly - this can be cumbersome with a Service with many operations (and a request / response for each). And this gets worse if the WCF service changes and needs to be regenerated.
So, if I may ask:

*

*What do you do consider best practice here? I am leaning toward keeping the Port types and dummy ODX's in the Schema assembly.

*Do you move the Generated Port Types out of the dummy ODX generated and then delete the Dummy ODX's?

Thanks!

A: I thing you're trying too hard.
What I would do is have the service reference of the consumed WCF service in an orchestration of its own (without any logic). Just a plain bare orchestration with only the port types defined there. This orchestration can then be in a separate assembly.
That way, you can reference this orchestration from other projects.
You should not try to separate the generated schemas from the port types. These are inextricably linked anyway because they are all, collectively, part of the "service contract".


text:
Q: MVC RedirectToAction in a catch block I´m trying to redirect to an action from one controller to another if something in a try-block goes wrong. What I want to achieve is a general way of presenting a view to the user if something goes wrong in different controllers by directing all errors to an errorhandling ActionResult in my Homecontroller. This is basically what the code looks like:
    try
    {
        Code that may go wrong
    }
    catch (Exception e)
    {
        set the errorcode (integer)

        Logg the error (write a simple textfile)

        RedirectToAction("ErrorHandling", "Home", errorcode);
    }

And in the Homecontroller i would like to generate a view, telling the user that something went wrong:
    public ActionResult ErrorHandling(int errorcode)
    {
        do something with the errorcode

        return View(different view depending on errorcode);
    }

My problem is that if i manipulate the code so that an exception is thrown every step in the catcblock is executed except for the RedirectToAction whic is being ignored. What am i missing? I´m kind of new to this, so hopefully there is a simple answer that i haven´t been able to find...

A: In your catch block try
  return new RedirectToRouteResult(new RouteValueDictionary
    {
        {"Controller", "Home"},
        {"Action", "ErrorHandling"},
        {"errorcode", errorcode}
    });

Maybe you simply forgot the return in your code:
return RedirectToAction("ErrorHandling", "Home", errorcode);


text:
Q: Parsed symbolic differentiation in C++ I found these two libraries:
 - muparser
 - symbolicc++
The first one is capable of efficient parsing of mathematical expression, so that with minimal wrapping I could make a parser object so that
parser my_parser("1/2 * x^2");
cout<<myparser(2)<<endl;

Would result in it printing 2.0. This is wonderful, but it only works with doubles, right?
The second one implements the Symbolic object so that on example I can do something like:
Symbolic x("x");
Symbolic x2 = x^2;
cout<<df(x2, x)<<endl;

Resulting in 2.0*x. So it is capable of differentiating expressions, which is fine.
What I would need to do is a mix of the two! I need a function to be parsed and then differentiated, so that I could do something like:
 cout<<df("1/2 * x^2", "x")<<endl;

And I would like it to print out 2.0*x as well.
Is it possible to do something like this? In principle, if muparser could work on any object, I could simply run an expression on Symbolic objects, and then differentiate them. But I couldn't make something like this work.
So is there any other workaround? I need something that takes an input string with an expression and returns an output string with the derivative of that expression.
Thank you!

A: This isn't a complete answer since, as they say, TMTOWTDI. However, to be able to use Symbolic++ you need to have program-level access... that is, you can't really write and compile
Symbolic x("x");
Symbolic x2 = x^2;

but you need something on the order of (but waaaaay more flexible than)
if (there_is_x_symbol) {
    expr = Symbolic x("x");
}
if (raise_to_the_2nd_power) {
    expr = expr^2;
}

To do this in a organic way you need a parser, and a parser that will not simply export an evaluate() method but something that will allow you access to the expression tree, for example
     ( multiply )
      /        \
  ( 2 )       ( square )
                 \
                ( x )

This you could evaluate recursively:
left = myEvaluate(node.left)
right = myEvaluate(node.right)
if (node.op == multiply) {
    return left * right;
}
if (node.op == square ) {
    return right ^ 2;
}
...

The muparser (and muparserX) libraries do not seem to allow this.
There are several other algebraic parsers out there, for example this looks promising. You can use the supplier Parser algorithm, and write an Evaluator of your own that uses Symbolic++ and outputs a Symbolic++ expression.
You do not need a deep knowledge of grammars to hack at such a parser - most will just generate a Reverse Polish Notation stack, and that's all you really need to know about.
In bocca al lupo :-)


text:
Q: Why are there no file insertion syscalls To my understanding, for manipulating files there is only the sys_write syscall in Linux, which overwrites the file content (or extends it, if at the end).
Why are there no syscalls for inserting or deleting content in files in Linux?
As all current file systems do not require the file to be stored in a continuous memory block, an efficient implementation should be possible.
(The files would get fragmented.)
With file system features as "copy on write" or "transparent file compression", the current way of inserting content seems to be very inefficient.

A:
As all current file systems do not require the file to be stored in a continuous memory block,

Filesystems might not require files to be stored in a continuous area (and that would be very inflexible indeed), but usually files are stored in fixed-size blocks (or sequences of contiguous blocks). Doing it that way simplifies the implementation, and the blocks are usually multiples of the block size of the underlying device.
So, implementing inserts of blocks with arbitrary length would make the file system format and implementation rather more complex or require moving potentially large amounts of data around. Neither of those is really good, and complex data structures can be built in userspace on top of the filesystem API.

A: On recent Linux systems that is actually possible, but with block (4096 most of the time), not byte granularity, and only on some filesystems (ext4 and xfs).
Quoting from the fallocate(2) manpage:

int fallocate(int fd, int mode, off_t offset, off_t len);
[...]
Collapsing file space
Specifying the FALLOC_FL_COLLAPSE_RANGE flag  (available  since  Linux
         3.15) in mode removes a byte range from a file, without leaving a hole.
         The byte range to be collapsed starts at offset and continues  for  len
         bytes.   At  the  completion of the operation, the contents of the file
         starting at the location offset+len will be appended  at  the  location
         offset, and the file will be len bytes smaller.
[...]
Increasing file space
Specifying  the FALLOC_FL_INSERT_RANGE flag (available since Linux 4.1)
         in mode increases the file space by inserting a hole  within  the  file
         size  without  overwriting  any  existing data.  The hole will start at
         offset and continue for len bytes.   When  inserting  the  hole  inside
         file,  the  contents  of  the  file  starting at offset will be shifted
         upward (i.e., to a higher file offset) by len bytes.  Inserting a  hole
         inside a file increases the file size by len bytes.


text:
Q: Python 3.5 for Windows missing tkinter I have Python 3.5.1 for Windows (official python.org installer) installed and it seems to be missing tkinter. For example:
C:\Users\kostya>python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from tkinter import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'tkinter'

Does anyone have an idea about were I can download the package?

A: The installer has an option "[X] install tkinter, IDLE, turtle". It should be on by default, but you might have clicked it off. If you run the installer again, you should see an option to repair. That should get you an option to see if the box is checked. Must sure it is and 'repair'.

A: If using Windows, open settings and got to Apps and features:

Select Modify.

The click Modify (again) and then check the [x] Tcl/Tk box.


text:
Q: Emulate/Simulate iOS in Linux I'm developing a web app that apparently is having problems in iOS devices. The problem is that I don't own an iOS device and I develop in Linux Ubuntu. I'm looking for a way to emulate/simulate this OS in Linux (especially the browser), but haven't found anything.
So far, what I've found is the iOS SDK's Simulator, but that is meant for the Mac. And also some emulator for Windows. Has anyone done this before?

A: *

*Run Ripple emulator(retired as of 2015-12-06) on Chrome

*Run iPadian on WineHQ

*Run QMole on Linux or Android

*Run XCode on PureDarwin

A: The only solution I can think of is to install VMWare or any other VT then install OSX on a VM.
It works pretty good for testing.

A: On linux you can check epiphany-browser, resizes the windows you'll get same bugs as in ios. Both browsers uses Webkit.
Ubuntu/Mint:
sudo apt install epiphany-browser

A: Maybe, this approach is better, https://saucelabs.com/mobile, mobile testing in the cloud with selenium

A: BrowserStack.com
On this site, you can emulate a lot of iOS's devices online.

A: You might want to try screenfly. It worked great for me.

A: As far as I know, there is no such a thing as iOS emulator on windows or linux, there are only some gameengines that enable you to compile same code for both iOS and windows or linux and there is a toolchain to compile iOS application using linux. none of them are realy emulator/simulator things. and to use that toolchain you need a jailbreaked iOS device to test binary file created using toolchain. I mean linux itself can't run the binary created itself. and by the way even in mac simulator is just an intermediate program which runs mac-compiled binary, since if you change compiling for iOS from simulator or the other way, all the files are rebuild. and also there are some real differences, like iOS is a case-sensitive operation while simulator is not.
so the best solution is to buy an iOS device yourself.


text:
Q: Github Move code from old repo to new repo retaining commit history Old Repo Directory Structure
old-repo
\-- apple
\-- mango
\-- banana

New Repo Directory Structure
new-repo
\-- vegetables
\-- fruits
    \-- apple
    \-- mango
    \-- banana

Need to move contents of old repo to new repo with different structure with maintaining commit history from old repo.


text:
Q: JNI thread causing SIGSEGV Cypress fx2lp USB chip What ways could I debug this JNI code? I see that it states the problematic frame is writeUSB function but I am not seeing anything wrong with this. This Java application is written for Mac and their is a JNI that was written to communicate with hardware we manufacture in house. The USB chip in our hardware is from cypress fx2lp  Cy64713. I am not sure why this is causing a SIGSEGV...
full dump here
http://pastebin.com/BbgK796a
Full source for this JNI is HERE
https://bitbucket.org/snippets/partialdata/6L69r/ucs30interfacejni
Here is the debugger console in netbeans when i plug in our hardware turn it on and then debug the application.
http://pastebin.com/TkyqZxus

A: Scrolling down to this part of your stack trace is fairly useful:
Stack: [0x000070000011a000,0x000070000021a000],  sp=0x0000700000218010,  free space=1016k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [UCS30InterfaceJNI.dylib+0x1146]  _Z8writeUSBPP20IOUSBInterfaceStructPhi+0x46
C  [UCS30InterfaceJNI.dylib+0xfcc]  _Z15getSerialNumberPP20IOUSBInterfaceStruct+0x6c
C  [UCS30InterfaceJNI.dylib+0x2b19]  _Z14findUSBDevicesPc+0x259
C  [UCS30InterfaceJNI.dylib+0x2f40]  Java_ucs30interface_Main_findUCS30s+0x40
j  ucs30interface.Main.findUCS30s()Ljava/lang/String;+0

Although the argument names are somewhat mangled by the C++ compiler you can see the names of the functions that were called when the program failed.
The top one matches a function something like writeUSB(IOUSBInterfaceStruct**,int*).  Find a function like that and look for places it uses pointers. One of the pointers in that function is probably pointing to memory that was never allocated or has already been freed.
Update
If you can't see the problem in the top-level function it may be in the functions that call it. eg if the function that calls it (getSerialNumber) calls it with a bad pointer that could cause the same SIGSEGV. On Linux with Netbeans 8.1 RC2, I can step from java code to C++ code with a debugger. You can try it on a Mac but I am not sure if it works. Without a debugger you can resort to putting in printf's. Put one between each line of code. The prints that show up are before the bad line and the ones that do not show up are after the bad line. You should make sure all the printf's end with \n and you flush stdout or the print may still be buffered when the SIGSEGV occurs. You can also split the function into smaller functions called from this one which will also help narrow things down. Print the values of the variables. command being a string needs to have a terminating 0 before the end of the array it is coming from. You will probably need to see the calling code to know how long that array is. interface being a pointer to a pointer could cause a failure either by being a bad pointer or pointing to a bad pointer. It is possible the problem is in one of the functions writeUSB calls like WritePipe, if that function were inlined it might not show up on the stacktrace.


text:
Q: Load SMS messages in vmsg format to new iphone on linux I have a backup of SMSs from an old phone in vmsg format.
What would be necessary in order to lead them on the iPhone? I am new to apple products. Can I not make a backup  of the phone and download it to my linux computer? How? If so, it would be a matter of converting the messages to other format. I take it sqlite from a bit of googling around. I am a computer programmer, this is not a problem for me. What's confusing me is the whole backup and restore policies.
Or ideally, is there a way to restore only the sms.db?
Or any other way of leading SMSs in any other format? Writing a script to convert them would not be a problem.

A: You really have multiple questions in one, but I'll assume the question marked in bold is your primary question:
Yes, you can make a backup of your phone and download it to your Linux computer.
From your wording it is hard to know whether you by "download" mean that the Linux computer is seperate from the computer that makes the backup, or not. In both cases this is possible:
Scenario A:
Use iTunes on your Mac to create a local backup of your iPhone.
  Afterwards use any file copying program to copy ~/Bibliotek/Application Support/MobileSync/Backup/ to your Linux PC.
You can copy over the network, via a USB disk, or any other ordinary way of copying files.
Scenario B:
Install libimobiledevice on your Linux PC. Depending on Linux distribution, this is normally available in your package manager.
  Use the idevicebackup tool to create a backup.
If libimobiledevice is not available in your package manager, you can download it from:
http://www.libimobiledevice.org
When you do have the backup, your SMS messages are stored in a file originally named "sms.db", which is really a SQLite3 database containing the messages.
There's no built-in support for the vmsg format in libimobiledevice. However, you could create your own tool, as you describe, to convert from vmsg into SQL statements, that you could execute to add the messages to the SQLite database. Then you can restore the backup again to transfer the messages back to the phone.


text:
Q: Tab Box CSS for shinydashboard I'm trying to change the tab style for tabBox in shinydashboard.  I was able to change the background of the tabs that aren't selected, but I can't change the background of the tab that is selected or the text that appears in each tab.  This is what I added to a custom.css file to change the unselected tab backgrounds:
.nav-tabs {
  background-color: #006747;
}

I tried stuff like .nav-tabs .active but I couldn't get anything to work.
Also if anybody knows how to change the small colored sliver that appears next to your selected tab, that would be appreciated also.

A: Developper tools and "inspect element" are very handy to figure out which classes you to change the css from.
To change the sliver and the color of the selected tab, you could do:
.nav-tabs-custom .nav-tabs li.active:hover a, .nav-tabs-custom .nav-tabs li.active a {
     background-color: transparent;
     border-color: transparent;
}

.nav-tabs-custom .nav-tabs li.active {
     border-top-color: #FFF;
}

Here's an example (backbone code from here):
library(shiny)
library(shinydashboard)
body <- dashboardBody(
        fluidRow(tags$style(".nav-tabs {
  background-color: #006747;
}

.nav-tabs-custom .nav-tabs li.active:hover a, .nav-tabs-custom .nav-tabs li.active a {
background-color: transparent;
border-color: transparent;
}

.nav-tabs-custom .nav-tabs li.active {
    border-top-color: #FFF;
}"),
                tabBox(
                        title = "First tabBox",
                        # The id lets us use input$tabset1 on the server to find the current tab
                        id = "tabset1", height = "250px",
                        tabPanel("Tab1", "First tab content"),
                        tabPanel("Tab2", "Tab content 2")
                )

))

shinyApp(
        ui = dashboardPage(
                dashboardHeader(title = "tabBoxes"),
                dashboardSidebar(),
                body
        ),
        server = function(input, output) {
        }
)