Programs & Examples On #Non deterministic

Nondeterminism refers either to a computing system where the result may be one of many specified results or to a theoretical construct in which a computing system is allowed to try many options in parallel to search for a result.

CSS grid wrapping

Use either auto-fill or auto-fit as the first argument of the repeat() notation.

<auto-repeat> variant of the repeat() notation:

repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )

auto-fill

When auto-fill is given as the repetition number, if the grid container has a definite size or max size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container.

https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fill

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, 186px);
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_

The grid will repeat as many tracks as possible without overflowing its container.

Using auto-fill as the repetition number of the repeat() notation

In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.

The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.


auto-fit

The auto-fit keyword behaves the same as auto-fill, except that after grid item placement any empty repeated tracks are collapsed.

https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fit

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, 186px);
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_

The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to 0.

A collapsed track is treated as having a fixed track sizing function of 0px.

Using auto-fit as the repetition number of the repeat() notation

Unlike the auto-fill image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.


auto-fill vs auto-fit

The difference between the two is noticeable when the minmax() function is used.

Use minmax(186px, 1fr) to range the items from 186px to a fraction of the leftover space in the grid container.

When using auto-fill, the items will grow once there is no space to place empty tracks.

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_

When using auto-fit, the items will grow to fill the remaining space because all the empty tracks will be collapsed to 0px.

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_


Playground:

CodePen

Inspecting auto-fill tracks

auto-fill


Inspecting auto-fit tracks

auto-fit

Separation of business logic and data access in django

Django employs a slightly modified kind of MVC. There's no concept of a "controller" in Django. The closest proxy is a "view", which tends to cause confusion with MVC converts because in MVC a view is more like Django's "template".

In Django, a "model" is not merely a database abstraction. In some respects, it shares duty with the Django's "view" as the controller of MVC. It holds the entirety of behavior associated with an instance. If that instance needs to interact with an external API as part of it's behavior, then that's still model code. In fact, models aren't required to interact with the database at all, so you could conceivable have models that entirely exist as an interactive layer to an external API. It's a much more free concept of a "model".

fork() and wait() with two child processes

Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

Erm, after understanding your question: are you sure that the signature-method only creates a SHA1 and encrypts it? GPG et al offer to compress/clear sign the data. Maybe this java-signature-alg also creates a detachable/attachable signature.

Get Value of Row in Datatable c#

Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...

for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
    double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}

Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.

error C2065: 'cout' : undeclared identifier

I came here because I had the same problem, but when I did #include "stdafx.h" it said it did not find that file.
What did the trick for me was: #include <algorithm>.
I use Microsoft Visual Studio 2008.
These are the things that you can use then, incl. 'count': Link

Simple if else onclick then do?

You should use onclick method because the function run once when the page is loaded and no button will be clicked then

So you have to add an even which run every time the user press any key to add the changes to the div background

So the function should be something like this

htmlelement.onclick() = function(){
    //Do the changes 
}

So your code has to look something like this :

var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no = document.getElementById("no");

yes.onclick = function(){
    box.style.backgroundColor = "red";
}

no.onclick = function(){
    box.style.backgroundColor = "green";
}

This is meaning that when #yes button is clicked the color of the div is red and when the #no button is clicked the background is green

Here is a Jsfiddle

Forcing to download a file using PHP

Configure your server to send the file with the media type application/octet-stream.

Select a Dictionary<T1, T2> with LINQ

var dictionary = (from x in y 
                  select new SomeClass
                  {
                      prop1 = value1,
                      prop2 = value2
                  }
                  ).ToDictionary(item => item.prop1);

That's assuming that SomeClass.prop1 is the desired Key for the dictionary.

Python send POST with header

If we want to add custom HTTP headers to a POST request, we must pass them through a dictionary to the headers parameter.

Here is an example with a non-empty body and headers:

import requests
import json

url = 'https://somedomain.com'
body = {'name': 'Maryja'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(body), headers=headers)

Source

Git pull - Please move or remove them before you can merge

If you are getting error like

  • branch master -> FETCH_HEAD error: The following untracked working tree files would be overwritten by merge: src/dj/abc.html Please move or remove them before you merge. Aborting

Try removing the above file manually(Careful). Git will merge this file from master branch.

Bootstrap 3: How do you align column content to bottom of row

When working with bootsrap usually face three main problems:

  1. How to place the content of the column to the bottom?
  2. How to create a multi-row gallery of columns of equal height in one .row?
  3. How to center columns horizontally if their total width is less than 12 and the remaining width is odd?

To solve first two problems download this small plugin https://github.com/codekipple/conformity

The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns

Common code

<style>
    [class*=col-] {position: relative}
    .row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
    .row-centered {text-align:center}   
    .row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top} 
</style>

<script src="assets/conformity/conformity.js"></script>
<script>
    $(document).ready(function () {
        $('.row-conformity > [class*=col-]').conformity();
        $(window).on('resize', function() {
            $('.row-conformity > [class*=col-]').conformity();
        });
    });
</script>

1. Aligning content of the column to the bottom

<div class="row row-conformity">
    <div class="col-sm-3">
        I<br>create<br>highest<br>column
    </div>
    <div class="col-sm-3">
        <div class="to-bottom">
            I am on the bottom
        </div>
    </div>
</div>

2. Gallery of columns of equal height

<div class="row row-conformity">
    <div class="col-sm-4">We all have equal height</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
</div>

3. Horizontal alignment of columns to the center (less than 12 col units)

<div class="row row-centered">
    <div class="col-sm-3">...</div>
    <div class="col-sm-4">...</div>
</div>

All classes can work together

<div class="row row-conformity row-centered">
    ...
</div>

How can I write these variables into one line of code in C#?

Look into composite formatting:

Console.WriteLine("{0}.{1}.{2}", mon, da, yer);

You could also write (although it's not really recommended):

Console.WriteLine(mon + "." + da + "." + yer);

And, with the release of C# 6.0, you have string interpolation expressions:

Console.WriteLine($"{mon}.{da}.{yer}");  // note the $ prefix.

:: (double colon) operator in Java 8

:: is called Method Reference. It is basically a reference to a single method. I.e. it refers to an existing method by name.

Short Explanation:
Below is an example of a reference to a static method:

class Hey {
     public static double square(double num){
        return Math.pow(num, 2);
    }
}

Function<Double, Double> square = Hey::square;
double ans = square.apply(23d);

square can be passed around just like object references and triggered when needed. In fact, it can be just as easily used as a reference to "normal" methods of objects as static ones. For example:

class Hey {
    public double square(double num) {
        return Math.pow(num, 2);
    }
}

Hey hey = new Hey();
Function<Double, Double> square = hey::square;
double ans = square.apply(23d);

Function above is a functional interface. To fully understand ::, it is important to understand functional interfaces as well. Plainly, a functional interface is an interface with just one abstract method.

Examples of functional interfaces include Runnable, Callable, and ActionListener.

Function above is a functional interface with just one method: apply. It takes one argument and produces a result.


The reason why ::s are awesome is that:

Method references are expressions which have the same treatment as lambda expressions (...), but instead of providing a method body, they refer an existing method by name.

E.g. instead of writing the lambda body

Function<Double, Double> square = (Double x) -> x * x;

You can simply do

Function<Double, Double> square = Hey::square;

At runtime, these two square methods behave exactly the same as each other. The bytecode may or may not be the same (though, for the above case, the same bytecode is generated; compile the above and check with javap -c).

The only major criterion to satisfy is: the method you provide should have a similar signature to the method of the functional interface you use as object reference.

The below is illegal:

Supplier<Boolean> p = Hey::square; // illegal

square expects an argument and returns a double. The get method in Supplier returns a value but does not take an argument. Thus, this results in an error.

A method reference refers to the method of a functional interface. (As mentioned, functional interfaces can have only one method each).

Some more examples: the accept method in Consumer takes an input but doesn't return anything.

Consumer<Integer> b1 = System::exit;   // void exit(int status)
Consumer<String[]> b2 = Arrays::sort;  // void sort(Object[] a)
Consumer<String> b3 = MyProgram::main; // void main(String... args)

class Hey {
    public double getRandom() {
        return Math.random();
    }
}

Callable<Double> call = hey::getRandom;
Supplier<Double> call2 = hey::getRandom;
DoubleSupplier sup = hey::getRandom;
// Supplier is functional interface that takes no argument and gives a result

Above, getRandom takes no argument and returns a double. So any functional interface that satisfies the criteria of: take no argument and return double can be used.

Another example:

Set<String> set = new HashSet<>();
set.addAll(Arrays.asList("leo","bale","hanks"));
Predicate<String> pred = set::contains;
boolean exists = pred.test("leo");

In case of parameterized types:

class Param<T> {
    T elem;
    public T get() {
        return elem;
    }

    public void set(T elem) {
        this.elem = elem;
    }

    public static <E> E returnSame(E elem) {
        return elem;
    }
}

Supplier<Param<Integer>> obj = Param<Integer>::new;
Param<Integer> param = obj.get();
Consumer<Integer> c = param::set;
Supplier<Integer> s = param::get;

Function<String, String> func = Param::<String>returnSame;

Method references can have different styles, but fundamentally they all mean the same thing and can simply be visualized as lambdas:

  1. A static method (ClassName::methName)
  2. An instance method of a particular object (instanceRef::methName)
  3. A super method of a particular object (super::methName)
  4. An instance method of an arbitrary object of a particular type (ClassName::methName)
  5. A class constructor reference (ClassName::new)
  6. An array constructor reference (TypeName[]::new)

For further reference, see http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html.

How to use GROUP_CONCAT in a CONCAT in MySQL

SELECT ID, GROUP_CONCAT(CONCAT_WS(':', NAME, VALUE) SEPARATOR ',') AS Result 
FROM test GROUP BY ID

Excel concatenation quotes

Try this:

CONCATENATE(""""; B2 ;"""")

@widor provided a nice solution alternative too - integrated with mine:

CONCATENATE(char(34); B2 ;char(34))

Difference between _self, _top, and _parent in the anchor tag target attribute

Section 6.16 Frame target names in the HTML 4.01 spec defines the meanings, but it is partly outdated. It refers to “windows”, whereas HTML5 drafts more realistically speak about “browsing contexts”, since modern browsers often use tabs instead of windows in this context.

Briefly, _self is the default (current browsing context, i.e. current window or tab), so it is useful only to override a <base target=...> setting. The value _parent refers to the frameset that is the parent of the current frame, whereas _top “breaks out of all frames” and opens the linked document in the entire browser window.

How to solve error: "Clock skew detected"?

Simply go to the directory where the troubling file is, type touch * without quotes in the console, and you should be good.

Why aren't variable-length arrays part of the C++ standard?

(Background: I have some experience implementing C and C++ compilers.)

Variable-length arrays in C99 were basically a misstep. In order to support VLAs, C99 had to make the following concessions to common sense:

  • sizeof x is no longer always a compile-time constant; the compiler must sometimes generate code to evaluate a sizeof-expression at runtime.

  • Allowing two-dimensional VLAs (int A[x][y]) required a new syntax for declaring functions that take 2D VLAs as parameters: void foo(int n, int A[][*]).

  • Less importantly in the C++ world, but extremely important for C's target audience of embedded-systems programmers, declaring a VLA means chomping an arbitrarily large chunk of your stack. This is a guaranteed stack-overflow and crash. (Anytime you declare int A[n], you're implicitly asserting that you have 2GB of stack to spare. After all, if you know "n is definitely less than 1000 here", then you would just declare int A[1000]. Substituting the 32-bit integer n for 1000 is an admission that you have no idea what the behavior of your program ought to be.)

Okay, so let's move to talking about C++ now. In C++, we have the same strong distinction between "type system" and "value system" that C89 does… but we've really started to rely on it in ways that C has not. For example:

template<typename T> struct S { ... };
int A[n];
S<decltype(A)> s;  // equivalently, S<int[n]> s;

If n weren't a compile-time constant (i.e., if A were of variably modified type), then what on earth would be the type of S? Would S's type also be determined only at runtime?

What about this:

template<typename T> bool myfunc(T& t1, T& t2) { ... };
int A1[n1], A2[n2];
myfunc(A1, A2);

The compiler must generate code for some instantiation of myfunc. What should that code look like? How can we statically generate that code, if we don't know the type of A1 at compile time?

Worse, what if it turns out at runtime that n1 != n2, so that !std::is_same<decltype(A1), decltype(A2)>()? In that case, the call to myfunc shouldn't even compile, because template type deduction should fail! How could we possibly emulate that behavior at runtime?

Basically, C++ is moving in the direction of pushing more and more decisions into compile-time: template code generation, constexpr function evaluation, and so on. Meanwhile, C99 was busy pushing traditionally compile-time decisions (e.g. sizeof) into the runtime. With this in mind, does it really even make sense to expend any effort trying to integrate C99-style VLAs into C++?

As every other answerer has already pointed out, C++ provides lots of heap-allocation mechanisms (std::unique_ptr<int[]> A = new int[n]; or std::vector<int> A(n); being the obvious ones) when you really want to convey the idea "I have no idea how much RAM I might need." And C++ provides a nifty exception-handling model for dealing with the inevitable situation that the amount of RAM you need is greater than the amount of RAM you have. But hopefully this answer gives you a good idea of why C99-style VLAs were not a good fit for C++ — and not really even a good fit for C99. ;)


