Q:

how to extract HTML table contents to DataTable

I have this html page and the contents in the page looks like below

I'm trying to fetch the contents in the page into a DataTable and display it to a grid
for example in
exodus-5.1-20150612-NIGHTLY-bacon.zip

I need to get the name of the link as well as the uri too
name : - exodus-5.1-20150612-NIGHTLY-bacon.zip
uri : - /exodus-5.1/bacon/exodus-5.1-20150612-NIGHTLY-bacon.zip
following is what I have ended up
 Dim request As HttpWebRequest = HttpWebRequest.Create(url)
 request.Method = WebRequestMethods.Http.Get
 Dim response As HttpWebResponse = request.GetResponse()
 Dim reader As New StreamReader(response.GetResponseStream())
 Dim webpageContents As String = reader.ReadToEnd()
 response.Close()

A:

Although not VB.Net this is a very easy task to achieve using another .Net language F# and the HTML Type Provider which is part of the FSharp.Data project available via Nuget.
The HTML Type Provider gives you typed access to HTML documents inside Visual Studio, i.e.
// Reference the FSharp.Data Nuget package
#r @".\packages\FSharp.Data.2.2.3\lib\net40\FSharp.Data.dll"
// Type provider over your HTML document specified in yourUrl
type html = FSharp.Data.HtmlProvider<yourUrl>
// Get the rows from the HTML table in the page
let allRows = html.GetSample().Tables.Table1.Rows |> Seq.skip 1
// Skip empty rows
let validRows = allRows |> Seq.where (fun row -> row.Name <> "")

Then load the valid rows into a DataTable:
// Reference the System.Data assembly
#r "System.Data.dll"
// Create a DataTable
let table = new System.Data.DataTable()
// Add column names to the table
for name in ["Parent";"Name";"Last modified";"Size"] do table.Columns.Add(name) |> ignore
// Add row values to the table
for row in validRows do
  table.Rows.Add(row.Column1, row.Name, row.``Last modified``, row.Size) |> ignore

and finally show the DataTable on a form:
// Reference the Windows.Forms assembly
#r "System.Windows.Forms.dll"
open System.Windows.Forms
// Create a form
let form = new Form(Width=480,Height=320)
// Initialise a grid
let grid = new DataGridView(Dock=DockStyle.Fill)
form.Controls.Add(grid)
// Set the grid data source with the table
form.Load.Add(fun _ -> grid.DataSource <- table)
form.Show()

Which shows a populated DataGrid in a form:


Q:

Rails :uniqueness validation not finding previous records

I'm having a bizzarre glitch, where Rails does not validate the uniqueness of an attribute on a model, despite the attribute being saved perfectly, and despite the validation being written correctly.
I added a validation to ensure the uniqueness of a value on one of my Rails models, Spark, with this code:
validates :content_hash, :presence => true, :uniqueness => true

The content_hash is an attribute created from the model's other attributes in a method called using a before_validation callback. Using the Rails console, I've confirmed that this hash is actually being created before the validation, so that is not the issue.
When I call in the Rails console spark.valid? on a spark for which I know a collision exists on its content_hash, the console tells me that it has run this query:
Spark Exists (0.2ms)  SELECT 1 AS one FROM "sparks" WHERE "sparks"."content_hash" = '443524b1c8e14d627a3fadfbdca50118c6dd7a7f' LIMIT 1

And the method returns that the object is valid. It seems that the validator is working perfectly fine, and is running the correct query to check the uniqueness of the content_hash, the problem is instead on the database end (I'm using sqlite3). I know this because I decided to check on the database myself to see if a collision really exists using this query:
SELECT "sparks".* FROM "sparks" WHERE "sparks"."content_hash" = '443524b1c8e14d627a3fadfbdca50118c6dd7a7f'

Bizarrely, this query returns  nothing from the database, despite the fact that I can see with my own eyes that other records with this content_hash exist on the table.
For some reason, this is an issue that exists exclusively with the content_hash attribute of the sparks table, because when I run similar queries for the other attributes of the table, the output is correct.
The content_hash column is no different from the others which work as expected, as seen in this relevant part of my schema.rb file:
create_table "sparks", :force => true do |t|
    t.string   "spark_type"
    t.string   "content_type"
    t.text     "content"
    t.text     "content_hash"
    t.datetime "created_at",   :null => false
    t.datetime "updated_at",   :null => false
end

Any help on this problem would be much appreciated; I'm about ready to tear my hair out over this thing.

A:

Okay, I managed to fix the problem. I think it was an sqlite3 issue, because everything worked perfectly once I changed the type of content_hash from a text column to a string column. Weird.


Q:

How to manage SwiftUI state with nested structs?

I have the following structs generated from protobufs so they're not modifiable directly:
// This file can not be modified
// It's auto-generated from protobufs

struct Shelf {
  var id: Int
  var title: String

  var books: [Books]
}

struct Book {
  var id: Int
  var title: String

  var pages: [Pages]
  var shelfId: Int
}

struct Page {
  var id: Int
  var content: String

  var bookId: Int
}

What's the proper way of passing the state between 3 nested SwiftUI views when creating or modifying a new Shelf with Books+Pages? I want to allow the user to create the whole shelf at once going through nested view and save Shelf+Books+Pages to the backend only once when he's on the top view and clicking "Save".

I tried to create an extension for objects to conform to 'ObservableObject' but failed with:
Non-class type 'Shelf' cannot conform to class protocol 'ObservableObject'

A:

I made the full project, to demonstrate how to pass the data. This took a lot of time, but here it is.
It is available on GitHub at George-J-E/BookshelvesExample if you want to download the full project to see all the code. This is what the project looks like:

This project is quite similar to my answer for SwiftUI - pass data to different views.
As a summary, I created an ObservableObject which is used with @EnvironmentObject. It looks like this:
class Reference: ObservableObject {

    @Published var shelves = [...]
    var books: [Book] {
        return shelves[shelfId - 1].books
    }
    var pages: [Page] {
        return shelves[shelfId - 1].books[bookId - 1].pages
    }

    var shelfId = 1
    var bookId = 1

    func addShelf(title: String) {
        /* ... */
    }
    func addBook(title: String) {
        /* ... */
    }
    func addPage(content: String) {
        /* ... */
    }

    func totalBooks(for shelf: Shelf) -> String {
        /* ... */
    }
    func totalPages(for book: Book) -> String {
        /* ... */
    }
}

The views are then all connected using NavigationLink. Hope this works for you!

If you are remaking this manually, make you replace
let contentView = ContentView()

with
let contentView = ContentView().environmentObject(Reference())

in the SceneDelegate.swift.

A:

Well, the preferable design in this case would be to use MVVM based on ObservableObject for view model (it allows do not touch/change generated model, but wrap it into convenient way for use in View).
It would look like following
class Library: ObservableObject {
  @Published var shelves: [Shelf] = []
}

However, of course, if required, all can be done with structs only based on @State/@Binding only.
Assuming (from mockup) that the initial shelf is loaded in some other place the view hierarchy (in simplified presentation just to show the direction) can be:
struct ShelfView: View {
    @State private var shelf: Shelf

    init(_ shelf: Shelf) {
        _shelf = State<Shelf>(initialValue: shelf)
    }

    var body: some View {
        NavigationView {
            List {
                ForEach(Array(shelf.books.enumerated()), id: \.1.id) { (i, book) in
                    NavigationLink("Book \(i)", destination: BookView(book: self.$shelf.books[i]))
                }
                .navigationBarTitle(shelf.title)
            }
        }
    }
}

struct BookView: View {
    @Binding var book: Book
    var body: some View {
        List {
            ForEach(Array(book.pages.enumerated()), id: \.1.id) { (i, page) in
                NavigationLink("Page \(i)", destination: PageView(page: page))
            }
            .navigationBarTitle(book.title)
        }
    }
}

struct PageView: View {
    var page: Page
    var body: some View {
        ScrollView {
            Text(page.content)
        }
    }
}

A:

Basically, you need a storage for your books/pages, and preferably that storage can be uniquely referenced among your views. This means a class :)
class State: ObservableObject {
    @Published var shelves = [Shelf]()

    func add(shelf: Shelf) { ... }
    func add(book: Book, to shelf: Shelf) { ... }
    func add(page: Page, to book: Book) { ... }
    func update(text: String, for page: Page) { ... }
}

You can then either inject the State instance downstream in the view hierarchy, on inject parts of it, like a Shelf instance:
struct ShelvesList: View {
    @ObserverdObject var state: State

    var body: some View {
        ForEach(state.shelves) { ShelfView(shelf: $0, shelfOperator: state) }
    }
}

// this conceptually decouples the storage and the operations, allowing
// downstream views to see only parts of the entire functionality
protocol ShelfOperator: BookOperator {
    func add(book: Book, to shelf: Shelf)
}

extension State: ShelfOperator { }

struct ShelfView: View
    var shelf: Shelf
    @State var selectedBook: Book
    var shelfOperator: ShelfOperator

    var body: some View {
        ForEach(shelf.books) { book in
            Text(book.title).tapGesture {
               // intercepting tap to update the book view with the new selected book
               self.selectedBook = book
            }
        }
        BookView(book: selectedBook, bookOperator: operator)
    }
}

// This might seem redundant to ShelfOperator, however it's not
// A view that renders a book doesn't need to know about shelf operations
// Interface Segregation Principle FTW :)
protocol BookOperator: PageOperator {
    func add(page: Page, to book: Book)
}

struct BookView: View {
    var book: Book
    var bookOperator: BookOperator

    var body: some View { ... }
}

// Segregating the functionality via protocols has multiple advantages:
// 1. this "leaf" view is not polluted with all kind of operations the big
// State would have
// 2. PageView is highly reusable, since it only depends on entities it needs
// to do its job.
protocol PageOperator {
    func update(text: String, for page: Page)
}

struct PageView: View {
    var page: Page
    var pageOperator: PageOperator

