text:
Q: Am I not understanding ArrayList or am I missing something? I'm trying to create a very, very simple program.
I want my class called Text to simply print out a string, specifically, one letter.
Then in my second class called Window, I want to create an ArrayList of that class, iterate through the list and call the method of my Text class to print out the string. But it does not print anything.
What am I doing wrong?
public class Text {

    private String a;

    public void printA() {
        a = "a";
        System.out.print(a);
    }

}

and the other class..
import java.util.ArrayList;

public class Window {

    private ArrayList<Text> string = new ArrayList<Text>(5);

    public Window() {
        addText();
    }

    public void iterate() {
        for (int i = 0; i < string.size() - 1; i++) {
            string.get(i).printA();
        }
    }

    public void addText() {
        for (int i = 0; i <string.size() - 1; i++) {
            string.add(new Text());
        }
    }

    public static void main(String[] args) {
        Window wind = new Window();
        wind.iterate();
    }

}

A: for(int i = 0; i <string.size()-1;i++){
    string.add(new Text());

}

initialy the arraylist is empty, so string.size() == 0
the forlus wil not be executed, change to
public void addText(){
     string.add(new Text())
}

or even better
public void addText(Text t){
     string.add(t)
}

that way you can add Text-object created with different constructors

A: If you modify iterate to:
public void iterate(){
    System.out.println(string.size()-1);
    for(int i = 0; i < string.size()-1;i++){
        string.get(i).printA();

    }
}

You will get -1
Let me explain why:
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. private ArrayList<Text>string = new ArrayList<Text>(5); merely sets the capacity of the underlying array that is the data structure that implement the ArrayList object. size() returns the number of objects inside of the ArrayList not the capcity
public void addText(){
    for(int i = 0; i <string.size()-1;i++){
        string.add(new Text());

    }
}

The for loop's expression doesn't evaluate to true, and therefore you never add a single object to the loop which is why iterate would print -1 if you added the print statement there

A: problem it this method.
public void addText(){
        for(int i = 0; i <string.size()-1;i++){
            string.add(new Text());

        }
    }

this doesn't add anything at all. because string.size() is 0.
may be you should change it to
public void addText(int size){
    for(int i = 0; i <size-1;i++){
        string.add(new Text());

    }
}

Ps: new Arraylist<Text>(5) actually creates an empty list with initial capacity = 5 (not size). See it here

A: The
new ArrayList<Text>(5);

Doesn't mean you have 5 elements array. It means that this is just initial capacity of internal array for storing elements. Due to this your init code:
public void addText(){
    for(int i = 0; i <string.size()-1;i++){
        string.add(new Text());

    }
}

faces no elements in the list with string.size() = 0.
Use this instead (If you like to add 5 elements):
public void addText(){
    for(int i = 0; i < 5;i++){
        string.add(new Text());

    }
}

There is no problem to add more elements (even if the initial capacity was only '5'). From docu "As elements are added to an ArrayList, its capacity grows automatically."

A: Well for stater your method in Text needs parameter so it KNOWS to take in 'a' and if you're variable in your parameter is going to be 'a' as well you need use "this." so that the compiler knows that the two are different.
public class Text {
private String a;

public void printA(String a) {
    this.a = "a";
    System.out.print(a);
}

}

A: What you are doing wrong is that you are creating the ArrayList with a capacity of 5, but it does not yet have 5 objects in it. Thus, the addText method does nothing. Here's a version that works:
public void addText(){
    for(int i = 0; i < 4; i++){
        string.add(new Text());
    }
}

Note that string.size() - 1 has been changed to 4, becuase string.size() is 0, and you want to add 4 elements to the list. Also, your iterate method could use a little refactoring:
public void iterate(){
    for(Text text : string){
        string.get(i).printA();
    }
}

Instead of a simple loop, an enhanced for is used instead. This is no more than a typing shortcut, but it improves efficiency for LinkedLists.


text:
Q: When did this "Great Siege" that the orcs talk about in this dialog happen? An extract from the Two Towers - The Choices of Master Samwise

At this point Sam began to listen more attentively and pressed his ear
  against the stone.
'Who cut the cords she'd put round him, Shagrat? Same one as cut the
  web. Didn't you see that? And who stuck a pin into Her Ladyship? Same
  one, I reckon. And where is he? Where is he, Shagrat? '
Shagrat made no reply.
`You may well put your thinking cap on, if you've got one. It's no
  laughing matter. No one, no one has ever stuck a pin in Shelob before,
  as you should know well enough. There's no grief in that; but
  think-there's someone loose hereabouts as is more dangerous than any
  other damned rebel that ever walked since the bad old times, since the
  Great Siege. Something has slipped.'

What is this "Great Siege" the two orcs are talking about?

A: Mordor was besieged for 7 years during the Last Alliance. It was after this that the tower of Cirith Ungol was built by the men of the west to guard Mordor.

As he gazed at it suddenly Sam understood, almost with a shock, that this stronghold had been built not to keep enemies out of Mordor, but to keep them in. It was indeed one of the works of Gondor long ago, an eastern outpost of the defences of Ithilien, made when, after the Last Alliance, Men of Westernesse kept watch on the evil land of Sauron where his creatures still lurked.
The Return of the King: The Tower of Cirith Ungol

A: The Siege Of Barad-Dúr
The siege that ended the War of the Last Alliance, and the Second Age, was called The Great Siege and is also explicitly referenced as such by Tolkien:

"the Second Age ends with the Last Alliance (of Elves and Men) and the great siege of Mordor"
Letter 131

I would say it's safe to conclude that this is the Great Siege of old that is being spoken about. The siege started in SA 3434 and ended in SA 3441 along with the Second Age. This conversation was in TA 3019, meaning the siege was 3026 years before.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting every other letter to upper and lower case in javascript I am trying to convert a name string 'talhakhan' to 'TaLhaKhAn'. I can loop through the entire variable but I am facing issue in assignment. Please check my code:

var name = 'talhakhan';
var counter = true;
for (var e = 0; e < name.length; e++) {
  if (counter)
    name.charAt(e) = name.charAt(e).toUpperCase();
  else
    name.charAt(e) = name.charAt(e).toLowerCase();
  counter = false;
}

error:

VM704:1 Uncaught ReferenceError: Invalid left-hand side in assignment
at :1:11

A: name.charAt(e) calls a function which returns a value. You can't assign a value to a function call.
You can assign a value to a variable though. Simply build up a new string with the altered values. Your logic with counter also needed amending as in your version it would always be false after the first character.
Demo:

var name = 'talhakhan';
var counter = true;
var newname = "";
for (var e = 0; e < name.length; e++) {
  if (counter) {
    newname += name.charAt(e).toUpperCase();
    counter = false;
  }
  else {
    newname += name.charAt(e).toLowerCase();
    counter = true;
  }
}

alert(newname);

A: I guess you want to produce TaLhAkHaN and not TaLhaKhAn judging by your code sample…
You can split the string, apply your transformation and join back into a string. (this will break special characters made of surrogate pairs)

let name = 'talhakhan';
name = name.split('').map((character, i) =>
  (i % 2) ? character.toUpperCase() : character.toLowerCase()
).join('')
console.log(name)


text:
Q: Formatting a new disk and MBR Having a brand new disk am i right that MBR and bootstrap code is created by the formatting tool such a DOS format or Linux fdisk/cfdisk?

A: On windows,

*

*GUI

*

*In Disk Management, right-click the disk you want to initialize, and then click Initialize Disk.

*In the Initialize Disk dialog box, select the disk(s) to initialize. You can select whether to use the master boot record (MBR) or GUID partition table (GPT) partition style

*Command Line

*

*In command line, type diskpart. Next, select disk your ant to Initialize by typing select disk <disk_number>.

*Now bring disk online using online disk and then type convert <mbr/gpt> to Initialize its partition table.

Note: if you get and error Initializifn try clearing its current attributes by typing `attributes disk clear'.

On Linux,

*

*GUI

In gparted, select the disk you want to perform your action on. Now,  select device > Create partition Table. Select your partition table of choice and apply it.

*

*shell/cli

You need parted for this. In parted, select your disk by typing parted /dev/<disk_name> (use fdisk -l to find your disk name) and then mklabel msdos to convert to MBR

NOTE: CHANGUNG YOUR PARTITION TABLE IS DANGEROUS AND CAN CAUSE PERMANENT LOSS OF DATA. PROCEED WITH CAUTION. MAKE SURE YOU HAVE BACKUPS OF DATA BEFORE FORMATTING. MAKE SURE YOU HAVE SELECTED THE RIGHT DISK BEFORE FORMATTING. DAMAGE COULD BE IRREVERSIBLE.

A: That's close, but not entirely accurate.

*

*The partition table is created by fdisk on MS-DOS, diskpart or diskmgmt.msc on Windows, fdisk, parted, gdisk on Linux, and so on.

*The bootstrap code is usually written by a separate tool, usually by the OS installer itself (or by tools like grub-install). Even though BIOS bootstrap code happens to live in the MBR alongside the partition table, it's still a separate item. (UEFI boot code exists as files in a partition, for example.)

*The format and mkfs commands don't touch the partition table – they create a new filesystem on the given partition (or, rarely, disk).


text:
Q: Show "Loading" image while WebView loads page in Android my android app is simple client for web site. It opens site's url, using JavaScript and DOM enters username and password (predefined) and clicks "Log in" button. It uses WebView class.
Question: how during that process I could show some "ajax" loading image  instead of showing webweiv on the same activity?
THank you!

A: You can set a WebViewClient to your webview and use the callbacks onPagestart and onPageFinished to show the progress.


text:
Q: jQuery append to a ul without an id? I've been working on a squarespace site (which does not let you edit the body code or this would be as easy as dropping another li item into a ul) and I need to pin the squarespace block for social icons into the navbar (which is structured as a ul). All the jQuery tuts I've seen on appending use the ul-id as the point to append to. Unfortunately, the ul on my site does not have a specific id. It looks like this:

        <li class="page-collection active-link" id="51f05bd9e4b01bb187e35cd7
          Home

Now I want to append the following code to this list (keep in mind this is a "block" of squarespace code that the site reads in a way that displays social media icons where it is placed.)

Is it possible to append to the existing ul in the header using the jQuery .append() function? If so what class/id do I append to?

A: You can select it hierarchally:
var html = '

';

$('#topnav .main-nav > ul').append(html);

A: try using this
$('div#topnav nav.main-nav > ul').append('li html code here');


text:
Q: Efficient MySQL Database Design for Multi-User Web Apps I am developing a site that will allow for users to track sales numbers for personal crafts. The way it will work is that a user will be able to submit/edit weekly sales data, and then once the data is stored, be able to view it in various forms of table or graph, track trends, etc.
My concern is that as the userbase grows, if it grows, I want a database design that will scale with it, and be manageable. I am self taught when it comes to proper web apps like this, and while I have all the PHP and JS knowledge I need to assemble the site, and I've worked with jQuery before, this one I am less sure about.
Am I better off storing users' weekly reports in one big table, or creating a separate database, in which each user has their own table, in turn containing that user's weekly reports? There's going to be far more pulling this data for charts done than there is altering or adding to it, so my goal is primarily efficiency and simplicity of storing/recalling the data.
The thing that has me most stumped is the best way to handle the fact that different users will have different amounts of products, and those amounts will change. In a user's first week, perhaps they log sales for 2 items, but come the third week, they add a new item to the list of things they are selling. The database needs to allow for this kind of thing with low overhead, as most users will have more than 1 product.
How would you structure this database?

A: I would suggest one large table with the innoDB engine for row-level locking instead of table locking. Then create an index on the username and entry time.
I would suggest that the table per user be a bit much, you would be wasting space on the harddisk and database allocated for the table which a user may not need. There is no problem with mySQL support 5+ million rows, if your table even gets that big.
Simplicity is best.


text:
Q: How to integrate CKEditor in rails 6? I am developing a rails 6 app in which I want to integrate CKEditor. I have done installing as per the Github README and my knowledge to Rails 6.
There is no error in backlogs as well in the browser console but still, I am getting only the box which can be stretch but with no toolbar.