For more on the topic, see N3810 "Alternatives for Array Extensions", Bjarne Stroustrup's October 2013 paper on VLAs. Bjarne's POV is very different from mine; N3810 focuses more on finding a good C++ish syntax for the things, and on discouraging the use of raw arrays in C++, whereas I focused more on the implications for metaprogramming and the typesystem. I don't know if he considers the metaprogramming/typesystem implications solved, solvable, or merely uninteresting.


A good blog post that hits many of these same points is "Legitimate Use of Variable Length Arrays" (Chris Wellons, 2019-10-27).

CSS customized scroll bar in div

I tried a lot of plugins, most of them don't support all browsers, I prefer iScroll and nanoScroller works for all these browsers :

  • IE11 -> IE6
  • IE10 - WP8
  • IE9 - WP7
  • IE Xbox One
  • IE Xbox 360
  • Google Chrome
  • FireFox
  • Opera
  • Safari

But iScroll do not work with touch!

demo iScroll : http://lab.cubiq.org/iscroll/examples/simple/
demo nanoScroller : http://jamesflorentino.github.io/nanoScrollerJS/

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Accessing attributes from an AngularJS directive

See section Attributes from documentation on directives.

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

What are advantages of Artificial Neural Networks over Support Vector Machines?

We should also consider that the SVM system can be applied directly to non-metric spaces, such as the set of labeled graphs or strings. In fact, the internal kernel function can be generalized properly to virtually any kind of input, provided that the positive definiteness requirement of the kernel is satisfied. On the other hand, to be able to use an ANN on a set of labeled graphs, explicit embedding procedures must be considered.

How to use relative/absolute paths in css URLs?

Personally, I would fix this in the .htaccess file. You should have access to that.

Define your CSS URL as such:

url(/image_dir/image.png);

In your .htacess file, put:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^image_dir/(.*) subdir/images/$1

or

RewriteRule ^image_dir/(.*) images/$1

depending on the site.

Get WooCommerce product categories from WordPress

<?php

  $taxonomy     = 'product_cat';
  $orderby      = 'name';  
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no  
  $title        = '';  
  $empty        = 0;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
 $all_categories = get_categories( $args );
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;       
        echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';

        $args2 = array(
                'taxonomy'     => $taxonomy,
                'child_of'     => 0,
                'parent'       => $category_id,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                echo  $sub_category->name ;
            }   
        }
    }       
}
?>

This will list all the top level categories and subcategories under them hierarchically. do not use the inner query if you just want to display the top level categories. Style it as you like.

Object creation on the stack/heap?

  1. Object* o; o = new Object();

  2. Object* o = new Object();

Both these statement creates the object in the heap memory since you are creating the object using "new".

To be able to make the object creation happen in the stack, you need to follow this:

Object o;
Object *p = &o;

Creating Scheduled Tasks

You can use Task Scheduler Managed Wrapper:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch Notepad whenever the trigger fires
         td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }
}

Alternatively you can use native API or go for Quartz.NET. See this for details.

How to change FontSize By JavaScript?

JavaScript is case sensitive.

So, if you want to change the font size, you have to go:

span.style.fontSize = "25px";

Font awesome is not showing icon

You may have used a VCS (git or somesuch) to transfer icon files to the server. git says:

warning: CRLF will be replaced by LF in webroot/fonts/FontAwesome.otf.
The file will have its original line endings in your working directory.
warning: CRLF will be replaced by LF in webroot/fonts/fontawesome-webfont.eot.
The file will have its original line endings in your working directory.
warning: CRLF will be replaced by LF in webroot/fonts/fontawesome-webfont.ttf.
The file will have its original line endings in your working directory.
warning: CRLF will be replaced by LF in webroot/fonts/fontawesome-webfont.woff.
The file will have its original line endings in your working directory.
warning: CRLF will be replaced by LF in webroot/fonts/fontawesome-webfont.woff2.
The file will have its original line endings in your working directory.

You probably have to fix your fonts.

Converting a sentence string to a string array of words in Java

You can use simple following code

String str= "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.print(words[i]+" ");

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Encountered the same error in different use case.

Use Case: In chrome when tried to call Spring REST end point in angular.

enter image description here

Solution: Add @CrossOrigin("*") annotation on top of respective Controller Class.

enter image description here

I want to show all tables that have specified column name

--get tables that contains selected columnName

SELECT  c.name AS ColName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%batchno%'

its worked...

Installing SciPy and NumPy using pip

What operating system is this? The answer might depend on the OS involved. However, it looks like you need to find this BLAS library and install it. It doesn't seem to be in PIP (you'll have to do it by hand thus), but if you install it, it ought let you progress your SciPy install.

Auto-expanding layout with Qt-Designer

I've tried to find a "fit to screen" property but there is no such.

But setting widget's "maximumSize" to a "some big number" ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.

How to make a text box have rounded corners?

This can be done with CSS3:

<input type="text" />

input
{
  -moz-border-radius: 15px;
 border-radius: 15px;
    border:solid 1px black;
    padding:5px;
}

http://jsfiddle.net/UbSkn/1/


However, an alternative would be to put the input inside a div with a rounded background, and no border on the input

How do I 'svn add' all unversioned files to SVN?

After spending some time trying to figure out how to recursively add only some of the files, i thought it would be valid to share what did work for me:

FOR /F %F IN ('dir /s /b /a:d') DO svn add --depth=empty "%F"
FOR /F %F IN ('dir /s /b /a *.cs *.csproj *.rpt *.xsd *.resx *.ico *.sql') DO svn add "%F"

Here goes some explanation.

The first command adds all the directories. The second command adds only the files accordingly to the specifed patterns.

Let me give more details:

  • FOR: you know, the loop control.
  • /F: means take the files and directories (not sure exactly).
  • %F: its a variable; it will assume the value of each of the listed files at a time; it could have another one-character-name.
  • IN: no need to explain, right?
  • ('dir /s /b /a:d'): the DOS command that will list the directories; in my case /s is recursive, /b is to take only the full path, /a:d means only the directory; change it as you wish keeping the parenthesis and apostrophes.
  • DO: means that what comes next in the command is what will be executed for each directory
  • svn add --depth=empty: it is the desired SVN commando to be run; the depth definition means to add only the directory and not the files inside them.
  • "%F": that's how you use the variable defined earlier.

In the second command, the only differences are the dir command and the svn command, i think it is clear enough.

encrypt and decrypt md5

This question is tagged with PHP. But many people are using Laravel framework now. It might help somebody in future. That's why I answering for Laravel. It's more easy to encrypt and decrypt with internal functions.

$string = 'c4ca4238a0b923820dcc';
$encrypted = \Illuminate\Support\Facades\Crypt::encrypt($string);
$decrypted_string = \Illuminate\Support\Facades\Crypt::decrypt($encrypted);

var_dump($string);
var_dump($encrypted);
var_dump($decrypted_string);

Note: Be sure to set a 16, 24, or 32 character random string in the key option of the config/app.php file. Otherwise, encrypted values will not be secure.

But you should not use encrypt and decrypt for authentication. Rather you should use hash make and check.

To store password in database, make hash of password and then save.

$password = Input::get('password_from_user'); 
$hashed = Hash::make($password); // save $hashed value

To verify password, get password stored of account from database

// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
  // Password is not matching 
} else {
  // Password is matching 
}

Correct way to initialize HashMap and can HashMap hold different value types?

The way you're writing it is equivalent to

HashMap<Object, Object> map = new HashMap<Object, Object>();

What goes inside the brackets is you communicating to the compiler what you're going to put in the HashMap so that it can do error checking for you. If Object, Object is what you actually want (probably not) you should explicitly declare it. In general you should be as explicit as you can with the declaration to facilitate error checking by the compiler. What you've described should probably be declared like this:

HashMap<String, Object> map = new HashMap<String, Object>();

That way you at least declare that your keys are going to be strings, but your values can be anything. Just remember to use a cast when you get a value back out.

What are the rules about using an underscore in a C++ identifier?

The rules (which did not change in C++11):

  • Reserved in any scope, including for use as implementation macros:
    • identifiers beginning with an underscore followed immediately by an uppercase letter
    • identifiers containing adjacent underscores (or "double underscore")
  • Reserved in the global namespace:
    • identifiers beginning with an underscore
  • Also, everything in the std namespace is reserved. (You are allowed to add template specializations, though.)

From the 2003 C++ Standard:

17.4.3.1.2 Global names [lib.global.names]

Certain sets of names and function signatures are always reserved to the implementation:

  • Each name that contains a double underscore (__) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
  • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165

165) Such names are also reserved in namespace ::std (17.4.3.1).

Because C++ is based on the C standard (1.1/2, C++03) and C99 is a normative reference (1.2/1, C++03) these also apply, from the 1999 C Standard:

7.1.3 Reserved identifiers

Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.

  • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
  • Each macro name in any of the following subclauses (including the future library directions) is reserved for use as specified if any of its associated headers is included; unless explicitly stated otherwise (see 7.1.4).
  • All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.154
  • Each identifier with file scope listed in any of the following subclauses (including the future library directions) is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.

No other identifiers are reserved. If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.

If the program removes (with #undef) any macro definition of an identifier in the first group listed above, the behavior is undefined.

154) The list of reserved identifiers with external linkage includes errno, math_errhandling, setjmp, and va_end.

Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code:

  • Names beginning with a capital E followed a digit or uppercase letter:
    • may be used for additional error code names.
  • Names that begin with either is or to followed by a lowercase letter
    • may be used for additional character testing and conversion functions.
  • Names that begin with LC_ followed by an uppercase letter
    • may be used for additional macros specifying locale attributes.
  • Names of all existing mathematics functions suffixed with f or l are reserved
    • for corresponding functions that operate on float and long double arguments, respectively.
  • Names that begin with SIG followed by an uppercase letter are reserved
    • for additional signal names.
  • Names that begin with SIG_ followed by an uppercase letter are reserved
    • for additional signal actions.
  • Names beginning with str, mem, or wcs followed by a lowercase letter are reserved
    • for additional string and array functions.
  • Names beginning with PRI or SCN followed by any lowercase letter or X are reserved
    • for additional format specifier macros
  • Names that end with _t are reserved
    • for additional type names.

While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard.


Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore.

After doing research on this article I no longer end my identifiers with _t as this is reserved by the POSIX standard.

The rule about any identifier ending with _t surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the GNU libtool manual, listing reserved names.

CesarB provided the following link to the POSIX 2004 reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The POSIX 2008 reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.

AttributeError: can't set attribute in python

namedtuples are immutable, just like standard tuples. You have two choices:

  1. Use a different data structure, e.g. a class (or just a dictionary); or
  2. Instead of updating the structure, replace it.

The former would look like:

class N(object):

    def __init__(self, ind, set, v):
        self.ind = ind
        self.set = set
        self.v = v

And the latter:

item = items[node.ind]
items[node.ind] = N(item.ind, item.set, node.v)

Edit: if you want the latter, Ignacio's answer does the same thing more neatly using baked-in functionality.

How to get MAC address of your machine using a C program?

Using getifaddrs you can get MAC address from the family AF_PACKET.

In order to display the MAC address to each interface, you can proceed like this:

#include <stdio.h>
#include <ifaddrs.h>
#include <netpacket/packet.h>

int main (int argc, const char * argv[])
{
    struct ifaddrs *ifaddr=NULL;
    struct ifaddrs *ifa = NULL;
    int i = 0;

    if (getifaddrs(&ifaddr) == -1)
    {
         perror("getifaddrs");
    }
    else
    {
         for ( ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
         {
             if ( (ifa->ifa_addr) && (ifa->ifa_addr->sa_family == AF_PACKET) )
             {
                  struct sockaddr_ll *s = (struct sockaddr_ll*)ifa->ifa_addr;
                  printf("%-8s ", ifa->ifa_name);
                  for (i=0; i <s->sll_halen; i++)
                  {
                      printf("%02x%c", (s->sll_addr[i]), (i+1!=s->sll_halen)?':':'\n');
                  }
             }
         }
         freeifaddrs(ifaddr);
    }
    return 0;
}

Ideone

How do I find the size of a struct?

Contrary to what some of the other answers have said, on most systems, in the absence of a pragma or compiler option, the size of the structure will be at least 6 bytes and, on most 32-bit systems, 8 bytes. For 64-bit systems, the size could easily be 16 bytes. Alignment does come into play; always. The sizeof a single struct has to be such that an array of those sizes can be allocated and the individual members of the array are sufficiently aligned for the processor in question. Consequently, if the size of the struct was 5 as others have hypothesized, then an array of two such structures would be 10 bytes long, and the char pointer in the second array member would be aligned on an odd byte, which would (on most processors) cause a major bottleneck in the performance.

Printing Even and Odd using two Threads in Java

Found the solution. Someone looking for solution to this problem can refer :-)

