Q:

Randomise (rearrange) dataframe rows in R in alternating manner using a 2 level factor column variable

I am trying to randomize my data collection. I am going to observe 10 animals (baboon_list) and each animal gets 4 sessions (2 am and 2 pm). So in total there are 40 sessions.
baboon_list=rep(c("Hound","Sunflower","Nick","Pompom",
                  "CrookedTail","Hugger","R","Chris","Puncture","Brown"),each=4)

session_vec=rep(c("AM","PM"),each=1,times=20)

sampling=data.frame(baboon_list,session_vec)

randomized_sampling=sampling[sample(nrow(sampling)),]

I wish to randomize the way I observe them. I created a randomized data frame but I want it to be listed with alternating am and pm sessions. That is, the rows should be randomized but arranged in alternating am and pm sessions. How do I do that?
For now, I randomized the baboon_list vector before combining it with session_vec into a data frame which solved my purpose.
data.frame(sample(baboon_list),session_vec)

How about if I am given such a dataframe and I have to rearrange it? Should I deconstruct that data frame and reconstruct using my method?
Sorry if this is a trivial question, I am new to R and statistics.

A:

Starting with your "sorted" sampling dataframe, you could do something like the following. For each baboon, select 4 random row (rr) positions from the remaining rows and label those baboon rows with the random row value. Then remove the row positions from the available rows (! rows %in% rr) and repeat with the next baboon.
baboons = levels(sampling$baboon_list)
rows = 1:nrow(sampling)
d = data.frame()
for (i in 1:length(baboons)) {
  n = nrow(sampling[baboon_list=='R',])
  rr = sort(sample(rows,n))   # 4 random row positions
  d = rbind(d,
            data.frame(sampling[baboon_list==baboons[i],], rr) )
  rows = rows[! rows %in% rr]  # remove the 4 row positions
}
subset(d, baboon_list=='Brown')

   baboon_list session_vec rr
37       Brown          AM  2
38       Brown          PM  6
39       Brown          AM 23
40       Brown          PM 30


Q:

How do I change the progress value of a progress bar programmatically?

I'm trying to create a custom view of some components because I need this combination a lot in my application. Everything in the code works except the progress of my progressBar. I think that it doesn't get the value correctly of the XML file.
In my init void I call the setProgressBar(progress) to provide the current value to my xml file. When I enter for example 'setProgressBar(88)' it works perfectly but not with a value that it has to find in the xml file.
CustomProgressbar.java
public class CustomProgressbar extends RelativeLayout {
    @StyleableRes
    int index0 = 0;
    @StyleableRes
    int index1 = 1;
    @StyleableRes
    int index2 = 2;

    TextView titleText;
    TextView valueText;
    ProgressBar progressBar;

    public CustomProgressbar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        inflate(context, R.layout.custom_progressbar_layout, this);

        int[] sets = {R.attr.title, R.attr.value, R.attr.progress};

        TypedArray typedArray = context.obtainStyledAttributes(attrs, sets);

        CharSequence title = typedArray.getText(index0);
        CharSequence value = typedArray.getText(index1);
        int progress = typedArray.getInteger(index2,0);

        typedArray.recycle();

        titleText = findViewById(R.id.title_text);
        valueText = findViewById(R.id.value_text);
        progressBar = findViewById(R.id.progressbar_attr);

        setTitleText(title);
        setValueText(value);
        setProgressBar(progress);

    }

    public CharSequence getTitleText() {
        return titleText.getText();
    }
    public CharSequence getValueText() {
        return valueText.getText();
    }
    public int getProgressBar() {
        return progressBar.getProgress();
    }

    public void setTitleText(CharSequence value) {
        titleText.setText(value);
    }
    public void setValueText(CharSequence value) {
        valueText.setText(value);
    }
    public void setProgressBar(int value) {
        progressBar.setProgress(value);
    }
}

custom_progressbar_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

        <TextView
            android:id="@+id/title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="@android:color/black" />

        <TextView
            android:id="@+id/value_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignParentEnd="true"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="@android:color/black" />

        <ProgressBar
            android:id="@+id/progressbar_attr"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="25dp"
            android:layout_below="@id/value_text"
            android:layout_alignParentStart="true"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="10dp"
            android:max="100"
            android:maxHeight="10dip"
            android:minHeight="10dip"
            android:progressTint="@android:color/holo_green_dark"
            android:progressDrawable="@drawable/progressbars" />
</RelativeLayout>

main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainClass"
    android:background="@android:color/background_dark">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        app:cardCornerRadius="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="15dp">

            <com.x.customprogressbar.CustomProgressbar
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:title="ThisIsTheTitle"
                app:value="€ 28,30"
                app:progress="77" />
        </LinearLayout>

    </android.support.v7.widget.CardView>
</LinearLayout>

And my attributes
<resources>
    <declare-styleable name="CustomProgressbar">
        <attr name="title" format="string"/>
        <attr name="value" format="string"/>
        <attr name="progress" format="integer"/>
    </declare-styleable>
</resources>

Current results:

The XML file, as it should look. There it works perfectly.
Link1

When I run the app.
Link2

(I'm not allowed yet to add images so I got links.)

A:

try this, styles attributes are getting in the other way
public class CustomProgressbar extends RelativeLayout {

private TextView titleText;
private TextView valueText;
private ProgressBar progressBar;

public CustomProgressbar(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context, attrs);
}

private void init(Context context, AttributeSet attrs) {
    inflate(context, R.layout.custom_progressbar_layout, this);

    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomProgressbar);

    CharSequence title = typedArray.getText(R.styleable.CustomProgressbar_title);
    CharSequence value = typedArray.getText(R.styleable.CustomProgressbar_value);
    int progress = typedArray.getInteger(R.styleable.CustomProgressbar_progress, 0);

    typedArray.recycle();

    titleText = findViewById(R.id.title_text);
    valueText = findViewById(R.id.value_text);
    progressBar = findViewById(R.id.progressbar_attr);

    setTitleText(title);
    setValueText(value);
    setProgressBar(progress);

}

public CharSequence getTitleText() {
    return titleText.getText();
}

public CharSequence getValueText() {
    return valueText.getText();
}

public int getProgressBar() {
    return progressBar.getProgress();
}

public void setTitleText(CharSequence value) {
    titleText.setText(value);
}

public void setValueText(CharSequence value) {
    valueText.setText(value);
}

public void setProgressBar(int value) {
    progressBar.setProgress(value);
}

}


Q:

Как прикрепить кнопки внизу экрана?

Какой лучше всего использовать layout, чтобы прикрепить кнопки к нижней части экрана?Остальная часть должна прокручиваться...

A:

Используйте RelativeLayout и выставьте android:layout_alignParentBottom="true" для контейнера с кнопками.


Q:

How do I add a title to my activity?

How do I add an activity title to my new activity to be displayed on the action bar?
I already added a title when creating that new activity so where is the problem

A:

Under your activity declaration in your manifest.xml add the following :
 <activity
        android:name=".YourActivity"
        android:label="Your activity name">


Q:

php json multidimensional array syntax

I have a problem with the JSON I'm creating in PHP;  I create the array in a while loop from an sql query. $featuresCSV is a comma-separated string like "1,3,4".  In the JSON I need it to end up like feature-1: 1,feature-2: 1,feature-3: 1  The 1 represents true for my checkbox in my front-end program.
while ($stmt2->fetch()) {

  $features = array();
  $featuresTmp = explode(',', $featuresCSV, -1);

  foreach ($featuresTmp as &$featureItem) {
    $features[] = array("feature-" . $featureItem => 1);
  }

  $items[] = array('price' => $price, 'image' => $image, 'features' => $features);
}
...
json_encode($output);

The JSON ends up looking like this:
{"price":8900,
"image":"4d3f22fe-9f1a-4a7e-a564-993c821b2279.jpg",
"features":[{"feature-1":1},{"feature-2":1}]}

but I need it to look like this:
{"price":8900,
"image":"4d3f22fe-9f1a-4a7e-a564-993c821b2279.jpg",
"features":[{"feature-1":1,"feature-2":1}]}

Notice how feature-1 and feature-2 aren't separated by brackets in the second.

A:

You need to assign the elements at "feature-1" and "feature-2".
foreach ($featuresTmp as &$featureItem) {
   $features["feature-" . $featureItem] = 1;
}

The syntax $feature[] = ... is for appending to the end of an array.


Q:

EDI Parser in .NET

Has anyone created a .NET application that reads and parses an EDI file?
EDI file - used by shipping industries to provide information on shipment invoice.

A:

Check out EDIFabric on codeplex
http://edifabric.codeplex.com/
ediFabric is a .NET library (.dll) to convert EDI documents to .NET objects (or XML) and vice verse. EDI document rules are represented as .NET classes. There is one class (.cs file) per every EDI message type.

A:

An Edi Serializer for dotnet that is free and opensource is EDI.Net. It supports X12, EdiFact as well as the UK only TRADACOMS formats. It even works on dotnetcore and NetStandard 1.0
*disclaimer I wrote the library

A:

There are a bunch out there, but none that I'm aware of for free.  Try http://www.edidev.com/FullPriceList.htm
They've been around awhile.


Q:

jQuery apply class to

My current HTML structure

«
October 2014
»

Mo
Tu
We
Th
Fr
Sa
Su

29
30
1
2
3
4
5

6
7
8
9
10
11
12

13
14
15
16
17
18
19

20
21
22
23
24
25
26

27
28
29
30
31
1
2

3
4
5
6
7
8
9

Today

Clear

In the above generated HTML, there is one  with class today day which is

    27
    28
    29
    30
    31
    1
    2

How can I apply CSS class to its
, so the result would be

    27
    28
    29
    30
    31
    1
    2

The class today day will be applied to only one .
Thanks.

A:

You can find the td with classes today and day then find its parent which will be the tr element and add the class mycustomclass to it.
$('td.today.day').parent().addClass('mycustomClass')

A:

Try this : find td having class="today day" and get the parent of it to add mycustomClass
$(function(){
  $('td.today.day').parent().addClass('mycustomClass');
});


Q:

Image not visible while using dynamic image source - MVC5

I am trying to create an image slideshow using MVC5. Here is my model class:
public class ImageSlider
{
    public string Source { get; set; }
    public string ImageName { get; set; }
    public string Title { get; set; }
}

For this model, I'd created a controller and an action within:
public ActionResult _imageSlider()
{
    return View(new List<ImageSlider> {
       new ImageSlider { Source = "~/_Slider/Images/google.jpg" },
       new ImageSlider { Source = "~/_Slider/Images/googlePlus.jpg" },
       new ImageSlider { Source = "~/_Slider/Images/facebook.jpg" }
    });
}

