text:
Q: IIS Rewrite - Add WWW but not to subdomains I run an online service where I recently added an AWS Load Balancer.
Before, everything was running on domains without www, but due to the AWS ELB can change its IP, we have to run the setup with CNAME records instead of A records.
CNAME records cannot point to the root domain. So I have to rewrite everything to www.
We have multiple customers and about 50% of them use their own domain, the rest is running as a subdomain to our main domain.
What I need is:
example.com -> www.example.com
www.example.com -> www.example.com
customer1.ourdomain.com --> customer1.ourdomain.com
customer2.ourdomain.com --> customer2.ourdomain.com

I am not the best in setting up rules for IIS rewrite in web.config, but I hope that someone can point me to the correct solution.
Previously we've been running with this, for removing www, but now I need the opposite.
    <rule name="Remove www" stopProcessing="true">
      <match url="(.*)" ignoreCase="true" />
      <conditions logicalGrouping="MatchAll">
        <add input="{HTTP_HOST}" pattern="^www\.(.+)$" />
      </conditions>
      <action type="Redirect" url="http://{C:1}/{R:0}" appendQueryString="true" redirectType="Permanent" />
    </rule>

Everything is running http (for now).

A:     <rule name="Add www">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^ourdomain\.com" />
      </conditions>
      <action type="Redirect" url="http://www.{HTTP_HOST}{UNENCODED_URL}" redirectType="Permanent" />
    </rule>


text:
Q: How to pass a map in react native I am building a chat and need to pass the data inside the key "buttons" as a Prop to a component. Can anyone clarify how should I do this?
I don't know what is the exact PropType to use in this case.
This is the json of the response from where I wanto to get the data:
{
"answer": {
    "key": "1605009993OpdNRfNx",
    "name": "Text message example",
    "modules": [null, {
        "position": 1,
        "text": "Text message description",
        "textHTML": "Text message description",
        "type": "text",
        "buttons": {
            "1605010005zDRgizhW": {
                "key": "1605010005zDRgizhW",
                "payload": "1605009983S6UBYapR",
                "position": 1,
                "text": "button 1"
            },
            "16050100433baadqRu": {
                "key": "16050100433baadqRu",
                "payload": "1605010037bRkMrp9V",
                "position": 2,
                "text": "button 2"
            }
        }
    }]
}

}
Thanks in advance

A: Parse the json, then pull out the object named "buttons". After that, pass the buttons object to the child component.
Here is an example:
App.js
import React from 'react';
import {View} from "react-native";
import TestComponent from "./TestComponent";

const jsonData = "{\n" +
    "\"answer\": {\n" +
    "    \"key\": \"1605009993OpdNRfNx\",\n" +
    "    \"name\": \"Text message example\",\n" +
    "    \"modules\": [null, {\n" +
    "        \"position\": 1,\n" +
    "        \"text\": \"Text message description\",\n" +
    "        \"textHTML\": \"Text message description\",\n" +
    "        \"type\": \"text\",\n" +
    "        \"buttons\": {\n" +
    "            \"1605010005zDRgizhW\": {\n" +
    "                \"key\": \"1605010005zDRgizhW\",\n" +
    "                \"payload\": \"1605009983S6UBYapR\",\n" +
    "                \"position\": 1,\n" +
    "                \"text\": \"button 1\"\n" +
    "            },\n" +
    "            \"16050100433baadqRu\": {\n" +
    "                \"key\": \"16050100433baadqRu\",\n" +
    "                \"payload\": \"1605010037bRkMrp9V\",\n" +
    "                \"position\": 2,\n" +
    "                \"text\": \"button 2\"\n" +
    "            }\n" +
    "        }\n" +
    "    }]\n" +
    "}\n" +
    "}"

export default function App() {

    const data = JSON.parse(jsonData);
    const buttons = data.answer.modules[1].buttons;

    return (
        <View style={{flex: 1, justifyContent: "center", alignItems: "center"}}>
            <TestComponent buttons={buttons} />
        </View>
    );
}

TestComponent.js
import React from "react";
import {View, StyleSheet, Button} from "react-native";

const TestComponent = props => {

    const { buttons } = props;

    const onPressHandler = () => {
        console.log(buttons);
    }

    return (
        <View>
            <Button title={"Press Me."} onPress={onPressHandler} />
        </View>
    );
};

export default TestComponent;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Firebase error saving rules, Line 1: mismatched input How can I resolve this error in Firestore security rules?

A: You are missing the rules version line at the top and also the syntax you are using is for Firebase realtime database. Try the following rules for Firestore.
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}


text:
Q: Is it bad programming practice to create a static singelton of main class in java? I am considering using the Singelton Design Pattern and create a Singelton of my Main class. While I was searching, I found some comments that this is rather bad programming practice, especially since the declaration of a static method does not do justice to object-oriented programming. Do you have any suggestions for improving my code?
public class MainClass {
private static MainClass instance = new MainClass();

public static MainClass getMainInstance() {
    return instance;
}

public static void main(String[] args) {
    MainClass main = Main.instance;
}
}

A: First of all for a singleton Object implemented on the class must includes the following.

*

*it Should have all the constructor marked private.

*it should have the static method having the logic to create the object exactly only one time.

*it should have the static reference class variable to hold the single possible instance.

with these we can ensure the Singleton object, but this is not the only way as we can have the creational design pattern or the Fly weight design pattern to overcome the static method call.

Regarding Static keyword, it is still using the Class instance of a
  object. As we all know any object have the equivalent Singleton class
  object that gets created on the heap during class loading process. So
  it is not out of OOPS.

Hope this helps !!!

A: While the use of design patterns often helps in clean programming overusing them in cases where there are not necessary will lead to overcomplicated code.
If you want to create a singleton of your application it would be more beneficial to declare a class or better an enum that contains the application that will be run by your main function.
Using a enum:
public enum Application{
    instance;

    public void run(){
    //do awesome stuff
    }
}

This has the effect that even through serialization the application can not be duplicated but also that you can not generalize your application with interfaces.
When using a normal class to implement a singelton you need to make the constructor private or protect the class otherwise from beeing instanciated again.
Using a normal class with private constructor:
public class Application{
    private static final Application instance = new Application();

    private Application(){}

    public Application getApplication(){
        return instance;
    }

    public void run(){
    //do awesome stuff
    }
}

This variant has the advantage that the class can still implement interfaces or extend classes e.g. Runnable.
The disadvantage would be that through the use of serialization the class can still be instanciated multiple time.


text:
Q: Create a Chrome cube in OpenGL / Glut? I'm attempting to make a chromed cube in GLUT / OpenGL and I'm not sure exactly how to do it.
I looked up a "Materials Table" in a textbook which showed "Chrome" as being:
Ambient: (0.25, 0.25, 0.25), Diffuse: (0.4, 0.4, 0.4), and Specular: (0.774597,0.774597,0.774597).
My question is, how do I create a simple cube and apply this material/texture to it in Glut/OpenGL?
Do I use "glutSolidCube()"?  If so, how do I then apply the chrome texture to it?
Can any GLUT/OpenGL people point me in the right direction?

A: This should be as simple as calling glMaterialfv() before glutSolidCube().
I haven't done OpenGL since school, but here's some display loop code from an old project that used a sphere that should get you on the right track:
_Ambient[CHROME][0] = 0.25f;
_Ambient[CHROME][1] = 0.25f;
_Ambient[CHROME][2] = 0.25f;
_Ambient[CHROME][3] = 1.0f;
_Diffuse[CHROME][0] = 0.4f;
_Diffuse[CHROME][1] = 0.4f;
_Diffuse[CHROME][2] = 0.4f;
_Diffuse[CHROME][3] = 1.0f;
_Specular[CHROME][0] = 0.774597f;
_Specular[CHROME][1] = 0.774597f;
_Specular[CHROME][2] = 0.774597f;
_Specular[CHROME][3] = 1.0f;
_Shininess[CHROME] = 76.8f;

void Display()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glPushMatrix();
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, _Ambient[CHROME]);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, _Diffuse[CHROME]);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, _Specular[CHROME]);
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, _Shininess[CHROME]);
    // Translations...
    glutSolidSphere(_Radius, _Slices, _Stacks);
  glPopMatrix();

  glFlush();

  glutSwapBuffers();
}

A: Have you looked at environment mapping? You want your object to reflect light from other objects in the environment, so you basically apply a texture that looks like the environment and generate texture coordinates based on normals. This will give the surface a mirrored appearance. You can have OpenGL automatically generate texture coordinates for each vertex based with glTexGen.
NeHe tutorial 23 covers this with sphere mapping. You can also generate your own texture coordinates per-vertex or per-pixel using GLSL. Here's a tutorial on that.


text:
Q: If $A=\bigcup F_i$ is a filtered algebra, why is the multiplication on $\mathcal{G}(A)=\bigoplus (F_n/F_{n-1})$ well-defined?
From the wiki page, suppose $A=\bigcup F_i$ is a filtered algebra, and $\mathcal{G}(A)=\bigoplus_{n\geq 0}G_n$ the associated graded algebra, where $G_0=F_0$ and $G_n=F_n/F_{n-1}$. The multiplication is defined by
  $$(x+F_{n-1})(y+F_{m-1})=xy+F_{n+m-1}.
$$ Why is this well-defined?

If $x,x'\in F_n$ and $y,y'\in F_m$, such that $x-x'\in F_{n-1}$ and $y-y'\in F_{m-1}$, then
$$
(x-x')(y-y')=xy-x'y-xy'+x'y'\in F_{n+m-2}
$$
and then $xy-x'y'=x'y+xy'-2x'y'+z$ for some $z\in F_{n+m-2}$. Presumably the RHS is in $F_{n+m-1}$ so that $xy+F_{n+m-1}=x'y'+F_{n+m-1}$. But $x'y,xy',x'y'\in F_{n+m}$, so it's not clear to me why that would be true.

A: Note that you have
$$x'y + xy' - 2x'y' = x' (y-y') + y' (x - x') \in F_{n} F_{m-1} + F_{m} F_{n-1} \subseteq F_{n+m-1} $$
using your assumptions on $y-y'$ and $x - x'$.


text:
Q: Find color in image: how could reduce cpu usage? I have this piece of code:
im = Image.open( 'image.png' )

eachPixel = im.load( )
width, height = im.size

for x in range( 0, width ):
    for y in range( 0, height ):
        if eachPixel[ x, y ] == ( 255, 0, 0 ):
            return = True

Works, i only need the position of the first pixel with this color, any way to reduce cpu usage? the image is 800x600, sleep not work because this is for while loop in realtime.
Replacing colors, removing, crop, or using another lib, anything. Thanks!
Sorry my bad english.

A: You can do it with numpy like this. I used this image for testing:

The code is:
#!/usr/bin/env python3
import numpy as np
from PIL import Image

# Load image and make into NumPy array
im=np.array(Image.open('image.png').convert('RGB'),dtype=np.uint8)

# Colour we are looking for
red=np.array([255,0,0],dtype=np.uint8)

# Find the red pixels
np.where(np.all(im==red,axis=-1))

The result is:
(array([10, 10, 10, 11, 11, 11]), array([10, 11, 12, 10, 11, 12]))

which means the first red pixel is at 10,10, the second at 10,11 etc.
On my Mac, that takes 7.03ms for an 800x600 image.

Just to check, we can dump the image using ImageMagick like this and check where the red pixels are:
convert image.png txt:

Output
# ImageMagick pixel enumeration: 23,22,65535,srgb
0,0: (0,65535,0)  #00FF00  lime
1,0: (0,65535,0)  #00FF00  lime
2,0: (0,65535,0)  #00FF00  lime
...
...
7,10: (0,65535,0)  #00FF00  lime
8,10: (0,65535,0)  #00FF00  lime
9,10: (0,65535,0)  #00FF00  lime
10,10: (65535,0,0)  #FF0000  red    <--- red
11,10: (65535,0,0)  #FF0000  red    <--- red
12,10: (65535,0,0)  #FF0000  red    <--- red
13,10: (0,65535,0)  #00FF00  lime
14,10: (0,65535,0)  #00FF00  lime
...
...
8,11: (0,65535,0)  #00FF00  lime
9,11: (0,65535,0)  #00FF00  lime
10,11: (65535,0,0)  #FF0000  red   <--- red
11,11: (65535,0,0)  #FF0000  red   <--- red
12,11: (65535,0,0)  #FF0000  red   <--- red
13,11: (0,65535,0)  #00FF00  lime
14,11: (0,65535,0)  #00FF00  lime
15,11: (0,65535,0)  #00FF00  lime
...
...

If the red pixels are often near the top of the image, you could do 1/4 of the image at a time, or if you have 4 CPU cores, you could do 1/4 of the image on each core:
np.where(np.all(im[0:height//4,:,:]==red,axis=-1))

That takes 1.7ms instead of 7ms.


text:
Q: How to prove $\Bigg|{\sum^{\infty}_{n=m}a_n}\Bigg|\leq \sum^{\infty}_{n=m}|a_n|$ How to prove $$\Bigg|{\sum^{\infty}_{n=m}a_n}\Bigg|\leq \sum^{\infty}_{n=m}|a_n|$$
Where $\sum^{\infty}_{n=m}a_n$ is absolutely convergent.
I can prove this for finite series.

A: If $A_n\leq B_n$ for every $n,$ and the sequences $(A_n)_n$ and $(B_n)_n$ converge to, respectively, $A$ and $B,$ then $A\leq B.$
This is from the definition of convergence (Definitions are tools to be used!): Take any $r>0.$  There are only finitely many $n$ for which $A_n\leq A-r$ and there are only  finitely many $n$ for which $B_n\geq B+r.$ So for all but a finite collection of values of $n$ we have both $A_n>A-r$ and $B_n<B+r.$
It suffices for this Q that what we have, so far, is that for any $r>0$ there exists some $n$ such that $(A_n>A-r\land B_n<B+r)$ and hence $$B+r>B_n\geq A_n>A-r.$$ This implies $B+r>A-r,$ equivalently $$B-A>-2r.$$ Now this is true for any positive number $r$, so $(-2r)$ can be any negative number. So $B-A$ is greater than any negative number, so $B-A\geq 0.$
In your Q, apply this with  $A_n=|\sum_{j=m}^{m+n}a_j|$ and $B_n=\sum_{j=m}^{m+n}|a_j|.$

A: As $\sum_{k=1}^\infty|a_k|$ converges, its partial sums as sequence have the Cauchy property. By the finite application of the triangle inequality, as you did, you find that
$$
\left|\sum_{k=n}^\infty a_k-\sum_{k=m}^\infty a_k\right|\le\left|\sum_{k=n}^\infty |a_k|-\sum_{k=m}^\infty|a_k|\right|
$$
so that the Cauchy property also translates to the partial sums of $\sum_{k=1}^\infty a_k$. As $\Bbb R$ is a complete metric space, every Cauchy sequence converges. Now you can commute absolute value and limit on the left side in
$$
\lim_{n\to\infty}\left|\sum_{k=m}^n a_k\right|\le \lim_{n\to\infty}\sum_{k=m}^n |a_k|=\sum_{k=m}^\infty |a_k|
$$
to get your claim.

A: By the result for finite series, we have
$$|\sum_{n=m}^{M}a_n| \le \sum_{n=m}^{M}|a_n|\le \sum_{n=m}^{\infty}|a_n| .$$
for all $M.$ So the expression on the left is bounded above by $ \sum_{n=m}^{\infty}|a_n|$ for all $M.$ It follows that the limit as $M\to \infty$ of the expression on the left is bounded above by $ \sum_{n=m}^{\infty}|a_n|.$ In other words
$$|\sum_{n=m}^{\infty}a_n| \le \sum_{n=m}^{\infty}|a_n|.$$


text:
Q: What are some elegant features or uses of Perl?
What?  Perl Beautiful?  Elegant?  He must be joking!

It's true, there's some ugly Perl out there.  And by some, I mean lots.  We've all seen it.

Well duh, it's symbol soup.  Isn't it?

Yes there are symbols.  Just like 'math' has 'symbols'.  It's just that we programmers are more familiar with the standard mathematical symbols.  We grew to accept the symbols from our mother languages, whether that be ASM, C, or Pascal.  Perl just decided to have a few more.

Well, I think we should get rid of all the unnecessary symbols.  Makes the code look better.

The language for doing so already exists.  It's called Lisp.  (and soon, perl 6.)

Okay, smart guy.  Truth is, I can already invent my own symbols.  They're called functions and methods.  Besides, we don't want to reinvent APL.

Oh, fake alter ego, you are so funny!  It's really true, Perl can be quite beautiful.  It can be quite ugly, as well.  With Perl, TIMTOWTDI.
So, what are your favorite elegant bits of Perl code?

A: A favorite example of mine is Perl's implementation of a factorial calculator.  In Perl 5, it looks like so:
use List::Util qw/reduce/;
sub factorial {
    reduce { $a * $b } 1 .. $_[0];
}

This returns false if the number is <= 1 or a string and a number if a number is passed in (rounding down if a fraction).
And looking forward to Perl 6, it looks like this:
sub factorial {
    [*] 1..$^x
}

And also ( from the blog in the link above ) you can even implement this as an operator:
sub postfix:<!>(Int $x) {
    [*] 1..($x || 1)
}

and then use it in your code like so:
my $fact5 = 5!;

A: Three-line classes with constructors, getter/setters and type validation:
{
    package Point;
    use Moose;

    has ['x', 'y'] => (isa => 'Num', is => 'rw');
}

package main;
my $point = Point->new( x => '8', y => '9' );

$point->x(25);

A: If you have a comma separated list of flags, and want a lookup table for them, all you have to do is:
my %lookup = map { $_ => 1 } split /,/, $flags;

Now you can simply test for which flags you need like so:
if ( $lookup{FLAG} ) {
    print "Ayup, got that flag!";
}

A: I am surprised no one has mentioned this. It's a masterpiece in my opinion:

#!/usr/bin/perl
                                           $==$';
                                         $;||$.| $|;$_
             ='*$ (                  ^@(%_+&~~;# ~~/.~~
         ;_);;.);;#)               ;~~~~;_,.~~,.* +,./|~
    ~;_);@-,  .;.); ~             ~,./@@-__);@-);~~,.*+,.
  /|);;;~~@-~~~~;.~~,.           /.);;.,./@~~@-;.;#~~@-;;
  ;;,.*+,./.);;#;./@,./        |~~~~;#-(@-__@-__&$#%^';$__
   ='`'&'&';$___="````"  |"$[`$["|'`%",';$~=("$___$__-$[``$__"|
              "$___"|       ("$___$__-$[.%")).("'`"|"'$["|"'#").
        '/.*?&([^&]*)&.*/$'.++$=.("/``"|"/$[`"|"/#'").(";`/[\\`\\`$__]//`;"
        |";$[/[\\$[\\`$__]//`;"|";#/[\\\$\\.$__]//'").'@:=("@-","/.",
       "~~",";#",";;",";.",",.",");","()","*+","__","-(","/@",".%","/|",
        ";_");@:{@:}=$%..$#:;'.('`'|"$["|'#')."/(..)(..)/".("```"|"``$["|
        '#("').'(($:{$'.$=.'}<<'.(++$=+$=).')|($:{$'.$=.'}))/'.("```;"|
        "``$[;"|"%'#;").("````'$__"|"%$[``"|"%&!,").${$[};`$~$__>&$=`;$_=
       '*$(^@(%_+&@-__~~;#~~@-;.;;,.(),./.,./|,.-();;#~~@-);;;,.;_~~@-,./.,
        ./@,./@~~@-);;;,.(),.;.~~@-,.,.,.;_,./@,.-();;#~~@-,.;_,./|~~@-,.
          ,.);););@-@-__~~;#~~@-,.,.,.;_);~~~~@-);;;,.(),.*+);;# ~~@-,
           ./|,.*+,.,.);;;);*+~~@-,.*+,.;;,.;.,./.~~@-,.,.,.;_)   ;~~~
             ~@-,.;;,.;.,./@,./.);*+,.;.,.;;@-__~~;#~~@-,.;;,.*   +);;
               #);@-,./@,./.);*+~~@-~~.%~~.%~~@-;;__,. /.);;#@-   __@-
                 __   ~~;;);/@;#.%;#/.;#-(@-__~~;;;.;_ ;#.%~~~~  ;;()
                      ,.;.,./@,.  /@,.;_~~@- ););,.;_   );~~,./  @,.
                      ;;;./@,./|  ~~~~;#-(@- __,.,.,.    ;_);~~~ ~@
                       -~~());;   #);@-,./@,  .*+);;;     ~~@-~~
                       );~~);~~  *+~~@-);-(   ~~@-@-_      _~~@-
                       ~~@-);;   #,./@,.;.,    .;.);@      -~~@-;
                       #/.;#-(   ~~@-@-__      ~~@-~~       @-);@
                       -);~~,    .*+,./       |);;;~        ~@-~~
                        ;;;.;     _~~@-@     -__);.         %;#-(
                        @-__@      -__~~;#  ~~@-;;          ;#,.
                        ;_,..         %);@-,./@,            .*+,
                        ..%,           .;.,./|)             ;;;)
                        ;;#~            ~@-,.*+,.           ,.~~
                       @-);            *+,.;_);;.~         ~););
                      ~~,.;         .~~@-);~~,.;.,         ./.,.;
                      ;,.*+        ,./|,.);  ~~@-         );;;,.(
                    ),.*+);                              ;#~~/|@-
                  __~~;#~~                                $';$;;

A: I absolutely love Black Perl (link to version rewritten to compile under Perl 5).  It compiles, but as far as I can tell it doesn't actually do anything.
That's what you get for a language written by a linguist from a pragmatic perspective rather than from a theoretical perspective.
Moving on from that, you can think about the Perl that people complain about as pidgin Perl (perfectly useful, but not expressive, and beware of trying to express anything complex in it), and the stuff that @pjf is talking about as "proper" Perl, the language of Shakespeare, Hemingway, Hume and so on. [edit:  err, though easier to read than Hume and less dated than Shakespeare.] [re-edit and hopefully less alcoholic than Hemingway]

A: Perl facilitates the use of lists/hashes to implement named parameters, which I consider very elegant and a tremendous aid to self-documenting code.
my $result = $obj->method(
    flux_capacitance       => 23,
    general_state          => 'confusion',
    attitude_flags         => ATTITUDE_PLEASANT | ATTITUDE_HELPFUL,
);

A: My favourite pieces of elegant Perl code aren't necessarily elegant at all.  They're meta-elegant, and allow you to get rid of all those bad habits that many Perl developers have slipped into.  It would take me hours or days to show them all in the detail they deserve, but as a short list they include:

*

*autobox, which turns Perl's primitives into first-class objects.

*autodie, which causes built-ins to throw exceptions on failure (removing most needs for the or die... construct).  See also my autodie blog and video).

*Moose, which provide an elegant, extensible, and correct way of writing classes in Perl.

*MooseX::Declare, which provides syntaxic aweseomeness when using Moose.