public class PrintEvenOddTester {

    public static void main(String... args) {
        Printer print = new Printer();
        Thread t1 = new Thread(new TaskEvenOdd(print, 10, false));
        Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
        t1.start();
        t2.start();
    }

}

class TaskEvenOdd implements Runnable {

    private int max;
    private Printer print;
    private boolean isEvenNumber;

    TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {
        this.print = print;
        this.max = max;
        this.isEvenNumber = isEvenNumber;
    }

    @Override
    public void run() {

        //System.out.println("Run method");
        int number = isEvenNumber == true ? 2 : 1;
        while (number <= max) {

            if (isEvenNumber) {
                //System.out.println("Even :"+ Thread.currentThread().getName());
                print.printEven(number);
                //number+=2;
            } else {
                //System.out.println("Odd :"+ Thread.currentThread().getName());
                print.printOdd(number);
                // number+=2;
            }
            number += 2;
        }

    }

}

class Printer {

    boolean isOdd = false;

    synchronized void printEven(int number) {

        while (isOdd == false) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Even:" + number);
        isOdd = false;
        notifyAll();
    }

    synchronized void printOdd(int number) {
        while (isOdd == true) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Odd:" + number);
        isOdd = true;
        notifyAll();
    }

}

This gives output like:

Odd:1
Even:2
Odd:3
Even:4
Odd:5
Even:6
Odd:7
Even:8
Odd:9
Even:10

Difference between matches() and find() in Java Regex

find() will consider the sub-string against the regular expression where as matches() will consider complete expression.

find() will returns true only if the sub-string of the expression matches the pattern.

public static void main(String[] args) {
        Pattern p = Pattern.compile("\\d");
        String candidate = "Java123";
        Matcher m = p.matcher(candidate);

        if (m != null){
            System.out.println(m.find());//true
            System.out.println(m.matches());//false
        }
    }

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}

Checking that a List is not empty in Hamcrest

This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));

But if you have to use older version - instead of bugged empty() you could use:

hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan; or
import static org.hamcrest.Matchers.greaterThan;)

Example:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));

The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.

jQuery.css() - marginLeft vs. margin-left?

I think it is so it can keep consistency with the available options used when settings multiple css styles in one function call through the use of an object, for example...

$(".element").css( { marginLeft : "200px", marginRight : "200px" } );

as you can see the property are not specified as strings. JQuery also supports using string if you still wanted to use the dash, or for properties that perhaps cannot be set without the dash, so the following still works...

$(".element").css( { "margin-left" : "200px", "margin-right" : "200px" } );

without the quotes here, the javascript would not parse correctly as property names cannot have a dash in them.

EDIT: It would appear that JQuery is not actually making the distinction itsleft, instead it is just passing the property specified for the DOM to care about, most likely with style[propertyName];

How to add meta tag in JavaScript

Try

_x000D_
_x000D_
document.head.innerHTML += '<meta http-equiv="X-UA-..." content="IE=edge">'
_x000D_
_x000D_
_x000D_

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

word-break:break-all :

word to continue to border then break in newline.

word-wrap:break-word :

At first , word wrap in newline then continue to border.

Example :

_x000D_
_x000D_
div {_x000D_
   border: 1px solid red;_x000D_
   width: 200px;_x000D_
}_x000D_
_x000D_
span {_x000D_
  background-color: yellow;_x000D_
}_x000D_
_x000D_
.break-all {_x000D_
  word-break:break-all;_x000D_
 }_x000D_
.break-word {_x000D_
  word-wrap:break-word;  _x000D_
}
_x000D_
<b>word-break:break-all</b>_x000D_
_x000D_
<div class="break-all">_x000D_
  This text is styled with_x000D_
  <span>soooooooooooooooooooooooooome</span> of the text_x000D_
  formatting properties._x000D_
</div>_x000D_
_x000D_
<b> word-wrap:break-word</b>_x000D_
_x000D_
<div class="break-word">_x000D_
  This text is styled with_x000D_
  <span>soooooooooooooooooooooooooome</span> of the text_x000D_
  formatting properties._x000D_
</div>
_x000D_
_x000D_
_x000D_

Merge (with squash) all changes from another branch as a single commit

You can do this with the "rebase" command. Let's call the branches "main" and "feature":

git checkout feature
git rebase main

The rebase command will replay all of the commits on "feature" as one commit with a parent equal to "main".

You might want to run git merge main before git rebase main if "main" has changed since "feature" was created (or since the most recent merge). That way, you still have your full history in case you had a merge conflict.

After the rebase, you can merge your branch to main, which should result in a fast-forward merge:

git checkout main
git merge feature

See the rebase page of Understanding Git Conceptually for a good overview

How to make a variadic macro (variable number of arguments)

#define DEBUG

#ifdef DEBUG
  #define PRINT print
#else
  #define PRINT(...) ((void)0) //strip out PRINT instructions from code
#endif 

void print(const char *fmt, ...) {

    va_list args;
    va_start(args, fmt);
    vsprintf(str, fmt, args);
        va_end(args);

        printf("%s\n", str);

}

int main() {
   PRINT("[%s %d, %d] Hello World", "March", 26, 2009);
   return 0;
}

If the compiler does not understand variadic macros, you can also strip out PRINT with either of the following:

#define PRINT //

or

#define PRINT if(0)print

The first comments out the PRINT instructions, the second prevents PRINT instruction because of a NULL if condition. If optimization is set, the compiler should strip out never executed instructions like: if(0) print("hello world"); or ((void)0);

Using relative URL in CSS file, what location is it relative to?

Try using:

body {
  background-attachment: fixed;
  background-image: url(./Images/bg4.jpg);
}

Images being folder holding the picture that you want to post.

Using a Python subprocess call to invoke a Python script

subprocess.call expects the same arguments as subprocess.Popen - that is a list of strings (the argv in C) rather than a single string.

It's quite possible that your child process attempted to run "s" with the parameters "o", "m", "e", ...

Where can I get a virtual machine online?

You can get free Virtual Machine and many more things online for 3 months provided by Microsoft Azure. I guess you need VPN for learning purpose. For that it would suffice.

Refer http://www.windowsazure.com/en-us/pricing/free-trial/

Java Does Not Equal (!=) Not Working?

You need to use the method equals() when comparing a string, otherwise you're just comparing the object references to each other, so in your case you want:

if (!statusCheck.equals("success")) {

Convert from enum ordinal to enum type

public enum Suit implements java.io.Serializable, Comparable<Suit>{
  spades, hearts, diamonds, clubs;
  private static final Suit [] lookup  = Suit.values();
  public Suit fromOrdinal(int ordinal) {
    if(ordinal< 1 || ordinal> 3) return null;
    return lookup[value-1];
  }
}

the test class

public class MainTest {
    public static void main(String[] args) {
        Suit d3 = Suit.diamonds;
        Suit d3Test = Suit.fromOrdinal(2);
        if(d3.equals(d3Test)){
            System.out.println("Susses");
        }else System.out.println("Fails");
    }
}

I appreciate that you share with us if you have a more efficient code, My enum is huge and constantly called thousands of times.

"Could not find acceptable representation" using spring-boot-starter-web

In my case I was sending in correct object in ResponseEntity<>().

Correct :

@PostMapping(value = "/get-customer-details", produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> getCustomerDetails(@RequestBody String requestMessage) throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("customerId", "123");
    jsonObject.put("mobileNumber", "XXX-XXX-XXXX");
    return new ResponseEntity<>(jsonObject.toString(), HttpStatus.OK);
}

Incorrect :

return new ResponseEntity<>(jsonObject, HttpStatus.OK);

Because, jsonObject's toString() method "Encodes the jsonObject as a compact JSON string". Therefore, Spring returns json string directly without any further serialization.

When we send jsonObject instead, Spring tries to serialize it based on produces method used in RequestMapping and fails due to it "Could not find acceptable representation".

Adjust plot title (main) position

We can use title() function with negative line value to bring down the title.

See this example:

plot(1, 1)
title("Title", line = -2)

enter image description here

How to Set Active Tab in jQuery Ui

Inside your function for the click action use

$( "#tabs" ).tabs({ active: # });

Where # is replaced by the tab index you want to select.

Edit: change from selected to active, selected is deprecated

How do you make an anchor link non-clickable or disabled?

Add a css class:

.disable_a_href{
    pointer-events: none;
}

Add this jquery:

$("#ThisLink").addClass("disable_a_href"); 

How do I get bootstrap-datepicker to work with Bootstrap 3?

I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.

You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.

Here is my solution:

<div class="form-group row">
  <div class="col-xs-8">
    <label class="control-label">My Label</label>
    <div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
      <input class="form-control" type="text" readonly="" value="12-02-2012">
      <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
  </div>
</div>

CSS changes in datepicker.css on lines 176-177:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 34:

this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;

UPDATE

Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:

CSS changes in datepicker.css on lines 446-447:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 46:

 this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;

Finally, the JavaScript to enable the datepicker (with some options):

 $(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });

Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

Case Function Equivalent in Excel

Recently I unfortunately had to work with Excel 2010 again for a while and I missed the SWITCH function a lot. I came up with the following to try to minimize my pain:

=CHOOSE(SUM((A1={"a";"b";"c"})*ROW(INDIRECT(1&":"&3))),1,2,3)
CTRL+SHIFT+ENTER

where A1 is where your condition lies (it could be a formula, whatever). The good thing is that we just have to provide the condition once (just like SWITCH) and the cases (in this example: a,b,c) and results (in this example: 1,2,3) are ordered, which makes it easy to reason about.

Here is how it works:

  • Cond={"c1";"c2";...;"cn"} returns a N-vector of TRUE or FALSE (with behaves like 1s and 0s)
  • ROW(INDIRECT(1&":"&n)) returns a N-vector of ordered numbers: 1;2;3;...;n
  • The multiplication of both vectors will return lots of zeros and a number (position) where the condition was matched
  • SUM just transforms this vector with zeros and a position into just a single number, which CHOOSE then can use
  • If you want to add another condition, just remember to increment the last number inside INDIRECT
  • If you want an ELSE case, just wrap it inside an IFERROR formula
  • The formula will not behave properly if you provide the same condition more than once, but I guess nobody would want to do that anyway

When should one use a spinlock instead of mutex?

The rule for using spinlocks is simple: use a spinlock if and only if the real time the lock is held is bounded and sufficiently small.

Note that usually user implemented spinlocks DO NOT satisfy this requirement because they do not disable interrupts. Unless pre-emptions are disabled, a pre-emption whilst a spinlock is held violates the bounded time requirement.

Sufficiently small is a judgement call and depends on the context.

Exception: some kernel programming must use a spinlock even when the time is not bounded. In particular if a CPU has no work to do, it has no choice but to spin until some more work turns up.

Special danger: in low level programming take great care when multiple interrupt priorities exist (usually there is at least one non-maskable interrupt). In this higher priority pre-emptions can run even if interrupts at the thread priority are disabled (such as priority hardware services, often related to the virtual memory management). Provided a strict priority separation is maintained, the condition for bounded real time must be relaxed and replaced with bounded system time at that priority level. Note in this case not only can the lock holder be pre-empted but the spinner can also be interrupted; this is generally not a problem because there's nothing you can do about it.

How to iterate over the keys and values with ng-repeat in AngularJS?

Here's a working example:

<div class="item item-text-wrap" ng-repeat="(key,value) in form_list">
  <b>{{key}}</b> : {{value}}
</div>

edited

How to convert a char array to a string?

There is a small problem missed in top-voted answers. Namely, character array may contain 0. If we will use constructor with single parameter as pointed above we will lose some data. The possible solution is:

cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;

Output is:

123
123 123

Python xml ElementTree from a string source?

You need the xml.etree.ElementTree.fromstring(text)

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)

Find object in list that has attribute equal to some value (that meets any condition)

I just ran into a similar problem and devised a small optimization for the case where no object in the list meets the requirement.(for my use-case this resulted in major performance improvement):

Along with the list test_list, I keep an additional set test_value_set which consists of values of the list that I need to filter on. So here the else part of agf's solution becomes very-fast.

What is the best way to tell if a character is a letter or number in Java without using regexes?

Compare its value. It should be between the value of 'a' and 'z', 'A' and 'Z', '0' and '9'

Using a SELECT statement within a WHERE clause

There's a much better way to achieve your desired result, using SQL Server's analytic (or windowing) functions.

SELECT DISTINCT Date, MAX(Score) OVER(PARTITION BY Date) FROM ScoresTable

If you need more than just the date and max score combinations, you can use ranking functions, eg:

SELECT  *
FROM    ScoresTable t
JOIN (   
    SELECT 
        ScoreId,
        ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Score DESC) AS [Rank] 
        FROM ScoresTable
) window ON window.ScoreId = p.ScoreId AND window.[Rank] = 1