Edit - Please find the associated code with the CKEditor.

*

*Added gem 'ckeditor', '~> 5.1' in Gemfile.

confif/initializers/assets.rb
# Be sure to restart your server when you modify this file.

Rails.application.config do |assets|
  # Version of your assets, change this if you want to expire all your assets.
  assets.version = '1.0'

  # Add additional assets to the asset load path.
  # Rails.application.config.assets.paths << Emoji.images_path
  # Add Yarn node_modules folder to the asset load path.
  assets.paths << Rails.root.join('node_modules')

  # For ckeditor
  assets.precompile += %w[ckeditor/*]
end

# Rails.application.config.assets.precompile += %w( admin.js admin.css )

*

*Ran rails generate ckeditor:install --orm=active_record --backend=active_storage

*Mount the Ckeditor::Engine in your routes (config/routes.rb): as mount Ckeditor::Engine => '/ckeditor'

*Setup editor version to load in config/initializers/ckeditor.rb
Ckeditor.setup do |config|
  require 'ckeditor/orm/active_record'
  config.cdn_url = 'https://cdn.ckeditor.com/ckeditor5/21.0.0/classic/ckeditor.js'
end

*

*View in form

<%= simple_form_for @product, url: products_path,
  wrapper: :horizontal_form,
  wrapper_mappings: {
    boolean:       :horizontal_boolean,
    check_boxes:   :horizontal_collection,
    date:          :horizontal_multi_select,
    datetime:      :horizontal_multi_select,
    file:          :horizontal_file,
    radio_buttons: :horizontal_collection,
    range:         :horizontal_range,
    time:          :horizontal_multi_select
  } do |f| %>

  <%= f.error_notification %>

  <%= f.input :name %>

  <%= f.input :description, as: :ckeditor, input_html: { ckeditor: { toolbar: 'Full' } } %>

  <%= f.input :category_id, collection: Category.all.map{|c| ["#{c.name}", c.id]}, prompt: :translate %>

  <%= f.input :sub_category_id, collection: SubCategory.all.map{|c| ["#{c.name}", c.id]}, prompt: :translate %>

  <%= f.input :size, :include_blank => "Select the size of the Product", collection: product_size_list %>

  <%= f.input :material, :include_blank => "Select the material of the Product", collection: product_size_list %>

  <%= f.input :surface, :include_blank => "Select the surface of the Product", collection: product_size_list %>

  <%= f.input :images, as: :file, input_html: { multiple: true } %>

  <%= f.input :price %>

      <%= f.button :submit, class: "btn-primary" %>
      <%= f.button :button, "Clear", type: "reset", class: "btn-outline-secondary" %>
      <%= link_to 'Back', products_path %>

<% end %>

A: You are using a CDN url for CKEDITOR 5 but the gem ckeditor say it support only ckeditor 4


text:
Q: Probability of disjoint path of some color in a rectangle Let $R = [a,b] \times [c,d] $ be a rectangular box. Discretize $R$ by a hexagonal lattice of mesh size $\delta > 0$. Consider the usual critical percolation on it. Let $E_{wwbwwb}$ and $E_{wbwbwb}$ be the events that going from left to right in the box we can find six disjoint paths of colors white-white-black-white-black-black and white-black-white-black-white-black respectively. Show that $\mathbb{P}(E_{wwbwbb}) = \mathbb{P}(E_{wbwbwb}) $.
Hint: color flipping.
I thought to do that but I'm not sure: do you think that this work?
It suffices to show that $ \mathbb{P}(E_{wwb})=\mathbb{P}(E_{wbw}) $ since by mirroring the paths and flipping the colors we get then $\mathbb{P}(E_{wwbwbb}) = \mathbb{P}(E_{wbwbwb}) $. Moreover we have again by flipping the color that $\mathbb{P}(E_{wbw})= \mathbb{P}(E_{bwb})$ and $\mathbb{P}(E_{wwb})=\mathbb{P}(E_{bbw})$.
Now consider $ \mathbb{P}(E_{wwb})= \mathbb{P}(E_{w} \cap E_{wb}) $ and since $E_w$ is an increasing event and $E_{wb}$ a decreasing event, by FKG inequality we get that
$$ \mathbb{P}(E_{wwb})= \mathbb{P}(E_{w} \cap E_{wb}) \leq \mathbb{P}(E_w) \mathbb{P}(E_{wb}) $$
again by flipping colors we get that $ \mathbb{P}(E_{w})=\mathbb{P}(E_{b})$ and then we deduce that
$$\mathbb{P}(E_w) \mathbb{P}(E_{wb}) = \mathbb{P}(E_b) \mathbb{P}(E_{wb}) $$
now we get that $E_b$ and $E_{wb}$ are both decreasing events, then again by FKG inequality we get
$$\mathbb{P}(E_{wwb}) \leq \mathbb{P}(E_b) \mathbb{P}(E_{wb}) \leq \mathbb{P}(E_{bwb})= \mathbb{P}(E_{wbw})  $$
For the other direction we have that $E_{b}$ and $E_{bw}$ are both decreasing events hence
$$ \mathbb{P}(E_{wwb})= \mathbb{P}(E_{bbw})\geq \mathbb{P} (E_{b}) \mathbb{P}(E_{bw})$$
now similarly as above we have
$$\mathbb{P} (E_{b}) \mathbb{P}(E_{bw}) = \mathbb{P}(E_w) \mathbb{P}(E_{bw})$$
and now $E_w$ is increasing and $E_{bw}$ is decreasing hence
$$ \mathbb{P}(E_w) \mathbb{P}(E_{bw}) \geq \mathbb{P}(E_{wbw}) $$
hence the result.


text:
Q: Extract from text the first and 6th column if there is a 6th column I have data in following format and I want to extract the first column and the column 6, if there is a column six:
ID1        Bacteria;Firmicutes;Clostridia;Clostridiales;
ID2        Bacteria;Firmicutes;Clostridia;Clostridiales;Eubacteriaceae;Eubacterium;Eubacterium hallii;
ID3        Bacteria;Firmicutes;
ID4        Bacteria;Firmicutes;
ID5        Bacteria;Firmicutes;Clostridia;
ID6        Bacteria;
ID7        Bacteria;Firmicutes;Clostridia;Clostridiales;Ruminococcaceae;Faecalibacterium;
ID8        Bacteria;Firmicutes;Clostridia;Clostridiales;Ruminococcaceae;Faecalibacterium;Faecalibacterium prausnitzii;

The output should be:
ID2 Eubacterium
ID7 Faecalibacterium
ID8 Faecalibacterium

I try to solve the problem by split by ";" and grep the 6th column cut -d ";" -f 6 but think you will have a better solution. Thank you in advance!

A: You can use awk:
awk -F\; 'NF>=6{print substr ($1, 0, 4), $6}' file

If there are 6 or more fields, then it extracts fields 1 and 6 based on delimiter ;. and then extracts first 3 chars from field 1.
Sample output:
$ awk -F\; 'NF>=6{print substr ($1, 0, 4), $6}' file
ID2 Eubacterium
ID7 Faecalibacterium
ID8 Faecalibacterium

A: Grep for lines with 6 ;'s:
egrep '(.*;){6}' file

Cut columns 1,6 with delimeter ;
cut -f1,6 -d';' file

remove the \s.*; junk (notice I don't use sed, perl is good for regex):
perl -pe 's/\s.*;/ /'

Altogether now:
egrep '(.*;){6}' file | cut -f1,6 -d';' | perl -pe 's/\s.*;/ /'

There you go , an answer using grep, cut and regex.


text:
Q: Cannot pass STDIN using shell_exec() in PHP I am a complete beginner in PHP.
I want to execute a java .jar file using PHP.The jar file takes input from STDIN and generates the output at STDOUT.To execute the jar file this is what I do in my Ubuntu Linux terminal:
./java/bin/java -jar abc.jar
<here goes the STDIN>
Ctrl+D
<The output gets generated here at the STDOUT>

This works perfect.However when I replicate this in PHP as:
$p=shell_exec("./java/bin/java -jar abc.jar $s 0<&-");

This sends $p the output generated when STDIN is empty.Which definitely means that $s is not being passed.I am perfectly sure my jar file works perfectly,it's the php script where my mistake is.Can anyone please point out my mistake? Thanks in advance.

A: Complete shot in the dark, but:
$p=shell_exec(sprintf('./java/bin/java -jar abc.jar "%s" 0<&-', addslashes($s)));

It could be a case that $s contains unescaped characters that ruin the command syntax.


text:
Q: How to add a new type of calendar to using by Windows? There are many type of calendars that use in the world. Below link is the list of these calendars:
http://en.wikipedia.org/wiki/List_of_calendars
Microsoft dosent provide all type of calendars in the Windows.
Which API should I use to add a new type of calendar to using by Windows? (May be something like drivers.)

A: There is no provision for user extensible calendars in Windows. Your only option is to create your own support for the given calendar.


text:
Q: Is it misleading to say that intermediate code runs in a virtual machine If I am correct in understanding what I've read a virtual machine is essentially a compiler for intermediate code.
But it is never said that Delphi (as an example of unmanaged code) runs in its compiler.
Would it be less confusing to just describe a virtual machine as a compiler?

A: A traditional compiler does a one-time conversion from source code to object code.  A virtual machine like the JVM uses a mixture of interpretation (of bytecode) and a just-in-time compiler that compiles segments of bytecode to native code.  It's not accurate to describe a VM overall as a compiler.

A: There's a compiler that translates source code to VM code (bytecode), and a JIT compiler for VM code -> machine code.  The VM is the standard that the source code -> VM compiler targets, not necessarily the specific implementation.  It could be implemented with a real machine, in which case it wouldn't need to do JIT compilation.
A VM is closer to an emulator (or if your JIT is really stupid, an interpreter :))

A: I think what people are trying to capture with the terminology is that there's an extra layer of abstraction with virtual machines. So, same code, but the VM for each platform allows it to run on that specific platform.


text:
Q: Best Way to Store data for retrieval in my system I am making a booking system in php. I'm currently after some advice on the best way to store items in the database. I currently have 3 tables:
Table 1 = Hire Stock (Primary Key = asset_id)

(contains fields specific to the items such as size, weight, power consumption
Table 2 = Project  (Primary Key = project_id)

(contains the project start date, end date, customer name.)
Table 3 = availability  (Primary Key = asset_id)

(Everytime an item is added to a project, it is stored here with it's project id)
I need the ability to be able to search through every item in the inventory, and check that it is available for hire when it is needed. If I have to loop through every item comparing date ranges it's going to take ages. Are there better ways to store the data? Better ways to search through it?

A: Your schema seems sensible. Just join the tables correctly and test that your asset_id is not in those assigned to any project whose date range overlaps the period of the new project you need it for.
Assuming you've created the new project and want to assign products to it.
You want a query that is something like this:
$query= "select * from Hire_Stock h ".
"Where h.asset_id not in ".
"( Select a.asset_id from availability a, Project p2, Project p1 ".
"Where p1.project_id = :new_proj ". // The id of the new/planned project
"and p2.project_id != p1.project_id ".
"and p2.end_date >= p1.start_date ".
"and p2.start_date <= p1.end_date ".
"and a.project_id = p2.project_id )";

// using oracle oci

$pok=oci_parse($conn,$query);

if (!$pok) die("Query ($query) Failed!<br>");

oci_bind_by_name($pok,':new_proj',$new_proj,-1);

$res=oci_execute($pok);

While ($hs_row=oci_fetch_array($pok),OCI_ASSOC)
(
  extract($hs_row);
  :
)


text:
Q: If $V \in \mathbb{R}^{n \times n}$ is an orthogonal matrix, and $V^T e=0$, ($e$ is the ones vector) then is it true $V_m^T e = 0\, \forall \, mIf $V$ is an orthogonal matrix, and  $V^T e=0$, then is it true that the sum of any subset of the columns also $= 0$?
I am struggling to prove this, but I'm unable to come up with a counterexample....

A: If $V$ is an orthogonal matrix, then by definition
$V^TV = VV^T = I, \tag 1$
the identity matrix.  Thus
$V^T = V^{-1}, \tag 2$
and with
$V^Te = 0, \tag 3$
we have
$e = Ie = (VV^T)e = V(V^Te) = V(0) = 0; \tag 4$
thus any vector $e$ satisfying (3) vanishes, which comes as no surprise, since the columns of $V^T$ are linearly independent:  if we write $V^T$ in columnar form as
$V^T = [W_1 \; W_2 \; \ldots \; W_n], \tag 5$
the $W_i$ being the columns of $V^T$, then taking any vector
$f = \begin{pmatrix} f_1 \\ f_2 \\ \vdots \\ f_n \end{pmatrix}, \tag 6$
we have
$V^T f =  [W_1 \; W_2 \; \ldots \; W_n]\begin{pmatrix} f_1 \\ f_2 \\ \vdots \\ f_n \end{pmatrix} = \displaystyle \sum_1^n f_i W_i; \tag 7$
that is, the entries of the vector $f$ form the coefficients of the linear expansion
$\displaystyle \sum_1^n f_i W_i; \tag 8$
of $V^Tf$ in terms of the columns of $V^T$; since the columns of an orthogonal matrix are, in fact, orthonormal as vectors (which follows from (1)), and hence linearly independent, the expresion (8) may only vanish if each of the $f_i$ does; that is, only if $f = 0$.  (4) is nothing more than a condensed, abstract presentation of these remarks in more algebraic terms.
Since there are no non-zero vectors such as $e$ or $f$ satisfying (3), we may conclude from (5)-(8) that no sum of the $W_i$ may vanish.
Note Added in Edit, Sunday 16 September 2018 8:27 AM PST:  To affirm further that the $f_i = 0$, $1 \le i \le n$, note that the $W_i$ orthonormal means
$\langle W_i, W_j \rangle = \delta_{ij}, \; 1 \le i, j \le n; \tag 9$
thus taking $\langle W_j, \cdot \rangle$ with each side of
$\displaystyle \sum_1^n f_i W_i = 0 \tag{10}$
we obtain
$f_j = \displaystyle \sum_1^n f_i \delta_{ij} = \sum_1^n f_i \langle W_j, W_i \rangle = \langle W_j, \sum_1^n f_i W_i \rangle = \langle W_j, 0 \rangle = 0 \tag{11}$
for all $f_j$, $1 \le j \le n$.  A simple sum of the $W_i$ occurs if we only take each $f_i = 0, 1$; but we see here this is impossible unless all the $f_i = 0$.
Furthermore, I should probably point out that for $V$, and hence $V^T$, orthogonal matrices, and $e = (1, 1, \ldots, 1)^T$, there is no way that
$V^T e = 0 \tag{12}$
can possible bind; so in effect, the hypothesis of the problem are self-contradictory; vacuous.
I mean, for sure the implication
$V^Te = 0 \Longrightarrow V_m^T e = 0, \tag{13}$
is true; but the hypothesis being false renders indeterminate the truth value of any conclusion.  End of Note.


text:
Q: how to pass data to the nested component in Angular 8? In a parent html, I have many components such as chart 1,2,3,4,5. Then whenever I changed the date, I want to send the selected date to all the components. The code below is the implementation of the parent child event emitter. But I am getting no value from this html file when I check <kt-chart1> component?
Also, I want to know when I get the data so I can sort chart by date by executing functions.
html

        <mat-form-field class="flex-container">

                <input
                    matInput
                    placeholder="Choose a date"
                    [satDatepicker]="picker2"
                    formControlName="date"
                    (dateChange)="DateChanged($event)"
                />

            <sat-datepicker #picker2 [rangeMode]="true"> </sat-datepicker>
            <sat-datepicker-toggle
                matSuffix
                [for]="picker2"
            ></sat-datepicker-toggle>
        </mat-form-field>

Cost Per Tonne

        <kt-chart1 (sendingDateEmitter)="receivedDate($event)"></kt-chart1>
        <kt-chart2 (sendingDateEmitter)="receivedDate($event)"></kt-chart2>
        <kt-chart3 (sendingDateEmitter)="receivedDate($event)"></kt-chart3>

Typescript
    @Output() sendDateEmitter = new EventEmitter<any>();

    DateChanged($event) {
        this.sendDateEmitter.emit($event.value);

    }

A: To each of the charts add
@Input() date: Date;

And pass it to charts
<kt-chart1 (sendingDateEmitter)="receivedDate($event)" [date]="form.get('date').value"></kt-chart1>
<kt-chart2 (sendingDateEmitter)="receivedDate($event)" [date]="form.get('date').value"></kt-chart2>

Make sure form is initialized before rendering, otherwise you might need to do something like [date]="form.get('date')?.value"
To detect date changes in chart use OnChanges
ngOnChanges(changes: SimpleChanges) {
  if (changes.date) {
    // Date has changed, do something with it.
  }
}

A: Why don't you just declare a variable and bind it to Child's input parameter. Something like this:
Parent Component:
parentDate: Date;

DateChanged($event) {
  this.parentDate = $event.value);
}

Parent Component html:
<kt-chart1 [childDate]="parentDate"></kt-chart1>

Child Component
@Input() childDate: Date;

Angular will automatically take care of all the event emitter and passing of data you are taking to do.


text:
Q: Angular Child Component does not change values when parent values change The parent component is getting data from another component(Home Component) via routerLink. It is then sending this data to the child component.
This works well for the first time.
There is a search bar in my header which is visible in the home component page as well as the page rendered by parent and child component. Upon clicking on a valid entry in the search bar, I pass the id and category params to parent again, however, only the parent component changes while the child remains the same as the earlier one.
How do I pass the values again to child without refreshing?
Parent Component HTML:

{{id}}

{{category}}

  <child-component [id] = "id" [category] = "category"> </child-component>

Parent Component TS:
import { Component, OnInit ,ViewChild} from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';

@Component({
  selector: 'parent-component',
  templateUrl: './parent-component.component.html'
})
export class ParentComponent implements OnInit {

  id : any
  category : any

ngOnInit() {
      this.route.paramMap.subscribe(params => {
      this.id = params.get('id');
      this.category = params.get("media_type");})

//do other stuff

Child Component TS:
import { Component, OnInit , Input} from '@angular/core';

@Component({
  selector: 'child-component',
  templateUrl: './child-component.component.html'
})
export class ChildComponent implements OnInit {

  @Input() id: any;
  @Input() category: any;

//do other stuff


text:
Q: What is the unchecked value for a checkbox in html? I am trying to determine on page load if a checkbox should be checked or not. I have tried setting checked to false but that just says it's an invalid value. I have also tried using a hidden field and setting that to the php value and on window.load setting the checkbox value but for some reason that didn't work either. I am looking for a simple way to do this.
$customer = Customer::getCustomer($id);

$isChecked = "checked";

if ($customer->isactive) {
$isChecked = "unchecked";
}

<input type="checkbox" value="Active" checked="<?=$isChecked?>" />

Is it really this difficult in html to uncheck a checkbox?

A: Unchecked is the default state of the checkbox so you dont need to add anything:
Unchecked:
<input type="checkbox" value="Active" />

Checked:
<input type="checkbox" value="Active" checked="checked" />

or you don't even need to do this ="checked"
<input type="checkbox" value="Active" checked />

is enough too (:
So comming back to you example you could do:
<input type="checkbox" value="Active" checked="<?php echo ($customer->isactive) ? '' : 'checked'; ?>" />

A: <input type="checkbox" value="ACTUAL_VALUE" checked><!-- Will be posted unless manually unchecked by the user -->

You need to only put 'checked' if it is actually checked. This input won't be posted to the server on form submit if it is not checked.
For unchecked it is simply:
<input type="checkbox" value="ACTUAL_VALUE"> <!-- Won't be posted unless checked by the user -->

Based on your comments I would do something like this, using a ternary operator:
<input type="checkbox" value="ACTUAL_VALUE" <?php echo $customer->isactive ? 'checked' : '';?>>

A: This seems to be the only way I can edit my question or add additional info. Wow...
Look enter now adds a line break yay!!
Okay I am getting the value from my database of whether or not it's active and should be checked or unchecked depending on that value. I guess I could do it this way.
<?php
if ($customer->isactive) {
?> <input type="checkbox" checked="checked" />
<?php } else { ?>
<input type="checkbox" /> <?php } ?>

I know leaving it blank won't check it but that won't work because I have to have the checked= part in case it should be checked unless there is a way to add checked="checked" if the customer is active and not add anything if it isn't active.


text:
Q: Как создать zip-архив блоками заданного размера? Это продолжение предыдущего вопроса, где я пытаюсь для создания zip-файлов использовать open source библиотеку SharpZipLib. Возник вопрос организации архивов в виде томов определенного размера (например, для записи архивов >4Гб на FAT32 диск). Может кто-то из тех, кто использовал данную библиотеку, подсказать вариант выполнения?
З.Ы. Документация по либе крайне скудная и плохо организована, поэтому сам найти способ не смог :(

A: Попробуйте dotNetZip - он позволяет решить вашу задачу.
DotNetZip example:
int SegmentsCreated ;
using (ZipFile zip = new ZipFile())
{
  zip.UseUnicode= true;  // utf-8
  zip.AddDirectory(@"MyDocuments\ProjectX");
  zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ;
  zip.MaxOutputSegmentSize = 100*1024 ; // 100k segments
  zip.Save("MyFiles.zip");

  SegmentsCreated = zip.NumberOfSegmentsForMostRecentSave ;
}

A: Можете простым кодом вроде этого поделить уже готовый zip-файл на части:
public static void SplitFile(string source, long partSize, string destinationFormat, int firstFileNumber = 0)
{
    var sourceStream = File.OpenRead(source);

    var buffer = new byte[80*1024];
    var position = sourceStream.Position;
    var fileNumber = firstFileNumber;

    while (position < sourceStream.Length)
    {
        var filename = String.Format(destinationFormat, fileNumber);

        using(var destinationStream = File.Create(filename))
        {
            var count = 0;

            do
            {
                count = sourceStream.Read(buffer, 0, (int)Math.Min(buffer.LongLength, partSize - destinationStream.Position));
                destinationStream.Write(buffer, 0, count);
                position += count;
            } while (count > 0);
        }

        fileNumber++;
    }
}

вызов:
SplitFile(
    source: @"C:\test\test.zip",
    destinationFormat: @"C:\test\test.z{0:D2}",
    partSize: 100000*1024
    );

Если хотите сразу писать в несколько файлов, то конструктору ZipFile можно подавать в качестве аргумента экземпляры Stream/Filestream.
При желании, можно сделать наследника для одного из этих классов, который и будет автоматически писать в несколько файлов. Это не сложно, просто кода нужно относительно много, т.к. требуется что бы поток был Seekable и Readable(не смотря на то, что мы собираемся только писать в поток)


text:
Q: Display the values from different column in one column I want to display the values of unique from 3 columns or i would like to say i want to know the status of the product if it is listed in any 3 of countries in the table.

*

*pls display the unique of D,F & H in K and display if any values corresponding to D,F & H in "L".

OR

*when we enter a product from col D,F & H in col K .. Col L must display the status of that product.

Hope u understand what i want.
https://docs.google.com/spreadsheets/d/1D_Vv_lSrBdRgKFQfPt8IIxrgMoB_ca6yyZwkDymvRLQ/edit#gid=0

A: Please use the following formula
=QUERY({C4:D11;E4:F11;G4:H11}, "where Col2 is not null")

Functions used:

*

*QUERY
Using {C4:D11;E4:F11;G4:H11} we create an array of stacked ranges one on top of the other.
(Please adjust ranges to your needs)

A: From the information you provided, I could think of using CONCATENATE to display the value from these country rows if one is filled and the rest are empty.
You could use the following formula and then expand below:
=CONCATENATE(D4,F4,H4,K4)

Here is an image demonstrating the result of this. Let me know  if this was what you were aiming for:


text:
Q: Can I make a login system for use with embedded systems to login and upload data with Django? I want to try make a web service where the users can post data into a database, and it also should support data posts by some system that is not used my some user. In the end it should have some type of webAPI to allow other users to make other kind of web services using whatever data it contains in the database.
But my main question is does Django have some type of shell interaction function that I can use to let embedded system to login, then to talk to my web service and post data?

A: You can build a REST API using one of the packages listed here:
http://www.djangopackages.com/grids/g/api/


text:
Q: F5 BIG-IP Powershell/iControl - Query Current Connections at the Node Level I am working on Powershell scripts to do automated deployments to our servers behind our BIG-IP LTM.
I have simple scripts that use the iControl powershell cmdlets to disable and re-enable the nodes:
Disable-F5.LTMNodeAddress -Node xxx.xxx.xxx.xxx
These work quite well, however for this to become a truly automated process, what I need next is a way to query the Current Connections to the node as they bleed off so that my automation doesn't begin the deployment until current connections = 0.
I've tried the code here without any luck and gone down a few more rabbit holes that didn't get me what I  need.
Hoping someone has tried this more recently and had better luck than I am
Thanks!

A: Found it.
https://devcentral.f5.com/questions/get-local-traffic-statistics-gt-nodes
`$ic = get-F5.iControl
$ic.LocalLBNodeAddress.get_statistics("NODE_IP") | %{$.statistics.statistics | ? {$.type -eq "STATISTIC_SERVER_SIDE_CURRENT_CONNECTIONS"} | %{$_.value.low} }`


text:
Q: Strange behavior in a flexbox when resizing window on mobile chrome There is a very strange behavior with flexbox happening on a mobile browser.
Please see this gif for a visual of what's happening
This only happens on a mobile browser, I'm currently using Chrome mobile on a Google Pixel phone. I have a resize script running that resizes multiple elements on the page as a workaround for not being able to properly utilize 100vh like so:
window.onresize = function() {
        document.getElementById("backgroundImage").style.height = window.innerHeight;
        document.getElementById("mainScreen").style.height = window.innerHeight;
        if (window.innerWidth > 750) {
          document.getElementById("scrollContent").style.height = window.innerHeight - "96";
        } else {
          document.getElementById("scrollContent").style.height = window.innerHeight - "72";
        }
    };

The items that are being effected as seen in the gif are items in a flex container. This behavior happens when I scroll up to hide the navigation bar, then click one of the flex links.
I'm using Vuejs, and the content below is being populated by checking for a prop change. The flex links pass a string into a function that changes the project view to the selected project.
I also have a script to add a class that changes the background color on the selected link, and remove that class on all other links, which is how I am changing the active link background.
var webComp = Vue.component('design-comp', {
  template: "#webComp",
  props:['trans-state'],
  components: {
      'project-comp': projectComp,
  },
  data: function() {
    return {
      activeProj: 'default',
    }
  },
  methods: {
    changeProj: function(proj) {
      this.activeProj = proj;
      var a = document.getElementsByClassName('projClick');
      for (i=0; i<a.length; i++) {
        a[i].classList.remove('projActive');
      }
      event.currentTarget.classList.add('projActive');
      document.getElementById('webContainer').scrollTop = 0;
    }
  },
  created: function() {
    this.activeProj = "default";
  }
});

Here is the relevant portion of my SASS file:
#webContainer {
  margin-top: 50px;
  height: calc(100% - 50px);
  .projHeader {
    display: flex;
    justify-content: center;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    background-color: $headerColor;
    box-sizing: border-box;

    .projClick {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      height: 50px;
      box-sizing: border-box;
      background-color: $contentColor;
      border-right: 2px solid $headerColor;
      border-left: 2px solid $headerColor;
      border-bottom: 4px solid $headerColor;
      border-top: 4px solid $headerColor;
      flex-basis: 50px;
      transition: background-color 0.3s;

      &.projActive {
        background-color: $linkActiveColor;
      }

      p {
        color: $fontColor;
        font-family: $titleFont;
        font-size: 2em;
      }
    }
  }
}

Here is the relevant HTML:

0

1

2

3

4

5

6

7

        Project Page is loaded here

I'm hoping someone might know what is going on because I really don't see a reason for this to be happening.

A: Try this:
#webContainer {
  margin: 0;
  padding-top: 50px;
  height: 100%;
  box-sizing: border-box; /* if you didn't apply it before */
...

A: With the help of Kosh Very, I was able to find a solution that works perfectly while still keeping the intended style of the element.
#webContainer {
  margin-top: 50px;
  box-sizing: border-box;
  position: relative;
  height: 100%;

    .projHeader {
        ...
        position: fixed;
        ...
    }
}