*Perl::Critic, your personal, automatic, extensible and knowledgeable code reviewer.  See also this Perl-tip.

*Devel::NYTProf, which provides me the most detailed and usable profiling information I've seen in any programming language.  See also Tim Bunce's Blog.

*PAR, the Perl Archiver, for bundling distributions and even turning whole programs into stand-alone executable files.  See also this Perl-tip.

*Perl 5.10, which provides some stunning regexp improvements, smart-match, the switch statement, defined-or, and state variables.

*Padre, the only Perl editor that integrates the best bits of the above, is cross-platform, and is completely free and open source.

If you're too lazy to follow links, I recently did a talk at Linux.conf.au about most of the above.  If you missed it, there's a video of it on-line (ogg theora).  If you're too lazy to watch videos, I'm doing a greatly expanded version of the talk as a tutorial at OSCON this year (entitled doing Perl right).
All the best,
Paul

A: Adding to the love of map and grep, we can write a simple command-line parser.
my %opts = map { $_ => 1 } grep { /^-/ } @ARGV;

If we want, we can set each flag to it's index in @ARGV:
my %opts = map { $ARGV[$_] => $_ } grep { $ARGV[$_] =~ /^-/ } 0 .. $#ARGV;

That way, if a flag has an argument, we can get the argument like this:
if( defined( $opts{-e} ) ) {
  my $arg = $ARGV[ $opts{-e} ];
  # do -e stuff for $arg
}

Of course, some people will cry that we're reinventing the wheel and we should use getopt or some variant thereof, but honestly, this was a fairly easy wheel to reinvent. Plus, I don't like getopt.
If you don't like how long some of those lines are, you can always use intermediate variables or just convenient line breaks (hey, Python fanatics? You hear that? We can put one line of code across two lines and it still works!) to make it look better:
my %opts = map  { $ARGV[$_] => $_   }
           grep { $ARGV[$_] =~ /^-/ } 0 .. $#ARGV;

A: I'm surprised no one mentioned the Schwartzian Transform.
my @sorted =
  map  { $_->[0] }
  sort { $a->[1] <=> $b->[1] }
  map  { [ $_, expensive_func($_) ] }
@elements;

And in the absence of a slurp operator,
my $file = do { local $/; readline $fh };

A: Have a list of files the user wants your program to process? Don't want to accidentally process a program, folder, or nonexistent file? Try this:
@files = grep { -T } @files;

And, like magic, you've weeded out all the inappropriate entries. Don't want to ignore them silently? Add this line before the last one:
warn "Not a file: $_" foreach grep { !-T } @files;

Prints a nice warning message for every file that it can't process to standard error. The same thing without using grep would look like this:
my @good;
foreach(@files) {
  if(-T) {
    push @good, $_;
  } else {
    warn "Not a file: $_";
  }
}

grep (and map) can be used to make code shorter while still keeping it very readable.

A: The "or die" construct:
open my $fh, "<", $filename
    or die "could not open $filename: $!";

The use of qr// to create grammars:
#!/usr/local/ActivePerl-5.10/bin/perl

use strict;
use warnings;
use feature ':5.10';

my $non_zero         = qr{[1-9]};
my $zero             = qr{0};
my $decimal          = qr{[.]};
my $digit            = qr{$non_zero+ | $zero}x;
my $non_zero_natural = qr{$non_zero+ $digit*}x;
my $natural          = qr{$non_zero_natural | $zero}x;
my $integer          = qr{-? $non_zero_natural | $zero}x;
my $real             = qr{$integer (?: $decimal $digit)?}x;

my %number_types = (
    natural => qr/^$natural$/,
    integer => qr/^$integer$/,
    real    => qr/^$real$/
);

for my $n (0, 3.14, -5, 300, "4ever", "-0", "1.2.3") {
    my @types = grep { $n =~ $number_types{$_} } keys %number_types;
    if (@types) {
        say "$n is of type", @types == 1 ? " ": "s ", "@types";
    } else {
        say "$n is not a number";
    }
}

Anonymous subroutines used to factor out duplicate code:
my $body = sub {
    #some amount of work
};

$body->();
$body->() while $continue;

instead of
#some amount of work
while ($continue) {
    #some amount of work again
}

Hash based dispatch tables:
my %dispatch = (
    foo => \&foo,
    bar => \&bar,
    baz => \&baz
);

while (my $name = iterator()) {
    die "$name not implemented" unless exists $dispatch{$name};
    $dispatch{$name}->();
}

instead of
while (my $name = iterator()) {
    if ($name eq "foo") {
        foo();
    } elsif ($name eq "bar") {
        bar();
    } elsif ($name eq "baz") {
        baz();
    } else {
        die "$name not implemented";
    }
}

A: This file parsing mechanism is compact and easy to customize (skip blank lines, skip lines starting with X, etc..).
open(H_CONFIG, "< $file_name") or die("Error opening file: $file_name! ($!)");
while (<H_CONFIG>)
{
   chomp;         # remove the trailing newline
   next if $_ =~ /^\s*$/; # skip lines that are blank
   next if $_ =~ /^\s*#/; # skip lines starting with comments
   # do something with the line
}

I use this type of construct in diverse build situations - where I need to either pre or post process payload files (S-records, etc..) or C-files or gather directory information for a 'smart build'.

A: My favourite elegant Perl feature is that it uses different operators for numerical values and string values.
my $string = 1 . 2;
my $number = "1" + "2";
my $unambiguous = 1 . "2";

Compare this to other dynamic languages such as JavaScript, where "+" is used for concatenation and addition.
var string = "1" + "2";
var number = 1 + 2;
var ambiguous = 1 + "2";

Or to dynamic languages such as Python and Ruby that require type coercion between strings and numberical values.
string = "1" + "2"
number = 1 + 2
throws_exception = 1 + "2"

In my opinion Perl gets this so right and the other languages get it so wrong.

A: Poorer typists like me who get cramps hitting the shift key too often and have an almost irrational fear of using a semicolon started writing our Perl code in python formatted files.  :)
e.g.
>>> k = 5
>>> reduce(lambda i,j: i*j, range(1,k+1),1)
120
>>> k = 0
>>> reduce(lambda i,j: i*j, range(1,k+1),1)
1


text:
Q: bash, can't grep root partition from df using \< \> OS: FreeBSD 8.2, bash
Hey guys,
I'm stumped as to why I can't grep the the line with / partition from df:
/dev/amrd0s1a    1012974    452694     479244    49%    /

I want to be able to grep that line only, (other lines have slashes too) so I figured one of these would work:
df -m | grep -E '\<'/'\>'

df -m | grep -E '\</\>'

df -m | grep -E '\<"/"\>'

but neither of those work, I was wanting to do it this way so I could practice using the '\< \>'. I tried with out the -E as well.
Can this be done? What am I doing wrong?
Thanks in advance!

A: Try:
df -m | grep "/$"

$  means end of line

A: The problem is that \< and \> are for word boundaries, but / is not a word character. Instead match the preceding whitespace and following EOL: [[:space:]]/$.

A: Why not just specifying / as parameter?
  df -m /

to strip off the headline:
  df -m / | tail -n 1

A: You could get this line using the following:
df -m | grep " \+/$"


text:
Q: Vulkan: vkCreateGraphicsPipelines: Access violation reading location 0x00000016.(nvoglv32.dll) Im still stuck same problem for like two weeks and dont know what im supposed to do. Im currently writing a vulkan renderer that is simply supposed to draw a single triangle but i cannot figure out why vkCreateGraphicsPipelines throws the same exceptions every time. In case it helps im following these two tutorials: https://www.youtube.com/watch?v=mzVFHEmnRLg&list=PL58qjcU5nk8uH9mmlASm4SFy1yuPzDAH0 and https://vulkan-tutorial.com/
// RenderingEngine.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
//#include "vulkan\vulkan.h"
#define GLFW_INCLUDE_VULKAN
#include <GLFW\glfw3.h>
#include <iostream>
#include <fstream>
#include <vector>

#define ASSERT_VK(val)\
    if(val != VK_SUCCESS){\
        std::cerr << val;\
        __debugbreak();\
    }

VkInstance instance;
VkSurfaceKHR surface;
VkDevice device;
VkSwapchainKHR swapchain;
uint32_t amountImagesInSwapchain = 0;
VkImageView *imageViews;
GLFWwindow *window;
VkShaderModule shaderModuleVert, shaderModuleFrag;
VkPipelineLayout pipelineLayout;
VkRenderPass renderPass;
VkPipeline pipeline;

const uint32_t WIDTH = 1600;
const uint32_t HEIGHT = 900;
const std::vector<const char*> enabledValidationLayers = {
    "VK_LAYER_LUNARG_standard_validation"
};
std::vector<const char*> enabledExtensions = {
    VK_EXT_DEBUG_UTILS_EXTENSION_NAME
};
const VkFormat usedFormat = VK_FORMAT_B8G8R8A8_UNORM;

VkDebugUtilsMessengerEXT callback;

static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
    VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
    VkDebugUtilsMessageTypeFlagsEXT messageType,
    const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
    void * pUserData) {
    if (messageSeverity > VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
        std::cerr << "Validationlayer: " << pCallbackData->pMessage << std::endl;
    }
    return VK_FALSE;
}
VkResult createDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
    const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT *pCallback) {
    auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
    if (func) {
        return func(instance, pCreateInfo, pAllocator, pCallback);
    }
    else {
        return VK_ERROR_EXTENSION_NOT_PRESENT;
    }
}
void destroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT callback,
    const VkAllocationCallbacks* pAllocator) {
    auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
    if (func) {
        func(instance, callback, pAllocator);
    }
}

std::vector<char> readFile(const std::string &filename) {
    std::ifstream file(filename, std::ios::binary | std::ios::ate);

    if (!file) {
        std::cerr << "Could not open shader!" <<  std::endl;
        throw std::runtime_error("Could not open shaderfile!");
    }
    size_t size = (size_t) file.tellg();
    std::vector<char> fileBuffer(size);
    file.seekg(0);
    file.read(fileBuffer.data(), size);
    file.close();
    return fileBuffer;
}

void startGLFW() {
    glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);

    window = glfwCreateWindow(WIDTH, HEIGHT, "Tech Demo", nullptr, nullptr);
}

void createShaderModule(const std::vector<char> &code, VkShaderModule* shaderModule) {
    VkShaderModuleCreateInfo shaderModuleCreateInfo;
    shaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
    shaderModuleCreateInfo.pNext = nullptr;
    shaderModuleCreateInfo.flags = 0;
    shaderModuleCreateInfo.codeSize = code.size();
    shaderModuleCreateInfo.pCode = (uint32_t*)code.data();

    ASSERT_VK(vkCreateShaderModule(device, &shaderModuleCreateInfo, nullptr, shaderModule));
}