You may want to use RANK() instead of ROW_NUMBER() if you want multiple records to be returned if they both share the same MAX(Score).

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

Jquery UI datepicker. Disable array of Dates

For DD-MM-YY use this code:

var array = ["03-03-2017', '03-10-2017', '03-25-2017"]

$('#datepicker').datepicker({
    beforeShowDay: function(date){
    var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
    return [ array.indexOf(string) == -1 ]
    }
});

function highlightDays(date) {
    for (var i = 0; i < dates.length; i++) {
    if (new Date(dates[i]).toString() == date.toString()) {
        return [true, 'highlight'];
    }
}
return [true, ''];
}

calculating execution time in c++

With C++11 for measuring the execution time of a piece of code, we can use the now() function:

auto start = chrono::steady_clock::now();

//  Insert the code that will be timed

auto end = chrono::steady_clock::now();

// Store the time difference between start and end
auto diff = end - start;

If you want to print the time difference between start and end in the above code, you could use:

cout << chrono::duration <double, milli> (diff).count() << " ms" << endl;

If you prefer to use nanoseconds, you will use:

cout << chrono::duration <double, nano> (diff).count() << " ns" << endl;

The value of the diff variable can be also truncated to an integer value, for example, if you want the result expressed as:

diff_sec = chrono::duration_cast<chrono::nanoseconds>(diff);
cout << diff_sec.count() << endl;

For more info click here

Android studio logcat nothing to show

Run this command in terminal. It will start working again.

adb kill-server && adb start-server

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

I have installed VMWare Workstation. So, It was causing the error.

Services.msc and stopped the 'Workstation' Services.

This has solved my problems.

Thanks

How do I import a pre-existing Java project into Eclipse and get up and running?

I think you'll have to import the project via the file->import wizard:

http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse

It's not the last step, but it will start you on your way.

I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).

How to check if dropdown is disabled?

The legacy solution, before 1.6, was to use .attr and handle the returned value as a bool. The main problem is that the returned type of .attr has changed to string, and therefore the comparison with == true is broken (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)).

With 1.6 .prop was introduced, which returns a bool.

Nevertheless, I suggest to use .is(), as the returned type is intrinsically bool, like:

$('#dropUnit').is(':disabled');
$('#dropUnit').is(':enabled');

Furthermore .is() is much more natural (in terms of "natural language") and adds more conditions than a simple attribute-comparison (eg: .is(':last'), .is(':visible'), ... please see documentation on selectors).

How can you check for a #hash in a URL using JavaScript?

If the URI is not the document's location this snippet will do what you want.

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}

jquery how to catch enter key and change event to tab

This is at last what is working for me perfectly. I am using jqeasyui and it is working fine

$(document).on('keyup', 'input', function(e) {
 if(e.keyCode == 13 && e.target.type        !== 'submit') {
   var inputs =   $(e.target).parents("form").eq(0).find(":input:visible"),
   idx = inputs.index(e.target);
       if (idx == inputs.length - 1) {
          inputs[0].select()
       } else {
          inputs[idx + 1].focus();
          inputs[idx + 1].select();
       }
 }

});

Controlling number of decimal digits in print output in R

One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))

For example, if you have a vector as elements and would like to get sum of it

elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432

Apparently, the last digital as 1 been truncated, the ideal result should be -876.54321, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements)), redundant zero(s) generate as -876.5432100000

Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321, there are 5 decimal digits need to print, then we can set up a parameter for format function as below:

decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321

We can change the decimal_length based on each time query, so it can satisfy different decimal printing requirement.

Difference between except: and except Exception as e: in Python

Using the second form gives you a variable (named based upon the as clause, in your example e) in the except block scope with the exception object bound to it so you can use the infomration in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

  • if you unable to find assembly reference from when (Right click on reference ->add required assembly)

try this Package manager console
Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3 and then add by using add reference .

IF...THEN...ELSE using XML

<IF id="if-1">
   <TIME from="5pm" to="9pm" />
<ELSE>
   <something else />
</ELSE>
</IF>

I don't know if this makes any sense to anyone else or it is actually usable in your program, but I would do it like this.

My point of view: You need to have everything related to your "IF" inside your IF-tag, otherwise you won't know what ELSE belongs to what IF. Secondly, I'd skip the THEN tag because it always follows an IF.

print call stack in C or C++

For a linux-only solution you can use backtrace(3) that simply returns an array of void * (in fact each of these point to the return address from the corresponding stack frame). To translate these to something of use, there's backtrace_symbols(3).

Pay attention to the notes section in backtrace(3):

The symbol names may be unavailable without the use of special linker options. For systems using the GNU linker, it is necessary to use the -rdynamic linker option. Note that names of "static" functions are not exposed, and won't be available in the backtrace.

Only get hash value using md5sum (without filename)

For the sake of completeness a way with sed using regex and capture group:

md5=$(md5sum "${my_iso_file}" | sed -r 's:\\*([^ ]*).*:\1:')

The regulare expression is capturing everything in a group until a space is reached. To get capture group working you need to capture everything in sed. (More about sed and caputer groups here: https://stackoverflow.com/a/2778096/10926293)
As delimiter in sed i use colons because they are not valid in file paths and i don't have to escape the slashed in the filepath.

UICollectionView cell selection and cell reuse

What I did to solve this was to make the changes in the customized cell. You have a custom cell called DataSetCell in its class you could do the following (the code is in swift)

override var isSelected: Bool {
    didSet {
        if isSelected {
            changeStuff
        } else {
            changeOtherStuff
        }
    }
}

What this does is that every time the cell is selected, deselected, initialized or get called from the reusable queue, that code will run and the changes will be made. Hope this helps you.

Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

Java Runtime.getRuntime(): getting output from executing a command line program

Try reading the InputStream of the runtime:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-send", argument};
Process proc = rt.exec(commands);
BufferedReader br = new BufferedReader(
    new InputStreamReader(proc.getInputStream()));
String line;
while ((line = br.readLine()) != null)
    System.out.println(line);

You might also need to read the error stream (proc.getErrorStream()) if the process is printing error output. You can redirect the error stream to the input stream if you use ProcessBuilder.

What does string::npos mean in this code?

The document for string::npos says:

npos is a static member constant value with the greatest possible value for an element of type size_t.

As a return value it is usually used to indicate failure.

This constant is actually defined with a value of -1 (for any trait), which because size_t is an unsigned integral type, becomes the largest possible representable value for this type.

Open new Terminal Tab from command line (Mac OS X)

when you are in a terminal window, command + n => opens a new terminal and command + t => opens a new tab in current terminal window

What is the best way to iterate over multiple lists at once?

You can use zip:

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
...   print x, y
... 
1 a
2 b
3 c

How to send an object from one Android Activity to another using Intents?

If you have a singleton class (fx Service) acting as gateway to your model layer anyway, it can be solved by having a variable in that class with getters and setters for it.

In Activity 1:

Intent intent = new Intent(getApplicationContext(), Activity2.class);
service.setSavedOrder(order);
startActivity(intent);

In Activity 2:

private Service service;
private Order order;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quality);

    service = Service.getInstance();
    order = service.getSavedOrder();
    service.setSavedOrder(null) //If you don't want to save it for the entire session of the app.
}

In Service:

private static Service instance;

private Service()
{
    //Constructor content
}

public static Service getInstance()
{
    if(instance == null)
    {
        instance = new Service();
    }
    return instance;
}
private Order savedOrder;

public Order getSavedOrder()
{
    return savedOrder;
}

public void setSavedOrder(Order order)
{
    this.savedOrder = order;
}

This solution does not require any serialization or other "packaging" of the object in question. But it will only be beneficial if you are using this kind of architecture anyway.

What does __FILE__ mean in Ruby?

__FILE__ is the filename with extension of the file containing the code being executed.

In foo.rb, __FILE__ would be "foo.rb".

If foo.rb were in the dir /home/josh then File.dirname(__FILE__) would return /home/josh.

How to calculate the sentence similarity using word2vec model of gensim with python

I have tried the methods provided by the previous answers. It works, but the main drawback of it is that the longer the sentences the larger similarity will be(to calculate the similarity I use the cosine score of the two mean embeddings of any two sentences) since the more the words the more positive semantic effects will be added to the sentence.

I thought I should change my mind and use the sentence embedding instead as studied in this paper and this.

OpenMP set_num_threads() is not working

The omp_get_num_threads() function returns the number of threads that are currently in the team executing the parallel region from which it is called. You are calling it outside of the parallel region, which is why it returns 1.

How to find the Git commit that introduced a string in any branch?

You can do:

git log -S <whatever> --source --all

To find all commits that added or removed the fixed string whatever. The --all parameter means to start from every branch and --source means to show which of those branches led to finding that commit. It's often useful to add -p to show the patches that each of those commits would introduce as well.

Versions of git since 1.7.4 also have a similar -G option, which takes a regular expression. This actually has different (and rather more obvious) semantics, explained in this blog post from Junio Hamano.

As thameera points out in the comments, you need to put quotes around the search term if it contains spaces or other special characters, for example:

git log -S 'hello world' --source --all
git log -S "dude, where's my car?" --source --all

Here's an example using -G to find occurrences of function foo() {:

git log -G "^(\s)*function foo[(][)](\s)*{$" --source --all

Can I have multiple background images using CSS?

The easiest way I have found to use two different background images in one div is with this line of code:

body {
    background:url(image1.png) repeat-x, url(image2.png) repeat;
}

Obviously, that does not have to be for only the body of the website, you can use that for any div you want.

Hope that helps! There is a post on my blog that talks about this a little more in depth if anyone needs further instructions or help - http://blog.thelibzter.com/css-tricks-use-two-background-images-for-one-div.

React onClick and preventDefault() link refresh/redirect?

A nice and simple option that worked for me was:

<a href="javascript: false" onClick={this.handlerName}>Click Me</a>

Oracle Convert Seconds to Hours:Minutes:Seconds

Try this one. Very simple and easy to use

select to_char(to_date(10000,'sssss'),'hh24:mi:ss') from dual;

How do you create an asynchronous method in C#?

One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:

You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.

Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.

private async Task<DateTime> CountToAsync(int num = 1000)
{
    await Task.Yield();
    for (int i = 0; i < num; i++)
    {
        Console.WriteLine("#{0}", i);
    }
    return DateTime.Now;
}

".addEventListener is not a function" why does this error occur?

Try this one:

var comment = document.querySelector("button");
function showComment() {
  var place = document.querySelector('#textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);

Use querySelector instead of className

How to set image to fit width of the page using jsPDF?

I discovered this while experimenting with html2canvas this morning. While this doesn't include provisions for printing multiple pages it does scale the image to page width and reframes the height in ratio to the adjusted width:

html2canvas(document.getElementById('testdiv')).then(function(canvas){
        var wid: number
        var hgt: number
        var img = canvas.toDataURL("image/png", wid = canvas.width, hgt = canvas.height);
        var hratio = hgt/wid
        var doc = new jsPDF('p','pt','a4');
        var width = doc.internal.pageSize.width;    
        var height = width * hratio
        doc.addImage(img,'JPEG',20,20, width, height);
        doc.save('Test.pdf');
    });

How to have jQuery restrict file types on upload?

I try to write working code example, I test it and everything works.

Hare is code:

HTML:

<input type="file" class="attachment_input" name="file" onchange="checkFileSize(this, @Model.MaxSize.ToString(),@Html.Raw(Json.Encode(Model.FileExtensionsList)))" />

Javascript:

 //function for check attachment size and extention match
function checkFileSize(element, maxSize, extentionsArray) {
    var val = $(element).val(); //get file value

    var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase(); // get file extention 
    if ($.inArray(ext, extentionsArray) == -1) {
        alert('false extension!');
    }

    var fileSize = ($(element)[0].files[0].size / 1024 / 1024); //size in MB
    if (fileSize > maxSize) {
        alert("Large file");// if Maxsize from Model > real file size alert this
    }
}

PostgreSQL: Which version of PostgreSQL am I running?

A simple way is to check the version by typing psql --version in terminal

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

It is because you set the width:100% which by definition only spans the width of the screen. You want to set the min-width:100% which sets it to the width of the screen... with the ability to grow beyond that.

Also make sure you set min-width:100% for body and html.

Why do we need to use flatMap?

['a','b','c'].flatMap(function(e) {
    return [e, e+ 'x', e+ 'y',  e+ 'z'  ];
});
//['a', 'ax', 'ay', 'az', 'b', 'bx', 'by', 'bz', 'c', 'cx', 'cy', 'cz']


['a','b','c'].map(function(e) {
    return [e, e+ 'x', e+ 'y',  e+ 'z'  ];
});
//[Array[4], Array[4], Array[4]]

You use flatMap when you have an Observable whose results are more Observables.

If you have an observable which is produced by an another observable you can not filter, reduce, or map it directly because you have an Observable not the data. If you produce an observable choose flatMap over map; then you are okay.

As in second snippet, if you are doing async operation you need to use flatMap.

_x000D_
_x000D_
var source = Rx.Observable.interval(100).take(10).map(function(num){_x000D_
    return num+1_x000D_
});_x000D_
source.subscribe(function(e){_x000D_
    console.log(e)_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.1/Rx.min.js"></script>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
var source = Rx.Observable.interval(100).take(10).flatMap(function(num){_x000D_
    return Rx.Observable.timer(100).map(() => num)_x000D_
});_x000D_
source.subscribe(function(e){_x000D_
    console.log(e)_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.1/Rx.min.js"></script>
_x000D_
_x000D_
_x000D_

Check if a record exists in the database

You can write as follows:

SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
if (check_User_Name.ExecuteScalar()!=null)
{
    int UserExist = (int)check_User_Name.ExecuteScalar();
    if (UserExist > 0)
    {
        //Username Exist
    }
}

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

Can try with below code

 WebDriverWait wait = new WebDriverWait(driver, 30);

Pass other element would receive the click:<a class="navbar-brand" href="#"></a>

    boolean invisiable = wait.until(ExpectedConditions
            .invisibilityOfElementLocated(By.xpath("//div[@class='navbar-brand']")));

Pass clickable button id as shown below

    if (invisiable) {
        WebElement ele = driver.findElement(By.xpath("//div[@id='button']");
        ele.click();
    }

Calling a phone number in swift

For Swift 4.2 and above

if let phoneCallURL = URL(string: "tel://\(01234567)"), UIApplication.shared.canOpenURL(phoneCallURL)
{
    UIApplication.shared.open(phoneCallURL, options: [:], completionHandler: nil)
}

How to do a SQL NOT NULL with a DateTime?

erm it does work? I've just tested it?

/****** Object:  Table [dbo].[DateTest]    Script Date: 09/26/2008 10:44:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DateTest](
    [Date1] [datetime] NULL,
    [Date2] [datetime] NOT NULL
) ON [PRIMARY]

GO
Insert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008')
Insert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008')
Go
SELECT * FROM DateTest WHERE Date1 is not NULL
GO
SELECT * FROM DateTest WHERE Date2 is not NULL

Default interface methods are only supported starting with Android N

Update your build.gradle(Module:app) add compileOptions block and add JavaVersion.VERSION_1_8

apply plugin: 'com.android.application'

android {
    .................
    .........................
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

I have met the same problem and after long investigation of my XML file I found the problem: there was few unescaped characters like « ».

What does file:///android_asset/www/index.html mean?

The URI "file:///android_asset/" points to YourProject/app/src/main/assets/.

Note: android_asset/ uses the singular (asset) and src/main/assets uses the plural (assets).

Suppose you have a file YourProject/app/src/main/assets/web_thing.html that you would like to display in a WebView. You can refer to it like this:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/web_thing.html");

The snippet above could be located in your Activity class, possibly in the onCreate method.

Here is a guide to the overall directory structure of an android project, that helped me figure out this answer.

Java equivalent to C# extension methods

Technically C# Extension have no equivalent in Java. But if you do want to implement such functions for a cleaner code and maintainability, you have to use Manifold framework.

package extensions.java.lang.String;

import manifold.ext.api.*;

@Extension
public class MyStringExtension {

  public static void print(@This String thiz) {
    System.out.println(thiz);
  }

  @Extension
  public static String lineSeparator() {
    return System.lineSeparator();
  }
}

Get environment value in controller

In Controller

$hostname = $_ENV['IMAP_HOSTNAME_TEST']; (or) $hostname = env('IMAP_HOSTNAME_TEST');

In blade.view

{{$_ENV['IMAP_HOSTNAME_TEST']}}

Get the current user, within an ApiController action, without passing the userID as a parameter

In WebApi 2 you can use RequestContext.Principal from within a method on ApiController

RE error: illegal byte sequence on Mac OS X

mklement0's answer is great, but I have some small tweaks.

It seems like a good idea to explicitly specify bash's encoding when using iconv. Also, we should prepend a byte-order mark (even though the unicode standard doesn't recommend it) because there can be legitimate confusions between UTF-8 and ASCII without a byte-order mark. Unfortunately, iconv doesn't prepend a byte-order mark when you explicitly specify an endianness (UTF-16BE or UTF-16LE), so we need to use UTF-16, which uses platform-specific endianness, and then use file --mime-encoding to discover the true endianness iconv used.

(I uppercase all my encodings because when you list all of iconv's supported encodings with iconv -l they are all uppercase.)

# Find out MY_FILE's encoding
# We'll convert back to this at the end
FILE_ENCODING="$( file --brief --mime-encoding MY_FILE )"
# Find out bash's encoding, with which we should encode
# MY_FILE so sed doesn't fail with 
# sed: RE error: illegal byte sequence
BASH_ENCODING="$( locale charmap | tr [:lower:] [:upper:] )"
# Convert to UTF-16 (unknown endianness) so iconv ensures
# we have a byte-order mark
iconv -f "$FILE_ENCODING" -t UTF-16 MY_FILE > MY_FILE.utf16_encoding
# Whether we're using UTF-16BE or UTF-16LE
UTF16_ENCODING="$( file --brief --mime-encoding MY_FILE.utf16_encoding )"
# Now we can use MY_FILE.bash_encoding with sed
iconv -f "$UTF16_ENCODING" -t "$BASH_ENCODING" MY_FILE.utf16_encoding > MY_FILE.bash_encoding
# sed!
sed 's/.*/&/' MY_FILE.bash_encoding > MY_FILE_SEDDED.bash_encoding
# now convert MY_FILE_SEDDED.bash_encoding back to its original encoding
iconv -f "$BASH_ENCODING" -t "$FILE_ENCODING" MY_FILE_SEDDED.bash_encoding > MY_FILE_SEDDED
# Now MY_FILE_SEDDED has been processed by sed, and is in the same encoding as MY_FILE

How do I create a MongoDB dump of my database?

use "path" for windows else it gives the error as: positional arguments not allowed

Storage permission error in Marshmallow

if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Log.d(TAG, "Permission granted");
        } else {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    100);
        }

        fab.setOnClickListener(v -> {
            Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.refer_pic);
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/*");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            String path = MediaStore.Images.Media.insertImage(requireActivity().getContentResolver(),
                    b, "Title", null);
            Uri imageUri = Uri.parse(path);
            share.putExtra(Intent.EXTRA_STREAM, imageUri);
            share.putExtra(Intent.EXTRA_TEXT, "Here is text");
            startActivity(Intent.createChooser(share, "Share via"));
        });

Calculating distance between two points, using latitude longitude?

was a lot of great answers provided however I found some performance shortcomings, so let me offer a version with performance in mind. Every constant is precalculated and x,y variables are introduced to avoid calculating the same value twice. Hope it helps

    private static final double r2d = 180.0D / 3.141592653589793D;
    private static final double d2r = 3.141592653589793D / 180.0D;
    private static final double d2km = 111189.57696D * r2d;
    public static double meters(double lt1, double ln1, double lt2, double ln2) {
        double x = lt1 * d2r;
        double y = lt2 * d2r;
        return Math.acos( Math.sin(x) * Math.sin(y) + Math.cos(x) * Math.cos(y) * Math.cos(d2r * (ln1 - ln2))) * d2km;
    }

How to iterate over the files of a certain directory, in Java?

Use java.io.File.listFiles
Or
If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles

Creating for loop until list.length

Yes you can, with range [docs]:

for i in range(1, len(l)):
    # i is an integer, you can access the list element with l[i]

but if you are accessing the list elements anyway, it's more natural to iterate over them directly:

for element in l:
   # element refers to the element in the list, i.e. it is the same as l[i]

If you want to skip the the first element, you can slice the list [tutorial]:

for element in l[1:]:
    # ...

can you do another for loop inside this for loop

Sure you can.

Where are the recorded macros stored in Notepad++?

Go to %appdata%\Notepad++ folder.

The macro definitions are held in shortcuts.xml inside the <Macros> tag. You can copy the whole file, or copy the tag and paste it into shortcuts.xml at the other location.
In the latter case, be sure to use another editor, since N++ overwrites shortcuts.xml on exit.

How to print float to n decimal places including trailing 0s?

I guess this is essentially putting it in a string, but this avoids the rounding error:

import decimal

def display(x):
    digits = 15
    temp = str(decimal.Decimal(str(x) + '0' * digits))
    return temp[:temp.find('.') + digits + 1]

How to set time zone of a java.util.Date?

If you must work with only standard JDK classes you can use this:

/**
 * Converts the given <code>date</code> from the <code>fromTimeZone</code> to the
 * <code>toTimeZone</code>.  Since java.util.Date has does not really store time zome
 * information, this actually converts the date to the date that it would be in the
 * other time zone.
 * @param date
 * @param fromTimeZone
 * @param toTimeZone
 * @return
 */
public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
{
    long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
    long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);

    return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
}

/**
 * Calculates the offset of the <code>timeZone</code> from UTC, factoring in any
 * additional offset due to the time zone being in daylight savings time as of
 * the given <code>date</code>.
 * @param date
 * @param timeZone
 * @return
 */
private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
{
    long timeZoneDSTOffset = 0;
    if(timeZone.inDaylightTime(date))
    {
        timeZoneDSTOffset = timeZone.getDSTSavings();
    }

    return timeZone.getRawOffset() + timeZoneDSTOffset;
}

Credit goes to this post.

What's the purpose of SQL keyword "AS"?

The AS keyword is to give an ALIAS name to your database table or to table column. In your example, both statement are correct but there are circumstance where AS clause is needed (though the AS operator itself is optional), e.g.

SELECT salary * 2 AS "Double salary" FROM employee;

In this case, the Employee table has a salary column and we just want the double of the salary with a new name Double Salary.

Sorry if my explanation is not effective.


Update based on your comment, you're right, my previous statement was invalid. The only reason I can think of is that the AS clause has been in existence for long in the SQL world that it's been incorporated in nowadays RDMS for backward compatibility..

Is there an R function for finding the index of an element in a vector?

A small note about the efficiency of abovementioned methods:

 library(microbenchmark)

  microbenchmark(
    which("Feb" == month.abb)[[1]],
    which(month.abb %in% "Feb"))

  Unit: nanoseconds
   min     lq    mean median     uq  max neval
   891  979.0 1098.00   1031 1135.5 3693   100
   1052 1175.5 1339.74   1235 1390.0 7399  100

So, the best one is

    which("Feb" == month.abb)[[1]]

Align printf output in Java

You can refer to this blog for printing formatted coloured text on console

https://javaforqa.wordpress.com/java-print-coloured-table-on-console/

public class ColourConsoleDemo {
/**
*
* @param args
*
* "\033[0m BLACK" will colour the whole line
*
* "\033[37m WHITE\033[0m" will colour only WHITE.
* For colour while Opening --> "\033[37m" and closing --> "\033[0m"
*
*
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("\033[0m BLACK");
System.out.println("\033[31m RED");
System.out.println("\033[32m GREEN");
System.out.println("\033[33m YELLOW");
System.out.println("\033[34m BLUE");
System.out.println("\033[35m MAGENTA");
System.out.println("\033[36m CYAN");
System.out.println("\033[37m WHITE\033[0m");

//printing the results
String leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";

System.out.format("|---------Test Cases with Steps Summary -------------|%n");
System.out.format("+----------------------+---------+---------+---------+%n");
System.out.format("| Test Cases           |Passed   |Failed   |Skipped  |%n");
System.out.format("+----------------------+---------+---------+---------+%n");

String formattedMessage = "TEST_01".trim();

leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
System.out.print("\033[31m"); // Open print red
System.out.printf(leftAlignFormat, formattedMessage, 2, 1, 0);
System.out.print("\033[0m"); // Close print red
System.out.format("+----------------------+---------+---------+---------+%n");
}

How do I resolve a HTTP 414 "Request URI too long" error?

Under Apache, the limit is a configurable value, LimitRequestLine. Change this value to something larger than its default of 8190 if you want to support a longer request URI. The value is in /etc/apache2/apache2.conf. If not, add a new line (LimitRequestLine 10000) under AccessFileName .htaccess.

However, note that if you're actually running into this limit, you are probably abusing GET to begin with. You should use POST to transmit this sort of data -- especially since you even concede that you're using it to update values. If you check the link above, you'll notice that Apache even says "Under normal conditions, the value should not be changed from the default."

How to create a file in Android?

I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.content.Context;

public class AndroidFileFunctions {

    public static String getFileValue(String fileName, Context context) {
        try {
            StringBuffer outStringBuf = new StringBuffer();
            String inputLine = "";
            /*
             * We have to use the openFileInput()-method the ActivityContext
             * provides. Again for security reasons with openFileInput(...)
             */
            FileInputStream fIn = context.openFileInput(fileName);
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader inBuff = new BufferedReader(isr);
            while ((inputLine = inBuff.readLine()) != null) {
                outStringBuf.append(inputLine);
                outStringBuf.append("\n");
            }
            inBuff.close();
            return outStringBuf.toString();
        } catch (IOException e) {
            return null;
        }
    }

    public static boolean appendFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context, Context.MODE_APPEND);
    }

    public static boolean setFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context,
                Context.MODE_WORLD_READABLE);
    }

    public static boolean writeToFile(String fileName, String value,
            Context context, int writeOrAppendMode) {
        // just make sure it's one of the modes we support
        if (writeOrAppendMode != Context.MODE_WORLD_READABLE
                && writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
                && writeOrAppendMode != Context.MODE_APPEND) {
            return false;
        }
        try {
            /*
             * We have to use the openFileOutput()-method the ActivityContext
             * provides, to protect your file from others and This is done for
             * security-reasons. We chose MODE_WORLD_READABLE, because we have
             * nothing to hide in our file
             */
            FileOutputStream fOut = context.openFileOutput(fileName,
                    writeOrAppendMode);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            // Write the string to the file
            osw.write(value);
            // save and close
            osw.flush();
            osw.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static void deleteFile(String fileName, Context context) {
        context.deleteFile(fileName);
    }
}

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

The compiler is confused by the function signature. You can fix it like this:

let task = URLSession.shared.dataTask(with: request as URLRequest) {

But, note that we don't have to cast "request" as URLRequest in this signature if it was declared earlier as URLRequest instead of NSMutableURLRequest:

var request = URLRequest(url:myUrl!)

This is the automatic casting between NSMutableURLRequest and the new URLRequest that is failing and which forced us to do this casting here.

Why isn't .ico file defined when setting window's icon?

This works for me with Python3 on Linux:

import tkinter as tk

# Create Tk window
root = tk.Tk()

# Add icon from GIF file where my GIF is called 'icon.gif' and
# is in the same directory as this .py file
root.tk.call('wm', 'iconphoto', root._w, tk.PhotoImage(file='icon.gif'))

How to read data From *.CSV file using javascript?

Actually you can use a light-weight library called any-text.

  • install dependencies
npm i -D any-text
  • use custom command to read files
var reader = require('any-text');
 
reader.getText(`path-to-file`).then(function (data) {
  console.log(data);
});

or use async-await :

var reader = require('any-text');
 
const chai = require('chai');
const expect = chai.expect;
 
describe('file reader checks', () => {
  it('check csv file content', async () => {
    expect(
      await reader.getText(`${process.cwd()}/test/files/dummy.csv`)
    ).to.contains('Lorem ipsum');
  });
});

How to enable Ad Hoc Distributed Queries

If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:

EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO

How do I add records to a DataGridView in VB.Net?

The function you're looking for is 'Insert'. It takes as its parameters the index you want to insert at, and an array of values to use for the new row values. Typical usage might include:

myDataGridView.Rows.Insert(4,new object[]{value1,value2,value3});

or something to that effect.

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

Step to follow

1. Open your app.module.ts file.

.

2. Add import { FormsModule } from '@angular/forms';

.

3. Add FormsModule to imports asimports: [ BrowserModule, FormsModule ],

.

Final result will look like this

.....
import { FormsModule } from '@angular/forms';
.....
@NgModule({
.....
  imports: [   
     BrowserModule, FormsModule 
  ],
.....
})

How to search and replace text in a file?

You can do the replacement like this

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
    f2.write(line.replace('old_text', 'new_text'))
f1.close()
f2.close()

Get most recent row for given ID

SELECT * FROM (SELECT * FROM tb1 ORDER BY signin DESC) GROUP BY id;

How to get Month Name from Calendar?

You will get this way also.

  String getMonthForInt(int num) {
        String month = "wrong";
        DateFormatSymbols dfs = new DateFormatSymbols();
        String[] months = dfs.getMonths();
        if (num >= 0 && num <= 11 ) {
            month = months[num];
        }
        return month;
    }

Count cells that contain any text

COUNTIF function will only count cells that contain numbers in your specified range.

COUNTA(range) will count all values in the list of arguments. Text entries and numbers are counted, even when they contain an empty string of length 0.

Example: Function in A7 =COUNTA(A1:A6)

Range:

A1 a

A2 b

A3 banana

A4 42

A5

A6

A7 4 -> result

Google spreadsheet function list contains a list of all available functions for future reference https://support.google.com/drive/table/25273?hl=en.

How to redirect to Login page when Session is expired in Java web application?

How to redirect to Login page when Session is expired in Java web application?

This is a wrong question. You should differentiate between the cases "User is not logged in" and "Session is expired". You basically want to redirect to login page when user is not logged in. Not when session is expired. The currently accepted answer only checks HttpSession#isNew(). But this obviously fails when the user has sent more than one request in the same session when the session is implicitly created by the JSP or what not. E.g. when just pressing F5 on the login page.

As said, you should instead be checking if the user is logged in or not. Given the fact that you're asking this kind of question while standard authentication frameworks like j_security_check, Shiro, Spring Security, etc already transparently manage this (and thus there would be no need to ask this kind of question on them), that can only mean that you're using a homegrown authentication approach.

Assuming that you're storing the logged-in user in the session in some login servlet like below:

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @EJB
    private UserService userService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.find(username, password);

        if (user != null) {
            request.getSession().setAttribute("user", user);
            response.sendRedirect(request.getContextPath() + "/home");
        } else {
            request.setAttribute("error", "Unknown login, try again");
            doGet(request, response);
        }
    }

}