I still feel like the initial problem is a bug of some sort, but this is at least a workaround.


text: Q: How to display popup by clicking on "save and publish" button in Umbraco content page I want popup to show up when I click on "save and publish" in umbraco admin content page. should anyone knows how do I do that or at least how to hijack javascript code into umbraco admin pages.


text:
Q: VSCode: How to change user (in order to have the permissions to save files) when connected via SSH to remote machine So far I have found the way to connect VScode to a remote machine of my company and to edit files directly by following this documentation and this tutorial.
However, I cannot save my files once edited, because the user I have declared in the configuration file for accessing remote hosts via SSH does not have the privileges to edit files.

I know there are ways and VScode extensions allowing to save files remotely from VScode as sudo, but in my case I need to switch to another user than root to save those files, because this is the process stated in my company.
Let me clarify this:
When accessing remote hosts from my terminal, I have to access with a personal user, let's say user_P, and then turn to another user to edit files, let's say user_O, with
sudo -i -u user_O

So, to edit a file tentative.txt placed in /tmp/ of my remote host, I usually do, from my local machine
ssh user_P@<remote_machine_ip>
sudo -i -u user_O
vim /tmp/tentative.txt

and I cannot do
ssh user_O@<remote_machine_ip>
vim /tmp/tentative.txt