void startVulkan() {
    VkApplicationInfo appInfo;
    appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
    appInfo.pNext = nullptr;
    appInfo.pApplicationName = "RenderingEngine";
    appInfo.applicationVersion = VK_MAKE_VERSION(0, 0, 0);
    appInfo.pEngineName = "RenderingEngine";
    appInfo.engineVersion = VK_MAKE_VERSION(0, 0, 0);
    appInfo.apiVersion = VK_API_VERSION_1_1;

    uint32_t layerAmount = 0;
    vkEnumerateInstanceLayerProperties(&layerAmount, nullptr);
    VkLayerProperties *layers = new VkLayerProperties[layerAmount];
    vkEnumerateInstanceLayerProperties(&layerAmount, layers);

    std::cout << "Amount of layers: " << layerAmount << std::endl;
    for (int i = 0; i < layerAmount; i++) {
        std::cout << "Name:        " << layers[i].layerName << std::endl
            << "Description: " << layers[i].description << std::endl << std::endl;
    }

    uint32_t extensionAmount = 0;
    vkEnumerateInstanceExtensionProperties(nullptr, &extensionAmount, nullptr);
    VkExtensionProperties *extensions = new VkExtensionProperties[extensionAmount];
    vkEnumerateInstanceExtensionProperties(nullptr, &extensionAmount, extensions);

    std::cout << std::endl
        << "Amount of Extension: " << extensionAmount << std::endl;
    for (int i = 0; i < extensionAmount; i++) {
        std::cout << "Name:        " << extensions[i].extensionName << std::endl;
    }

    //TODO: Improve adding
    uint32_t amountGLFWExtensions = 0;
    const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&amountGLFWExtensions);
    for (int i = 0; i < amountGLFWExtensions; i++) {
        enabledExtensions.push_back(glfwExtensions[i]);
    }

    VkInstanceCreateInfo instanceInfo;
    instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
    instanceInfo.pNext = nullptr;
    instanceInfo.flags = 0;
    instanceInfo.pApplicationInfo = &appInfo;
    instanceInfo.enabledLayerCount = enabledValidationLayers.size();
    instanceInfo.ppEnabledLayerNames = enabledValidationLayers.data();
    instanceInfo.enabledExtensionCount = enabledExtensions.size();
    instanceInfo.ppEnabledExtensionNames = enabledExtensions.data();
    std::cout << &instanceInfo << " " << &instance;
    ASSERT_VK(vkCreateInstance(&instanceInfo, nullptr, &instance));

    VkDebugUtilsMessengerCreateInfoEXT debugUtilsMessengerCreateInfo;
    debugUtilsMessengerCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
    debugUtilsMessengerCreateInfo.pNext = nullptr;
    debugUtilsMessengerCreateInfo.flags = 0;
    debugUtilsMessengerCreateInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
        VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
        VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
    debugUtilsMessengerCreateInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
        VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
    debugUtilsMessengerCreateInfo.pfnUserCallback = debugCallback;
    debugUtilsMessengerCreateInfo.pUserData = nullptr;

    ASSERT_VK(createDebugUtilsMessengerEXT(instance, &debugUtilsMessengerCreateInfo, nullptr, &callback ));

    ASSERT_VK(glfwCreateWindowSurface(instance, window, nullptr, &surface))

    vkGetInstanceProcAddr(instance, "");

    uint32_t numberPhysDevices = 0;
    ASSERT_VK(vkEnumeratePhysicalDevices(instance, &numberPhysDevices, nullptr));

    VkPhysicalDevice* physDevices = new VkPhysicalDevice[numberPhysDevices];

    ASSERT_VK(vkEnumeratePhysicalDevices(instance, &numberPhysDevices, physDevices));

    for (int i = 0; i < numberPhysDevices; i++) {
        printStats(physDevices[i]);
    }

    float queuePrios[] = { 1.0, 1.0, 1.0, 1.0 };

    VkDeviceQueueCreateInfo devQueueCreateInfo;
    devQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
    devQueueCreateInfo.pNext = nullptr;
    devQueueCreateInfo.flags = 0;
    //TODO: Choose Familiy Index based on fitting properties
    devQueueCreateInfo.queueFamilyIndex = 0;
    devQueueCreateInfo.queueCount = 1;
    devQueueCreateInfo.pQueuePriorities = queuePrios;

    VkPhysicalDeviceFeatures enabledFeatures = {};
    VkDeviceCreateInfo devCreateInfo;

    const std::vector<const char*> deviceExtensions = {
        VK_KHR_SWAPCHAIN_EXTENSION_NAME
//      VK_EXT_DEBUG_UTILS_EXTENSION_NAME
    };

    devCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
    devCreateInfo.pNext = nullptr;
    devCreateInfo.flags = 0;
    devCreateInfo.queueCreateInfoCount = 1;
    devCreateInfo.pQueueCreateInfos = &devQueueCreateInfo;
    devCreateInfo.enabledLayerCount = 0;
    devCreateInfo.ppEnabledLayerNames = nullptr;
    devCreateInfo.enabledExtensionCount = deviceExtensions.size();
    devCreateInfo.ppEnabledExtensionNames = deviceExtensions.data();
    devCreateInfo.pEnabledFeatures = &enabledFeatures;

    //TODO: Pick best suitable device instead of first one
    ASSERT_VK(vkCreateDevice(physDevices[0], &devCreateInfo, nullptr, &device));

    VkQueue dQueue;
    vkGetDeviceQueue(device, 0, 0, &dQueue);

    VkBool32 surfaceSupport = false;
    ASSERT_VK(vkGetPhysicalDeviceSurfaceSupportKHR(physDevices[0], 0, surface, &surfaceSupport));

    if (!surfaceSupport) {
        std::cerr << "Surface not supported!" << std::endl;
    }

    VkSwapchainCreateInfoKHR swapchainCreateInfo;

    swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
    swapchainCreateInfo.pNext = nullptr;
    swapchainCreateInfo.flags = 0;
    swapchainCreateInfo.surface = surface;
    swapchainCreateInfo.minImageCount = 3;  //TODO: Check validity
    swapchainCreateInfo.imageFormat = usedFormat;
    swapchainCreateInfo.imageColorSpace  = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
    swapchainCreateInfo.imageExtent = VkExtent2D{ WIDTH, HEIGHT};
    swapchainCreateInfo.imageArrayLayers = 1;
    swapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
    swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
    swapchainCreateInfo.queueFamilyIndexCount = 0;
    swapchainCreateInfo.pQueueFamilyIndices = nullptr;
    swapchainCreateInfo.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
    swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
    swapchainCreateInfo.presentMode = VK_PRESENT_MODE_FIFO_KHR;
    swapchainCreateInfo.clipped = VK_TRUE;
    swapchainCreateInfo.oldSwapchain = VK_NULL_HANDLE;

    ASSERT_VK(vkCreateSwapchainKHR(device, &swapchainCreateInfo, nullptr, &swapchain));

    vkGetSwapchainImagesKHR(device, swapchain, &amountImagesInSwapchain, nullptr);
    VkImage *swapchainImages = new VkImage[amountImagesInSwapchain];
    ASSERT_VK(vkGetSwapchainImagesKHR(device, swapchain, &amountImagesInSwapchain, swapchainImages));

    imageViews = new VkImageView[amountImagesInSwapchain];
    for (int i = 0; i < amountImagesInSwapchain; i++) {
        VkImageViewCreateInfo imageViewCreateInfo;
        imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
        imageViewCreateInfo.pNext = nullptr;
        imageViewCreateInfo.flags = 0;
        imageViewCreateInfo.image = swapchainImages[i];
        imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
        imageViewCreateInfo.format = VK_FORMAT_B8G8R8A8_UNORM;
        imageViewCreateInfo.components = VkComponentMapping{ VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY };
        imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
        imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
        imageViewCreateInfo.subresourceRange.levelCount = 1;
        imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
        imageViewCreateInfo.subresourceRange.layerCount = 1;

        ASSERT_VK(vkCreateImageView(device, &imageViewCreateInfo, nullptr, &imageViews[i]));
    }

    std::vector<char> shaderCodeVert = readFile("vert.spv");
    std::vector<char> shaderCodeFrag = readFile("frag.spv");

    createShaderModule(shaderCodeVert, &shaderModuleVert);
    createShaderModule(shaderCodeFrag, &shaderModuleFrag);

    VkPipelineShaderStageCreateInfo pipelineShaderStageCreateInfoVert;
    pipelineShaderStageCreateInfoVert.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    pipelineShaderStageCreateInfoVert.pNext = nullptr;
    pipelineShaderStageCreateInfoVert.flags = 0;
    pipelineShaderStageCreateInfoVert.stage = VK_SHADER_STAGE_VERTEX_BIT;
    pipelineShaderStageCreateInfoVert.module = shaderModuleVert;
    pipelineShaderStageCreateInfoVert.pName = "main";
    pipelineShaderStageCreateInfoVert.pSpecializationInfo = nullptr;

    VkPipelineShaderStageCreateInfo pipelineShaderStageCreateInfoFrag;
    pipelineShaderStageCreateInfoFrag.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
    pipelineShaderStageCreateInfoFrag.pNext = nullptr;
    pipelineShaderStageCreateInfoFrag.flags = 0;
    pipelineShaderStageCreateInfoFrag.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
    pipelineShaderStageCreateInfoFrag.module = shaderModuleVert;
    pipelineShaderStageCreateInfoFrag.pName = "main";
    pipelineShaderStageCreateInfoFrag.pSpecializationInfo = nullptr;

    VkPipelineShaderStageCreateInfo stages[] = { pipelineShaderStageCreateInfoVert, pipelineShaderStageCreateInfoFrag };

    VkPipelineVertexInputStateCreateInfo vertexInputStateCreateInfo;
    vertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
    vertexInputStateCreateInfo.pNext = nullptr;
    vertexInputStateCreateInfo.flags = 0;
    vertexInputStateCreateInfo.vertexBindingDescriptionCount = 0;
    vertexInputStateCreateInfo.pVertexBindingDescriptions = nullptr;
    vertexInputStateCreateInfo.vertexAttributeDescriptionCount = 0;
    vertexInputStateCreateInfo.pVertexAttributeDescriptions = nullptr;

    VkPipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateCreateInfo;
    pipelineInputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
    pipelineInputAssemblyStateCreateInfo.pNext = nullptr;
    pipelineInputAssemblyStateCreateInfo.flags = 0;
    pipelineInputAssemblyStateCreateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
    pipelineInputAssemblyStateCreateInfo.primitiveRestartEnable = VK_FALSE;

    VkViewport viewPort;
    viewPort.x = 0.0f;
    viewPort.y = 0.0f;
    viewPort.width = WIDTH;
    viewPort.height = HEIGHT;
    viewPort.minDepth = 0.0f;
    viewPort.maxDepth = 1.0f;

    VkRect2D scissor;
    scissor.offset = { 0, 0 };
    scissor.extent = { WIDTH, HEIGHT };

    VkPipelineViewportStateCreateInfo pipelineViewportStateCreateInfo;
    pipelineViewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
    pipelineViewportStateCreateInfo.pNext = nullptr;
    pipelineViewportStateCreateInfo.flags = 0;
    pipelineViewportStateCreateInfo.viewportCount = 1;
    pipelineViewportStateCreateInfo.pViewports = &viewPort;
    pipelineViewportStateCreateInfo.scissorCount = 1;
    pipelineViewportStateCreateInfo.pScissors = &scissor;

    VkPipelineRasterizationStateCreateInfo pipelineRasterizationStateCreateInfo;
    pipelineRasterizationStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
    pipelineRasterizationStateCreateInfo.pNext = nullptr;
    pipelineRasterizationStateCreateInfo.flags = 0;
    pipelineRasterizationStateCreateInfo.depthClampEnable = VK_FALSE;
    pipelineRasterizationStateCreateInfo.rasterizerDiscardEnable = VK_FALSE;
    pipelineRasterizationStateCreateInfo.polygonMode = VK_POLYGON_MODE_FILL;
    pipelineRasterizationStateCreateInfo.cullMode = VK_CULL_MODE_BACK_BIT;
    pipelineRasterizationStateCreateInfo.frontFace = VK_FRONT_FACE_CLOCKWISE;
    pipelineRasterizationStateCreateInfo.depthBiasEnable = VK_FALSE;
    pipelineRasterizationStateCreateInfo.depthBiasConstantFactor = 0.0f;
    pipelineRasterizationStateCreateInfo.depthBiasClamp = 0.0f;
    pipelineRasterizationStateCreateInfo.depthBiasSlopeFactor = 0.0f;
    pipelineRasterizationStateCreateInfo.lineWidth = 1.0f;

    VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo;
    pipelineMultisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
    pipelineMultisampleStateCreateInfo.pNext = nullptr;
    pipelineMultisampleStateCreateInfo.flags = 0;
    pipelineMultisampleStateCreateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
    pipelineMultisampleStateCreateInfo.sampleShadingEnable = VK_FALSE;
    pipelineMultisampleStateCreateInfo.minSampleShading = 1.0f;
    pipelineMultisampleStateCreateInfo.pSampleMask = nullptr;
    pipelineMultisampleStateCreateInfo.alphaToCoverageEnable = VK_FALSE;
    pipelineMultisampleStateCreateInfo.alphaToOneEnable = VK_FALSE;

    VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState;
    pipelineColorBlendAttachmentState.blendEnable = VK_TRUE;
    pipelineColorBlendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
    pipelineColorBlendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
    pipelineColorBlendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD;
    pipelineColorBlendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
    pipelineColorBlendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
    pipelineColorBlendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD;
    pipelineColorBlendAttachmentState.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;

    VkPipelineColorBlendStateCreateInfo pipelineColorBlendStateCreateInfo;
    pipelineColorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
    pipelineColorBlendStateCreateInfo.pNext = nullptr;
    pipelineColorBlendStateCreateInfo.flags = 0;
    pipelineColorBlendStateCreateInfo.logicOpEnable = VK_FALSE;
    pipelineColorBlendStateCreateInfo.logicOp = VK_LOGIC_OP_NO_OP;
    pipelineColorBlendStateCreateInfo.attachmentCount = 1;
    pipelineColorBlendStateCreateInfo.pAttachments = &pipelineColorBlendAttachmentState;
    pipelineColorBlendStateCreateInfo.blendConstants[0] = 0.0f;
    pipelineColorBlendStateCreateInfo.blendConstants[1] = 0.0f;
    pipelineColorBlendStateCreateInfo.blendConstants[2] = 0.0f;
    pipelineColorBlendStateCreateInfo.blendConstants[3] = 0.0f;

    VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo;
    pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
    pipelineLayoutCreateInfo.pNext = nullptr;
    pipelineLayoutCreateInfo.flags = 0;
    pipelineLayoutCreateInfo.setLayoutCount = 0;
    pipelineLayoutCreateInfo.pSetLayouts = nullptr;
    pipelineLayoutCreateInfo.pushConstantRangeCount = 0;
    pipelineLayoutCreateInfo.pPushConstantRanges = nullptr;

    ASSERT_VK(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout));

    VkAttachmentDescription attachmentDescription;
    attachmentDescription.flags = 0;
    attachmentDescription.format = usedFormat;
    attachmentDescription.samples = VK_SAMPLE_COUNT_1_BIT;
    attachmentDescription.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
    attachmentDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
    attachmentDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
    attachmentDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
    attachmentDescription.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
    attachmentDescription.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;

    VkAttachmentReference attachmentReference;
    attachmentReference.attachment = 0;
    attachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;

    VkSubpassDescription subpassDescription;
    subpassDescription.flags = 0;
    subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
    subpassDescription.inputAttachmentCount = 0;
    subpassDescription.pInputAttachments = nullptr;
    subpassDescription.colorAttachmentCount = 1;
    subpassDescription.pColorAttachments = &attachmentReference;
    subpassDescription.pResolveAttachments = nullptr;
    subpassDescription.pDepthStencilAttachment = nullptr;
    subpassDescription.preserveAttachmentCount = 0;
    subpassDescription.pPreserveAttachments = nullptr;

    VkRenderPassCreateInfo renderPassCreateInfo;
    renderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
    renderPassCreateInfo.pNext = nullptr;
    renderPassCreateInfo.flags = 0;
    renderPassCreateInfo.attachmentCount = 1;
    renderPassCreateInfo.pAttachments = &attachmentDescription;
    renderPassCreateInfo.subpassCount = 1;
    renderPassCreateInfo.pSubpasses = &subpassDescription;
    renderPassCreateInfo.dependencyCount = 0;
    renderPassCreateInfo.pDependencies = nullptr;

    ASSERT_VK(vkCreateRenderPass(device, &renderPassCreateInfo, nullptr, &renderPass));

    VkGraphicsPipelineCreateInfo pipelineCreateInfo;
    pipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
    pipelineCreateInfo.pNext = nullptr;
    pipelineCreateInfo.flags = 0;
    pipelineCreateInfo.stageCount = 2;
    pipelineCreateInfo.pStages = stages;
    pipelineCreateInfo.pVertexInputState = &vertexInputStateCreateInfo;
    pipelineCreateInfo.pInputAssemblyState = &pipelineInputAssemblyStateCreateInfo;
    pipelineCreateInfo.pTessellationState = nullptr;
    pipelineCreateInfo.pViewportState = &pipelineViewportStateCreateInfo;
    pipelineCreateInfo.pRasterizationState = &pipelineRasterizationStateCreateInfo;
    pipelineCreateInfo.pMultisampleState = &pipelineMultisampleStateCreateInfo;
    pipelineCreateInfo.pDepthStencilState = nullptr;
    pipelineCreateInfo.pColorBlendState = &pipelineColorBlendStateCreateInfo;
    pipelineCreateInfo.pDynamicState = nullptr;
    pipelineCreateInfo.layout = pipelineLayout;
    pipelineCreateInfo.renderPass = renderPass;
    pipelineCreateInfo.subpass = 0;
    pipelineCreateInfo.basePipelineHandle = VK_NULL_HANDLE;
    pipelineCreateInfo.basePipelineIndex = -1;

    std::cout << &pipelineCreateInfo << ", " << &pipeline;
    ASSERT_VK(vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineCreateInfo, nullptr, &pipeline));

    delete[] swapchainImages;
    delete[] layers;
    delete[] extensions;
    delete[] physDevices;

}

