text:
Q: How do I transfer json objects into an excel file using python? How do I transfer json objects into an excel file using python?
I am currently working on a project to make a database of professors.
I was able to loop through each link in a for loop and get such data:
{"total": 1, "offset": 0, "data": [{"authorId": "118985833", "name": "Krystle K. Madrid"}]}

{"total": 1, "offset": 0, "data": [{"authorId": "107707217", "name": "S. N. Kirnon"}]}

{"total": 5, "offset": 0, "data": [{"authorId": "121754802", "name": "Jason L. Jarvis"}, {"authorId": "143879405", "name": "J. Jarvis"}, {"authorId": "145088127", "name": "J. Jarvis"}, {"authorId": "31259897", "name": "J. W. Jarvis"}, {"authorId": "38535862", "name": "J. D. Jarvis"}]}

I am trying to find a way to make a excel file with columns AuthorID and Name.
Please let me know if anyone can help me how I can do this using Python.

A: With Pandas:
import pandas as pd

df = pd.DataFrame(
  [
    data
    for link in links
    for data in link["data"]
  ]
)
df.rename(columns={"authorId": "AuthorId", "name": "Name"}).to_csv("data.csv")

A: For example, you could do something like the following:
dics = [
    {"total": 1, "offset": 0, "data": [{"authorId": "118985833", "name": "Krystle K. Madrid"}]},
{"total": 1, "offset": 0, "data": [{"authorId": "107707217", "name": "S. N. Kirnon"}]},
{"total": 5, "offset": 0, "data": [{"authorId": "121754802", "name": "Jason L. Jarvis"}, {"authorId": "143879405", "name": "J. Jarvis"}, {"authorId": "145088127", "name": "J. Jarvis"}, {"authorId": "31259897", "name": "J. W. Jarvis"}, {"authorId": "38535862", "name": "J. D. Jarvis"}]}
]

df = pd.DataFrame(columns = ['AuthorID','Name'])

for d1 in dics:
    for d2 in d1["data"]:
        df = pd.concat([df,
                        pd.DataFrame({"AuthorID":[d2["authorId"]],
                                      "Name":[d2["name"]]})],
                        ignore_index=True)

The result:
    AuthorID               Name
0  118985833  Krystle K. Madrid
1  107707217       S. N. Kirnon
2  121754802    Jason L. Jarvis
3  143879405          J. Jarvis
4  145088127          J. Jarvis
5   31259897       J. W. Jarvis
6   38535862       J. D. Jarvis

A similar loop with the same result:
for d1 in dics:
    d_new = {"AuthorID":[d2["authorId"] for d2 in d1["data"]],
            "Name":[d2["name"] for d2 in d1["data"]]}
    df = pd.concat([df,pd.DataFrame(d_new)],ignore_index=True)

Here's a one line solution:
df = pd.DataFrame({"AuthorID":[d2["authorId"] for d1 in dics for d2 in d1["data"]],
            "Name":[d2["name"] for d1 in dics for d2 in d1["data"]]})


text:
Q: Why won't my iOS beta app connect to network / internet? I'm facing a weird problem.
While I was testing my app on xCode, everything was working like a charm, even internet accessing.
I uploaded my build to Testflight and my testers won't be able to connect.
Even more surprising : I realize that the one I'm using on my phone is the xCode build, not installed via testflight, and still wont be able to access the internet while it was perfectly able to do so while connected to xCode...
EDIT : tested my web service which works as well
Did any one of you already face this problem ? How should I solve this ?
Thanks very much in advance
Vincent

A: Ok,
I Had a deeper look into it after @Ladislav and @Losiowaty suggestions.
The problem was actually elsewere. The app behavior was like if there was a network problem. I didn't remember about it but I changed one line in the returned jSon use, which caused a non fatal error and the results not showing, which couldn't be seen without reading logs.
Thank you all for your time anyway !

redpajama_set_name: RedPajamaStackExchange