since user_O does not have permissions to access the remote host from my local machine.
So, If my VScode is connected to my remote host by using the configuration file
Host my_host
    HostName <my_host_IP>
    User user_P
    IdentityFile /home/<my_local_user>/.ssh/known_hosts

and it is connected to remote folder /tmp/ , how can I "switch" to user_O and edit and save tentative.txt successfully?
Disclaimer:
I know accessing and editing files directly on remote machines is dangerous, but I am going to do it only on test enviromnments.


text:
Q: Read environment variable using Macros iOS I like to read the environment variable in my header file using macros and assign to LOGGING_ENABLED in following code (instate of static value like 1).
#define LOGGING_ENABLED   1

Any way to get environment variable using Macros ?


text:
Q: When I run this, it functions as usual but it seems to repeat once. Why does this happen? Whenever I run this I get a "pycache" file placed in the same folder as this project - and its only with this project.
def list_name():
    from project_name import name_sorter as a
    list1 = []
    name = a()
    if name is False:
        return False
    else:
        list1.append(name)
        return list1[list1.index(name)]
def name_sorter():
    from project_name import name_digit as def1
    a = input("Full Name: ")
    bool1 = def1(a)
    if bool1 is False:
        return False
    else:
        if a.count(" ") == 1:
            name_first = a.upper()[0] + a.lower()[1:a.find(" ")]
            name_last = a.upper()[a.find(" ")+1] + a.lower()[a.find(" ")+2:]
            return name_first + " " + name_last
        else:
            return False
def name_digit(a, x = 0):
    if len(a) < 3 or len(a) > 60 or " " not in a:
        return False
    else:
        for b in a:
            x += 1
            if b.isdigit():
                return False
            elif x == len(a):
                return True
from project_name import list_name as list1
a = list1()
while a is False:
    print("Invalid")
    a = list1()
print(a)

Also, is it better to have everything in one file or in separate files but in the same folder?

A:
it functions as usual but it seems to repeat once. Why does this happen?

Yes, it runs twice - once as a script, and once as an imported module (imported from itself). Each time an import statement is encountered, Python looks for the desired module, and if it doesn't already have one cached, it loads that source file in a special way that creates a module object that can be cached. However, everything at top level still executes when that module creation occurs - that's how the module's contents are determined.

I get a "pycache" file placed in the same folder as this project - and its only with this project.

It's only with this project because this is the one where you're doing the weird thing with import that you shouldn't do. The __pycache__ is used internally to improve module loading time on subsequent runs of the program - it's a separate sort of caching, that works even if you restart Python (because it's on disk instead of in memory).
This is honestly the first time I've ever seen someone attempt something like that:
from project_name import list_name as list1

for the simple purpose of giving something within the same file a new name. You normally shouldn't try that anyway - if something was wrong with the original name, then just fix that - but the correct way to do it is as simple as can be:
list1 = list_name

If this surprises you, you need to fix your understanding of how Python deals with the names of things.


text:
Q: Why does MSBuild maintain a hold on a file? I've got the following MSBuild script:
<Copy SourceFiles="$(AdminPath)\web.config" DestinationFiles="$(AdminPath)\tmpweb.config" />
<TransformXml Source="$(AdminPath)\tmpweb.config" Transform="$(AdminPath)\web.$(Configuration).config" Destination="$(AdminPath)\web2.config" />
<Copy Sourcefiles="$(AdminPath)\web2.config" DestinationFiles="$(AdminPath)\web.config" OverwriteReadOnlyFiles="true" />
<Delete Files="$(AdminPath)\tmpweb.config;$(AdminPath)\web2.config" />

However, although web2.config is deleted, tmpweb.config is not "because it is being used by another process" (error MSB3061).
How do I get around this?
I've tried copying the file as described in this blog post but that doesn't seem to work either.

A: I was using v10 of the publishing tasks. I should have used v12.
For future reference using the following:
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>

A: It's not the MSBuild who's locking the file, but the TransformXml task and it's mighty annoying under certain deployment strategies. You can try workarounds from the bug report, personally I wrap it in a custom task via either TransformXml task class or XmlTransformation class directly which gives an added benefit of extra flexibility, eg logging via IXmlTransformationLogger, ie downgrading certain warnings to debug messages to keep the log less noisy.


text:
Q: migration to webpack 5 - Safari 10 error unable to delete property Hi I have migrated project to webpack 5 but on safari 10 i get error as below. Could you help to sort it out?

      minimize: true,
      minimizer: [new TerserPlugin({
        terserOptions: {
          mangle: {
            toplevel: true,
          },
          safari10: true,
        },
      })],
    },

browsers list
last 2 versions
> 1%
not dead
Firefox ESR
IE 11
last 3 iOS major versions
Safari >= 10
iOS >= 10


text:
Q: Would going from 4gb ram to 8gb increase magento speed on localhost? I upgraded my pc from 2.1gh and 2gb ram to dual coure 2.6gh processor and 4GB RAM, magento runs faster but I am still not happy with it (takes 4-6 seconds to open a page).
My memory usage is around 40% alltogether.
Would upgrating to 8GB RAM speed up my magento locally?

A: I would say, by itself, No.  The fact that you are sharing resources on a local machine between MySQL and PHP with Magento is inherently slow within itself.   Will you get more throughput?  Probably, but not enough to notice.
You will get more of a performance gain by installing Varnish, and enabling Magento full page caching AFTER you install more RAM.  Magento cache stores itself in the RAM and so does Varnish.  Also make sure you have APC cache installed.  Those three COMBINED with more RAM will make all the difference in the world.
For Varnish .. Give it about 1GB RAM in the VCL settings  ..  Sounds like a lot, but it'll save your life.
For APC, give it at least 256MB of room in the APC settings ...  It would probably behove you to do 512MB if you can afford it.
I am also going to include my PHP.INI magento optimized settings as well as my MySQL settings:
PHP.INI
 max_execution_time = 18000
 max_input_time = 60
 memory_limit = 1024M
 max_input_vars = 10000
 post_max_size = 102M
 upload_max_filesize =100 M
 max_file_uploads = 20
 default_socket_timeout = 60
 pdo_mysql.cache_size = 2000
 mysql.cache_size = 2000
 mysqli.cache_size = 2000
 apc.enabled = 1
 apc.shm_segments = 1
 apc.shm_size = 1024M
 apc.num_files_hint = 10000
 apc.user_entries_hint = 10000
 apc.ttl = 0
 apc.user_ttl = 0
 apc.gc_ttl = 3600
 apc.cache_by_default = 1
 apc.filters = "apc\.php$"
 apc.mmap_file_mask = "/tmp/apc.XXXXXX"
 apc.slam_defense = 0
 apc.file_update_protection = 2
 apc.enable_cli = 0
 apc.max_file_size = 10M
 apc.use_request_time = 1
 apc.stat = 1
 apc.write_lock = 1
 apc.report_autofilter = 0
 apc.include_once_override = 0
 apc.localcache = 0
 apc.localcache.size = 256M
 apc.coredump_unmap = 0
 apc.stat_ctime = 0
 apc.canonicalize = 1
 apc.lazy_functions = 1
 apc.lazy_classes = 1