Then you can check for that in a login filter like below:

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {    
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        String loginURI = request.getContextPath() + "/login";

        boolean loggedIn = session != null && session.getAttribute("user") != null;
        boolean loginRequest = request.getRequestURI().equals(loginURI);

        if (loggedIn || loginRequest) {
            chain.doFilter(request, response);
        } else {
            response.sendRedirect(loginURI);
        }
    }

    // ...
}

No need to fiddle around with brittle HttpSession#isNew() checks.

Subtract days, months, years from a date in JavaScript

Use the moment.js library for time and date management.

import moment = require('moment');

const now = moment();

now.subtract(7, 'seconds'); // 7 seconds ago
now.subtract(7, 'days');    // 7 days and 7 seconds ago
now.subtract(7, 'months');  // 7 months, 7 days and 7 seconds ago
now.subtract(7, 'years');   // 7 years, 7 months, 7 days and 7 seconds ago
// because `now` has been mutated, it no longer represents the current time

jQuery add required to input fields

Using .attr method

.attr(attribute,value); // syntax

.attr("required", true);
// required="required"

.attr("required", false);
// 

Using .prop

.prop(property,value) // syntax

.prop("required", true);
// required=""

.prop("required", false);
//

Read more from here

https://stackoverflow.com/a/5876747/5413283

How to input a regex in string.replace?

This tested snippet should do it:

import re
line = re.sub(r"</?\[\d+>", "", line)

Edit: Here's a commented version explaining how it works:

line = re.sub(r"""
  (?x) # Use free-spacing mode.
  <    # Match a literal '<'
  /?   # Optionally match a '/'
  \[   # Match a literal '['
  \d+  # Match one or more digits
  >    # Match a literal '>'
  """, "", line)

Regexes are fun! But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special: "metacharacters" which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: www.regular-expressions.info. The time you spend there will pay for itself many times over. Happy regexing!

the easiest way to convert matrix to one row vector

You can use the function RESHAPE:

B = reshape(A.',1,[]);

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

The official documentation of Dockerfile best practices does a great job explaining the differences. Dockerfile best practices

CMD:

The CMD instruction should be used to run the software contained by your image, along with any arguments. CMD should almost always be used in the form of CMD ["executable", "param1", "param2"…]. Thus, if the image is for a service, such as Apache and Rails, you would run something like CMD ["apache2","-DFOREGROUND"]. Indeed, this form of the instruction is recommended for any service-based image.

ENTRYPOINT:

The best use for ENTRYPOINT is to set the image’s main command, allowing that image to be run as though it was that command (and then use CMD as the default flags).

How to check if pytorch is using the GPU?

Create a tensor on the GPU as follows:

$ python
>>> import torch
>>> print(torch.rand(3,3).cuda()) 

Do not quit, open another terminal and check if the python process is using the GPU using:

$ nvidia-smi

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

How to define constants in ReactJS

Warning: this is an experimental feature that could dramatically change or even cease to exist in future releases

You can use ES7 statics:

npm install babel-preset-stage-0

And then add "stage-0" to .babelrc presets:

{
    "presets": ["es2015", "react", "stage-0"]
}

Afterwards, you go

class Component extends React.Component {
    static foo = 'bar';
    static baz = {a: 1, b: 2}
}

And then you use them like this:

Component.foo

Slide div left/right using jQuery

$('#hello').hide('slide', {direction: 'left'}, 1000); requires the jQuery-ui library. See http://www.jqueryui.com

Move textfield when keyboard appears swift

For anyone not using storyboards to set the layout constraint. This is a pure programmatic way to get it working on Swift 5:

  1. Define an empty constraint in your viewController. In this case, I am building a chat app that has a UIView containing text view at the very bottom of the screen.
var discussionsMessageBoxBottomAnchor: NSLayoutConstraint = NSLayoutConstraint()
  1. In viewDidLoad add the constraints for the bottom-most view. In this case discussionsMessageBox. Also, add the listener for keyboard events.

For correctly initializing the constraint, you need to first add the subview and then define the constraint.

NotificationCenter.default.addObserver(self,
                                       selector: #selector(self.keyboardNotification(notification:)),
                                       name: NSNotification.Name.UIKeyboardWillChangeFrame,
                                       object: nil)

view.addSubview(discussionsMessageBox)

if #available(iOS 11.0, *) {
    discussionsMessageBoxBottomAnchor = discussionsMessageBox.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0)
} else {
    // Fallback on earlier versions
    discussionsMessageBoxBottomAnchor = discussionsMessageBox.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
}

NSLayoutConstraint.activate([ discussionsMessageBoxBottomAnchor ])

  1. Define deinit.
deinit {
        NotificationCenter.default.removeObserver(self)
    }
  1. Next add the code that @JosephLord defined, with one correction to fix offset math.
extension DiscussionsViewController {
    @objc func keyboardNotification(notification: NSNotification) {
        guard let userInfo = notification.userInfo else { return }
        
        let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        let endFrameY = endFrame?.origin.y ?? 0
        let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
        let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
        let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
        let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
        
        if endFrameY >= UIScreen.main.bounds.size.height {
            self.discussionsMessageBoxBottomAnchor.constant = 0.0
        } else {
            //Changed line
            self.discussionsMessageBoxBottomAnchor.constant = -1 * (endFrame?.size.height ?? 0.0)
        }
        
        UIView.animate(
            withDuration: duration,
            delay: TimeInterval(0),
            options: animationCurve,
            animations: { self.view.layoutIfNeeded() },
            completion: nil)
    }
}

How to get relative path from absolute path

Play with something like:

private String GetRelativePath(Int32 level, String directory, out String errorMessage) {
        if (level < 0 || level > 5) {
            errorMessage = "Find some more smart input data";
            return String.Empty;
        }
        // ==========================
        while (level != 0) {
            directory = Path.GetDirectoryName(directory);
            level -= 1;
        }
        // ==========================
        errorMessage = String.Empty;
        return directory;
    }

And test it

[Test]
    public void RelativeDirectoryPathTest() {
        var relativePath =
            GetRelativePath(3, AppDomain.CurrentDomain.BaseDirectory, out var errorMessage);
        Console.WriteLine(relativePath);
        if (String.IsNullOrEmpty(errorMessage) == false) {
            Console.WriteLine(errorMessage);
            Assert.Fail("Can not find relative path");
        }
    }

Getting Textarea Value with jQuery

It can be done at easily like as:

     <a id="send-thoughts" href="">Click</a>
     <textarea id="message"></textarea>

        $("a#send-thoughts").click(function() {
            var thought = $("#message").val();
            alert(thought);
        });

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

How to check Oracle database for long running queries

Step 1:Execute the query