text:
Q: ConstraintLayout, adding constraints moves all my elements I am trying to design a custom field for a recyclerview, but I encountered problems regarding the ConstraintLayout. Using the design, I moved all my design elements where I wanted, but as soon as I add any kind of constraint (using Infer Contstraints or writing directly in the XML file, all of the elements move in completely different positions which are in no way how I positioned them. Here is my XML code:
<android.support.constraint.ConstraintLayout 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:id="@+id/relativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_row_selector"
android:padding="8dp"
tools:layout_editor_absoluteY="81dp">

<!-- Thumbnail Image -->
<ImageView
    android:id="@+id/thumbnail"
    android:layout_width="87dp"
    android:layout_height="89dp"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="8dp" />

<!-- Movie Title -->
<TextView
    android:id="@+id/title"
    android:layout_width="216dp"
    android:layout_height="wrap_content"
    android:textSize="@dimen/title"
    android:textStyle="bold"
    tools:layout_editor_absoluteX="90dp"
    tools:layout_editor_absoluteY="8dp" />

<!-- Rating -->
<TextView
    android:id="@+id/rating"
    android:layout_width="72dp"
    android:layout_height="21dp"
    android:textSize="@dimen/rating"
    tools:layout_editor_absoluteX="90dp"
    tools:layout_editor_absoluteY="85dp" />

<!-- Genre -->
<TextView
    android:id="@+id/genre"
    android:layout_width="334dp"
    android:layout_height="28dp"
    android:textColor="@color/genre"
    android:textSize="@dimen/genre"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="114dp" />

<!-- Release Year -->
<TextView
    android:id="@+id/releaseYear"
    android:layout_width="129dp"
    android:layout_height="21dp"
    android:textColor="@color/year"
    android:textSize="@dimen/year"
    tools:layout_editor_absoluteX="172dp"
    tools:layout_editor_absoluteY="85dp" />

<ImageView
    android:id="@+id/btnBookOption"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:src="@drawable/book_add_touch"
    android:textColor="@color/white"
    tools:ignore="RtlHardcoded"
    tools:layout_editor_absoluteX="304dp"
    tools:layout_editor_absoluteY="39dp" />

<TextView
    android:id="@+id/author"
    android:layout_width="195dp"
    android:layout_height="38dp"
    tools:layout_editor_absoluteX="90dp"
    tools:layout_editor_absoluteY="39dp" />

</android.support.constraint.ConstraintLayout>

Here is how I am trying to make my list look:

And here is how it looks after I add constraints

How can I add the constraints, but make the layout look like in the first pic at the same time? Thank you.

A: You have to create the constraints properly. You can check the documentation for more details.
Be aware that the tools annotated parameters are only for development preview. When you run your app the compiler removes those parameters.
<android.support.constraint.ConstraintLayout 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:id="@+id/relativeLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="8dp"
    tools:layout_editor_absoluteY="81dp">

    <!-- Thumbnail Image -->
    <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="87dp"
        android:layout_height="89dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="8dp" />

    <!-- Movie Title -->
    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/thumbnail"
        app:layout_constraintTop_toTopOf="@id/thumbnail"
        tools:layout_editor_absoluteX="90dp"
        tools:layout_editor_absoluteY="8dp" />

    <!-- Rating -->
    <TextView
        android:id="@+id/rating"
        android:layout_width="72dp"
        android:layout_height="21dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toEndOf="@id/thumbnail"
        app:layout_constraintTop_toBottomOf="@id/author"
        tools:layout_editor_absoluteX="90dp"
        tools:layout_editor_absoluteY="85dp" />

    <!-- Genre -->
    <TextView
        android:id="@+id/genre"
        android:layout_width="334dp"
        android:layout_height="28dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="114dp" />

    <!-- Release Year -->
    <TextView
        android:id="@+id/releaseYear"
        android:layout_width="129dp"
        android:layout_height="21dp"
        android:layout_marginStart="8dp"
        app:layout_constraintStart_toEndOf="@id/rating"
        tools:layout_editor_absoluteX="172dp"
        tools:layout_editor_absoluteY="85dp" />

    <ImageView
        android:id="@+id/btnBookOption"
        android:layout_width="24dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:focusable="false"
        app:layout_constraintBottom_toTopOf="@id/releaseYear"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/author"
        app:layout_constraintTop_toBottomOf="@id/title"
        tools:ignore="RtlHardcoded"
        tools:layout_editor_absoluteX="304dp"
        tools:layout_editor_absoluteY="39dp" />

    <TextView
        android:id="@+id/author"
        android:layout_width="0dp"
        android:layout_height="38dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toStartOf="@id/btnBookOption"
        app:layout_constraintStart_toEndOf="@id/thumbnail"
        app:layout_constraintTop_toBottomOf="@id/title"
        tools:layout_editor_absoluteX="90dp"
        tools:layout_editor_absoluteY="39dp" />

<android.support.constraint.ConstraintLayout>

A: Try this..
<android.support.constraint.ConstraintLayout 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:id="@+id/relativeLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:padding="8dp"
    tools:layout_editor_absoluteY="81dp">

    <!-- Thumbnail Image -->
    <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="87dp"
        android:layout_height="89dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:background="@tools:sample/backgrounds/scenic" />

    <!-- Movie Title -->
    <TextView
        android:id="@+id/title"
        android:layout_width="216dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@id/thumbnail"
        tools:text="@tools:sample/first_names" />

    <!-- Rating -->
    <TextView
        android:id="@+id/rating"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:textSize="@dimen/rating"
        app:layout_constraintEnd_toStartOf="@+id/releaseYear"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintHorizontal_weight="3"
        app:layout_constraintStart_toEndOf="@+id/thumbnail"
        app:layout_constraintTop_toBottomOf="@id/btnBookOption"
        tools:text="@tools:sample/us_zipcodes" />

    <!-- Genre -->
    <TextView
        android:id="@+id/genre"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="20dp"
        android:layout_marginTop="12dp"
        android:textColor="@color/genre"
        android:textSize="@dimen/genre"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/rating"
        tools:text="@tools:sample/cities" />

    <!-- Release Year -->
    <TextView
        android:id="@+id/releaseYear"
        android:layout_width="129dp"
        android:layout_height="21dp"
        android:textColor="@color/year"
        android:textSize="@dimen/year"
        app:layout_constraintEnd_toStartOf="@id/btnBookOption"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_weight="5"
        app:layout_constraintStart_toEndOf="@+id/rating"
        app:layout_constraintTop_toBottomOf="@id/btnBookOption"
        tools:text="@tools:sample/date/ddmmyy" />

    <TextView
        android:id="@+id/author"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        app:layout_constraintTop_toTopOf="@id/btnBookOption"
        app:layout_constraintBottom_toBottomOf="@id/btnBookOption"
        app:layout_constraintEnd_toStartOf="@+id/btnBookOption"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintStart_toEndOf="@+id/thumbnail"
        tools:text="@tools:sample/full_names" />

    <ImageView
        android:id="@+id/btnBookOption"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/author"
        app:layout_constraintTop_toBottomOf="@id/title"
        tools:ignore="RtlHardcoded"
        tools:src="@android:drawable/alert_dark_frame" />

</android.support.constraint.ConstraintLayout>


text:
Q: Return all roles, including custom roles Rewritten: Hopefully this helps others. The question wasn't a duplicate question. The custom roles and subscriber account were not being written. It turns out that the if statement after the internal foreach was stopping the writing of the custom roles. Once removed then the loop worked properly.
It's very important for novices to be provided explanations. In this case, I would like to know why the if statement blocked the writing of the custom roles.
if ( $wp_roles->get_role( $role_name )->has_cap( $new_cap ) )

Original statements (bold unique parts to question):
This is frustrating me. After months of trying different ways to think about retrieving all of the default and custom roles, I believed the following code would work. However, it is only returning 4 of the 5 default roles and none of the custom roles. This code works to return administrator, editor, author, and contributor but not subscriber.
I can write an elseif statement after the inner foreach loop and force subscriber to be written as well as an elseif statement to force a known custom role .. but that defeats the purpose of a foreach to return all roles.
Sorry but I'm a complete novice trying to read and understand as much as possible. This means I'm not asking you to write the code but maybe point me in the direction as well as provide an explanation.
        global $current_user, $wp_roles;

    $all_roles = $wp_roles->roles;

    $editable_roles = apply_filters( 'editable_roles', $all_roles );

    foreach ( $editable_roles as $role_name => $role_info ) {

        /** If you have changed the wp_ prefix then you must modify this line to match the new prefix */
        if ( is_object( $current_user ) && isset( $current_user->data->wp_capabilities[ $role_name ] ) ) {

            foreach ( $new_caps as $new_cap ) {
                if ( $wp_roles->get_role( $role_name )->has_cap( $new_cap ) ) {
                    $capabilities[ $new_cap ] = true;
                    $current_user->add_role( $role_name );

                }
            }

        }

    }


text:
Q: Why does the DOM remove my classes automatically when the page is changed? I have a custom written accordion for my "sidenav", it's very simple, Just adding class on click event to trigger and menu items collapse but the problem is when I click on a link in the collapsed
 the page starts to redirect; all the classes which I added with javascript click handler are automatically removed and it looks very ugly:

... and how can I fix it?
It's my javascript(jquery) and html code:
$('.mine-trigger').click(function(){

        var
        control_click       = $(this).hasClass('mine-trigger-open'),
        howmuchchildrens    = $(this).children('.mine-content').children('.mine-content__link').length,
        calcPixels          = (howmuchchildrens * 48) + 'px';

        if (control_click == false){
            $(this).addClass('mine-trigger-open');
            $(this).children('.mine-content').css('max-height', calcPixels);
        }
        if (control_click == true) {
            $(this).removeClass('mine-trigger-open');
            $(this).children('.mine-content').css('max-height', 0);
        }
    });

                Cariler

                <a class="sidenav__link mine-content__link" href='<?php echo site_url('yonetim/cari')?>'>

                    Cari

                <a class="sidenav__link mine-content__link" href='<?php echo site_url('yonetim/personel')?>'>

                    Personel

A: The event is triggered from the LI so "this" will always be .mine-trigger and clicking on any child elements will toggle the close.  inspect the event.target to determine if the click was within a navigation link to determine if you should close the accordion.
$('.mine-trigger').click(function(e){
    var is_open = $(this).hasClass('mine-trigger-open');
    var from_link = is_open && $(e.target).closest('.mine-content__link').length == 1;

    if (!is_open) {
        // open accordion
    } else if (is_open && !from_link) {
        // close accordion
    }

You could also get/set a cookie value or localStorage to re-open the accordion on the page you are navigating to.

A: Simply put, the page doesn't automatically remove the classes you've applied.
Clearly, you deliberately apply them when a closed element is clicked, before removing them and setting the max-height of the children to 0.
You're setting the max-height attribute for the children, yet they appear slowly. That appears to indicate there's a transition being used when the "mine-trigger-open" class is applied. The max-height is set instantly, but the actual height changes over a period of time.
When you go the other way though, you instantly set the max-height attribute to 0. Even if there's a transition happening on the height attribute, you wont see the elements, since they've been hidden. Instead of applying the max-height attribute at this point, I'd suggest that it appear in the rule that governs the transition when "mine-trigger-open" is added or removed.


text:
Q: Get specific metadata only from List of Blobs in Azure Storage [Azure-Blob][REST] I am successfully able to get a List of Blobs in a Container through REST calls in Azure Blob through this code.
const request = require("request");
require("dotenv").config();

const account = process.env.ACCOUNT_NAME || "";
const key = process.env.ACCOUNT_KEY || "";
var strTime = new Date().toUTCString();
const containerName = "demo";

const BearerToken = <BearerToken>;

const options = {
  url: `https://${account}.blob.core.windows.net/${containerName}?comp=list&restype=container`,

  headers: {
    Authorization: `Bearer ${BearerToken}`,
    "x-ms-date": strTime, //var strTime = new Date().toUTCString();
    "x-ms-version": "2019-02-02", // Stable xms vesrion
  },
};

function callback(error, response, body) {
  console.log(response.body);
}

request(options, callback);

The output of the code:
 <?xml version="1.0" encoding="utf-8"?>
<EnumerationResults ServiceEndpoint="https://<storageaccount>.blob.core.windows.net/" ContainerName="demo">
    <Blobs>
        <Blob>
            <Name>
                Mayank Photo.jpg
            </Name>
            <Properties>
                <Creation-Time>
                    Fri, 12 Mar 2021 09:09:32 GMT
                </Creation-Time>
                <Last-Modified>
                    Fri, 12 Mar 2021 09:09:32 GMT
                </Last-Modified>
                <Etag>
                    0x8D8E5368CBE80AB
                </Etag>
                <Content-Length>
                    16685
                </Content-Length>
                <Content-Type>
                    image/jpeg
                </Content-Type>
                <Content-Encoding />
                <Content-Language />
                <Content-CRC64 />
                <Content-MD5>
                    AIoyEnG9amzFlWZ7t1YlCw==
                </Content-MD5>
                <Cache-Control />
                <Content-Disposition />
                <BlobType>
                    BlockBlob
                </BlobType>
                <AccessTier>
                    Hot
                </AccessTier>
                <AccessTierInferred>
                    true
                </AccessTierInferred>
                <LeaseStatus>
                    unlocked
                </LeaseStatus>
                <LeaseState>
                    available
                </LeaseState>
                <ServerEncrypted>
                    true
                </ServerEncrypted>
            </Properties>
        </Blob>
        <Blob>
            <Name>
                MayankPhoto.jpg
            </Name>
            <Properties>
                <Creation-Time>
                    Fri, 12 Mar 2021 09:10:28 GMT
                </Creation-Time>
                <Last-Modified>
                    Fri, 12 Mar 2021 09:10:28 GMT
                </Last-Modified>
                <Etag>
                    0x8D8E536AE20F3A1
                </Etag>
                <Content-Length>
                    16685
                </Content-Length>
                <Content-Type>
                    image/jpeg
                </Content-Type>
                <Content-Encoding />
                <Content-Language />
                <Content-CRC64 />
                <Content-MD5>
                    AIoyEnG9amzFlWZ7t1YlCw==
                </Content-MD5>
                <Cache-Control />
                <Content-Disposition />
                <BlobType>
                    BlockBlob
                </BlobType>
                <AccessTier>
                    Hot
                </AccessTier>
                <AccessTierInferred>
                    true
                </AccessTierInferred>
                <LeaseStatus>
                    unlocked
                </LeaseStatus>
                <LeaseState>
                    available
                </LeaseState>
                <ServerEncrypted>
                    true
                </ServerEncrypted>
            </Properties>
        </Blob>
    </Blobs>
    <NextMarker />
</EnumerationResults>

As you can see there are many other fields/metadata returned apart from the blob name is there a way to get only some specific metadata field in output eg: filename, DateCreated, ContentLength.
Because sometimes I may encounter a long list of files in that case I need a short and fast response.
I think it might have something to with the metadata URL parameter in the include specified here but I don't know how to modify my URL accordingly.

A: It is mentioned in the documentation, you just need to have it as
https://myaccount.blob.core.windows.net/mycontainer?restype=container&comp=list&include=snapshots&include=metadata

A: The properties you listed are the system properties of a blob and they will be returned by default. There's no way to filter those properties and ask Blob Storage Service to return a few of those properties.
A blob can have additional properties which are not returned by default. One of them is user-defined metadata. To get user-defined metadata, you would need to add include=metadata in your request. Other such property is copy properties (i.e. information if a blob is created as a result of a copy operation). To see the copy information, you would need to add include=copy in your request.


text:
Q: How can I downgrade from ruby 1.9.1 to ruby 1.8.7 I just upgraded to rails 3 but was running ruby 1.9.1 prior to the upgrade. Rails 3 doesn't support Ruby 1.9.1. How can I downgrade to ruby 1.8.7?

A: install rvm, this will allow you to run multiple versions of ruby and switch between them at will:  rvm

A: This will downgrade from your current version to 1.8.7:
gem update --system 1.8.7

A: As others have mentioned, its hard to come up with exact solution, in general to downgrade or switch versions for a user:

*

*Install Ruby 1.8.7 (or locate it on your system if you have it already)

*Edit your .bash_profile or .bashrc file to update your $PATH so that the 1.8.7 executable is found first. Something like this:
export RUBY_187_HOME='/path/to/1.8.7'
export PATH=$RUBY_187_HOME/bin:$PATH

*This is a little similar to what RVM does and it works.

*To test, try
$ which ruby
$ /path/to/1.8.7/bin/ruby


text:
Q: Calculate sliding durations in scala I have a list of Tuples and a datum like below
val datum =("R",89)
val dataList = Seq(("R",91),("R",95),("X",96),("S",98))

I want to calculate the duration between elements in the list , starting with the datum so the result would be
res0:> Seq(("R",7) , ("X",2))  //R - 96-89 , X - 98-96

Things I have tried are not functional
a) I used a sliding on the list and used a pattern match with an accumulator to hold the values. This used a Boolean and a listBuffer to keep adding values into the list
b) Used a map function with an accumulator tuple with a pattern match for the tuple , compare the _1 values and when the values change compare reset the accumulator and collect the result of the subtraction
I was imagining if foldLeft or fold functions could be used to make it more "functional". In this case we would have .foldLeft(List()) as the initial value and then write a map function that takes in 2 tuples and compare manually possibly with a flag as well.
Any pointers as to how this can be made "functional"
b) Used a map function that