    var body: some View { ... }

What happens with the code above is that data flows downstream, and events propagate upstream, and any changes caused by events are then propagated downstream, meaning your views are always in sync with the data.
Once you're done with the editing, just grab the list of shelves from the State instance and send them to the backend.


Q:

iTunes Backup - iOS & Settings only - No Apps

Is there a way to backup the iPhone such that none of the apps are included? I can always download the apps from the iTunes App Store after the iPhone is restored. I would like to backup all the settings for Mail, Messages, iCloud, and the OS itself .. but I just don't have enough space on my SSD for the App backups in iTunes.

A:

Short Answer
Back up to iCloud and to iTunes. Then, delete the Mobile Applications folder from Windows Explorer/Finder to remove the apps that have been backed up to iTunes.
Long Answer
Make sure you read the Apple support page before you get started, but basically, I would recommend backing up to iCloud, which says that it will automatically back up your camera roll, accounts, documents, and settings. Then, do a full backup to iTunes by clicking Back Up when you plug in your iOS device. and you can remove the folder Mobile Applications on Windows or Mac by navigating to the Users\Music\iTunes\iTunes Media\Mobile Applications folder (actual folder names may vary based on operating system).
Pictures
Deleting the Mobile Applications Folder

Look at the directory path at the bottom of the picture, too.


Q:

PDO ON DUPLICATE KEY UPDATE not work on PHP 5.1.6

<?php
$sql = "INSERT INTO `tables`
    (
        `uuid`,
        `name`
    )
    VALUES
    (
        :uuid,
        :name
    )
    ON DUPLICATE KEY UPDATE
        `name` = :name
    ";
$sth = $dbh->prepare($sql);
$sth->bindValue(':uuid', 'abc');
$sth->bindValue(':name', 'Chan');
$sth->execute()

When I execute code first time, it's insert correct data to table, but when I execute second time, name value turns to 0, even I change name to other value get the same result, but if I do it like:
<?php

$sql = "INSERT INTO `tables`
    (
        `uuid`,
        `name`
    )
    VALUES
    (
        :uuid,
        :name
    )
    ON DUPLICATE KEY UPDATE
        `name` = 'other name'
    ";
$sth = $dbh->prepare($sql);
$sth->bindValue(':uuid', 'abc');
$sth->bindValue(':name', 'Chan');
$sth->execute()

The name value become other name, how to fix it?

A:

AFAIK you can't use the same parameter name more than one time. So try the following
<?php
$sql = "INSERT INTO `tables`
(
    `uuid`,
    `name`
)
VALUES
(
    :uuid,
    :name
)
ON DUPLICATE KEY UPDATE
    `name` = :name2
";

$sth = $dbh->prepare($sql);
$sth->bindValue(':uuid', 'abc');
$sth->bindValue(':name', 'Chan');
$sth->bindValue(':name2', 'Chan');
$sth->execute()

EDIT: See the comment below


Q:

How to know if current time is between two timespans?

I have two time spans like so:
TimeSpan Starttime : 16:37:00
TimeSpan EndTime: 17:37:00

current time:
DateTime currentDate = DateTime.Now;
TimeSpan now = currentDate.TimeOfDay;

Problem:
I can't figure out how to know if the current time is between starttime and endtime. i want to send mesages only between those two timespans.
How do i do this?
My attempt:
 if(startTime.Hours < now.Hours && endTime.Hours > now.Hours)
   // do stuff

This does not cover all scenarios since I need it to be exactly between starttime and endtime to the last second but I dont know how to do this.

A:

You can just use:
if (startTime < now && now < endTime)

Note that:

This doesn't check the date; doesn't look like that's an issue here
Depending on why you're doing this, you may want to consider intervals such as "10pm-2am" at which point you effectively want to reverse the logic
In most cases, it's worth making the lower-bound inclusive and the upper-bound exclusive, e.g.
if (startTime <= now && now < endTime)

That's useful because then you can have several intervals where the end of one interval is the start of the next interval, and any one time is in exactly one interval.

To handle the "10pm-2am" example, you'd want something like:
if (interval.StartTime < interval.EndTime)
{
    // Normal case, e.g. 8am-2pm
    return interval.StartTime <= candidateTime && candidateTime < interval.EndTime;
}
else
{
    // Reverse case, e.g. 10pm-2am
    return interval.StartTime <= candidateTime || candidateTime < interval.EndTime;
}


Q:

Parse .txt to .csv

Is it possible to create a Java program which recognizes the text in a .txt file and write it in a .csv file? If yes,how would you start with such a problem?
My .txt file is Text1 |Text 2 so I could somehow get the char "|" and split it into two cells.

A:

This is very simple in Java 8:
public static void main(String[] args) throws Exception {
    final Path path = Paths.get("path", "to", "folder");
    final Path txt = path.resolve("myFile.txt");
    final Path csv = path.resolve("myFile.csv");
    try (
            final Stream<String> lines = Files.lines(txt);
            final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(csv, StandardOpenOption.CREATE_NEW))) {
        lines.map((line) -> line.split("\\|")).
                map((line) -> Stream.of(line).collect(Collectors.joining(","))).
                forEach(pw::println);
    }
}

First you get your files at Path objects.
Then you open a PrintWriter to your destination Path.
Now you do some Java 8 stream processing with lambdas:

Files.lines(txt) streams the lines from the file
map((line) -> line.split("\\|")) splits each line to a String[] on |
map((line) -> Stream.of(line).collect(Collectors.joining(","))) joins the individual String[] again using ,
forEach(pw::println) writes the new lines to the destination file.

Using import static:
    try (
            final Stream<String> lines = Files.lines(txt);
            final PrintWriter pw = new PrintWriter(newBufferedWriter(csv, StandardOpenOption.CREATE_NEW))) {
        lines.map((line) -> line.split("\\|")).
                map((line) -> Stream.of(line).collect(joining(","))).
                forEach(pw::println);
    }

As Java 8 was released only yesterday here is a Java 7 solution:
public static void main(String[] args) throws Exception {
    final Path path = Paths.get("path", "to", "folder");
    final Path txt = path.resolve("myFile.txt");
    final Path csv = path.resolve("myFile.csv");
    final Charset utf8 = Charset.forName("UTF-8");
    try (
            final Scanner scanner = new Scanner(Files.newBufferedReader(txt, utf8));
            final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(csv, utf8, StandardOpenOption.CREATE_NEW))) {
        while (scanner.hasNextLine()) {
            pw.println(scanner.nextLine().replace('|', ','));
        }
    }
}

Again, with import static:
    try (
            final Scanner scanner = new Scanner(newBufferedReader(txt, utf8));
            final PrintWriter pw = new PrintWriter(newBufferedWriter(csv, utf8, StandardOpenOption.CREATE_NEW))) {
        while (scanner.hasNextLine()) {
            pw.println(scanner.nextLine().replace('|', ','));
        }
    }


Q:

Load balancing PostgreSQL with Windows Servers

I have a question concerning the possibilities of load balancing when using PostgreSQL with Windows Servers. On Unix systems this is made possible by using pgpool-II. How can I achieve the same with Windows?
I know that you cannot mix systems when it comes to replication. Pgpool documentation states:

Can I mix different platforms of PostgreSQL as pgpool-II backends, for example Linux and Windows?
In streaming replication mode, no

What about a different scenario? Can I run pgpool on a Unix machine, and configure replication & load balancing on a pool of Windows Servers?
I'm using Windows Server 2008 R2 in case it matters.

A:

Can I run pgpool on a Unix machine, and configure replication & load balancing on a pool of Windows Servers?

Yes, you can. That's probably the best option in your situation, barring porting PgPool-II to Windows.
However, I suspect that load balancing across read replicas isn't necessary most of the time people do it, and that appropriate database tuning, indexing and configuration is often sufficient.


Q:

rake db:migrate, source and destination

I'm new to ruby and mysql.
I was told to execute two commands below:

mysql -u root; then CREATE DATABASE sd
rake db:migrate.

The sd database was empty when created. After I ran the 2nd command, sd is full of items.
I'm wondering how rake knows that the destination is sd and what the source is.
I know that there are some scripts under db/migrate folder, so I guess rake knows who the destination is from such newly-created(I assume, 'cause I'm new to ruby) scripts. But how about the source?
Thanks!

A:

The source of the data will normally be controlled by the db/migrate/*.rb files as you are aware of.
But they may have hooked another task onto db:migrate via the Rakefile or lib/tasks/*.rake files so "rake db:mirgrate" may also runs some extra tasks. A common task that adds seed information is the rake db:seed task, which normally runs db/seeds.rb .
When I use db/seeds.rb I typically put my seed data in db/fixtures/*.yml, but others may have different places.
on newer rails you can also use rake db:create to do the database creation (assuming the user in database.yml has sufficient privileges). rake -T db will tell you wnat tasks have been named with db in them, eg:
$ rake -T db
rake db:create          # Create the database from DATABASE_URL or config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)
rake db:drop            # Drops the database using DATABASE_URL or the current Rails.env (use db:drop:all to drop all databases)
rake db:fixtures:load   # Load fixtures into the current environment's database.
rake db:migrate         # Migrate the database (options: VERSION=x, VERBOSE=false).
rake db:migrate:status  # Display status of migrations
rake db:rollback        # Rolls the schema back to the previous version (specify steps w/ STEP=n).
rake db:schema:dump     # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load     # Load a schema.rb file into the database
rake db:seed            # Load the seed data from db/seeds.rb
rake db:seed_fu         # Loads seed data for the current environment.
rake db:setup           # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)
rake db:structure:dump  # Dump the database structure to db/structure.sql. Specify another file with DB_STRUCTURE=db/my_structure.sql
rake db:test:seed       # seed the test database
rake db:version         # Retrieves the current schema version number


Q:

selected value tag of Form::model doesn't bind property from Model

I'm learning Laravel and have an issue when trying to bind a property of the Model to selected values of the select tag. I tried to leave the 3rd parameter null because I believe Form Model Binding will automatically take care of it but it doesn't work. Here is what I already tried:
   {{$article->tag_list}} // show [1,3]

    //it doesn't work
   {!! Form::select('tag_list[]', $tags, null , ['class' => 'form-control', 'multiple'] ) !!}
    -------------

    //it doesn't work as well
    {!! Form::select('tag_list[]', $tags, $article->tag_list  , ['class' => 'form-control', 'multiple'] ) !!}
    -----------

    //it works
    {!! Form::select('tag_list[]', $tags, [1,3] , ['class' => 'form-control', 'multiple'] ) !!}

In the model I have the getTagListAttribute() which works fine.
public function getTagListAttribute(){
    return $this->tags->lists('id');
}

With Text Input, the form works fine. Btw, I'm using 5.2.1 version. What am I missing here ?

A:

I found the missing piece. the select function expects an array but getTagListAttribute() return an Collection object.
public function getTagListAttribute(){
  return $this->tags->lists('id')->all();
}
or I can do this
public function getTagListAttribute(){
  return $this->tags->lists('id')->toArray();
}


Q:

How to choose which scene shows up first spritekit/swift?

Where is it declared which scene will show up first on load up of the app? The first file I made which is the game obviously shows up first, but if I'm wanting to switch it so that my main menu pops up first, how and where do I do that?
Thanks

A:

In the view controller, the first scene is set. By default, it's automatically set to GameScene but you can change this by altering the code in the GameScene. You should change this line in unarchive from file:
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene to
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! sceneName
and this line in didMoveToView
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
 to
if let scene = GameScene.unarchiveFromFile("GameScene") as? sceneName {

This will cause the game to load sceneName, or whatever you scene is called as the initial scene.


Q:

how can I make these diagrams with latex?

I need to prepare several diagrams with latex and the closest match to what I need to do are these two diagrams, can anyone provide hints how to do them? I'm familiar with TikZ but these diagrams look like advance level to me. Can anyone suggest a package/plugin etc to implement something like this?

A:

Here's some code for the second part:
\documentclass{article}
\usepackage[margin=2cm]{geometry}
\usepackage{bbding}
\usepackage{tikz}
\usetikzlibrary{calc,matrix,arrows}

\begin{document}

\newcommand\MyCross{\XSolid}

\begin{tikzpicture}[remember picture]
\begin{scope}
\matrix[matrix of nodes,column sep=-1mm] (mat1)
{
 \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 & \color{red}{\MyCross} & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 & & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 & & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
};
\draw[help lines] (mat1-4-2.north west) rectangle (mat1-5-7.south east);
\draw[-latex, shorten >=-3pt, shorten <=-3pt] (mat1-4-2) to[out=180,in=130] (mat1-5-2.160);
\node[anchor=south] at (mat1.north) {A};
\end{scope}
\begin{scope}[xshift=3.8cm]
\matrix[matrix of nodes,column sep=-1mm] (mat2)
{
 \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 &  & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 &  &  & \MyCross & \MyCross & \MyCross & \MyCross \\
 &  &  & \color{blue}{\MyCross} & \MyCross & \MyCross & \MyCross \\
 &  &  &  &  & \MyCross & \MyCross \\
 &  &  &  &  &  & \MyCross \\
};
\draw[help lines] (mat2-4-4.north west) rectangle (mat2-5-7.south east);
\node[anchor=south] at (mat2.north) {B};
\end{scope}
\begin{scope}[xshift=8cm]
\matrix[matrix of nodes,column sep=-1mm] (mat3)
{
 \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 &  & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 &  & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 &  & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
};
\draw[help lines] (mat3-1-4.north west) rectangle (mat3-7-5.south east);
\node[anchor=south] at (mat3.north) {A};
\end{scope}
\begin{scope}[xshift=11.8cm]
\matrix[matrix of nodes,column sep=-1mm] (mat4)
{
 \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 &  & \MyCross & \MyCross & \MyCross & \MyCross & \MyCross \\
 &  &  & \MyCross & \MyCross & \MyCross & \MyCross \\
 &  &  & \color{red}{\MyCross} & \MyCross & \MyCross & \MyCross \\
 &  &  &  &  & \MyCross & \MyCross \\
 &  &  &  &  &  & \MyCross \\
};
\draw[help lines] (mat4-1-4.north west) rectangle (mat4-5-5.south east);
\draw[-latex, shorten >=-3pt, shorten <=-3pt] (mat4-5-5) to[out=270,in=-40] (mat4-5-4.-80);
\node[anchor=south] at (mat4.north) {B};
\end{scope}
\draw ( $ (mat2-1-7)!.5!(mat3-1-1) + (0,0.5) $ ) -- +(0,-4.6);
\end{tikzpicture}

\end{document}

And here'ssome code for the first part (building on phimuemue's code):
\documentclass{article}
\usepackage[margin=2cm]{geometry}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[scale=1.5]
\foreach \x in {0,...,9} {
  \node at (\x-.35,-0.6) {$v_{\x}$};
}
\clip (-0.3,-1.3) rectangle (8.3,4.3);
\foreach \x in {0,...,8} {
  \foreach \y in {0,...,4} {
    \node at  (\x cm,\y cm) (g-\x-\y) {$G_{\x,\y}$};
  }
}
\foreach \y in {0,...,3} {
  \foreach \x in {0,...,8} {
    \draw[->,shorten <=2pt,shorten >=7pt] (g-\x-\y) -- +(0,20pt);
  }
}
\foreach \y in {0,...,4} {
  \foreach \x in {0,...,7} {
    \draw[->,shorten >=2pt,shorten >=7pt] (g-\x-\y) -- +(20pt,0);
  }
}
\foreach \y in {0,...,3} {
  \foreach \x in {1,...,8} {
    \draw[->] (\x-.3,\y+.3) -- (\x - .6, \y+.6);
  }
}
\foreach \x in {0,...,11} {
  \draw[dashed,thick] (\x-4.35,5) -- (\x + .65, 0);
}
\end{tikzpicture}

\end{document}

A:

No complete working solution, but at least something to start with (for the first diagram, second ones should be simpler):
\begin{tikzpicture}[scale=1.2]
  \foreach \x in {0,...,8} {
    \foreach \y in {0,...,4} {
      \node at  (\x cm,\y cm) {$G_{\x,\y}$};
      \draw[->] (\x-.3,\y+.3) -- (\x - .6, \y+.6);
      \draw[->] (\x-.2,\y+.3) -- (\x - .2, \y+.6);
      \draw[->] (\x+.3,\y) -- (\x + .6, \y);
    }
  }
  \foreach \x in {0,...,7} {
    \draw[dashed,thick] (\x-1.35,5) -- (\x + 3.65, 0);
  }
\end{tikzpicture}


Q:

Pointers and online change in TwinCAT and CoDeSys

Are pointers safe against online change of running PLC program in TwinCAT 2.10 and in CoDeSys 2.3 on which the first one is based? What happens if memory block gets reallocated as part of online program change and there are pointers pointing to that memory block?

A:

ADR (Address Operator) description in TwinCAT's help says:
Attention:
After an Online Change there might be changes concerning the data on certain addresses. Please regard this in case of using pointers on addresses.
It looks to me like pointers cannot be stored permanently if someone pretends to use online modification of the program. Otherwise if pointers are stored (for example as a binding between some data structures) online change should be avoided.


Q:

mysqli select query does not work propley

i'm trying to pull out all rows from mysql table.
I have created this code
function getAllRows($tablename){
            $query = $this->mysqli->prepare("SELECT * FROM `".$tablename."`");
            $query->execute();
            $query->bind_result($results);
            while($query->fetch())
            {
                $rows[] = $results;
            }
            return $rows;
        }

but I recive this error:
( ! ) Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in D:\wamp64\www\easyApi\configuration.php on line 16
Thanks for the help.

A:

You must bind the same number of column you get suing the select
could be you select * return more then a column
try adding the right number of var to your bind_result
$query = $this->mysqli->prepare("SELECT col1, col2 FROM `".$tablename."`");

...
$stmt->bind_result($col1, $col2);


Q:

Loop and list all p-values (percentage and not histogram)

I have the following Mathematica code (see below). It currently provides a histogram as the solution. Instead of a histogram I want to count the number of times the p-value calculated surpasses a certain level so I can get a percentage of those times it would fail to reject or reject the hypothesis test at the $\alpha$ level set. So for each test, I should get a percentage below or equal to the p-value and a (1-percentage) above the p-value. Also, is there a way that if you have the histograms already that you can pull the actual values which Mathematica used to make the histogram?
DD[a_, b_, c_, μ_, ν_, σ_, τ_] =
  MixtureDistribution[{a, b, c, a, b, c},
   {NormalDistribution[-μ, τ],
    NormalDistribution[-ν, σ],
    NormalDistribution[-μ - ν, σ + τ],
    NormalDistribution[μ, τ],
    NormalDistribution[ν, σ],
    NormalDistribution[μ + ν, σ + τ]}];

tests = {AndersonDarlingTest, CramerVonMisesTest,
   KolmogorovSmirnovTest, KuiperTest, PearsonChiSquareTest,
   WatsonUSquareTest};

n = 100;(* change to your larger number, i.e., 1000 *)

pValues =
  Table[
    data = RandomVariate[\[ScriptD] = JohnsonDistribution["SU", 0, 1, 0, 1], 1000];
    (*Target Distributions here*)
    data1 = RandomVariate[f = DD[0.46, 0.435, 0.105, 0, 0, 0.671, 1.7], 1000];
    (*SIGMA goes here*)
    #[data, f, SignificanceLevel -> 0.01] & /@ tests, {n}
  ] // Transpose;

Partition[
  Histogram[#[[2]], PlotLabel -> #[[1]]] & /@
   Transpose[{tests, pValues}],
  2] // Grid

A:

The counts:
Count[#, _?(# > 0.05 &)] & /@ pValues
(* {81, 98, 95, 87, 70, 91} *)

or as percentages:
100./n Count[#, _?(# > 0.05 &)] & /@ pValues
(* {81., 98., 95., 87., 70., 91.} *)

And if you have only the histograms left, you can extract the data as follows:

{45, 26, 13, 8, 3, 3, 2

Play with the indices to get the results for the various parts in the grid.


Q:

Why does php throw syntax error in code

echo "<input  type=\"text\" size=3 name=\"{$item[\"name\"]}\"/>";

but following works fine
echo "<input  type=\"text\" size=3 name=\"{$item['name']}\"/>";

As per my understanding \" really escape the "

A:

You don't need to escape the quotes inside the {}. That's supposed to be quoted because it means the string index "name" for the PHP array $name. Without quotes (or escaped quotes), name is treated as a constant (which I'm assuming it isn't), and then you've got an extra pair of quotes which don't belong.
OTOH, this would also be correct:
echo "<input  type=\"text\" size=\"3\" name=\"$item[name]\"/>";

(no quotes around name and no {} either)
see http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing

re:comment
Any non-keyword without quotes or the $ sign is regarded as a constant (as you can define with the define function), thus "name" (with quotes) is a string, and name without quotes is a constant.
when written like this, however:
echo "{$item[name]}";

PHP will first look for a constant with the name name, then if it doesn't exist, it will use the string "name". However, it will (depending on your settings?) also issue a warning.


Q:

Limits with logs

Find the limit by interpreting the expression as an appropriate derivative.
$$\lim_{w \rightarrow 1} \frac{-8 \ln  w }{w - 1}= ?.$$

A:

$$\lim_{w\rightarrow1}\dfrac{-8\ln(w)}{w-1}=-8\lim_{w\rightarrow1}\dfrac{\ln(w)}{w-1}$$Now, by using L'Hopital's Rule
$$-8\lim_{w\rightarrow1}\left(\dfrac{\dfrac1w}{1}\right)=-8\lim_{w\rightarrow1}\dfrac1w=-8$$


Q:

How can I detect a duplicate post in PHP?

I have a form which inserts the text (of an article) into a database. When a user submits an article (that has already been submitted) it gets submitted also into the db.
How can I detect a duplicate post (like on stackoverflow)?
Should I select everything from the database and check if the submitted post is like a one before. (I want to post the duplicate alert on the article page as the first comment)
Any help appreciated.
Thanks...

A:

Create an unique ID, e.g. with uniq_id(), put it in a hidden field within your HTML form, then save it in the database in a field that is set to UNIQUE. When the INSERT operation fails, you know that the POST has already been sent before.


Q:

post Notification Delayed

I'm trying to post Notifications via AlarmManager delayed. For this purpose I created an AlarmReciever which currently looks like this:
public class NotificationAlarmReciever extends BroadcastReceiver{

public static final String TAG = "NotificationAlarmReciever";

public static final String KEY_NOTIFICATION_EXTRA = "NotificationExtra";
public static final String KEY_NOTIFICATION_ID = "NotificationId";

@Override
public void onReceive(Context context, Intent intent) {
    LogCat.d(TAG, "AlarmReciever Triggered");
    LogIntent(intent);
    Bundle b = intent.getExtras();
    if (b != null){
        if (b.containsKey(KEY_NOTIFICATION_EXTRA)){
            Notification n = b.<Notification>getParcelable(KEY_NOTIFICATION_EXTRA);
                    int request = 100
                    if(b.containsKey(KEY_NOTIFICATION_ID)){
                        request = b.getInt(KEY_NOTIFICATION_ID)
                    }
            NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(request, n);
        }
    }
}

private void LogIntent(Intent intent) {
    //logs Intent....

}
}

I created a TestActivty where I try to start an Alarm like this:
public void onClick(View v) {
            Context c = getApplicationContext();
            int requestCode = 333;

            Notification notification = new Notification(R.drawable.balloon_overlay_close,"ticker", System.currentTimeMillis() + Integer.parseInt(mWhen.getText().toString()));
            Intent notificationAction = new Intent(c, TestActivity.class);
            PendingIntent notificationPendingOperation = PendingIntent.getActivity(c, requestCode, notificationAction, 0);
            notification.setLatestEventInfo(c, "HEADER", "MESSAGE", notificationPendingOperation);

            AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            Intent alarmIntent = new Intent(c, NotificationAlarmReciever.class);
            alarmIntent.putExtra(NotificationAlarmReciever.KEY_NOTIFICATION_EXTRA, notification);
            PendingIntent alarmOperation = PendingIntent.getBroadcast(c, requestCode, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Line 127
            alarmManager.set(requestCode, notification.when, alarmOperation);
}

as soon as alarmManager.set is called I get a NullPointerException saying:
08-01 16:37:15.592: ERROR/AndroidRuntime(4422): FATAL EXCEPTION: main
08-01 16:37:15.592: ERROR/AndroidRuntime(4422): java.lang.NullPointerException
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at android.os.Parcel.readException(Parcel.java:1328)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at android.os.Parcel.readException(Parcel.java:1276)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at android.app.IAlarmManager$Stub$Proxy.set(IAlarmManager.java:174)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at android.app.AlarmManager.set(AlarmManager.java:139)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at de.eos.uptrade.android.core.TestActivity$1.onClick(TestActivity.java:127)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at android.view.View.performClick(View.java:2485)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at android.view.View$PerformClick.run(View.java:9080)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at android.os.Handler.handleCallback(Handler.java:587)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at android.os.Looper.loop(Looper.java:130)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at android.app.ActivityThread.main(ActivityThread.java:3683)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at java.lang.reflect.Method.invokeNative(Native Method)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at java.lang.reflect.Method.invoke(Method.java:507)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-01 16:37:15.592: ERROR/AndroidRuntime(4422):     at dalvik.system.NativeStart.main(Native Method)

I dont know, what I am doing wrong.

A:

Take a look at AlarmManager.set(...) documentation.
There you can see that the first parameter 'type' cannot be 333. It can be set to either ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC or RTC_WAKEUP, which correspond to the integer values 3, 2, 1 and 0. Those are your choices.


Q:

Building JSON requests dynamically in Java

I'm creating a client that can send different requests to a server. Part of my goal is to not have any large dependencies.
A request can look as following:
{
  "method": "getUser",
  "methodParameters": {
    "a": "b",
    "c": "d",
    "e": "f",
    "data": {
      "u": "v",
      "x": "y"
    }
  },
  "version": "1.3"
}

The content of the data object is different for every type of request method.
My question is, what would be the best "Java-way" to build these JSON requests dynamically?
So far I've only come up with a couple alternatives that I don't think is the best way to do it..
Example 1
Just a normal POJO with some set/getters and a SimpleJSON object.
public class MethodOne {
    JSONObject data = new JSONObject();

    private void setX(String x) {
        data.put("x", x);
    }

    private String getX() {
        return (String) data.get("x");
    }

    private void setY(String y) {
        data.put("y", y);
    }

    private String getY() {
        return (String) data.get("y");
    }
}

Example 2
public class RequestData {
    public JSONObject methodOne(String x, String y) {
        JSONObject data = new JSONObject();
        data.put("x", x);
        data.put("y", y);
        return data;
    }

    public JSONObject methodTwo(String a, String b) {
        JSONObject data = new JSONObject();
        data.put("a", a);
        data.put("b", b);
        return data;
    }
}

So what do you think. Is any of the above solutions better for the job, or is there a third solution that I have yet to come up with? Thanks.

A:

Note your example 1 is not a POJO, it's a wrapped JSONObject.
GSON can be used with a true POJO:
class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  //setters/getters optional
}

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);

There is also a getAsJsonObject method if you need that rather than a String. See also https://stackoverflow.com/a/13434887/360211 about that.


Q:

I want to get the time of starting an application

The time is displayed in Logcat,
and I want to get it by codes because Logcat doesn't always display the time.
Any of the ways of solving it will be acceptable
Thanks and Regards,

A:

Yon can try something like this:

At the start of the code you want to measure, add

int start = System.currentTimeMillis();
  This gives you start point

At the end of the code to measure, add

int end = System.currentTimeMillis();

int duration = end - start; // That is duration you need.

Now you may append duration to file, post it to some service or do what ever you want to do with it...


Q:

thread onterminate - help writing the event

Using Delphi-v5 and a component (TmFileScan -- thanks Mats) that runs in a thread and I want to be able to Terminate the thread gracefully. After a lot of searching and reading here, I have been able to Terminate it but I need an Event to handle some screen-clean up after an Abort.
In the Thread I have added
while not(Terminated) do // Iterating about a zillion times :)
  ...

Then in the app...
Button1Click...
begin
  SearchThread.Terminate;
end;

and it works nicely. I have the screen clean up in the existing OnReady event which is fired when the thread has completed normally. But it is never seen if the Thread was Terminated so I need to add an OnAbort event to the component.
Could someone please give me a code snippet for that event. There are Pause and Resume events in the Component but no Abort.
Thank you.

A:

The TThread class has an OnTerminate event available.  It is triggered by the virtual TThread.DoTerminate() method, which is called after Execute() exits, regardless of whether Execute() exits normally or via an uncaught exception.  I would suggest overriding DoTerminate() and have it trigger the OnAbort event if the Terminated property is True or the FatalException property is not nil, and to trigger the OnReady event otherwise.
Update: Assuming you are using this TmFileScan component, then I suggest you make the following modifications so the OnReady event is always triggered:
TSearchThread = class(TThread)
private
  ...
protected
  ...
  procedure DoTerminate; override; // <-- add this
public
  destructor Destroy; override; // <-- add this
end;

constructor TSearchThread.Create(Owner: TmFileScan; SubDir, Started: Boolean;
  FilePaths, Filter: TStrings; fOnFileFound: TOnFileFoundEvent;
  fOnReady: TOnReadyEvent);
begin
  inherited Create(true);
  ...
  ffList := TStringList.Create; // <-- add this
  ...
  Resume;
end;

// add this
destructor TSearchThread.Destroy;
begin
  ffList.Free;
  inherited Destroy;
end;

procedure TSearchThread.Execute;
var
  ...
begin // function FindFile
  // remove this
  {
  ffList:= TStringList.Create;
  try
    while not Terminated do
    begin
  }
      for q:= 0 to ffPaths.Count - 1 do
      begin
        if Terminated then Break; // <-- add this
        for n:= 0 to ffFilters.Count - 1 do
        begin
          if Terminated then Break; // <-- add this
          Spec:= ffFilters[n];
          RFindFile(BackSlashFix(ffPaths[q]));
        end;
      end;
  // remove this
  {
      Synchronize(Ready); // <-- remove this
      Terminate;
    end;
  finally
    ffList.Free;
  end;
  }
end;

// add this
procedure TSearchThread.DoTerminate;
begin
  Synchronize(Ready);
  inherited;
end;


Q:

Finding covariance using the expectation values using E(XY)

We choose numbers from {2, 3} by tossing a fair coin; the coin
is tossed twice. Choose 2 if the coin turns up Heads and 3 if the coin is Tails. So
the possible outcomes are {(2, 2),(2, 3),(3, 2),(3, 3)}. Let X be the first number
chosen (so X ∈ {2, 3}) and let Y be the product of the two chosen numbers. Compute the covariance
Cov(X, Y).
So I know the formula for covariance is Cov(X,Y) = E(XY)-E(X)E(Y).
I have worked out E(X) = 2P(X=2) + 3P(X=3) = 2.5
E(Y) = 4P(X=4) + 6P(X=6) + 9(X=9) = 6.25
However I am confused as to how to find E(XY)?

A:

Well, you do the same analysis: $XY$ can possibly be $8$, $12$, $18$ and $27$, so
\begin{align}
\mathbb{E}(XY) &=8\mathbb{P}(XY=8)+12\mathbb{P}(XY=12)+18\mathbb{P}(XY=18)+27\mathbb{P}(XY=27)\\
&= \frac{8+12+18+27}{4}\\
&= \frac{65}{4}
\end{align}


Q:

Script not starting on boot with start-stop-daemon

My script (located in /etc/init.d) is creating a pid file ($PIDFILE), but there is no process running. My daemon script includes:
start-stop-daemon --start --quiet --pidfile $PIDFILE -m -b --startas $DAEMON --test > /dev/null || return 1

The script works fine when executing it manually.

A:

You need to create startup links.
sudo update-rc.d SCRIPT_NAME defaults

then reboot. SCRIPT_NAME is the name of the script in /etc/init.d (Without the path)

A:

Was able to get it working, but tried so many things, don't know exactly what fixed it (probably an error in script or config). However, learned a lot and wanted to share since I can't find much of the same in the internet abyss.
It seems Ubuntu (and many other distros based on Ubuntu, including Mint) has migrated to Upstart for job and service management. Upstart includes SysVinit (using /etc/init.d daemons) compatibility that still can use update-rc.d to manage daemons (so if you are familiar with that usage, you can keep on using it). The Upstart method is to use a single .conf file in the /etc/init folder. My SCRIPT.conf file is very simple (I'm using a python script):
start on filesystem or runlevel [2345]
stop on runlevel [016]

exec python /usr/share/python-support/SCRIPT/SCRIPT.py

This simple file completely replaces the standard script in /etc/init.d with the case statement to provide [start|stop|restart|reload] functions and the pointer to /usr/bin/SCRIPT. You can see that it includes runlevel control that would normally be found in the /etc/rc*.d files (thus eliminating several files).
I tried update-rc.d to create the necessary /etc/rc*.d/ files for my daemon. My daemon bash script is located in /etc/init.d and includes the start-stop-daemon command as in my original question.  (That command also works fine from terminal.)
I had /etc/rc*.d/ files, the bash script in /etc/init.d and /etc/init/SCRIPT.conf file during boot and it seems that Upstart likely first looks for the .conf file for its direction because the SysVinit command service SCRIPT [start|stop|restart|reload] returns Unknown Instance, however you can find the process is running with ps -elf | grep SCRIPT_FILE.
One interesting thing to note is the forking of your daemon when using .conf. The script as written above only spawns one fork of the daemon. However, total independence of the original script is possible by using expect fork or expect daemon and respawn (see the Upstart Cookbook for reference). Using these will ensure that your daemon will never be killed (at least by using the kill command).
I continued to test both my daemon and the boot process by utilizing the sudo initctl reload-configuration command. This reloads the conf files where you can test your daemon by the sudo [start|stop|restart] SCRIPT command. The result of the start command is:
$ sudo start SCRIPT
SCRIPT start/running, process xxxx

$ sudo restart SCRIPT
SCRIPT start/running, process xxxx

$ sudo stop SCRIPT
SCRIPT stop/waiting

Also, there is a nice log in /var/log/upstart/SCRIPT.log that gives you useful information for your daemon during boot. Mine still has a very annoying bug that prevents root from displaying osd messages with notify-send from my daemon. My log file includes a gtk warning (I will open another question to solicit help).
Hope this helps others in developing their daemons.


Q:

Azure blob storage: Unable to upload the blob with size 0

Our applicaiton has a requirement to upload the blob with size 0.
We are using cURL to invoke Azure storage REST API.
While uploading with size it failing with HTTP error code [400]
Following error message it returned

<?xml version="1.0" encoding="utf-8"?>
    <Error>
           InvalidHeaderValue
           <Message>
                  The value for one of the HTTP headers
                  is not in the correct format.
                  RequestId:2b1ec18b-0001-007d-7811-e40725000000
                  Time:2016-07-22T12:07:28.5435467Z
          </Message>
          <HeaderName>Content-Length</HeaderName>
          <HeaderValue>-1</HeaderValue>
          </Error>

Through wireshark, we ensured that, the value of content length header is sent appropriatly.
Following are the captured headers from wireshark

PUT /test/DC70439C-5004-11E6-B4B2-91D87435845D HTTP/1.1
Host: mytest.blob.core.windows.net
Accept: */*
Transfer-Encoding: chunked
x-ms-blob-type:BlockBlob
x-ms-version:2015-02-21
Content-Length:0
x-ms-date:Fri, 22 Jul 2016 12:07:28 GMT
Authorization:SharedKey   kanchan:HQQ7a47TPQtEhL0ek6rim64ZKC8NRubgKuq+4Os+Aoo=
Expect: 100-continue

