Programs & Examples On #Magit

Magit is an Emacs mode for interacting with Git.

Remove empty array elements

With these types of things, it's much better to be explicit about what you want and do not want.

It will help the next guy to not get caught by surprise at the behaviour of array_filter() without a callback. For example, I ended up on this question because I forgot if array_filter() removes NULL or not. I wasted time when I could have just used the solution below and had my answer.

Also, the logic is language angnostic in the sense that the code can be copied into another language without having to under stand the behaviour of a php function like array_filter when no callback is passed.

In my solution, it is clear at glance as to what is happening. Remove a conditional to keep something or add a new condition to filter additional values.

Disregard the actual use of array_filter() since I am just passing it a custom callback - you could go ahead and extract that out to its own function if you wanted. I am just using it as sugar for a foreach loop.

<?php

$xs = [0, 1, 2, 3, "0", "", false, null];

$xs = array_filter($xs, function($x) {
    if ($x === null) { return false; }
    if ($x === false) { return false; }
    if ($x === "") { return false; }
    if ($x === "0") { return false; }
    return true;
});

$xs = array_values($xs); // reindex array   

echo "<pre>";
var_export($xs);

Another benefit of this approach is that you can break apart the filtering predicates into an abstract function that filters a single value per array and build up to a composable solution.

See this example and the inline comments for the output.

<?php

/**
 * @param string $valueToFilter
 *
 * @return \Closure A function that expects a 1d array and returns an array
 *                  filtered of values matching $valueToFilter.
 */
function filterValue($valueToFilter)
{
    return function($xs) use ($valueToFilter) {
        return array_filter($xs, function($x) use ($valueToFilter) {
            return $x !== $valueToFilter;
        });
    };
}

// partially applied functions that each expect a 1d array of values
$filterNull = filterValue(null);
$filterFalse = filterValue(false);
$filterZeroString = filterValue("0");
$filterEmptyString = filterValue("");

$xs = [0, 1, 2, 3, null, false, "0", ""];

$xs = $filterNull($xs);        //=> [0, 1, 2, 3, false, "0", ""]
$xs = $filterFalse($xs);       //=> [0, 1, 2, 3, "0", ""]
$xs = $filterZeroString($xs);  //=> [0, 1, 2, 3, ""]
$xs = $filterEmptyString($xs); //=> [0, 1, 2, 3]

echo "<pre>";
var_export($xs); //=> [0, 1, 2, 3]

Now you can dynamically create a function called filterer() using pipe() that will apply these partially applied functions for you.

<?php

/**
 * Supply between 1..n functions each with an arity of 1 (that is, accepts
 * one and only one argument). Versions prior to php 5.6 do not have the
 * variadic operator `...` and as such require the use of `func_get_args()` to
 * obtain the comma-delimited list of expressions provided via the argument
 * list on function call.
 *
 * Example - Call the function `pipe()` like:
 *
 *   pipe ($addOne, $multiplyByTwo);
 *
 * @return closure
 */
function pipe()
{
    $functions = func_get_args(); // an array of callable functions [$addOne, $multiplyByTwo]
    return function ($initialAccumulator) use ($functions) { // return a function with an arity of 1
        return array_reduce( // chain the supplied `$arg` value through each function in the list of functions
            $functions, // an array of functions to reduce over the supplied `$arg` value
            function ($accumulator, $currFn) { // the reducer (a reducing function)
                return $currFn($accumulator);
            },
            $initialAccumulator
        );
    };
}

/**
 * @param string $valueToFilter
 *
 * @return \Closure A function that expects a 1d array and returns an array
 *                  filtered of values matching $valueToFilter.
 */
function filterValue($valueToFilter)
{
    return function($xs) use ($valueToFilter) {
        return array_filter($xs, function($x) use ($valueToFilter) {
            return $x !== $valueToFilter;
        });
    };
}

$filterer = pipe(
    filterValue(null),
    filterValue(false),
    filterValue("0"),
    filterValue("")
);

$xs = [0, 1, 2, 3, null, false, "0", ""];
$xs = $filterer($xs);

echo "<pre>";
var_export($xs); //=> [0, 1, 2, 3]

Transpose list of lists

Methods 1 and 2 work in Python 2 or 3, and they work on ragged, rectangular 2D lists. That means the inner lists do not need to have the same lengths as each other (ragged) or as the outer lists (rectangular). The other methods, well, it's complicated.

the setup

import itertools
import six

list_list = [[1,2,3], [4,5,6, 6.1, 6.2, 6.3], [7,8,9]]

method 1 — map(), zip_longest()

>>> list(map(list, six.moves.zip_longest(*list_list, fillvalue='-')))
[[1, 4, 7], [2, 5, 8], [3, 6, 9], ['-', 6.1, '-'], ['-', 6.2, '-'], ['-', 6.3, '-']]

six.moves.zip_longest() becomes

The default fillvalue is None. Thanks to @jena's answer, where map() is changing the inner tuples to lists. Here it is turning iterators into lists. Thanks to @Oregano's and @badp's comments.

In Python 3, pass the result through list() to get the same 2D list as method 2.


method 2 — list comprehension, zip_longest()

>>> [list(row) for row in six.moves.zip_longest(*list_list, fillvalue='-')]
[[1, 4, 7], [2, 5, 8], [3, 6, 9], ['-', 6.1, '-'], ['-', 6.2, '-'], ['-', 6.3, '-']]

The @inspectorG4dget alternative.


method 3 — map() of map()broken in Python 3.6

>>> map(list, map(None, *list_list))
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [None, 6.1, None], [None, 6.2, None], [None, 6.3, None]]

This extraordinarily compact @SiggyF second alternative works with ragged 2D lists, unlike his first code which uses numpy to transpose and pass through ragged lists. But None has to be the fill value. (No, the None passed to the inner map() is not the fill value. It means there is no function to process each column. The columns are just passed through to the outer map() which converts them from tuples to lists.)

Somewhere in Python 3, map() stopped putting up with all this abuse: the first parameter cannot be None, and ragged iterators are just truncated to the shortest. The other methods still work because this only applies to the inner map().


method 4 — map() of map() revisited

>>> list(map(list, map(lambda *args: args, *list_list)))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]   // Python 2.7
[[1, 4, 7], [2, 5, 8], [3, 6, 9], [None, 6.1, None], [None, 6.2, None], [None, 6.3, None]] // 3.6+

Alas the ragged rows do NOT become ragged columns in Python 3, they are just truncated. Boo hoo progress.

Hide text using css

One of the ways I achieve this is to use :before or :after. I've used this approach for several years, and particularly works great with glyph vector icons.

h1 {
    position: relative;
    text-indent: -9999px;                 /* sends the text off-screen */
    }
h1:before {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    display: block;
    width: 600px;
    height: 100px;
    content: ' ';
    background: transparent url(/the_img.png) 0 0 no-repeat;
    }

How do I invert BooleanToVisibilityConverter?

A simple one way version which can be used like this:

Visibility="{Binding IsHidden, Converter={x:Static Ui:Converters.BooleanToVisibility}, ConverterParameter=true}

can be implemented like this:

public class BooleanToVisibilityConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    var invert = false;

    if (parameter != null)
    {
      invert = Boolean.Parse(parameter.ToString());
    }

    var booleanValue = (bool) value;

    return ((booleanValue && !invert) || (!booleanValue && invert)) 
      ? Visibility.Visible : Visibility.Collapsed;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}

How to add column to numpy array

If you have an array, a of say 210 rows by 8 columns:

a = numpy.empty([210,8])

and want to add a ninth column of zeros you can do this:

b = numpy.append(a,numpy.zeros([len(a),1]),1)

Http Post With Body

 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