void gameloop() {

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
    }
}

void shutdownGLFW() {

    glfwDestroyWindow(window);
}

void shutdownVulkan() {
    vkDeviceWaitIdle(device);

    vkDestroyPipeline(device, pipeline, nullptr);
    vkDestroyRenderPass(device, renderPass, nullptr);
    vkDestroyPipelineLayout(device, pipelineLayout, nullptr);

    for (int i = 0; i < amountImagesInSwapchain; i++) {
        vkDestroyImageView(device, imageViews[i], nullptr);
    }
    delete[] imageViews;

    vkDestroyShaderModule(device, shaderModuleVert, nullptr);
    vkDestroyShaderModule(device, shaderModuleFrag, nullptr);

    vkDestroySwapchainKHR(device, swapchain, nullptr);
    vkDestroyDevice(device, nullptr);
    vkDestroySurfaceKHR(instance, surface, nullptr);
    destroyDebugUtilsMessengerEXT(instance, callback, nullptr);
    vkDestroyInstance(instance, nullptr);
}

int main() {

    startGLFW();
    startVulkan();

    gameloop();
    shutdownVulkan();
    shutdownGLFW();

    return 0;
}

The function can be found in line 549 and i have a suspicion why it might be because its the only thing i did differently from the first video tutorial.
This shader is simply supposed to return the hardcoded positions but i enabled the the second extension only because the only command in the main required me to enable it. This is the only difference to what was originally done in the tutorial. I tried finding out what these shader extensions are about but i couldnt get any answers to it. There might be another cause but im pretty sure its the shader. I hope someone can help me.
#version 450
#extension GL_ARB_separate_shader_objects : enable
#extension GL_KHR_vulkan_glsl : enable

out gl_PerVertex{
    vec4 gl_Position;
};

vec2 positions[3] = vec2[](
    vec2(0.0, -0.5),
    vec2(0.5, 0.5),
    vec2(-0.5, 0.5)
);

void main(){
    gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0);

}


text:
Q: When trying to convert a list of python dictionaries into a SQLite table I keep getting an error? I'm attempting to convert a list of python dictionaries into an SQLite table, using the code below.
conn = sqlite3.connect('stockData.db')
c = conn.cursor()
c.executemany(f"INSERT INTO AAPL1M2021 (time,open,high,low,close,volume) VALUES (%(t)s,%(o)s,%(h)s,%(l)s,%(c)s,%(v)s)", data)

Whenever I run this code it returns the error below.
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
<ipython-input-7-dce4eb1e6f6f> in <module>
      2 conn = sqlite3.connect('stockData.db')
      3 c = conn.cursor()
----> 4 c.executemany("INSERT INTO AAPL1M2021 (time,open,high,low,close,volume) VALUES (%(t)s,%(o)s,%(h)s,%(l)s,%(c)s,%(v)s)", data)

OperationalError: near "%": syntax error

I must be missing something because I can't seem to find a solution.
Here is a sample dictionary from the list of dictionaries.
{'v': 26666,
  'vw': 133.233,
  'o': 133.31,
  'c': 133.49,
  'h': 133.49,
  'l': 133.02,
  't': 1609750800000,
  'n': 87}

A: Python's sqlite package doesn't use %s style formatting.  It uses ? for positional placeholders or :name for keyword placeholders.
So your query might look like
c.execute(
    "INSERT INTO AAPL1M2021 (time,open,high,low,close,volume) VALUES (:t, :o, :h, :l, :c, :v)",
    data
)

Note that executemany is used for lists of arguments for executing mulitple queries.  For a single dict use execute; use executemany for a list of dicts.


text:
Q: fix error caused by error in `setup_params()`with y-axis for stacked barplot ggplot2 I am trying to build a stacked barplot that looks like so...

My dataframe looks like this:
df = structure(list(Year_Publication = c(1989L, 1994L, 2001L, 2002L,
                                         2002L, 2004L, 2006L, 2007L, 2009L, 2011L, 2012L, 2013L, 2014L,
                                         2015L, 2016L, 2017L, 2017L, 2017L, 2018L, 2018L, 2018L, 2019L,
                                         2019L, 2019L, 2020L, 2020L, 2020L, 2020L, 2021L, 2021L, 2022L,
                                         2022L, 2022L, 2022L), Taxa = c("Cervidae", "Teleostei", "Chondrichtyes",
                                                                        "Chondrichtyes", "Gastropoda", "Teleostei", "Malacostraca", "Teleostei",
                                                                        "Teleostei", "Teleostei", "Teleostei", "Teleostei", "Teleostei",
                                                                        "Teleostei", "Teleostei", "Chondrichtyes", "Teleostei", "Chondrostei",
                                                                        "Teleostei", "Chondrichtyes", "Decapoda", "Teleostei", "Gastropoda",
                                                                        "Chondrichtyes", "Chondrostei", "Teleostei", "Bivalvia", "Tetrapoda",
                                                                        "Teleostei", "Orthoptera", "Chondrichtyes", "Teleostei", "Reptilia",
                                                                        "Bovidae"), Total_Species_Per_Taxa = c(1L, 2L, 1L, 1L, 3L, 1L,
                                                                                1L, 1L, 2L, 4L, 2L, 1L, 1L, 2L, 4L, 2L, 4L, 1L, 7L, 3L, 1L, 6L,
                                                                                1L, 3L, 1L, 7L, 2L, 1L, 1L, 1L, 4L, 4L, 1L, 1L), Total_Species_Per_Pub = c(1L,
                                                                                2L, 1L, 4L, 4L, 1L, 1L, 1L, 2L, 4L, 2L, 1L, 1L, 2L, 4L, 7L, 7L,
                                                                                7L, 11L, 11L, 11L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 2L, 2L,
                                                                                10L, 10L, 10L, 10L)), class = "data.frame", row.names = c(NA,
                                                                                -34L))