A: Here's what you can do
first create a function that takes datum, dataList and empty list (which will be the final list). And you iterate through the function using your logic.
def func(x : Tuple2[String, Int], y : Seq[Tuple2[String, Int]], z: List[Tuple2[String, Int]]) : List[Tuple2[String, Int]] = y match {
  case (a::b) => if(x._1 == a._1) func(x, b, z) else func(a, b, z :+ (x._1, a._2-x._2))
  case Nil => z
}

Thats all now just call the function
val finalTuples = func(datum, dataList, List.empty[Tuple2[String, Int]])

finalTuples is finalTuples: List[(String, Int)] = List((R,7), (X,2))


text:
Q: Very Slow Download speed in terminal The download speed in Terminal is very slow. about 40kBytes. But the speed in the browser works fine
I have chosen the best server but I still get the problem
by the way loot at the output of tracepath 1.1.1.1 output if it helps:

A: If you are getting fast speed in the browser and only slow speed for installing packages, the network mirror might be having a problem.
You can use netselect package, as it guarantees the fastest mirror selection.
The netselect package is not available within Ubuntu's standard repository by default, so we will need to download it from Debian stable repository. So, run these commands
wget http://ftp.ru.debian.org/debian/pool/main/n/netselect/netselect_0.3.ds1-26_amd64.deb
sudo dpkg -i netselect_0.3.ds1-26_amd64.deb

Once you have the netselect command available on your Ubuntu system use it to locate the fastest mirror based on the lowest ICMP latency. The netselect output will be relative to your location. The output will show the top 20 apt Ubuntu mirrors ( if available ):
sudo netselect -s 20 -t 40 $(wget -qO - mirrors.ubuntu.com/mirrors.txt)

Manually alter your /etc/apt/sources.list file to reflect the above netselect results
sudo nano /etc/apt/sources.list

or use sed command, where the lower score number on the left represents a higher mirror transfer rate. Example:
sudo sed -i 's/http:\/\/us.archive.ubuntu.com\/ubuntu\//http:\/\/ubuntu.uberglobalmirror


text:
Q: Creating article pagination Hi I'm using silverstripe 2.4.7 and I'm having difficulty getting the pagination to work. I've created a function in my page.php to get the latest articles like so
function AllNewsPosts($num=1) {
$news = DataObject::get_one("NewsHolder");
return ($news) ? DataObject::get("NewsEntry", "ParentID > 0", "Date DESC", "", $num) : false;
}

Then when i put this function into the control and pagination tags one article shows up however the links to the concurrent articles do not work - essentially the pagination is not working and I'm not sure how to fix it
<% if AllNewsPosts %>
        <% control AllNewsPosts %>

$MenuTitle | $Date.Time $Date.Long

$Content.FirstParagraph

            See more about this event

        <% end_control %>
        <% else %>

'There are no entries'

        <% end_if %>

        <% if AllNewsPosts.MoreThanOnePage %>

      <% if AllNewsPosts.NotFirstPage %>
        Prev
      <% end_if %>

          <% control AllNewsPosts.PaginationSummary(0) %>
          <% if CurrentBool %>
            $PageNum
          <% else %>
            <% if Link %>
              $PageNum
            <% else %>
              …
            <% end_if %>
          <% end_if %>
        <% end_control %>

      <% if AllNewsPosts.NotLastPage %>
        Next
      <% end_if %>

<% end_if %>

Any help is much appreciated

A: Note: The following answer is for Silverstripe 2.4. This should not be used for Silverstripe 3.0+ sites. From 3.0 and onwards the PaginatedList object makes pagination much easier.
You are not setting a limit on how many entries to retrieve in your query, or where to start from.
The following tutorial explains how to apply pagination to a set of data objects exactly as you are trying to do:
http://www.ssbits.com/tutorials/2010/paginating-a-filtered-dataobjectset/
Here is an attempt at altering your function to include limit and start as needed for pagination:
PHP
function AllNewsPosts() {
    if(!isset($_GET['start']) || !is_numeric($_GET['start']) || (int)$_GET['start'] < 1)
    {
        $_GET['start'] = 0;
    }

    $SQL_start = (int)$_GET['start'];

    $newsEntries = DataObject::get('NewsEntry', '', 'Date DESC');
    $doSet = new DataObjectSet();
    foreach ($newsEntries as $newsEntry) {
        if ($newsEntry->canView()) {
            $doSet->push($newsEntry);
        }
    }
    $doSet->setPageLimits($SQL_start, 10, $doSet->Count());
    return $doSet;
}

Note the above will display 10 items per page. You can change this to however you need per page.


text:
Q: mysqldump not escaping single quotes properly I use mysqldump to backup my mysql database.
The problem is that the sql file generated by mysqldump doesn't escapes single quotes properly.
Here is an example of the mysqldump generated sql script :
INSERT INTO `someTable` VALUES (1,'This ain\'t escaped correctly');

That single quote escaping in "ain't" doesn't work and it makes the rest of the script being inside that string.
Is there a way around this?

A: That output of mysqldump is working as designed, and it is properly escaped, unless you try to restore the dump on a MySQL instance with SQL_MODE=NO_BACKSLASH_ESCAPES set.
There's an outstanding feature request to make mysqldump use a pair of single-quotes to escape literal single-quotes, as per ANSI SQL.  See http://bugs.mysql.com/bug.php?id=65941
In the meantime you might be able to convert from backslash-singlequote to pair-of-singlequotes with a command line this:
mysqldump test | sed -e "s/\\\'/''/g" > test-dump.sql

I tried that out briefly by creating a dummy table in my test database and inserting the string "O'Hare" into the table.  But that's hardly a comprehensive test -- I take no responsibility for this suggestion working in all cases.