Can you plese help to figure out why content-length header value has been set as -1?
Thanks and regards,
Rahul Naik

A:

I didn't reproduce your issue. The following is my tested code using cURL to upload file to Azure blob storage. It works on my side, and I can upload a file of size 0(set file content as ""). Hope this could give you some tips.
storage_account="<account name>"
container_name="<container name>"
access_key="<account key>"
content="<file content>"
len=${#content}
blobname="<blob name>"
blob_store_url="blob.core.windows.net"
authorization="SharedKey"
request_method="PUT"
request_date=$(TZ=GMT date "+%a, %d %h %Y %H:%M:%S %Z")
storage_service_version="2011-08-18"
# HTTP Request headers
x_ms_date_h="x-ms-date:$request_date"
x_ms_version_h="x-ms-version:$storage_service_version"
# Build the signature string
canonicalized_headers="x-ms-blob-type:BlockBlob\n${x_ms_date_h}\n${x_ms_version_h}"
canonicalized_resource="/${storage_account}/${container_name}/${blobname}"
string_to_sign="${request_method}\n\n\n${len}\n\napplication/x-www-form-urlencoded\n\n\n\n\n\n\n${canonicalized_headers}\n${canonicalized_resource}"
# Decode the Base64 encoded access key, convert to Hex.
decoded_hex_key="$(echo -n $access_key | base64 -d -w0 | xxd -p -c256)"
signature=$(printf "$string_to_sign" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$decoded_hex_key" -binary |  base64 -w0)
authorization_header="Authorization: $authorization $storage_account:$signature"

curl \
  -X PUT \
  -H "$x_ms_date_h" \
  -H "$x_ms_version_h" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -H "$authorization_header" \
  -H "x-ms-blob-type:BlockBlob" \
  -d ${content} "https://${storage_account}.${blob_store_url}/${container_name}/${blobname}"


Q:

How to convert a UTC time to local time

Hi I am delivering a UTC time from the server to the client's browser. The time shows up correctly but the timezone does not. Here is how the time is showing up:

Tue Jul 15 2014 19:35:00 GMT-0500

The date and time are correct but the time zone is not. I just want to change the GMT -0500 to UTC. When I change it to UTC then I can convert it to local time.

A:

Even though you're receiving a UTC time, the javascript object will always show up as the local time in the console. For example:
var date = new Date(1405458751062);

Outputs this for me:
Tue Jul 15 2014 17:12:31 GMT-0400

You have to take that date object and output the specific properties.
For example in UTC:
date.getUTCFullYear() + "-" + (date.getUTCMonth() + 1) + "-" + date.getUTCDate() + " " + date.getUTCHours() + ":" + date.getUTCMinutes();

Outputs:
2014-7-15 21:12

Or local time:
date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes();

Outputs:
2014-7-15 17:12

To me it seems like you are parsing in your date incorrectly because 19:35 hasn't come around yet. You need to make sure your date is parsed correctly so that when you output the date object to the console (ex. console.log(date)), it will display the date in your browser's local time. From there you must format the date properly in UTC using a method similar to above.

I would suggest using Moment.js though. It makes life easy:
var date = moment(1405458751062);
date.toString();         // returns Tue Jul 15 2014 17:12:31 GMT-0400
date.utc().toString();   // returns Tue Jul 15 2014 21:12:31 GMT+0000
date.local().toString(); // returns Tue Jul 15 2014 17:12:31 GMT-0400

The library makes it very easy to format dates as well.


Q:

Molar heat of fusion of ice?

The molar heat of fusion of ice is 6.01 kJ/mol.
Can you explain what this means? What I think it means is that it requires 6.01 kJ to melt a mole of ice. I'm not positive though..

A:

Your interpretation is correct.
The molar heat of fusion is the amount of heat necessary to melt a mole of ice at its melting (or freezing) point. That means, to get 1 mole of water from 1 mole of ice at its melting point (0 degrees Celsius) it would require an input of $6.01\ \mathrm{kJ}$.
The conceptual reasoning is that it requires so much energy to break the bonds and allow more motion (but not completely).
Conversely, $6.01\ \mathrm{kJ}$ would be released upon the freezing of water at that point (1 mole of water anyway).


Q:

What is the best practice for capturing all inner exception details?

What is the best practice for logging complete exception details including all possible inner exceptions?
Currently, I use the following code:
try
{
    //some code that throws an exception
}
catch(Exception ex)
{
    do
    {
        Console.WriteLine(ex.Message+ex.StackTrace);
        ex=ex.InnerException;
    }while(ex!=null)
}

Are there any scenarios where this code may fail?

A:

Have you tried  just using ex.ToString()?  It gives most (if not all) of the data you need to diagnose - including the message details, stack trace, and inner exceptions:
From MSDN:

ToString returns a representation of the current exception that is
  intended to be understood by humans. Where the exception contains
  culture-sensitive data, the string representation returned by ToString
  is required to take into account the current system culture. Although
  there are no exact requirements for the format of the returned string,
  it should attempt to reflect the value of the object as perceived by
  the user. The default implementation of ToString obtains the name of
  the class that threw the current exception, the message, the result of
  calling ToString on the inner exception, and the result of calling
  Environment.StackTrace. If any of these members is null, its value is
  not included in the returned string.

A:

I have this extension method which suits my purposes just fine.
public static class ExceptionExtensions {
    public static string ToMessageAndCompleteStacktrace(this Exception exception) {
        Exception e = exception;
        StringBuilder s = new StringBuilder();
        while (e != null) {
            s.AppendLine("Exception type: " + e.GetType().FullName);
            s.AppendLine("Message       : " + e.Message);
            s.AppendLine("Stacktrace:");
            s.AppendLine(e.StackTrace);
            s.AppendLine();
            e = e.InnerException;
        }
        return s.ToString();
    }
}

And use it like this:
using SomeNameSpaceWhereYouStoreExtensionMethods;
try {
    // Some code that throws an exception
}
catch(Exception ex) {
    Console.WriteLine(ex.ToMessageAndCompleteStacktrace());
}

Update
Since I'm receiving upvotes for this answer I want to add that I stopped using this extension method, and now I'm just using exception.ToString(). It gives more information. So please, stop using this method, and just use .ToString(). See the answer above.


Q:

How to check if class has methods added by aspect?

Suppose I have a simple class:
public class TestClass {
   /*...*/
}

I created an aspect which injects new method to this class:
public aspect TestAspect {
    public void TestClass.aspectMethod() {
        /*...*/
    }
}

Now, how can I check if TestClass has method added by TestAspect in runtime?

A:

The simplest way would be to simply reflect on the class:
TestClass.class.getDeclaredMethod("aspectMethod")

which will throw NoSuchMethodException if it isn't there.  Or if you have the bytes you could use a byte code visitor to check what methods exist in the byte code - but the reflective route would be less messing around.


Q:

PrimeNg Upgrade - Button.html:2 ERROR Error: Cannot find a differ supporting object 'float: left;'

I just started upgrading a project to primeNg 8.1.1 and it seem in-line style tags on buttons are no longer supported...
I'm getting the following error in all my buttons which have style='float:left:
Button.html:2 ERROR Error: Cannot find a differ supporting object 'float: left;'
    at KeyValueDiffers.find (core.js:28471)
    at NgStyleR2Impl.setNgStyle (common.js:5884)
    at NgStyle.set ngStyle [as ngStyle] (common.js:6161)
    at updateProp (core.js:32189)
    at checkAndUpdateDirectiveInline (core.js:31867)
    at checkAndUpdateNodeInline (core.js:44367)
    at checkAndUpdateNode (core.js:44306)
    at debugCheckAndUpdateNode (core.js:45328)
    at debugCheckDirectivesFn (core.js:45271)
    at Object.eval [as updateDirectives] (Button.html:2)

this works fine on the previous version 8.0.3
I tried a few different formats for the in-line styling but still had no luck
this is the usual tag causing the issue:
<p-button (onClick)="clickRefresh()"
          icon="pi pi-refresh"
          label="Refresh"
          style="float: left;"
          styleClass="ui-button-secondary"
></p-button>

A:

Now you must change string to objects，I think this is a break change.
https://github.com/primefaces/primeng/commit/b774ab2a5811b223c49dcef55ba84bcbcfa09579
<p-button (onClick)="clickRefresh()"
          icon="pi pi-refresh"
          label="Refresh"
          [style]="{float: 'left'}"
          styleClass="ui-button-secondary"
></p-button>


Q:

Answer was deleted - how can I challenge the reason?

I had an answer deleted with the reason given that it "didn't answer the question" which I disagree with.  Is there a way I can respond/chat with the person who deleted it to question their reasoning?  Comments are disabled.
The question I attempted to answer has two parts: is "this data correct" and "does it contradict a belief".  If the answer to the first part is 'no' then the second part is irrelevant.  All the answers I saw address the first part (one stands out) and say basically 'yes'.  None seem to address the second piece.  They more or less just say "no" without explaining why the fact that data doesn't contradict the belief.  This is a logical question and it's not clear to me what kind of references are relevant to a logical argument.

A:

I am not the mod ...in question, but I can probably give you my impression on why your answer was deleted.
On this site we have basically two major problems that we need to solve in order for the community to be functional:

We need questions to be based on specific, evidence based, largely believed claims
We need answers to be based on evidence.

The first requirement is to avoid wasting time, but also to avoid "how many angels can fit on a pin" kind of questions. Many controversial topics are controversial because they are hard to debate, and because the debate becomes an argument on personal values and beliefs and not on measurable facts.
Requiring the questions to be about factual, disprovable claims allows a fair way of judging answers -- by requiring them to present evidence, we can judge how convincing that evidence is, instead of focusing on the pure "truthiness" of the answer, which in many cases is a matter of opinions.
In this particular case, I agree that the claim is pointless: showing high CO2 in the past is irrelevant, it's cherry picking. But -- is it also a lie? That's what the question is about, the facts. A perfect answer would bring in evidence that the facts are true, but also that their truthiness is irrelevant, not because of logic, but bringing in the climate science context that shows their irrelevance. At a minimum, though, we expect a verification of the facts asked about -- your answer did not do that, but delegated it to DavePhd's answer and added common-sense based commentary to it.
This seems to be a valid reason to remove it, given how the site works.


Q:

"Falling forces"

First, I'm completely ignorant in physics, that's why I need your help and I'm sorry if I don't have a proper technical language.
I was trying to understand the forces that play a role during a fall when climbing. In particular, the carabiners indicate the maximum force in kilo-Newtons ($kN$) a carabiner can carry before break (e.g. $22 kN$).
Reading on Wikipedia I understood (I think) how to calculate the force ($N$) of my body.
$$1 kg = 9.81 N$$
$$75 kg * 9.81 N/kg = 735.75 N = 0.736 kN$$
Now I know that my body, if I stand on Earth, has a weight of $0.736 kN$. This is nice but not really useful to me, because what I want to calculate is the force on the carabiner if my body is in free fall for, for example, 6 metres.
Can anyone teach me the topics I need to know and help me to understand how to find the proper formula? Thanks!

A:

As first approximation a person falling in climbing is subjected to
$$
F_{stop} = \sqrt{2*g*m*k*\frac{Q}{L}}
$$
where k represents the elasticity of the rope, Q is length of the fall and L the length of the rope.
The carabiner will be subjected to a force equal to $2F_{stop}$.
In case of perfectly vertical fall and no friction.
Have in mind that 22kN is not a random choice but is twice the maximum force a human body can absorb without major damages... carabiners are designed to break at 22kN.
You should find out the derivation of the formula in this article:
W. Dan Curtis. Taking a Whipper – The Fall-Factor Concept in Rock Climbing, The College Mathematics Journal, March 2005, Vol. 36, No. 2


Q:

can anyone translate this language please? what Language is it?

Can anyone please translate the text in this image please, I have no clue where to start?

A:

The language is Kazakh. It's a fragment of a poem by Шал (Тілеуке) Құлекеұлы aka Шал ақын (1748 – 1819):
Бұл дүниенің мысалы
Ұшып өткен құспен тең.
Өмірде көрген жақсылық
Ұйықтап өткен түспен тең.
Атадан мирас ақылың,
Түзік айтқан мақұлың,
Ләзім болған іспен тең.
Үлкеннен көрген зорлығың,
Жаманнан көрген қорлығың
Ойлап тұрсаң, бозбала,
Дұшпаннан көрген күшпен тең.
Ағайының көп болса,
Бірлігі оның бек болса,
Жамандық жер кез келсе,
Бір-біріне сеп болса,
Бүтін тұрған бұзылмай,
Отыз екі тіспен тең.
That's how Google translates it:
An example of this world
It is equal to the birds that fly.
Goodness in life
It is the same as sleeping color.
From the Father to Your Majesty,
The verdict,
It is equal to the pleasure.
Your aggression from the eldest,
It's a bad idea
Wait, boy,
Equal to the force seen by the enemy.
If he has a big brother,
If his unity is firm,
When a wicked person comes to an end,
If you sow each other,
Without a break,
Thirty-two teeth are equal.
Here's the audio for the whole poem.


Q:

How to recognise when it is appropriate to code CSS

I am working on a custom CSS file within a wordpress theme installation.
Within the CSS, there are times when I need to identify something like '.example', other times when it must be displayed as '#example' and other times when it is fine to keep it as 'example'.
Could someone please clarify the rules and how I can distinguish and decide for myself in the future which one to use in each instance?
This might have something to do with div ids and classes.

A:

There is no 100% rule but generally:
An id must be unique, therefore any styles applied to an ID are only usable for the one element on the page. Therefore it usually makes more sense to style by class rather than ID because the mjority of the time you are going to want to reuse your styles. Additionally using an ID makes it harder to override the style later because id's hijack specificity.
I even take this one step further in that nothing should EVER be styled by ID but rather always styled by class. The one exception i occasionally make is for page-level scoping based on the id of the body tag. But even then a class is just as useful.
Id recommend reading up on OOCSS (note: i dont use any of the files used to illustrate the examples - im solely referencing the FAQ)


Q:

Group ListView by a component on a JSON in Xamarin.Forms

I'm trying to group items from a JSON in the ListView.
My JSON is stored in an web repository, I already pulled it from the server and listed it but ungrouped.
I've read a lot of tutorials about how to group C# List but none of them solved my problem.
Here's the JSON:
[
  {
    "status": "Status 1",
    "erpCode": "1901",
    "name": "Name 1",
    "statusReportDate": "24/08/2018",
    "statusReportDescription": "Description 1"
  },
  {
    "status": "Status 2",
    "erpCode": "2160",
    "name": "Name 2",
    "statusReportDate": "24/08/2018",
    "statusReportDescription": "Description 2"
  },
  {
    "status": "Status 2",
    "erpCode": "543",
    "name": "Name 3",
    "statusReportDate": "24/08/2018",
    "statusReportDescription": "Description 3"
  }
]

My method that pull the JSON from a web repository and convert it to a List and ObservableCollection:
protected async void OnGetList()
{
    if (CrossConnectivity.Current.IsConnected)
    {

        try
        {
            //Getting JSON data from the Web
            var content = await _client.GetStringAsync(Url);

            //We deserialize the JSON data from this line
            var list = JsonConvert.DeserializeObject<List<Company>>(content);

            //After deserializing , we store our data in the List called ObservableCollection
            ObservableCollection<Company> collection = new ObservableCollection<Company>(list);
            myList.ItemsSource = collection;

        }
        catch (Exception ey)
        {
            Debug.WriteLine("" + ey);
        }
    }
}

XAML ListView:
<ListView x:Name="myList"
                  HasUnevenRows="True"
                  ItemSelected="MyList_ItemSelected">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal" Margin="5" HorizontalOptions="Fill">
                    <Button Text="{Binding erpCode}"/>

                    <StackLayout HorizontalOptions="Fill">
                        <Grid>
                            <Label Text="{Binding name}"/>
                            <Label Text="{Binding statusReportDate}"/>
                        </Grid>
                        <Label Text="{Binding statusReportDescription}"/>
                    </StackLayout>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

I want to group it by "status" and print something like this:
Status 1
Name 1
Status 2
Name 2
Name 3
Status N
Name n1
Name n2
Name n3
...

A:

Check out this article: https://xamarinhelp.com/xamarin-forms-listview-grouping/
But better to use ObservableCollection, where the above article uses List.
So you have to create an ObservableCollection of a type that is a subclass of ObservableCollection.
First create a type that subclasses ObservableCollection that will hold one group of companies by status:
public class CompanyByStatusList : ObservableCollection<Company>
{
    public string Status { get; set; }
    public ObservableCollection<Company> Companies => this;
}

Then create an ObservableCollection of CompanyByStatusList. This will be your ItemsSource for your ListView.
public ObservableCollection<CompanyByStatusList> CompanyList { get; set; }

Then you want to create a CompanyByStatusList for each status that holds all of the companies in that specific status, and then add each of those CompanyByStatusList to the CompanyList collection. Make sure to set the Status property of each CompanyByStatusList
And make sure to set IsGroupingEnabled="true" on your ListView. ListView xaml:
<ListView ItemsSource="{Binding CompanyList}"
      IsGroupingEnabled="true"
         HasUnevenRows="true">
    <ListView.GroupHeaderTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding Status}" />
            </ViewCell>
        </DataTemplate>
    </ListView.GroupHeaderTemplate>

    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal" Margin="5" HorizontalOptions="Fill">
                    <Button Text="{Binding erpCode}"/>

                    <StackLayout HorizontalOptions="Fill">
                        <StackLayout Orientation="Horizontal">
                            <Label Text="{Binding name}"/>
                            <Label Text="{Binding statusReportDate}"/>
                        </StackLayout>
                        <Label Text="{Binding statusReportDescription}"/>
                    </StackLayout>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>


Q:

Using QProcess to read standard output

In my QT widget application I am attempting to run a shellscript that opens a C++ program and provides inputs to the program as well. The program starts a command prompt that requires the users input to start. Once the program is started the output of the program is redirected via the standard output to a text file. I am attempting to use QProcess to open and run this shellscript, then read the standard output that is being used to print the result of the C++ program to the text file. The shell script only runs this process and does not terminate it. This is because I need to continuously read this output into the GUI as the program is running. It will not be sufficient to wait until the program is finished to read this information. I am fairly new to QT and C++ programming. I was hoping that someone could help me with my implementation of this.
QProcess process;
process.start("/home/pi/Desktop/ShellScripts/RunTutorial3.sh");
QString output =process.readAllStandardOutput();
qDebug() << output;
QString err = process.readAllStandardError();
qDebug() << err;

I have experimented with using other read function such as readline and also trying to start the process as a detatched process. I have not had success with any of my experimentations. Is it possible to do what I am attempting in QT. I just need the program to run continuously and for QT to read this output every so often.
Shell script:
#!/bin/bash
cd
cd Desktop
cd tutorial3App
cd bin
echo "start" | ./tutorial3

C++ code: I need the meanTOE value to be captured in standard output to use in my GUI.
/ Calculate average time to end of discharge
            double meanToE = std::accumulate(ToESamples.begin(), ToESamples.end(), 0.0)/ToESamples.size();
            file << ": EOL in " << meanToE << " s" << std::endl;

A:

As I said in my comments one of the main problems is that when you run tutorial3 that process is separated so you can not get the output. Therefore, I recommend executing it directly, and QProcess is probably a local variable, eliminating after printing an empty text, a possible solution is to create a pointer. Another improvement would be to use the readyReadStandardOutput and readyReadStandardError signals since the impressions are not automatic.
QProcess *process = new QProcess(this);

connect(process, &QProcess::readyReadStandardOutput, [process, this](){
    QString output =process->readAllStandardOutput();
    qDebug() << "output: "<< output;
});

connect(process, &QProcess::readyReadStandardError, [process](){
    QString err = process->readAllStandardError();
    qDebug() << "error: "<<err;
});

process->setWorkingDirectory("/home/pi/Desktop/tutorial3App/bin/")
process->start("tutorial3", QStringList() << "start");


Q:

Any tweaks after installing lubuntu?

I have recently installed lubuntu and want some software to make it run smoothly.Also, after i installed lubuntu, i saw no grub image (it seems bad without image) So, Please tell me how to set  grub image

A:

First update your system , so that It will let you install updates.
sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade

To play MP3 songs you might need some codecs , so
sudo apt-get install lubuntu-restricted-extras

Open Ubuntu Software Center and Look for VLC Media Player.
For Having better Battery you can use tlp.
sudo add-apt-repository ppa:linrunner/tlp
sudo apt-get update
sudo apt-get install tlp

To change GRUB background , you can use Grub Customizer
sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer


Q:

Nuget Install-Package successful but no reference added to csproj

I've got a bunch of projects in the same solution, which have project dependencies all correctly set between them (when nedded, obviously). There is one project whose DLL has no dependencies to any other project of the same solution (let's name it My_First_Dll.dll). I created Nuget packages for all DLLs successfuly.
Now when I go into package manager console in my test project where I want to add certain references created from the first solution, for example My_Dependent_Dll, I type Install-Package MyNamespace.My_Dependent_Dll. Nuget says it gets the DLL, and I can see it in the packages folder created on my solution folder, in the packages.config file created in my solution, in the references list of the project and even editing the csproj I can see the reference with hintpath. So everything's fine for My_Dependent_dll.
Problem: My_First_Dll.dll, which is referenced by My_Dependent_dll, according to the nuget output, is successfuly installed as well (as it should, bc it is referenced by My_Dependent_Dll), and the dll actually is downloaded to the packages folder and added to the packages.config. BUT My_First_Dll is not added to the references in the solution explorer, and is completly missing from the csproj. So it "doesn't exist" for Visual Studio.
None of the questions here helped me.