and I have tried this code:
ggplot(data = taxa_diversity, aes(x = `Year_Publication`, fill = Taxa)) +
  geom_bar(aes(y = `Total_Species_Per_Pub`), stat = "count")

AND

ggplot(data = taxa_diversity, aes(x = `Year_Publication`, y = `Total_Species_Per_Pub`, fill = Taxa)) +
  geom_bar(stat = "count")

But I keep getting this error
Error in `geom_bar()`:
! Problem while computing stat.
ℹ Error occurred in the 1st layer.
Caused by error in `setup_params()`:
! `stat_count()` must only have an x or y aesthetic.
Run `rlang::last_error()` to see where the error occurred.

I know it's an error with the y-axis, because I can get it to work when I don't include an command for the y-axis... but then it gives me a graph with the wrong values on the y-axis.
Any idea how to fix this?

A: Update (removed basic answer):
Using geom_col() we could set y in aes:
my_color <- c("#41859f", "#404040", "#ea9f91","#bfd2d9",
              "#981f26", "#575a7b", "#ce2a0a", "#eddca3",
              "#2c6049", "#41859f", "#404040", "#ea9f91")
library(ggplot2)
ggplot(data =df, aes(x = `Year_Publication`, y = `Total_Species_Per_Pub`, fill = Taxa)) +
  geom_col()+
  scale_x_continuous("Year_Publication", labels = as.character(df$Year_Publication), breaks = df$Year_Publication)+
  scale_fill_manual(values=my_color)+
  theme_classic()


text:
Q: Insert a chart built with google apps script into a google spreadsheet This may sound a dumb question, but I have searched the web a lot and I didn't find what I wanted...
I 've managed to build the chart I want to display, from the data on different spreadsheets, and I would like to insert the chart into a spreadsheet without having to paste the data on the sheet. Is this possible ?
I can also use UIApp to display it, but then I would like to have it displayed on the spreadsheet without having to call it from a menu or a button.
Thanks for your help,
edelans
--
Here is my code so far, it's working as I can see on the debugger tool
  function BuildMTChart(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var DataChart = MTLastMonth()  // MTLastMonth() returns an array with the data I need
  var dSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Dashboard");

      var dataTable = Charts.newDataTable();
          dataTable.addColumn(Charts.ColumnType['DATE'], 'Date');
          dataTable.addColumn(Charts.ColumnType['NUMBER'], 'Maintenance');
          dataTable.addColumn(Charts.ColumnType['NUMBER'], 'Troubleshooting');
          for ( var i = 0; i < DataChart.length; i++) {
            dataTable.addRow([DataChart[i][0], DataChart[i][1], DataChart[i][2]]);
          }
          dataTable.build();

    var chart = Charts.newAreaChart()
        .setDataTable(dataTable)
        .setDimensions(800, 400)
        .setYAxisTitle("Hours")
        .setXAxisTitle("Date")
        .build();

A: There used to be setDataTable method for EmbeddedChartBuilder. But I couldn't make it work.
So as far as I understand, you can add charts to the spreadsheet from the script, but those need to have their data in the spreadsheet itself:
var chart = workingSheet.newChart()
  .setChartType(Charts.ChartType.COLUMN)
  .setPosition(8, 2, 0, 0)
  .setTitle("Sample chart")
  .setXAxisTitle("...")
  .setYAxisTitle("...")
  .addRange(range)    // This could be smth. like SpreadsheetApp.getActiveSpreadsheet().getRange("B2:C8")
  .build();

SpreadsheetApp.getActiveSpreadsheet().insertChart(chart);

Here it says you can set some advanced chart options. Maybe there is a way to pass a DataTable there as well?
For now I'd recommend populating the spreadsheet with your data and then adding a chart based on ranges. If you don't want this data visible in the google doc, you can hide columns or move it to a new sheet.

A: May be you can add this to UiApp, size it properly and setup a trigger, so that the UI app is displayed every time the spreadsheet is opened? Something like this.
function onOpen() {
  return myUiApp();
}

function myUiApp() {
  //All your code to build the chart and add it to the app
}


text:
Q: How to inherit template constructor that will not work with base class instances? I have many derived classes from base. Those classes must inherit constructor from base, but that constructor should only work with derived or base class instances.
Base class example:
template<typename T, typename U>
struct bar
{
  bar() = default;

  template<typename _Bar_or_Derived>
  bar(const _Bar_or_Derived &); // must accept any bar or its derived classes
};

Derived classes example:
template<typename T, typename U>
struct foo : public bar<T, U>
{
  using bar<T, U>::bar;

 // must inherit something like foo(const Foo_or_Bar&)
};

template<typename T, typename U>
struct not_foo : public bar<T, U>
{
  using bar<T, U>::bar;

 // must inherit something like not_foo(const NotFoo_or_Bar&)
};

How to do such a thing?

A: It seems you want CRTP instead of common base class to avoid to duplicate code:
template <typename > struct Bar;
template <template <typename, typename> class C, typename T1, typename T2>
struct Bar<C<T1, T2>>
{
     Bar(const Bar&) {/*..*/}

     template <typename U1, U2>
     Bar(const Bar<C<U1, U2>>&) {/*..*/}

     template <typename U1, U2>
     Bar(const C<U1, U2>&) {/*..*/}
};
// Maybe you just need template <template <typename, typename> class C> struct Bar{};
// instead, as T1, T2 seems not used

template<typename T, typename U>
struct foo : public bar<foo>
{
    using bar<foo>::bar;
};

template<typename T, typename U>
struct not_foo : public bar<not_foo>
{
  using bar<not_foo>::bar;
};


text:
Q: Adding API output to HTML page I'm trying to make a food bank finder for food banks in California. The API data can be found here. So far, the data opens up on a separate tab (due to the target being "_blank") But I would want the data to output on the screen once the user presses the button, and only specific parts of the data (the name and address of the food bank). How would I show the output on the website and only specific parts of the data? Thank you for your time
<!DOCTYPE html>

<meta charset="UTF-8">

<title>Sample Page</title>

Find a location

Enter you zip code below

    <form action="https://controllerdata.lacity.org/resource/v2mg-qsxf.json" target="_blank" method="get" >
    Zip Code:
    <input type="number" id="zip_code" name="zip_code">

    <input type="submit" value="Submit">
    </form>

A: Your current solution seems fully HTML based. I think that you can best do this in JavaScript however, doing an asynchronous request for the data using the API like this:
fetch('https://controllerdata.lacity.org/resource/v2mg-qsxf.json')
  .then((res) => res.json())
  .then((data) => {
    // do something with data here
    console.log(data)
  });

You can add a button that triggers a JS function to search in the retrieved data.

A: This is my suggestion:

var form = document.getElementById('form');
var output = document.getElementById('output');

form.onsubmit = () => {
var zip_code = document.getElementById('zip_code').value;
fetch('https://controllerdata.lacity.org/resource/v2mg-qsxf.json?zip_code=' + zip_code)
    .then(res => res.json())
    .then(res => {
        output.innerHTML = res[0].name + ' - ' + res[0].street_address;
    });
return false;
};
<form id="form">
  Zip Code:
  <input type="number" id="zip_code" name="zip_code">

  <input type="submit" value="Submit">
</form>

It shows desired results (name and address) on the same page (try, for example, zip code 94501).


text:
Q: Passing only clicked element to onClick function - reactjs I have multiple elements with same className and i want if some element (with className history-node) is clicked it should get className active along with current className.
But i am having an issue, there are childs of that element and if child elements gets clicked they also get class Active.
Here is the code:

 {this.handleHistoryClick(e.target)}}>
    {heading.action}
    {moment(heading.added_at).format("MMMM Do, YYYY")}

handleHistoryClick function
handleHistoryClick(target){
  $('.history-node').removeClass('active'); //removing active class from all elements
  target.className = 'history-node active';
}

I want to run function when user click on element with className history-node
But if user clicks on history-title, ClickHandler gives class active to history-title element.
EXPECTED BEHAVIOUR: if history-node is clicked only history-node should get class active.

A: One tip and how to solve your problem (In two ways)
Tip: Not usually the best idea to mix React with jQuery. React came in as a major paradigm shift in how we interact with the DOM. Try to read a little bit more about React, how it works, why is it so different from simply adding/removing elements in the DOM with jQ.
Some references to help you with that:
How to go from jQuery to React.js?
Thinking in React for jQuery Programmers

Now, back to your question
You should use currentTarget.
As the .history-title and .history-date elements are wrapped within .history-node, any click on them will trigger it's parent's event, since .history-node body is .history-title + .history-date. That's the correct behavior. When you trigger an event in JS, the event object receives two parameters: target, which is the event triggering the event and currentTarget, the element that is actually listening for the event.
Now for the code:
with JQ
Component:

    {heading.action}
    {moment(heading.added_at).format("MMMM Do, YYYY")}

Click:
handleHistoryClick(event){
  $('.history-node').removeClass('active')
  event.currentTarget.classList.add('active')
}

The React way (Pure React, no modules)
Component:
class HistoryNode extends Component {
    constructor(props) {
        super(props)
        this.state = { isActive: false }
        this.handleClick = this.handleClick.bind(this)
    }

    handleClick(e) {
      let state = this.state
      this.setState({isActive: !state.isActive})
    }

    render() {
      return(

          <div className={`history-node ${this.state.isActive ? 'active' : ''}`} onClick={handleHistoryClick}>
            {heading.action}

               {moment(heading.added_at).format("MMMM Do, YYYY")}

      )
    }
}

Notice how you don't need to manipulate the DOM at any moment at the React solution. You just attach your event to that particular component, define how it's state change should reflect on the UI and let React do the rest.
Hope it helps ;)
Reference for target vs currentTarget

A: I think the event propagates to child components.
Have you tried this ?

    {heading.action}
    {moment(heading.added_at).format("MMMM Do, YYYY")}

HandleClick function
handleHistoryClick(event){
  event.stopPropagation();
  $('.history-node').removeClass('active');
  event.target.className = 'history-node active';
}

EDIT : You could make it simpler though (and without jQuery) using your component state. But without knowing how you wrote your component I cannot give you a snippet illustrating it. Be careful too as you interact directly with the DOM, this implies a performance loss. Using the React state allows you to avoid such thing!


text:
Q: Augmented Dickey-Fuller Trend and Intercept I am trying to determine if I should include an "intercept" or a "trend and intercept" when using the Augmented Dickey-Fuller (ADF) test.  I ran a regression with my dependent variable and a time trend and both the intercept and trend were statistically significant.  Is this statistical significance what determines if I should include a "trend and intercept" in the ADF test?  My data is unstructured/undated.  The series contains 252 observations and there are about 6 observations per year from 1970-2014.  Below are my regression results and a graph of the raw data.

A: library(tseries)
library(urca)
data2<-na.remove(data1$SANDP) #assumed one dataset
    data2
    c<-adf.test(data2,k=2)
    c
    summary(c$statistic)

useful command for you
summary(ur.df(data2,type=c("drift"),lags=2,selectlags =c("Fixed")))


text:
Q: MS Access UPDATE query is adding new rows I'm stumped as to why this is happening. This is my UPDATE query in MS ACCESS:
UPDATE TempMyTable AS b
RIGHT JOIN MyTable AS a ON (a.[ID] = b.[ID])
AND (a.T3 = b.T3) AND (a.T2 = b.T2) AND (a.T1 = b.T1)
SET b.T1 = a.T1, b.T2 = a.T2, b.T3 = a.T3
WHERE (((b.ID) Is Null));