A: Bill Karwin's answer is really good, and even I was using a similar solution, until yesterday when I got a message field which has a "\" character, which was escaped with "\" and as it was the last character of the field, the next character was a single-quote, marking the end of the string field content. Now, here's the string a the solution below, I used Perl regex "look-behind":
INSERT INTO "My_table" VALUES ('Table_1','316947','pradeep@yahoo.com','Richard','asha@pradeep.net.in','Skip\\','HAPPY VISHU
\r\n\r\n\r\n')

Solution: with 2 examples:
[pradeep@ubuntu ~]# cat /tmp/a.txt
INSERT INTO "My_table" VALUES ('Table_1','316947','pradeep@yahoo.com','Richard','asha@pradeep.net.in','Skip\\','HAPPY VISHU
\r\n\r\n\r\n')
INSERT INTO "My_table" VALUES ('Table_1','316947','pradeep@yahoo.com','Richard','asha@pradeep.net.in','Pradeep\'s Skip\\','HAPPY VISHU
\r\n\r\n\r\n')
[pradeep@ubuntu ~]# cat /tmp/a.txt | perl -pe 's/(?<!\x5c)\x5c\x27/\x27\x27/g;' | perl -pe 's/(\x5c\x5c)+\x5c\x27/$1\x27\x27/g;'
INSERT INTO "My_table" VALUES ('Table_1','316947','pradeep@yahoo.com','Richard','asha@pradeep.net.in','Skip\\','HAPPY VISHU
\r\n\r\n\r\n')
INSERT INTO "My_table" VALUES ('Table_1','316947','pradeep@yahoo.com','Richard','asha@pradeep.net.in','Pradeep''s Skip\\','HAPPY VISHU
\r\n\r\n\r\n')


text:
Q: evaluate function limit by change of variable I'm struggling with this limit, tried everything on it but can't treat this indeterminate form...
$$ \lim_{x\rightarrow  0} \frac{\sin\frac{1}{x}}{e^{\frac{1}{x}} + 1}$$
Ideally, I want to evaluate it using a change of variables, but every other method would be most welcome.
I thank you guys for your explanation and your help.

A: Let $y=\frac1x$. The limit becomes $$\lim\limits_{y\to\pm\infty}\frac{\sin y}{e^y+1}$$Note that when $y\to-\infty$, $e^y+1\to1$, so the limit becomes $\lim\limits_{y\to-\infty}\sin y$ which does not exist, so the overall limit does not exist.
If you solely care about the limit as $x\to0^+$, then we consider $y\to\infty$ in our transformed limit, as below$$\lim\limits_{y\to\infty}\frac{\sin y}{e^y+1}$$ As $e^y+1\to\infty$, while $|\sin y|\leq1$, this limit equals $0$.

A: The right limit exists and it is $0$ because the numerator is bounded and the denominator goes to $\infty$
The left limit does not exist because the denominator approaches $1$ while the  numerator does not have a limit as it jumps up and down between $1$ and $-1$
Thus the limit does not exist.

A: Use that $$\left|\frac{\sin(u)}{e^u+1}\right|\le \left|\frac{1}{e^u+1}\right|$$


text:
Q: Magento: Multiple rows for a single custom attribute of a catalog product? Here's what I'm trying to do...
A given item in our store might be in multiple numerical "Product Groups". We also need to use those product groups to qualify/disqualify those items for coupons and sales rules.
If I define "Product Group" as custom attribute through EAV, the best I can do is set the Backend Model to "array", and have the multiple product groups saved as comma-delimited text in a varchar field. This is obviously less than ideal (and doesn't even convert back to an array on load).
Is there any way to have true one-to-many database rows for a product's custom attributes?

A: Is there a reason you can't just create a secondary category structure and just set the categories to be not shown in the navigation? Another option would be to use a new attribute set for each product group. It sounds like you're over complicating it with an attribute arrays, Both of these solutions will allow you to use coupons and sales rules.


text:
Q: Measuring end-to-end latency with the Paho sample pub/sub app My aim is to measure MQTT device-to-device message latency (not throughput) and I'm looking for feedback on my code-hacks.  The setup is simple; just one device serving as two end-points (old Linux PC with two terminal sessions; one running the subscriber and the other running the publisher sample app) and the default broker at tcp://m2m.eclipse.org:1883). I inserted time-capturing code-fragments into the C-language publish/subscribe sample apps on the src/samples folder.
Below are the changes. Please provide feedback.
Changes to the subscribe sample app (MQTTAsync_subscribe.c)
Inserted the lines below at the top of the msgarrvd (message arrived) function
//print arrival time
struct timeval tv;
gettimeofday (&tv, NULL);
printf("Message arrived: %ld.%06ld\n", tv.tv_sec, tv.tv_usec);

Changes to the publish sample app (MQTTAsync_publish.c)
Inserted the lines below at the top of the onSend (callback) function
struct timeval tv;
gettimeofday (&tv, NULL);
printf("Message with token value %d delivery confirmed at %ld.%06ld\n",
               response->token, tv.tv_sec, tv.tv_usec);

With these changes (after subtracting the time message arrived at the subscriber from the time that the delivery was confirmed at the publisher), I get a time anywhere between 1 millisecond and 0.5 millisecond.
Questions
Does this make sense as a rough benchmark on latency?
Is this the round-trip time?
Is the round-trip time in the right ball-park? Should be less? more?
Is it the one-way time?
Should I design the latency benchmark in a different way? I need a rough measurements (I'm comparing with XMPP).
I'm using the default QoS value (1). Should I change it?
The publisher takes a finite amount of time to connect (and disconnect). Should these be added?

A: The 200ms latency is high ! Can you please upload your code here ?
Does this make sense as a rough benchmark on latency?
-- Yes it makes sense. But a better approach is to make an automated time subtract with subscribed message and both synchronized to NTP.
Is this the round-trip time? Is it the one-way time?
-- Messages got published - you received ACK for publisher and same message got transferred to subscribed client.
Is the round-trip time in the right ball-park? Should be less? more?
-- It should be less.
Should I design the latency benchmark in a different way? I need a rough measurements (I'm comparing with XMPP).
I'm using the default QoS value (1). Should I change it?
-- Try with QoS 0 ( fire and forget )
The publisher takes a finite amount of time to connect (and disconnect). Should these be added?
-- Yes. It needs to be added but this time should be very small.


text:
Q: How to escape & in a POST request in jQuery? i have an input element with & in value:
<input type="checkbox" value="Biografie, životopisy, osudy, Domácí rock&pop" />

When i try sending it through an ajax request:
$.ajax({
    type: "POST",
    url: "/admin/kategorie/add/link.json",
    data: "id="+id+"&value="+value+"&type="+type,
    error: function(){alert('Chyba! Reloadněte prosím stránku.');}
});

the post data that actually gets sent is:
id: 1
pop:
type: e
value: Biografie, životopisy, osudy, Domácí rock

*Note that all the variables in data are defined and value contains $(thatInputElement).attr('value').
How can I escape the & properly so that post field value would contain Biografie, životopisy, osudy, Domácí rock&pop?

A: You can set your data option as an object and let jQuery do the encoding, like this:
$.ajax({
  type: "POST",
  url: "/admin/kategorie/add/link.json",
  data: { id: id, value: value, type: type },
  error: function(){ alert('Chyba! Reloadněte prosím stránku.'); }
});

You can encode each value using encodeURIComponent(), like this:
encodeURIComponent(value)

But the first option much simpler/shorter in most cases :)

A: Have you tried this syntax?
 data: {"id":id, "value": value, "type": type }

A: The javascript function "escape()" should work and on the server the method HttpUtility.UrlDecode should unescape. There may be some exceptions. Additionally if you need to decode on the client, there is an equivalent "unescape()" on the client.

A: Use the HTML character code for & instead: \u0026

A: You could create an object and pass that along instead:
vars = new Object();
vars.id = id;
vars.value = value;
vars.type = type;

$.ajax({
  type: "POST",
  url: "/admin/kategorie/add/link.json",
  data: vars,
  error: function(){ alert('Chyba! Reloadněte prosím stránku.'); }
});

A: you can replace & with {and} at client side, then replace {and} to & at server side


text:
Q: Mutating Function in Protocol Extension Where Self is UIViewController I've written a protocol and corresponding extension which utilizes a simple StringStack in tandem with a naming convention of the form "<origin>@<destination>" to perform segues between nested views in my Swift application. I'm new to swift so if there's a better way to implement what are essentially forward and back buttons across multiple views, I'm open to it. However the following code is problematic for reasons I detail below.
struct StringStack {
    var stack: Array = [String]()

    mutating func push(str: String)->Void {
        self.stack.append(str)
    }

    mutating func pop()->String {
        self.stack.popLast()
    }
}

protocol SegueForwardAndBackward {
    var thisIdentifier: String {get set}
    var segueStack: StringStack {get set}
}

extension SegueForwardAndBackward where Self: UIViewController {

    mutating func performForwardSegue(nextIdentifier: String) {
        let identifier: String = thisIdentifier + "@" + nextIdentifier
        segueStack.push(identifier)
        performSegueWithIdentifier(identifier, sender: self)
    }

    mutating func performBackwardSegue() {
        let divided = segueStack.pop().componentsSeparatedByString("@")
        // reverses destination and origin of identifier
        let segueIdentifier: String = divided[1] + "@" + divided[0]
        performSegueWithIdentifier(segueIdentifier, sender: self)
    }

    func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if var destinationViewController: SegueForwardAndBackward = segue.destinationViewController as? SegueForwardAndBackward {
            destinationViewController.segueStack = segueStack
        }
    }
}

My initial problem is that mutating functions aren't allowed in protocol extension as detailed in this bug report. There is a proposed workaround given in that report however the following results in an error claiming that 'SegueForwardAndBackward' is not a subtype of 'UIViewController'.
class A: UIViewController, SegueForwardAndBackward {

    mutating func testFunc() {
        var p: SegueForwardAndBackward = self
        p.performBackwardSegue()
    }
}

I did come across a potential solution where I could make SegueForwardAndBackward a class protocol as detailed in another question. However, implementing a class protocol results in a segfault, which I presume is because I declare my extension to be where Self: UIViewController, and unfortunately I've no clue how to resolve this.
At the moment I'm quite frustrated with what appears to be yet another bug in Swift, so any help in reworking my approach, or deciphering these errors would be much appreciated.
Thanks in advance for your response!

A: This question seems to address an alternate solution for nested forward and back buttons, so without any other responses, this it what I'll be going with. However, the issue I posed still stands out as a pretty strange bug in swift.

A: On diving a bit deeper, I found that the mutating modifier on the functions on the protocol extensions are not needed in your case, if you add nonmutating on the segueStack. Because you're telling
struct StringStack {
    var stack: Array = [String]()

    mutating func push(str: String)->Void {
        self.stack.append(str)
    }

    mutating func pop()->String? {
        self.stack.popLast()
    }
}

protocol SegueForwardAndBackward {
    var thisIdentifier: String {get set}
    var segueStack: StringStack {get nonmutating set}
}

extension SegueForwardAndBackward where Self: UIViewController {

    func performForwardSegue(nextIdentifier: String) {
        let identifier: String = thisIdentifier + "@" + nextIdentifier
        segueStack.push(str: identifier)
        performSegue(withIdentifier: identifier, sender: self)
    }

    func performBackwardSegue() {
        guard let divided = segueStack.pop()?.components(separatedBy: "@") else { return }
        // reverses destination and origin of identifier
        let segueIdentifier: String = divided[1] + "@" + divided[0]
        performSegue(withIdentifier: segueIdentifier, sender: self)
    }

    func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if var destinationViewController: SegueForwardAndBackward = segue.destination as? SegueForwardAndBackward {
            destinationViewController.segueStack = segueStack
        }
    }
}

And your class would look like
class A: UIViewController, SegueForwardAndBackward {

    var thisIdentifier: String
    var segueStack: StringStack

    func testFunc() {
        self.performBackwardSegue
    }

    init(thisIdentifier: String, segueStack: StringStack) {
        super.init(nibName: "A", bundle: .main)

        self.thisIdentifier = thisIdentifier
        self.segueStack = segueStack
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

However this means that if you conform a struct to SegueForwardAndBackward, you'll need to implement a nonmutating set.
struct B: SegueForwardAndBackward {

    var thisIdentifier: String
    var segueStack: StringStack { //Toy example
        get {
            UserDefaults.standard.object(forKey: "someKey") as! StringStack
        }
        nonmutating set {
            UserDefaults.standard.set(newValue, forKey: "someKey")
        }
    }
}


text:
Q: Apache server dead I've been struggling around to get my website running with HTTP redirect https and ssl.
Apache 2.4.41
Ubuntu 20.04 LTS
Current data:
iptables -> https://www.toptal.com/developers/hastebin/acufujubuz.sql
It was a bit long so I decided to paste it in a url
UFW ->
Status: active

To                         Action      From
--                         ------      ----
Apache Full                ALLOW       Anywhere
OpenSSH                    ALLOW       Anywhere
Apache Full (v6)           ALLOW       Anywhere (v6)
OpenSSH (v6)               ALLOW       Anywhere (v6)

VS ->
<VirtualHost *:80>
  ServerName <mydomain>
  ServerAlias  www.<mydomain>

  Redirect permanent / https://<mydomain>/

RewriteEngine on
RewriteCond %{SERVER_NAME} =www.<mydomain> [OR]
RewriteCond %{SERVER_NAME} =<mydomain>
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

<VirtualHost *:443>
  ServerAdmin <mydomain>
  ServerName <mydomain>
  ServerAlias <mydomain>
  DocumentRoot /var/www/<mydomain>
  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined
  Protocols h2 http/1.1

<If "%{HTTP_HOST} == '<mydomain>'">
    Redirect permanent / https://<mydomain>/
  </If>

</VirtualHost>

Apache status ->
apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
     Active: inactive (dead) since Sun 2021-12-26 13:45:17 CET; 12min ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 12093 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
    Process: 12177 ExecStop=/usr/sbin/apachectl stop (code=exited, status=0/SUCCESS)
   Main PID: 12097 (code=exited, status=0/SUCCESS)

dec 26 13:45:14 <>.stratoserver.net systemd[1]: Starting The Apache HTTP Server...
dec 26 13:45:14 <>.stratoserver.net systemd[1]: Started The Apache HTTP Server.
dec 26 13:45:17 <>.stratoserver.net apachectl[12179]: httpd (pid 12097?) not running
dec 26 13:45:17 <>.stratoserver.net systemd[1]: apache2.service: Succeeded.

It did however work for one moment, it only showed the default page even though it is disabled. And now it just refuses to run. Some help would be great, any extra info needed let me know.
Error log ->
[Sun Dec 26 13:45:14.394312 2021] [core:warn] [pid 12097:tid 140257795902528] AH00098: pid file /var/run/apache2/apache2.pid overwritten -- Unclean shutdown of previous Apache run?
[Sun Dec 26 13:45:14.395297 2021] [mpm_event:notice] [pid 12097:tid 140257795902528] AH00489: Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f configured -- resuming normal operations
[Sun Dec 26 13:45:14.395309 2021] [core:notice] [pid 12097:tid 140257795902528] AH00094: Command line: '/usr/sbin/apache2'
[Sun Dec 26 13:45:14.397770 2021] [mpm_event:alert] [pid 12098:tid 140257795902528] (11)Resource temporarily unavailable: AH00480: apr_thread_create: unable to create worker thread
[Sun Dec 26 13:45:14.402620 2021] [mpm_event:alert] [pid 12099:tid 140257477809920] (11)Resource temporarily unavailable: AH03104: apr_thread_create: unable to create worker thread
[Sun Dec 26 13:45:16.396433 2021] [mpm_event:alert] [pid 12097:tid 140257795902528] AH02324: A resource shortage or other unrecoverable failure was encountered before any child process initialized successfully... httpd is exiting!

Ran configtest output -> Syntax OK
Could not find specifically httpd.conf, did however find a http2.conf consisting:

# mod_http2 doesn't work with mpm_prefork
<IfModule !mpm_prefork>
    Protocols h2 h2c http/1.1

    # # HTTP/2 push configuration
    #
    # H2Push          on
    #
    # # Default Priority Rule
    #
    # H2PushPriority * After 16
    #
    # # More complex ruleset:
    #
    # H2PushPriority  *                       after
    # H2PushPriority  text/css                before
    # H2PushPriority  image/jpeg              after   32
    # H2PushPriority  image/png               after   32
    # H2PushPriority  application/javascript  interleaved
    #
    # # Configure some stylesheet and script to be pushed by the webserver
    #
    # <FilesMatch "\.html$">
    #     Header add Link "</style.css>; rel=preload; as=style"
    #     Header add Link "</script.js>; rel=preload; as=script"
    # </FilesMatch>
    # Since mod_http2 doesn't support the mod_logio module (which provide the %O format),
    # you may want to change your LogFormat directive as follow:
    #
    # LogFormat "%v:%p %h %l %u %t \"%r\" %>s %B \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
    # LogFormat "%h %l %u %t \"%r\" %>s %B \"%{Referer}i\" \"%{User-Agent}i\"" combined
    # LogFormat "%h %l %u %t \"%r\" %>s %B" common
</IfModule>

And found this part in apache2.conf
# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

#<Directory /srv/>
#   Options Indexes FollowSymLinks
#   AllowOverride None
#   Require all granted
#</Directory>`

Also memory;
$ free  -m
              total        used        free      shared  buff/cache   available
Mem:           4096          95        3701           3         298        3997
Swap:             0           0           0

A: Editing the tasks done fix this whole for me.
systemctl set-property apache2.service TasksMax=infinity


text:
Q: How can I render text under a textbox? Make something like in html/css

A: You can do what you want by wrapping each input and label in div elements, and floating the divs.
Example Here
HTML:

        <input type="text" size="6" />

label1

        <input type="text" size="6" />

label2

        <input type="text" size="6" />

label3

CSS:
div.boxwrap div {
    float: left ;
}
div.boxwrap div h5 {
    text-align: center ;
}
div.clearfloat {
    clear: both ;
}

A: This is similar to @Gus' answer, but a little more semantic:
<form action="" method="post">
  <fieldset>
    <input type="text" name="day" id="day" />
    Day
  </fieldset>
  <fieldset>
    <input type="text" name="hour" id="hour" />
    Hour
  </fieldset>
  <fieldset>
  <input type="text" name="min" id="min" />
    Min
  </fieldset>
  <fieldset>
    <input type="text" name="sec" id="sec" />
    Sec
  </fieldset>
</form>

With the following CSS:
fieldset {
  display: inline-block;
  width: 10em;
  margin: 0 1em 0 0;
  border: 1px solid #ccc;
}

fieldset > input,
fieldset > label {
  display: block;
  width: 8em;
  text-align: center;
  margin: 0 auto;
}

Live demo posted at: jsbin.

Edited to make it a just a little prettier...

New CSS:
form {
  width: 49.5em;
  overflow: hidden;
  border: 1px solid #ccc;
}
fieldset {
  display: block;
  float: left;
  width: 10em;
  margin: 0 1em 0 0;
  border: 1px solid #ccc;
}
  fieldset:last-child {
  margin: 0;
}

fieldset > input,
fieldset > label {
  display: block;
  text-align: center;
  margin: 0 auto;
}
fieldset > input {
  width: 80%;
  font-size: 1.4em;
}

And revised demo (again) at jsbin

A: It's crude, but you could add an absolutely positioned div with that text in it and position it where it's needed. You'd probably also have to position the textboxes absolutely.
You might also be able to get away with a negative margin at the top (probably not in IE, though).

A: No hacking involved - should be all browsers friendly.

            <input type="text" name="day" id="day">

            day

            <input type="text" name="hour" id="hour">

            Min

            <input type="text" name="min" id="min">

            day

            <input type="text" name="sec" id="sec">

            Sec

A: Here's the most semantic approach (and it works all the way back to IE6, no worries):

        <title>Title</title>

        <form action="#">
            <fieldset>

                    <input type="text" name="day" id="day">
                    Day

                    <input type="text" name="hour" id="hour">
                    Hour

                    <input type="text" name="minute" id="minute">
                    Min

                    <input type="text" name="second" id="second">
                    Sec

            </fieldset>
        </form>


text:
Q: Looking for a formula to represent the sequence $2,4,2,8,2,4,2,16,2,4,2,8,\dots$ Is there a formula with which I can represent the sequence $2,4,2,8,2,4,2,16,2,4,2,8,\dots$?

A: Let $P_n$ denote the number of zeros at the end of the binary representation of $n$.
Note that $P_n$ also gives the number of times that $n$ is divisible by $2$.
Your sequence can be represented as: $$a_n=2^{P_n+1}$$

A: Go to oeis.org  (Online Encyclopedia of Integer Sequences)
Put 2,4,2,8,2,4,2,16,2,4,2,8 into the box
click the "Search" button
get two different named sequences that contain this:
A209675, the Radon function at even positions
A171977, a(n) = 2^(k+1) where 2^k is the highest power of 2 dividing n
An added bonus: this will often give you additional properties, references, and remarks about the sequence

A: Hint: Consider the prime factorizations of the even numbers.

A: you can also look it up here. You just need to enter enough terms of your sequence. If you don't find it, it may mean that it is a new sequence ( or that it shares few terms with some other sequence ).
https://oeis.org/
and here it is:
https://oeis.org/search?q=2%2C4%2C2%2C8%2C2%2C4%2C2%2C16%2C2%2C4%2C2%2C8%2C...&language=english&go=Search


text:
Q: How would you go about making growing lines in pygame This is my first real code project. I'm trying to make a crash gambling game I have done the surface and some other stuff, but the most difficult thing that I have found is making animated lines in pygame. I am trying to make a line arc that grows as I have the spacebar down. I have looked on youtube stack and overflow and done a couple of searches on Reddit. but I have not seen a way to do this. If you know how to do it and could tell me it would be great.
thanks,
Isaac
here's my code: I plan to add the function at the keydown
import math
import random

import pygame
from pygame import mixer

pygame.init()
clock = pygame.time.Clock()

screen = pygame.display.set_mode((800,800))
screen.fill((0,0,0))

grid = pygame.image.load('grid3.jpg')
playerImg = pygame.image.load('rocketship.gif')
playerX = 370
playerY = 480
playerX_change = 0

WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0, 255, 0)
BLUE=(0,0,255)
BLACK=(0,0,0)

PI= math.pi

print("Isaax")

running=True
while running:
screen = pygame.display.set_mode((800,800))
screen.fill((0,0,0))
screen.blit(grid, (0,0))
screen.blit(playerImg, (755,375))
pygame.display.flip()
pygame.draw.arc(grid,RED,[-750,-700,1550,1300],3*PI/2,   2*PI, 5)
for event in pygame.event.get():
  if event.type == pygame.KEYDOWN:
   if event.key == pygame.K_SPACE:
    print("Isaac not Isaax")

clock.tick(60)

  # RGB = Red, Green, Blue

    # Background Image

for event in pygame.event.get():
  if event.type == pygame.QUIT:
    running = False


text:
Q: Laravel best naming convention for controller method and route I'm creating an ajax request to get item details
Here's what my controller method looks like.
class SystemItemsController extends Controller
  {
      function getDetails(Request $request){
       $response =  SystemItems::where('item_name', 'like', '%' .$name . '%')->get();
       return response()->json($response,200);
  }

  }

and my
routing name
Route::get("/system-items/item-details","SystemItemsController@getStockDetails");
question : what would be the best naming convention for my route(item-details) and method(getStockDetails)?
follow up Q : can i do this using laravel resource?

A: You can use kebab-case and plural in the URI pattern, but camelCase and singular for Controller name, as that is what Laravel will look for if trying to do route–model binding.
You can use it for resouce routes, but note, for this route
Route::resource('item-details', 'ItemDetailController');

the route parameter will result in snake_case and singular
/item-details/{item_detail}

For the controller methods the conventional names are index, show, create, store, edit, update and delete. And snakeCase for custom methods.
Also you can add a route group to prefix with some uri like /system-items
Route::group(['prefix'  =>  'system-items'], function () {
    Route::resource('item-details', 'ItemDetailController');
});

run php artisan route:list to see the result
+--------+-----------+-----------------------------------------------------+-------------------------+---------------------------------------------------------------------------+--------------+
| Domain | Method    | URI                                                 | Name                    | Action                                                                    | Middleware   |
+--------+-----------+-----------------------------------------------------+-------------------------
|        | GET|HEAD  | api/v1/system-items/item-details                    | item-details.index      | App\Http\Controllers\Api\v1\ItemDetailController@index                         | api          |
|        | POST      | api/v1/system-items/item-details                    | item-details.store      | App\Http\Controllers\Api\v1\ItemDetailController@store                         | api          |
|        | GET|HEAD  | api/v1/system-items/item-details/create             | item-details.create     | App\Http\Controllers\Api\v1\ItemDetailController@create                        | api          |
|        | GET|HEAD  | api/v1/system-items/item-details/{item_detail}      | item-details.show       | App\Http\Controllers\Api\v1\ItemDetailController@show                          | api          |
|        | PUT|PATCH | api/v1/system-items/item-details/{item_detail}      | item-details.update     | App\Http\Controllers\Api\v1\ItemDetailController@update                        | api          |
|        | DELETE    | api/v1/system-items/item-details/{item_detail}      | item-details.destroy    | App\Http\Controllers\Api\v1\ItemDetailController@destroy                       | api          |
|        | GET|HEAD  | api/v1/system-items/item-details/{item_detail}/edit | item-details.edit       | App\Http\Controllers\Api\v1\ItemDetailController@edit

Of course, all of these are conventions and you can customize everything by doing it by hand and using your own conventions.


text:
Q: Running pyspark word count example I am just starting to learn Spark so please bear with me if this is too obvious.
I installed spark and I am able to run it in a terminal (by "./bin/pyspark").
But I fail to try the following example (word count):
path = os.path.join("sample-text.txt")
with open(path, "w") as testFile:
    _ = testFile.write("Hello world Hello")

file = sc.textFile(path)
counts = file.flatMap(lambda line: line.split(" ")) \
             .map(lambda word: (word, 1)) \
             .reduceByKey(lambda a, b: a + b)

path2 = os.path.join("word-count.txt")
counts.saveAsTextFile(path2)

Everything went through, but when I was trying to open the output word-count.txt file, it says that this document cannot be opened.
What am I doing wrong?

A:
I was trying to open the output word-count.txt file

It creates a directory named word-count.txt, not a file.
$ ls word-count.txt
_SUCCESS   part-00000 part-00001 part-00002
$ cat word-count.txt/part-00000
(u'world', 1)
$ cat word-count.txt/part-00001
(u'Hello', 1)
(u'hello', 1)

Your code works. You have other permission problems with your OS that are preventing you from creating / opening the directory.
Related (scala, but same idea) - how to make saveAsTextFile NOT split output into multiple file?


text:
Q: Won't display data in run, or won't display data in debug.  This is the edit to my question. There is quite a bit of code here, but the problem area is below the second set of three line comments. I stuck the rest in just in case I'm completely wrong about where the problem is. With the "if" statement I can display fine in a run, but not in debug. If I get rid of the conditional it runs fine in debug, but not in a regular run. These errors only occur on the first run of the quiz. In either mode it runs fine  fi I take a second quiz. Any help or suggestions are appreciated. Thanks...
    // ** this function is called from another component that passes in the array of qnums
    // ** and  then function clears data from previous quizzes. Component starts in the
    // ** "loadingState **//
        public function startQuiz(qNums:Array):void
        {
            quizNumbers = qNums;
            // ** deleted the reset functions for readability ** //
            showQuestion();
        }

    // ** calls the questions from sql  ** //
        protected function showQuestion():void{
            getQuestionByNumberResult.token = quizService.getQuestionByNumber(quizNumbers[i]);
        }

    // ** result handler from the sql call  and randomizes answers and feedbacks ** //
        protected function getQuestionByNumberResult_resultHandler(event:ResultEvent):void
        {
        // ** deleted the logic that builds the arrays and randomizes them ** //
            ranAnswerArray = Randomizer.qsAndFbcks(answersArray, tempArray);
            ranFeebbackArray = Randomizer.qsAndFbcks(feedbackArray, tempArray);

        // ** This seems to be where the problem is. With the "if" statement it runs fine in a ** //
        // ** regular run, but doesn't display the first question in debug mode. Without the "if" and I just ** //                  // ** call  the showTheQuestion() function it is the problem is reversed ; it runs fine in debug, ** //
        // ** but doesn't show the first question in a regular run. ** //

            if (currentState != "quizingState"){
            currentState="quizingState";
            addEventListener(StateChangeEvent.CURRENT_STATE_CHANGE, quizStateChange);}
            else{ showTheQuestion();}

            //showTheQuestion();
        }
        // ** function called from state change listener ** //
        protected function quizStateChange(event:StateChangeEvent):void
        {
            showTheQuestion();
        }
        // ** this function tells the visual components what to display ** //
        protected function showTheQuestion():void{
            // ** deleted logic that says how many radios and labels should be visible ** //
            questionText.text = data.question_txt;
            zanswer01.text = ranAnswerArray[0];
            zanswer02.text = ranAnswerArray[1];
            zanswer03.text = ranAnswerArray[2];
            zanswer04.text = ranAnswerArray[3];
        }
    ]]>
</fx:Script>

<s:states>
    <s:State name="quizingState"/>
    <s:State name="loadingState"/>
    <s:State name="finishedState"/>
</s:states>

// ** deleted the declarations block for readability. I left the display components just in case ** //
// ** something seemed wrong with them. ** //

    <s:Label id="questionText" includeIn="quizingState" x="42" y="54" width="699" height="138" color="#5BAAFB"
             fontFamily="Arial" fontSize="22" fontWeight="normal"
             text=""/>
    <s:Form includeIn="quizingState" x="48" y="167" height="219">
        <s:HGroup id="zhGroup01" verticalAlign="baseline">
            <s:RadioButton groupName="selectedAnswer" value="0"/>
            <s:Label id="zanswer01" text="" verticalAlign="middle"/>
        </s:HGroup>
        <s:HGroup id="zhGroup02" verticalAlign="baseline">
            <s:RadioButton groupName="selectedAnswer" value="1"/>
            <s:Label id="zanswer02" text=""/>
        </s:HGroup>
        <s:HGroup id="zhGroup03" verticalAlign="baseline">
            <s:RadioButton id="zradio3" groupName="selectedAnswer" value="2"/>
            <s:Label id="zanswer03" text=""/>
        </s:HGroup>
        <s:HGroup id="zhGroup04" verticalAlign="baseline">
            <s:RadioButton id="zradio4" groupName="selectedAnswer" value="3"/>
            <s:Label id="zanswer04" text=""/>
        </s:HGroup>
    </s:Form>

A: You shouldn't run showTheQuestion() right after a state change.  Your components in the state haven't had time to initialize just yet.  I would argue that you don't need that function since the state is the one that show "show the question".
If you really need it, you should add it to a creation complete event on one of the state components, or maybe the enterState event on the state itself.


text:
Q: why am I getting a PROTOCOL ERROR from OkHttp request? I've been searching for awhile on this topic. I'm trying to send data to my backend server using OkHttp. However, I am getting this error:
okhttp3.internal.http2.StreamResetException: stream was reset:PROTOCOL_ERROR
val client = OkHttpClient()
val response = client.newCall(
    Request.Builder()
           .addHeader("Authorization:", "Bearer $firebaseToken")
           .url("https://someURL/"+ podcastId.toString())
           .build())
    .execute()

I'm not sure if this has to do with the URL or my Authorization header? Any help would be appreciated, thanks in advance.

A: I solved a similar problem by restricting the request to use HTTP 1, see:
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));


text:
Q: OpenCV: How do I proceed to pick up the n best descriptors of an image using SIFT? I'm implementing SIFT with OpenCV, and would like to build a dataset of images descriptors, but just pick up only the n best (200 best, 300...)

A: According to the documentation for SIFT

SIFT::SIFT(int nfeatures=0, int nOctaveLayers=3, double contrastThreshold=0.04, double edgeThreshold=10, double sigma=1.6)
nfeatures – The number of best features to retain. The features are ranked by their scores (measured in SIFT algorithm as the local contrast)

So you can simply pass nfeatures = 200 in the constructor to keep the best 200 keypoints.


text:
Q: How non-Google Web Font can be applied to recurly.js hosted fields? I would like to apply a self-hosted commercial font for recurly.js hosted fields. Is there any way to do this?
(The related documentation of recurly.js mentions the Google Web Fonts only so I suspect there is no way to achieve this currently)


text:
Q: Change the "clicked" current button background When I click a button in a list of buttons, all the buttons in the for-loop change their backgrounds. I already added a method on click, and applied CSS to the button, but I don't know how to change the background color of only the clicked button.
App.vue:
<template>
  <div id="app">
    <!-- <button v-on:click="counter += 1">Add 1</button> -->
    <button
      class="button variation colors"
      v-for="(p,index) in varbutss"
      :key="index"
      :id="p.items_id"
      :value="p.color"
      @click="colorclick(p.items_id,p.color)"
    >{{p.color}}</button>
  </div>
</template>

<script>
import $ from "jquery";
export default {
  name: "App",
  methods: {
    colorclick: function(e,color) {
      console.log(e);

      $(".colors").css("background-color", color);
    }
  },
  data() {
    return {
      varbutss: [
        {
          items_id: 1,
          color: "red"
        },
        {
          items_id: 2,
          color: "blue"
        }
      ]
    };
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

https://codesandbox.io/s/optimistic-dijkstra-st34h?file=/src/App.vue

A: The problem is in this line:
$(".colors").css("background-color", color);

The $(".colors") code finds all elements with the classname of colors. Since each button is assigned the colors class, all buttons are returned, which causes all buttons to have the same color.
Your click-handler passes the button ID as the first argument, so you could use that in your query to limit the scope of color changes to that button. That is, change the selector to be #BUTTONID.colors:
colorclick: function(e, color) {
  $(`#${e}.colors`).css("background-color", color);
}

demo

However, DOM manipulation (with jQuery) should be avoided because those changes will be overwritten if Vue rerenders the component. There's typically a way to rewrite your code without manipulating the DOM. For example, you could apply a class based on a variable that is set by your click-handler.


text:
Q: Changing file permissions with Ionic I am writing file to device storage using @ionic-native/file's copyFile method.
In Android, it's possible to use
file.setExecutable(true, false);
file.setReadable(true, false);
file.setWritable(true, false);

I need to do this in my Ionic app so that the file can be successfully used by another application. I've not been able to find any methods or documentation for Ionic that would make this possible.
Does anyone have any ideas how I can accomplish this using Ionic?


text:
Q: How to delete duplicate data including the original data in datagridview vb.net How can I delete both duplicate and original data in datagridview? I tried different codes but I only manage to delete the duplicate.
Dim i As Integer = 0
While i < numberOfRows

    For ii As Integer = (numberOfRows) To (i + 1) Step -1
        If dtg3.Rows(i).Cells(0).Value.ToString() =
        dtg3.Rows(ii).Cells(0).Value.ToString() And
        dtg3.Rows(i).Cells(2).Value.ToString() =
        dtg3.Rows(ii).Cells(2).Value.ToString() And
        dtg3.Rows(i).Cells(3).Value.ToString() =
        dtg3.Rows(ii).Cells(3).Value.ToString() And
        dtg3.Rows(i).Cells(8).Value.ToString() =
        dtg3.Rows(ii).Cells(8).Value.ToString() Then
        dtg3.Rows.Remove(dtg3.Rows(ii))

        numberOfRows -= 1
    End If

Next
i += 1
End While

What I want is, to delete the duplicate and the original data from my datagridview, hope someone helps me here.

A: there you go
For Each row As DataGridViewRow In DataGridView1.Rows
        For Each nextrow As DataGridViewRow In DataGridView1.Rows

            If row.Index <> nextrow.Index Then
                If row.Cells(0).Value = nextrow.Cells(0).Value Then
                    MsgBox("Duplicate on col 0, index = " & row.Index.ToString)
                End If
                If row.Cells(2).Value = nextrow.Cells(2).Value Then
                    MsgBox("Duplicate on col 2, index = " & row.Index.ToString)
                End If
                If row.Cells(3).Value = nextrow.Cells(3).Value Then
                    MsgBox("Duplicate on col 3, index = " & row.Index.ToString)
                End If
                If row.Cells(8).Value = nextrow.Cells(8).Value Then
                    MsgBox("Duplicate on col 8, index = " & row.Index.ToString)
                End If
            End If

        Next
    Next

This will also check all the column for duplicates not only the row under it like in your example, you were incrementing i and incrementing ii so you were always checking only 2 rows at the same time instead of comparing 1 row to all others..

A: For Each row As DataGridViewRow In dtg3.Rows
            For Each nextrow As DataGridViewRow In dtg3.Rows
                If row.Index <> nextrow.Index Then
                    If row.Cells(0).Value = nextrow.Cells(0).Value AndAlso
row.Cells(2).Value = nextrow.Cells(2).Value AndAlso row.Cells(3).Value =
nextrow.Cells(3).Value AndAlso row.Cells(8).Value = nextrow.Cells(8).Value Then

                        dtg3.Rows.Remove(row)
                        dtg3.Rows.Remove(nextrow)

                    End If
                End If

            Next

        Next


text:
Q: Javascript & html: opacity change causing unexpected behaviour I set out to make a simple fade transition between 3 elements which are on top of each other by using absolute positioning and changing their opacity via Javascript, but the following code does not work as I had expected, and I am unsure as to why.

 0

 1

 2

I think it is something to do with using += with element.style.opacity, but Firefox gives me unhelpful errors and Chrome gives no errors at all.

A: Memebers of element.style object are strings. So try this
prevItem.style.opacity = parseFloat(prevItem.style.opacity) - 0.1;
nextItem.style.opacity = parseFloat(nextItem.style.opacity) + 0.1;

A: element.style.opacity is being retrieved as a string. To fix this, replace these lines:
prevItem.style.opacity -= 0.1;
nextItem.style.opacity += 0.1;

With these:
prevItem.style.opacity = (+prevItem.style.opacity) - 0.1;
nextItem.style.opacity = (+nextItem.style.opacity) + 0.1;

Additionally, for the first iteration, the zero will flash momentarily. This is because although it was set to 1.0 in the CSS, it has no style attribute in the HTML. You can fix this by setting its opacity to 1.0 in init (right after the items = line):
items[0].style.opacity = 1.0;


text:
Q: C# variable height for nodes in a TreeView Despite my google efforts, I could not find a solution to use a default .NET treeview and have variable height for each node in that tree view.
I need is a way to have 2 types of node with different heights.
Ideally, I would also like that one node type can also become bigger as the mouse hover it.
Any clever guy around? :)

A: I realize this is quite old ... but I found something interesting yesterday. This thread contains an answer by Chris Forbes which suggests that it is indeed possible to have items of variable height, if the treeview has the TVS_NONEVENHEIGHT style. I played around with this idea and the github code snippet he linked to, and found that this actually does work but does not provide 100% flexibility (see list of limitations below). I'm also not sure if it would be suitable to change the height of an item on mouse hover.
Why it does what it does is beyond me though, as the window style just seems to enable the user to set an odd item height instead of an even one.
Limitations and caveats:

*

*It needs lots of work, as the node must be completely owner drawn. This code example is not fully functional in that respect.

*You can only set the item height to multiples of the control's ItemHeight property (in fact, you actually set it to the factor you want, 1, 2, 3, ...). I did experiment with setting the control's ItemHeight property to 1 and then set the node height to the pixel height I wanted. It does seem to work, but if you add items at design time, it just produces weird and broken looking results in the designer. I didn't test this thoroughly though.

*You can't set the height if the node hasn't been added to a TreeNodeCollection, as the TreeNode's handle will not have been created.

*You can't modify the item height at design time.

*I don't use pinvoke stuff frequently, so some of those definitions may need some work. For example, the original definition of TVITEMEX has some conditional entries which I didn't know how to replicate.

Here's a 247 line code snippet that demonstrates this, just replace Program.cs of a Windows Forms Application with this code.
It still does need lots of work, as the OwnerDraw code does not yet do anything regarding drawing icons, tree lines, checkboxes and the like, but I thought it was a pretty surprising find, worthy to be posted here.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace TreeTest
{
  static class Program
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new TreeForm());
    }
  }

  public static class NativeExtensions
  {
    public const int TVS_NONEVENHEIGHT = 0x4000;

    [DllImport("user32")]
    //private static extern IntPtr SendMessage(IntPtr hwnd, uint msg, IntPtr wp, IntPtr lp);
    private static extern IntPtr SendMessage(IntPtr hwnd, uint msg, IntPtr wp, ref TVITEMEX lp);

    private const int TVM_GETITEM = 0x1100 + 62;
    private const int TVM_SETITEM = 0x1100 + 63;

    [StructLayout(LayoutKind.Sequential)]
    private struct TVITEMEX
    {
      public uint mask;
      public IntPtr hItem;
      public uint state;
      public uint stateMask;
      public IntPtr pszText;
      public int cchTextMax;
      public int iImage;
      public int iSelectedImage;
      public int cChildren;
      public IntPtr lParam;
      public int iIntegral;
      public uint uStateEx;
      public IntPtr hwnd;
      public int iExpandedImage;
      public int iReserved;
    }

    [Flags]
    private enum Mask : uint
    {
      Text = 1,
      Image = 2,
      Param = 4,
      State = 8,
      Handle = 16,
      SelectedImage = 32,
      Children = 64,
      Integral = 128,
    }

    /// <summary>
    /// Get a node's height. Will throw an error if the Node has not yet been added to a TreeView,
    /// as it's handle will not exist.
    /// </summary>
    /// <param name="tn">TreeNode to work with</param>
    /// <returns>Height in multiples of ItemHeight</returns>
    public static int GetHeight(this TreeNode tn)
    {
      TVITEMEX tvix = new TVITEMEX
      {
        mask = (uint)(Mask.Handle | Mask.Integral),
        hItem = tn.Handle,
        iIntegral = 0
      };
      SendMessage(tn.TreeView.Handle, TVM_GETITEM, IntPtr.Zero, ref tvix);
      return tvix.iIntegral;
    }

    /// <summary>
    /// Set a node's height. Will throw an error if the Node has not yet been added to a TreeView,
    /// as it's handle will not exist.
    /// </summary>
    /// <param name="tn">TreeNode to work with</param>
    /// <param name="height">Height in multiples of ItemHeight</param>
    public static void SetHeight(this TreeNode tn, int height)
    {
      TVITEMEX tvix = new TVITEMEX
      {
        mask = (uint)(Mask.Handle | Mask.Integral),
        hItem = tn.Handle,
        iIntegral = height
      };
      SendMessage(tn.TreeView.Handle, TVM_SETITEM, IntPtr.Zero, ref tvix);
    }
  }

  public class TreeViewTest : TreeView
  {
    public TreeViewTest()
    {
      // Do DoubleBuffered painting
      SetStyle(ControlStyles.AllPaintingInWmPaint, true);
      SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

      // Set value for owner drawing ...
      DrawMode = TreeViewDrawMode.OwnerDrawAll;
    }

    /// <summary>
    /// For TreeNodes to support variable heights, we need to apply the
    /// TVS_NONEVENHEIGHT style to the control.
    /// </summary>
    protected override CreateParams CreateParams
    {
      get
      {
        var cp = base.CreateParams;
        cp.Style |= NativeExtensions.TVS_NONEVENHEIGHT;
        return cp;
      }
    }

    /// <summary>
    /// Do not tempt anyone to change the DrawMode property, be it via code or via
    /// Property grid. It's still possible via code though ...
    /// </summary>
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
      EditorBrowsable(EditorBrowsableState.Never)]
    public new TreeViewDrawMode DrawMode
    {
      get { return base.DrawMode; }
      set { base.DrawMode = value; }
    }

    /// <summary>
    /// OwnerDraw code. Still needs a lot of work, no tree lines, symbols, checkboxes etc. are drawn
    /// yet, just the plain item text and background ...
    /// </summary>
    /// <param name="e"></param>
    protected override void OnDrawNode(DrawTreeNodeEventArgs e)
    {
      e.DrawDefault = false;

      // Draw window colour background
      e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);

      // Draw selected item background
      if (e.Node.IsSelected)
        e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Node.Bounds);

      // Draw item text
      TextRenderer.DrawText(e.Graphics, e.Node.Text, Font, e.Node.Bounds,
        e.Node.IsSelected ? SystemColors.HighlightText : SystemColors.WindowText,
        Color.Transparent, TextFormatFlags.Top | TextFormatFlags.NoClipping);

      // Draw focus rectangle
      if (Focused && e.Node.IsSelected)
        ControlPaint.DrawFocusRectangle(e.Graphics, e.Node.Bounds);

      base.OnDrawNode(e);
    }

    /// <summary>
    /// Without this piece of code, for some reason, drawing of items that get selected/unselected
    /// is deferred until MouseUp is received.
    /// </summary>
    /// <param name="e"></param>
    protected override void OnMouseDown(MouseEventArgs e)
    {
      base.OnMouseDown(e);
      TreeNode clickedNode = GetNodeAt(e.X, e.Y);
      if (clickedNode.Bounds.Contains(e.X, e.Y))
      {
        SelectedNode = clickedNode;
      }
    }
  }

  public class TreeForm : Form
  {
    public TreeForm() { InitializeComponent(); }

    private System.ComponentModel.IContainer components = null;

    protected override void Dispose(bool disposing)
    {
      if (disposing && (components != null))
      {
        components.Dispose();
      }
      base.Dispose(disposing);
    }

    private void InitializeComponent()
    {
      this.treeViewTest1 = new TreeTest.TreeViewTest();
      this.SuspendLayout();
      //
      // treeViewTest1
      //
      this.treeViewTest1.Dock = System.Windows.Forms.DockStyle.Fill;
      this.treeViewTest1.Location = new System.Drawing.Point(0, 0);
      this.treeViewTest1.Name = "treeViewTest1";
      this.treeViewTest1.Size = new System.Drawing.Size(284, 262);
      this.treeViewTest1.TabIndex = 0;
      //
      // Form2
      //
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
      this.ClientSize = new System.Drawing.Size(284, 262);
      this.Controls.Add(this.treeViewTest1);
      this.Name = "Form2";
      this.Text = "Form2";
      this.ResumeLayout(false);
    }

    private TreeViewTest treeViewTest1;

    protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);

      AddNodes(treeViewTest1.Nodes, 0, new Random());
    }

    private void AddNodes(TreeNodeCollection nodes, int depth, Random r)
    {
      if (depth > 2) return;

      for (int i = 0; i < 3; i++)
      {
        int height = r.Next(1, 4);
        TreeNode tn = new TreeNode { Text = $"Node {i + 1} at depth {depth} with height {height}" };
        nodes.Add(tn);
        tn.SetHeight(height);
        AddNodes(tn.Nodes, depth + 1, r);
      }
    }
  }
}