column username format 'a10'
column osuser format 'a10'
column module format 'a16'
column program_name format 'a20'
column program format 'a20'
column machine format 'a20'
column action format 'a20'
column sid format '9999'
column serial# format '99999'
column spid format '99999'
set linesize 200
set pagesize 30
select
a.sid,a.serial#,a.username,a.osuser,c.start_time,
b.spid,a.status,a.machine,
a.action,a.module,a.program
from
v$session a, v$process b, v$transaction c,
v$sqlarea s
Where
a.paddr = b.addr
and a.saddr = c.ses_addr
and a.sql_address = s.address (+)
and to_date(c.start_time,'mm/dd/yy hh24:mi:ss') <= sysdate - (15/1440) -- running for 15 minutes
order by c.start_time
/   

Step 2: desc v$session

Step 3:select sid, serial#,SQL_ADDRESS, status,PREV_SQL_ADDR from v$session where sid='xxxx' //(enter the sid value)

Step 4: select sql_text from v$sqltext where address='XXXXXXXX';

Step 5: select piece, sql_text from v$sqltext where address='XXXXXX' order by piece;

Having issues with a MySQL Join that needs to meet multiple conditions

SELECT 
    u . *
FROM
    room u
        JOIN
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

How do I send a POST request as a JSON?

for python 3.4.2 I found the following will work:

import urllib.request
import json      

body = {'ids': [12, 14, 50]}  
myurl = "http://www.testmycode.com"

req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8')   # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)

Python logging: use milliseconds in time format

tl;dr for folks looking here for an ISO formatted date:

instead of using something like '%Y-%m-%d %H:%M:%S.%03d%z', create your own class as @unutbu indicated. Here's one for iso date format:

import logging
from time import gmtime, strftime

class ISOFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        t = strftime("%Y-%m-%dT%H:%M:%S", gmtime(record.created))
        z = strftime("%z",gmtime(record.created))
        s = "%s.%03d%s" % (t, record.msecs,z)        
        return s

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

console = logging.StreamHandler()
logger.addHandler(console)

formatter = ISOFormatter(fmt='%(asctime)s - %(module)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)

logger.debug('Jackdaws love my big sphinx of quartz.')
#2020-10-23T17:25:48.310-0800 - <stdin> - DEBUG - Jackdaws love my big sphinx of quartz.

Append a single character to a string or char array in java?

1. String otherString = "helen" + character;

2. otherString +=  character;

Best way to get value from Collection by index

I agree with Matthew Flaschen's answer and just wanted to show examples of the options for the case you cannot switch to List (because a library returns you a Collection):

List list = new ArrayList(theCollection);
list.get(5);

Or

Object[] list2 = theCollection.toArray();
doSomethingWith(list[2]);

If you know what generics is I can provide samples for that too.

Edit: It's another question what the intent and semantics of the original collection is.

How to Get a Sublist in C#

Reverse the items in a sub-list

int[] l = {0, 1, 2, 3, 4, 5, 6};
var res = new List<int>();
res.AddRange(l.Where((n, i) => i < 2));
res.AddRange(l.Where((n, i) => i >= 2 && i <= 4).Reverse());
res.AddRange(l.Where((n, i) => i > 4));

Gives 0,1,4,3,2,5,6

how to "execute" make file

You don't tend to execute the make file itself, rather you execute make, giving it the make file as an argument:

make -f pax.mk

If your make file is actually one of the standard names (like makefile or Makefile), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make man page to see which takes precedence).

Uninstall all installed gems, in OSX?

gem list --no-version | grep -v -e 'psych' -e 'rdoc' -e 'openssl' -e 'json' -e 'io-console' -e 'bigdecimal' | xargs sudo gem uninstall -ax

grep here is excluding default gems. All other gems will be uninstalled. You can also precede it with sudo in case you get permission issues.

Format a JavaScript string using placeholders and an object of substitutions?

As a quick example:

var name = 'jack';
var age = 40;
console.log('%s is %d yrs old',name,age);

The output is:

jack is 40 yrs old

Bluetooth pairing without user confirmation

If you are asking if you can pair two devices without the user EVER approving the pairing, no it cannot be done, it is a security feature. If you are paired over Bluetooth there is no need to exchange data over NFC, just exchange data over the Bluetooth link.

I don't think you can circumvent Bluetooth security by passing an authentication packet over NFC, but I could be wrong.

How to clear cache of Eclipse Indigo

If you are asking about cache where eclipse stores your project and workspace information right click on your project(s) and choose refresh. Then go to project in the menu on top of the window and click "clean".

This typically does what you need.

If it does not try to remove project from the workspace (just press "delete" on the project and then say that you DO NOT want to remove the sources). Then open project again.

If this does not work too, do the same with the workspace. If this still does not work, perform fresh checkout of your project from source control and create new workspace.

Well, this should work.

CSS3 Transition not working

HTML:

<div class="foo">
    /* whatever is required */
</div>

CSS:

.foo {
    top: 0;
    transition: top ease 0.5s;
}

.foo:hover{
    top: -10px;
}

This is just a basic transition to ease the div tag up by 10px when it is hovered on. The transition property's values can be edited along with the class.hover properties to determine how the transition works.

How to ignore HTML element from tabindex?

You can use tabindex="-1".

The W3C HTML5 specification supports negative tabindex values:

If the value is a negative integer
The user agent must set the element's tabindex focus flag, but should not allow the element to be reached using sequential focus navigation.


Watch out though that this is a HTML5 feature and might not work with old browsers.
To be W3C HTML 4.01 standard (from 1999) compliant, tabindex would need to be positive.


Sample usage below in pure HTML.

_x000D_
_x000D_
<input />_x000D_
<input tabindex="-1" placeholder="NoTabIndex" />_x000D_
<input />
_x000D_
_x000D_
_x000D_

Java - Abstract class to contain variables?

I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.

public abstract class ExternalScript extends Script {

    private String source;

    public void setSource(String file) {
        source = file;
    }

    public String getSource() {
        return source;
    }
}

Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:

  • If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier.
  • If your getter/setter methods aren't getting and setting, then describe them as something else.

Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.

Can we have multiple "WITH AS" in single sql - Oracle SQL

the correct syntax is -

with t1
as
(select * from tab1
where conditions...
),
t2
as
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
)
select * from t1, t2
where t1.col1=t2.col2;

Is there a Google Keep API?

No there isn't. If you watch the http traffic and dump the page source you can see that there is an API below the covers, but it's not published nor available for 3rd party apps.

Check this link: https://developers.google.com/gsuite/products for updates.

However, there is an unofficial Python API under active development: https://github.com/kiwiz/gkeepapi

How do I check if I'm running on Windows in Python?

in sys too:

import sys
# its win32, maybe there is win64 too?
is_windows = sys.platform.startswith('win')

Multiple conditions in ngClass - Angular 4

There are multiple ways to write same logic. As it mentioned earlier, you can use object notation or simply expression. However, I think you should not that much logic in HTML. Hard to test and find issue. You can use a getter function to assign the class.

For Instance;

public getCustomCss() {
    //Logic here;
    if(this.x == this.y){
        return 'class1'
    }
    if(this.x == this.z){
        return 'class2'
    }
}
<!-- HTML -->
<div [ngClass]="getCustomCss()"> Some prop</div>

//OR

get customCss() {
    //Logic here;
    if(this.x == this.y){
        return 'class1'
    }
    if(this.x == this.z){
        return 'class2'
    }
}
<!-- HTML -->
<div [ngClass]="customCss"> Some prop</div>

Unit test naming best practices

Kent Beck suggests:

  • One test fixture per 'unit' (class of your program). Test fixtures are classes themselves. The test fixture name should be:

    [name of your 'unit']Tests
    
  • Test cases (the test fixture methods) have names like:

    test[feature being tested]
    

For example, having the following class:

class Person {
    int calculateAge() { ... }

    // other methods and properties
}

A test fixture would be:

class PersonTests {

    testAgeCalculationWithNoBirthDate() { ... }

    // or

    testCalculateAge() { ... }
}

Can I delete data from the iOS DeviceSupport directory?

More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:

  1. Delete this folder after every few days interval. Most of the time, it occupy huge space!

      ~/Library/Developer/Xcode/DerivedData
    
  2. All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.

      ~/Library/Developer/Xcode/Archives
    
  3. iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.

    ~/Library/Developer/Xcode/iOS DeviceSupport
    
  4. Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.

      ~/Library/Developer/CoreSimulator 
    

(Here's a handy shell command for step 5: xcrun simctl delete unavailable )

  1. Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!

    ~/Library/Caches/com.apple.dt.Xcode
    
  2. Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.

     ~/Library/Application Support/MobileSync/Backup
    

Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac

I got back about 40GB!

Getting Chrome to accept self-signed localhost certificate

Here is a solution using only Java 8 keytool.exe instead of openssl:

@echo off
set PWD=changeit
set DNSNAME=%COMPUTERNAME%

echo create ca key
keytool -genkeypair -alias ca -keystore test.jks -keyalg RSA -validity 3650 -ext bc:critical=ca:true -dname "CN=CA" -storepass:env PWD -keypass:env PWD
echo generate cert request for ca signing
keytool -certreq -keystore test.jks -storepass:env PWD -alias ca -file ca.csr -ext bc:critical=ca:true
echo generate signed cert
keytool -gencert -keystore test.jks -storepass:env PWD -alias ca -infile ca.csr -outfile ca.cer -validity 3650 -ext bc:critical=ca:true
echo CA created. Import ca.cer in windows and firefox' certificate store as "Trusted CA".
pause

echo create server cert key for %DNSNAME%
keytool -genkeypair -alias leaf -keystore test.jks -keyalg RSA -validity 3650 -ext bc=ca:false -ext san=dns:%DNSNAME%,dns:localhost,ip:127.0.0.1 -dname "CN=Leaf" -storepass:env PWD -keypass:env PWD
echo generate cert request
keytool -certreq -keystore test.jks -storepass:env PWD -alias leaf -file leaf.csr -ext bc=ca:false -ext san=dns:%DNSNAME%,dns:localhost,ip:127.0.0.1
echo generate signed cert
keytool -gencert -keystore test.jks -storepass:env PWD -alias ca -infile leaf.csr -outfile leaf.cer -validity 3650 -ext bc=ca:false -ext san=dns:%DNSNAME%,dns:localhost,ip:127.0.0.1

rem see content
rem keytool -printcert -file leaf.cer -storepass:env PWD 

echo install in orig keystore
keytool -importcert -keystore test.jks -storepass:env PWD -file leaf.cer -alias leaf

echo content of test.jks:
keytool -list -v -storepass:env PWD -keystore test.jks
pause

You could also use pipes instead of files, but with the files, you can check the intermediate results if something goes wrong. SSL tested with IE11, Edge, FF54, Chrome60 on windows and Chrome60 on Android.

Please change the default password before using the script.

How to highlight a selected row in ngRepeat?

Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
    ...
</ul>

Plunker

Getting the name of a variable as a string

I wrote the package sorcery to do this kind of magic robustly. You can write:

from sorcery import dict_of

columns = dict_of(n_jobs, users, queues, priorities)

and pass that to the dataframe constructor. It's equivalent to:

columns = dict(n_jobs=n_jobs, users=users, queues=queues, priorities=priorities)

JTable - Selected Row click event

 private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {                                     
     JTable source = (JTable)evt.getSource();
            int row = source.rowAtPoint( evt.getPoint() );
            int column = source.columnAtPoint( evt.getPoint() );
            String s=source.getModel().getValueAt(row, column)+"";

            JOptionPane.showMessageDialog(null, s);


} 

if you want click cell or row in jtable use this way

What is the role of "Flatten" in Keras?

If you read the Keras documentation entry for Dense, you will see that this call:

Dense(16, input_shape=(5,3))

would result in a Dense network with 3 inputs and 16 outputs which would be applied independently for each of 5 steps. So, if D(x) transforms 3 dimensional vector to 16-d vector, what you'll get as output from your layer would be a sequence of vectors: [D(x[0,:]), D(x[1,:]),..., D(x[4,:])] with shape (5, 16). In order to have the behavior you specify you may first Flatten your input to a 15-d vector and then apply Dense:

model = Sequential()
model.add(Flatten(input_shape=(3, 2)))
model.add(Dense(16))
model.add(Activation('relu'))
model.add(Dense(4))
model.compile(loss='mean_squared_error', optimizer='SGD')

EDIT: As some people struggled to understand - here you have an explaining image:

enter image description here

Spring REST Service: how to configure to remove null objects in json response

I've found a solution through configuring the Spring container, but it's still not exactly what I wanted.

I rolled back to Spring 3.0.5, removed and in it's place I changed my config file to:

    <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>
        </list>
    </property>
</bean>


<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="jacksonSerializationConfig" />
    <property name="targetMethod" value="setSerializationInclusion" />
    <property name="arguments">
        <list>
            <value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
        </list>
    </property>
</bean>

This is of course similar to responses given in other questions e.g.

configuring the jacksonObjectMapper not working in spring mvc 3

The important thing to note is that mvc:annotation-driven and AnnotationMethodHandlerAdapter cannot be used in the same context.

I'm still unable to get it working with Spring 3.1 and mvc:annotation-driven though. A solution that uses mvc:annotation-driven and all the benefits that accompany it would be far better I think. If anyone could show me how to do this, that would be great.

ImageButton in Android

I think you already solved this problem, and as other answers suggested

android:background="@drawable/eye"

is available. But I prefer

android:src="@drawable/eye"
android:background="00000000" // transparent

and it works well too.(of course former code will set image as a background and the other will set image as a image) But according to your selected answer, I guess you meant 9-patch.

symbol(s) not found for architecture i386

I fixed a similar error on my project by changing the Build Settings > Architectures for ALL of my targets.

The problem: When I upgraded from Xcode 4.4 to Xcode 4.5, my project still compiled fine on the simulator but did not compile on devices. On devices it threw the error "symbol(s) not found for architecture armv7s," along with the misleading "Apple Mach-O Linker Error" and "clang: error: linker command failed with exit code 1 (use -v to see invocation)."

The cause (in my case): My project had multiple targets, and even though the Build Settings > Architectures for the main target was set to include armv7s architecture, the main target depended on another target (listed under Build Phases > Dependencies), and I hadn't thought to reset the Build Settings > Architectures for that other target, and I had to change that to include armv7s. I suppose the simulator and device run on different architectures, and that's why the simulator was OK while the device wasn't.

Remove all special characters from a string in R?

You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all from the stringr package, though gsub from base R works just as well.

The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.

x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")

(The base R equivalent is gsub("[[:punct:]]", " ", x).)

An alternative is to swap out all non-alphanumeric characters.

str_replace_all(x, "[^[:alnum:]]", " ")

Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.

Apache Spark: map vs mapPartitions?

Imp. TIP :

Whenever you have heavyweight initialization that should be done once for many RDD elements rather than once per RDD element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), use mapPartitions() instead of map(). mapPartitions() provides for the initialization to be done once per worker task/thread/partition instead of once per RDD data element for example : see below.