A:

[SOLVED]
Apparently nuget doesn't like dlls ending in .resources.dll. And guess what? My non_dependent_DLL had exactly that ending.
Reference:
on https://docs.nuget.org/create/nuspec-reference

NuGet does not add references to any dlls that end with '.resources.dll'

which lead me to the explanation in the following link
http://nuget.codeplex.com/discussions/280566
Hope it helps anyone with this problem.


Q:

Python, XP to Level converter

so im bassicly trying to convert a players XP into a level number, im just wondering if there is a more efficant way / neater way as this looks horrible and compared to something looks like it takes time as it had to run every elif. Cheers.
# XP to Level converter
    if self.xp >= "0":
        self.level = "Level 0"
    elif self.xp >= "1000":
        self.level = "Level 1"
    elif self.xp >= "3000":
        self.level = "Level 2"
    elif self.xp >= "5000":
        self.level = "Level 3"
    elif self.xp >= "7500":
        self.level = "Level 4"
    elif self.xp >= "10000":
        self.level = "Level 5"
    elif self.xp >= "13000":
        self.level = "Level 6"
    elif self.xp >= "15000":
        self.level = "Level 7"
    elif self.xp >= "20000":
        self.level = "Level 8"
    elif self.xp >= "25000":
        self.level = "Level 9"
    elif self.xp >= "30000":
        self.level = "Level 10"
    elif self.xp >= "35000":
        self.level = "Level 11"
    elif self.xp >= "41000":
        self.level = "Level 12"
    elif self.xp >= "47500":
        self.level = "Level 13"
    elif self.xp >= "52500":
        self.level = "Level 14"
    elif self.xp >= "60000":
        self.level = "Level 15"
    elif self.xp >= "68000":
        self.level = "Level 16"
    elif self.xp >= "76500":
        self.level = "Level 17"
    elif self.xp >= "85500":
        self.level = "Level 18"
    elif self.xp >= "95000":
        self.level = "Level 19"
    elif self.xp >= "105000":
        self.level = "Level 20"
    elif self.xp >= "115000":
        self.level = "MAX LEVEL"
    else:
        self.level = "Level Could Not Be Converted"

    print(self.level)