then add elements for each pair

 nameValuePairs.add(new BasicNameValuePair("yourReqVar", Value);
 nameValuePairs.add( ..... );

Then use the HttpPost:

HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

and use the HttpClient and Response to get the response from the server

What is the preferred/idiomatic way to insert into a map?

The first version:

function[0] = 42; // version 1

may or may not insert the value 42 into the map. If the key 0 exists, then it will assign 42 to that key, overwriting whatever value that key had. Otherwise it inserts the key/value pair.

The insert functions:

function.insert(std::map<int, int>::value_type(0, 42));  // version 2
function.insert(std::pair<int, int>(0, 42));             // version 3
function.insert(std::make_pair(0, 42));                  // version 4

on the other hand, don't do anything if the key 0 already exists in the map. If the key doesn't exist, it inserts the key/value pair.

The three insert functions are almost identical. std::map<int, int>::value_type is the typedef for std::pair<const int, int>, and std::make_pair() obviously produces a std::pair<> via template deduction magic. The end result, however, should be the same for versions 2, 3, and 4.

Which one would I use? I personally prefer version 1; it's concise and "natural". Of course, if its overwriting behavior is not desired, then I would prefer version 4, since it requires less typing than versions 2 and 3. I don't know if there is a single de facto way of inserting key/value pairs into a std::map.

Another way to insert values into a map via one of its constructors:

std::map<int, int> quadratic_func;

quadratic_func[0] = 0;
quadratic_func[1] = 1;
quadratic_func[2] = 4;
quadratic_func[3] = 9;

std::map<int, int> my_func(quadratic_func.begin(), quadratic_func.end());

List comprehension on a nested list?

>>> l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']]
>>> new_list = [float(x) for xs in l for x in xs]
>>> new_list
[40.0, 20.0, 10.0, 30.0, 20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0, 30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0]

Test for existence of nested JavaScript object key

I think the following script gives more readable representation.

declare a function:

var o = function(obj) { return obj || {};};

then use it like this:

if (o(o(o(o(test).level1).level2).level3)
{

}

I call it "sad clown technique" because it is using sign o(


EDIT:

here is a version for TypeScript

it gives type checks at compile time (as well as the intellisense if you use a tool like Visual Studio)

export function o<T>(someObject: T, defaultValue: T = {} as T) : T {
    if (typeof someObject === 'undefined' || someObject === null)
        return defaultValue;
    else
        return someObject;
}

the usage is the same:

o(o(o(o(test).level1).level2).level3

but this time intellisense works!

plus, you can set a default value:

o(o(o(o(o(test).level1).level2).level3, "none")

How to iterate over a JSONObject?

I made a small recursive function that goes through the entire json object and saves the key path and its value.

// My stored keys and values from the json object
HashMap<String,String> myKeyValues = new HashMap<String,String>();

// Used for constructing the path to the key in the json object
Stack<String> key_path = new Stack<String>();

// Recursive function that goes through a json object and stores 
// its key and values in the hashmap 
private void loadJson(JSONObject json){
    Iterator<?> json_keys = json.keys();

    while( json_keys.hasNext() ){
        String json_key = (String)json_keys.next();

        try{
            key_path.push(json_key);
            loadJson(json.getJSONObject(json_key));
       }catch (JSONException e){
           // Build the path to the key
           String key = "";
           for(String sub_key: key_path){
               key += sub_key+".";
           }
           key = key.substring(0,key.length()-1);

           System.out.println(key+": "+json.getString(json_key));
           key_path.pop();
           myKeyValues.put(key, json.getString(json_key));
        }
    }
    if(key_path.size() > 0){
        key_path.pop();
    }
}

How do I mock an autowired @Value field in Spring with Mockito?

I'd like to suggest a related solution, which is to pass the @Value-annotated fields as parameters to the constructor, instead of using the ReflectionTestUtils class.

Instead of this:

public class Foo {

    @Value("${foo}")
    private String foo;
}

and

public class FooTest {

    @InjectMocks
    private Foo foo;

    @Before
    public void setUp() {
        ReflectionTestUtils.setField(Foo.class, "foo", "foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Do this:

public class Foo {

    private String foo;

    public Foo(@Value("${foo}") String foo) {
        this.foo = foo;
    }
}

and

public class FooTest {

    private Foo foo;

    @Before
    public void setUp() {
        foo = new Foo("foo");
    }

    @Test
    public void testFoo() {
        // stuff
    }
}

Benefits of this approach: 1) we can instantiate the Foo class without a dependency container (it's just a constructor), and 2) we're not coupling our test to our implementation details (reflection ties us to the field name using a string, which could cause a problem if we change the field name).

What is the "right" way to iterate through an array in Ruby?

Trying to do the same thing consistently with arrays and hashes might just be a code smell, but, at the risk of my being branded as a codorous half-monkey-patcher, if you're looking for consistent behaviour, would this do the trick?:

class Hash
    def each_pairwise
        self.each { | x, y |
            yield [x, y]
        }
    end
end

class Array
    def each_pairwise
        self.each_with_index { | x, y |
            yield [y, x]
        }
    end
end

["a","b","c"].each_pairwise { |x,y|
    puts "#{x} => #{y}"
}

{"a" => "Aardvark","b" => "Bogle","c" => "Catastrophe"}.each_pairwise { |x,y|
    puts "#{x} => #{y}"
}

HTML5 Form Input Pattern Currency Format

I'm wrote this price pattern without zero price.

(0\.((0[1-9]{1})|([1-9]{1}([0-9]{1})?)))|(([1-9]+[0-9]*)(\.([0-9]{1,2}))?)

Valid For:

  • 1.00
  • 1
  • 1.5
  • 0.10
  • 0.1
  • 0.01
  • 2500.00

Invalid For:

  • 0
  • 0.00
  • 0.0
  • 2500.
  • 2500.0000

Check my code online: http://regexr.com/3binj

Getting the value of an attribute in XML

This is more of an xpath question, but like this, assuming the context is the parent element:

<xsl:value-of select="name/@attribute1" />

Vue.js : How to set a unique ID for each component instance?

To Nihat's point (above): Evan You has advised against using _uid: "The vm _uid is reserved for internal use and it's important to keep it private (and not rely on it in user code) so that we keep the flexibility to change its behavior for potential future use cases. ... I'd suggest generating UIDs yourself [using a module, a global mixin, etc.]"

Using the suggested mixin in this GitHub issue to generate the UID seems like a better approach:

let uuid = 0;

export default {
  beforeCreate() {
    this.uuid = uuid.toString();
    uuid += 1;
  },
};

What is the most efficient way to concatenate N arrays?

Here is a function by which you can concatenate multiple number of arrays

function concatNarrays(args) {
    args = Array.prototype.slice.call(arguments);
    var newArr = args.reduce( function(prev, next) {
       return prev.concat(next) ;
    });

    return newArr;
}

Example -

console.log(concatNarrays([1, 2, 3], [5, 2, 1, 4], [2,8,9]));

will output

[1,2,3,5,2,1,4,2,8,9]

Getting strings recognized as variable names in R

The basic answer to the question in the title is eval(as.symbol(variable_name_as_string)) as Josh O'Brien uses. e.g.

var.name = "x"
assign(var.name, 5)
eval(as.symbol(var.name)) # outputs 5

Or more simply:

get(var.name) # 5

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

I fixed this issue by adding following code in my file.

@Component
@Scope(value = "session",  proxyMode = ScopedProxyMode.TARGET_CLASS)

XML configuration -

<listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener 
        </listener-class>
</listener>

Above we can do using Java configuration -

@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}

How to add a RequestContextListener with no-xml configuration?

I am using spring version 5.1.4.RELEASE and no need to add below changes in pom.

<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.2.10</version>
</dependency>

What are the true benefits of ExpandoObject?

I think it will have a syntactic benefit, since you'll no longer be "faking" dynamically added properties by using a dictionary.

That, and interop with dynamic languages I would think.

How does one make random number between range for arc4random_uniform()?

I've made an Int type extension. tested it in playground, hope this is useful. It also accepts negative ranges:

extension Int
{
    static func random(range: Range<Int> ) -> Int
    {
        var offset = 0

        if range.startIndex < 0   // allow negative ranges
        {
            offset = abs(range.startIndex)
        }

        let mini = UInt32(range.startIndex + offset)
        let maxi = UInt32(range.endIndex   + offset)

        return Int(mini + arc4random_uniform(maxi - mini)) - offset
    }
}

use like

var aRandomInt = Int.random(-500...100)  // returns a random number within the given range.

or define it as a Range extension as property like this:

extension Range
{
    var randomInt: Int
    {
        get
        {
            var offset = 0

            if (startIndex as Int) < 0   // allow negative ranges
            {
                offset = abs(startIndex as Int)
            }

            let mini = UInt32(startIndex as Int + offset)
            let maxi = UInt32(endIndex   as Int + offset)

            return Int(mini + arc4random_uniform(maxi - mini)) - offset
        }
    }
}

// usage example: get an Int within the given Range:
let nr = (-1000 ... 1100).randomInt

SQL Query to find the last day of the month

Calculate the last date of the month is quite simple calculation -

1 - Find the total months count till today's date using DATEDIFF function -

Select DATEDIFF(MM,0,GETDATE())

Output - 1374, If getdate() output is "2014-07-23 19:33:46.850"

2 -Increment by 1 into total months count -

Select DATEDIFF(MM,0,GETDATE())+1

Output - 1375, If getdate() output is "2014-07-23 19:33:46.850"

3 - Get the first date of next month -

Select DATEADD(MM,DATEDIFF(MM,0,GETDATE())+1,0)

Output - '2014-08-01 00:00:00.000', If getdate() output is "2014-07-23 19:33:46.850"

4 - Subtract by -1 into the first date of next month, which will return last date of the current month -

Select DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,0,GETDATE())+1,0))

Output - '2014-07-31 00:00:00.000', If getdate() output is "2014-07-23 19:33:46.850"

In the same manner of calculation we can achieve the -

  1. Last date of next month
  2. Last date of the previous month and so on.

Converting a pointer into an integer

Since uintptr_t is not guaranteed to be there in C++/C++11, if this is a one way conversion you can consider uintmax_t, always defined in <cstdint>.

auto real_param = reinterpret_cast<uintmax_t>(param);

To play safe, one could add anywhere in the code an assertion:

static_assert(sizeof (uintmax_t) >= sizeof (void *) ,
              "No suitable integer type for conversion from pointer type");

How to read an entire file to a string using C#?

string contents = System.IO.File.ReadAllText(path)

Here's the MSDN documentation

Create a text file for download on-the-fly

<?php

    header('Content-type: text/plain');
    header('Content-Disposition: attachment;
            filename="<name for the created file>"');
    /*
    assign file content to a PHP Variable $content
    */
    echo $content;
?>

jQuery click event not working after adding class

Based on @Arun P Johny this is how you do it for an input:

<input type="button" class="btEdit" id="myButton1">

This is how I got it in jQuery:

$(document).on('click', "input.btEdit", function () {
    var id = this.id;
    console.log(id);
});

This will log on the console: myButton1. As @Arun said you need to add the event dinamically, but in my case you don't need to call the parent first.

UPDATE

Though it would be better to say:

$(document).on('click', "input.btEdit", function () {
    var id = $(this).id;
    console.log(id);
});

Since this is JQuery's syntax, even though both will work.

Where do alpha testers download Google Play Android apps?

  1. Publish your alpha apk by pressing the submit button.

  2. Wait until it's published.
    (e.g.: CURRENT APK published on Apr 28, 2015, 2:20:13AM)

  3. Select Alpha testers - click Manage list of testers.

  4. Share the link with your testers (by email).
    (e.g.: https://play.google.com/apps/testing/uk.co.xxxxx.xxxxx)

Connect with SSH through a proxy

This is how I solved it, hoping to help others later.

My system is debian 10, and minimal installation.

I also have the same problem like this.

git clone [email protected]:nothing/nothing.git
Cloning into 'nothing'...
nc: invalid option -- 'x'
nc -h for help
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Or

git clone [email protected]:nothing/nothing.git
Cloning into 'nothing'...
/usr/bin/nc: invalid option -- 'X'
nc -h for help
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

So, I know the nc has different versions like openbsd-netcat and GNU-netcat, you can change the nc in debian to the openbsd version, but I choose to change the software like corkscrew, because the names of the two versions of nc in system are same, and many people don’t understand it well. My approach is as follows.

sudo apt install corkscrew

Then.

vim ~/.ssh/config

Change this file like this.

Host github.com
    User git
    ProxyCommand corkscrew 192.168.1.22 8118 %h %p

192.168.1.22 and 8118 is my proxy server's address and port, you should change it according to your server address.

It's work fine.

Thanks @han.

"java.lang.OutOfMemoryError: PermGen space" in Maven build

We face this error when permanent generation heap is full and some of us we use command prompt to build our maven project in windows. since we need to increase heap size, we could set our environment variable @ControlPanel/System and Security/System and there you click on Change setting and select Advanced and set Environment variable as below

  • Variable-name : MAVEN_OPTS
  • Variable-value : -XX:MaxPermSize=128m

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

You can use:

os.execute("sleep 1") -- I think you can do every command of CMD using os.execute("command")

or you can use:

function wait(waitTime)
    timer = os.time()
    repeat until os.time() > timer + waitTime
end

wait(YourNumberHere)

Calling an executable program using awk

I use the power of awk to delete some of my stopped docker containers. Observe carefully how i construct the cmd string first before passing it to system.

docker ps -a | awk '$3 ~ "/bin/clish" { cmd="docker rm "$1;system(cmd)}'

Here, I use the 3rd column having the pattern "/bin/clish" and then I extract the container ID in the first column to construct my cmd string and passed that to system.

Iterating through struct fieldnames in MATLAB

Since fields or fns are cell arrays, you have to index with curly brackets {} in order to access the contents of the cell, i.e. the string.

Note that instead of looping over a number, you can also loop over fields directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.

teststruct = struct('a',3,'b',5,'c',9)

fields = fieldnames(teststruct)

for fn=fields'
  fn
  %# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
  teststruct.(fn{1})
end

maxlength ignored for input type="number" in Chrome

For React users,

Just replace 10 with your max length requirement

 <input type="number" onInput={(e) => e.target.value = e.target.value.slice(0, 10)}/>

Twitter bootstrap collapse: change display of toggle button

Easier with inline coding

<button type="button" ng-click="showmore = (showmore !=null && showmore) ? false : true;" class="btn float-right" data-toggle="collapse" data-target="#moreoptions">
            <span class="glyphicon" ng-class="showmore ? 'glyphicon-collapse-up': 'glyphicon-collapse-down'"></span>
            {{ showmore !=null && showmore ? "Hide More Options" : "Show More Options" }}
        </button>


<div id="moreoptions" class="collapse">Your Panel</div>

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

Why not try adding Scope? Scope is a very good feature of Eloquent.

class User extends Eloquent {

    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

    public function scopeWomen($query)
    {
        return $query->whereGender('W');
    }

}

$users = User::popular()->women()->orderBy('created_at')->get();

Eloquent #scopes in Laravel Docs

Should you always favor xrange() over range()?

A good example given in book: Practical Python By Magnus Lie Hetland

>>> zip(range(5), xrange(100000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

I wouldn’t recommend using range instead of xrange in the preceding example—although only the first five numbers are needed, range calculates all the numbers, and that may take a lot of time. With xrange, this isn’t a problem because it calculates only those numbers needed.

Yes I read @Brian's answer: In python 3, range() is a generator anyway and xrange() does not exist.

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

Why does a base64 encoded string have an = sign at the end

http://www.hcidata.info/base64.htm

Encoding "Mary had" to Base 64

In this example we are using a simple text string ("Mary had") but the principle holds no matter what the data is (e.g. graphics file). To convert each 24 bits of input data to 32 bits of output, Base 64 encoding splits the 24 bits into 4 chunks of 6 bits. The first problem we notice is that "Mary had" is not a multiple of 3 bytes - it is 8 bytes long. Because of this, the last group of bits is only 4 bits long. To remedy this we add two extra bits of '0' and remember this fact by putting a '=' at the end. If the text string to be converted to Base 64 was 7 bytes long, the last group would have had 2 bits. In this case we would have added four extra bits of '0' and remember this fact by putting '==' at the end.

Handling InterruptedException in Java

As it happens I was just reading about this this morning on my way to work in Java Concurrency In Practice by Brian Goetz. Basically he says you should do one of three things

  1. Propagate the InterruptedException - Declare your method to throw the checked InterruptedException so that your caller has to deal with it.

  2. Restore the Interrupt - Sometimes you cannot throw InterruptedException. In these cases you should catch the InterruptedException and restore the interrupt status by calling the interrupt() method on the currentThread so the code higher up the call stack can see that an interrupt was issued, and quickly return from the method. Note: this is only applicable when your method has "try" or "best effort" semantics, i. e. nothing critical would happen if the method doesn't accomplish its goal. For example, log() or sendMetric() may be such method, or boolean tryTransferMoney(), but not void transferMoney(). See here for more details.

  3. Ignore the interruption within method, but restore the status upon exit - e. g. via Guava's Uninterruptibles. Uninterruptibles take over the boilerplate code like in the Noncancelable Task example in JCIP § 7.1.3.

How to get primary key of table?

Shortest possible code seems to be something like

// $dblink contain database login details 
// $tblName the current table name 
$r = mysqli_fetch_assoc(mysqli_query($dblink, "SHOW KEYS FROM $tblName WHERE Key_name = 'PRIMARY'")); 
$iColName = $r['Column_name']; 

jQuery load more data on scroll

Improving on @deepakssn answer. There is a possibility that you want the data to load a bit before we actually scroll to the bottom.

var scrollLoad = true;
$(window).scroll(function(){
 if (scrollLoad && ($(document).height() - $(window).height())-$(window).scrollTop()<=800){
    // fetch data when we are 800px above the document end
    scrollLoad = false;
   }
  });

[var scrollLoad] is used to block the call until one new data is appended.

Hope this helps.

How do I line up 3 divs on the same row?

I'm not sure how I ended up on this post but since most of the answers are using floats, absolute positioning, and other options which aren't optimal now a days, I figured I'd give a new answer that's more up to date on it's standards (float isn't really kosher anymore).

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
  flex-direction:row;_x000D_
}_x000D_
_x000D_
.column {_x000D_
  flex: 1 1 0px;_x000D_
  border: 1px solid black;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div class="column">Column 1</div>_x000D_
    <div class="column">Column 2<br>Column 2<br>Column 2<br>Column 2<br></div>_x000D_
    <div class="column">Column 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to split a string in Haskell?

Use Data.List.Split, which uses split:

[me@localhost]$ ghci
Prelude> import Data.List.Split
Prelude Data.List.Split> let l = splitOn "," "1,2,3,4"
Prelude Data.List.Split> :t l
l :: [[Char]]
Prelude Data.List.Split> l
["1","2","3","4"]
Prelude Data.List.Split> let { convert :: [String] -> [Integer]; convert = map read }
Prelude Data.List.Split> let l2 = convert l
Prelude Data.List.Split> :t l2
l2 :: [Integer]
Prelude Data.List.Split> l2
[1,2,3,4]

How to fix committing to the wrong Git branch?

If you haven't yet pushed your changes, you can also do a soft reset:

git reset --soft HEAD^

This will revert the commit, but put the committed changes back into your index. Assuming the branches are relatively up-to-date with regard to each other, git will let you do a checkout into the other branch, whereupon you can simply commit:

git checkout branch
git commit

The disadvantage is that you need to re-enter your commit message.

How do you compare structs for equality in C?

memcmp does not compare structure, memcmp compares the binary, and there is always garbage in the struct, therefore it always comes out False in comparison.

Compare element by element its safe and doesn't fail.

LINQ to SQL Left Outer Join

Public Sub LinqToSqlJoin07()
Dim q = From e In db.Employees _
        Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
        From o In ords.DefaultIfEmpty _
        Select New With {e.FirstName, e.LastName, .Order = o}

ObjectDumper.Write(q) End Sub

Check http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx

How do I push to GitHub under a different username?

If after running git push Git asks for a password of user, but you would like to push as new_user, you may want to use git config remote.origin.url:

$ git push
[email protected]:either/branch/or/path's password:

At this point use ^C to quit git push and use following to push as new_user.

$ git config remote.origin.url
[email protected]:either/branch/or/path

$ git config remote.origin.url [email protected]:either/branch/or/path

$ git push
[email protected]:either/branch/or/path's password:

Creating Unicode character from its number

Remember that char is an integral type, and thus can be given an integer value, as well as a char constant.

char c = 0x2202;//aka 8706 in decimal. \u codepoints are in hex.
String s = String.valueOf(c);

In Perl, how can I read an entire file into a string?

open f, "test.txt"
$file = join '', <f>

<f> - returns an array of lines from our file (if $/ has the default value "\n") and then join '' will stick this array into.

Force git stash to overwrite added files

To force git stash pop run this command

git stash show -p | git apply && git stash drop

How to destroy Fragment?

It's used in Kotlin

appCompatActivity?.getSupportFragmentManager()?.popBackStack()

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

Check div is hidden using jquery

Try

if($('#car2').is(':hidden'))
{  
    alert('car 2 is hidden');       
}

NodeJS w/Express Error: Cannot GET /

I was facing the same problem as mentioned in the question. The following steps solved my problem.

I upgraded the nodejs package link with following steps

  1. Clear NPM's cache:

    npm cache clean -f
    
  2. Install a little helper called 'n'

    npm install -g n  
    

Then I went to node.js website, downloaded the latest node js package, installed it, and my problem was solved.

Check if a path represents a file or a folder

String path = "Your_Path";
File f = new File(path);

if (f.isDirectory()){



  }else if(f.isFile()){



  }

Android update activity UI from service

for me the simplest solution was to send a broadcast, in the activity oncreate i registered and defined the broadcast like this (updateUIReciver is defined as a class instance) :

 IntentFilter filter = new IntentFilter();

 filter.addAction("com.hello.action"); 

 updateUIReciver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                //UI update here

            }
        };
 registerReceiver(updateUIReciver,filter);

And from the service you send the intent like this:

Intent local = new Intent();

local.setAction("com.hello.action");

this.sendBroadcast(local);

don't forget to unregister the recover in the activity on destroy :

unregisterReceiver(updateUIReciver);

How to select a specific node with LINQ-to-XML

Assuming the ID is unique:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

You could also use First, FirstOrDefault, SingleOrDefault or Where, instead of Single for different circumstances.

How to change the height of a div dynamically based on another div using css?

In this piece of code the height of left panel will gets adjusted to the height of right panel dynamically...

function resizeDiv() {
var rh=$('.pright').height()+'px'.toString();
$('.pleft').css('height',rh);
}

You can try this here http://jsfiddle.net/SriharshaCR/7q585k1x/9/embedded/result/

How to loop through an array of objects in swift

Unwrap and downcast the objects to the right type, safely, with if let, before doing the iteration with a simple for in loop.

if let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] 
{
    for object in photos {
        let url = object.url
    }
}

There's also guard let else instead of if let if you prefer having the result available in scope:

guard let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] else 
{
    // break or return
}
// now 'photos' is available outside the guard
for object in photos {
    let url = object.url
}

Could someone explain this for me - for (int i = 0; i < 8; i++)

for (int i = 0; i < 8; i++) {
  //code
}

In simplest terms

int i = 0;
if (i < 8) //code
i = i + 1; //i = 1
if (i < 8) //code
i = i + 1;  //i = 2
if (i < 8) //code
i = i + 1;  //i = 3
if (i < 8) //code
i = i + 1; //i = 4
if (i < 8) //code
i = i + 1; //i = 5
if (i < 8) //code
i = i + 1; //i = 6
if (i < 8) //code
i = i + 1; //i = 7
if (i < 8) //code
i = i + 1; //i = 8
if (i < 8) //code - this if won't pass

How do I sort a list of dictionaries by a value of the dictionary?

You have to implement your own comparison function that will compare the dictionaries by values of name keys. See Sorting Mini-HOW TO from PythonInfo Wiki

How to call a parent method from child class in javascript?

Here's how its done: ParentClass.prototype.myMethod();

Or if you want to call it in the context of the current instance, you can do: ParentClass.prototype.myMethod.call(this)

Same goes for calling a parent method from child class with arguments: ParentClass.prototype.myMethod.call(this, arg1, arg2, ..) * Hint: use apply() instead of call() to pass arguments as an array.

Setting equal heights for div's with jQuery

Important improvement! (I added $(this).height('auto'); before measuring height - we should reset it to auto. Then we can use this function on resize)

function equalheight () {
            $('.cont_for_height').each(function(){  

                var highestBox = 0;
                $('.column_height', this).each(function(){

                    var htmlString = $( this ).html()

                    ;


                $(this).height('auto');

                    if($(this).height() > highestBox) 
                       highestBox = $(this).height(); 
                });  

                $('.column_height',this).height(highestBox);

        });  

        }

grunt: command not found when running from terminal

For windows

npm install -g grunt-cli

npm install load-grunt-tasks

Then run

grunt

ClassNotFoundException com.mysql.jdbc.Driver

see to it that the argument of Class. forName method is exactly "com. mysql. jdbc. Driver". If yes then see to it that mysql connector is present in lib folder of the project. if yes then see to it that the same mysql connector . jar file is in the ClassPath variable (system variable)..

What are all the common ways to read a file in Ruby?

if the file is small (slurping):

puts File.read("filename.txt")

if the file is big (streaming):

File.foreach("filename.txt") { |line| puts line }

Calculating how many days are between two dates in DB2?

values timestampdiff (16, char( 
    timestamp(current timestamp + 1 year + 2 month - 3 day)- 
    timestamp(current timestamp)))
1
=
422



values timestampdiff (16, char( 
    timestamp('2012-03-08-00.00.00')- 
    timestamp('2011-12-08-00.00.00')))
1
=
90

---------- EDIT BY galador

SELECT TIMESTAMPDIFF(16, CHAR(CURRENT TIMESTAMP - TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD'))
FROM CHCART00
WHERE CHSTAT = '05'

EDIT

As it has been pointed out by X-Zero, this function returns only an estimate. This is true. For accurate results I would use the following to get the difference in days between two dates a and b:

SELECT days (current date) - days (date(TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD')))
FROM CHCART00 
WHERE CHSTAT = '05';

Checkbox angular material checked by default

You can either set with ngModel either with [checked] attribute. ngModel binded property should be set to 'true':

1.

  <mat-checkbox class = "example-margin" [(ngModel)] = "myModel"> 
    <label>Printer </label> 
  </mat-checkbox>

2.

<mat-checkbox [checked]= "myModel" class = "example-margin" > 
    <label>Printer </label> 
</mat-checkbox>

3.

<mat-checkbox [ngModel]="myModel" class="example-margin">
    <label>Printer </label> 
</mat-checkbox>

DEMO

Detect whether there is an Internet connection available on Android

Also another important note. You have to set android.permission.ACCESS_NETWORK_STATE in your AndroidManifest.xml for this to work.

_ how could I have found myself the information I needed in the online documentation?

You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. Check out the documentation on ConnectivityManager. The description tells you what to do.

Java String remove all non numeric characters

Currency decimal separator can be different from Locale to another. It could be dangerous to consider . as separator always. i.e.

+------------------------------------+
¦    Locale      ¦      Sample       ¦
¦----------------+-------------------¦
¦ USA            ¦ $1,222,333.44 USD ¦
¦ United Kingdom ¦ £1.222.333,44 GBP ¦
¦ European       ¦ €1.333.333,44 EUR ¦
+------------------------------------+

I think the proper way is:

  • Get decimal character via DecimalFormatSymbols by default Locale or specified one.
  • Cook regex pattern with decimal character in order to obtain digits only

And here how I am solving it:

code:

import java.text.DecimalFormatSymbols;
import java.util.Locale;

    public static String getDigit(String quote, Locale locale) {
    char decimalSeparator;
    if (locale == null) {
        decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
    } else {
        decimalSeparator = new DecimalFormatSymbols(locale).getDecimalSeparator();
    }

    String regex = "[^0-9" + decimalSeparator + "]";
    String valueOnlyDigit = quote.replaceAll(regex, "");
    try {
        return valueOnlyDigit;
    } catch (ArithmeticException | NumberFormatException e) {
        Log.e(TAG, "Error in getMoneyAsDecimal", e);
        return null;
    }
    return null;
}

I hope that may help,'.

trim left characters in sql server?

use "LEFT"

 select left('Hello World', 5)

or use "SUBSTRING"

 select substring('Hello World', 1, 5)

How to split a string of space separated numbers into integers?

Just use strip() to remove empty spaces and apply explicit int conversion on the variable.

Ex:

a='1  ,  2, 4 ,6 '
f=[int(i.strip()) for i in a]

PHP post_max_size overrides upload_max_filesize

By POST file uploads are done (commonly, there are also other methods). Look into the method attribute of the form which contains the file-upload field ;)

The lowest limit of any related setting supersedes a higher setting:

See Handling file uploads: Common Pitfals which explains this in detail and how to calculate the values.

Printing 1 to 1000 without loop or conditionals

There are plenty of abnormal exits due to stack overflows so far, but no heap ones yet, so here's my contribution:

#include <cstdio>
#include <cstdlib>
#include <sys/mman.h>
#include <sys/signal.h>
#define PAGE_SIZE 4096
void print_and_set(int i, int* s)
{
  *s = i;
  printf("%d\n", i);
  print_and_set(i + 1, s + 1);
}
void
sigsegv(int)
{
  fflush(stdout); exit(0);
}
int
main(int argc, char** argv)
{
  int* mem = reinterpret_cast<int*>
    (reinterpret_cast<char*>(mmap(NULL, PAGE_SIZE * 2, PROT_WRITE,
                                  MAP_PRIVATE | MAP_ANONYMOUS, 0, 0)) +
     PAGE_SIZE - 1000 * sizeof(int));
  mprotect(mem + 1000, PAGE_SIZE, PROT_NONE);
  signal(SIGSEGV, sigsegv);
  print_and_set(1, mem);
}

Not very good practice, and no error checks (for obvious reasons) but I don't think that is the point of the question!

There are plenty of other abnormal termination options, of course, some of which are simpler: assert(), SIGFPE (I think someone did that one), and so on.

How to change the server port from 3000?

Using Angular 4 and the cli that came with it I was able to start the server with $npm start -- --port 8000. That worked ok: ** NG Live Development Server is listening on localhost:8000, open your browser on http://localhost:8000 **

Got the tip from Here

enter image description here enter image description here

Is there a link to the "latest" jQuery library on Google APIs?

Use:

<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
//<![CDATA[
    google.load("jquery", "1");
    //google.load("jqueryui", "1");
    //google.load("swfobject", "1");
//]]>
</script>

Note: The above snippet will stick to 1.7.1 or 1.11.1.

My advice for production is to hard code the CDN jQuery version: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

You can find the latest Libraries of Google CDN here: https://developers.google.com/speed/libraries/

Or use the jQuery CDN: https://code.jquery.com/

Generating a PDF file from React Components

You can use ReactPDF

Lets you convert a div into PDF with ease. You will need to match your existing markup to use ReactPDF markup, but it is worth it.

How to disable back swipe gesture in UINavigationController on iOS 7

This works in viewDidLoad: for iOS 8:

  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      self.navigationController.interactivePopGestureRecognizer.enabled = false;
  });

Lots of the problems could be solved with help of the good ol' dispatch_after.

Though please note that this solution is potentially unsafe, please use your own reasoning.

Update

For iOS 8.1 delay time should be 0.5 seconds

On iOS 9.3 no delay needed anymore, it works just by placing this in your viewDidLoad:
(TBD if works on iOS 9.0-9.3)

navigationController?.interactivePopGestureRecognizer?.enabled = false

JTable How to refresh table model after insert delete or update the data.

DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed

PHP check file extension

$path = 'image.jpg';
echo substr(strrchr($path, "."), 1); //jpg

How to tell if JRE or JDK is installed

according to JAVA documentation, the JDK should be installed in this path:

/Library/Java/JavaVirtualMachines/jdkmajor.minor.macro[_update].jdk

See the uninstall JDK part at https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html

So if you can find such folder then the JDK is installed

Java get last element of a collection

Iterables.getLast from Google Guava. It has some optimization for Lists and SortedSets too.

How to add footnotes to GitHub-flavoured Markdown?

Although I am not aware if it's officially documented anywhere, you can do footer notes in Github.

  1. Mark the place where you want to insert footer link with a number enclosed in square brackets, I.E. [1]

  2. On the bottom of the post, make a reference of the numbered marker and followed by a colon and the link, I.E. [1]: http://www.example.com/link1

And once you preview it, it will be rendered as numbered links in the body of the post.

How to reload a div without reloading the entire page?

jQuery.load() is probably the easiest way to load data asynchronously using a selector, but you can also use any of the jquery ajax methods (get, post, getJSON, ajax, etc.)

Note that load allows you to use a selector to specify what piece of the loaded script you want to load, as in

$("#mydiv").load(location.href + " #mydiv");

Note that this technically does load the whole page and jquery removes everything but what you have selected, but that's all done internally.

c# regex matches example

So you're trying to grab numeric values that are preceded by the token "%download%#"?

Try this pattern:

(?<=%download%#)\d+

That should work. I don't think # or % are special characters in .NET Regex, but you'll have to either escape the backslash like \\ or use a verbatim string for the whole pattern:

var regex = new Regex(@"(?<=%download%#)\d+");
return regex.Matches(strInput);

Tested here: http://rextester.com/BLYCC16700

NOTE: The lookbehind assertion (?<=...) is important because you don't want to include %download%# in your results, only the numbers after it. However, your example appears to require it before each string you want to capture. The lookbehind group will make sure it's there in the input string, but won't include it in the returned results. More on lookaround assertions here.

Popup window in winform c#

If you mean to create a new form when a button is clicked, the below code may be of some use to you:

private void settingsButton_Click(Object sender, EventArgs e)
{
    // Create a new instance of the Form2 class
    Form2 settingsForm = new Form2();

    // Show the settings form
    settingsForm.Show();
}

From here, you could also use the 'Show Dialog' method

How do I restrict an input to only accept numbers?

None of the solutions proposed worked fine for me, and after a couple of hours I finally found the way.

This is the angular directive:

angular.module('app').directive('restrictTo', function() {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var re = RegExp(attrs.restrictTo);
            var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/;

            element[0].addEventListener('keydown', function(event) {
                if (!exclude.test(event.key) && !re.test(event.key)) {
                    event.preventDefault();
                }
            });
        }
    }
});

And the input would look like:

<input type="number" min="0" name="inputName" ng-model="myModel" restrict-to="[0-9]">

The regular expression evaluates the pressed key, not the value.

It also works perfectly with inputs type="number" because prevents from changing its value, so the key is never displayed and it does not mess with the model.

Matplotlib scatter plot with different text at each data point

You may also use pyplot.text (see here).

def plot_embeddings(M_reduced, word2Ind, words):
    """ 
        Plot in a scatterplot the embeddings of the words specified in the list "words".
        Include a label next to each point.
    """
    for word in words:
        x, y = M_reduced[word2Ind[word]]
        plt.scatter(x, y, marker='x', color='red')
        plt.text(x+.03, y+.03, word, fontsize=9)
    plt.show()

M_reduced_plot_test = np.array([[1, 1], [-1, -1], [1, -1], [-1, 1], [0, 0]])
word2Ind_plot_test = {'test1': 0, 'test2': 1, 'test3': 2, 'test4': 3, 'test5': 4}
words = ['test1', 'test2', 'test3', 'test4', 'test5']
plot_embeddings(M_reduced_plot_test, word2Ind_plot_test, words)

enter image description here

ldconfig error: is not a symbolic link

simple run in shell : sudo apt-get install --reinstall libexpat1
got same problem with libxcb - solved in this way - very fast :)

What is the difference between DSA and RSA?

Referring, https://web.archive.org/web/20140212143556/http://courses.cs.tamu.edu:80/pooch/665_spring2008/Australian-sec-2006/less19.html

RSA
RSA encryption and decryption are commutative
hence it may be used directly as a digital signature scheme
given an RSA scheme {(e,R), (d,p,q)}
to sign a message M, compute:
S = M power d (mod R)
to verify a signature, compute:
M = S power e(mod R) = M power e.d(mod R) = M(mod R)

RSA can be used both for encryption and digital signatures, simply by reversing the order in which the exponents are used: the secret exponent (d) to create the signature, the public exponent (e) for anyone to verify the signature. Everything else is identical.

DSA (Digital Signature Algorithm)
DSA is a variant on the ElGamal and Schnorr algorithms. It creates a 320 bit signature, but with 512-1024 bit security again rests on difficulty of computing discrete logarithms has been quite widely accepted.

DSA Key Generation
firstly shared global public key values (p,q,g) are chosen:
choose a large prime p = 2 power L
where L= 512 to 1024 bits and is a multiple of 64
choose q, a 160 bit prime factor of p-1
choose g = h power (p-1)/q
for any h<p-1, h(p-1)/q(mod p)>1
then each user chooses a private key and computes their public key:
choose x<q
compute y = g power x(mod p)

DSA key generation is related to, but somewhat more complex than El Gamal. Mostly because of the use of the secondary 160-bit modulus q used to help speed up calculations and reduce the size of the resulting signature.

DSA Signature Creation and Verification

to sign a message M
generate random signature key k, k<q
compute
r = (g power k(mod p))(mod q)
s = k-1.SHA(M)+ x.r (mod q)
send signature (r,s) with message

to verify a signature, compute:
w = s-1(mod q)
u1= (SHA(M).w)(mod q)
u2= r.w(mod q)
v = (g power u1.y power u2(mod p))(mod q)
if v=r then the signature is verified

Signature creation is again similar to ElGamal with the use of a per message temporary signature key k, but doing calc first mod p, then mod q to reduce the size of the result. Note that the use of the hash function SHA is explicit here. Verification also consists of comparing two computations, again being a bit more complex than, but related to El Gamal.
Note that nearly all the calculations are mod q, and hence are much faster.
But, In contrast to RSA, DSA can be used only for digital signatures

DSA Security
The presence of a subliminal channel exists in many schemes (any that need a random number to be chosen), not just DSA. It emphasises the need for "system security", not just a good algorithm.

How to drop a list of rows from Pandas dataframe?

In a comment to @theodros-zelleke's answer, @j-jones asked about what to do if the index is not unique. I had to deal with such a situation. What I did was to rename the duplicates in the index before I called drop(), a la:

dropped_indexes = <determine-indexes-to-drop>
df.index = rename_duplicates(df.index)
df.drop(df.index[dropped_indexes], inplace=True)

where rename_duplicates() is a function I defined that went through the elements of index and renamed the duplicates. I used the same renaming pattern as pd.read_csv() uses on columns, i.e., "%s.%d" % (name, count), where name is the name of the row and count is how many times it has occurred previously.

does linux shell support list data structure?

For make a list, simply do that

colors=(red orange white "light gray")

Technically is an array, but - of course - it has all list features.
Even python list are implemented with array

How to check if an int is a null

You have to access to your class atributes.

To access to it atributes, you have to do:

person.id
person.name

where

person

is an instance of your class Person.

This can be done if the attibutes can be accessed, if not, you must use setters and getters...

How to loop through a plain JavaScript object with the objects as members?

Under ECMAScript 5, you can combine Object.keys() and Array.prototype.forEach():

_x000D_
_x000D_
var obj = {_x000D_
  first: "John",_x000D_
  last: "Doe"_x000D_
};_x000D_
_x000D_
//_x000D_
// Visit non-inherited enumerable keys_x000D_
//_x000D_
Object.keys(obj).forEach(function(key) {_x000D_
_x000D_
  console.log(key, obj[key]);_x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

T-SQL How to select only Second row from a table?

you can use OFFSET and FETCH NEXT

SELECT id
FROM tablename
ORDER BY column
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY;

NOTE:

OFFSET can only be used with ORDER BY clause. It cannot be used on its own.

OFFSET value must be greater than or equal to zero. It cannot be negative, else return error.

The OFFSET argument is used to identify the starting point to return rows from a result set. Basically, it exclude the first set of records.

The FETCH argument is used to return a set of number of rows. FETCH can’t be used itself, it is used in conjuction with OFFSET.

How to include a Font Awesome icon in React's render()

In case you are looking to include the font awesome library without having to do module imports and npm installs, put this in the head section of your React index.html page:

public/index.html (in head section)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>

Then in your component (such as App.js) just use standard font awesome class convention. Just remember to use className instead of class:

<button className='btn'><i className='fa fa-home'></i></button>

Jquery to get the id of selected value from dropdown

Try the change event and selected selector

$('#jobSel').change(function(){
    var optId = $(this).find('option:selected').attr('id')
})

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

This has to be done during your exe4j configuration. In the fourth step of Exe4j wizard which is Executable Info select> Advanced options select 32-bit or 64-bit. This worked well for me. or else install both JDK tool-kits x64 and x32 in your machine.

MySQL Select Multiple VALUES

Try or:

WHERE id = 3 or id = 4

Or the equivalent in:

WHERE id in (3,4)

How to extract string following a pattern with grep, regex or perl

Here's a solution using HTML tidy & xmlstarlet:

htmlstr='
<table name="content_analyzer" primary-key="id">
<type="global" />
</table>
<table name="content_analyzer2" primary-key="id">
<type="global" />
</table>
<table name="content_analyzer_items" primary-key="id">
<type="global" />
</table>
'

echo "$htmlstr" | tidy -q -c -wrap 0 -numeric -asxml -utf8 --merge-divs yes --merge-spans yes 2>/dev/null |
sed '/type="global"/d' |
xmlstarlet sel -N x="http://www.w3.org/1999/xhtml" -T -t -m "//x:table" -v '@name' -n

How to get arguments with flags in Bash

I like Robert McMahan's answer the best here as it seems the easiest to make into sharable include files for any of your scripts to use. But it seems to have a flaw with the line if [[ -n ${variables[$argument_label]} ]] throwing the message, "variables: bad array subscript". I don't have the rep to comment, and I doubt this is the proper 'fix,' but wrapping that if in if [[ -n $argument_label ]] ; then cleans it up.

Here's the code I ended up with, if you know a better way please add a comment to Robert's answer.

Include File "flags-declares.sh"

# declaring a couple of associative arrays
declare -A arguments=();
declare -A variables=();

# declaring an index integer
declare -i index=1;

Include File "flags-arguments.sh"

# $@ here represents all arguments passed in
for i in "$@"
do
  arguments[$index]=$i;
  prev_index="$(expr $index - 1)";

  # this if block does something akin to "where $i contains ="
  # "%=*" here strips out everything from the = to the end of the argument leaving only the label
  if [[ $i == *"="* ]]
    then argument_label=${i%=*}
    else argument_label=${arguments[$prev_index]}
  fi

  if [[ -n $argument_label ]] ; then
    # this if block only evaluates to true if the argument label exists in the variables array
    if [[ -n ${variables[$argument_label]} ]] ; then
      # dynamically creating variables names using declare
      # "#$argument_label=" here strips out the label leaving only the value
      if [[ $i == *"="* ]]
        then declare ${variables[$argument_label]}=${i#$argument_label=} 
        else declare ${variables[$argument_label]}=${arguments[$index]}
      fi
    fi
  fi

  index=index+1;
done;

Your "script.sh"

. bin/includes/flags-declares.sh

# any variables you want to use here
# on the left left side is argument label or key (entered at the command line along with it's value) 
# on the right side is the variable name the value of these arguments should be mapped to.
# (the examples above show how these are being passed into this script)
variables["-gu"]="git_user";
variables["--git-user"]="git_user";
variables["-gb"]="git_branch";
variables["--git-branch"]="git_branch";
variables["-dbr"]="db_fqdn";
variables["--db-redirect"]="db_fqdn";
variables["-e"]="environment";
variables["--environment"]="environment";

. bin/includes/flags-arguments.sh

# then you could simply use the variables like so:
echo "$git_user";
echo "$git_branch";
echo "$db_fqdn";
echo "$environment";

How to convert a Java object (bean) to key-value pairs (and vice versa)?

If you do not want to hardcode calls to each getter and setter, reflection is the only way to call these methods (but it is not hard).

Can you refactor the class in question to use a Properties object to hold the actual data, and let each getter and setter just call get/set on it? Then you have a structure well suited for what you want to do. There is even methods to save and load them in the key-value form.

How to declare a constant map in Golang?

You may emulate a map with a closure:

package main

import (
    "fmt"
)

// http://stackoverflow.com/a/27457144/10278

func romanNumeralDict() func(int) string {
    // innerMap is captured in the closure returned below
    innerMap := map[int]string{
        1000: "M",
        900:  "CM",
        500:  "D",
        400:  "CD",
        100:  "C",
        90:   "XC",
        50:   "L",
        40:   "XL",
        10:   "X",
        9:    "IX",
        5:    "V",
        4:    "IV",
        1:    "I",
    }

    return func(key int) string {
        return innerMap[key]
    }
}

func main() {
    fmt.Println(romanNumeralDict()(10))
    fmt.Println(romanNumeralDict()(100))

    dict := romanNumeralDict()
    fmt.Println(dict(400))
}

Try it on the Go playground

How to add http:// if it doesn't exist in the URL

nickf's solution modified:

function addhttp($url) {
    if (!preg_match("@^https?://@i", $url) && !preg_match("@^ftps?://@i", $url)) {
        $url = "http://" . $url;
    }
    return $url;
}

Simulating Slow Internet Connection

I was using http://www.netlimiter.com/ and it works very well. Not only limit speed for single processes but also shows actual transfer rates.

Printing to the console in Google Apps Script?

Updated for 2020

In February of 2020, Google announced a major upgrade to the built-in Google Apps Script IDE, and it now supports console.log(). So, you can now use both:

  1. Logger.log()
  2. console.log()

Happy coding!

How to check if a Unix .tar.gz file is a valid file without uncompressing?

What about just getting a listing of the tarball and throw away the output, rather than decompressing the file?

tar -tzf my_tar.tar.gz >/dev/null

Edited as per comment. Thanks zrajm!

Edit as per comment. Thanks Frozen Flame! This test in no way implies integrity of the data. Because it was designed as a tape archival utility most implementations of tar will allow multiple copies of the same file!

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Towards the second half of Create REST API using ASP.NET MVC that speaks both JSON and plain XML, to quote:

Now we need to accept JSON and XML payload, delivered via HTTP POST. Sometimes your client might want to upload a collection of objects in one shot for batch processing. So, they can upload objects using either JSON or XML format. There's no native support in ASP.NET MVC to automatically parse posted JSON or XML and automatically map to Action parameters. So, I wrote a filter that does it."

He then implements an action filter that maps the JSON to C# objects with code shown.

How to Detect if I'm Compiling Code with a particular Visual Studio version?

This is a little old but should get you started:

//******************************************************************************
// Automated platform detection
//******************************************************************************

// _WIN32 is used by
// Visual C++
#ifdef _WIN32
#define __NT__
#endif

// Define __MAC__ platform indicator
#ifdef macintosh
#define __MAC__
#endif

// Define __OSX__ platform indicator
#ifdef __APPLE__
#define __OSX__
#endif

// Define __WIN16__ platform indicator 
#ifdef _Windows_
#ifndef __NT__
#define __WIN16__
#endif
#endif

// Define Windows CE platform indicator
#ifdef WIN32_PLATFORM_HPCPRO
#define __WINCE__
#endif

#if (_WIN32_WCE == 300) // for Pocket PC
#define __POCKETPC__
#define __WINCE__
//#if (_WIN32_WCE == 211) // for Palm-size PC 2.11 (Wyvern)
//#if (_WIN32_WCE == 201) // for Palm-size PC 2.01 (Gryphon)  
//#ifdef WIN32_PLATFORM_HPC2000 // for H/PC 2000 (Galileo)
#endif

Split Java String by New Line

As an alternative to the previous answers, guava's Splitter API can be used if other operations are to be applied to the resulting lines, like trimming lines or filtering empty lines :

import com.google.common.base.Splitter;

Iterable<String> split = Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings().split(docStr);

Note that the result is an Iterable and not an array.

Member '<method>' cannot be accessed with an instance reference

I had the same issue - although a few years later, some may find a few pointers helpful:

Do not use ‘static’ gratuitously!

Understand what ‘static’ implies in terms of both run-time and compile time semantics (behavior) and syntax.

  • A static entity will be automatically constructed some time before
    its first use.

  • A static entity has one storage location allocated, and that is
    shared by all who access that entity.

  • A static entity can only be accessed through its type name, not
    through an instance of that type.

  • A static method does not have an implicit ‘this’ argument, as does an instance method. (And therefore a static method has less execution
    overhead – one reason to use them.)

  • Think about thread safety when using static entities.

Some details on static in MSDN:

How can I display just a portion of an image in HTML/CSS?

Another alternative is the following, although not the cleanest as it assumes the image to be the only element in a container, such as in this case:

<header class="siteHeader">
  <img src="img" class="siteLogo" />
</header>

You can then use the container as a mask with the desired size, and surround the image with a negative margin to move it into the right position:

.siteHeader{
    width: 50px;
    height: 50px;
    overflow: hidden;
}

.siteHeader .siteLogo{
    margin: -100px;
}

Demo can be seen in this JSFiddle.

Only seems to work in IE>9, and probably all significant versions of all other browsers.

Extracting extension from filename in Python

# try this, it works for anything, any length of extension
# e.g www.google.com/downloads/file1.gz.rs -> .gz.rs

import os.path

class LinkChecker:

    @staticmethod
    def get_link_extension(link: str)->str:
        if link is None or link == "":
            return ""
        else:
            paths = os.path.splitext(link)
            ext = paths[1]
            new_link = paths[0]
            if ext != "":
                return LinkChecker.get_link_extension(new_link) + ext
            else:
                return ""

querySelector, wildcard element match?

Set the tagName as an explicit attribute:

for(var i=0,els=document.querySelectorAll('*'); i<els.length;
          els[i].setAttribute('tagName',els[i++].tagName) );

I needed this myself, for an XML Document, with Nested Tags ending in _Sequence. See JaredMcAteer answer for more details.

document.querySelectorAll('[tagName$="_Sequence"]')

I didn't say it would be pretty :) PS: I would recommend to use tag_name over tagName, so you do not run into interferences when reading 'computer generated', implicit DOM attributes.

CSS-Only Scrollable Table with fixed headers

Inspired by @Purag's answer, here's another flexbox solution:

_x000D_
_x000D_
/* basic settings */_x000D_
table { display: flex; flex-direction: column; width: 200px; }_x000D_
tr { display: flex; }_x000D_
th:nth-child(1), td:nth-child(1) { flex-basis: 35%; }_x000D_
th:nth-child(2), td:nth-child(2) { flex-basis: 65%; }_x000D_
thead, tbody { overflow-y: scroll; }_x000D_
tbody { height: 100px; }_x000D_
_x000D_
/* color settings*/_x000D_
table, th, td { border: 1px solid black; }_x000D_
tr:nth-child(odd) { background: #EEE; }_x000D_
tr:nth-child(even) { background: #AAA; }_x000D_
thead tr:first-child { background: #333; }_x000D_
th:first-child, td:first-child { background: rgba(200,200,0,0.7); }_x000D_
th:last-child, td:last-child { background: rgba(255,200,0,0.7); }
_x000D_
<table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>a_x000D_
        <th>bbbb_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>fooo vsync dynamic_x000D_
        <td>bar_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
      <tr>_x000D_
        <td>a_x000D_
        <td>b_x000D_
  </table>
_x000D_
_x000D_
_x000D_

How to create a DB link between two oracle instances

Create database link NAME connect to USERNAME identified by PASSWORD using 'SID';

Specify SHARED to use a single network connection to create a public database link that can be shared among multiple users. If you specify SHARED, you must also specify the dblink_authentication clause.

Specify PUBLIC to create a public database link available to all users. If you omit this clause, the database link is private and is available only to you.

Connecting to SQL Server Express - What is my server name?

If sql server is installed on your machine, you should check

Programs -> Microsoft SQL Server 20XX -> Configuration Tools -> SQL Server Configuration Manager -> SQL Server Services You'll see "SQL Server (MSSQLSERVER)"

Programs -> Microsoft SQL Server 20XX -> Configuration Tools -> SQL Server Configuration Manager -> SQL Server Network Configuration -> Protocols for MSSQLSERVER -> TCP/IP Make sure it's using port number 1433

If you want to see if the port is open and listening try this from your command prompt... telnet 127.0.0.1 1433

And yes, SQL Express installs use localhost\SQLEXPRESS as the instance name by default.

Spring Data JPA find by embedded object property

If you are using BookId as an combined primary key, then remember to change your interface from:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {

to:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {

And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:

public class QueuedBook implements Serializable {

@EmbeddedId
@NotNull
private BookId bookId;

...

Install msi with msiexec in a Specific Directory

This one worked for me too

msiexec /i "msi path" INSTALLDIR="D:\myfolder" /q

I had tried two other iterations and both installed in the default C:\Program Files

INSTALLDIR="D:\myfolder" /q got it installed on the other drive.

How to repair a serialized string which has been corrupted by an incorrect byte count length?

In my case I was storing serialized data in BLOB field of MySQL DB which apparently wasn't big enough to contain the whole value and truncated it. Such a string obviously could not be unserialized.
Once converted that field to MEDIUMBLOB the problem dissipated. Also it may be needed to switch in table options ROW_FORMAT to DYNAMIC or COMPRESSED.

How to do a simple file search in cmd

dir /b/s *.txt  

searches for all txt file in the directory tree. Before using it just change the directory to root using

cd/

you can also export the list to a text file using

dir /b/s *.exe >> filelist.txt

and search within using

type filelist.txt | find /n "filename"

EDIT 1: Although this dir command works since the old dos days but Win7 added something new called Where

where /r c:\Windows *.exe *.dll

will search for exe & dll in the drive c:\Windows as suggested by @SPottuit you can also copy the output to the clipboard with

where /r c:\Windows *.exe |clip

just wait for the prompt to return and don't copy anything until then.

EDIT 2: If you are searching recursively and the output is big you can always use more to enable paging, it will show -- More -- at the bottom and will scroll to the next page once you press SPACE or moves line by line on pressing ENTER

where /r c:\Windows *.exe |more

For more help try

where/?

How to monitor SQL Server table changes by using c#?

Generally, you'd use Service Broker

That is trigger -> queue -> application(s)

Edit, after seeing other answers:

FYI: "Query Notifications" is built on Service broker

Edit2:

More links

Git error: "Please make sure you have the correct access rights and the repository exists"

Try https instead of ssh. Choose the https option from project home page where you copy the clone url from.

What is Hive: Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

I know I am 3 years late on this thread, however still providing my 2 cents for similar cases in future.

I recently faced the same issue/error in my cluster. The JOB would always get to some 80%+ reduction and fail with the same error, with nothing to go on in the execution logs either. Upon multiple iterations and research I found that among the plethora of files getting loaded some were non-compliant with the structure provided for the base table(table being used to insert data into partitioned table).

Point to be noted here is whenever I executed a select query for a particular value in the partitioning column or created a static partition it worked fine as in that case error records were being skipped.

TL;DR: Check the incoming data/files for inconsistency in the structuring as HIVE follows Schema-On-Read philosophy.

Error : ORA-01704: string literal too long

What are you using when operate with CLOB?

In all events you can do it with PL/SQL

DECLARE
  str varchar2(32767);
BEGIN
  str := 'Very-very-...-very-very-very-very-very-very long string value';
  update t1 set col1 = str;
END;
/

Proof link on SQLFiddle

How do I create a link to add an entry to a calendar?

UPDATE (free for personal use):
HTTPS IS NOW SUPPORTED

While my answer below detailing how-to for each service WILL work, IMO it's much easier now to go with a third-party like AddThisEvent [https://addthisevent.com]. It lets you customize lots of options as well as add to Facebook and more. Unfortunately, they've now made it a paid service for anything other than personal use and do enforce this.

I assume there are other third-party solutions like this one, but I can only speak to this one, and it has worked great for us so far.


For an "Add to my Google Calendar", they used to have a code generator form you could use, but have since taken it down. For more details on Google Calendar links, see squarecandy's answer below.

For Outlook, it's a BIT more complicated, but basically you need to create a .vcs file with the event's data, and just make a link to that file. Step-by-step instructions here.

For an iCal link, you could use a PHP class like this one, or follow this page's instructions on how to create an ics file (iCal file).

Why do we have to specify FromBody and FromUri?

Just addition to above answers ..

[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring

For Ex..

public class GeoPoint
{
    public double Latitude { get; set; } 
    public double Longitude { get; set; }
}

[RoutePrefix("api/Values")]
public ValuesController : ApiController
{
    [Route("{Latitude}/{Longitude}")]
    public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}

Can be called like:

http://localhost/api/values/47.678558/-122.130989

asp.net mvc3 return raw html to view

That looks fine, unless you want to pass it as Model string

public class HomeController : Controller
{
    public ActionResult Index()
    {
        string model = "<HTML></HTML>";
        return View(model);
    }
}

@model string
@{
    ViewBag.Title = "Index";
}

@Html.Raw(Model)

What is the fastest way to transpose a matrix in C++?

Consider each row as a column, and each column as a row .. use j,i instead of i,j

demo: http://ideone.com/lvsxKZ

#include <iostream> 
using namespace std;

int main ()
{
    char A [3][3] =
    {
        { 'a', 'b', 'c' },
        { 'd', 'e', 'f' },
        { 'g', 'h', 'i' }
    };

    cout << "A = " << endl << endl;

    // print matrix A
    for (int i=0; i<3; i++)
    {
        for (int j=0; j<3; j++) cout << A[i][j];
        cout << endl;
    }

    cout << endl << "A transpose = " << endl << endl;

    // print A transpose
    for (int i=0; i<3; i++)
    {
        for (int j=0; j<3; j++) cout << A[j][i];
        cout << endl;
    }

    return 0;
}

Python Database connection Close

You might try turning off pooling, which is enabled by default. See this discussion for more information.

import pyodbc
pyodbc.pooling = False
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
csr.close()
del csr

Difference between HashMap and Map in Java..?

Map is an interface, i.e. an abstract "thing" that defines how something can be used. HashMap is an implementation of that interface.

Git - What is the difference between push.default "matching" and "simple"

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

How to check for an active Internet connection on iOS or macOS?

Using Apple's Reachability code, I created a function that'll check this correctly without you having to include any classes.

Include the SystemConfiguration.framework in your project.

Make some imports:

#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>

Now just call this function:

/*
Connectivity testing code pulled from Apple's Reachability Example: https://developer.apple.com/library/content/samplecode/Reachability
 */
+(BOOL)hasConnectivity {
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
    if (reachability != NULL) {
        //NetworkStatus retVal = NotReachable;
        SCNetworkReachabilityFlags flags;
        if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
            if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
            {
                // If target host is not reachable
                return NO;
            }

            if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
            {
                // If target host is reachable and no connection is required
                //  then we'll assume (for now) that your on Wi-Fi
                return YES;
            }


            if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
            {
                // ... and the connection is on-demand (or on-traffic) if the
                //     calling application is using the CFSocketStream or higher APIs.

                if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                {
                    // ... and no [user] intervention is needed
                    return YES;
                }
            }

            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
            {
                // ... but WWAN connections are OK if the calling application
                //     is using the CFNetwork (CFSocketStream?) APIs.
                return YES;
            }
        }
    }

    return NO;
}

And it's iOS 5 tested for you.

Closure in Java 7

Please see this wiki page for definition of closure.

And this page for closure in Java 8: http://mail.openjdk.java.net/pipermail/lambda-dev/2011-September/003936.html

Also look at this Q&A: Closures in Java 7

How to send authorization header with axios

res.setHeader('Access-Control-Allow-Headers',
            'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');

Blockquote : you have to add OPTIONS & Authorization to the setHeader()

this change has fixed my problem, just give a try!

Update style of a component onScroll in React.js

You can pass a function to the onScroll event on the React element: https://facebook.github.io/react/docs/events.html#ui-events

<ScrollableComponent
 onScroll={this.handleScroll}
/>

Another answer that is similar: https://stackoverflow.com/a/36207913/1255973

How to create a hidden <img> in JavaScript?

You can hide an image using javascript like this:

document.images['imageName'].style.visibility = hidden;

If that isn't what you are after, you need to explain yourself more clearly.

boolean in an if statement

Since you already initialized clearly as bool, I think === operator is not required.

How to close a Tkinter window by pressing a Button?

You can use lambda to pass a reference to the window object as argument to close_window function:

button = Button (frame, text="Good-bye.", command = lambda: close_window(window))

This works because the command attribute is expecting a callable, or callable like object. A lambda is a callable, but in this case it is essentially the result of calling a given function with set parameters.

In essence, you're calling the lambda wrapper of the function which has no args, not the function itself.

How to read strings from a Scanner in a Java console application?

Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
scanner.nextLine(); //This is needed to pick up the new line
System.out.println("Enter employee name:");
name = scanner.nextLine();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();

Calling nextInt() was a problem as it didn't pick up the new line (when you hit enter). So, calling scanner.nextLine() after that does the work.

How to edit default.aspx on SharePoint site without SharePoint Designer

You can always use Sharepoint Solution Generator to create a project and edit in VS2008.

You can find the Generator along with Sharepoint Developer tools.

How to disable <br> tags inside <div> by css?

I used it like this:

@media (max-width: 450px) {
  br {
    display: none;
  }
}

nb: media query via Foundation nb2: this is useful if one of the editor intend to use
tags in his/her copy and you need to deal with it specifically under some conditions—on mobile for example.

How can I URL encode a string in Excel VBA?

No, nothing built-in (until Excel 2013 - see this answer).

There are three versions of URLEncode() in this answer.

  • A function with UTF-8 support. You should probably use this one (or the alternative implementation by Tom) for compatibility with modern requirements.
  • For reference and educational purposes, two functions without UTF-8 support:
    • one found on a third party website, included as-is. (This was the first version of the answer)
    • one optimized version of that, written by me

A variant that supports UTF-8 encoding and is based on ADODB.Stream (include a reference to a recent version of the "Microsoft ActiveX Data Objects" library in your project):

Public Function URLEncode( _
   ByVal StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String
  Dim bytes() As Byte, b As Byte, i As Integer, space As String

  If SpaceAsPlus Then space = "+" Else space = "%20"

  If Len(StringVal) > 0 Then
    With New ADODB.Stream
      .Mode = adModeReadWrite
      .Type = adTypeText
      .Charset = "UTF-8"
      .Open
      .WriteText StringVal
      .Position = 0
      .Type = adTypeBinary
      .Position = 3 ' skip BOM
      bytes = .Read
    End With

    ReDim result(UBound(bytes)) As String

    For i = UBound(bytes) To 0 Step -1
      b = bytes(i)
      Select Case b
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Chr(b)
        Case 32
          result(i) = space
        Case 0 To 15
          result(i) = "%0" & Hex(b)
        Case Else
          result(i) = "%" & Hex(b)
      End Select
    Next i

    URLEncode = Join(result, "")
  End If
End Function

This function was found on freevbcode.com:

Public Function URLEncode( _
   StringToEncode As String, _
   Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String

  Dim TempAns As String
  Dim CurChr As Integer
  CurChr = 1

  Do Until CurChr - 1 = Len(StringToEncode)
    Select Case Asc(Mid(StringToEncode, CurChr, 1))
      Case 48 To 57, 65 To 90, 97 To 122
        TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
      Case 32
        If UsePlusRatherThanHexForSpace = True Then
          TempAns = TempAns & "+"
        Else
          TempAns = TempAns & "%" & Hex(32)
        End If
      Case Else
        TempAns = TempAns & "%" & _
          Right("0" & Hex(Asc(Mid(StringToEncode, _
          CurChr, 1))), 2)
    End Select

    CurChr = CurChr + 1
  Loop

  URLEncode = TempAns
End Function

I've corrected a little bug that was in there.


I would use more efficient (~2× as fast) version of the above:

Public Function URLEncode( _
   StringVal As String, _
   Optional SpaceAsPlus As Boolean = False _
) As String

  Dim StringLen As Long: StringLen = Len(StringVal)

  If StringLen > 0 Then
    ReDim result(StringLen) As String
    Dim i As Long, CharCode As Integer
    Dim Char As String, Space As String

    If SpaceAsPlus Then Space = "+" Else Space = "%20"

    For i = 1 To StringLen
      Char = Mid$(StringVal, i, 1)
      CharCode = Asc(Char)
      Select Case CharCode
        Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
          result(i) = Char
        Case 32
          result(i) = Space
        Case 0 To 15
          result(i) = "%0" & Hex(CharCode)
        Case Else
          result(i) = "%" & Hex(CharCode)
      End Select
    Next i
    URLEncode = Join(result, "")
  End If
End Function

Note that neither of these two functions support UTF-8 encoding.

How best to read a File into List<string>

[Edit]

If you are doing this to trim the beginning of a log file, you can avoid loading the entire file by doing something like this:

// count the number of lines in the file
int count = 0;
using (var sr = new StreamReader("file.txt"))
{
    while (sr.ReadLine() != null) 
        count++;
}

// skip first (LOG_MAX - count) lines
count = LOG_MAX - count;
using (var sr = new StreamReader("file.txt"))
using (var sw = new StreamWriter("output.txt"))
{
    // skip several lines
    while (count > 0 && sr.ReadLine() != null) 
        count--;

    // continue copying
    string line = "";
    while ((line = sr.ReadLine()) != null)
        sw.WriteLine(line);
}

First of all, since File.ReadAllLines loads the entire file into a string array (string[]), copying to a list is redundant.

Second, you must understand that a List is implemented using a dynamic array under the hood. This means that CLR will need to allocate and copy several arrays until it can accommodate the entire file. Since the file is already on disk, you might consider trading speed for memory and working on disk data directly, or processing it in smaller chunks.

  1. If you need to load it entirely in memory, at least try to leave in an array:

     string[] lines = File.ReadAllLines("file.txt");
    
  2. If it really needs to be a List, load lines one by one:

     List<string> lines = new List<string>();
     using (var sr = new StreamReader("file.txt"))
     {
          while (sr.Peek() >= 0)
              lines.Add(sr.ReadLine());
     }
    

    Note: List<T> has a constructor which accepts a capacity parameter. If you know the number of lines in advance, you can prevent multiple allocations by preallocating the array in advance:

     List<string> lines = new List<string>(NUMBER_OF_LINES);
    
  3. Even better, avoid storing the entire file in memory and process it "on the fly":

     using (var sr = new StreamReader("file.txt"))
     {
          string line;
          while ((line = sr.ReadLine()) != null) 
          {
              // process the file line by line
          }
     }
    

ImportError: Cannot import name X

I just got this error too, for a different reason...

from my_sub_module import my_function

The main script had Windows line endings. my_sub_module had UNIX line endings. Changing them to be the same fixed the problem. They also need to have the same character encoding.

How can I use jQuery to make an input readonly?

Perhaps it's meaningful to also add that

$('#fieldName').prop('readonly',false);

can be used as a toggle option..

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

If you already have MinGW installed in Windows 7, just simply do the following:

  1. Make another copy of C:\MinGW\bin\mingw32-make.exe file in the same folder.
  2. Rename the file name from mingw32-make.exe to make.exe.
  3. Run make command again.

Tested working in my laptop for above steps.

How to return JSON with ASP.NET & jQuery

Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.

Of course, it's then up to you to do what you need to do on the client side.

I would be thinking something like this:

[WebMethod]
public static List GetProducts()
{
   var products  = context.GetProducts().ToList();   
   return products;
}

There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data

Smooth scroll to div id jQuery

You need to animate the html, body

DEMO http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});

Input widths on Bootstrap 3

ASP.net MVC go to Content- Site.css and remove or comment this line:

input,
select,
textarea {
    /*max-width: 280px;*/
}

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

Varying is an alias for varchar, so no difference, see documentation :)

The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1). If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

git: can't push (unpacker error) related to permission issues

This problem can also occur after Ubuntu upgrades that require a reboot.

If the file /var/run/reboot-required exists, do or schedule a restart.

Reverse each individual word of "Hello World" string with Java

Taking into account that the separator can be more than one space/tab and that we want to preserve them:

public static String reverse(String string)
{
    StringBuilder sb = new StringBuilder(string.length());
    StringBuilder wsb = new StringBuilder(string.length());
    for (int i = 0; i < string.length(); i++)
    {
        char c = string.charAt(i);
        if (c == '\t' || c == ' ')
        {
            if (wsb.length() > 0)
            {
                sb.append(wsb.reverse().toString());
                wsb = new StringBuilder(string.length() - sb.length());
            }
            sb.append(c);
        }
        else
        {
            wsb.append(c);
        }
    }
    if (wsb.length() > 0)
    {
        sb.append(wsb.reverse().toString());
    }
    return sb.toString();

}

Get all column names of a DataTable into string array using (LINQ/Predicate)

I'd suggest using such extension method:

public static class DataColumnCollectionExtensions
{
    public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
    {
        return source.Cast<DataColumn>();
    }
}

And therefore:

string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();

You may also implement one more extension method for DataTable class to reduce code:

public static class DataTableExtensions
{
    public static IEnumerable<DataColumn> GetColumns(this DataTable source)
    {
        return source.Columns.AsEnumerable();
    }
}

And use it as follows:

string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

Recently I came across the same issue. I was able to ssh to my pi on my network, but not from outside my home network.

I had already:

  • installed and tested ssh on my home network.
  • Set a static IP for my pi.
  • Set up a Dynamic DNS service and installed the software on my pi. I referenced these instructions for setting up the static ip, and there are many more instructional resources out there.

Also, I set up port forward on my router for hosting a web site and I had even port forward port 22 to my pi's static IP for ssh, but I left the field blank where you specify the application you are performing the port forwarding for on the router. Anyway, I added 'ssh' into this field and, VOILA! A working ssh connection from anywhere to my pi.

I'll write out my router's port forwarding settings.

(ApplicationTextField)_ssh     (external port)_22     (Internal Port)_22     (Protocal)_Both     (To IP Address)_192.168.1.###     (Enabled)_checkBox

Port forwarding settings can be different for different routers though, so look up directions for your router.

Now, when I am outside of my home network I connect to my pi by typing:

ssh pi@[hostname]

Then I am able to input my password and connect.

how to find seconds since 1970 in java

The difference you see is most likely because you don't zero the hour, minute, second and milliseconds fields of your Calendar instances: Calendar.getInstance() gives you the current date and time, just like new Date() or System.currentTimeMillis().

Note that the month field of Calendar is zero-based, i.e. January is 0, not 1.

Also, don't prefix numbers with zero, this might look nice and it even works till you reach 8: 08 isn't a valid numeral in Java. Prefixing numerals with zero makes the compiler assume you're defining them as octal numerals which only works up to 07 (for single digits).

Just drop calendar1 completely (1970-01-01 00:00:00'000 is the begin of the epoch, i.e. zero anyway) and do this:

public long returnSeconds(int year, int month, int date) {
    final Calendar cal = Calendar.getInstance();
    cal.set(year, month, date, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTimeInMillis() / 1000;
}

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

If you want to find interactively logged on users, I found a great tip here :https://p0w3rsh3ll.wordpress.com/2012/02/03/get-logged-on-users/ (Win32_ComputerSystem did not help me)

$explorerprocesses = @(Get-WmiObject -Query "Select * FROM Win32_Process WHERE Name='explorer.exe'" -ErrorAction SilentlyContinue)
If ($explorerprocesses.Count -eq 0)
{
    "No explorer process found / Nobody interactively logged on"
}
Else
{
    ForEach ($i in $explorerprocesses)
    {
        $Username = $i.GetOwner().User
        $Domain = $i.GetOwner().Domain
        Write-Host "$Domain\$Username logged on since: $($i.ConvertToDateTime($i.CreationDate))"
    }
}

Twitter Bootstrap date picker

Some people posted the link to this bootstrap-datepicker.js implementation. I used that one in the following way, it works with Bootstrap 3.

This is the markup I used:

<div class="input-group date col-md-3" data-date-format="dd-mm-yyyy" data-date="01-01-2014">                        
    <input id="txtHomeLoanStartDate" class="form-control" type="text" readonly="" value="01-01-2014" size="14" />
    <span class="input-group-addon add-on">
        <span class="glyphicon glyphicon-calendar"</span>
    </span>
</div>

This is the javascript:

$('.date').datepicker();

I also included the javascript file downloaded from the link above, along with it's css file, and of course, you should remove any bootstrap grid classes like the col-md-3 to suit your needs.

How to detect a route change in Angular?

Router 3.0.0-beta.2 should be

this.router.events.subscribe(path => {
  console.log('path = ', path);
});

How to use LDFLAGS in makefile

In more complicated build scenarios, it is common to break compilation into stages, with compilation and assembly happening first (output to object files), and linking object files into a final executable or library afterward--this prevents having to recompile all object files when their source files haven't changed. That's why including the linking flag -lm isn't working when you put it in CFLAGS (CFLAGS is used in the compilation stage).

The convention for libraries to be linked is to place them in either LOADLIBES or LDLIBS (GNU make includes both, but your mileage may vary):

LDLIBS=-lm

This should allow you to continue using the built-in rules rather than having to write your own linking rule. For other makes, there should be a flag to output built-in rules (for GNU make, this is -p). If your version of make does not have a built-in rule for linking (or if it does not have a placeholder for -l directives), you'll need to write your own:

client.o: client.c
    $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ $<

client: client.o
    $(CC) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $@

Custom CSS Scrollbar for Firefox

As of late 2018, there is now limited customization available in Firefox!

See these answers:

And this for background info: https://bugzilla.mozilla.org/show_bug.cgi?id=1460109


There's no Firefox equivalent to ::-webkit-scrollbar and friends.

You'll have to stick with JavaScript.

Plenty of people would like this feature, see: https://bugzilla.mozilla.org/show_bug.cgi?id=77790


As far as JavaScript replacements go, you can try:

In SQL, is UPDATE always faster than DELETE+INSERT?

The bigger the table (number of and size of columns) the more expensive it becomes to delete and insert rather than update. Because you have to pay the price of UNDO and REDO. DELETEs consume more UNDO space than UPDATEs, and your REDO contains twice as many statements as are necessary.

Besides, it is plain wrong from a business point of view. Consider how much harder it would be to understand a notional audit trail on that table.


There are some scenarios involving bulk updates of all the rows in a table where it is faster to create a new table using CTAS from the old table (applying the update in the the projection of the SELECT clause), dropping the old table and renaming the new table. The side-effects are creating indexes, managing constraints and renewing privileges, but it is worth considering.

Changing variable names with Python for loops

It looks like you want to use a list instead:

group=[]
for i in range(3):
     group[i]=self.getGroup(selected, header+i)

Can someone explain how to implement the jQuery File Upload plugin?

Droply.js is perfect for this. It's simple and comes pre-packaged with a demo site that works out of the box.

How to display pdf in php

easy if its pdf or img use

return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));

Rename computer and join to domain in one step with PowerShell

You can just use Add-Computer, there is a parameter for "-NewName"

Example: Add-Computer -DomainName MYLAB.Local -ComputerName TARGETCOMPUTER -newname NewTARGETCOMPUTER

You might want to check also the parameter "-OPTIONS"

http://technet.microsoft.com/en-us/library/hh849798.aspx

Material UI and Grid system

I hope this is not too late to give a response.

I was also looking for a simple, robust, flexible and highly customizable bootstrap like react grid system to use in my projects.

The best I know of is react-pure-grid https://www.npmjs.com/package/react-pure-grid

react-pure-grid gives you the power to customize every aspect of your grid system, while at the same time it has built in defaults which probably suits any project

Usage

npm install react-pure-grid --save

-

import {Container, Row, Col} from 'react-pure-grid';

const App = () => (
      <Container>
        <Row>
          <Col xs={6} md={4} lg={3}>Hello, world!</Col>
        </Row>
        <Row>
            <Col xsOffset={5} xs={7}>Welcome!</Col>
        </Row>
      </Container>
);

How to change the color of winform DataGridview header?

It can be done.

From the designer: Select your DataGridView Open the Properties Navigate to ColumnHeaderDefaultCellStype Hit the button to edit the style.

You can also do it programmatically:

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Purple;

Hope that helps!

Should ol/ul be inside <p> or outside?

The short answer is that ol elements are not legally allowed inside p elements.

To see why, let's go to the spec! If you can get comfortable with the HTML spec, it will answer many of your questions and curiosities. You want to know if an ol can live inside a p. So…

4.5.1 The p element:

Categories: Flow content, Palpable content.
Content model: Phrasing content.


4.5.5 The ol element:

Categories: Flow content.
Content model: Zero or more li and script-supporting elements.

The first part says that p elements can only contain phrasing content (which are “inline” elements like span and strong).

The second part says ols are flow content (“block” elements like p and div). So they can't be used inside a p.


ols and other flow content can be used in in some other elements like div:

4.5.13 The div element:

Categories: Flow content, Palpable content.
Content model: Flow content.

How to check if mysql database exists

Be careful when checking for existence with a like statement!

If in a series of unfortunate events your variable ends up being empty, and you end up executing this:

SHOW DATABASES like '' -- dangerous!

It will return ALL databases, thus telling the calling script that it exists since some rows were returned.

It's much safer and better practice to use an "=" equal sign to test for existence.

The correct and safe way to test for existence should be:

SHOW DATABASES WHERE `database` = 'xxxxx' -- safe way to test for existence

Note that you have to wrap the column name database with backticks, it can't use relaxed syntax in this case.

This way, if the code creating the variable 'xxxxx' returned blank, then SHOW DATABASES will not return ALL databases, but will return an empty set.

Detailed 500 error message, ASP + IIS 7.5

In web.config under

<system.webServer>

replace (or add) the line

<httpErrors errorMode="Detailed"></httpErrors>

with

<httpErrors existingResponse="PassThrough" errorMode="Detailed"></httpErrors>

This is because by default IIS7 intercepts HTTP status codes such as 4xx and 5xx generated by applications further up the pipeline.

Next, enable "Send Errors to Browser" under the "ASP" section, and under "Error Pages / Edit Feature Settings", select "Detailed errors".

Also, give Write permissions on the website folder to the IIS_IUSRS builtin group.

How to specify multiple return types using type-hints

The statement def foo(client_id: str) -> list or bool: when evaluated is equivalent to def foo(client_id: str) -> list: and will therefore not do what you want.

The native way to describe a "either A or B" type hint is Union (thanks to Bhargav Rao):

def foo(client_id: str) -> Union[list, bool]:

I do not want to be the "Why do you want to do this anyway" guy, but maybe having 2 return types isn't what you want:

If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation. You can also indicate that None could be returned with Optional[list]

How can I post data as form data instead of a request payload?

This isn't a direct answer, but rather a slightly different design direction:

Do not post the data as a form, but as a JSON object to be directly mapped to server-side object, or use REST style path variable

Now I know neither option might be suitable in your case since you're trying to pass a XSRF key. Mapping it into a path variable like this is a terrible design:

http://www.someexample.com/xsrf/{xsrfKey}

Because by nature you would want to pass xsrf key to other path too, /login, /book-appointment etc. and you don't want to mess your pretty URL

Interestingly adding it as an object field isn't appropriate either, because now on each of json object you pass to server you have to add the field

{
  appointmentId : 23,
  name : 'Joe Citizen',
  xsrf : '...'
}

You certainly don't want to add another field on your server-side class which does not have a direct semantic association with the domain object.

In my opinion the best way to pass your xsrf key is via a HTTP header. Many xsrf protection server-side web framework library support this. For example in Java Spring, you can pass it using X-CSRF-TOKEN header.

Angular's excellent capability of binding JS object to UI object means we can get rid of the practice of posting form all together, and post JSON instead. JSON can be easily de-serialized into server-side object and support complex data structures such as map, arrays, nested objects, etc.

How do you post array in a form payload? Maybe like this:

shopLocation=downtown&daysOpen=Monday&daysOpen=Tuesday&daysOpen=Wednesday

or this:

shopLocation=downtwon&daysOpen=Monday,Tuesday,Wednesday

Both are poor design..

Remove all files except some from a directory

I prefer to use sub query list:

rm -r `ls | grep -v "textfile.txt\|backup.tar.gz\|script.php\|database.sql\|info.txt"`

-v, --invert-match select non-matching lines

\| Separator

How to get the number of threads in a Java process

Generic solution that doesn't require a GUI like jconsole (doesn't work on remote terminals), ps works for non-java processes, doesn't require a JVM installed.

ps -o nlwp <pid>

How do I get the application exit code from a Windows command line?

At one point I needed to accurately push log events from Cygwin to the Windows Event log. I wanted the messages in WEVL to be custom, have the correct exit code, details, priorities, message, etc. So I created a little Bash script to take care of this. Here it is on GitHub, logit.sh.

Some excerpts:

usage: logit.sh [-h] [-p] [-i=n] [-s] <description>
example: logit.sh -p error -i 501 -s myscript.sh "failed to run the mount command"

Here is the temporary file contents part:

LGT_TEMP_FILE="$(mktemp --suffix .cmd)"
cat<<EOF>$LGT_TEMP_FILE
    @echo off
    set LGT_EXITCODE="$LGT_ID"
    exit /b %LGT_ID%
EOF
unix2dos "$LGT_TEMP_FILE"

Here is a function to to create events in WEVL:

__create_event () {
    local cmd="eventcreate /ID $LGT_ID /L Application /SO $LGT_SOURCE /T $LGT_PRIORITY /D "
    if [[ "$1" == *';'* ]]; then
        local IFS=';'
        for i in "$1"; do
            $cmd "$i" &>/dev/null
        done
    else
        $cmd "$LGT_DESC" &>/dev/null
    fi
}

Executing the batch script and calling on __create_event:

cmd /c "$(cygpath -wa "$LGT_TEMP_FILE")"
__create_event

How to generate and manually insert a uniqueidentifier in sql server?

ApplicationId must be of type UniqueIdentifier. Your code works fine if you do:

DECLARE @TTEST TABLE
(
  TEST UNIQUEIDENTIFIER
)

DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();

INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);

SELECT * FROM @TTEST

Therefore I would say it is safe to assume that ApplicationId is not the correct data type.

How to have css3 animation to loop forever

Whilst Elad's solution will work, you can also do it inline:

   -moz-animation: fadeinphoto 7s 20s infinite;
-webkit-animation: fadeinphoto 7s 20s infinite;
     -o-animation: fadeinphoto 7s 20s infinite;
        animation: fadeinphoto 7s 20s infinite;

How can I insert data into Database Laravel?

make sure you use the POST to insert the data. Actually you were using GET.

Deserializing JSON data to C# using JSON.NET

Building off of bbant's answer, this is my complete solution for deserializing JSON from a remote URL.

using Newtonsoft.Json;
using System.Net.Http;

namespace Base
{
    public class ApiConsumer<T>
    {
        public T data;
        private string url;

        public CalendarApiConsumer(string url)
        {
            this.url = url;
            this.data = getItems();
        }

        private T getItems()
        {
            T result = default(T);
            HttpClient client = new HttpClient();

            // This allows for debugging possible JSON issues
            var settings = new JsonSerializerSettings
            {
                Error = (sender, args) =>
                {
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        System.Diagnostics.Debugger.Break();
                    }
                }
            };

            using (HttpResponseMessage response = client.GetAsync(this.url).Result)
            {
                if (response.IsSuccessStatusCode)
                {
                    result = JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result, settings);
                }
            }
            return result;
        }
    }
}

Usage would be like:

ApiConsumer<FeedResult> feed = new ApiConsumer<FeedResult>("http://example.info/feeds/feeds.aspx?alt=json-in-script");

Where FeedResult is the class generated using the Xamasoft JSON Class Generator

Here is a screenshot of the settings I used, allowing for weird property names which the web version could not account for.

Xamasoft JSON Class Generator

How do I print to the debug output window in a Win32 app?

Your Win32 project is likely a GUI project, not a console project. This causes a difference in the executable header. As a result, your GUI project will be responsible for opening its own window. That may be a console window, though. Call AllocConsole() to create it, and use the Win32 console functions to write to it.

Target elements with multiple classes, within one rule

Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.

The following:

.blue-border, .background {
    border: 1px solid #00f;
    background: #fff;
}

is for when you want to add styles to elements that have either the blue-border or background class, for example:

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

would all get a blue border and white background applied to them.

However, the accepted answer is different.

.blue-border.background {
    border: 1px solid #00f;
    background: #fff;
}

This applies the styles to elements that have both classes so in this example only the <div> with both classes should get the styles applied (in browsers that interpret the CSS properly):

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.

"Line contains NULL byte" in CSV reader (Python)

pandas.read_csv now handles the different UTF encoding when reading/writing and therefore can deal directly with null bytes

data = pd.read_csv(file, encoding='utf-16')

see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

Find and replace Android studio

I think the shortcut that you're looking for is:

Ctrl+Shift+R on Windows and Linux/Ubuntu

Cmd+Shift+R on Mac OS X

ref: source

Loop until a specific user input

Your code won't work because you haven't assigned anything to n before you first use it. Try this:

def oracle():
    n = None
    while n != 'Correct':
        # etc...

A more readable approach is to move the test until later and use a break:

def oracle():
    guess = 50

    while True:
        print 'Current number = {0}'.format(guess)
        n = raw_input("lower, higher or stop?: ")
        if n == 'stop':
            break
        # etc...

Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.

Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.

Generating random numbers in Objective-C

Better to use arc4random_uniform. However, this isn't available below iOS 4.3. Luckily iOS will bind this symbol at runtime, not at compile time (so don't use the #if preprocessor directive to check if it's available).

The best way to determine if arc4random_uniform is available is to do something like this:

#include <stdlib.h>

int r = 0;
if (arc4random_uniform != NULL)
    r = arc4random_uniform (74);
else
    r = (arc4random() % 74);

.bashrc: Permission denied

If you can't access the file and your os is any linux distro or mac os x then either of these commands should work:

sudo nano .bashrc

chmod 777 .bashrc 

it is worthless

Run jar file in command prompt

Try this

java -jar <jar-file-name>.jar

Error: Unexpected value 'undefined' imported by the module

This can be caused by multiple scenarios like

  1. Missing commas
imports: [
    BrowserModule
   ,routing <= Missing Comma
   ,FeatureComponentsModule
  ],
  1. Double Commas
imports: [
    BrowserModule, 
   ,routing <=Double Comma
   ,FeatureComponentsModule
  ],
  1. Exporting Nothing from the Module
  2. Syntax errors
  3. Typo Errors
  4. Semicolons inside Objects, Arrays
  5. Incorrect import Statements

Bootstrap 4 File Input

Without JQuery

HTML:

<INPUT type="file" class="custom-file-input"  onchange="return onChangeFileInput(this);">

JS:

function onChangeFileInput(elem){
  var sibling = elem.nextSibling.nextSibling;
  sibling.innerHTML=elem.value;
  return true;
}

KliG

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

Just to give you an another option, you could use https://sourceforge.net/projects/dd2vmdk/ as well. dd2vmdk is a *nix-based program that allows you to mount raw disk images (created by dd, dcfldd, dc3dd, ftk imager, etc) by taking the raw image, analyzing the master boot record (physical sector 0), and getting specific information that is need to create a vmdk file.

Personally, imo Qemu and the Zapotek's raw2vmdk tools are the best overall options to convert dd to vmdks.

Disclosure: I am the author of this project.

How to compare each item in a list with the rest, only once?

This code will count frequency and remove duplicate elements:

from collections import Counter

str1='the cat sat on the hat hat'

int_list=str1.split();

unique_list = []
for el in int_list:

    if el not in unique_list:
        unique_list.append(el)
    else:
        print "Element already in the list"

print unique_list

c=Counter(int_list)

c.values()

c.keys()

print c

How to add a custom button to the toolbar that calls a JavaScript function?

You can add the button image as follows:

CKEDITOR.plugins.add('showtime',   //name of our plugin
{    
    requires: ['dialog'], //requires a dialog window
    init:function(a) {
  var b="showtime";
  var c=a.addCommand(b,new CKEDITOR.dialogCommand(b));
  c.modes={wysiwyg:1,source:1}; //Enable our plugin in both modes
  c.canUndo=true;
 
  //add new button to the editor
  a.ui.addButton("showtime",
  {
   label:'Show current time',
   command:b,
   icon:this.path+"showtime.png"   //path of the icon
  });
  CKEDITOR.dialog.add(b,this.path+"dialogs/ab.js") //path of our dialog file
 }
});

Here is the actual plugin with all steps described.