and here is my partial view:

    @foreach (var item in Model)
    {

    }

Now the problem is that when I create image tag as above, I do not see any image while I can see in my page source that these elements have beeen created. But if I create these tags in HTML, all images are visible. Example:

I know I am missing very small thing here but I couldn't figure out what. Can anyone please help me?

A:

You need to use @Url.Content like this, change your View.
 @foreach (var item in Model)
    {

    }


Q:

Passwords storage, hash() with sha-512 or crypt() with blowfish (bcrypt)?

This is my current password hashing procedure in PHP/SQL projects...

Take 512bits of per-user salt from /dev/urandom, stored in the user's DB record in addition to the final hash
Take 512bits of "pepper" from /dev/urandom which is stored in the file system. This is a
constant per-application and is the same for each user
Then hash('sha512', $password.$salt.$pepper, TRUE)

The hash and salt are stored in binary in the DB, mainly out of habit. I don't think it makes any difference in terms of security. If anything it's slightly less convenient for SQL backups and makes the PHP code appear marginally more complex.
Is hash() with SHA-256 or SHA-512 generally considered to have been superceeded by bcrypt these days?
I believe SHA-2 (256/512) is still considered cryptographically secure and I'm probably overdoing the entropy bits. It's far more likely that it would be a flaw in my code that would lead to problems than an attacker reverse-engineering a SHA-2 hash from a DB dump.
But should I update my methodology going forward to use crypt() with CRYPT_BLOWFISH instead (I believe this is referred to as bcrypt, with blowfish technically being a cipher rather than hashing algorithm)?
Even just as future best practice?
I'm not particularly concerned about the computational expense of the algorithms (within reason). This would only ever be a factor when creating accounts, changing passwords or on login when you hash then compare. Those activities make up a small percentage of page views. I guess in a way the slower the better, if it makes a server work harder to generate then it will make an attacker's work slower to brute force.
Cheers, B

A:

If you can wait til php 5.5, there will be some helpful functions for this built in:
https://gist.github.com/3707231
Till then, use crypt - you could look at this forward compatible port of the new functions:
https://github.com/ircmaxell/password_compat


Q:

Graph with edge disjoint cycles

If the vertices of graph have a degree of at least $n\geq2$, show that the graph has at least $\frac{n}{2}$ edge disjoint cycles.
Unsure how to approach this, but I understand that edge disjoint cycles are cycles within a graph that don't have the same edge.

A:

Before you do anything, note that the graph must be finite. If the graph weren't finite, a trivial example of a graph with every vertex of degree $2$ without any cycle would be the integer line, where every point is labelled with an integer and each point $n$ would be connected to points $n+1$ and $n-1$.

With that out of the way, it's mostly a matter of actually drawing out these edge-disjoint cycles.
We can use induction. Let $G$ be a finite graph where every vertex is of degree at least $2$. Then, pick any vertex $v_0$, and starting from that vertex, trace a path through the vertices $v_1, v_2, v_3, \ldots$. If at any point along this path we reach a vertex $v_n$ that we already passed earlier in the path, we have a cycle and we're done. But supposing we'd never visited $v_n$ before, then only one edge on $v_n$ is part of the path, and therefore we can continue drawing the path by the another edge on $v_n$ since the degree of $v_n$ is at least 2.
Continue until you do get a vertex that's already in the path – because the graph is finite, this will happen eventually by the pigeonhole principle.
Now that we've proven that, do you see how to approach the problem when each vertex is of degree at least $2n$?


Q:

Multiline string alignment / indenting in Eclipse

I'm using Eclipse Luna and I want to align / indent multi-line string literals so that that each line begins on the same column. But I'm having trouble convincing Eclipse to do it in the Code Style Formatter.
This is how it's currently formatting:
    final String string1 =
        "abc" +
            "def" +
            "ghi";

    System.out.println(
        "abc" +
            "def" +
            "ghi");

    System.out.println("" + // an ugly workaround
        "abc" +
        "def" +
        "ghi");

    method("xyz",
        "" +           // Especially ugly in this case
            "abc" +
            "def" +
            "ghi");

But this is what I really want:
    final String string2 =
        "abc" +
        "def" +
        "ghi";

    System.out.println(
        "abc" +
        "def" +
        "ghi");

    // Or something like this would be fine too
    final String string3 =
        "abc"
      + "def"
      + "ghi";

    System.out.println(
        "abc"
      + "def"
      + "ghi");

It seems like such a simple and desirable format.  Just start each part of the broken-up line on the same column.  But I haven't been able to find a way to do it anywhere.

A:

The following settings sort of work for your 2 first examples. Copy paste the your example into a block and then reformat. With this setting however you need to manually  break the lines, the formatter will then indent them and keep from joining them. You will probably need to tweek other settings since the "default indention for wrapped lines" is 0.
Under Line Wrapping:

Check "Never join already wrapped lines"
Set "Default indention for wrapped lines:" to 0
Expressions / Assignments:

Wrap where necessary,
Indent by one

Expressions / Binary expressions:

Wrap where necessary,
Check Wrap before operator,
Default indention

There is also the option to disable the formatter and then re-enable it after the code you want to format manually. This can be useful when you have tabular data in initializers you want to format for readability. This is under Off/On Tags in the formatter settings.


Q:

How to solve $y = \cos(x) + \sin(x)$

How do I solve $y=\cos(x) + \cos(90-x)$ where $0 \leq x \leq 45$ degrees? If I have some value $Y$, I need to find a value for $x$ such that this equation is true. Thanks for the help

A:

Hint:
It implies: $$y^2=(\cos x+\sin x)^2=\cos^2x+\sin^2x+2\sin x\cos x=1+\sin 2x$$
Then further you can work with $\arcsin$.


Q:

Remove element from Ajax Response

Let's says I want to load this file by AJAX :

    Hello !

Remove me, please.