A:

You could use arrays for the levelpoints
xp = 7600

limit = [0,1000,3000,5000,7500,10000]
level = -1

for points in limit:
    if xp > points:
        level = level + 1
    else:
        break

print(level)


Q:

Segfault when assigning token pointer (from strtok) to pointer element of 2d VLA of structs

I'm attempting to parse a csv file and store those values in an 2d VLA.
The first codeblock shows the two calls I have to the function TokenizeLine which very simply uses strtok to break the line apart and assign the token to the appropriate cell in the array. The second block is the function in question.
  //Get first line of file then iterate through lines until
  //beginning comments are passed over
  fgets(currentLineStr, 8192, fileIn);
  while (currentLineStr[0] == '#')
        fgets(currentLineStr, 8192, fileIn);

  //Start adding values to array. current line held by currentLineStr
  //is assigned first
  TokenizeLine(currentLineStr, eTable, yIndex, x, y);

  yIndex++;
  while(fgets(currentLineStr, 8192, fileIn) != NULL)
  {
        TokenizeLine(currentLineStr, eTable, yIndex, x, y);
        yIndex++;
  }

Within the following function I'm getting a segfault when assigning the token pointer to the pointer contained in the eTable struct.
void TokenizeLine(int x; int y; char currentLineStr[], Entry eTable[x][y], int yIndex, int x, int y)
{
  char *tokPtr;
  int xIndex = 0;

  tokPtr = strtok(currentLineStr, "|");
 *** eTable[xIndex][yIndex].str = tokPtr;*** (error happening here)

  while(tokPtr != NULL)
  {
        tokPtr = strtok(NULL, "|");
        eTable[xIndex][yIndex].str = tokPtr;
        //printf("%s\n", eTable[xIndex][yIndex].str);

        xIndex++;
  }
}