A: I didn't find an answer to your question.  @Frank is right about this not being possible in WinForms.
However, Microsoft design guidelines offer some alternatives to TreeViews IF your hierarchy is only two levels deep.
From https://learn.microsoft.com/en-us/windows/win32/uxguide/ctrl-tree-views:

You must use a tree view if you need to display a hierarchy of more than two levels (not including the root node).

A: That is not possible with the System.Windows.Forms.TreeView nor with any 3rd party replacement I'm aware of. The capabilities of the standard treeview are right about those shown in the Windows Explorer folder view.
Maybe you want to give us some more information about your task or goal. This would allow us to point you to some other alternatives.
Of course, you can always implement you own tree view, but with your requirements this can become a quite time consuming task, I think.

A: If you are using an icon the easiest way is to set the icon size... this atleast worked in the compact framework, I set the image height to the height i wanted the object. you could possibly just have an icon that matches your background if you don't want an icon.


text:
Q: angularjs ng-repeat table with nested table element I have a view where I displaying basic customer information (Name and email) and inside it there is customer details table.
I tried to write ng-repeat in tbody section but child table not getting the data and it's printed only once.
Also I tried to use ng-repeat-start ng-repeat-end but I'm getting errors that no matching ng-repeat-end is found

Error: [$compile:uterdir] Unterminated attribute, found
  'ng-repeat-start' but no matching 'ng-repeat-end' found.