I'm checking for changes in the T1, T2 and T3 columns. If there's a change, update the columns in the TempMyTable rows.
However what is happening is that new rows are added with empty values in all fields except the values for T1, T2 and T3.
EDIT: solution, use INNER JOIN and check if columns DO NOT match with the '<>' operator.
UPDATE TempMyTable AS b
INNER JOIN MyTable AS a
ON ((a.T1 <> b.T1) OR (a.T2 <> b.T2) OR (a.T3 <> b.T3))
AND (a.[ID] = b.[ID])
SET b.T1 = a.T1, b.T2 = a.T2, b.T3 = a.T3;

A: You're using a RIGHT JOIN, which will include rows where nothing exists in MyTable. These rows are being updated (an UPDATE query in Microsoft Access always affects rows of both tables when using joins even if you're only using Set on columns in one table), thus creating new rows.
Change the join to an INNER JOIN:
UPDATE TempMyTable AS b
INNER JOIN MyTable AS a ON (a.[ID] = b.[ID])
AND (a.T3 = b.T3) AND (a.T2 = b.T2) AND (a.T1 = b.T1)
SET b.T1 = a.T1, b.T2 = a.T2, b.T3 = a.T3
WHERE (((b.ID) Is Null));

Note, however, that this query does nothing, since you're checking WHERE (((b.ID) Is Null));, and you're joining on b.ID. That means Access will be unable to return rows under any circumstance. You will likely want to remove that WHERE clause.
In the end, OP was looking for differences with matched IDs, thus the following query was used:
UPDATE TempMyTable AS b
INNER JOIN MyTable AS a
ON ((a.T1 <> b.T1) OR (a.T2 <> b.T2) OR (a.T3 <> b.T3))
AND (a.[ID] = b.[ID])
SET b.T1 = a.T1, b.T2 = a.T2, b.T3 = a.T3;


text:
Q: How to truncated tag with AES GCM? I'm using AES/GCM encryption and I'm trying to reduce tag from 128 bits to 32 bits.
I've found some documentation about GCMParameterSpec method which is supposed to do this work.
You can see my code bellow:
    Cipher cipher = null;
    try {

        byte[] input = Utils.hexStringToByteArray("d9313225f88406e5a55909c5aff5269a");
        byte[] keyByte = Utils.hexStringToByteArray("cfa2b0719afe65b60b1461cdc6a7f7e3");

        SecretKeySpec key = new SecretKeySpec(keyByte, "AES");
        cipher = Cipher.getInstance("AES/GCM/NoPadding");
        GCMParameterSpec spec = new GCMParameterSpec(32, Utils.hexStringToByteArray("000000000000000000000000"));
        cipher.init(Cipher.ENCRYPT_MODE, key, spec);
        /*byte[] aad = Utils.hexStringToByteArray("000000");
        cipher.updateAAD(aad);*/

        final byte[] encrypted = new byte[cipher.getOutputSize(0)];
        cipher.update(input, 0, input.length, encrypted, 0);  //Not being updated for current data.

        //Tag output
        byte[] tag = new byte[cipher.getOutputSize(0)];

        cipher.doFinal(tag, 0);

        cipher.init(Cipher.DECRYPT_MODE, key, spec);
        //cipher.updateAAD(aad);
        final byte[] data1 = new byte[16];

        int offset = cipher.update(encrypted, 0, encrypted.length, data1, 0);

        cipher.update(tag, 0, tag.length, data1, offset);
        cipher.doFinal(data1,offset);

    }
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();

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

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

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

    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    } catch (ShortBufferException e) {
        e.printStackTrace();
    }

}

It sends me this exception:

java security invalidkeyexception: Invalid value for MAC size: 32

Do you have some issue or can you explain me why it doesn't work?
Thanks.


text:
Q: Delete item from listview I have listview which contains textview and buttons. When i delete listview item and i try to scroll down, i get exception on this:
BuildQueue eile = countryList.get(position);

Exception:
02-08 19:11:04.279: E/AndroidRuntime(10509): java.lang.IndexOutOfBoundsException: Invalid index 15, size is 15

Seems i do not updating something when i delete item from listview. I think i have problem with ViewHolder, but i do not know what kind of...
My ArrayAdapter code:
public class MyCustomAdapter extends ArrayAdapter<BuildQueue> {

        private ArrayList<BuildQueue> countryList;

        public MyCustomAdapter(Context context, int textViewResourceId,ArrayList<BuildQueue> countryList) {
            super(context, textViewResourceId, countryList);
            this.countryList = new ArrayList<BuildQueue>();
            this.countryList.addAll(countryList);
        }

        private class ViewHolder {
            TextView code;
            TextView field;
            Button del;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;

            if (convertView == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = vi.inflate(R.layout.queue_buildings, null);

                holder = new ViewHolder();
                holder.code = (TextView) convertView.findViewById(R.id.code);
                holder.field = (TextView) convertView.findViewById(R.id.field_text);
                holder.del = (Button) convertView.findViewById(R.id.del_button);
                convertView.setTag(holder);

                holder.del.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        Button del_button = (Button) v;
                        BuildQueue building = (BuildQueue) del_button.getTag();
                        countryList.remove(building);
                        dataAdapter.notifyDataSetChanged();
                    }
                });
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            BuildQueue eile = countryList.get(position);
            holder.code.setText(" ( Level: " + eile.getOld_level() + " to "+eile.getNew_level()+")");

            holder.field.setText(eile.getNameSort());
            holder.field.setTag(eile);

            holder.del.setText("Delete");
            holder.del.setTag(eile);

            return convertView;

        }
    }

A: You are using a two arrays in your Adapter, but only changing one of them.
Every Adapter uses getCount() to determine how many row should be drawn. ArrayAdapter's getCount() simply asks for the size of the array that you pass to the super constructor here: super(context, textViewResourceId, countryList);.  But you are also using a second, local array and when you delete a value from this countryList getCount() has no idea this happened which results in getView() throwing an IndexOutOfBoundsException...
Either extend BaseAdapter, or use ArrrayAdapter's methods like getItem(), add(), and remove() and remove your local data set.


text:
Q: Css class is overridden by jQuery I am using BigText library to make some text to fit into div.
My Problem is that the additional style I applied to the text is override and ignored. For example text-align:left is not working anymore. And the list points are not shown. How can I get the functionality of the script and add the css class?
I am calling the bigText function like that:
jQuery:
$(function() {
    $(window).on('resize', function() {
        $(".area_competences_text").bigText();
    });

    $(window).trigger('resize');
});

HTML:

SOME TEXT

SOME TEXT

SOME TEXT

SOME TEXT

SOME TEXT

SOME TEXT

CSS:
.area_competences_text {
    text-align: left;
    padding-top: 5%;
    padding-left: 5%;
    padding-right: 5%;
    padding-bottom: 5%;
}

A: you can do this without using css like below:
$(function() {
        $(window).on('resize', function() {
            $(".area_competences_text").bigText();
            $(".area_competences_text").css("text-align","left")
                                       .css("padding","5%");
        });
            $(window).trigger('resize');
        });

A: You can add !important
.area_competences_text {
    text-align: left !important;

}

A: What I would do was to add a ID or another class to the div:
EX#1
HTML

SOME TEXT

SOME TEXT

SOME TEXT

SOME TEXT

SOME TEXT

SOME TEXT

CSS
#my_id {
    text-align: left !important;
    padding-top: 5% !important;
    padding-left: 5% !important;
    padding-right: 5% !important;
    padding-bottom: 5% !important;
}

EX#2
HTML

SOME TEXT

SOME TEXT

SOME TEXT

SOME TEXT

SOME TEXT

SOME TEXT

CSS
.area_competences_text.second_class {
    text-align: left !important;
    padding-top: 5% !important;
    padding-left: 5% !important;
    padding-right: 5% !important;
    padding-bottom: 5% !important;
}

When you are adding ID or another class and refer to both of classes, you then are more specific about what needs to be styled.

A: You can add !important to a setting to not let it be overridden:
.area_competences_text {
    text-align: left !important;
etc.
}

A: You can use !important like below:
.area_competences_text {
    text-align: left !important;
    padding-top: 5%;
    padding-left: 5%;
    padding-right: 5%;
    padding-bottom: 5%;
}

A:

...


text:
Q: App crashes when passing data from RecyclerView in Fragment to Activity with Glide Hello I am trying to pass data from my RecyclerView in Fragment, to my activity. But the app crashes. The code works when i try to open another activity so im guessing the error is in my Gallery.java activity.
I tried putting .asBitMap where it says Glide in Gallery.java Activit, but it is marked as an error
Here is my Gallery.java
package co.quindio.sena.navigationdrawerejemplo;

import android.nfc.Tag;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

public class Gallery extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);
        getIncomingIntent();
    }
    private void getIncomingIntent(){
       if(getIntent().hasExtra("image_url")){
           String imageUrl = getIntent().getStringExtra("image_url");
           String imageName = getIntent().getStringExtra("image_name");
           setImage(imageUrl,imageName);
        }
    }
    private void setImage(String imageUrl, String imageName){
        TextView name= (TextView) findViewById(R.id.idInfo);
        ImageView image= (ImageView) findViewById(R.id.idImagen);
        Glide.with(this)

                .load(imageUrl)
                .into(image);

    }
}

Here is my adapter class
package co.quindio.sena.navigationdrawerejemplo.adapters;

import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

import co.quindio.sena.navigationdrawerejemplo.Gallery;
import co.quindio.sena.navigationdrawerejemplo.R;
import co.quindio.sena.navigationdrawerejemplo.clases.PersonajeVo;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by CHENAO on 13/07/2017.
 */

public class PersonajesAdapter extends RecyclerView.Adapter<PersonajesAdapter.PersonajeViewHolder>{

    ArrayList<PersonajeVo> listaPersonaje;
    private Context mContext;

    public PersonajesAdapter(Context context,ArrayList<PersonajeVo> listaPersonaje) {
        this.listaPersonaje=listaPersonaje;
        this.mContext=context;
        ArrayList<String> mImages = new ArrayList<>();
        ArrayList<String>mImageNames = new ArrayList<>();
    }

    @Override
    public PersonajeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,null,false);
        return new PersonajeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(PersonajeViewHolder holder, final int position) {
        holder.txtNombre.setText(listaPersonaje.get(position).getNombre());
        holder.txtInformacion.setText(listaPersonaje.get(position).getInfo());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, Gallery.class);

                intent.putExtra("image_url", (Parcelable) listaPersonaje.get(position));
                intent.putExtra("image_name", (Parcelable) listaPersonaje.get(position));
                mContext.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return listaPersonaje.size();
    }

    public class PersonajeViewHolder extends RecyclerView.ViewHolder {
        TextView txtNombre,txtInformacion;
        ImageView foto;

        public PersonajeViewHolder(View itemView) {
            super(itemView);
            txtNombre= (TextView) itemView.findViewById(R.id.idNombre);
            txtInformacion= (TextView) itemView.findViewById(R.id.idInfo);
            foto= (ImageView) itemView.findViewById(R.id.idImagen);
        }
    }
}

A: the problem is:
you send a Parcelable:
intent.putExtra("image_url", (Parcelable) listaPersonaje.get(position));
                intent.putExtra("image_name", (Parcelable) listaPersonaje.get(position));

but get it as String
String imageUrl = getIntent().getStringExtra("image_url");
           String imageName = getIntent().getStringExtra("image_name");