And MySQL
MY.CNF
key_buffer              = 256M
max_allowed_packet      = 16M
thread_stack            = 192K
thread_cache_size       = 32
myisam-recover         = BACKUP
max_connections        = 2500
query_cache_limit       = 2M
query_cache_size        = 64M
expire_logs_days        = 10
max_binlog_size         = 100M

[mysqldump]
quick
quote-names
max_allowed_packet      = 16M

[isamchk]
key_buffer              = 16M

I hope that helps you

A: If your memory usage is 40% now, then no. Sufficient RAM does make a difference, but in this case the extra 4 wouldn't make much of a difference.
Magento is quite slow due do its complexity and the fact that it uses thousands of files.
To increase Magento's load speed, try to disable stuff you don't need in the admin section, and perhaps Google for other tips. Also, the load speed will differ between different browsers.


text:
Q: Continuous self-maps in the Golomb space that are neither increasing nor decreasing Let $\mathbb{N}$ denote the set of the positive integers. The Golomb space is a space ${\bf G} =(\mathbb{N},\tau)$ where a basis of $\tau$ is generated by
$$\big\{\{a+bn: n\in \mathbb{N}\cup\{0\}\}: a,b\in\mathbb{N} \text{ and } a,b \text{ relatively prime}\big\}.$$
Is there a continous map $f: {\bf G}\to {\bf G}$ that is neither increasing ($n<m \in \mathbb{N}$ implies $f(n) \leq f(m)$) nor decreasing ($n<m \in \mathbb{N}$ implies $f(n) \geq f(m)$)?

A: For polynomials with non-negative integer coefficients and no constant term, the following simple (but not obvious) fact was observed by Paulina Szczuka.
Theorem. Each polynomial $f:\mathbb N\to\mathbb N$, $f:x\mapsto a_1x+a_2x^2+\dots+a_nx^n$, with integer coefficients and no constant term is continuous in the Golomb topology on $\mathbb N$.
Proof. Take any number $x\in\mathbb N$ and a basic neighborhood $f(x)+b\mathbb N_0$ of its image in the Golomb topology.
Since $f(x)$ is divisible by $x$, the number $b$ is relatively prime with $x$, so $x+b\mathbb N_0$ is a well-defined basic neighborhood of $x$ in $\mathbb G$. Observe that $$f(x+n\mathbb N_0)\subset f(x+b\mathbb Z)\subset f(x)+b\mathbb Z.$$
Since $f(\mathbb N)\subset\mathbb N$ and $f(0)=0$, the polynomial $f$ is not constant, so, for any $y\in Y$ in the finite set $Y:= (f(x)+b\mathbb Z)\setminus (f(x)+b\mathbb N_0)$ the set $f^{-1}(y)$ is finite. The neighborhood $O_x=(x+b\mathbb N_0)\setminus \bigcup_{y\in Y}f^{-1}(y)$ of $x$ in the Golomb topology has the required property: $f(O_x)\subset f(x)+b\mathbb N_0$.
Corollary, The polynomial $f:\mathbb G\to\mathbb G$, $f:x\mapsto x^3-12x^2+45x$, on the Golomb space is continuous but it is neither increasing nor decreasing (since $f(1)=34$, $f(3)=54$ and $f(5)=50$).
Remark. It can be shown (see Theorem 5 in this paper) that the semigroup $S(\mathbb G)$ of
 all continuous self-maps of the Golomb space has cardinality  $|S(\mathbb G)|=\mathfrak c$.


text:
Q: Export dashboard URL from job I have a notebook running as a job in Azure Databricks.  The results are shown in a Databricks dashboard.  I want the dashboard URL to be sent to the team when the run is finished.
How do I retrieve the URL of the dashboard for the current run ?
I know the job ID, I managed to get the base of the URL with
dbutils.notebook.entry_point.getDbutils().notebook().getContext().browserHostName().toString()

and I found one can get the Run ID with
dbutils.notebook.entry_point.getDbutils().notebook().getContext().currentRunId().toString()

but the URL should contain the "Run", which is different than the "Run ID".  Furthermore, the URL doesn't display a dashboard without some UUID I don't know how to get.  Where can I get these informations ?

A: Here is my solution :
run_id = None
url = None
try:
  run_id = json.loads(dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson())["tags"]["idInJob"]
  url = f"https://XXX.azuredatabricks.net/?o=YYY#job/11/run/{run_id}/dashboard/ZZZ"
except:
  pass

I figured XXX, YYY and ZZZ do not change along runs, you will find them by looking at your sample dashboard.
run_id and url will stay None if the notebook is launched in interactive mode.


text:
Q: WebGL: difference between vertex shader transform and app/software transform I'm trying to perform the same transform in javascript as in a vertex shader. My vertex shader is transforming vertices like a typical WebGL example:
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0)
My canvas is 600x600px (but the canvas size turns out to be irrelevant in this case.)
The resulting gl_Position.xy is not what I expected. Rather than being in the range 0,600 or -300,300 or -1,1, it seems to be roughly -6,6. (I ended up writing tests in the shader eg: if the transformed gl_Position.x > 5.0 color it red.)
That -6,6 (or 12x12) drawing area remains constant regardless of canvas size.
After adding a scale factor and tweaking it by eye, I've managed to sync my javascript transform with the shader transform. But how do I get the size of the drawing area of the transformed vertices from WebGL? How is that -6,6 range determined?

A: If you are truly trying to match the vertex transforms, you neglected a few operations that occur AFTER programmable vertex transformation.
You forgot that gl_Position.xyz still has a few transformations to go before you have the NDC or screen space coordinates you discussed in your question.

*

*There is a perspective divide that occurs after the vertex shader and before rasterization (pos.xyz /= pos.w)

*

*Given an orthographic projection matrix this should be a no-op, pos.w will always be 1.0...

*There is also a viewport transform that will take the coordinates out of NDC space and into screen space.

*

*The viewport transform is a little different from all the rest, since the viewport is not defined using a matrix, it basically just defines a scale and bias operation and has no affect on clipping.

Take a few moments to review this illustration:

(source: songho.ca)
The output from your vertex shader is labeled Clip Coordinates (clip space) in this diagram, and you should be aware that primitive assembly and rasterization are where the transformation into Window Coordinates (screen space) is finally completed. Moreover, the two operations discussed in bullet points above are not part of the programmable pipeline.
In case you were wondering, the diagram is from Song Ho Ahn (안성호)'s website. It is part of an article titled 『OpenGL Transformation』, which may help to reinforce what I discussed in this answer.


text:
Q: select box change css class Unfortunately I can not work it out with x-editable...
I´m trying to change a (hprimary) css class on select with x-editable. Here is my jsfiddel: jsfiddel (only with x-editable). Also, i tried It with a normal select button and it is working there. ( jsfiddel2 ) So what do I have to change in x-editable script to make it work?
html:

TEST
    not selected

javascript:
$(function () {
$.fn.editable.defaults.mode = 'popup';
$('#select').editable({
    prepend: "not selected",
    placement: 'right',
    source: [{
        value: 1,
        text: 'NTP(red)'
    }, {
        value: 2,
        text: 'SUCCESS(green)'
    }, {
        value: 3,
        text: 'OPTION(blue)'
    }],

});
});

css:
.hpanel {
background-color: none;
border: none;
box-shadow: none;
margin-bottom: 25px
}
.hpanel.hprimary .panel-body {
border-top: 2px solid #34495e
}
.hpanel.hgreen .panel-body {
border-top: 2px solid #62cb31
}
.hpanel.hblue .panel-body {
border-top: 2px solid #3498db
}
.hpanel.hred .panel-body {
border-top: 2px solid #e74c3c
}

A: You can use the validate() callback option as described here to be alerted when the user has selected a value.
Based on your example, you would then use a regular expression to extract the color from the text value and add the appropriate class to the hpanel element.


text:
Q: How to overwrite td content with an include file with JS? I have a menu with names of different htm files like this:

I want when I click in one, the content of a td shows the document that I just clicked, I have a for that list this names, and set the calling to the JS function:
<% for (int i=0; i < fileNames.length; i++) { %>

         <%= fileNames[i] %>

<% } %>

I'm using a Jsp that displays the content of the first document by default:

    <%@ include file ="/docs/document1.htm" %>

I'd like something like this in my JS Function:
function refreshContent(element) {
    var name = element.textContent;
    var tdContaner = document.getElementById("documentContaner");
    tdContaner.innerHTML = '<%@ include file ="/docs/'+ name +'.htm" %>';
}

first question: Is it possible do it this way? or Do I need to refresh the page to show new content?
second question: If it's possible, How can I write an include file inside the TD?

A: You cannot use JavaScript to insert server side code into the DOM. Server side code needs to be executed by the appropriate runtime / interpreter on the server before the results are delivered to the browser.
To achieve this type of effect, you would need to write an HTTP endpoint which returns just the content of that cell and then use Ajax (usually via the XMLHttpRequest object) to fetch it, and then use DOM methods to insert the result into the cell.

A: You can send AJAX from page to load file

        test

if you have jquery on your page use it

        test

UPD. or preload file & name and show/hide them

        <% for (int i=0; i < fileNames.length; i++) { %>

<%= fileNames[i] %>

<%@ include file ="/docs/document1.htm" %>

    <% } %>

with jquery

        <% for (int i=0; i < fileNames.length; i++) { %>

<%= fileNames[i] %>

<%@ include file ="/docs/document1.htm" %>

    <% } %>


text:
Q: How can I bind the value of a field to a label in Xamarin? Here is what I tried. Note that I removed parts of the XAML to make the question shorter but I tested it out by setting detailx.text in my cs and when I do it that way it displays XXXX:
<Frame x:Class="Japanese.PhrasesFrame">
    <StackLayout x:Name="phrasesFrameStackLayout" >
        <Grid x:Name="phraseGrid">
            <Grid x:Name="wordGrid" >
                <Grid x:Name="detailGrid">
                   <Label x:Name="detail1" Text="{Binding English}" XAlign="Center" />
                   <Label x:Name="detailx" XAlign="Center" />

In my CS I have
    public PhrasesFrame()
    {
        InitializeComponent();
        correctButton.Clicked += correctButtonClicked;
        resetButton.Clicked += resetButtonClicked;
        SetBindings();
        wordGrid.BindingContext = AS.phrase;
    }

In a method I have this:
public partial class PhrasesFrame : Frame
{
    Random rand = new Random();