my code:

      Customer Name
      Email

      {{customer.Name}}
      {{customer.EMail}}

          Name
          Address
          City
          Zip Code
          Contact
          Email
          Phone

          {{customer.Name}}
          {{customer.Address}}
          {{customer.City}}
          {{customer.PostCode}}
          {{customer.Contact}}
          {{customer.EMail}}
          {{customer.PhoneNo}}

Any ideas how it should be solved?

Test data:
[{ _id: 569fa2ab011d2ddc3065b802,
Name: 'Gicom',
SearchName: 'GICOM',
Address: 'some address',
Address2: '',
City: '',
Contact: '',
PhoneNo: '123456',
FaxNo: '',
PostCode: '',
Country: '',
EMail: 'mail@test.com',
MonitoringSource: 'US',
__v: 0 },
{ _id: 569fa2ab011d2ddc3065b803,
Name: 'Mitsui',
SearchName: 'MITSUI',
Address: '',
Address2: '',
City: '',
Contact: '',
PhoneNo: '',
FaxNo: '',
PostCode: '',
Country: '',
EMail: '',
MonitoringSource: 'US',
__v: 0 },
{ _id: 569fa2ab011d2ddc3065b804,
Name: 'Icon',
SearchName: 'ICON',
Address: 'customer address',
Address2: '',
City: 'some city',
Contact: '',
PhoneNo: '789456',
FaxNo: '',
PostCode: '',
Country: '',
EMail: 'mymail@test.com',
MonitoringSource: 'US',
__v: 0 }]