so please using  getIntent().getParcelableExtra("image_url") and  getIntent().getParcelableExtra("image_name")
or send a String
intent.putExtra("image_url", listaPersonaje.get(position).getImageUrl());
                intent.putExtra("image_name",listaPersonaje.get(position).getImageName());

assume listaPersonaje item have getImageName() and getImageUrl() method that get "image_url" and "image_name" value
UPDATE 1 If you want send a drawable, first, convert it to byte array
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.your_resource);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();

and pass it via intent extras,
send:
intent.putExtra("image_url", b);

and receiver:
byte[] b = getIntent().getByteArray("image_url");

finally, using it for image view
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);

UPDATE 2 In case we have a drawble, we need to convert it to bitmap
public static Bitmap drawableToBitmap (Drawable drawable) {
    Bitmap bitmap = null;

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if(bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
    } else {
        bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    }

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

UPDATE 3, finally, using both of 2 way above, we have a way to resolve your issue when pass a drawable via intent
   Drawable drawable = listaPersonaje.get(position).getImageUrl()
        // convert drawable to byte array
        Bitmap bitmap = drawableToBitmap(drawable);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        // send it
        intent.putExtra("image_url", b);
        <!----------------------------------------------->
        // receiver
        byte[] b = getIntent().getByteArray("image_url");
        // and using glide to show it
        Glide.with(this)
                .load(b)
                .asBitmap()
                .into(imageview);

A: If you are passing only image_url and image_name then you have no need to pass as Parcelable.you just pass the only string in intent.
 Intent intent = new Intent(mContext, Gallery.class);
                intent.putExtra("image_url",listaPersonaje.get(position));
                intent.putExtra("image_name", listaPersonaje.get(position));
                mContext.startActivity(intent);

And fetch data in Gallery Activity

String imageUrl = getIntent().getStringExtra("image_url");
           String imageName = getIntent().getStringExtra("image_name");

I hope its help you.

A: I will add some more information here in addition to the @gianhtran s answer.
In bindviewholder method, you will get the PersonajeVo object by listaPersonaje.get(position).
@Override
    public void onBindViewHolder(PersonajeViewHolder holder, final int position) {
        final PersonajeVo personajeVo = listaPersonaje.get(position);
        holder.txtNombre.setText(personajeVo.getNombre());
        holder.txtInformacion.setText(personajeVo.getInfo());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, Gallery.class);
                intent.putExtra("image_url", personajeVo.getImageUrl());
                intent.putExtra("image_name", personajeVo.getImageName());
                mContext.startActivity(intent);
            }
        });
    }

Secondly, if you want all of the details from PersonajeVo object, then  you can put it this way,
    Intent intent = new Intent();
    intent.putExtra("personaje_obj",personajeVo); //make sure personjeVo model class is parcelable or cast it as (Parcelable)personajeVo
    mContext.startActivity(intent);)

and getting it back in another activity as follows,
Intent mIntent = getIntent();
if(mIntent!=null && mIntent.hasExtra("personaje_obj"))
{
PersonajeVo personajeVo = mIntent.getParcelableExtra("personaje_obj");
}

A: Actually no need to intent inside onBindViewHolder. Do it in this way
 public class PersonajeViewHolder extends RecyclerView.ViewHolder {
    TextView txtNombre,txtInformacion;
    ImageView foto;
    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        int get = AdatperPosition();
   if(pos != RecyclerView.NO_POSITION){
   Item clickDataItem = listaPersonaje.get(position);
   Intent intent = new Intent(mContext, Gallery.class);
   intent.putExtra("image_url", listaPersonaje.get(position));
   intent.putExtra("image_name",  listaPersonaje.get(position));
   mContext.startActivity(intent);
        }
    });


text:
Q: Dimension of the input of second convolutional layer? In the following code I have introduced one convolution and one maximum pooling layer. Output of pooling layer has a shape of (4,6,6,1). Now I want to define second convolutional layer. What will be the input for the second convolutional layer? Can I call same conv2d function? But here the input channel is different.
 batch_size = 4
 image_height = 12
 image_width =12
 input_channel = 2
 output_channel =1
 input =  tf.Variable(tf.random_normal([batch_size,image_height,image_width,input_channel]))
 filter = tf.Variable(tf.random_normal([2,2,input_channel,output_channel]))
 def conv2d(inputs,filters):
     return tf.nn.conv2d(inputs,filters,strides=[1,1,1,1],padding='SAME')
 def max_pool(conv_out):
     return tf.nn.max_pool(conv_out,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
 conv_out1 = conv2d(input,filter)
 pooling_out1= max_pool(conv_out1)
 sess =tf.InteractiveSession()
 sess.run(tf.initialize_all_variables())
 print conv_out1.get_shape()
 print pooling_out1.get_shape()

A: You can call the same conv2d function, but hopefully with different filters.


text:
Q: Bluetooth not supported on android devices how to show text ((this device not support the Bluetooth )) if this app installed on device not support the Bluetooth
here is my code
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

                    // want to add code here to show text ((this device not support
                    //the Bluetooth )) if this app installed on device not support
                    // the Bluetooth

A: If BT is not suppored by the device the code BluetoothAdapter.getDefaultAdapter() will return null. See android docs. And usefull tutorial also is there.
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // Device does not support Bluetooth
}


text:
Q: File Copy problem in C# the given path's format is not supported Here is my code to copy a file from one local location to another, and play it in winforms using windows media player.
I am getting an exception "The given path's format is not supported." during the file copy.
I can't seem to understand the issue. Can anyone please help? Thanks in advance.
Value of exepath variable- "file:\C:\Users\HP\source\repos\TestProject\TestProject\bin\Debug"

Value of vdopath variable- "file:\C:\Users\HP\source\repos\TestProject\TestProject\bin\Debug\Folder1\Folder2\file"

Value of strtupPath- "C:\Users\HP\source\repos\TestProject\TestProject\bin"

Value of newvdopath- "C:\Users\HP\source\repos\TestProject\TestProject\bin\vdofile.mkv"

   using System.Collections.Generic;
   using System.ComponentModel;
   using System.Data;
   using System.Drawing;
   using System.Linq;
   using System.Text;
   using System.Threading.Tasks;
   using System.Windows.Forms;
   using WMPLib;
   using System.IO;

   namespace TestProject
   {
       public partial class vdo_form_tmplt1 : Form
       {
           public vdo_form_tmplt1()
           {
              InitializeComponent();
           }

           private void PlayVideo_Click(object sender, EventArgs e)
           {

               string exepath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);

               string vdopath = System.IO.Path.Combine(exepath, "Folder1\\Folder2\\file");

               string strtupPath = System.IO.Path.GetDirectoryName(Application.StartupPath);

               string newvdopath = System.IO.Path.Combine(strtupPath, "vdofile.mkv");

               System.IO.File.Copy(vdopath, newvdopath);

               axWindowsMediaPlayer1.stretchToFit = true;
               axWindowsMediaPlayer1.URL = newvdopath;
           }

       }
   }


text:
Q: Lambda expression in Java? I need to switch part of my projects from C# to Java. But before which, I would like to compare two languages carefully and completely.
Regarding to lambda expression, I could write very elegant code via C#, the question is how to implement the same feature gracefully in Java? Thanks in advance!
class Program
{
    enum Gender
    {
        Male,
        Female
    }
    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public Gender Gender { get; set; }
        public override string ToString()
        {
            return string.Format("Id: {0}, Name: {1}, Age: {2}, Gender: {3}", Id, Name, Age, Gender);
        }
    }

    static void Main(string[] args)
    {
        var students = new[] {
            new Student { Id = 1, Name = "Nathanial Archibald", Age = 18, Gender = Gender.Male },
            new Student { Id = 2, Name = "Georgina Sparks", Age = 19, Gender = Gender.Female },
            new Student { Id = 3, Name = "Daniel Humphrey", Age = 20, Gender = Gender.Male },
            new Student { Id = 4, Name = "Jenny Humphrey", Age = 17, Gender = Gender.Female },
        };

        var men = students.Where(p => p.Gender == Gender.Male);
        var ageAbove18 = students.Where(p => p.Age > 18);
        var humphrey = students.Where(p => p.Name.EndsWith("Humphrey"));
        var idGT1orderbyAge = students.Where(p => p.Id > 1).OrderBy(p => p.Age);

        foreach (var s in men) Console.WriteLine(s.ToString());
        foreach (var s in ageAbove18) Console.WriteLine(s.ToString());
        foreach (var s in humphrey) Console.WriteLine(s.ToString());
        foreach (var s in idGT1orderbyAge) Console.WriteLine(s.ToString());
    }
}

A: Java in version 8 might support lambda.;)
You can use this Site or this.
See this example:
final Array<Integer> a = array(1, 2, 3);
final Array<Integer> b = a.map({int i => i + 42});
arrayShow(intShow).println(b); // {43,44,45}

A: Currently java doesn't support Lambda operation, but this will going to be introduced in Java 8.
For further reference site
But as you want to switch to Java this is a good option but as long as lambda operation is not supported you can create your methods to do the same task and after java 8 release shift to the lambha operation
here is an example of lambha operation in java 8

A: Java 8 supports Lambda expression. Here is how you can use lambda expression in java to sort a list of Students
private static void sort(List<Student> students) {
Comparator<Student> rollNumberComparator = (student1, student2) ->
    student1.getRollNumber().compareTo(student2.getRollNumber());

Collections.sort(students,rollNumberComparator);

}
You can refer :
http://www.groupkt.com/post/088a8dea/lambda-expressions---java-8-feature.htm

A: Lambda expressions aren't part of the current version of Java (1.7) it is a feature for Java 8, which wont be released at least until next year

A: Lambda expression for functional interface


text:
Q: If my datastore transaction fails, will code after the transaction run? What happens if my datastore transaction fails and I have some more code that is supposed to run after it finishes? Does the application throw and error and end there? Will my second block of code run or will it never be reached?
ofy().transact(new Runnable() {
    @Override
    public void run() {
        // Some code here.
    }
});

// Some more datastore code here. Will this be reached if the transact fails?

A: If the transaction fails you will get an exception. If you don't handle the exception it will propagate.


text:
Q: Define dummy columns for each day of year BigQuery I have a table of a similar format

ID
date

1
2020-01-01

1
2020-01-02

2
2020-01-02

And I would like to add a day of the year dummy column for each day in 2020 similar to the table below. If the date entry for a row is Jan 1 2020 for example, then the dummy column for that day takes a 1, else 0. My data spans all of 2020 so I would need 366 columns. Is it possible to do this with some sort of loop (and avoid a bunch of case whens) ?

ID
date
2020_01_01
2020-01-02

1
2020-01-01
1
0

1
2020-01-02
0
1

2
2020-01-02
0
1

A:
I just reshaped (pivoted) the output of this table wide in another language and it worked just fine

Consider pivot approach available in BigQuery - let's start with just simplified example data you have in your question
select * from (
  select *, replace(cast(date as string), '-', '_') col
  from `project.dataset.table`
)
pivot(count(col) as _ for col in ('2020_01_01', '2020_01_02'))

if applied to sample data in your question - output is

Obviously, if you have whole year of dates - you don't want to type all 360+ columns - in such cases you can use execute immediate as in below example
execute immediate (select '''
  select * from (
    select *, replace(cast(date as string), '-', '_') col
    from `project.dataset.table`
  )
  pivot(count(col) as _ for col in (''' || string_agg(concat('"', replace(cast(day as string), '-', '_'), '"')) || '''))
'''
from unnest(generate_date_array('2020-01-01', '2020-12-31')) day
)

this will return as many those expected 360+ column for each day or 2020 year like in below example