How can I get only the Hello content ? I tried multiples ways to remove the .removeme div, it always failed :
$.ajax({
    url: 'loadme.html',
    success: function(data) {
        var response = $('
').html(data);

        // First try :
        var content1 = response.find('.content').html()
        console.log(content1); // Return : Hello !
Remove me, please.

        // Second Try :
        var content2 = response.find('.content').remove('.removeme').html()
        console.log(content2); // Return : Hello !
Remove me, please.

        // Third Try :
        var content3 = response.find('.content').html();
        console.log($(content3).remove('.removeme').html()); // Return : Remove me, please
    }
});

A:

Try:
var temp = response.find('.content');
temp.children('.removeme').remove();
var content4 = temp.html();


Q:

Drag & Drop folder in a batch to be read in java application

I'm kinda new in Java and even more in batch, I'm working on a little program that auto check bunch of specific files in a folder, however at this point, I need to use a Scanner in Java to read the path of the folder I want to check and I wonder what would I need to just have to drag and drop the folder into my batch to execute this application
Here is the start of my application with the scanner
public static void main (String[] args) {
        System.out.print("Locators folder : ");
        Scanner sc = new Scanner(System.in);
        String path = sc.next();
        sc.close();
        File[] folders = new File(path).listFiles();

And here is the batch even if it won't bring much info
@ECHO off

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" -jar "E:\Hugo\Documents\_Quadrica\afc.jar"

A:

You don't need a Scanner to get the path.
When you drag a file (or folder) onto your batch file, it becomes a command line argument to your batch file, so all you need to do is add %1 to the end of the java command in the batch file, i.e.
"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" -jar "E:\Hugo\Documents\_Quadrica\afc.jar" "%1"

Note: Enclose %1 in double quotes is necessary if the path contains spaces. Also note that it will not work if the path contains unusual characters like &, for example. Please refer to Batch file Copy using %1 for drag and drop
Then in your java code, the path is actually in the args parameter to method main(), so your java code should be...
public static void main (String[] args) {
    if (args.length > 0) {
        System.out.println("Locators folder: " + args[0]);
    }
}


Q:

What is the dataKeyName for a gridview bound to a string array?

Can anyone give me a short snippet that, given a GridView that was originally bound to a simple string array, and given a GridViewRow row, will return the value that was bound to the row?

A:

You can't, the only property System.String has is Length, and DataKeyName expects a property of the object you are binding to. To answer your second question, here is an example of getting the string value from a GridViewRow.
In your ASPX file:
<asp:GridView ID="GridView1" runat="server"
    OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderText="String Value">
            <ItemTemplate>
                <%# Container.DataItem %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

In your codebehind:
protected void Page_Load(object sender, EventArgs e) {
    string[] arrayOfStrings = new string[] { "first", "second", "third" };
    GridView1.DataSource = arrayOfStrings;
    GridView1.DataBind();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
    if (e.Row.RowType == DataControlRowType.DataRow) {
        // e.Row is of type GridViewRow
        // e.Row.DataItem contains the original value that was bound,
        // but it is of type object so you'll need to cast it to a string.
        string value = (string)e.Row.DataItem;
    }
}

The only reasonable workaround to the problem is to either create a wrapper class that has properties. Or if you are using .NET 3.5, you can use LINQ to make a temporary list which only includes your value as a property of the class. There is an example of this technique on MSDN Forums by vtcoder.
List<string> names = new List<string>(new string[] { "John", "Frank", "Bob" });

var bindableNames = from name in names
                    select new {Names=name};

GridView1.DataSource = bindableNames.ToList();

Then "Name" would be the DataKeyName and BoundField DataField.


Q:

What does the Java 8 Collector UNORDERED characteristic mean?

In official documentation you can read that:

UNORDERED
  Indicates that the collection operation does not commit to
  preserving the encounter order of input elements.

This is not too helpful without any examples.
My question is, what exactly does UNORDERED characteristic mean? Should I use it with reducing collectors like min or sum or is it only applicable to collection collectors?
In OpenJDK looks like reducing operations (min, sum, avg) have empty characteristics. I expected to find there at least CONCURRENT and UNORDERED.

A:

In the absence of special pleading, stream operations must behave as if the elements are processed in the encounter order of the source.  For some operations -- such as reduction with an associative operation -- one can obey this constraint and still get efficient parallel execution.  For others, though, this constraint is very limiting.  And, for some problems, this constraint isn't meaningful to the user.  Consider the following stream pipeline:
people.stream()
      .collect(groupingBy(Person::getLastName,
                          mapping(Person::getFirstName));

Is it important that the list of first names associated with "Smith" appear in the map in the order they appeared in the initial stream?  For some problems, yes, for some no -- we don't want the stream library guessing for us.  An unordered collector says that it's OK to insert the first names into the list in an order inconsistent with the order in which Smith-surnamed people appear in the input source.  By relaxing this constraint, sometimes (not always), the stream library can give a more efficient execution.
For example, if you didn't care about this order preservation, you could execute it as:
people.parallelStream()
      .collect(groupingByConcurrent(Person::getLastName,
                                    mapping(Person::getFirstName));

The concurrent collector is unordered, which permits the optimization of sharing an underlying ConcurrentMap, rather than having O(log n) map-merge steps.  Relaxing the ordering constraint enables a real algorithmic advantage -- but we can't assume the constraint doesn't matter, we need for the user to tell us this.  Using an UNORDERED collector is one way to tell the stream library that these optimizations are fair game.

A:

UNORDERED essentially means that the collector is both associative (required by the spec) and commutative (not required).
Associativity allows splitting the computation into subparts and then combining them into the full result, but requires the combining step to be strictly ordered. Examine this snippet from the docs:
 A a2 = supplier.get();
 accumulator.accept(a2, t1);
 A a3 = supplier.get();
 accumulator.accept(a3, t2);
 R r2 = finisher.apply(combiner.apply(a2, a3));  // result with splitting

In the last step, combiner.apply(a2, a3), the arguments must appear in exactly this order, which means that the entire computation pipeline must track the order and respect it in the end.
Another way of saying this is that the tree we get from recursive splitting must be ordered.
On the other hand, if the combining operation is commutative, we can combine any subpart with any other, in no particular order, and always obtain the same result. Clearly this leads to many optimization opportunities in both space and time dimensions.
It should be noted that there are UNORDERED collectors in the JDK which don't guarantee commutativity. The main category are the "higher-order" collectors which are composed with other downstream collectors, but they don't enforce the UNORDERED property on them.

A:

The inner Collector.Characteristics class itself is fairly terse in its description, but if you spend a few seconds exploring the context you will notice that the containing Collector interface provides additional information

For collectors that do not have the UNORDERED characteristic, two accumulated results a1 and a2 are equivalent if finisher.apply(a1).equals(finisher.apply(a2)). For unordered collectors, equivalence is relaxed to allow for non-equality related to differences in order. (For example, an unordered collector that accumulated elements to a List would consider two lists equivalent if they contained the same elements, ignoring order.)

In OpenJDK looks like reducing operations (min, sum, avg) have empty characteristics, I expected to find there at least CONCURRENT and UNORDERED.

At least for doubles summation and averages definitely are ordered and not concurrent because the summation logic uses subresult merging, not a thread-safe accumulator.


Q:

Why won't "git reset HEAD" undo my uncommitted, unstaged changes?

I've previously been able to undo changes through SourceTree by performing the "Discard" function, which under the hood produces this command:
git -c diff.mnemonicprefix=false -c core.quotepath=false reset -q HEAD -- myproj.csproj
git -c diff.mnemonicprefix=false -c core.quotepath=false checkout HEAD -- myproj.csproj

Suddenly this doesn't work. I do the Discard, no error occurs, refreesh the view, but the files are still "modified". I've then tried to do the same in the command line with the following, same result:
c:\myproject> git reset HEAD

Unstaged changes after reset:
M       myproj.csproj

Why is it still listed as an unstaged change?
I've verified that the file is indeed writable (no process is holding a lock)
update
git checkout didn't work either:
C:\myproject>git checkout myproj.csproj

C:\myproject>git status
# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   myproj.csproj
#
no changes added to commit (use "git add" and/or "git commit -a")

Update 2
Also tried:

git checkout --
git checkout -- .
git checkout HEAD

,none of which solves my problem
update 3 - huge step closer:
Turns out when I do the checkout, the .csproj is indeed reverted to the correct version, but the checked out version uses a different line feed encoding. While the checked-in version has CR-LF (0D-0A) for line feed, the checked-out has only LF (0A). Hence git belives the file to be different on every single line. Why this?
update 4: added the second line of git-commands issued by SourceTree. I didn't notice that the first time around, that's why I thought git reset HEAD would do anything. This doesn't change the fact that the underlying problem still is CR/LF-related (I think)
summary
I never found a solution to the issue, but I "solved" it by checking in the file. My original question didn't contain information that SourceTree indeed issued the correct commands to rollback what I wanted, so most answers here address that issue. The real issue is still unclear, but my main theory is that it was CR/LF related.

A:

If you need to remove local changes then run following command
git checkout -- file_name

git reset HEAD does not remove local changes.

A:

I suspect that you had files saved with CRLF line endings in your repository, and then somewhere along the way your configuration was changed so that git started normalizing end-of-line characters (either core.autocrlf was set to true, or the .gitAttributes file was added or changed). When I ran into this problem, it turned out that a .gitAttributes file that contained * text=auto had been added to my repo.
(EOL normalization means that git will write the end-of-line characters as LF in its database, regardless of what you use in your working copy).
Git doesn't automatically check your files to see if they require EOL normalization after you enable it. You have to explicitly tell it to check all of your files, or else you end up in this situation: the files in your repository still have CRLF line endings, and git will only notice that it should normalize them when it touches each file. So the next time you commit some changes to a file, git will write the file to its database with LF line endings.
The problem occurs when git touches the file through a read operation. Say you make changes to a file that has CRLF line endings and then try to discard your changes. Git will read the clean copy from its database, see that it has CRLF line endings, and then mark the file as modified. The file has not actually been modified, but git is saying that it wants to write a change to the EOL characters to its database. This happens every time you attempt to discard your changes, check out that file, or even do a hard reset. That is why it seems to be impossible to undo those modifications.
You should have git normalize the line endings on all of your text files, so this problem doesn't continue to pop up (see https://stackoverflow.com/a/4683783/1369 for instructions on how to do that). If it's possible, you might even want to modify your history so the line endings are normalized at the same time the .gitAttributes settings were changed.
If you cannot modify your history, then you may run into situations where you need to check out old versions of your files that still have the CRLF line endings. You will probably get stuck with a list of modified files that you cannot discard and don't want to commit. In that case, you can use this work-around to essentially make git forget that it wants to modify those files:

Check out the old version
Turn off end-of-line normalization
git reset
Re-enable end-of-line normalization


Q:

Java 8 : grouping field values by field names

I'm trying to find a more elegant way to create a map that group field values by field names using Java 8 than the following:
@Test
public void groupFieldValuesByFieldNames() {
    Person lawrence = aPerson().withFirstName("Lawrence").withLastName("Warren").born();
    Person gracie = aPerson().withFirstName("Gracie").withLastName("Ness").born();

    Map<String, List<String>> valuesByFieldNames = new HashMap<>();
    Stream.of(lawrence, gracie).forEach(person -> {
        valuesByFieldNames.computeIfAbsent("lastName", s -> new ArrayList<>()).add(person.getLastName());
        valuesByFieldNames.computeIfAbsent("firstName", s -> new ArrayList<>()).add(person.getFirstName());
    });

    assertThat(valuesByFieldNames, hasEntry("lastName", asList("Warren", "Ness")));
    assertThat(valuesByFieldNames, hasEntry("firstName", asList("Lawrence", "Gracie")));
}

A:

Try this.
Map<String, List<String>> valuesByFieldNames = Stream.of(lawrence, gracie)
    .flatMap(p -> Stream.of(new String[]{"firstName", p.getFirstName()},
                            new String[]{"lastName", p.getLastName()}))
    .collect(Collectors.groupingBy(a -> a[0],
             Collectors.mapping(a -> a[1], Collectors.toList())));

Or more generally
Map<String, List<String>> valuesByFieldNames = Stream.of(lawrence, gracie)
    .flatMap(p -> Stream.of(new AbstractMap.SimpleEntry<>("firstName", p.getFirstName()),
                            new AbstractMap.SimpleEntry<>("lastName", p.getLastName())))
    .collect(Collectors.groupingBy(e -> e.getKey(),
             Collectors.mapping(e -> e.getValue(), Collectors.toList())));


Q:

Deserialize into a list inside the deserialized class?

Small sample:
<head>
    <coordinate>
    ...
    </coordinate>

    <coordinate>
    ...
    </coordinate>

    <coordinate>
    ...
    </coordinate>

    <coordinate>
    ...
    </coordinate>
    etc.
</head>

This should result in:
public class Head
{
    public coordinate[] coordinates;
}

Does the deserialization of the first code sample result in the second code sample after casting the object to the type "Head" ?
public static void Main(string[] args)
{
    XmlSerializer deserializer = new XmlSerializer(typeof(Head));
    TextReader reader = new StreamReader("file.xml");
    Head obj = (Head)deserializer.Deserialize(reader);
    reader.Close();
}

A:

You can deserialize your given xml, having flat sequence of coordinate xml element, by following way.
Your Sample XML:
<head>
    <coordinate>
    ...
    </coordinate>

    <coordinate>
    ...
    </coordinate>

    <coordinate>
    ...
    </coordinate>

    <coordinate>
    ...
    </coordinate>
    etc.
</head>

Model Class:
[XmlElement(ElementName = "head")]
public class Head
{
    [XmlElement(ElementName = "coordinate")]
    public coordinate[] coordinates;
}

With above Model class deserializing to Head should work with below code of yours..
public static void Main(string[] args)
{
    XmlSerializer deserializer = new XmlSerializer(typeof(Head));
    TextReader reader = new StreamReader("file.xml");
    Head obj = (Head)deserializer.Deserialize(reader);
    reader.Close();
}

What I have done is decorate coordinates property with [XmlElement] attribute. So you just need to modify your Model class as above to map properly with given xml sample. More examples you can find at below reference link on msdn.
Reference: MSDN - Serializing an Array as a Sequence of Elements


Q:

How to integrate HSQL DB with java application

I would like to integrate HSQL in my Java application for testing purposes. Is there any tutorial that describes in a simple way how to integrate it-I want to distribute it with my app. I'm not restricted to HSQL any other easier solution are welcomed.
Thanks

A:

Your question is extremely broad and not really possible to answer, but I'll try anyway.
HSQLDB is not different to any other DBMS (except that it can run in the same process as your application - that is different e.g. to PostgreSQL).
Starting the database is described in the first chapter of the manual including a chapter on how to create a new database
Apart from that, just run your CREATE TABLE statements e.g. from within your application, the included SqlTool or any (JDBC based) SQL client that you like.
Deployment and integration into your application is described in the manual as well: http://hsqldb.org/doc/2.0/guide/deployment-chapt.html.
The chapter "Embedded Databases in Desktop Applications" might also be interesting to you.


Q:

Memory usage in Linux R

I am loading a 6 GB dataset in R running over Centos Linux 6.3, 128 GB RAM, 16 Core machine.
Simultaneously I am monitoring the RAM usage with top command. After about 104 minutes, in the  output of the top command, the VIRT column shows 189 GB.
Now, I am not able to understand how the VIRT column shows more than 128GB (which is the limit). Is there some kind of shared memory that is being used?

A:

There is simple rule with the virtual memory.
Linux is using RAM for often used processes, but other one it can store at the hard drive, as a virtual memory.
In my opinion, better way to get real memory usage is to use free -m command.


Q:

Compiling Python 2.7.12 with non-system Openssl on Centos 5

I'm currently trying to get Python 2.7.12 to compile with Openssl 1.0.2h on a Centos 5 host.
The reason for this is that I need Paramiko 2 to run on this host but that doesn't support the system provided OpenSSL version which is 0.9.8e-fips-rhel5 01 Jul 2008.
I've found some great hints and tips on here but it just doesn't seem to work. I'm now posting this in hope that someone will spot what I've done wrong/is missing.
For the OpenSSL setup I've done the following:
OPENSSL_ROOT="$HOME/.build/openssl-1.0.1e"
cd /tmp
curl http://www.openssl.org/source/openssl-1.0.2h.tar.gz | tar zxvf -
cd openssl-1.0.2.h
mkdir -p "$OPENSSL_ROOT"
./config no-hw --prefix="$OPENSSL_ROOT" --openssldir=...
make install

Then since I don't want to replace the system installed Python with 2.7.12 I've done the following:
First I added /usr/local/lib to /etc/ld.so.conf and ran ldconfig.
After that I've run:
cd /tmp
wget http://python.org/ftp/python/2.7.12/Python-2.7.12.tar.xz
tar xf Python-2.7.12.tar.xz
cd Python-2.7.12
./configure CPPFLAGS="-I$OPENSSL_ROOT/include"  LDFLAGS="-L$OPENSSL_ROOT/lib"  --prefix=/usr/local --enable-unicode=ucs4 --enable-shared
make && make altinstall

This is when I thought I'd have it compiled against the new version of OpenSSL but no, as you can see from the output here:
[root@an-host openssl-1.0.2h]# python2.7 -c "import ssl; print ssl.OPENSSL_VERSION"
OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008

And I'm sure that I'm running the newly compiled version since that is echoed here:
[root@an-host openssl-1.0.2h]# python2.7
Python 2.7.12 (default, Aug  1 2016, 11:46:42)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

I have even gone as far as removing openssl-devel with Yum but it still doesn't seem to care/compile against 1.0.2h.
This is driving me slightly mad at the moment so any input/feedback/help is greatly appreciated.

A:

I think I tried to copy too cute solutions and mix and match - tidied up and simplified a bit and got it to work in the end.
This is what I did this time:
Download and install OpenSSL
cd /tmp
curl http://www.openssl.org/source/openssl-1.0.2h.tar.gz | tar zxvf -
cd openssl-1.0.2.h
./config shared --prefix=/usr/local/
make && make install

Set up some environment variables
export LDFLAGS="-L/usr/local/lib/"
export LD_LIBRARY_PATH="/usr/local/lib/"
export CPPFLAGS="-I/usr/local/include -I/usr/local/include/openssl"

Download and install Python 2.7.12
wget http://python.org/ftp/python/2.7.12/Python-2.7.12.tar.xz
tar xf Python-2.7.12.tar.xz
cd Python-2.7.12
./configure --prefix=/usr/local/ --enable-unicode=ucs4 --enable-shared
make && make altinstall

And now it works as expected, displaying the newer OpenSSL version.
[root@an-host Python-2.7.12]# python2.7
Python 2.7.12 (default, Aug  1 2016, 14:48:09)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
>>> print ssl.OPENSSL_VERSION
OpenSSL 1.0.2h  3 May 2016

However, it still didn't work as expected. :( Running the program I got the following error from Paramiko:
RuntimeError: You are linking against OpenSSL 0.9.8, which is no longer support by the OpenSSL project. You need to upgrade to a newer version of OpenSSL.

The solution I found was to uninstall and reinstall the Cryptography bits and pieces by running.
pip2.7 uninstall cryptography
pip2.7 install cryptography

After all that - it now works.


Q:

Using a timer / scheduler with calendar

[In Java] Hey, I searched a lot on the web and the only thing I found doesn't work for me. What I need is to execute a specific task every week from the user's calendar. I want it to count time even if the user didn't open the application. What I found on internet would reset the calendar everytime the user would launch the app.
Thanks.

A:

I’m thinking: persist the last time the task was performed. On app launch, check if more than a week ago. If it is, execute immediately. If not, start a timer to execute a week after last time.
How to find the next execution time one week after the previous execution time? It depends on the type you use for your last execution time, but many java.time types will accept plus(1, ChronoUnit.WEEKS). Some also have a plusWeeks method for even greater convenience.


Q:

Centos Dedicated Server Security

We have clean CentOS 5.6 setup and virtualmin on it, that's all. What type of security steps would you suggest are appropriate?
http://www.wiredtree.com/supportservices/servershield.php this page have a good summary of checklists i think. which steps on these are required to do? or do you have better suggestions rather then those security hardenings:
(Esspecially ddos and brute force attack protection is a problem it seems)
Firewall Protection:

    APF – Configure both ingress and egress firewall protection.
    BFD – Detect and prevent brute force attacks.
    CPHulk – Detect and prevent brute force attacks.

HTTP Intrusion and DOS Protection:

    Mod_security – Install and configure mod_security for Apache with auto-updating ruleset.
    Mod_evasive – Install and configure DOS, DDOS, and brute force detection and suppression for Apache.
    PHP SuHosin – PHP Hardening through the Hardened PHP Project. Available on request.

Server Hardening:

    Disable IP Source Routing – Enable protection against IP source route attacks.
    Disable ICMP Redirect Acceptance – Enable protection against ICMP redirect attacks.
    Enable syncookie protection – Enable protection against TCP Syn Flood attacks.
    Enable ICMP rate-limiting – Enable protection against ICMP flood attacks.
    Harden host.conf – Enable spoofing protection and protection against DNS poisoning attacks.
    Harden Apache – Prevent module and version disclosure information.
    Harden SSH – Allow only SSH version 2 connections.
    Harden Named – Enable protection against DNS recursion attacks.
    Ensure Filesystem Permissions – Fix permission on world writable directories and prevent against directory-transversal attacks.
    Harden temporary directory and shared memory locations – Enforce noexec, nosuid on tmp and shm mounts.
    Harden “fetching” utilities - Allows root-only access of wget, curl, and other utilties often used in web-based attacks.
    Remove unnecessary packages – removes RPMS which are not needed to prevent against potential vulnerabilities and free up disk space.
    Disable unused services – Disable services which are not used.
    Disable unneeded processes – Disable processes which are not needed for server operation.
    PAM Resource Hardening – Protects against exploits which use core dumps and against user resource exhausting through fork bombs and other shell attacks.
    PHP Hardening – Enable OpenBaseDir protection.

Security Audits:

    Rootkit Hunter – Nightly scan to detect system intrusions.
    Chkrootkit – Nightly scan to detect system intrusions.
    Nobody Process Scanner – Scans for unauthorized "nobody" processes.

A:

This is a wide range question and my first answer may sound rude:
Remove Virtualmin!
Please don't get this wrong, but the possibility to open some doors with some clicks points directly to the biggest security thread: The subject between keyboard and chair.
If you want a secure setup, you should:

Only install, whats needed
Only run, whats proper configurated
Check the security advisorys for all software, you install
always check the "paranoid" section of software documentation, if you are.
try to use techniques that are maybe installed (apparmor,SELinux)

If you have a big automated security stack, you don't understand at all, you may have a bigger risk of getting hacked, than you would have with a small stack, you really know.
The biggest common mistakes in hosting environments are the webapps and the db(connection) settings. Take good care of Joomla and friends, make your DB only listen on localhost. Always use settings restrictively as possible. For example: Avoid chmod 777, read your logs. Monitor the machine with nagios. Be paranoid.
I'm really sure, you'll find help in specific cases here. In much cases "secure setup OS APPLICATION" produces a useful search result on a search engine of your choice.


Q:

In Restful web service deployed in a standalone non cluster environment, do we need to use thread safe data structures?

I have a Restful webservice deployed in a non cluster standalone setup..
As we know multiple threads will be automatically spawned to cater to the requests from multiple clients to any of the endpoints defined in this webservice..
Note that there is no explicit spawning of threads from my end..
I am using HashMap inside one of the service/business methods ..I am iterating through the Map and in certain cases removing some data from the Map..
1.Are the multiple threads spawned for the  multiple clients workinh on the same copy of the HashMap object ??
2.Is it recommended to use a ConcurrentHashMap in the above scenario even if each thread is using its own copy of the HashMap??
Putting the code snippet :-
            Map<String,List<String>> method1(Item itm){

            Map<String, FeatureEntity> featureEntityMap = itm.getFeatureEntities();// itm comes from method parameter
            Map<String,List<String>> propertyFilterMap = new HashMap<String,List<String>>();//new Map to be constructed and returned by method

            Set<String> keySet = featureEntityMap.keySet();
            Iterator itr = keySet.iterator();
            while(itr.hasNext()){
                String featureName = (String) itr.next();
                if(featureName.contains("."+lable.toLowerCase())){
                    String split [] = featureName.split("\\.");
                    if(split!=null && !LABEL_SPECIFIC_PROPERTIES.contains(split[0])){//based on condition data is deleted from featureEntityMap
                        List<String> itemList = Arrays.asList(featureEntityMap.get(featureName).getValueAsString().split("\\s*,\\s*"));
                        itr.remove();
                        propertyFilterMap.put(split[0],itemList );
                    }
                }

            }

            return propertyFilterMap;

        }

Question is "is it mandatory to use a ConcurrentHashMap for featureEntityMap ??"

A:

The below answer is based on a generic understanding of your question, since the specific code for your case is missing.
Ok, so the short answer to your question about the hashMap "object" being used by multiple sessions or "threads" as you call, will not be the same.
Unless you have a singleton implemented, each "thread" will be creating it's own HashMap object.
Now when you say;

I am iterating through the Map and in certain cases removing some data from the Map

If what you are adding and removing from a map is completely contained within that session and has no effect on any of the other sessions (or threads), you should be okay.
But if you doing some kind of transactions using the map, that will affect other sessions, you need to think it over!
eg, you are fetching properties from a file, changing them and updating the file, or say you are doing some db updates or inserts based on your map content, Or any other such activity which will affect the logic of the other thread, then you will need to synchronise your HashMap (use a ConcurrentHashMap)


Q:

Getting smaller list through this weird operation in python?

I have list1 and a factor called n. Now, I do this weird operation to return list2 from list1 based on the factor n (>1). Here is an example:
list1=[1,2,3,4,5,6,7,8,9,10]
n=2
list2=[3,7,11,15,19]

Notice that list2 is obtained by summing the adjacent numbers.Another example is :
list1=[1,2,3,4,5,6,7,8,9,10]
n=2.5
list2=[4.5,10.5,17,23]

In this case: n=2.5. So the first element in list2 = list1[0]+list1[1]+0.5*list1[2] and the second element is 0.5*list1[2]+list1[3]+list1[4] and so on. The len(list2)=ceil(len(list1)/n)
I can do it for n=2,4,8 etc. by recursively applying the following function I wrote.
def (list1,n):
list2len=ceil(len(list1)/n)
      tmparr=np.empty(list2len,dtype=float)
      for i in range(0, list2len) :
         j=2*i
         tmparr[i]=Filter[j]+Filter[j+1]
      list2=np.empty(list2len,dtype=float)
      np.copyto(list2,tmparr)

But, I am not sure how to code this in python for n ~= 2^m. Any help?

A:

This is one way:
list1=[1,2,3,4,5,6,7,8,9,10]
n = 2.5

list2 = []
s = 0
f = n
for x in list1:
    s += x*min(f, 1.)
    f -= 1
    if f <= 0:
        list2.append(s)
        s = x*-f
        f += n
print list2


Q:

Is there something that iBeacon offers that can't be done on iOS 6 using Core Bluetooth?

I've been starting to read about the above and on BLE devices in general and trying to find the differences between those 2 frameworks. Is there something that the iBeacon API offers beside the option to use startMonitoringForRegion with CLBeaconRegion (which will basically "wake up" or notify the app that you're in range)?
To my understanding on iPhone 4S and up I can get a list of BLE devices and check their signal strength on iOS 6 sure, i't will not be as simple as the API for ranging but still, am I missing something?
Thanks

A:

Yes, the CoreLocation APIs allow you to see iBeacon devices where CoreBluetooth does not.  See my in depth discussion of this here:  http://developer.radiusnetworks.com/2013/10/21/corebluetooth-doesnt-let-you-see-ibeacons.html
This may not matter if you want to roll your own Bluetooth LE devices that are fully visible by CoreBluetooth.  But such devices are somewhat more complex and more power-hungry.  iBeacons by contrast are transmit only and send a minimal amount of data.
The bottom line is that if you want your app to see standard iBeacons, CoreBluetooth simply will not do the job.


Q:

java stream mutate data with terminal operation

Java Stream Cheat Sheet
Going by this Cheat sheet for Java Stream - I understand that Java streams cannot mutate data.

For example in the code used below, am I right in saying that - using a forEach terminal operation the data is being mutated?
List<Foo> fooList=new ArrayList<>();
fooList.stream()
.filter(foo-> return foo.getSomeBoolean())
.forEach(foo->{
  foo.setSomeBoolean(false);
});

I am confused that the forEach terminal operation can have side effects on the data but not mutate the data?

Could someone explain how the foreach is allowed to mutate the data here?

A:

You cannot mutate fooList, but you can perform side-effects on the elements using terminal operations. As the cheat sheet says, a stream is a pipe-line, not a data structure. You cannot mutate something that is not a data structure, but you can manipulate the individual elements that are flowing through the pipeline.


Q:

When building my flutter app, it fails with GradleExeption

When I try to build my app for public release I get this error from the app level build.gradle. I'm getting the error below:
Launching lib\main.dart on SM G973F in debug mode...
Initializing gradle...
Resolving dependencies...
* Error running Gradle:
ProcessException: Process "C:\Users\tbsvst18tedbom\AndroidStudioProjects\tab_truth_true\android\gradlew.bat" exited abnormally:

FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\tbsvst18tedbom\AndroidStudioProjects\tab_truth_true\android\app\build.gradle' line: 11

* What went wrong:
Could not compile build file 'C:\Users\tbsvst18tedbom\AndroidStudioProjects\tab_truth_true\android\app\build.gradle'.
> startup failed:
  build file 'C:\Users\tbsvst18tedbom\AndroidStudioProjects\tab_truth_true\android\app\build.gradle': 11: unable to resolve class GradleExeption
   @ line 11, column 11.
         throw new GradleExeption("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
               ^

  1 error

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
  Command: C:\Users\tbsvst18tedbom\AndroidStudioProjects\tab_truth_true\android\gradlew.bat app:properties

Finished with error: Please review your Gradle project setup in the android/ folder.

This is the app level build.gradle code:
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleExeption("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1.0.0'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 29

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.tab.tab_truth_true"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-ads:18.3.0'
}

apply plugin: 'com.google.gms.google-services'  // Google Play services Gradle plugin

I have tried everything, what I know, but achieved nothing.  please help me out.

A:

You've got a typo in your Gradle file, change GradleExeption to GradleException at line 11 in your Gradle file.


Q:

The difference in Haskell function argument type declaration

I am new to Haskell.
I am just confused by the difference between the argument type declarations here:
someFunction :: (Integral a) => a -> Bool -> a

This will compile.
someFunction :: (Integral a, Bool b) => a -> b -> a

Yet given this, the compiler will complain:

• Expecting one fewer arguments to ‘Bool’
  Expected kind ‘* -> Constraint’, but ‘Bool’ has kind ‘*’
• In the type signature:
    someFunction :: (Integral a, Bool b) => a -> b -> a

What is the difference between the two declarations?  I tried to search with Google but it seems there is no direct answer to this one.
Thanks!

Thanks for the quick answers guys. And they lead me to the next question: what are the thoughts behind having argument constraints to be in different places in the declaration? (vs C-like languages where the constraints, abstract or concrete, are mixed together in the declaration)

A:

Integral is not a type: it is a typeclass. It describes a constraint on a type.
So, the signature:
someFunction :: (Integral a) => a -> Bool -> a

means that "As long as a is an instance of Integral, this function can work on it".
Your second example of  (Integral a, Bool b) => a -> b -> a does not make sense, because Bool is a type, not a typeclass.
What does it mean to be an instance of Integral? Well, it means that somewhere, someone has written, for some type, for instance Int:
instance Integral Int where
    -- (declarations here)

Here's an example of your own typeclass: Sizeable:
class Sizeable s where
    size :: s -> Int

We can see this as types which have an associated size, which is defined by the size function. So, we can add some instances:
instance Sizeable [a] where
    size = length

instance Sizeable (a,b) where
    size _ = 2

instance Sizeable (a,b,c) where
    size _ = 3

So, we could write the function:
sizePlusOne s = (size s) + 1

And this would have the type:
sizePlusOne :: (Sizeable s) => s -> Int


Q:

Jquery match text string but exclude some if part of a phrase

I have a project where I need to identify gender specific terminology but ignore the match if it's included in a list of phrases. I can get the following to work, I'll assume it's very inefficient, but if I try to add any more terms to the list I think I'm exceeding character length for the line.  How could I code this better, is it possible to have two separate arrays - one for the list of words to search (including word boundaries) and another for the list of excluded phrases?  When the match is identified it's highlighted by a red box. Thanks.
$( '#body' ).filter(function(index,obj) {
            if(/\b(boy)\b|\b(girl)\b|\b(son)\b|\b(daughter)\b|\b(grandfather)\b|\b(grandmother)\b|\b(father)\b|\b(mother)\b|\b(de facto)\b|\b(de-facto)\b|\b(husband)\b|\b(wife)\b|\b(lady)\b|\b(female)\b|\b(woman)\b|\b(gentleman)\b|\b(male)\b|\b(man)\b|\b(uncle)\b/.test($(obj).clone().removeInnerElements().html().toLowerCase())){

                if(/(Wife Pension|Dad and Partner pay|Isle of Man|What a Man project)/.test($(obj).elements[0].innerHTML)) {
                    return false;
                }
                return true;
            }
            return false;
        },
        $(obj).css("border","solid 3px red");

A:

if anyone is interested here's the working solution.  Thank you Terry for responding:
$( '#body' ).filter(function(index,obj){

            var html = $(obj).clone().removeInnerElements().html().toLowerCase();

            var blackList = [
              "boy",
              "girl",
              "son",
              "daughter",
              "grand\\s?father",
              "grand\\s?mother",
              "father",
              "mother",
              "de\\s?facto",
              "husband",
              "wife",
              "lady",
              "female",
              "woman",
              "gentleman",
              "male",
              "man"
            ];

            var allowedTerms = [
                "wife\\spension",
                "dad\\sand\\spartner\\spay",
                "isle\\sof\\sman",
                "what\\sa\\sman\\sproject"
            ];

            for (i in allowedTerms) {
                var re = new RegExp("\\b"+allowedTerms[i]+"\\b", "g");
                if (re.test(html)) {
                    html = html.replace(re, "");
                }
            }

            for (i in blackList) {
                var re = new RegExp("\\b"+blackList[i]+"\\b");
                if (re.test(html)) {
                    return true;
                }
            }

            return false;
        },
    $(obj).css("border","solid 3px red");


Q:

Inspect internal variables as scipy.optimize.minimize runs?

I usually inspect my variables with pdb as my program runs. Now I wish to debug my scipy.optimize.minimize by inspecting the variables as the optimization runs.
result = scipy.optimize.minimize(fun, x0, method='dogleg')

I tried using the callback option, but it doesn't give me access to the optimization's internal parameters, such as the Jacobian matrix, etc.
The returned result does have all the information I need, but it's only returned at the end of the entire optimization, but I need the (intermediate) results as the optimization runs.
So my question: how do I return the intermediate optimization parameters (such as Jacobian) as scipy.optimize.minimize runs?

A:

The easy way:
Just edit your local copy of scipy directly, chucking in printouts or logging into the source files directly.  You said this was just for debugging, anyway.  You could modify the callback to pass more info along.  Or, you could insert the pdb.set_trace() directly there into the optimization code and look around interactively.  To find which file you should be hacking around in, locate where the module is:
scipy.optimize.__file__

and then follow the trail.  You might want to delete any .pyc files hanging around.  In current scipy, it's located here in _minimize_trust_region.
The "clever" way:
You can use introspection to step back a frame and find the local variables, without needing to modify scipy sources directly.  Using frame hacks is fragile and implementation dependent, so by all means experiment with it for debugging but don't let stuff like this into any actual library code.
from scipy.optimize import minimize
import inspect

def fun(x):
    return (x - 42)**2

def jac(x):
    return 2*(x - 42)

def hess(x):
    return [[2]]

def vanilla_cb(x):
    print(x)

def callback_on_crack(x):
    print(inspect.currentframe().f_back.f_locals)
    print(x)

Using the plain callback, and starting at x0=99 we reach the minimum 42 after 6 iterations:
>>> minimize(fun,x0=99,method='dogleg',jac=jac,hess=hess,callback=vanilla_cb)
[ 98.]
[ 96.]
[ 92.]
[ 84.]
[ 68.]
[ 42.]

Using the souped-up callback, you can see all the good stuff in a dict!
>>> minimize(fun,99,method='dogleg',jac=jac,hess=hess,callback=callback_on_crack)
{'disp': False, 'unknown_options': {}, 'm': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9d10>, 'm_proposed': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9d10>, 'return_all': False, 'hess': <function function_wrapper at 0x1248938>, 'callback': <function callback_on_crack at 0x12487d0>, 'nhessp': [0], 'njac': [1], 'predicted_reduction': array([ 113.]), 'subproblem': <class 'scipy.optimize._trustregion_dogleg.DoglegSubproblem'>, 'maxiter': 200, 'warnflag': 0, 'gtol': 0.0001, 'args': (), 'initial_trust_radius': 1.0, 'hits_boundary': True, 'trust_radius': 2.0, 'predicted_value': array([ 3136.]), 'rho': array([ 1.]), 'x': array([ 98.]), 'nhess': [1], 'x0': array([ 99.]), 'hessp': None, 'k': 0, 'actual_reduction': array([ 113.]), 'jac': <function function_wrapper at 0x12488c0>, 'p': array([-1.]), 'eta': 0.15, 'fun': <function function_wrapper at 0x1248848>, 'nfun': [2], 'max_trust_radius': 1000.0, 'x_proposed': array([ 98.])}
[ 98.]
{'disp': False, 'unknown_options': {}, 'm': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9d90>, 'm_proposed': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9d90>, 'return_all': False, 'hess': <function function_wrapper at 0x1248938>, 'callback': <function callback_on_crack at 0x12487d0>, 'nhessp': [0], 'njac': [2], 'predicted_reduction': array([ 220.]), 'subproblem': <class 'scipy.optimize._trustregion_dogleg.DoglegSubproblem'>, 'maxiter': 200, 'warnflag': 0, 'gtol': 0.0001, 'args': (), 'initial_trust_radius': 1.0, 'hits_boundary': True, 'trust_radius': 4.0, 'predicted_value': array([ 2916.]), 'rho': array([ 1.]), 'x': array([ 96.]), 'nhess': [2], 'x0': array([ 99.]), 'hessp': None, 'k': 1, 'actual_reduction': array([ 220.]), 'jac': <function function_wrapper at 0x12488c0>, 'p': array([-2.]), 'eta': 0.15, 'fun': <function function_wrapper at 0x1248848>, 'nfun': [3], 'max_trust_radius': 1000.0, 'x_proposed': array([ 96.])}
[ 96.]
{'disp': False, 'unknown_options': {}, 'm': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9e50>, 'm_proposed': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9e50>, 'return_all': False, 'hess': <function function_wrapper at 0x1248938>, 'callback': <function callback_on_crack at 0x12487d0>, 'nhessp': [0], 'njac': [3], 'predicted_reduction': array([ 416.]), 'subproblem': <class 'scipy.optimize._trustregion_dogleg.DoglegSubproblem'>, 'maxiter': 200, 'warnflag': 0, 'gtol': 0.0001, 'args': (), 'initial_trust_radius': 1.0, 'hits_boundary': True, 'trust_radius': 8.0, 'predicted_value': array([ 2500.]), 'rho': array([ 1.]), 'x': array([ 92.]), 'nhess': [3], 'x0': array([ 99.]), 'hessp': None, 'k': 2, 'actual_reduction': array([ 416.]), 'jac': <function function_wrapper at 0x12488c0>, 'p': array([-4.]), 'eta': 0.15, 'fun': <function function_wrapper at 0x1248848>, 'nfun': [4], 'max_trust_radius': 1000.0, 'x_proposed': array([ 92.])}
[ 92.]
{'disp': False, 'unknown_options': {}, 'm': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9dd0>, 'm_proposed': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9dd0>, 'return_all': False, 'hess': <function function_wrapper at 0x1248938>, 'callback': <function callback_on_crack at 0x12487d0>, 'nhessp': [0], 'njac': [4], 'predicted_reduction': array([ 736.]), 'subproblem': <class 'scipy.optimize._trustregion_dogleg.DoglegSubproblem'>, 'maxiter': 200, 'warnflag': 0, 'gtol': 0.0001, 'args': (), 'initial_trust_radius': 1.0, 'hits_boundary': True, 'trust_radius': 16.0, 'predicted_value': array([ 1764.]), 'rho': array([ 1.]), 'x': array([ 84.]), 'nhess': [4], 'x0': array([ 99.]), 'hessp': None, 'k': 3, 'actual_reduction': array([ 736.]), 'jac': <function function_wrapper at 0x12488c0>, 'p': array([-8.]), 'eta': 0.15, 'fun': <function function_wrapper at 0x1248848>, 'nfun': [5], 'max_trust_radius': 1000.0, 'x_proposed': array([ 84.])}
[ 84.]
{'disp': False, 'unknown_options': {}, 'm': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9e10>, 'm_proposed': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9e10>, 'return_all': False, 'hess': <function function_wrapper at 0x1248938>, 'callback': <function callback_on_crack at 0x12487d0>, 'nhessp': [0], 'njac': [5], 'predicted_reduction': array([ 1088.]), 'subproblem': <class 'scipy.optimize._trustregion_dogleg.DoglegSubproblem'>, 'maxiter': 200, 'warnflag': 0, 'gtol': 0.0001, 'args': (), 'initial_trust_radius': 1.0, 'hits_boundary': True, 'trust_radius': 32.0, 'predicted_value': array([ 676.]), 'rho': array([ 1.]), 'x': array([ 68.]), 'nhess': [5], 'x0': array([ 99.]), 'hessp': None, 'k': 4, 'actual_reduction': array([ 1088.]), 'jac': <function function_wrapper at 0x12488c0>, 'p': array([-16.]), 'eta': 0.15, 'fun': <function function_wrapper at 0x1248848>, 'nfun': [6], 'max_trust_radius': 1000.0, 'x_proposed': array([ 68.])}
[ 68.]
{'disp': False, 'unknown_options': {}, 'm': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9d50>, 'm_proposed': <scipy.optimize._trustregion_dogleg.DoglegSubproblem object at 0xdc9d50>, 'return_all': False, 'hess': <function function_wrapper at 0x1248938>, 'callback': <function callback_on_crack at 0x12487d0>, 'nhessp': [0], 'njac': [6], 'predicted_reduction': array([ 676.]), 'subproblem': <class 'scipy.optimize._trustregion_dogleg.DoglegSubproblem'>, 'maxiter': 200, 'warnflag': 0, 'gtol': 0.0001, 'args': (), 'initial_trust_radius': 1.0, 'hits_boundary': False, 'trust_radius': 32.0, 'predicted_value': array([ 0.]), 'rho': array([ 1.]), 'x': array([ 42.]), 'nhess': [6], 'x0': array([ 99.]), 'hessp': None, 'k': 5, 'actual_reduction': array([ 676.]), 'jac': <function function_wrapper at 0x12488c0>, 'p': array([-26.]), 'eta': 0.15, 'fun': <function function_wrapper at 0x1248848>, 'nfun': [7], 'max_trust_radius': 1000.0, 'x_proposed': array([ 42.])}
[ 42.]


Q:

How to remove duplicate search result in elasticsearch?

First Create some example data (e1,e2,e3 are types and test is the index name):
PUT test/e1/1
{
  "id":1
  "subject": "subject 1"
}
PUT test/e2/1
{
  "id":1
  "subject": "subject 2"
}
PUT test/e3/2
{
  "id":2
  "subject": "subject 3"
}

Now my question is: how can I get just these two data? remove duplicate data with the same id in the curl -XGET _search result.
test/e1/1
{
  "id":1
  "subject": "subject 1"
}
test/e3/2
{
  "id":2
  "subject": "subject 3"
}

A:

First you will need to search across multiple index.
Then, on the result remove the duplicate ID.
POST  http://myElastic.com/test/e1,e2,e3/_search
{
  "aggs":{
    "dedup" : {
      "terms":{
        "field": "id"
       },
       "aggs":{
         "dedup_docs":{
           "top_hits":{
             "size":1
           }
         }
       }
    }
  }
}

This might help you:

search multi-index type
Remove duplicate documents from a search in Elasticsearch
Filter elasticsearch results to contain only unique documents based on one field value


Q:

Authenticating with Google API library for Java to Google cloud

I am attempting to create some GCP VMs using the API client libraries for Java, but the examples that I have seen seem to be old. I started with this https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/compute/cmdline/src/main/java/ComputeEngineSample.java but it looks like the GoogleCredential class is deprecated.
After some research I came up with this code
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
        if (credentials.createScopedRequired()) {
            List<String> scopes = new ArrayList<>();
            scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
            scopes.add(ComputeScopes.DEVSTORAGE_READ_WRITE);
            credentials = credentials.createScoped(scopes);
        }
        Compute compute = new Compute.Builder(httpTransport, jsonFactory, null)
            .setApplicationName("et").build();
        Compute.Instances.List instancesList = compute.instances().list("<GCP-PROJECT>", "us-central1-a");
        InstanceList executedOperation = instancesList.execute();

Next, I set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of my service account json file and ran my code, but it fails with a 401 Unauthorized error. The partial message is this
"message" : "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential.

The examples that I see are for other Google products like Storage, Pubsub etc, but I cant find any relevant example on how to use my credentials to invoke some operations on a Compute service. Any help would be appreciated.

A:

I took the Google sample and it works for me.
I abbreviated it to only enumerate instances.
PROJECT=
ZONE=
INSTANCE=
ACCOUNT=

gcloud projects create ${PROJECT}

gcloud alpha billing projects link ${PROJECT} \
--billing-account=${BILLING}

gcloud services enable compute.googleapis.com \
--project=${PROJECT}

# Create an instance to enumerate
gcloud compute instances create instance-1 \
--project=${PROJECT}  \
--zone=${ZONE} \
--machine-type=f1-micro \
--image-family=debian-10 \
--image-project=debian-cloud \
--preemptible

gcloud iam service-accounts create ${ACCOUNT} \
--project=${PROJECT}

gcloud iam service-accounts keys create ./${ACCOUNT}.json \
--iam-account=${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com \
--project=${PROJECT}

# Overly broad permissions but...
gcloud projects  add-iam-policy-binding ${PROJECT} \
--member=serviceAccount:${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com \
--role=roles/compute.admin

export GOOGLE_APPLICATION_CREDENTIALS=./${ACCOUNT}.json
mvn exec:java -Dexec.mainClass="com.dazwilkin.gce.App"

yields (edited for clarity):
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------------< com.dazwilkin.gce:gce >------------------------
[INFO] Building gce 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) @ gce ---
Hello Freddie!
================== Listing Compute Engine Instances ==================
{
  "id" : "6020825766320745087",
  "kind" : "compute#instance",
  "name" : "instance-1",
}
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.088 s
[INFO] Finished at: 2020-05-13T17:54:51-07:00
[INFO] ------------------------------------------------------------------------

and pom.xml:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.dazwilkin.gce</groupId>
  <artifactId>gce</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>gce</name>
  <url>http://maven.apache.org</url>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.9</source>
          <target>1.9</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>1.30.9</version>
    </dependency>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-compute</artifactId>
      <version>v1-rev235-1.25.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Update: google-auth-library
From the google-auth-library docs:

import com.google.auth.Credentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.http.HttpCredentialsAdapter;

import com.google.api.client.http.HttpRequestInitializer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class App
{

    public static void main(String[] args )
    {

    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    ...

    HttpRequestInitializer requestInitializer =
        new HttpCredentialsAdapter(credentials);
    Compute compute =
        new Compute.Builder(httpTransport, JSON_FACTORY, requestInitializer)
            .setApplicationName(APPLICATION_NAME)
            .build();
    ...

}

with pom.xml:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.dazwilkin.gce</groupId>
  <artifactId>gce</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>gce</name>
  <url>http://maven.apache.org</url>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.9</source>
          <target>1.9</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>1.30.9</version>
    </dependency>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-compute</artifactId>
      <version>v1-rev235-1.25.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-credentials</artifactId>
      <version>0.20.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-oauth2-http</artifactId>
      <version>0.20.0</version>
    </dependency>
  </dependencies>
</project>


Q:

Is there a way to move the unity launcher 'show' edge on multiple monitor setup?

I'm in a situation where my primary monitor is on my right and that is the screen with the Unity launcher. When I fullscreen an app, the edge that actually tiggers the launcher to reappear is on my left, on the screen that does not have the launcher.
Is there a way to fix this without moving the unity launcher to my left?
This is under Ubuntu 11.04.

A:

Sounds like a bug!
The detailed multi-monitor design is being worked out now, for 12.04 LTS. You might want to take a look at the proposed design as soon as a draft is available. Check design.canonical.com for news, or hop into #ubuntu-design to see if a draft is available.


Q:

How to deseralize and loop through JSON

I am trying to deserialize my JSON with newtonsoftjson so I cant loop through it with an foreach.
I know that I have to model my class as my JSON object and I think this is here I come short.
Also I am not quite sure how to implement the namespace so I basically just put it underneath the @page which doesn't throw and error so I guess that's fine (if this is wrong please let me know).
My files are:
TodoItem.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1
{
    public class TodoItem
    {
        public List<Array> tasks { get; set; }
        public int id { get; set; }
        public string name{ get; set; }
    }
}

Tasks.json:
[
    {
        "tasks": [
            {
                "id": 1,
                "name": "Køb tøj"
            },
            {
                "id": 2,
                "name": "vask tøj"
            },
            {
                "id": 3,
                "name": "Gør Rent"
            }
        ]
    }
]

Index.cshtml:
@using WebApplication1
@{
    Layout = "_Layout.cshtml";

    var json = System.IO.File.ReadAllText("pathtojson");

    List<TodoItem> data = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TodoItem>>(json);

}

    @{
        foreach(var item in data)
        {

@item

        }
    }

A:

You have an collection of Tasks.  Each Task has Id and Name properties.
 This can be modelled by splitting your class and updating to the below:
public class TodoItem
{
    public List<Task> Tasks { get; set; }
}

public class Task
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Then you can deserialize as:
TodoItem data = JsonConvert.DeserializeObject<TodoItem>(json);

foreach (var task in data.Tasks)
{
    Console.WriteLine($"Id: {task.Id}, Name: {task.Name}");
}

Rather than process the json in the view, I would deserialize the json in the controller then pass the deserialized json (model) back to the view.
// controller
public IActionResult Index()
{
    var json = System.IO.File.ReadAllText("pathtojson");
    TodoItem data = JsonConvert.DeserializeObject<TodoItem>(json);

    return View(data);    // pass the data the your view
}

// razor view
@model WebApplication1.Models.TodoItem    // define model for view
@{
    Layout = "_Layout.cshtml";
}
@foreach (var task in Model.Tasks)
{

Id: @task.Id, Name: @task.Name

}

I created a fiddle.


Q:

Why is there "is" in "... dīcitur is locus..."?

Why is there is (it) in the following phrase from Ørberg's Lingua Latina per se Illustrata, page 118?

Ōstium sīve ōs flūminis dīcitur is locus quō flumen in mare īnfluit.

Literally: By Ostium or os of the river is called [it] place where river in sea flows in.

A:

In this case, is, ea, id is a demonstrative pronoun (like hic, haec, hoc; ille, illa, illud; etc.).
Allen & Greenough §297 says the following about is, ea, id:

Is is a weaker demonstrative than the others and is especially common as a personal pronoun. It does not denote any special object, but refers to one just mentioned, or to be afterwards explained by a relative. Often it is merely a correlative to the relative quī:—

vēnit mihi obviam tuus puer, is mihi litterās abs tē reddidit (Att. 2.1.1), your boy met me, he delivered to me a letter from you.
eum cōnsulem quī nōn dubitet (Cat. 4.24), a consul who will not hesitate.

Your sample sentence demonstrates this correlation with a relative pronoun. You could translate as:

The [or: "that"] place by which a river flows into the sea is called the ostium [doorway] or os [mouth] of the river.

A:

This is a case where a word-by-word translation is misleading.
If you translate is as "that", it makes more sense.
And here you could translate it as "the".
In Latin you can use is like an adjective (e.g. is locus), but in English you can't (e.g. "it place" doesn't make sense, but "the place", "that place", or "this place" does).
The word is is not strictly necessary in the sentence, but it adds emphasis and gives a clear antecedent for the relative pronoun.


Q:

Create default childs to node in umbraco

I'm trying to find out how to force node to create only one node child of other type ?
I have 'hotel' node and i want to add one 'rooms' node and one 'facilities' node ('rooms' create 'room' and 'facilities' create 'facility')
by default when i will create hotel the system will create this 2 folders or to force him that he can create only one each
I prefer to do it with the management system (if possible) but code behind be good also !
Thanks in advance for all helpers!

A:

As far as I am concerned, I do not know a way to achieve this by means of the Umbraco backoffice.
However, you can use the ContentService Events in order to cancel the creation of that particular page if it has been already created. The ContentServiceSaving method will fire up each time that you try to create a node in the CMS.
public class ContentServiceEventsController : ApplicationEventHandler
{
    protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
      ContentService.Saving += ContentServiceSaving;
    }

    private void ContentServiceSaving(IContentService sender, SaveEventArgs<IContent> e)
    {

      switch (e.Entity.ContentType.Alias)
      {
        case "RoomsDocumentTypeAlias":
        case "FacilitiesDocumentTypeAlias":

        // Do your logic to detect if your Hotel node "Hilton eilat queen of sheba"
        // already contains either a Rooms node or a Facilities node underneath.
        // If so, cancel the creation of the event of a new one.
        e.Cancel = true;
        break;

        default:
               break;
      }
    }


Q:

Laravel 3 tables model relation construction

Hello I have the following 3 tables that are related to each other with ids as follows , I am trying to create a model in Laravel for each but I am confused in to how to use belongsTo & others...
 TABLE: posts
 -----------------------------
 id        Auto-inc
 type_id   if (3 its for a blog)
 title
 content

 TABLE: blog
 -----------------------------
 id        Auto-inc
 post_id   the post id
 cat_id    blog_cat table id
 slug

 TABLE:blog_cat
 -----------------------------
 id    Auto-inc
 cat_name

Now I am trying to write the model for Blog.php , BlogCat.php & Post.php , where I can use something like this :
$blog = Post::with('blogCat')->get()->toArray();

to get an array with the post & if type_id = 3 ( blog) to get also an array of the blog info from the blog table is this possible or I just need to use select , where / Join?
Thanks

A:

In your Blog model, you need a cat() relationship that returns a BelongsTo().
In your Post Model, you need a blog() relationship that returns a HasOne().
To get a collection of Posts with Blogs eager-loaded:
$blog = Post::with('blog')->get()

To get a collection of Posts with Blogs eager-loaded and BlogCats eager-loaded for each Blog:
$blog = Post::with('blog.blogCat')->get()

In order to only load Blog for Posts with a type_id of 3, you need to use an "eager load constraint"


Q:

Regex match 1024KB convert to 1MB?

I get the file size from the index of the page, it's 1024KB and I want it to print 1MB stead of 1024KB, what should I do? (completely noob here)
I got this:
if($row[2]==1) // Rapidshare Check
{
  $index=getpage($row[1]);
  if(strpos($index,"FILE DOWNLOAD")===false) //check if page contains the word file download  if not = bad link
  {
    mysql_query("UPDATE `v2links` SET `checked`='-1',`lastcheck`=NOW() WHERE `id`=".$row[0]);
    print "bad link\n";
    logstr("log-c.txt","bad link\n");
   }
   else
   {

    preg_match("**/([^\/\|\#\<\(\>\;\s][0-9]*[\s][KB]{2})/**",$index,$match);

     $fsize=$match[1];

  print $fsize."\n";
  logstr("log-c.txt","bad link\n");
  //logstr("log-c.txt","$caption | $fsize\n");
  mysql_query("UPDATE `v2links` SET `checked`='1',`fsize`='$fsize',`lastcheck`=NOW() WHERE `id`=".$row[0]);
  unset($match);
  }
 }

Thanks

A:

How accurate do you want the conversion to be?
s/0*([0-9]+)[0-9]{3}K/\1M/g

will lop off the last three numbers of a four or greater digit size... but it's a truncation, and doesn't even consider math.  (For example, 1999K -> 1M)
A possibly better method would be to s/K/000/g and s/M/000000/g to turn it into a (crude) number of bytes, and then convert as  you want back down.
The best possible method would be to process it, if it has a M multiply by 1024*1024; if it has K multiply by 1024. (if it has G, multiply by 1024*1024*1024).  Then, process the resulting size however you're trying to.
--Note that it'd be a good plan to store file size as an integer, rather than a string.
For processing and output, a series of if's are probably good enough, and you can set precise tollerances for how big something must be to be displayed as M instead of K.
--Or if you just want M, there's no if, and you just divide by 1024*1024.


Q:

Trace Diagnostics on Windows Azure not working when Defining Compile constants in msbuild

I have a Cloud Service project on windows Azure that have been running just fine with diagnostics working. Today I needed to add a compile constant in the build.
#if INCLUDE_LICENSE_MANAGER

#endif

I did this by giving msbuild the arguments /p:DefineConstants=INCLUDE_LICENSE_MANAGER but this resulted in the Trace written to diagnostics stopped working. (using the azure trace listener to log to blob storage ect)
So what have I misunderstood about Compile Constants since it caused my tracing to stop working?

A:

Your issue is actually related to MSBuild and the DefineConstants parameter.
When you use /p:DefineConstants=INCLUDE_LICENSE_MANAGER, MSBuild overrides the conditional compilation symbols already defined in your .csproj file (as noted here, but it is very easy to reproduce in a simple Console Application).
The TRACE conditional compilation symbol which is defined by default (both for Debug and Release configuration when creating a new project) is not defined anymore, thus preventing most methods from the System.Diagnostics.Trace to be executed.
In your case, you should manually define the TRACE constant in your MSBuild command, by using /p:DefineConstants="INCLUDE_LICENSE_MANAGER;TRACE".


Q:

Characteristic of integral domain if $(x+1)^2=x^2+1$

Let $A$  be an integral domain. Prove that if $(x+1)^2=x^2+1$ in $A[x]$, then $A$ must have characteristic $2$.

We have $x^2+2x+1=x^2+1$, so $2=0$, and hence the characteristic must be $1$ or $2$. Now, I don't see anything wrong with the characteristic being $1$. So, is the problem correct?

A:

The characteristic of an integral domain is the smallest positive integer $n$ such that $n \cdot 1_A= 0_A$. So if $n=1$, then $1_A = 0_A$ in your integral domain $A$. But, we usually (i.e. pretty much always) assume that an integral domain must have unity different from the $0$. Note that a characteristic of an integral domain must always be prime.


Q:

301 redirects to all except robots.txt

We have moved our website to a new domain and want all pages of the old site to get removed from search engines. It's the same site, same content, just a new domain, so search engines are taking time because of duplicate content (maybe). We have added .htaccess 301 from our old site to new site as:
redirect 301 / http://new-domain.com/

Now, to remove our old site from search engines, we changed our robots.txt on the old site as:
User-agent: *
Disallow: /

The problem is, the search engines are fetching robots.txt from the new-domain.com because of .htaccess 301 redirect.
How do I restrict 301 redirect for robots.txt?

A:

Remove the Redirect directive and try this mod_rewrite rule:
RewriteEngine on
RewriteRule !^robots\.txt$ http://other.example.com%{REQUEST_URI} [L,R=301]

This will redirect any request except /robots.txt.


Q:

Why Array index start from '0'

I have a question on C/C++ arrays.
Why does the index of the arrays start from '0' not from '1'?
Is there any mathematical reason for that?

A:

In most programming language, the name of any array is a pointer, which is nothing but a reference to a memory location, and so the expression array[n] points to a memory location which is n-elements away from the first element. This means that the index is used as an offset. The first element of the array is exactly contained in the memory location that array points to (0 elements away), so it should always be referred as array[0].
a[i] can also be read as value at [a+i] which is denoted as *(a+i) , so it always starts at zero.


Q:

Issue with scss syntax after conversion from less

My task is to convert all less to scss files . I used npm dependency "less-scss-convertor" for the same .
But when i am creating scss files i am getting these three errors repeatedly .
1st scenario -
In my common.scss i have defined
$S: "all and (max-width: 767px)";

in some other scss file i am using -
@media $S {
    .test-class {
        font-size: 8px;
    }
}

error1 - "media query expression must begin with '('"
2nd scenario -
In color.scss -
@mixin test-class("black", 1, 2);

@mixin generate-color-class($color, $arg1,
 $arg2) when ($arg2 > 0) {
    .${color}-${arg1} {
        color: ~"${${color}-${arg1}}";
     }
    @include generate-color-class($color,
 ($arg1 + 1), ($arg2 - 1));
}

error 2 - Invalid CSS after "...te-color-class(": expected ")", was '"black", 1, 2);'
3rd scenario -
@mixin vertical-translate($percent) {
    -ms-transform: translateY($percent);
    -webkit-transform: translateY($percent);
    transform: translateY($percent);
}

.Headerclass {
    @include vertical-translate (-50%);
 }

error 3 - no mixin named vertical-translate
Any pointers where i am going wrong ?

A:

1st scenario
You need to use the interpolation syntax of Sass: #{$var}
About Interpolation
@media #{$S} {
    .test-class {
        font-size: 8px;
    }
}

2nd scenario
See how mixins work with Sass. It's very different from Less.
About Mixins

3rd scenario
It works for me. Maybe you should remove the white space.
vertical-translate(-50%);


Q:

Should we allow PKI related questions?

If I take a look at our Tour this crypto site is for questions about:

Asymmetric and symmetric cryptographic algorithms
Cryptographic protocols and cryptanalysis techniques
Hashing
Entropy and information theory
Random number generation

although above is just a sample of course.
Should we allow Public Key Infrastructure related issues or should we close them (if unanswered) or migrate them to the IT Security site?

A:

In my opinion questions about PKI and key management are better asked at the IT Security site; that is: if they are mainly concerned about management (company rules, expiration dates etc). If they are about the algorithms or protocols used to accomplish PKI or key management however they could be on topic (i.e. we should not close them even when they are borderline off-topic, for instance if they are about chain verification).
This would still allow a lot of questions, which is good because we should be more concerned about answering questions than strict separation between IT security and crypto.


Q:

Ruby on Rails model associations nubie question

dear developers I have some problems with Rails models
Here is my sql tables
  create_table "areas", :primary_key => "ndc", :force => true do |t|
    t.string "townname", :limit => 256, :null => false
  end

  create_table "books", :primary_key => "ndc", :force => true do |t|
    t.integer "booked", :null => false
    t.integer "free",   :null => false
  end

class Book < ActiveRecord::Base
  self.primary_key = "ndc"
  has_one :area, :foreign_key => 'ndc'
end

class Area < ActiveRecord::Base
    self.primary_key = "ndc"
    belongs_to :book , :foreign_key => 'ndc'
end

in controller I have such code
   @books = Book.paginate :page => params[:page] || 1, :per_page => 10
     @books.each do |booking|
      p booking.area
      p booking

     end

In production mode doesn't work, booking.area is nil object. what it can be ?
Area becames nil if   config.cache_classes = true
so booking.area generates such queries
if cashe_classes = true
SELECT areas.* FROM areas WHERE (areas.ndc = NULL) LIMIT 1
but without cashing classes
 SELECT areas.* FROM areas WHERE (areas.ndc = 30) LIMIT 1
FIXED by removing  belongs_to :book , :foreign_key => 'ndc' from area class.

A:

Your areas table needs a book_id integer field to match against the books table's primary key.


Q:

Track HTML submissions when Javascript is being used

Conventional HTML lets you submit data via forms to a website and the destination (target) is usually visible in the sourcecode. Now, with JS it's a bit more difficult. You have to go through the JS files and find out what happens and where all the data is being sent to.
Is there an easier way to pin down where my data ends up (i.e. what file/address it is being sent to)??
Something like: I click on the button and it shows me what type of action was used and the destination URL?!
I'm on Ubuntu.

A:

Are you trying to prevent phishing attacks or merely capture redirects/ajax calls on button clicks .. what's the purpose of this experiment?
Because Firebug (a firefox add-on) or Chrome Inspector (native to Chrome, not quite as robust as Firebug) will do the things that you're asking for, and give you lots more information to boot.
Additionally, you might consider setting up a local proxy on your machine and capturing all http traffic. It really depends on what you're trying to accomplish.


Q:

Now I see there are a lot of duplicate questions on Stack Overflow

Possible Duplicates:
What can be done about repetitive questions?
Dealing with endlessly repeated questions

I am new to Stack Overflow, but I figured out there are a lot of questions continuously repeating with some key changes, and as I figured out using Google, I found the links of Stack Overflow with the almost same question and lots of very good answers.
Does it have worth to find the same answer on Stack Overflow and give the user the link of that article? Or post that code again?

A:

I think Stack Overflow is a community, so the community decides what is duplicate or not. If a group of people (mostly 5) thinks that a post is an exact duplicate, they can vote to close it.
If you don't have permissions for voting to close you can always comment with a link to the related question that delivers the correct answer, or flag it as duplicate. The OP will notice that and will get the answer to his question that way. Another happy customer leaves the building.
Otherwise, answer the question in full, with a clear written answer that might even better than the other answers on alike questions.
IMHO, answers with just links, even inside Stack Overflow are adding no (or at least a minimum) value at all, since the data on the other end of these links cannot be guaranteed to exist forever (what happens when that content is relocated or removed?), and should be avoided.


Q:

How do I find the lowest common multiple of two numbers?

I know this is a classic interview question, but here is my quick attempt at creating a function which returns the lowest common multiple of two numbers, something I never have to do in my day job:
def calc_common_multiplyer(int_low, int_high)
  i = 1
  int_high_res = []

  while true
    int_high_res << int_high * i
    if int_high_res.include?(int_low * i)
      return int_low * i
    end
    i = i+1
  end
end

I feel that this is very clunky. Is there a more efficient or standard solution?

A:

I'd do this in Ruby:
x.lcm(y)

:)

A:

First calculate the greatest common divisor (for example with the Euclidean algorithm), then
lcm(a,b) = if a == 0 && b == 0 then return 0 else return (a*b)/gcd(a,b)