A: It's working fine with few adjustments. I cleaned it up a little for you. Try my solution below & let me know if you have any questions:
Solution (Revised for Nested tables):

        Customer Name
        Email

        {{customer.Name}}
        {{customer.EMail}}

                    Name
                    Address
                    City
                    Zip Code
                    Contact
                    Email
                    Phone

                    {{customer.Name}}
                    {{customer.Address}}
                    {{customer.City}}
                    {{customer.PostCode}}
                    {{customer.Contact}}
                    {{customer.EMail}}
                    {{customer.PhoneNo}}

Note 1: If you are using Bootstrap & want to see the table data clearly, just apply  "table" class along with the existing "customer" class and you will see the difference.
Note 2: The problem with your code is the structure of the table. You did not place the child table properly. I made adjustment so that the child table will appear just below the main parent, in a separate row of its own & also moved the "collapsed" class over to the tr tag instead of the nested table. That will help you toggle the row as you see fit. I tested this revised solution with the data & it works fine on my end. Try it out & let me know how it goes.


text:
Q: Running two threads at once, and subsequently communicating between them I am trying to implement a stop and wait ARQ using a sender and receiver communicating on the same machine. My problem is making the two threads run simultaneously and, after that, communicating between the two threads (maybe using Thread.notify()). At the moment the code i have works when i run two separate main methods inside the 2 classes, without the flow control protocol implemented. However when I try and run the code from a separate main method, I can only run the Receiver thread or the Sender thread first, either of which causes the code to wait indefinitely. Im new to threading in general so any help is greatly appreciated!
Sender class:
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;