Been stuck on this for a while any/all input appreciated and encouraged.

A:

You're not checking the return value of the first strtok() call.
Also, in your while loop you check whether tokPtr is NULL, but then update it in the first line of the loop body before using it.
You need remove the initial set of eTable[xIndex][yIndex].str, and move the second strtok() call to the end of the while loop:
  tokPtr = strtok(currentLineStr, "|");

  while(tokPtr != NULL)
  {
        eTable[xIndex][yIndex].str = tokPtr;
        //printf("%s\n", eTable[xIndex][yIndex].str);

        tokPtr = strtok(NULL, "|");
        xIndex++;
  }


Q:

How to printout a single line at time according to a schedule from an ArrayList?

I am trying to create a method that prints out a single line at a time, with two minutes delay between. How do I do that?.
This part of the code reads a text file (questionsFile) and creates an ArrayList:
public Broadcaster(Socket connection) throws IOException {

    read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    write = new PrintStream(connection.getOutputStream());

    List<String> questionsList = new ArrayList<>();
    try (Stream<String> questionsStream = Files.lines(Paths.get(questionsFile))) {
        questionsList = questionsStream
                .parallel()
                .collect(Collectors.toList());

    } catch (IOException w) {
        w.printStackTrace();
    }

Here bellow there is a timer but for some reason, I can't make it work. The whole ArrayList is printed out with no delay what so ever. My intention is to use a printStream but for testing purposes, the text is currently printed out to the console. How can the code be rewritten so it prints out a single line at a time?
    List<String> finalQuestionsList = questionsList;
    timer.schedule(task(() -> finalQuestionsList.forEach(System.out::println))
            , 120, TimeUnit.SECONDS.toMillis(1));
}