val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = partition.map(record => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB 

  connection.close() // close dbconnection here
  newPartition.iterator // create a new iterator
})

Q2. does flatMap behave like map or like mapPartitions?

Yes. please see example 2 of flatmap.. its self explanatory.

Q1. What's the difference between an RDD's map and mapPartitions

map works the function being utilized at a per element level while mapPartitions exercises the function at the partition level.

Example Scenario : if we have 100K elements in a particular RDD partition then we will fire off the function being used by the mapping transformation 100K times when we use map.

Conversely, if we use mapPartitions then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.

There will be performance gain since map works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions).

map

Applies a transformation function on each item of the RDD and returns the result as a new RDD.

Listing Variants

def map[U: ClassTag](f: T => U): RDD[U]

Example :

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
 val b = a.map(_.length)
 val c = a.zip(b)
 c.collect
 res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8)) 

mapPartitions

This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.

preservesPartitioning indicates whether the input function preserves the partitioner, which should be false unless this is a pair RDD and the input function doesn't modify the keys.

Listing Variants

def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]

Example 1

val a = sc.parallelize(1 to 9, 3)
 def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
   var res = List[(T, T)]()
   var pre = iter.next
   while (iter.hasNext)
   {
     val cur = iter.next;
     res .::= (pre, cur)
     pre = cur;
   }
   res.iterator
 }
 a.mapPartitions(myfunc).collect
 res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8)) 

Example 2

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
 def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
   var res = List[Int]()
   while (iter.hasNext) {
     val cur = iter.next;
     res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
   }
   res.iterator
 }
 x.mapPartitions(myfunc).collect
 // some of the number are not outputted at all. This is because the random number generated for it is zero.
 res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10) 

The above program can also be written using flatMap as follows.

Example 2 using flatmap

val x  = sc.parallelize(1 to 10, 3)
 x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect

 res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10) 

Conclusion :

mapPartitions transformation is faster than map since it calls your function once/partition, not once/element..

Further reading : foreach Vs foreachPartitions When to use What?

SSIS expression: convert date to string

If, like me, you are trying to use GETDATE() within an expression and have the seemingly unreasonable requirement (SSIS/SSDT seems very much a work in progress to me, and not a polished offering) of wanting that date to get inserted into SQL Server as a valid date (type = datetime), then I found this expression to work:

@[User::someVar] = (DT_WSTR,4)YEAR(GETDATE()) + "-"  + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-"  + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " " + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)

I found this code snippet HERE

A button to start php script, how?

What exactly do you mean by "starts my php script"? What kind of PHP script? One to generate an HTML response for an end-user, or one that simply performs some kind of data processing task? If you are familiar with using the tag and how it interacts with PHP, then you should only need to POST to your target PHP script using an button of type "submit". If you are not familiar with forms, take a look here.

Changing directory in Google colab (breaking out of the python interpreter)

!pwd
import os
os.chdir('/content/drive/My Drive/Colab Notebooks/Data')
!pwd

view this answer for detailed explaination https://stackoverflow.com/a/61636734/11535267

Switch android x86 screen resolution

Based on my experience, it's enough to use the following additional boot options:

UVESA_MODE=320x480 DPI=160

No need to add vga definition. Watch out for DPI value! As bigger one makes your icons bigger.

To add the previous boot options, go to debug mode (during grub menu selection)

mount -o remount,rw /mnt
vi /mnt/grub/menu.lst

Now edit on this line:

kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=eeepc acpi_sleep=s3_bios,s3_mode SRC=/android-2.3-RC1 SDCARD=/data/sdcard.img UVESA_MODE=320x480 DPI=160

Reboot

How do I calculate tables size in Oracle

For sub partitioned tables and indexes we can use the following query



    SELECT owner, table_name, ROUND(sum(bytes)/1024/1024/1024, 2) GB
    FROM
    (SELECT segment_name table_name, owner, bytes
     FROM dba_segments
     WHERE segment_type IN ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')
     UNION ALL
     SELECT i.table_name, i.owner, s.bytes
     FROM dba_indexes i, dba_segments s
     WHERE s.segment_name = i.index_name
     AND   s.owner = i.owner
     AND   s.segment_type IN ('INDEX', 'INDEX PARTITION', 'INDEX SUBPARTITION')
     UNION ALL
     SELECT l.table_name, l.owner, s.bytes
     FROM dba_lobs l, dba_segments s
     WHERE s.segment_name = l.segment_name
     AND   s.owner = l.owner
     AND   s.segment_type = 'LOBSEGMENT'
     UNION ALL
     SELECT l.table_name, l.owner, s.bytes
     FROM dba_lobs l, dba_segments s
     WHERE s.segment_name = l.index_name
     AND   s.owner = l.owner
     AND   s.segment_type = 'LOBINDEX')
    WHERE owner in UPPER('&owner')
    GROUP BY table_name, owner
    HAVING SUM(bytes)/1024/1024 > 10  /* Ignore really small tables */
    ORDER BY SUM(bytes) DESC
    ;

dispatch_after - GCD in Swift?

Swift 3.0 version

Following closure function execute some task after delay on main thread.

func performAfterDelay(delay : Double, onCompletion: @escaping() -> Void){

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: {
       onCompletion()
    })
}

Call this function like:

performAfterDelay(delay: 4.0) {
  print("test")
}

Spring cron expression for every after 30 minutes

If someone is using @Sceduled this might work for you.

@Scheduled(cron = "${name-of-the-cron:0 0/30 * * * ?}")

This worked for me.

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

What coobird and Gerald said.

Additionally, JPEG is the file format name. JPG is commonly used abbreviated file extension for this format, as you needed to have a 3-letter file extension for earlier Windows systems. Likewise with TIFF and TIF.

Web browsers at the moment only display JPEG, PNG and GIF files - so those are the ones that can be shown on web pages.

CSS Vertical align does not work with float

Vertical alignment doesn't work with floated elements, indeed. That's because float lifts the element from the normal flow of the document. You might want to use other vertical aligning techniques, like the ones based on transform, display: table, absolute positioning, line-height, js (last resort maybe) or even the plain old html table (maybe the first choice if the content is actually tabular). You'll find that there's a heated debate on this issue.

However, this is how you can vertically align YOUR 3 divs:

.wrap{
    width: 500px;
    overflow:hidden;    
    background: pink;
}

.left {
    width: 150px;       
    margin-right: 10px;
    background: yellow;  
    display:inline-block;
    vertical-align: middle; 
}

.left2 {
    width: 150px;    
    margin-right: 10px;
    background: aqua; 
    display:inline-block;
    vertical-align: middle; 
}

.right{
    width: 150px;
    background: orange;
    display:inline-block;
    vertical-align: middle; 
}

Not sure why you needed both fixed width, display: inline-block and floating.

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

With the release of Java 5, the product version was made distinct from the developer version as described here

Sorting by date & time in descending order?

SELECT id, name, form_id, DATE(updated_at) as date
FROM wp_frm_items
WHERE user_id = 11 && form_id=9
ORDER BY date ASC

"DESC" stands for descending but you need ascending order ("ASC").

Facebook user url by id

UPDATE 2: This information is no more given by facebook. There is an official announcement for the behavior change (https://developers.facebook.com/blog/post/2018/04/19/facebook-login-changes-address-abuse/) but none for its alternative.

Yes, Just use this link and append your ID to the id parameter:

https://facebook.com/profile.php?id=<UID>

So for example:

https://facebook.com/profile.php?id=4

Will redirect you automatically to https://www.facebook.com/zuck Which is Mark Zuckerberg's profile.

If you want to do this for all your ids, then you can do it using a loop.

If you'd like, I can provide you with a snippet.

UPDATE: Alternatively, You can also do this:

https://facebook.com/<UID>

So that would be: https://facebook.com/4 which would automatically redirect to Zuck!

Save base64 string as PDF at client side with JavaScript

_x000D_
_x000D_
dataURItoBlob(dataURI) {_x000D_
      const byteString = window.atob(dataURI);_x000D_
      const arrayBuffer = new ArrayBuffer(byteString.length);_x000D_
      const int8Array = new Uint8Array(arrayBuffer);_x000D_
      for (let i = 0; i < byteString.length; i++) {_x000D_
        int8Array[i] = byteString.charCodeAt(i);_x000D_
      }_x000D_
      const blob = new Blob([int8Array], { type: 'application/pdf'});_x000D_
      return blob;_x000D_
    }_x000D_
_x000D_
// data should be your response data in base64 format_x000D_
_x000D_
const blob = this.dataURItoBlob(data);_x000D_
const url = URL.createObjectURL(blob);_x000D_
_x000D_
// to open the PDF in a new window_x000D_
window.open(url, '_blank');
_x000D_
_x000D_
_x000D_

WSDL validator?

If you would to validate WSDL programatically then you use WSDL Validator out of eclipse. http://wiki.eclipse.org/Using_the_WSDL_Validator_Outside_of_Eclipse should help or try this tool Graphical WSDL 1.1/2.0 editor.

nodejs npm global config missing on windows

Even though we have the .NPMRC can be in 3 locations, Please NOTE THAT - the file under the Per-User NPM config location take precedence over the Global & Built-in configurations.

  1. Global NPM config => C:\Users\%username%\AppData\Roaming\npm\etc\npmrc
  2. Per-user NPM config => C:\Users\%username%.npmrc
  3. Built-in NPM config => C:\Program Files\nodejs\node_modules\npm\npmrc

To find out which file is getting updated, try setting the proxy using the following command npm config set https-proxy https://username:[email protected]:6050

After that open the .npmrc files to see which file get updated.

Java Array, Finding Duplicates

This program will print all duplicates value from array.

public static void main(String[] args) {

    int[] array = new int[] { -1, 3, 4, 4,4,3, 9,-1, 5,5,5, 5 };
    
    Arrays.sort(array);

 boolean isMatched = false;
 int lstMatch =-1;
      for(int i = 0; i < array.length; i++) {  
          try {
                if(array[i] == array[i+1]) { 
                    isMatched = true;
                    lstMatch = array[i+1]; 
                }
                else if(isMatched) {
                    System.out.println(lstMatch);
                    isMatched = false;
                    lstMatch = -1;
                }
          }catch(Exception ex) {
              //TODO NA
          }

      }
      if(isMatched) {
          System.out.println(lstMatch);
      }

}

}

Will iOS launch my app into the background if it was force-quit by the user?

This might help you

In most cases, the system does not relaunch apps after they are force quit by the user. One exception is location apps, which in iOS 8 and later are relaunched after being force quit by the user. In other cases, though, the user must launch the app explicitly or reboot the device before the app can be launched automatically into the background by the system. When password protection is enabled on the device, the system does not launch an app in the background before the user first unlocks the device.

Source: https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html