import java.io.File;
import java.io.FileInputStream;
import tcdIO.*;

/**
 *
 * Sending side of a communication channel.
 *
 * The start method splits an image into a number of packets and sends them to a given receiver.
 * The main method acts as test for the class by filling the destination host and port number and the source port number.
 *
 */
public class Sender implements Runnable{
    static final int DEFAULT_SRC_PORT = 50000;
    static final int DEFAULT_DST_PORT = 50001;
    static final String DEFAULT_DST_HOST = "localhost";

    static final String FILENAME = "input.jpg";

    static final int MTU = 1500;

    static Terminal terminal;

    DatagramSocket socket;
    InetSocketAddress dstAddress;

    /**
     * Constructor
     *
     */
    Sender() {
        this(DEFAULT_DST_HOST, DEFAULT_DST_PORT, DEFAULT_SRC_PORT);
    }

    /**
     * Constructor
     *
     * Attempts to create socket at given port and create an InetSocketAddress for the destinations
     */
    Sender(String dstHost, int dstPort, int srcPort) {
        try {
            dstAddress= new InetSocketAddress(dstHost, dstPort);
            socket= new DatagramSocket(srcPort);
        }
        catch(java.lang.Exception e) {
            e.printStackTrace();
        }
    }

    synchronized void sleep() {
        try {this.wait(100);}catch(Exception e){e.printStackTrace();}
    }

    /**
     * Sender Method
     *
     * Transmits a given image as a collection of packets; the first packet contains the size of the image as string.
     */
    public void run() {
        byte[] data= null;
        DatagramPacket packet= null;

        File file= null;
        FileInputStream fin= null;
        byte[] buffer= null;
        int size;
        int counter;

        try {
            file= new File(FILENAME);               // Reserve buffer for length of file and read file
            buffer= new byte[(int) file.length()];
            fin= new FileInputStream(file);
            size= fin.read(buffer);
            if (size==-1) throw new Exception("Problem with File Access");
            terminal.println("File size: " + buffer.length + ", read: " + size);

            data= (Integer.toString(size)).getBytes();  // 1st packet contains the length only
            packet= new DatagramPacket(data, data.length, dstAddress);
            terminal.println("Please press any key");
            terminal.readChar();
            socket.send(packet);

            counter= 0;
            do {
                data= new byte[(counter+MTU<size) ? MTU : size-counter];  // The length of the packet is either MTU or a remainder
                java.lang.System.arraycopy(buffer, counter, data, 0, data.length);
                terminal.println("Counter: " + counter + " - Payload size: " + data.length);

                packet= new DatagramPacket(data, data.length, dstAddress);
                socket.send(packet);
                this.sleep();
                counter+= data.length;
            } while (counter<size);

        terminal.println("Send complete");
    }
    catch(java.lang.Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    Sender s;
    try {
        String dstHost;
        int dstPort;
        int srcPort;

        //dstHost= args[0];
        //dstPort= Integer.parseInt(args[1]);
        //srcPort= Integer.parseInt(args[2]);
        dstHost= DEFAULT_DST_HOST;
        dstPort= DEFAULT_DST_PORT;
        srcPort= DEFAULT_SRC_PORT;

        terminal= new Terminal("Sender");

        s= new Sender(dstHost, dstPort, srcPort);
        s.run();

        terminal.println("Program completed");
    } catch(java.lang.Exception e) {
        e.printStackTrace();
    }
}

}

Receiver Class:
import java.io.File;
import java.io.FileOutputStream;
import java.net.DatagramSocket;
import java.net.DatagramPacket;

import tcdIO.*;

/**
 * Receiving side of a communication channel.
 *
 * The class provides the basic functionality to receive a datagram from a sender.
 * The main method acts as test for the class by filling the port number at which to receive the datagram.
 */
public class Receiver implements Runnable{
    static final String FILENAME = "output.jpg";
    static final int DEFAULT_PORT = 50001;
    static final int MTU = 1500;
    static Terminal terminal;

    DatagramSocket socket;

    /**
     * Constructor
     *
     */
    Receiver() {
        this(DEFAULT_PORT);
    }

    /**
     * Constructor
     *
     * Attempts to create socket at given port
     */
    Receiver(int port) {
        try {
            socket= new DatagramSocket(port);
        }
        catch(java.lang.Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Receiver Method
     *
     * Attempts to receive a number of packets that contain an image; the first packet contains the size of the image
     */
    public void run() {
        byte[] data;
        byte[] buffer;
        DatagramPacket packet;
        int counter;
        int size;

        File file;
        FileOutputStream fout;

        try {
            data= new byte[MTU];  // receive first packet with size of image as payload
            packet= new DatagramPacket(data, data.length);
            terminal.println("Waiting for incoming packets");
            socket.receive(packet);

            data= packet.getData();   // reserve buffer to receive image
            size= (Integer.valueOf(new String(data, 0, packet.getLength()))).intValue();
            terminal.println("Filesize:" + size);
            buffer= new byte[size];

            counter= 0;
            while(counter<size) {  // receive packet and store payload in array
                data= new byte[MTU];
                packet= new DatagramPacket(data, data.length);
                socket.receive(packet);
                terminal.println("Received packet - Port: " + packet.getPort() + " - Counter: " + counter + " - Payload: "+packet.getLength());

                System.arraycopy(data, 0, buffer, counter, packet.getLength());
                counter+= packet.getLength();
            }

            file= new File(FILENAME);               // Create file and write buffer into file
            fout= new FileOutputStream(file);
            fout.write(buffer, 0, buffer.length);
            fout.flush();
            fout.close();
        }
        catch(java.lang.Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Test method
     *
     * Creates an instance of the class Receiver
     *
     * @param args arg[0] Port number to receive information on
     * /
    public static void main(String[] args) {
        Receiver r;

        try {
            terminal= new Terminal("Receiver");
            int port;

            //port= Integer.parseInt(args[0]);
            port= DEFAULT_PORT;
            r= new Receiver(port);
            r.run();

            terminal.println("Program completed");
        } catch(java.lang.Exception e) {
            e.printStackTrace();
        }
    }
    */
}

And the main, which just instantiates both and runs them:
import tcdIO.Terminal;

public class FlowControlMain {

    /**
     *
     *
     */
    public static void main(String[] args) {

        Sender s;
        Receiver r;
        try{
            String dstHost= "localhost";
            int dstPort= 50001;
            int srcPort= 50000;

            Sender.terminal= new Terminal("Sender");
            Receiver.terminal = new Terminal("Receiver");

            s= new Sender(dstHost, dstPort, srcPort);
            r = new Receiver(dstPort);
            s.run();
            r.run();

        }catch(Exception e){
            e.printStackTrace();

        }

    }

}

Apologies for the massive amount of code, just trying to give a complete picture

A: You're not using threads, you're executing the run() method in your main thread.
The correct way to start a Runnable in its own Thread is either
Thread t = new Thread(myRunnable);
t.start();

or to use an ExecutorService, which is a bit higher level and allows things such as thread pooling.