    public PhrasesFrame()
    {
        InitializeComponent();
        wordGrid.BindingContext = AS.phrase;
        AS.phrase = new PSCViewModel() { English = "abcd" };
        this.detailx.Text = "XXXX";
    }

My problem is that when I used Binding English then the label never shows the text abcd but I do see the XXXX
Can someone tell me if I am missing something obvious.  I tried everything but no success.

A: Try changing the order, like this:
AS.phrase = new PSCViewModel() { English = "abcd" };
wordGrid.BindingContext = AS.phrase;

Whenever you set the BindingContext at that moment it is applied, as is. If you make changes afterwards, you can, but you need to implement the INotifyPropertyChanged event to fire off a signal to the UI indicating which property has changed. Only then will it be update in the UI.


text:
Q: Giving a data frame a title and styling columns with Pandas Python I want to give dict_val dataframe a title that is placed in the center title. I am also trying to separate the each 3 digits with a comma on the Numbers column how would I be able to give a dataframe a title and style the a column as such and get the Expected Output below?
import pandas as pd
import numpy as np

title = 'Number and Numbers 2 Comparison'
numbers = np.array([123242737.4923,679754672.3849])
numbers2 = np.array([123523,467895])

dict_val = pd.DataFrame({'Numbers':numbers.round(2),'Numbers 2': numbers2})
display(dict_val)

Output:

Expected output:
  Number and Numbers 2 Comparison
    Numbers         Numbers 2
0   123,242,737.49  123523
1   679,754,672.38  467895

A: Use Styler.format:
dict_val.style.format(formatter={'Numbers': '{:,.2f}'})

Create MultiIndex and set styles for alignment to center:
text = 'Number and Numbers 2 Comparison'

dict_val.columns = pd.MultiIndex.from_product([[text], dict_val.columns])
print (dict_val)
  Number and Numbers 2 Comparison
                          Numbers Numbers 2
0                    1.232427e+08    123523
1                    6.797547e+08    467895

css = [ {'selector': 'th.col_heading.level0', 'props': 'text-align: center;'}]
dict_val.style.set_table_styles(css, overwrite=False).format(formatter={(text, 'Numbers'): '{:,.2f}'})


text:
Q: Cannot read property 'image' of undefined - image not rendering for only half of my docs I'm running an aggregation query then passing the results to the client for different artist 'pages'. I have six total artists in my database but receive the below image error for only the three artists that don't have listed events:
TypeError: /Users/app/views/artists/show.ejs:4
    2|

    3|

 >> 4|       <% for(let img of artist.image ) { %>
    5|         <img src="<%= img.url %>" class="card-img-top img-thumbnail" alt="...">
    6|       <% } %>
    7|

Cannot read property 'image' of undefined
    at eval (/Users/chaseschlachter/mtapp/views/artists/show.ejs:11:30)

The three that do have listed events render without any issue. Here's the function:
module.exports.showArtist = async (req, res,) => {
    const artistData = await Artist.findById(req.params.id).populate('events');
     if (!artistData) {
         req.flash('error', 'Cannot find that Artist');
         return res.redirect('/artists');
     }
 const artistDetails = await Event.aggregate([
    {
    "$match": {
    "artist": objectId(req.params.id)
    }
    },
    {
    $lookup: {
    from: "artists",
    let: {
    artistId: "$artist"
    },
    pipeline: [{
    $match: {
    $expr: {
    $and: [{
    $eq: ["$_id", "$$artistId"]
    }]
    }
    }
    }],
    as: "artist"
    }
    },
    {
    "$project": {
    "artist": {
    $arrayElemAt: ["$artist", 0]
    },
    "event": {
    "_id": "$_id",
    "event_name": "$event_name",
    "venue_name": "$venue_name",
    "address": "$address",
    "description": "$description",
    "type": "$type",
    "created": "$created",
    "event_start": "$event_start",
    "event_end": "$event_end",
    "notification": "$notification",
    "totalGuests": { $cond: { if: { $isArray: "$guests" }, then: { $size: "$guests" }, else: 0 } },
    "attendedGuests": {
    "$size": {
    "$filter": {
    "input": "$guests",
    "as": "guest",
    "cond": {
    "$and": [{
    "$eq": ["$$guest.attended", "Y"]
    }]
    }
    }
    }
    }
    }

    }
    },
    {
    "$group": {
    "_id": "$artist._id",
    "email": {
    "$first": "$artist.email"
    },
    "location": {
    "$first": "$artist.location"
    },
    "image": {
    "$first": "$artist.image"
    },
    "genre": {
    "$first": "$artist.genre"
    },
    "about": {
    "$first": "$artist.about"
    },
    "size": {
    "$first": "$artist.size"
    },
    "venmo": {
    "$first": "$artist.venmo"
    },
    "events": {
    "$push": "$event"
    }
    }
    },
    ]);
const artist = artistDetails[0]
res.render('artists/show', { artist });
};

Why is it tripping up on artists without events?


text:
Q: How is this a "Bayes classifier"? I am currently studying the textbook Learning with kernels: support vector machines, regularization, optimization and beyond by Schölkopf and Smola. Chapter 1.2 A Simple Pattern Recognition Algorithm says the following:

We are now in the position to describe a pattern recognition learning algorithm that is arguably one of the simplest possible. We make use of the structure introduced in the previous section; that is, we assume that our data are embedded into a dot product space $\mathcal{H}$. Using the dot product, we can measure distances in this space. The basic idea of the algorithm is to assign a previously unseen pattern to the class with closer mean.
We thus begin by computing the means of the two classes in feature space;
$$\mathbf{c}_+ = \dfrac{1}{m_+} \sum_{\{i \vert y_i = +1\}} \mathbf{x}_i, \tag{1.7}$$
$$\mathbf{c}_- = \dfrac{1}{m_-} \sum_{\{i \vert y_i = -1\}} \mathbf{x}_i, \tag{1.8}$$
where $m_+$ and $m_-$ are the number of examples with positive and negative labels, respectively. We assume that both classes are non-empty, thus $m_+, m_- > 0$. We assign a new point $\mathbf{x}$ to the class whose mean is closest (Figure 1.1). This geometric construction can be formulated in terms of the dot product $\langle \cdot, \cdot \rangle$. Half way between $\mathbf{c}_+$ and $\mathbf{c}_-$ lies the point $\mathbf{c} := (\mathbf{c}_+ + \mathbf{c}_-)/2$. We compute the class of $\mathbf{x}$ by checking whether the vector $\mathbf{x} - \mathbf{c}$ connecting $\mathbf{c}$ to $\mathbf{x}$ encloses an angle smaller than $\pi / 2$ with the vector $\mathbf{w} := \mathbf{c}_+ - \mathbf{c}_-$ connecting the class means. This leads to
$$\begin{align} y &= \text{sgn} \langle (\mathbf{x} - \mathbf{c}), \mathbf{w} \rangle \\ &= \text{sgn} \langle ( \mathbf{x} - ( \mathbf{c}_+ + \mathbf{c}_- ) / 2), ( \mathbf{c}_+ - \mathbf{c}_- ) \rangle \\ &= \text{sgn}( \langle \mathbf{x}, \mathbf{c}_+ \rangle - \langle \mathbf{x}, \mathbf{c}_- \rangle + b). \tag{1.9} \end{align}$$
Here, we have defined the offset
$$b := \dfrac{1}{2} ( \left| \right| \mathbf{c}_- \left| \right|^2 - \left| \right| \mathbf{c}_+ \left| \right|^2), \tag{1.10}$$
with the norm $\left| \right| \mathbf{x} \left| \right| := \sqrt{\langle \mathbf{x}, \mathbf{x} \rangle}$. If the class means have the same distance to the origin, then $b$ will vanish.
Note that (1.9) induces a decision boundary which has the form of a hyperplane (Figure 1.1); that is, a set of points that satisfy a constraint expressible as a linear equation.
It is instructive to rewrite (1.9) in terms of the input patterns $x_i$, using the kernel $k$ to compute the dot products. Note, however, that (1.6) only tells us how to compute the dot products between vectorial representations $\mathbf{x}_i$ of inputs $x_i$. We therefore need to express the vectors $\mathbf{c}_i$ and $\mathbf{w}$ in terms of $\mathbf{x}_1, \dots, \mathbf{x}_m$.

To this end, substitute (1.7) and (1.8) into (1.9) to get the decision function
$$\begin{align} y &= \text{sgn} \left( \dfrac{1}{m_+} \sum_{\{i \vert y_i = +1 \}} \langle \mathbf{x}, \mathbf{x}_i \rangle - \dfrac{1}{m_-} \sum_{\{i \vert y_i = -1 \}} \langle \mathbf{x}, \mathbf{x}_i \rangle + b \right) \\ &= \text{sgn} \left( \dfrac{1}{m_+} \sum_{\{i \vert y_i = +1 \}} k( x, x_i ) - \dfrac{1}{m_-} \sum_{\{i \vert y_i = -1 \}} k( x, x_i ) + b \right). \tag{1.11} \end{align}$$
Similarly, the offset becomes
$$b := \dfrac{1}{2} \left( \dfrac{1}{m^2_-} \sum_{\{(i, j) \vert y_i = y_j = -1 \}} k( x_i, x_j ) - \dfrac{1}{m^2_+} \sum_{\{(i, j) \vert y_i = y_j = +1 \}} k( x_i, x_j ) \right). \tag{1.12}$$
Surprisingly, it turns out that this rather simple-minded approach contains a well-known statistical classification method as a special case. Assume that the class means have the same distance to the origin (hence $b = 0$, cf. (1.10)), and that $k$ can be viewed as a probability density when one of its arguments is fixed. By this we mean that it is positive and has unit integral,
$$\int_\mathcal{X} k(x, x^\prime) \ dx = 1 \ \text{for all} \ x^\prime \in \mathcal{X}. \tag{1.13}$$
In this case, (1.11) takes the form of the so-called Bayes classifier separating the two classes, subject to the assumption that the two classes of patterns were generated by sampling from two probability distributions that are correctly estimated by the Parzen windows estimators of the two class densities,
$$p_+ (x) := \dfrac{1}{m_+} \sum_{\{ i \mid y_i = +1 \}} k(x, x_i) \ \ \text{and} \ \ p_- (x) := \dfrac{1}{m_-} \sum_{\{ i \mid y_i = -1 \}} k(x, x_i), \tag{1.14}$$
where $x \in \mathcal{X}$.

I'm confused by this part:

In this case, (1.11) takes the form of the so-called Bayes classifier separating the two classes, subject to the assumption that the two classes of patterns were generated by sampling from two probability distributions that are correctly estimated by the Parzen windows estimators of the two class densities,
$$p_+ (x) := \dfrac{1}{m_+} \sum_{\{ i \mid y_i = +1 \}} k(x, x_i) \ \ \text{and} \ \ p_- (x) := \dfrac{1}{m_-} \sum_{\{ i \mid y_i = -1 \}} k(x, x_i), \tag{1.14}$$
where $x \in \mathcal{X}$.

Firstly, I've only heard of naive Bayes classifiers, so I'm not sure whether this is referring to the naive Bayes classifier, or some more general type of "Bayes classifier"; is there a difference between these? Lastly, related to my first point, I don't see anything resembling (1.11) in the Wikipedia article for naive Bayes classifier, so how is (1.11) a "Bayes classifier", as the authors claim?

A: Overview of what the book is saying
According to the book, there are two classes of interest. Let these classes be $\omega_1$ and $\omega_2$. Also, given a feature vector $\mathbf{x}$, let:
$$
y =
\begin{cases}
+1 & \text{if} \quad \mathbf{x} \in \omega_1 \\
-1 & \text{if} \quad \mathbf{x} \in \omega_2
\end{cases}
$$
According to the book:

The basic idea of the algorithm is to assign a previously unseen pattern to the class with closer mean.

Given the training dataset $\mathcal{D}$ that consists of feature vectors with their corresponding class labels:
$$
\mathcal{D} = \{\mathbf{x}_1|\omega_1,\mathbf{x}_2|\omega_1,...,\mathbf{x}_N|\omega_1,\mathbf{x}_1|\omega_2,\mathbf{x}_2|\omega_2,...,\mathbf{x}_M|\omega_2\}
$$
The book also defines the following vectors as the mean vectors for each class:
$$
\mathbf{c}_+ = \frac{1}{m_+} \sum_{\{i \vert y_i = +1\}} \mathbf{x}_i \\
\mathbf{c}_- = \frac{1}{m_-} \sum_{\{i \vert y_i = -1\}} \mathbf{x}_i
$$
Where $m_+$ is the number of feature vectors that belong to class $\omega_1$ (this is the same as $N$ in $\mathcal{D}$) and $m_-$ is the number of feature vectors that belong to class $\omega_2$ (this is the same as $M$ in $\mathcal{D}$).
This means that, given a not-seen-before feature vector $\mathbf{x}$, the label $y$ of this feature vector is defined as follows:
$$
y =
\begin{cases}
+1 & \text{if} \quad \text{dist}(\mathbf{x},\mathbf{c}_+) < \text{dist}(\mathbf{x},\mathbf{c}_-) \\
-1 & \text{if} \quad \text{dist}(\mathbf{x},\mathbf{c}_+) > \text{dist}(\mathbf{x},\mathbf{c}_-)
\end{cases} \tag{1} \label{eq1}
$$
Where $\text{dist}(\cdot)$ is an arbitrary distance function. Note that:
$$
\mathbf{x} \in \omega_1 \iff \text{dist}(\mathbf{x},\mathbf{c}_+) < \text{dist}(\mathbf{x},\mathbf{c}_-) \\
\mathbf{x} \in \omega_2 \iff \text{dist}(\mathbf{x},\mathbf{c}_+) > \text{dist}(\mathbf{x},\mathbf{c}_-)
$$
Relationship to the Bayes classifier
The Bayes classifier assigns a feature vector $\mathbf{x}$ to class $\omega_1$ if:
$$
p(\omega_1|\mathbf{x}) > p(\omega_2|\mathbf{x})
$$
And assigns a feature vector $\mathbf{x}$ to class $\omega_2$ if:
$$
p(\omega_1|\mathbf{x}) < p(\omega_2|\mathbf{x})
$$
In other words:
$$
y =
\begin{cases}
+1 & \text{if} \quad p(\omega_1|\mathbf{x}) > p(\omega_2|\mathbf{x}) \\
-1 & \text{if} \quad p(\omega_1|\mathbf{x}) < p(\omega_2|\mathbf{x})
\end{cases} \tag{2} \label{eq2}
$$
The goal then is to show that equation \ref{eq1} is the same as equation \ref{eq2}.
Since:
$$
p(\omega_1|\mathbf{x}) = \frac{p(\mathbf{x}|\omega_1)p(\omega_1)}{p(\mathbf{x})}
$$
Using the law of total probability in the denominator:
$$
p(\mathbf{x}) = p(\mathbf{x}|\omega_1)p(\omega_1) + p(\mathbf{x}|\omega_2)p(\omega_2)
$$
So:
$$
p(\omega_1|\mathbf{x}) = \frac{p(\mathbf{x}|\omega_1)p(\omega_1)}{p(\mathbf{x}|\omega_1)p(\omega_1) + p(\mathbf{x}|\omega_2)p(\omega_2)}
$$
Dividing the numerator and the denominator by $p(\mathbf{x}|\omega_1)p(\omega_1)$:
$$
p(\omega_1|\mathbf{x}) = \frac{1}{1 + \frac{p(\mathbf{x}|\omega_2)p(\omega_2)}{p(\mathbf{x}|\omega_1)p(\omega_1)}}
$$
Since:
$$
\frac{p(\mathbf{x}|\omega_2)p(\omega_2)}{p(\mathbf{x}|\omega_1)p(\omega_1)} = \exp\left(\text{ln}\left(\frac{p(\mathbf{x}|\omega_2)p(\omega_2)}{p(\mathbf{x}|\omega_1)p(\omega_1)}\right)\right)
$$
Then:
$$
p(\omega_1|\mathbf{x}) = \frac{1}{1 + \exp\left(\text{ln}\left(\frac{p(\mathbf{x}|\omega_2)p(\omega_2)}{p(\mathbf{x}|\omega_1)p(\omega_1)}\right)\right)} = \sigma\left(\text{ln}\left(\frac{p(\mathbf{x}|\omega_2)p(\omega_2)}{p(\mathbf{x}|\omega_1)p(\omega_1)}\right)\right) \tag{3} \label{eq3}
$$
Where $\sigma(\cdot)$ is the logistic function. Note that since the right hand side of equation \ref{eq3} is only a function of the feature vector $\mathbf{x}$, then let:
$$
\sigma\left(\text{ln}\left(\frac{p(\mathbf{x}|\omega_2)p(\omega_2)}{p(\mathbf{x}|\omega_1)p(\omega_1)}\right)\right) = \sigma(f(\mathbf{x}))
$$
Where:
$$
f(\mathbf{x}) = \text{ln}\left(\frac{p(\mathbf{x}|\omega_2)p(\omega_2)}{p(\mathbf{x}|\omega_1)p(\omega_1)}\right)
$$
Since:
$$
\begin{align}
p(\omega_1|\mathbf{x}) + p(\omega_2|\mathbf{x}) &= 1 \\
p(\omega_2|\mathbf{x}) &= 1 - p(\omega_1|\mathbf{x})
\end{align}
$$
Then the decision rule for the Bayes classifier becomes:
$$
y =
\begin{cases}
+1 & \text{if} \quad \sigma(f(\mathbf{x})) > 1 -  \sigma(f(\mathbf{x})) \\
-1 & \text{if} \quad \sigma(f(\mathbf{x})) < 1 - \sigma(f(\mathbf{x}))
\end{cases}
$$
Or:
$$
y =
\begin{cases}
+1 & \text{if} \quad \sigma(f(\mathbf{x})) > \frac{1}{2} \\
-1 & \text{if} \quad \sigma(f(\mathbf{x})) < \frac{1}{2}
\end{cases}
$$
Notice that for the logistic function, given an arbitrary input $a \in \mathbb{R}$, $\sigma(a) \geq 0.5$ for $a \geq 0$ and $\sigma(a) < 0.5$ for $a < 0$. This means that the Bayes classifier decision rule can be further simplified to:
$$
y =
\begin{cases}
+1 & \text{if} \quad f(\mathbf{x}) > 0 \\
-1 & \text{if} \quad f(\mathbf{x}) < 0
\end{cases} \tag{4} \label{eq4}
$$
Equation \ref{eq1} can be re-written as:
$$
y =
\begin{cases}
+1 & \text{if} \quad \text{dist}(\mathbf{x},\mathbf{c}_+) - \text{dist}(\mathbf{x},\mathbf{c}_-) < 0 \\
-1 & \text{if} \quad \text{dist}(\mathbf{x},\mathbf{c}_+) - \text{dist}(\mathbf{x},\mathbf{c}_-) > 0
\end{cases} \tag{5} \label{eq5}
$$
Notice any similarity between equation \ref{eq5} and equation \ref{eq4}? They are in fact almost the same, we just need to flip the sign of $y$ for one of them. However, what is more interesting is that:
$$
f(\mathbf{x}) \equiv \text{dist}(\mathbf{x},\mathbf{c}_+) - \text{dist}(\mathbf{x},\mathbf{c}_-)
$$
The relationship above is almost true. What is missing is $\mathbf{c}_+$ and $\mathbf{c}_-$ in $f(\mathbf{x})$. This leads us to the central idea of almost all of supervised machine learning.
According to the Bayes classifer decision rule, we need to accurately estimate both $p(\omega_1|\mathbf{x})$ and $p(\omega_2|\mathbf{x})$. This in turn requires estimating $p(\mathbf{x}|\omega_1),p(\mathbf{x}|\omega_2),p(\omega_1),$ and $p(\omega_2)$. However, why estimate $p(\mathbf{x}|\omega_1),p(\mathbf{x}|\omega_2),p(\omega_1),$ and $p(\omega_2)$ when we can estimate $p(\omega_1|\mathbf{x})$ and $p(\omega_2|\mathbf{x})$ directly? See this question for more details.
Recall that:
$$
p(\omega_1|\mathbf{x}) = \sigma(f(\mathbf{x}))
$$
Therefore, to estimate $p(\omega_1|\mathbf{x})$ and $p(\omega_2|\mathbf{x})$ directly, we can choose some function $f$ and parameterize it by some parameters $\theta$ and estimate these parameters using the training dataset $\mathcal{D}$:
$$
p(\omega_1|\mathbf{x}) = \sigma(f(\mathbf{x};\theta(\mathcal{D})))
$$
In your case, this function is:
$$
\text{dist}(\mathbf{x},\mathbf{c}_+) - \text{dist}(\mathbf{x},\mathbf{c}_-)
$$
And the parameters are $\theta = (\mathbf{c}_+,\mathbf{c}_-)$, which are estimated using $\mathcal{D}$.


text:
Q: Variable Defined by Input I'm quite new to C and I was wondering if it is possible to have a variable be defined by an input by the user. I've made a simple prime number counter which shows all the prime numbers from 1 to 100 and I was wondering if there is a library or a code which allows me to define a variable by the user input. Here's my code for better understanding.
#include <stdio.h>

int main(void)
{
    for (int i = 2; i < 101; i++) { //I would want the "101" to be a user defined variable
        for (int j = 2; j <= i; j++) {
            if (i == j) {
                printf("%d\n", i);
            }
            else if (i%j == 0) {
                break;
            }
        }
    }
}

Thanks in advance!

A: #include <stdio.h>

int main(void) {
   int num;
   scanf("%d",&num); //to take a user input
 for (int i=2; i<=num; i++) //I would want the "101" to be a user defined variable
 {
  for (int j=2; j<=i; j++)
  {
    if (i == j)
      printf("%d\n",i);
    else if (i%j == 0)
      break;
  }
 }
}

A: Yes, using user input in this way is possible.  (It had better be possible!  Virtually all programs work on user input.)
In general, there are two main ways of doing it.  (1) read from the command line.  (2) read from a "file" -- which might just be the user's keyboard.
Let's look at both of these in turn.
1. Read from the command line.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
 int max;
 if(argc <= 1)
 {
  fprintf(stderr, "usage: %s max\n", argv[0]);
  exit(1);
 }
 max = atoi(argv[1]);
 for (int i=2; i<max; i++)
 {
  for (int j=2; j<=i; j++)
  {
    if (i == j)
      printf("%d\n",i);
    else if (i%j == 0)
      break;
  }
 }
}