private TimerTask task(Runnable task) {
    return new TimerTask() {
        @Override
        public void run() {
            task.run();

A:

The trivial solution would be:
for (String question : questionsList) {
    timer.schedule(task(() -> System.out.println(question)), 0);
    try {
        sleep(2000);
    } catch (Exception ignored) {}
}


Q:

Is there a tool that reports on PKI health (CRL dates, expiry, etc)?

I'm looking for a tool that will walk the AIA tree from a leaf node and check all corresponding CRL dates and times.
Ideally it will also check versions and cross root trusts.
Does such a tool exist? If not, what is the closest I can get to that goal?

A:

Just to add my one cent.
I'm not aware of any such ready tools, however this feature was requested by a customer of mine some time ago. Eventually, I ended up with my own PowerShell solution for Windows. Here are two blog posts where I describe the behavior:

Enterprise PKI (pkiview.msc) PowerShell Edition (PoC)
Enterprise PKI health verifier, PowerShell Edition v1.5

Although, postings refer to Microsoft ADCS, there is a -Certificate parameter where you can pass arbitrary certificate.
Generally, the script does the following:

Prepare input certificate;
Execute chain for each certificate to select trusted anchors and to go through the chain;
Retrieve all Issuer URLs from AIA;
Validate each url (must be either http or ldap) and attempt to download the contents;
If contents is downloaded, verify whether it is a certificate;
Verify if the downloaded certificate is an issuer of the certificate in subject;
Validate other cert properties;
Extract URLs from CDP extension;
Validate each url (must be either http or ldap) and attempt to download the contents;
If contents is downloaded, verify whether it is a CRL;
Validate basic CRL properties, like validity (not yet valid, expired, about to expire);
Validate whether the CRL has valid signature (against CA certificate);
Do the same for DeltaCRLs;
Extract all OCSP URLs from AIA extension;
Validate OCSP response by sending OCSP request and processing response;
Compose status report (managed, I maintain report object and you can access report properties);
Repeat steps 3-16 for each subsequent certificate in the chain up to root certificate;
Compose summary report.

Not all you've requested (cross-certificates are not verified), but enough for a good start.
Where to get the latest version of the script? It is a part of my PowerShell PKI module. Download sources of the most recent release: https://pspki.codeplex.com/releases
you will need only three files:

Get-EnterprisePKIHealthStatus.ps1
PKI.Core.dll
SysadminsLV.Asn1Parser.dll

All files are digitally signed by me. If you concern about dlls, they are opensourced: PKIX.NET (PKI.Core.dll) and Asn1DerParser.NET (SysadminsLV.Asn1Parser.dll)
and the last, online help for PowerShell function: Get-EnterprisePKIHealthStatus.
HTH


Q:

Add multiple items for one orderid in MySQL database

I am trying to insert multiple items under one orderid into my database and I am stuck on how to do this.
My current db table structure:
order
orderid (auto increment)
productdesc
quantity

Current result in database (when items added from datagrid)
orderid   productdesc   quantity
1         test          1
2         value         2
3         demo          3

Desired result
orderid productdesc quantity
1       test        1
1       value       2
1       demo        3

Is there a way to add the multiple items for one orderid before the next order comes which means the orderid would be 2. Can someone point me in the right direction? Thank you

A:

You should add the items in a separate table, orderitems (or orderlines). The order table contains the main information about the order, and each item contains a product and it has an orderid that refers to the id of the main records. That orderid in orderitem is called a foreign key, because it refers to the primary key of another table.
orders
orderid   customer
(auto inc)
1         John Doe
2         Jane Doe
3         Jim Doe

orderitems
orderitemid orderid   productdesc   quantity
(auto inc)  (FK)
1           1         test          1
2           1         value         2
3           1         demo          3
4           2         test          2
5           3         demo          1
6           3         value         1

So, when you want to insert an order, you insert one main record in orders, and a product in orderitems. When inserting an item, you will need to specify the orderid it belongs to. The database cannot know by itself which order you meant. You can keep adding items to it, even after you've created a new order, as long as you know the orderid of the order you want to modify.
And you can get that id using MySQL's function last_insert_id. So the steps are:

Insert order
Get id of order
Insert item(s)

Then, to query all items for an order, you can query it like this:
select
  o.orderid,
  o.customer
  oi.orderitemid,
  oi.productdesc,
  oi.quantity
from
  orders o
  inner join orderitems oi on oi.orderid = o.orderid
where
  o.orderid = 1

Or, if you need just the items:
select
  oi.orderitemid,
  oi.orderid,
  oi.productdesc,
  oi.quantity
from
  orderitems oi
where
  oi.orderid = 1

It's a matter of preference whether you want to give the orderitems an id as well. I think it's good to give a table like that a surrogate key as well, but it's a matter of opinion.


Q:

Compensating for a one_for_one supervisor's inability to restart a child: tcp/ip port listeners

I have created a generic behavior that encapsulates tcp/ip functionality. All the user of the behaviour has to do is implement the callbacks that handle parsed "commands" that come from whatever is on the other side of the socket.
My generic behvour creates a port-listener process that listens on a port via gen_tcp:accept. When someone connects to the port, the port-listener asks a supervisor to spin-up a new port-listener while it goes on to handle the socket communication with whatever client just connected. Because each of these port-listeners / socket-handlers are dynamically created and identical, I am using a simple_one_for_one supervisor to create them. Standard stuff.
Here is my question. If the port-listening process dies, the entire behivour is non-functional since there will be nothing listening to the port. Becuase the port-listener is create by a simple_one_for_one supervisor, the supervisor cannot restart a new port_listener.
So, do I create a keep_alive process that monitors the "latest" port listener and asks the superviosr to start another one should it die? Or, is there some other best-practice for this type of case.
Also, is there a way to see/examine the process being created by this behavior? It is not an application, so appmon doesn't work here.
Thanks

A:

You probably could go on with only one listener process since you are always able to transmit the socket ownership to another process by means of
gen_tcp:controlling_process(Socket, Pid)

And then your listener will be able too.
Then you would not be forced to simple_one_for_one supervisor at the top level but one_for_one instead. Or what you think should fit better. The top level supervisor will then spawn listener process and acceptors supervisor with simple_one_for_one strategy. Then the listener will surely be restarted if goes down somewhy (and if you want to).
Further you may consult a cowboy project to see what approaches authors are using.


Q:

How to make iexfianace stock take an input from a form data?

I am trying to get stock price from iexfianance. When i try to run this i get ValueError: Please input a symbol or list of symbols.How do i make s=Stock() to take input from the form? I Tried to change the input into a string but that didn't work its already a string. Please Help!!
class InvestmentForm(Form):
    stockSymbol = StringField('Stock Symbol', validators=[InputRequired(), Length(min=2, max=5 ,message='Please Enter Correct
    symbol')])
    allotment = FloatField('Allotment', validators=[InputRequired()])
    finalSharePrice = FloatField('Final Share Price', validators=[InputRequired()])
    sellCommision = FloatField('Sell Commision',validators=[InputRequired()])
    initialSharePrice = FloatField('Initial Share Price', validators=[InputRequired()])
    buyCommission = FloatField('Buy Commission', validators=[InputRequired()])

@app.route("/",methods=['GET','POST'])
def index():
    form = InvestmentForm()
    userInput = form.stockSymbol.data
    s = Stock(userInput)
    print(s.get_price())
    return render_template('home.html',form=form)

A:

You have to submit the form input data, add a submit = SubmitField() in your InvestmentForm. Make sure you pass request.form in form = InvestmentForm(request.form) or just use Flask-WTF.
class InvestmentForm(Form):
    submit = SubmitField()

@app.route("/", methods=['GET', 'POST'])
def index():
    form = InvestmentForm(request.form)
    if request.method == 'POST' and form.validate():
        user_input = form.stockSymbol.data
        s = Stock(user_input)
        print(s.get_price())
return render_template('home.html', form=form)


Q:

Dangling Class on Viewmodel DisplayName not being used on LabelFor

I'm trying to get a display name for an inner class on my view model to be shown on labelfor.
However it only ever displays "Name" for DetailsTab.PrimaryContact.Name
I've tried changing the attribute to Display(Name = "") also but that doesn't seem to work.Everywhere I look they say that this should be working but i just cannot get it to work. Have I missed something?
Question: How do I get my inner property to use the displayname on the labelfor
public class CustomerDetailsData
    {
        [DisplayName("Name")]
        [StringLength(250)]
        public string Name { get; set; }
        [StringLength(250)]
        public string Logo { get; set; }
        [DisplayName("Tenant ID")]
        public string CustomerId { get; set; }
        public DetailsData DetailsTab { get; set; }
        public class DetailsData
        {
            [DisplayName("Industry")]
            [StringLength(250)]
            public string Industry { get; set; }
            [DisplayName("Team Count")]
            [StringLength(250)]
            public string TeamCount { get; set; }
            public PrimaryContactData PrimaryContact { get; set; }

            public class PrimaryContactData
            {
                [DisplayName("Primary Contact Name")]
                public string Name { get; set; }
                [DisplayName("Primary Contact Email")]
                public string Email { get; set;}
                [DisplayName("Primary Contact Phone")]
                public string Phone { get; set;}
            }
        }
    }

          @Html.LabelFor(model => model.DetailsTab.PrimaryContact.Name)

          @Html.DisplayFor(model => model.DetailsTab.PrimaryContact.Name)

A:

It seems as if my project wasn't building properly, I did a rebuild and it started to pick up  my DisplayName