To read from the command line, we declare main with two arguments: argc and argv.  When main gets called, argc will be a count of how many arguments there are, and argv will contain those arguments.  argv is an array of strings, or more precisely, an array of pointers to char, or char *.  Also, the first argument will always be the name of the program.
We want the user to type
name_of_the_program 200

to print primes up to 200.  So we make sure that the user typed at least one argument, that is, we complain if argc isn't at leaast 2: one for the name of the program, 1 for the argument the user typed.  Assuming the user did type an argument, it'll be in argv[1].  (argc[0] is the program name.)  The command-line arguments are always passed as strings, but we want a number, an int.  So we call atoi to convert the string on the command line (like "200") to an int (like 200).
2. Read from a file.
In this case, the "file" we're going to read from is stdin, the standard input, which by default is the user's keyboard.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
 int max;
 char input_line[100];
 printf("How high to go? "); fflush(stdout);
 fgets(input_line, 100, stdin);
 max = atoi(input_line);
 if(max == 0)
 {
  fprintf(stderr, "try typing a number next time\n");
  exit(1);
 }
 for (int i=2; i<max; i++)
  ...

We print a prompt to tell the user what we need him to type.  We call
 fgets(input_line, 100, stdin);

to read one line of input -- that is, we expect the user to type some stuff, then hit RETURN.  Since we declared input_line to be an array of 100 characters, it's important that we tell fgets how big it is, so that fgets can be sure not to put more than 100 characters into the array.  (That could happen if the user, just to be ornery, typed 100 or more characters before hitting RETURN.)
Similarly to the command line case, we've read input_line as a line of text, a string.  So we call atoi again, to convert that string to an int.  Also, we make sure that the number is not 0.  If the user types "abc" or something, that isn't even a number, atoi will return 0, and we catch that, since we'd never want to try to print prime numbers up to 0.
[P.S. As an alternative to the fgets plus atoi technique I've presented here, another popular method is the scanf function (as illustrated, in fact, in another answer to this question).  You can use scanf, and it even seems pretty easy at first, but in the long run it's harder, and there are a bunch of things it doesn't handle at all well.  So I recommend learning how to use fgets and friends as soon as you can.]


text:
Q: using spring NamedParameterJdbcTemplate insertbatch method, insert object that have inner object I'm using Spring-boot and Oracle and I want to insert in to my database table new record using NamedParameterJdbcTemplate insertbatch method.
but my object(ProductMarket) have inner object(Market) with the value I need (getMarket().getId())
how can I tell SqlParameterSource to take the market id from the inner Object?
package x.dao.productMarket;

import java.util.List;

import x.model.base.ProductMarket;

public interface IProductMarketDao {

    public static final String INSERT_PRODUCT_MARKETS =
        " INSERT " +
        " INTO PRODUCT_MARKETS" +
        " (" +
        "    product_id ," +
        "    market_id" +
        " )" +
        " VALUES" +
        " (" +
        "    :productId ," +
        "    :marketId " +
        " ) ";

    void insert(List < ProductMarket > productMarkets);

}

package x.dao.productMarket;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Repository;

import x.model.base.ProductMarket;

@
Repository
public class ProductMarketDao implements IProductMarketDao {

    @
    Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @
    Override
    public void insert(List < ProductMarket > productMarkets) {
        SqlParameterSource[] batch =
            SqlParameterSourceUtils.createBatch(productMarkets.toArray());
        namedParameterJdbcTemplate.batchUpdate(INSERT_PRODUCT_MARKETS,
            batch);
    }
}

package x.model.base;

public class ProductMarket implements Serializable {

    private static final long serialVersionUID = 421870753189756693 L;

    private long productId;
    private Market market;

    /**
     * @return the productId
     */
    public long getProductId() {
            return productId;
        }
        /**
         * @param productId the productId to set
         */
    public void setProductId(long productId) {
        this.productId = productId;
    }

    public Market getMarket() {
        return market;
    }
    public void setMarket(Market market) {
        this.market = market;
    }

}

A: Supposing that the definition of market is as follows:
class Market {
    private final int id;
    private final String name;

    public Market(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

Then you can change your SQL template as follows:
static final String INSERT_PRODUCT_MARKETS =
        " INSERT " +
                " INTO product_markets" +
                " (" +
                "    product_id ," +
                "    market_id" +
                " )" +
                " VALUES" +
                " (" +
                "    :productId ," +
                "    :market.id " +
                " ) ";

Notice how I use a path to represent the named parameter in the form :market.id where market is the name of the field in ProductMarket and id is the name of field in Market.
Once defined in this way, the NamedParameterJdbcTemplate will be able to dereference the corresponding value and use it as the argument for the query.


text:
Q: Download file extract to specific directory with cURL I wish for the file to download to ~/downloads and keep the same filename. Then I want that file to be extracted (contents) to the ~/downloads/ok directory. ~/downloads/ok directory exists.
curl -Lo ~/downloads https://github.com/janeczku/haproxy-acme-validation-plugin/archive/0.1.1.tar.gz | tar zxf -C ~/downloads/ok

I get the error: tar (child): -C: Cannot open: No such file or directory

A: If you're saving the file to some location in curl, then piping to tar is pointless: there's no data being transferred over the pipe. And the f option in tar is for reading from a file (the filename must be the next argument), so that isn't useful in a pipe either. To save to a file and send to a pipe, use tee:
curl -L https://github.com/janeczku/haproxy-acme-validation-plugin/archive/0.1.1.tar.gz |
  tee ~/downloads/0.1.1.tar.gz |
  tar zx -C ~/downloads/ok

A: you may want
(cd ~/downloads && curl -L https://github.com/janeczku/haproxy-acme-validation-plugin/archive/0.1.1.tar.gz && cd ok && tar zxf ../0.1.1.tar.gz)

or more readably
(
    f='https://github.com/janeczku/haproxy-acme-validation-plugin/archive/0.1.1.tar.gz'
    cd ~/downloads &&
    curl -L $f &&
    cd ok &&
    tar zxf ../${f##*/}
)

I'm using parentheses to run the commands in a subshell so your current dir in your current shell is not altered

A: You need to redirect the file itself to the destination directory :
curl -LOk https://github.com/janeczku/haproxy-acme-validation-plugin/archive/0.1.1.tar.gz > ~/downloads/0.1.1.tar.gz

And proceed with the archive extraction.

A: curl -SL https://download.example.org/abc.tar.gz | tar -zxC /opt

will produce /opt/abc folder.
The -x for extract, -z for .gz and -C for destination directory,


text:
Q: More than one relationship to a class in a Class Diagram In a class diagram, is it possible to have two classes with more than one relationship? For example, a generalization relationship and a composition relationship?
For instance,

You can have either a composition relationship or a generalization relationship. A frozen Chocolate is a chocolate. But if you destroy the chocolate class the frozen chocolate class would also be destroyed. which also makes it a composition relationship.
But can you have both on the same diagram, or would you have to stick to one? Which one in this case?

A: This is a generalization relationship, FrozenChocolate is a Chocolate but adds extra properties. It is not a compositions, you cannot say that Chocolate has a FrozenChocolate.
Your argument about destroying Chocolate resulting in FrozenChocolate also being destroyed is invalid. These are not object instances. You cannot say that destroying Animal means that Dog is destroyed.


text:
Q: Why does powershell fail when run from registry open/command I'm trying to register a PowerShell script to run when I click on a URL in a Windows app (such as Outlook). (I want to be able to open URLs in different browsers/apps based on different URL patterns).
I've added
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file c:\win\bin\url-handler.ps1 "%1"

to HKEY_CLaSSES_ROOT\http\shell\open\command (replacing Google Chrome, my default).
The command works fine when in I run it from a CMD console. However, when I click a URL in Outlook, a console window opens, a red error message appears, then the console closes too quickly for me to read it.
The only error logs I can find in Event Viewer (for application PowerShell) shows
Engine state is changed from Available to Stopped.

Details:
NewEngineState=Stopped
PreviousEngineState=Available

SequenceNumber=10

HostName=ConsoleHost
HostVersion=2.0
HostId=7ca63c36-fcc1-4fbe-9488-dfc505a80141
EngineVersion=2.0
RunspaceId=a28185bd-f8da-4648-99aa-86066d199e04
PipelineId=
CommandName=
CommandType=
ScriptName=
CommandPath=
CommandLine=

Setting policy to Unrestricted did not solve this.
How can I track down what the error might be and how to fix it?

A: add -noexit to your command line to prevent that the PowerShell console immediately closes.


text:
Q: How to make a new dataframe with original tweets I am performing a sentiment analyses on tweets. I have made an algorithm that removes emoji's and some special characters before calculating the sentiment of the tweet. After that, the tweet without emoji's and special characters is put into a dataframe with the sentiments. Here is the code:
x = 0
a = 0
d = {}
for vertaling in df['text']:

    bericht = re.sub('[^A-Za-z0-9]', ' ', df['text'].iloc[x])
    bericht = re.sub(' +',' ', bericht)

    translations = translator.translate([bericht], dest='en')

    for translation in translations:
        a = a + 1
        print(a)
        print(translation.origin)
        analysis = TextBlob(translation.text)
        print(analysis.sentiment)
    x = x + 1
    d[translation.origin] = analysis.sentiment
c = ['Tweets','Sentiment']
df2 = pd.DataFrame(list(d.items()), columns=c)

I want the original tweet combined with the calculated sentiments. The code provided above combines the filtered tweets with the sentiment in this certain line:
c = ['Tweets','Sentiment']
df2 = pd.DataFrame(list(d.items()), columns=c)
Does anyone know a way where I can combine the original tweet with the new calculated sentiment in a dataframe?

A: Nevermind, I found the solution myself. Solution:
x = 0
a = 0
d = {}
#df2 = pd.DataFrame(['Tweets', 'Sentiment'])
df['Tweets'] = ""
df['Sentiment'] = ""
for vertaling in df['text']:

    df['Tweets'].iloc[x] = df['text'].iloc[x]

    bericht = re.sub('[^A-Za-z0-9]', ' ', df['text'].iloc[x])
    bericht = re.sub(' +',' ', bericht)

    translations = translator.translate([bericht], dest='en')

    for translation in translations:
        a = a + 1
        print(a)
        print(translation.origin)
        analysis = TextBlob(translation.text)
        df['Sentiment'].iloc[x] = analysis.sentiment

    x = x + 1
    d[translation.origin] = analysis.sentiment

This combines the new columns to my existing one.


text:
Q: Angular Http failure during parsing for url I got an error while posting form data using http.post method in angular. I am storing form data successfully into database, but http returns parsing error like this:
HttpErrorResponse
error: {error: SyntaxError: Unexpected token I in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "Inserted Successfully"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/api/post"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"

I could not figure out where is the problem.  API is written in Spring boot
Here is my code
component.ts
details: UserDetails = {
    firstName: '',
    lastName: '',
    email: '',
    adress: '',
    city: '',
    state: ''
  };

    public sendDetails(): void {
          const url  = 'http://localhost:8080/api/post';
          const headers = new HttpHeaders().set('Content-Type', 'application/json');
          this.http.post(url, JSON.stringify(this.details), {headers : headers} ).subscribe(
            data => {
              console.log(data);
            },
            err => {
              console.error(err);
            }
          );
      }

Service.java
public String postData(Map map) throws SQLException {
    Connection conn = null;
    CallableStatement cs = null;
    try {
      conn = ds.getConnection();
      cs = conn.prepareCall("Begin leo_pack.leo_postUserData1(?, ?, ?, ?, ?, ?); End;");
      cs.setString(1, String.valueOf(map.get("firstName")));
      cs.setString(2, String.valueOf(map.get("lastName")));
      cs.setString(3, String.valueOf(map.get("email")));
      cs.setString(4, String.valueOf(map.get("adress")));
      cs.setString(5, String.valueOf(map.get("city")));
      cs.setString(6, String.valueOf(map.get("state")));

      cs.execute();
      return "Inserted Successfully";

    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      if (cs != null) cs.close();
      if (conn != null) ds.evictConnection(conn);
    }
    return null;
  }

Controller.java
   @PostMapping(value = "/post", consumes = MediaType.APPLICATION_JSON_VALUE)
    private String test(@RequestBody Map map, BindingResult binding) throws SQLException, ValidationException {

        if(binding.hasErrors()){
            throw new ValidationException("error !!! ");
        }
        return service.postData(map);
    }

A: this.details don't need to be stringified. Also setting the Content-Type header as  application/json is redundant.
Give this a try:
constructor(private http: HttpClient, ...) {}

...

public sendDetails(): void {
  const url = 'http://localhost:8080/api/post';
  this.http.post(url, this.details).subscribe(
    data => {
      console.log(data);
    },
    err => {
      console.error(err);
    }
  );
}


text:
Q: deepdiff not calculating difference properly so while i was working with deepdiff i am facing some issues . while it is working fine on all type of changes most of the time . but some times it is giving an in correct difference . mostly when
the attribute.
ignore_order= True

but this is a necessary attribute .
it is not reading the json json properly . and mixing up the object as the json is very nested .
i tried checking on what kind of difference it is giving an error but it is pretty unclear as even for the same type of changes it is working fine most of the time . and the error is occuring at pretty random places.


text:
Q: How to auto login in angularjs application with url Can anyone say me how to auto login with angularjs 1.x .I will be sending the email with url and when they click on that url it should autoredirect to home page.
The url will be having email and encrypted password:
http://localhost:8080/login/amg1.2.3@outlook.com/$2a$08$cZPWmzta7Gn9Mj14r7zGWeMPKNKkkg8JS3gWNL2fQaFuBwrhgKQC
Clicking on this url should redirect me to home page without any login page.
I am using passport for login functionality.
can you explain me how,iam using passport with form post like this
app.get('/login/:email/:pwd', function(req, res) {
  console.log(req.params.email);
  console.log(req.params.pwd);
  var request = require('request');
  request.post({
    headers: {'content-type' : 'application/x-www-form-urlencoded'},
    url:     'http://localhost:8080/login/',
    form:    { email: req.params.email,password:req.params.pwd }
  }, function(error, response, body){
    console.log(error);
    console.log(body);
    console.log(response);
  });
});

Please check the gist how I am doing and tell me how can i improve the code gist.github.com/agupta330/0fb55b50eecf4b1305ebfe15869b295d

A: It has nothing to do with angular, because it is serverside.
You should not use the encryted password, because your link will never expire. It is better to generate a random key and store it in your database like you do it with sessions ids.
If the user clicks on the link an the key is valid and not expires, you generate a new session and send the session cookie together with the redict to your angular page to the user.
For the angular page you not have to change anything, because it seems like the user is loggedin like normal (with the session in the cookie)