Programs & Examples On #Init

May refer to Linux Init - the parent of all processes, which primary role is to create processes from a script stored in the file /etc/inittab. Or abbreviation of initialization - giving variables a "starting" value.

How to return a value from __init__ in Python?

Just wanted to add, you can return classes in __init__

@property
def failureException(self):
    class MyCustomException(AssertionError):
        def __init__(self_, *args, **kwargs):
            *** Your code here ***
            return super().__init__(*args, **kwargs)

    MyCustomException.__name__ = AssertionError.__name__
    return MyCustomException

The above method helps you implement a specific action upon an Exception in your test

When is the init() function run?

Yes assuming you have this:

var WhatIsThe = AnswerToLife()

func AnswerToLife() int {
    return 42
}

func init() {
    WhatIsThe = 0
}

func main() {
    if WhatIsThe == 0 {
        fmt.Println("It's all a lie.")
    }
}

AnswerToLife() is guaranteed to run before init() is called, and init() is guaranteed to run before main() is called.

Keep in mind that init() is always called, regardless if there's main or not, so if you import a package that has an init function, it will be executed.

Additionally, you can have multiple init() functions per package; they will be executed in the order they show up in the file (after all variables are initialized of course). If they span multiple files, they will be executed in lexical file name order (as pointed out by @benc):

It seems that init() functions are executed in lexical file name order. The Go spec says "build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler". It seems that go build works this way.


A lot of the internal Go packages use init() to initialize tables and such, for example https://github.com/golang/go/blob/883bc6/src/compress/bzip2/bzip2.go#L480

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

How to fix "Attempted relative import in non-package" even with __init__.py

Old thread. I found out that adding an __all__= ['submodule', ...] to the __init__.py file and then using the from <CURRENT_MODULE> import * in the target works fine.

What is the use of the init() usage in JavaScript?

NB. Constructor function names should start with a capital letter to distinguish them from ordinary functions, e.g. MyClass instead of myClass.

Either you can call init from your constructor function:

var myObj = new MyClass(2, true);

function MyClass(v1, v2) 
{
    // ...

    // pub methods
    this.init = function() {
        // do some stuff        
    };

    // ...

    this.init(); // <------------ added this
}

Or more simply you could just copy the body of the init function to the end of the constructor function. No need to actually have an init function at all if it's only called once.

How to run a command as a specific user in an init script?

I usually do it the way that you are doing it (i.e. sudo -u username command). But, there is also the 'djb' way to run a daemon with privileges of another user. See: http://thedjbway.b0llix.net/daemontools/uidgid.html

How to increment a number by 2 in a PHP For Loop

You should use other variable:

 $m=0; 
 for($n=1; $n<=8; $n++): 
  $n = $n + $m;
  $m++;
  echo '<p>'. $n .'</p>';
 endfor;

How to do a recursive find/replace of a string with awk or sed?

If you have access to node you can do a npm install -g rexreplace and then

rexreplace 'subdomainA.example.com' 'subdomainB.example.com' /home/www/**/*.*

How can I get a list of Git branches, ordered by most recent commit?

Use the --sort=-committerdate option of git for-each-ref;

Also available since Git 2.7.0 for git branch:

Basic Usage:

git for-each-ref --sort=-committerdate refs/heads/

# Or using git branch (since version 2.7.0)
git branch --sort=-committerdate  # DESC
git branch --sort=committerdate  # ASC

Result:

Result

Advanced Usage:

git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'

Result:

Result

Shell script to capture Process ID and kill it if exist

This should kill all processes matching the grep that you are permitted to kill.

-9 means "Kill all processes you can kill".

kill -9 $(ps -ef | grep [s]yncapp | awk '{print $2}')

How to make flutter app responsive according to different screen size?

My approach to the problem is similar to the way datayeah did it. I had a lot of hardcoded width and height values and the app looked fine on a specific device. So I got the screen height of the device and just created a factor to scale the hardcoded values.

double heightFactor = MediaQuery.of(context).size.height/708

where 708 is the height of the specific device.

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

declare @T1 table(ID int, ReceivedDate datetime, [type] varchar(10))
declare @T2 table(ID int, ReceivedDate datetime, [type] varchar(10))

insert into @T1 values(1, '20010101', '1')
insert into @T1 values(2, '20010102', '1')
insert into @T1 values(3, '20010103', '1')

insert into @T2 values(10, '20010101', '2')
insert into @T2 values(20, '20010102', '2')
insert into @T2 values(30, '20010103', '2')

;with cte1 as
(
  select *,
    row_number() over(order by ReceivedDate desc) as rn
  from @T1
  where [type] = '1'
),
cte2 as
(
  select *,
    row_number() over(order by ReceivedDate desc) as rn
  from @T2
  where [type] = '2'
)
select *
from cte1
where rn <= 2
union all
select *
from cte2
where rn <= 2

Sockets: Discover port availability using Java

For Java 7 you can use try-with-resource for more compact code:

private static boolean available(int port) {
    try (Socket ignored = new Socket("localhost", port)) {
        return false;
    } catch (IOException ignored) {
        return true;
    }
}

How to get all keys with their values in redis

KEYS command should not be used on Redis production instances if you have a lot of keys, since it may block the Redis event loop for several seconds.

I would generate a dump (bgsave), and then use the following Python package to parse it and extract the data:

https://github.com/sripathikrishnan/redis-rdb-tools

You can have json output, or customize your own output in Python.

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Extract a page from a pdf as a jpeg

Here is a solution which requires no additional libraries and is very fast. This was found from: https://nedbatchelder.com/blog/200712/extracting_jpgs_from_pdfs.html# I have added the code in a function to make it more convenient.

def convert(filepath):
    with open(filepath, "rb") as file:
        pdf = file.read()

    startmark = b"\xff\xd8"
    startfix = 0
    endmark = b"\xff\xd9"
    endfix = 2
    i = 0

    njpg = 0
    while True:
        istream = pdf.find(b"stream", i)
        if istream < 0:
            break
        istart = pdf.find(startmark, istream, istream + 20)
        if istart < 0:
            i = istream + 20
            continue
        iend = pdf.find(b"endstream", istart)
        if iend < 0:
            raise Exception("Didn't find end of stream!")
        iend = pdf.find(endmark, iend - 20)
        if iend < 0:
            raise Exception("Didn't find end of JPG!")

        istart += startfix
        iend += endfix
        jpg = pdf[istart:iend]
        newfile = "{}jpg".format(filepath[:-3])
        with open(newfile, "wb") as jpgfile:
            jpgfile.write(jpg)

        njpg += 1
        i = iend

        return newfile

Call convert with the pdf path as the argument and the function will create a .jpg file in the same directory

JS jQuery - check if value is in array

The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects. we can create a prototype for this purpose

Array.prototype.has_element = function(element) {
    return $.inArray( element, this) !== -1;
};

And then use it like this

var numbers= [1, 2, 3, 4];
numbers.has_element(3) => true
numbers.has_element(10) => false

See the Demo below

_x000D_
_x000D_
Array.prototype.has_element = function(element) {_x000D_
  return $.inArray(element, this) !== -1;_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
var numbers = [1, 2, 3, 4];_x000D_
console.log(numbers.has_element(3));_x000D_
console.log(numbers.has_element(10));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How can I decode HTML characters in C#?

As @CQ says, you need to use HttpUtility.HtmlDecode, but it's not available in a non-ASP .NET project by default.

For a non-ASP .NET application, you need to add a reference to System.Web.dll. Right-click your project in Solution Explorer, select "Add Reference", then browse the list for System.Web.dll.

Now that the reference is added, you should be able to access the method using the fully-qualified name System.Web.HttpUtility.HtmlDecode or insert a using statement for System.Web to make things easier.

Why do you need to put #!/bin/bash at the beginning of a script file?

It's called a shebang. In unix-speak, # is called sharp (like in music) or hash (like hashtags on twitter), and ! is called bang. (You can actually reference your previous shell command with !!, called bang-bang). So when put together, you get haSH-BANG, or shebang.

The part after the #! tells Unix what program to use to run it. If it isn't specified, it will try with bash (or sh, or zsh, or whatever your $SHELL variable is) but if it's there it will use that program. Plus, # is a comment in most languages, so the line gets ignored in the subsequent execution.

Count unique values in a column in Excel

You can do the following steps:

  1. First isolate the column (by inserting a blank column before and/or after the column you want to count the unique values if there are any adjacent columns;

  2. Then select the whole column, go to 'Data' > 'Advanced Filter' and check the checkbox 'Unique records only'. This will hide all non-unique records so you can count the unique ones by selecting the whole column.

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

For install with zsh and Homebrew:

brew install nvm

Then Add the following to ~/.zshrc or your desired shell configuration file:

export NVM_DIR="$HOME/.nvm"
. "/usr/local/opt/nvm/nvm.sh"

Then install a node version and use it.

nvm install 7.10.1
nvm use 7.10.1

What are the differences between the BLOB and TEXT datatypes in MySQL?

Blob datatypes stores binary objects like images while text datatypes stores text objects like articles of webpages

How to use LINQ Distinct() with multiple fields

public List<ItemCustom2> GetBrandListByCat(int id)
    {

        var OBJ = (from a in db.Items
                   join b in db.Brands on a.BrandId equals b.Id into abc1
                   where (a.ItemCategoryId == id)
                   from b in abc1.DefaultIfEmpty()
                   select new
                   {
                       ItemCategoryId = a.ItemCategoryId,
                       Brand_Name = b.Name,
                       Brand_Id = b.Id,
                       Brand_Pic = b.Pic,

                   }).Distinct();


        List<ItemCustom2> ob = new List<ItemCustom2>();
        foreach (var item in OBJ)
        {
            ItemCustom2 abc = new ItemCustom2();
            abc.CategoryId = item.ItemCategoryId;
            abc.BrandId = item.Brand_Id;
            abc.BrandName = item.Brand_Name;
            abc.BrandPic = item.Brand_Pic;
            ob.Add(abc);
        }
        return ob;

    }

convert '1' to '0001' in JavaScript

I use the following object:

function Padder(len, pad) {
  if (len === undefined) {
    len = 1;
  } else if (pad === undefined) {
    pad = '0';
  }

  var pads = '';
  while (pads.length < len) {
    pads += pad;
  }

  this.pad = function (what) {
    var s = what.toString();
    return pads.substring(0, pads.length - s.length) + s;
  };
}

With it you can easily define different "paddings":

var zero4 = new Padder(4);
zero4.pad(12); // "0012"
zero4.pad(12345); // "12345"
zero4.pad("xx"); // "00xx"
var x3 = new Padder(3, "x");
x3.pad(12); // "x12"

SQL RANK() versus ROW_NUMBER()

ROW_NUMBER : Returns a unique number for each row starting with 1. For rows that have duplicate values,numbers are arbitarily assigned.

Rank : Assigns a unique number for each row starting with 1,except for rows that have duplicate values,in which case the same ranking is assigned and a gap appears in the sequence for each duplicate ranking.

PHP Fatal error: Using $this when not in object context

$foobar = new foobar; put the class foobar in $foobar, not the object. To get the object, you need to add parenthesis: $foobar = new foobar();

Your error is simply that you call a method on a class, so there is no $this since $this only exists in objects.

EditText underline below text property

You can change the color of EditText programmatically just using this line of code easily:

edittext.setBackgroundTintList(ColorStateList.valueOf(yourcolor));

How to disable HTML button using JavaScript?

The official way to set the disabled attribute on an HTMLInputElement is this:

var input = document.querySelector('[name="myButton"]');
// Without querySelector API
// var input = document.getElementsByName('myButton').item(0);

// disable
input.setAttribute('disabled', true);
// enable
input.removeAttribute('disabled');

While @kaushar's answer is sufficient for enabling and disabling an HTMLInputElement, and is probably preferable for cross-browser compatibility due to IE's historically buggy setAttribute, it only works because Element properties shadow Element attributes. If a property is set, then the DOM uses the value of the property by default rather than the value of the equivalent attribute.

There is a very important difference between properties and attributes. An example of a true HTMLInputElement property is input.value, and below demonstrates how shadowing works:

_x000D_
_x000D_
var input = document.querySelector('#test');_x000D_
_x000D_
// the attribute works as expected_x000D_
console.log('old attribute:', input.getAttribute('value'));_x000D_
// the property is equal to the attribute when the property is not explicitly set_x000D_
console.log('old property:', input.value);_x000D_
_x000D_
// change the input's value property_x000D_
input.value = "My New Value";_x000D_
_x000D_
// the attribute remains there because it still exists in the DOM markup_x000D_
console.log('new attribute:', input.getAttribute('value'));_x000D_
// but the property is equal to the set value due to the shadowing effect_x000D_
console.log('new property:', input.value);
_x000D_
<input id="test" type="text" value="Hello World" />
_x000D_
_x000D_
_x000D_

That is what it means to say that properties shadow attributes. This concept also applies to inherited properties on the prototype chain:

_x000D_
_x000D_
function Parent() {_x000D_
  this.property = 'ParentInstance';_x000D_
}_x000D_
_x000D_
Parent.prototype.property = 'ParentPrototype';_x000D_
_x000D_
// ES5 inheritance_x000D_
Child.prototype = Object.create(Parent.prototype);_x000D_
Child.prototype.constructor = Child;_x000D_
_x000D_
function Child() {_x000D_
  // ES5 super()_x000D_
  Parent.call(this);_x000D_
_x000D_
  this.property = 'ChildInstance';_x000D_
}_x000D_
_x000D_
Child.prototype.property = 'ChildPrototype';_x000D_
_x000D_
logChain('new Parent()');_x000D_
_x000D_
log('-------------------------------');_x000D_
logChain('Object.create(Parent.prototype)');_x000D_
_x000D_
log('-----------');_x000D_
logChain('new Child()');_x000D_
_x000D_
log('------------------------------');_x000D_
logChain('Object.create(Child.prototype)');_x000D_
_x000D_
// below is for demonstration purposes_x000D_
// don't ever actually use document.write(), eval(), or access __proto___x000D_
function log(value) {_x000D_
  document.write(`<pre>${value}</pre>`);_x000D_
}_x000D_
_x000D_
function logChain(code) {_x000D_
  log(code);_x000D_
_x000D_
  var object = eval(code);_x000D_
_x000D_
  do {_x000D_
    log(`${object.constructor.name} ${object instanceof object.constructor ? 'instance' : 'prototype'} property: ${JSON.stringify(object.property)}`);_x000D_
    _x000D_
    object = object.__proto__;_x000D_
  } while (object !== null);_x000D_
}
_x000D_
_x000D_
_x000D_

I hope this clarifies any confusion about the difference between properties and attributes.

How to use environment variables in docker compose

As far as I know, this is a work-in-progress. They want to do it, but it's not released yet. See 1377 (the "new" 495 that was mentioned by @Andy).

I ended up implementing the "generate .yml as part of CI" approach as proposed by @Thomas.

blur() vs. onblur()

Contrary to what pointy says, the blur() method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Javascript test</title>
        <script type="text/javascript" language="javascript">
            window.onload = function()
            {
                var field = document.getElementById("field");
                var link = document.getElementById("link");
                var output = document.getElementById("output");

                field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
                field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
                link.onmouseover = function() { field.blur(); };
            };
        </script>
    </head>
    <body>
        <form name="MyForm">
            <input type="text" name="field" id="field" />
            <a href="javascript:void(0);" id="link">Blur field on hover</a>
            <div id="output"></div>
        </form>
    </body>
</html>

Note that I used link.onmouseover instead of link.onclick, because otherwise the click itself would have removed the focus.

How to see local history changes in Visual Studio Code?

I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.

List comprehension vs map

map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.

An example of the tiny speed advantage of map when using exactly the same function:

$ python -mtimeit -s'xs=range(10)' 'map(hex, xs)'
100000 loops, best of 3: 4.86 usec per loop
$ python -mtimeit -s'xs=range(10)' '[hex(x) for x in xs]'
100000 loops, best of 3: 5.58 usec per loop

An example of how performance comparison gets completely reversed when map needs a lambda:

$ python -mtimeit -s'xs=range(10)' 'map(lambda x: x+2, xs)'
100000 loops, best of 3: 4.24 usec per loop
$ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]'
100000 loops, best of 3: 2.32 usec per loop

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

If you are allowed to run real native binaries, then this is your compiler:

https://github.com/ircmaxell/php-compiler

It's a PHP compiler written in PHP!

It compiles PHP code to its own VM code. This VM code can then either be interpreted by its own interpreter (also written in PHP, isn't that crazy?) or it can be translated to Bitcode. And using the LLVM compiler framework (clang and co), this Bitcode can be compiled into a native binary for any platform that LLVM supports (pretty much any platform that matters today). You can choose to either do that statically or each time just before the code is executed (JIT style). So the only two requirements for this compiler to work on your system is an installed PHP interpreter and an installed clang compiler.

If you are not allowed to run native binaries, you could use the compiler above as an interpreter and let it interpret its own VM code, yet this will be slow as you are running a PHP interpreter that itself is running on a PHP engine, so you have a "double interpretation".

Disable dragging an image from an HTML page

See this answer; in Chrome and Safari you can use the following style to disable the default dragging:

-webkit-user-drag: auto | element | none;

You could try user-select for Firefox and IE(10+):

-moz-user-select: none | text | all | element
-ms-user-select: none | text | all | element

jQuery 'input' event

$("input#myId").bind('keyup', function (e) {    
    // Do Stuff
});

working in both IE and chrome

Where do I find old versions of Android NDK?

http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2

I successfully opened gstreamer SDK tutorials in Eclipse.

All I needed is to use an older version of ndk. specificly 9d.

(10c and 10d does not work, 10b - works just for tutorial-1 )

9d does work for all tutorials ! and you can:

  1. Download it from: http://dl.google.com/android/ndk/android-ndk-r9d-linux-x86_64.tar.bz2

  2. Extract it.

  3. set it in eclipse->window->preferences->Android->NDK->NDK location.

  4. build - (ctrl+b).

How does Trello access the user's clipboard?

Something very similar can be seen on http://goo.gl when you shorten the URL.

There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.

When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)

Error: Cannot access file bin/Debug/... because it is being used by another process

I've had this error crop up on me before, even in Visual Studio 2008. It came back and more prevalent in Visual Studio 2012.

Here is what I do.

Paste this in the troublesome project's pre-build event:

if exist "$(TargetPath).locked" del "$(TargetPath).locked"
if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked"

Linq : select value in a datatable column

I notice others have given the non-lambda syntax so just to have this complete I'll put in the lambda syntax equivalent:

Non-lambda (as per James's post):

var name = from i in DataContext.MyTable
           where i.ID == 0
           select i.Name

Equivalent lambda syntax:

var name = DataContext.MyTable.Where(i => i.ID == 0)
                              .Select(i => new { Name = i.Name });

There's not really much practical difference, just personal opinion on which you prefer.

How to auto adjust table td width from the content

Remove all widths set using CSS and set white-space to nowrap like so:

.content-loader tr td {
    white-space: nowrap;
}

I would also remove the fixed width from the container (or add overflow-x: scroll to the container) if you want the fields to display in their entirety without it looking odd...

See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp

phpmyadmin "no data received to import" error, how to fix?

No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration. See FAQ 1.16.

These are my upload settings from php.ini
upload_tmp_dir = "D:\xampp\xampp\tmp"       ;//set these for temp file storing

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 10M    ;//change it according to max file upload size

I am sure your problem will be short out using this instructions.

 upload_tmp_dir = "D:\xampp\xampp\tmp"

Here you can set any directory that can hold temp file, I have installed in D: drive xampp so I set it "D:\xampp\xampp\tmp".

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

Refer to here

write query with named parameter, use simple ListPreparedStatementSetter with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,

ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);

List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
    parameters.add(a.getId());

MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);     
return sql;

How to define object in array in Mongoose schema correctly with 2d geo index

You can declare trk by the following ways : - either

trk : [{
    lat : String,
    lng : String
     }]

or

trk : { type : Array , "default" : [] }

In the second case during insertion make the object and push it into the array like

db.update({'Searching criteria goes here'},
{
 $push : {
    trk :  {
             "lat": 50.3293714,
             "lng": 6.9389939
           } //inserted data is the object to be inserted 
  }
});

or you can set the Array of object by

db.update ({'seraching criteria goes here ' },
{
 $set : {
          trk : [ {
                     "lat": 50.3293714,
                     "lng": 6.9389939
                  },
                  {
                     "lat": 50.3293284,
                     "lng": 6.9389634
                  }
               ]//'inserted Array containing the list of object'
      }
});

Compare dates in MySQL

this is what it worked for me:

select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
 AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load

Ordering by specific field value first

There's also the MySQL FIELD function.

If you want complete sorting for all possible values:

SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core", "board", "other")

If you only care that "core" is first and the other values don't matter:

SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core") DESC

If you want to sort by "core" first, and the other fields in normal sort order:

SELECT id, name, priority
FROM mytable
ORDER BY FIELD(name, "core") DESC, priority

There are some caveats here, though:

First, I'm pretty sure this is mysql-only functionality - the question is tagged mysql, but you never know.

Second, pay attention to how FIELD() works: it returns the one-based index of the value - in the case of FIELD(priority, "core"), it'll return 1 if "core" is the value. If the value of the field is not in the list, it returns zero. This is why DESC is necessary unless you specify all possible values.

Line Break in HTML Select Option?

No, browsers don't provide this formatting option.

You could probably fake it with some checkboxes with <label>s, and JS to turn it into a fly out menu.

How to open Emacs inside Bash

Emacs takes many launch options. The one that you are looking for is emacs -nw. This will open Emacs inside the terminal disregarding the DISPLAY environment variable even if it is set. The long form of this flag is emacs --no-window-system.

More information about Emacs launch options can be found in the manual.

Call fragment from fragment

I would use a listener. Fragment1 calling the listener (main activity)

Dealing with HTTP content in HTTPS pages

I realise that this is an old thread but one option is just to remove the http: part from the image URL so that 'http://some/image.jpg' becomes '//some/image.jpg'. This will also work with CDNs

Amazon AWS Filezilla transfer permission denied

To allow user ec2-user (Amazon AWS) write access to the public web directory (/var/www/html),
enter this command via Putty or Terminal, as the root user sudo:

chown -R ec2-user /var/www/html

Make sure permissions on that entire folder were correct:

chmod -R 755 /var/www/html

Doc's:

Setting up amazon ec2-instances

Connect to Amazon EC2 file directory using Filezilla and SFTP (Video)

Understanding and Using File Permissions

Revert to Eclipse default settings

I was able to solve a similar problem like this:

  1. Close the Eclipse IDE
  2. Remove the .metadata folder from your eclipse workspace
  3. Relaunch eclipse

The only disadvantage is that you have to re-import all your projects.

How to change Toolbar home icon color

Try this: Set the toolbar's theme in your layout as follows

android:theme = "@android:style/ThemeOverlay.Material.Dark.ActionBar"

If you want further information

The curious case of the Overflow Icon Color by Martin Bonnin

C++ "Access violation reading location" Error

Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

Because findVertex can return NULL if it can't find the vertex.

Otherwise this f->adj; is trying to do

NULL->adj;

Which causes access violation.

How could others, on a local network, access my NodeJS app while it's running on my machine?

I had this problem. The solution was to allow node.js through the server's firewall.

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

How to obtain the last path segment of a URI

I'm using the following in a utility class:

public static String lastNUriPathPartsOf(final String uri, final int n, final String... ellipsis)
  throws URISyntaxException {
    return lastNUriPathPartsOf(new URI(uri), n, ellipsis);
}

public static String lastNUriPathPartsOf(final URI uri, final int n, final String... ellipsis) {
    return uri.toString().contains("/")
        ? (ellipsis.length == 0 ? "..." : ellipsis[0])
          + uri.toString().substring(StringUtils.lastOrdinalIndexOf(uri.toString(), "/", n))
        : uri.toString();
}

Calling a JSON API with Node.js

I'm using get-json very simple to use:

$ npm install get-json --save

Import get-json

var getJSON = require('get-json')

To do a GET request you would do something like:

getJSON('http://api.listenparadise.org', function(error, response){
    console.log(response);
})

How to open generated pdf using jspdf in new window

using javascript you can send the generated pdf to a new window using the following code.

var string = doc.output('datauristring');

var iframe = "<iframe width='100%' height='100%' src='" + string + "'></iframe>"

var x = window.open();
x.document.open();
x.document.write(iframe);
x.document.close();

WPF Databinding: How do I access the "parent" data context?

This will also work:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView will inherit its DataContext from Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Binding for such controls will work perfectly.

Add CSS class to a div in code behind

Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.

public static void RemoveCssClass(this WebControl control, String css) {
  control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());
}

public static void AddCssClass(this WebControl control, String css) {
  control.RemoveCssClass(css);
  css += " " + control.CssClass;
  control.CssClass = css;
}

Usage: hlCreateNew.AddCssClass("disabled");

Usage: hlCreateNew.RemoveCssClass("disabled");

What's the whole point of "localhost", hosts and ports at all?

In computer networking, localhost (meaning "this computer") is the standard hostname given to the address of the loopback network interface.

Localhost always translates to the loopback IP address 127.0.0.1 in IPv4.

It is also used instead of the hostname of a computer. For example, directing a web browser installed on a system running an HTTP server to http://localhost will display the home page of the local web site.

Source: Wikipedia - Localhost.


The :80 part is the TCP port. You can consider these ports as communications endpoints on a particular IP address (in the case of localhost - 127.0.0.1). The IANA is responsible for maintaining the official assignments of standard port numbers for specific services. Port 80 happens to be the standard port for HTTP.

How to change app default theme to a different app theme?

Actually you should define your styles in res/values/styles.xml. I guess now you've got the following configuration:

<style name="AppBaseTheme" parent="android:Theme.Holo.Light"/>
<style name="AppTheme" parent="AppBaseTheme"/>

so if you want to use Theme.Black then change AppBaseTheme parent to android:Theme.Black or you could change app style directly in manifest file like this - android:theme="@android:style/Theme.Black". You must be lacking android namespace before style tag.

You can read more about styles and themes here.

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

Use the createFromFormat method:

$start_date = DateTime::createFromFormat("U", $dbResult->db_timestamp);

UPDATE

I now recommend the use of Carbon

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I had the same problem but I solved in other way (becouse at right click on project folder no Maven tab apears only if I do that on pom.xml I can see a Maven tab):

So I tink that you get that error because the IDE (Eclipse) didn`t import the dependecies from Maven. Since you are using Spring framework and you probably have STS allready installed right-click on project folder Spring Tools -> Update Maven Dependecies.

I`m using Eclipse JUNO m2eclipse 1.3.0 Spring IDEE 3.1

Comparing two strings in C?

The name of the array indicates the starting address. Starting address of both namet2 and nameIt2 are different. So the equal to (==) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp(), or we can compare character by character using a loop.

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

Libraries cannot be directly used in any program if not properly added to the project gradle files.

This can easily be done in smart IDEs like inteli J.

1) First as a convention add a folder names 'libs' under your project src file. (this can easily be done using the IDE itself)

2) then copy or add your library file (eg: .jar file) to the folder named 'libs'

3) now you can see the library file inside the libs folder. Now right click on the file and select 'add as library'. And this will fix all the relevant files in your program and library will be directly available for your use.

Please note:

Whenever you are adding libraries to a project, make sure that the project supports the library

int to unsigned int conversion

Since we know that i is an int, you can just go ahead and unsigneding it!

This would do the trick:

int i = -62;
unsigned int j = unsigned(i);

jQuery change input text value

Best practice is using the identify directly:

$('#id').val('xxx');

How to get the data-id attribute?

This piece of code will return the value of the data attributes eg: data-id, data-time, data-name etc.., I have shown for the id

<a href="#" id="click-demo" data-id="a1">Click</a>

js:

$(this).data("id");

// get the value of the data-id -> a1

$(this).data("id", "a2");

// this will change the data-id -> a2

$(this).data("id");

// get the value of the data-id -> a2

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

Leave you stuff there and Try the following as well:

Start > Right-click on My computer > Properties > Advanced system settings > Environment Variables > look for variable name called "Path" in the lower box

set path value value as: (you can just add it to the starting of line, don't forgot semi column in between )

c:\Program Files\java\jre7\bin

Input size vs width

HTML controls the semantic meaning of the elements. CSS controls the layout/style of the page. Use CSS when you are controlling your layout.

In short, never use size=""

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Old question but anyway !

Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)

So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!

How to simulate key presses or a click with JavaScript?

For simulating keyboard events in Chrome:

There is a related bug in webkit that keyboard events when initialized with initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735

A working solution for it is posted in this SO answer.

When to use in vs ref vs out

Basically both ref and out for passing object/value between methods

The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed.

out : Argument is not initialized and it must be initialized in the method

ref : Argument is already initialized and it can be read and updated in the method.

What is the use of “ref” for reference-types ?

You can change the given reference to a different instance.

Did you know?

  1. Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument.

  2. You can't use the ref and out keywords for the following kinds of methods:

    • Async methods, which you define by using the async modifier.
    • Iterator methods, which include a yield return or yield break statement.
  3. Properties are not variables and therefore cannot be passed as out parameters.

Converting characters to integers in Java

43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back. http://en.wikipedia.org/wiki/ASCII

How to get current available GPUs in tensorflow?

In TensorFlow Core v2.3.0, the following code should work.

import tensorflow as tf
visible_devices = tf.config.get_visible_devices()
for devices in visible_devices:
  print(devices)

Depending on your environment, this code will produce flowing results.

PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU') PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

DataColumn Name from DataRow (not DataTable)

use DataTable object instead:

 private void doMore(DataTable dt)
    {
    foreach(DataColumn dc in dt.Columns)
    {
    MessageBox.Show(dc.ColumnName);
    }
    }

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

The input shape you have defined is the shape of a single sample. The model itself expects some array of samples as input (even if its an array of length 1).

Your output really should be 4-d, with the 1st dimension to enumerate the samples. i.e. for a single image you should return a shape of (1, 32, 32, 3).

You can find more information here under "Convolution2D"/"Input shape"

Edit: Based on Danny's comment below, if you want a batch size of 1, you can add the missing dimension using this:

image = np.expand_dims(image, axis=0)

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

That for changing directory of the XAMPP. So you have to change the Directory as well as ServerRoot "E:/xampp/apache"

DocumentRoot "E:/xampp/htdocs"


<Directory "E:/xampp/htdocs">


ScriptAlias /cgi-bin/ "E:/xampp/cgi-bin/"


<Directory "E:/xampp/cgi-bin">
    AllowOverride All
    Options None
    Require all granted
</Directory>

I also facing same problem for changing My laptop. thanks

GIT commit as different user without email / or only email

The specific format is:

git commit --author="John Doe <[email protected]>" -m "Impersonation is evil." 

How to convert a Kotlin source file to a Java source file

To convert a Kotlin source file to a Java source file you need to (when you in Android Studio):

  1. Press Cmd-Shift-A on a Mac, or press Ctrl-Shift-A on a Windows machine.

  2. Type the action you're looking for: Kotlin Bytecode and choose Show Kotlin Bytecode from menu.

enter image description here

  1. Press Decompile button on the top of Kotlin Bytecode panel.

enter image description here

  1. Now you get a Decompiled Java file along with Kotlin file in a adjacent tab:

enter image description here

Trying to get property of non-object in

$sidemenu is not an object, so you can't call methods on it. It is probably not being sent to your view, or $sidemenus is empty.

How can I easily convert DataReader to List<T>?

You cant simply (directly) convert the datareader to list.

You have to loop through all the elements in datareader and insert into list

below the sample code

using (drOutput)   
{
            System.Collections.Generic.List<CustomerEntity > arrObjects = new System.Collections.Generic.List<CustomerEntity >();        
            int customerId = drOutput.GetOrdinal("customerId ");
            int CustomerName = drOutput.GetOrdinal("CustomerName ");

        while (drOutput.Read())        
        {
            CustomerEntity obj=new CustomerEntity ();
            obj.customerId = (drOutput[customerId ] != Convert.DBNull) ? drOutput[customerId ].ToString() : null;
            obj.CustomerName = (drOutput[CustomerName ] != Convert.DBNull) ? drOutput[CustomerName ].ToString() : null;
            arrObjects .Add(obj);
        }

}

List all devices, partitions and volumes in Powershell

This is pretty old, but I found following worth noting:

PS N:\> (measure-command {Get-WmiObject -Class Win32_LogicalDisk|select -property deviceid|%{$_.deviceid}|out-host}).totalmilliseconds
...
928.7403
PS N:\> (measure-command {gdr -psprovider 'filesystem'|%{$_.name}|out-host}).totalmilliseconds
...
169.474

Without filtering properties, on my test system, 4319.4196ms to 1777.7237ms. Unless I need a PS-Drive object returned, I'll stick with WMI.

EDIT: I think we have a winner: PS N:> (measure-command {[System.IO.DriveInfo]::getdrives()|%{$_.name}|out-host}).to??talmilliseconds 110.9819

CSS list-style-image size

Here is an example to play with Inline SVG for a list bullet (2020 Browsers)

list-style-image: url("data:image/svg+xml,
                      <svg width='50' height='50'
                           xmlns='http://www.w3.org/2000/svg' 
                           viewBox='0 0 72 72'>
                        <rect width='100%' height='100%' fill='pink'/>
                        <path d='M70 42a3 3 90 0 1 3 3a3 3 90 0 1-3 3h-12l-3 3l-6 15l-3
                                 l-6-3v-21v-3l15-15a3 3 90 0 1 0 0c3 0 3 0 3 3l-6 12h30
                                 m-54 24v-24h9v24z'/></svg>")
  • Play with SVG width & height to set the size
  • Play with M70 42 to position the hand
  • different behaviour on FireFox or Chromium!
  • remove the rect

_x000D_
_x000D_
li{
  font-size:2em;
  list-style-image: url("data:image/svg+xml,<svg width='3em' height='3em'                          xmlns='http://www.w3.org/2000/svg' viewBox='0 0 72 72'><rect width='100%' height='100%' fill='pink'/><path d='M70 42a3 3 90 0 1 3 3a3 3 90 0 1-3 3h-12l-3 3l-6 15l-3 3h-12l-6-3v-21v-3l15-15a3 3 90 0 1 0 0c3 0 3 0 3 3l-6 12h30m-54 24v-24h9v24z'/></svg>");
}

span{
  display:inline-block;
  vertical-align:top;
  margin-top:-10px;
  margin-left:-5px;
}
_x000D_
<ul>
  <li><span>Apples</span></li>
  <li><span>Bananas</span></li>
  <li>Oranges</li>
</ul>
_x000D_
_x000D_
_x000D_

How different is Scrum practice from Agile Practice?

Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.

How to shutdown my Jenkins safely?

Use http://[jenkins-server]/exit

This page shows how to use URL commands.

how to create a cookie and add to http response from inside my service layer?

Following @Aravind's answer with more details

@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
    myServiceMethodSettingCookie(request, response);        //Do service call passing the response
    return new ModelAndView("CustomerAddView");
}

// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
    final String cookieName = "my_cool_cookie";
    final String cookieValue = "my cool value here !";  // you could assign it some encoded value
    final Boolean useSecureCookie = false;
    final int expiryTime = 60 * 60 * 24;  // 24h in seconds
    final String cookiePath = "/";

    Cookie cookie = new Cookie(cookieName, cookieValue);

    cookie.setSecure(useSecureCookie);  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL

    cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

    cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories

    response.addCookie(cookie);
}

Related docs:

http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html

http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html

CreateProcess: No such file or directory

I had a similar problem, caused by not installing the C++ compiler. In my case I was compiling .cpp files for a Python extension, but the compiler is first invoked as c:\mingw\bin\gcc.exe.

Internally, gcc.exe would notice it was asked to compile a .cpp file. It would try to call g++.exe and fail with the same error message:

gcc.exe: CreateProcess: no such file or directory

Inline for loop

you can use enumerate keeping the ind/index of the elements is in vm, if you make vm a set you will also have 0(1) lookups:

vm = {-1, -1, -1, -1}

print([ind if q in vm else 9999 for ind,ele in enumerate(vm) ])

How to add a changed file to an older (not last) commit in Git

Use git rebase. Specifically:

  1. Use git stash to store the changes you want to add.
  2. Use git rebase -i HEAD~10 (or however many commits back you want to see).
  3. Mark the commit in question (a0865...) for edit by changing the word pick at the start of the line into edit. Don't delete the other lines as that would delete the commits.[^vimnote]
  4. Save the rebase file, and git will drop back to the shell and wait for you to fix that commit.
  5. Pop the stash by using git stash pop
  6. Add your file with git add <file>.
  7. Amend the commit with git commit --amend --no-edit.
  8. Do a git rebase --continue which will rewrite the rest of your commits against the new one.
  9. Repeat from step 2 onwards if you have marked more than one commit for edit.

[^vimnote]: If you are using vim then you will have to hit the Insert key to edit, then Esc and type in :wq to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano".

<ng-container> vs <template>

A use case for it when you want to use a table with *ngIf and *ngFor - As putting a div in td/th will make the table element misbehave -. I faced this problem and that was the answer.

Replacing NULL with 0 in a SQL server query

Wrap your column in this code.

 ISNULL(Yourcolumn, 0)

Maybe check why you are getting nulls

Using Excel VBA to run SQL query

Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):

References required for SQL

Sub Module for Connecting to MS SQL with Remote Host & Username/Password

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub

CSS width of a <span> tag

You can't specify the width of an element with display inline. You could put something in it like a non-breaking space ( ) and then set the padding to give it some more width but you can't control it directly.

You could use display inline-block but that isn't widely supported.

A real hack would be to put an image inside and then set the width of that. Something like a transparent 1 pixel GIF. Not the recommended approach however.

Android Animation Alpha

This my extension, this is an example of change image with FadIn and FadOut :

fun ImageView.setImageDrawableWithAnimation(@DrawableRes() resId: Int, duration: Long = 300) {    
    if (drawable != null) {
        animate()
            .alpha(0f)
            .setDuration(duration)
             .withEndAction {
                 setImageResource(resId)
                 animate()
                     .alpha(1f)
                     .setDuration(duration)
             }

    } else if (drawable == null) {
        setAlpha(0f)
        setImageResource(resId)
        animate()
            .alpha(1f)
            .setDuration(duration)
    }
}

How to do a SUM() inside a case statement in SQL server

The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.

Example

This one works!

     SELECT t.device,
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This one not (omitted t.device from the select)

     SELECT 
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This will produce your error complaining that I'm grouping for something that is not included in the select

Please, provide all the query to get more support.

What does 'wb' mean in this code, using Python?

File mode, write and binary. Since you are writing a .jpg file, it looks fine.

But if you supposed to read that jpg file you need to use 'rb'

More info

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.

PHP, Get tomorrows date from date

Since you tagged this with , you can use it with the +1 day modifier like so:

$tomorrow_timestamp = strtotime('+1 day', strtotime('2013-01-22'));

That said, it's a much better solution to use DateTime.

LINQ to SQL Left Outer Join

You don't need the into statements:

var query = 
    from customer in dc.Customers
    from order in dc.Orders
         .Where(o => customer.CustomerId == o.CustomerId)
         .DefaultIfEmpty()
    select new { Customer = customer, Order = order } 
    //Order will be null if the left join is null

And yes, the query above does indeed create a LEFT OUTER join.

Link to a similar question that handles multiple left joins: Linq to Sql: Multiple left outer joins

Can't bind to 'formGroup' since it isn't a known property of 'form'

You need to import the FormsModule, ReactiveFormsModule in this module as well as the top level.

If you used a reactiveForm in another module then you've to do also this step along with above step: import also reactiveFormsModule in that particular module.

For example:

imports: [
  BrowserModule,
  FormsModule,
  ReactiveFormsModule,
  AppRoutingModule,
  HttpClientModule,
  BrowserAnimationsModule
],

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

You don't have to track whether you've already changed the character from upper to lower. Your code is already doing that since it's basically:

1   for each character x:
2       if x is uppercase:
3           convert x to lowercase
4       else:
5           if x is lowercase:
6                convert x to uppercase.

The fact that you have that else in there (on line 4) means that a character that was initially uppercase will never be checked in the second if statement (on line 5).

Example, start with A. Because that's uppercase, it will be converted to lowercase on line 3 and then you'll go back up to line 1 for the next character.

If you start with z, the if on line 2 will send you directly to line 5 where it will be converted to uppercase. Anything that's neither upper nor lowercase will fail both if statements and therefore remain untouched.

Remove all child nodes from a parent?

You can use .empty(), like this:

$("#foo").empty();

From the docs:

Remove all child nodes of the set of matched elements from the DOM.

How do I get the path of a process in Unix / Linux

I use:

ps -ef | grep 786

Replace 786 with your PID or process name.

How to create PDF files in Python

I use rst2pdf to create a pdf file, since I am more familiar with RST than with HTML. It supports embedding almost any kind of raster or vector images.

It requires reportlab, but I found reportlab is not so straight forward to use (at least for me).

Python RuntimeWarning: overflow encountered in long scalars

Here's an example which issues the same warning:

import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a

yields

RuntimeWarning: overflow encountered in long_scalars

In the example above it happens because a is of dtype int32, and the maximim value storable in an int32 is 2**31-1. Since 10**10 > 2**32-1, the exponentiation results in a number that is bigger than that which can be stored in an int32.

Note that you can not rely on np.seterr(all='warn') to catch all overflow errors in numpy. For example, on 32-bit NumPy

>>> np.multiply.reduce(np.arange(21)+1)
-1195114496

while on 64-bit NumPy:

>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848

Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals

In [47]: import math

In [48]: math.factorial(21)
Out[50]: 51090942171709440000L

According to numpy developer, Robert Kern,

Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays.

So the burden is on you to choose appropriate dtypes so that no operation overflows.

JavaScript: set dropdown selected item based on option text

A modern alternative:

const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

What is the difference between char array and char pointer in C?

From APUE, Section 5.14 :

char    good_template[] = "/tmp/dirXXXXXX"; /* right way */
char    *bad_template = "/tmp/dirXXXXXX";   /* wrong way*/

... For the first template, the name is allocated on the stack, because we use an array variable. For the second name, however, we use a pointer. In this case, only the memory for the pointer itself resides on the stack; the compiler arranges for the string to be stored in the read-only segment of the executable. When the mkstemp function tries to modify the string, a segmentation fault occurs.

The quoted text matches @Ciro Santilli 's explanation.

What are forward declarations in C++?

When the compiler sees add(3, 4) it needs to know what that means. With the forward declaration you basically tell the compiler that add is a function that takes two ints and returns an int. This is important information for the compiler becaus it needs to put 4 and 5 in the correct representation onto the stack and needs to know what type the thing returned by add is.

At that time, the compiler is not worried about the actual implementation of add, ie where it is (or if there is even one) and if it compiles. That comes into view later, after compiling the source files when the linker is invoked.

Debugging JavaScript in IE7

The hard truth is: the only good debugger for IE is Visual Studio.

If you don't have money for the real deal, download free Visual Web Developer 2008 Express EditionVisual Web Developer 2010 Express Edition. While the former allows you to attach debugger to already running IE, the latter doesn't (at least previous versions I used didn't allow that). If this is still the case, the trick is to create a simple project with one empty web page, "run" it (it starts the browser), now navigate to whatever page you want to debug, and start debugging.

Microsoft gives away full Visual Studio on different events, usually with license restrictions, but they allow tinkering at home. Check their schedule and the list of freebies.

Another hint: try to debug your web application with other browsers first. I had a great success with Opera. Somehow Opera's emulation of IE and its bugs was pretty close, but the debugger is much better.

Babel command not found

To install version 7+ of Babel run:

npm install -g @babel/cli
npm install -g @babel/core

how to count the spaces in a java string?

\t will match tabs, rather than spaces and should also be referred to with a double slash: \\t. You could call s.split( " " ) but that wouldn't count consecutive spaces. By that I mean...

String bar = " ba jfjf jjj j   ";
String[] split = bar.split( " " );
System.out.println( split.length ); // Returns 5

So, despite the fact there are seven space characters, there are only five blocks of space. It depends which you're trying to count, I guess.

Commons Lang is your friend for this one.

int count = StringUtils.countMatches( inputString, " " );

array of string with unknown size

string foo = "Apple, Plum, Cherry";

string[] myArr = null;

myArr = foo.Split(',');

How to find the 'sizeof' (a pointer pointing to an array)?

The answer is, "No."

What C programmers do is store the size of the array somewhere. It can be part of a structure, or the programmer can cheat a bit and malloc() more memory than requested in order to store a length value before the start of the array.

C++ sorting and keeping track of indexes

There are many ways. A rather simple solution is to use a 2D vector.

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
 vector<vector<double>> val_and_id;
 val_and_id.resize(5);
 for (int i = 0; i < 5; i++) {
   val_and_id[i].resize(2); // one to store value, the other for index.
 }
 // Store value in dimension 1, and index in the other:
 // say values are 5,4,7,1,3.
 val_and_id[0][0] = 5.0;
 val_and_id[1][0] = 4.0;
 val_and_id[2][0] = 7.0;
 val_and_id[3][0] = 1.0;
 val_and_id[4][0] = 3.0;

 val_and_id[0][1] = 0.0;
 val_and_id[1][1] = 1.0;
 val_and_id[2][1] = 2.0;
 val_and_id[3][1] = 3.0;
 val_and_id[4][1] = 4.0;

 sort(val_and_id.begin(), val_and_id.end());
 // display them:
 cout << "Index \t" << "Value \n";
 for (int i = 0; i < 5; i++) {
  cout << val_and_id[i][1] << "\t" << val_and_id[i][0] << "\n";
 }
 return 0;
}

Here is the output:

   Index   Value
   3       1
   4       3
   1       4
   0       5
   2       7

document.getelementbyId will return null if element is not defined?

getElementById is defined by DOM Level 1 HTML to return null in the case no element is matched.

!==null is the most explicit form of the check, and probably the best, but there is no non-null falsy value that getElementById can return - you can only get null or an always-truthy Element object. So there's no practical difference here between !==null, !=null or the looser if (document.getElementById('xx')).

css overflow - only 1 line of text

if addition please, if you have a long text please you can use this css code bellow;

text-overflow: ellipsis;
overflow: visible;
white-space: nowrap;

make the whole line text visible.

Call Class Method From Another Class

Just call it and supply self

class A:
    def m(self, x, y):
        print(x+y)

class B:
    def call_a(self):
        A.m(self, 1, 2)

b = B()
b.call_a()

output: 3

node: command not found

The problem is that your PATH does not include the location of the node executable.

You can likely run node as "/usr/local/bin/node".

You can add that location to your path by running the following command to add a single line to your bashrc file:

echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc

Python Loop: List Index Out of Range

You are accessing the list elements and then using them to attempt to index your list. This is not a good idea. You already have an answer showing how you could use indexing to get your sum list, but another option would be to zip the list with a slice of itself such that you can sum the pairs.

b = [i + j for i, j in zip(a, a[1:])]

What is Android keystore file, and what is it used for?

You can find more information about the signing process on the official Android documentation here : http://developer.android.com/guide/publishing/app-signing.html

Yes, you can sign several applications with the same keystore. But you must remember one important thing : if you publish an app on the Play Store, you have to sign it with a non debug certificate. And if one day you want to publish an update for this app, the keystore used to sign the apk must be the same. Otherwise, you will not be able to post your update.

What is __main__.py?

__main__.py is used for python programs in zip files. The __main__.py file will be executed when the zip file in run. For example, if the zip file was as such:

test.zip
     __main__.py

and the contents of __main__.py was

import sys
print "hello %s" % sys.argv[1]

Then if we were to run python test.zip world we would get hello world out.

So the __main__.py file run when python is called on a zip file.

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

This also can happen if the device you are trying to run on has some older version of the provisioning profile you are using that points to an old, expired or revoked certificate or a certificate without associated private key. Delete any invalid Provisioning Profiles under your device section in Xcode organizer.

This version of the application is not configured for billing through Google Play

Ahh found the solution after trying for a couple of hours.

  1. Google takes a while to process applications and update them to their servers, for me it takes about half a day. So after saving the apk as a draft on Google Play, you must wait a few hours before the in-app products will respond normally and allow for regular purchases.
  2. Export and sign APK. Unsigned APK trying to make purchases will get error.

How to select some rows with specific rownames from a dataframe?

Assuming that you have a data frame called students, you can select individual rows or columns using the bracket syntax, like this:

  • students[1,2] would select row 1 and column 2, the result here would be a single cell.
  • students[1,] would select all of row 1, students[,2] would select all of column 2.

If you'd like to select multiple rows or columns, use a list of values, like this:

  • students[c(1,3,4),] would select rows 1, 3 and 4,
  • students[c("stu1", "stu2"),] would select rows named stu1 and stu2.

Hope I could help.

Java - escape string to prevent SQL injection

You need the following code below. At a glance, this may look like any old code that I made up. However, what I did was look at the source code for http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.31/com/mysql/jdbc/PreparedStatement.java. Then after that, I carefully looked through the code of setString(int parameterIndex, String x) to find the characters which it escapes and customised this to my own class so that it can be used for the purposes that you need. After all, if this is the list of characters that Oracle escapes, then knowing this is really comforting security-wise. Maybe Oracle need a nudge to add a method similar to this one for the next major Java release.

public class SQLInjectionEscaper {

    public static String escapeString(String x, boolean escapeDoubleQuotes) {
        StringBuilder sBuilder = new StringBuilder(x.length() * 11/10);

        int stringLength = x.length();

        for (int i = 0; i < stringLength; ++i) {
            char c = x.charAt(i);

            switch (c) {
            case 0: /* Must be escaped for 'mysql' */
                sBuilder.append('\\');
                sBuilder.append('0');

                break;

            case '\n': /* Must be escaped for logs */
                sBuilder.append('\\');
                sBuilder.append('n');

                break;

            case '\r':
                sBuilder.append('\\');
                sBuilder.append('r');

                break;

            case '\\':
                sBuilder.append('\\');
                sBuilder.append('\\');

                break;

            case '\'':
                sBuilder.append('\\');
                sBuilder.append('\'');

                break;

            case '"': /* Better safe than sorry */
                if (escapeDoubleQuotes) {
                    sBuilder.append('\\');
                }

                sBuilder.append('"');

                break;

            case '\032': /* This gives problems on Win32 */
                sBuilder.append('\\');
                sBuilder.append('Z');

                break;

            case '\u00a5':
            case '\u20a9':
                // escape characters interpreted as backslash by mysql
                // fall through

            default:
                sBuilder.append(c);
            }
        }

        return sBuilder.toString();
    }
}

Add a border outside of a UIView (instead of inside)

There is actually a very simple solution. Just set them both like this:

view.layer.borderWidth = 5

view.layer.borderColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).cgColor

view.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.25).cgColor

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

interestingly in my git-bash on windows sed "" did the trick already:

$ echo -e "abc\r" >tst.txt
$ file tst.txt
tst.txt: ASCII text, with CRLF line terminators
$ sed -i "" tst.txt
$ file tst.txt
tst.txt: ASCII text

My guess is that sed ignores them when reading lines from input and always writes unix line endings on output.

How to parse JSON in Kotlin?

GSON is a good choice for Android and Web platform to parse JSON in a Kotlin project. This library is developed by Google. https://github.com/google/gson

1. First add GSON to your project:

dependencies {
   implementation 'com.google.code.gson:gson:2.8.6'
}

2. Now you need to convert your JSON to Kotlin Data class:

Copy your JSON and go to this(https://json2kt.com) website and paste your JSON to Input Json box. Write package(ex: com.example.appName) and Class name(ex: UserData) in proper box. This site will show live preview of your data class below and also you can download all classes at once in a zip file.

After downloading all classes extract zip file & place them into your project.

3. Now Parse like below:

val myJson = """
{
    "user_name": "john123",
    "email": "[email protected]",
    "name": "John Doe"
}
""".trimIndent()

val gson = Gson()
var mUser = gson.fromJson(myJson, UserData::class.java)
println(mUser.userName)

Done :)

JavaScript listener, "keypress" doesn't detect backspace?

Try keydown instead of keypress.

The keyboard events occur in this order: keydown, keyup, keypress

The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event.

HTTP post XML data in C#

In General:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

In your specific situation:

Instead of:

request.ContentType = "application/x-www-form-urlencoded";

use:

request.ContentType = "text/xml; encoding='utf-8'";

Also, remove:

string postData = "XMLData=" + Sendingxml;

And replace:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

with:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());

CSS3 Fade Effect

You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:

span {
    background: url(button.png) no-repeat 0 0;
}
a {
    width: 32px;
    height: 32px;
    text-align: left;
    background: rgb(255,255,255);

    -webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
    -moz-transition: background 300ms ease-in 200ms;
    -o-transition: background 300ms ease-in 200ms;
    transition: background 300ms ease-in 200ms;
    }
a:hover {
    background: rgba(255,255,255,0);
}

Calling a php function by onclick event

In Your HTML

<input type="button" name="Release" onclick="hello();" value="Click to Release" />

In Your JavaScript

<script type="text/javascript">
    function hello(){
        alert('Your message here');
    }
</script>

If you need to run PHP in JavaScript You need to use JQuery Ajax Function

<script type="text/javascript">
function hello(){
    $.ajax(
{     
 type:    'post',
 url:     'folder/my_php_file.php',
 data:    '&id=' + $('#id').val() + '&name=' +     $('#name').val(),
 dataType: 'json',
 //alert(data);
 success: function(data) 
 {
  //alert(data);
 }   
});
}
</script>

Now in your my_php_file.php file

<?php 
    echo 'hello';
?>

Good Luck !!!!!

How to detect DataGridView CheckBox event change?

You can force the cell to commit the value as soon as you click the checkbox and then catch the CellValueChanged event. The CurrentCellDirtyStateChanged fires as soon as you click the checkbox.

The following code works for me:

private void grid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        SendKeys.Send("{tab}");
    }

You can then insert your code in the CellValueChanged event.

exception in thread 'main' java.lang.NoClassDefFoundError:

Run it like this:

java -jar HelloWorld.jar

How to open a file / browse dialog using javascript?

you can't use input.click() directly, but you can call this in other element click event.

html

<input type="file">
<button>Select file</button>

js

var botton = document.querySelector('button');
var input = document.querySelector('input');
botton.addEventListener('click', function (e) {
    input.click();
});

this tell you Using hidden file input elements using the click() method

Gradle does not find tools.jar

If you use terminal to build and you have this error you can point to jdk bundled with android studio in your gradle.properties file:

org.gradle.java.home=/usr/local/android-studio/jre

How to find the first and second maximum number?

If you want the second highest number you can use

=LARGE(E4:E9;2)

although that doesn't account for duplicates so you could get the same result as the Max

If you want the largest number that is smaller than the maximum number you can use this version

=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

For LINQ -> SQL:

SingleOrDefault

  • will generate query like "select * from users where userid = 1"
  • Select matching record, Throws exception if more than one records found
  • Use if you are fetching data based on primary/unique key column

FirstOrDefault

  • will generate query like "select top 1 * from users where userid = 1"
  • Select first matching rows
  • Use if you are fetching data based on non primary/unique key column

Multiple Python versions on the same machine?

Update 2019: Using asdf

These days I suggest using asdf to install various versions of Python interpreters next to each other.

Note1: asdf works not only for Python but for all major languages.

Note2: asdf works fine in combination with popular package-managers such as pipenv and poetry.

If you have asdf installed you can easily download/install new Python interpreters:

# Install Python plugin for asdf:
asdf plugin-add python

# List all available Python interpreters:
asdf list-all python

# Install the Python interpreters that you need:
asdf install python 3.7.4
asdf install python 3.6.9
# etc...

# If you want to define the global version:
asdf global python 3.7.4

# If you want to define the local (project) version:
# (this creates a file .tool-versions in the current directory.)
asdf local python 3.7.4

Old Answer: Install Python from source

If you need to install multiple versions of Python (next to the main one) on Ubuntu / Mint: (should work similar on other Unixs'.)

1) Install Required Packages for source compilation

$ sudo apt-get install build-essential checkinstall
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev

2) Download and extract desired Python version

Download Python Source for Linux as tarball and move it to /usr/src.

Extract the downloaded package in place. (replace the 'x's with your downloaded version)

$ sudo tar xzf Python-x.x.x.tgz

3) Compile and Install Python Source

$ cd Python-x.x.x
$ sudo ./configure
$ sudo make altinstall

Your new Python bin is now located in /usr/local/bin. You can test the new version:

$ pythonX.X -V
Python x.x.x
$ which pythonX.X
/usr/local/bin/pythonX.X

# Pip is now available for this version as well:
$ pipX.X -V
pip X.X.X from /usr/local/lib/pythonX.X/site-packages (python X.X)

Why does the program give "illegal start of type" error?

You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

I found that you don't necessarily need the text vertically centred, it also looks good near the bottom of the row, it's only when it's at the top (or above centre?) that it looks wrong. So I went with this to push the links to the bottom of the row:

.navbar-brand {
    min-height: 80px;
}

@media (min-width: 768px) {
    #navbar-collapse {
        position: absolute;
        bottom: 0px;
        left: 250px;
    }
}

My brand image is SVG and I used height: 50px; width: auto which makes it about 216px wide. It spilled out of its container vertically so I added the min-height: 80px; to make room for it plus bootstrap's 15px margins. Then I tweaked the navbar-collapse's left setting until it looked right.

Jupyter Notebook not saving: '_xsrf' argument missing from post

I was able to solve it by clicking on the "Kernel" drop down menu and choosing "Interrupt."

List all kafka topics

Kafka is a distributed system and needs Zookeeper. you have to start zookeeper too. Follow "Quick Start" here : https://kafka.apache.org/0100/documentation.html#quickstart

Setting the classpath in java using Eclipse IDE

Try this:

Project -> Properties -> Java Build Path -> Add Class Folder.

If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.

How to generate a git patch for a specific commit?

if you just want diff the specified file, you can :

git diff master 766eceb -- connections/ > 000-mysql-connector.patch

How to parse JSON to receive a Date object in JavaScript?

There is no standard JSON representation of dates. You should do what @jAndy suggested and not serialize a DateTime at all; just send an RFC 1123 date string ToString("r") or a seconds-from-Unix-epoch number, or something else that you can use in the JavaScript to construct a Date.

How to remove square brackets from list in Python?

You could convert it to a string instead of printing the list directly:

print(", ".join(LIST))

If the elements in the list aren't strings, you can convert them to string using either repr (if you want quotes around strings) or str (if you don't), like so:

LIST = [1, "foo", 3.5, { "hello": "bye" }]
print( ", ".join( repr(e) for e in LIST ) )

Which gives the output:

1, 'foo', 3.5, {'hello': 'bye'}

Quickest way to compare two generic lists for differences

I think this is a simple and easy way to compare two lists element by element

x=[1,2,3,5,4,8,7,11,12,45,96,25]
y=[2,4,5,6,8,7,88,9,6,55,44,23]

tmp = []


for i in range(len(x)) and range(len(y)):
    if x[i]>y[i]:
        tmp.append(1)
    else:
        tmp.append(0)
print(tmp)

Handling errors in Promise.all

Not the best way to error log, but you can always set everything to an array for the promiseAll, and store the resulting results into new variables.

If you use graphQL you need to postprocess the response regardless and if it doesn't find the correct reference it'll crash the app, narrowing down where the problem is at

const results = await Promise.all([
  this.props.client.query({
    query: GET_SPECIAL_DATES,
  }),
  this.props.client.query({
    query: GET_SPECIAL_DATE_TYPES,
  }),
  this.props.client.query({
    query: GET_ORDER_DATES,
  }),
]).catch(e=>console.log(e,"error"));
const specialDates = results[0].data.specialDates;
const specialDateTypes = results[1].data.specialDateTypes;
const orderDates = results[2].data.orders;

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Worth mentioning: you should download the x64 version!

From the main download page (https://www.iis.net/downloads/microsoft/url-rewrite) click "additional downloads" (under the main download button) and download the x64 version (because for some reason - the default download version is x86)

Save base64 string as PDF at client side with JavaScript

you can use this function to download file from base64.

function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}

This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.

i hope this will help of you thanks

how to calculate binary search complexity

A binary search works by dividing the problem in half repeatedly, something like this (details omitted):

Example looking for 3 in [4,1,3,8,5]

  1. Order your list of items [1,3,4,5,8]
  2. Look at the middle item (4),
    • If it is what you are looking for, stop
    • If it is greater, look at the first half
    • If it is less, look at the second half
  3. Repeat step 2 with the new list [1, 3], find 3 and stop

It is a bi-nary search when you divide the problem in 2.

The search only requires log2(n) steps to find the correct value.

I would recommend Introduction to Algorithms if you want to learn about algorithmic complexity.

Testing if a site is vulnerable to Sql Injection

A login page isn't the only part of a database-driven website that interacts with the database.

Any user-editable input which is used to construct a database query is a potential entry point for a SQL injection attack. The attacker may not necessarily login to the site as an admin through this attack, but can do other things. They can change data, change server settings, etc. depending on the nature of the application's interaction with the database.

Appending a ' to an input is usually a pretty good test to see if it generates an error or otherwise produces unexpected behavior on the site. It's an indication that the user input is being used to build a raw query and the developer didn't expect a single quote, which changes the query structure.

Keep in mind that one page may be secure against SQL injection while another one may not. The login page, for example, may be hardened against such attacks. But a different page elsewhere in the site might be wide open. So, for example, if one wanted to login as an admin then one can use the SQL injection on that other page to change the admin password. Then return to the perfectly non-SQL-injectable login page and login as the admin.

What does "The APR based Apache Tomcat Native library was not found" mean?

It means exactly what it says: "The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path"

The library referred to is bundled into an OS specific dll (tcnative-1.dll) loaded via JNI. It allows tomcat to use OS functionalities not provided in the Java Runtime (such as sendfile, epoll, OpenSSL, system status, etc.). Tomcat will run just fine without it, but for some use cases, it will be faster with the native libraries.

If you really want it, download the tcnative-1.dll (or libtcnative.so for Linux) and put it in the bin folder, and add a system property to the launch configuration of the tomcat server in eclipse.

 -Djava.library.path=c:\dev\tomcat\bin

jQuery: How to get the event object in an event handler function without passing it as an argument?

in IE you can get the event object by window.event in other browsers with no 'use strict' directive, it is possible to get by arguments.callee.caller.arguments[0].

function myFunc(p1, p2, p3) {
    var evt = window.event || arguments.callee.caller.arguments[0];
}

What is the correct way of reading from a TCP socket in C/C++?

This is an article that I always refer to when working with sockets..

THE WORLD OF SELECT()

It will show you how to reliably use 'select()' and contains some other useful links at the bottom for further info on sockets.

How to set entire application in portrait mode only?

Yes you can do this both programmatically and for all your activities making an AbstractActivity that all your activities extends.

public abstract class AbstractActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}

This abstract activity can also be used for a global menu.

Ant if else condition?

The if attribute does not exist for <copy>. It should be applied to the <target>.

Below is an example of how you can use the depends attribute of a target and the if and unless attributes to control execution of dependent targets. Only one of the two should execute.

<target name="prepare-copy" description="copy file based on condition"
    depends="prepare-copy-true, prepare-copy-false">
</target>

<target name="prepare-copy-true" description="copy file based on condition"
    if="copy-condition">
    <echo>Get file based on condition being true</echo>
    <copy file="${some.dir}/true" todir="." />
</target>

<target name="prepare-copy-false" description="copy file based on false condition" 
    unless="copy-condition">
    <echo>Get file based on condition being false</echo>
    <copy file="${some.dir}/false" todir="." />
</target>

If you are using ANT 1.8+, then you can use property expansion and it will evaluate the value of the property to determine the boolean value. So, you could use if="${copy-condition}" instead of if="copy-condition".

In ANT 1.7.1 and earlier, you specify the name of the property. If the property is defined and has any value (even an empty string), then it will evaluate to true.

How to change the remote repository for a git submodule?

Just edit your .git/config file. For example; if you have a "common" submodule you can do this in the super-module:

git config submodule.common.url /data/my_local_common

How to use shared memory with Linux in C

Here's a mmap example:

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/*
 * pvtmMmapAlloc - creates a memory mapped file area.  
 * The return value is a page-aligned memory value, or NULL if there is a failure.
 * Here's the list of arguments:
 * @mmapFileName - the name of the memory mapped file
 * @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
 * @create - determines whether or not the area should be created.
 */
void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)  
{      
  void * retv = NULL;                                                                                              
  if (create)                                                                                         
  {                                                                                                   
    mode_t origMask = umask(0);                                                                       
    int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);                                           
    umask(origMask);                                                                                  
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      perror("open mmapFd failed");                                                                   
      return NULL;                                                                                    
    }                                                                                                 
    if ((ftruncate(mmapFd, size) == 0))               
    {                                                                                                 
      int result = lseek(mmapFd, size - 1, SEEK_SET);               
      if (result == -1)                                                                               
      {                                                                                               
        perror("lseek mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               

      /* Something needs to be written at the end of the file to                                      
       * have the file actually have the new size.                                                    
       * Just writing an empty string at the current file position will do.                           
       * Note:                                                                                        
       *  - The current position in the file is at the end of the stretched                           
       *    file due to the call to lseek().  
              *  - The current position in the file is at the end of the stretched                    
       *    file due to the call to lseek().                                                          
       *  - An empty string is actually a single '\0' character, so a zero-byte                       
       *    will be written at the last byte of the file.                                             
       */                                                                                             
      result = write(mmapFd, "", 1);                                                                  
      if (result != 1)                                                                                
      {                                                                                               
        perror("write mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
      retv  =  mmap(NULL, size,   
                  PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                     

      if (retv == MAP_FAILED || retv == NULL)                                                         
      {                                                                                               
        perror("mmap");                                                                               
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
    }                                                                                                 
  }                                                                                                   
  else                                                                                                
  {                                                                                                   
    int mmapFd = open(mmapFileName, O_RDWR, 00666);                                                   
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      return NULL;                                                                                    
    }                                                                                                 
    int result = lseek(mmapFd, 0, SEEK_END);                                                          
    if (result == -1)                                                                                 
    {                                                                                                 
      perror("lseek mmapFd failed");                  
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 
    if (result == 0)                                                                                  
    {                                                                                                 
      perror("The file has 0 bytes");                           
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                              
    retv  =  mmap(NULL, size,     
                PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                       

    if (retv == MAP_FAILED || retv == NULL)                                                           
    {                                                                                                 
      perror("mmap");                                                                                 
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 

    close(mmapFd);                                                                                    

  }                                                                                                   
  return retv;                                                                                        
}                                                                                                     

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

how to change language for DataTable

//Spanish
$('#TableName').DataTable({
    "language": {
        "sProcessing":    "Procesando...",
        "sLengthMenu":    "Mostrar _MENU_ registros",
        "sZeroRecords":   "No se encontraron resultados",
        "sEmptyTable":    "Ningún dato disponible en esta tabla",
        "sInfo":          "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
        "sInfoEmpty":     "Mostrando registros del 0 al 0 de un total de 0 registros",
        "sInfoFiltered":  "(filtrado de un total de _MAX_ registros)",
        "sInfoPostFix":   "",
        "sSearch":        "Buscar:",
        "sUrl":           "",
        "sInfoThousands":  ",",
        "sLoadingRecords": "Cargando...",
        "oPaginate": {
            "sFirst":    "Primero",
            "sLast":    "Último",
            "sNext":    "Siguiente",
            "sPrevious": "Anterior"
        },
        "oAria": {
            "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
            "sSortDescending": ": Activar para ordenar la columna de manera descendente"
        }
    }
});

Also using a cdn:

//cdn.datatables.net/plug-ins/a5734b29083/i18n/Spanish.json

More options: http://www.datatables.net/plug-ins/i18n/English [| Spanish | etc]

how to merge 200 csv files in Python

If the files aren't numbered in order, take the hassle-free approach below: Python 3.6 on windows machine:

import pandas as pd
from glob import glob

interesting_files = glob("C:/temp/*.csv") # it grabs all the csv files from the directory you mention here

df_list = []
for filename in sorted(interesting_files):

df_list.append(pd.read_csv(filename))
full_df = pd.concat(df_list)

# save the final file in same/different directory:
full_df.to_csv("C:/temp/merged_pandas.csv", index=False)

Show current assembly instruction in GDB

From within gdb press Ctrl x 2 and the screen will split into 3 parts.

First part will show you the normal code in high level language.

Second will show you the assembly equivalent and corresponding instruction Pointer.

Third will present you the normal gdb prompt to enter commands.

See the screen shot

VarBinary vs Image SQL Server Data Type to Store Binary Data?

There is also the rather spiffy FileStream, introduced in SQL Server 2008.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Check if object value exists within a Javascript array of objects and if not add a new object to array

It's rather trivial to check for existing username:

var arr = [{ id: 1, username: 'fred' }, 
  { id: 2, username: 'bill'}, 
  { id: 3, username: 'ted' }];

function userExists(username) {
  return arr.some(function(el) {
    return el.username === username;
  }); 
}

console.log(userExists('fred')); // true
console.log(userExists('bred')); // false

But it's not so obvious what to do when you have to add a new user to this array. The easiest way out - just pushing a new element with id equal to array.length + 1:

function addUser(username) {
  if (userExists(username)) {
    return false; 
  }
  arr.push({ id: arr.length + 1, username: username });
  return true;
}

addUser('fred'); // false
addUser('bred'); // true, user `bred` added

It will guarantee the IDs uniqueness, but will make this array look a bit strange if some elements will be taken off its end.

What is the easiest way to parse an INI file in Java?

As simple as 80 lines:

package windows.prefs;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IniFile {

   private Pattern  _section  = Pattern.compile( "\\s*\\[([^]]*)\\]\\s*" );
   private Pattern  _keyValue = Pattern.compile( "\\s*([^=]*)=(.*)" );
   private Map< String,
      Map< String,
         String >>  _entries  = new HashMap<>();

   public IniFile( String path ) throws IOException {
      load( path );
   }

   public void load( String path ) throws IOException {
      try( BufferedReader br = new BufferedReader( new FileReader( path ))) {
         String line;
         String section = null;
         while(( line = br.readLine()) != null ) {
            Matcher m = _section.matcher( line );
            if( m.matches()) {
               section = m.group( 1 ).trim();
            }
            else if( section != null ) {
               m = _keyValue.matcher( line );
               if( m.matches()) {
                  String key   = m.group( 1 ).trim();
                  String value = m.group( 2 ).trim();
                  Map< String, String > kv = _entries.get( section );
                  if( kv == null ) {
                     _entries.put( section, kv = new HashMap<>());   
                  }
                  kv.put( key, value );
               }
            }
         }
      }
   }

   public String getString( String section, String key, String defaultvalue ) {
      Map< String, String > kv = _entries.get( section );
      if( kv == null ) {
         return defaultvalue;
      }
      return kv.get( key );
   }

   public int getInt( String section, String key, int defaultvalue ) {
      Map< String, String > kv = _entries.get( section );
      if( kv == null ) {
         return defaultvalue;
      }
      return Integer.parseInt( kv.get( key ));
   }

   public float getFloat( String section, String key, float defaultvalue ) {
      Map< String, String > kv = _entries.get( section );
      if( kv == null ) {
         return defaultvalue;
      }
      return Float.parseFloat( kv.get( key ));
   }

   public double getDouble( String section, String key, double defaultvalue ) {
      Map< String, String > kv = _entries.get( section );
      if( kv == null ) {
         return defaultvalue;
      }
      return Double.parseDouble( kv.get( key ));
   }
}

Take multiple lists into dataframe

Adding one more scalable solution.

lists = [lst1, lst2, lst3, lst4]
df = pd.concat([pd.Series(x) for x in lists], axis=1)

How to lookup JNDI resources on WebLogic?

java is the root JNDI namespace for resources. What the original snippet of code means is that the container the application was initially deployed in did not apply any additional namespaces to the JNDI context you retrieved (as an example, Tomcat automatically adds all resources to the namespace comp/env, so you would have to do dataSource = (javax.sql.DataSource) context.lookup("java:comp/env/jdbc/myDataSource"); if the resource reference name is jdbc/myDataSource).

To avoid having to change your legacy code I think if you register the datasource with the name myDataSource (remove the jdbc/) you should be fine. Let me know if that works.

DynamoDB vs MongoDB NoSQL

We chose a combination of Mongo/Dynamo for a healthcare product. Basically mongo allows better searching, but the hosted Dynamo is great because its HIPAA compliant without any extra work. So we host the mongo portion with no personal data on a standard setup and allow amazon to deal with the HIPAA portion in terms of infrastructure. We can query certain items from mongo which bring up documents with pointers (ID's) of the relatable Dynamo document.

The main reason we chose to do this using mongo instead of hosting the entire application on dynamo was for 2 reasons. First, we needed to preform location based searches which mongo is great at and at the time, Dynamo was not, but they do have an option now.

Secondly was that some documents were unstructured and we did not know ahead of time what the data would be, so for example lets say user a inputs a document in the "form" collection like this: {"username": "user1", "email": "[email protected]"}. And another user puts this in the same collection {"phone": "813-555-3333", "location": [28.1234,-83.2342]}. With mongo we can search any of these dynamic and unknown fields at any time, with Dynamo, you could do this but would have to make a index every time a new field was added that you wanted searchable. So if you have never had a phone field in your Dynamo document before and then all of the sudden, some one adds it, its completely unsearchable.

Now this brings up another point in which you have mentioned. Sometimes choosing the right solution for the job does not always mean choosing the best product for the job. For example you may have a client who needs and will use the system you created for 10+ years. Going with a SaaS/IaaS solution that is good enough to get the job done may be a better option as you can rely on amazon to have up-kept and maintained their systems over the long haul.

Android: I lost my android key store, what should I do?

If you lost a keystore file, don't create/update the new one with another set of value. First do the thorough search. Because it will overwrite the old one, so it will not match to your previous apk.

If you use eclipse most probably it will store in default path. For MAC (eclipse) it will be in your elispse installation path something like:

/Applications/eclipse/Eclipse.app/Contents/MacOS/

then your keystore file without any extension. You need root privilege to access this path (file).

How do I make a WPF TextBlock show my text on multiple lines?

Use the property TextWrapping of the TextBlock element:

<TextBlock Text="StackOverflow Forum"
           Width="100"
           TextWrapping="WrapWithOverflow"/>

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

If using Nginx and getting a similar problem, then this might help:

Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.

If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

NSUserDefaults - How to tell if a key exists

Swift 3 / 4:

Here is a simple extension for Int/Double/Float/Bool key-value types that mimic the Optional-return behavior of the other types accessed through UserDefaults.

(Edit Aug 30 2018: Updated with more efficient syntax from Leo's suggestion.)

extension UserDefaults {
    /// Convenience method to wrap the built-in .integer(forKey:) method in an optional returning nil if the key doesn't exist.
    func integerOptional(forKey: String) -> Int? {
        return self.object(forKey: forKey) as? Int
    }
    /// Convenience method to wrap the built-in .double(forKey:) method in an optional returning nil if the key doesn't exist.
    func doubleOptional(forKey: String) -> Double? {
        return self.object(forKey: forKey) as? Double
    }
    /// Convenience method to wrap the built-in .float(forKey:) method in an optional returning nil if the key doesn't exist.
    func floatOptional(forKey: String) -> Float? {
        return self.object(forKey: forKey) as? Float
    }
    /// Convenience method to wrap the built-in .bool(forKey:) method in an optional returning nil if the key doesn't exist.
    func boolOptional(forKey: String) -> Bool? {
        return self.object(forKey: forKey) as? Bool
    }
}

They are now more consistent alongside the other built-in get methods (string, data, etc.). Just use the get methods in place of the old ones.

let AppDefaults = UserDefaults.standard

// assuming the key "Test" does not exist...

// old:
print(AppDefaults.integer(forKey: "Test")) // == 0
// new:
print(AppDefaults.integerOptional(forKey: "Test")) // == nil

How to make a transparent HTML button?

**add the icon top button like this **

_x000D_
_x000D_
#copy_btn{_x000D_
 align-items: center;_x000D_
 position: absolute;_x000D_
 width: 30px;_x000D_
  height: 30px;_x000D_
     background-color: Transparent;_x000D_
    background-repeat:no-repeat;_x000D_
    border: none;_x000D_
    cursor:pointer;_x000D_
    overflow: hidden;_x000D_
    outline:none;_x000D_
}_x000D_
.icon_copy{_x000D_
 position: absolute;_x000D_
 padding: 0px;_x000D_
 top:0;_x000D_
 left: 0;_x000D_
width: 25px;_x000D_
  height: 35px;_x000D_
  _x000D_
}
_x000D_
<button id="copy_btn">_x000D_
_x000D_
                        <img class="icon_copy" src="./assest/copy.svg" alt="Copy Text">_x000D_
</button>
_x000D_
_x000D_
_x000D_

How can I use grep to find a word inside a folder?

Why not do a recursive search to find all instances in sub directories:

grep -r 'text' *

This works like a charm.

How to activate "Share" button in android app?

Share Any File as below ( Kotlin ) :
first create a folder named xml in the res folder and create a new XML Resource File named provider_paths.xml and put the below code inside it :

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path
        name="files"
        path="."/>

    <external-path
        name="external_files"
        path="."/>
</paths>

now go to the manifests folder and open the AndroidManifest.xml and then put the below code inside the <application> tag :

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>

now you put the below code in the setOnLongClickListener :

share_btn.setOnClickListener {
    try {
        val file = File("pathOfFile")
        if(file.exists()) {
            val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
            val intent = Intent(Intent.ACTION_SEND)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setType("*/*")
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent)
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        toast("Error")
    }
}

How to zero pad a sequence of integers in bash so that all have the same width?

In your specific case though it's probably easiest to use the -f flag to seq to get it to format the numbers as it outputs the list. For example:

for i in $(seq -f "%05g" 10 15)
do
  echo $i
done

will produce the following output:

00010
00011
00012
00013
00014
00015

More generally, bash has printf as a built-in so you can pad output with zeroes as follows:

$ i=99
$ printf "%05d\n" $i
00099

You can use the -v flag to store the output in another variable:

$ i=99
$ printf -v j "%05d" $i
$ echo $j
00099

Notice that printf supports a slightly different format to seq so you need to use %05d instead of %05g.

MySQL convert date string to Unix timestamp

Here's an example of how to convert DATETIME to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))

Here's an example of how to change date format:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')

Documentation: UNIX_TIMESTAMP, FROM_UNIXTIME

ImportError: No module named Crypto.Cipher

This problem can be fixed by installing the C++ compiler (python27 or python26). Download it from Microsoft https://www.microsoft.com/en-us/download/details.aspx?id=44266 and re-run the command : pip install pycrypto to run the gui web access when you kill the process of easy_install.exe.

Bootstrap 3 scrollable div for table

You can use too

style="overflow-y: scroll; height:150px; width: auto;"

It's works for me

What is the point of the diamond operator (<>) in Java 7?

Your understanding is slightly flawed. The diamond operator is a nice feature as you don't have to repeat yourself. It makes sense to define the type once when you declare the type but just doesn't make sense to define it again on the right side. The DRY principle.

Now to explain all the fuzz about defining types. You are right that the type is removed at runtime but once you want to retrieve something out of a List with type definition you get it back as the type you've defined when declaring the list otherwise it would lose all specific features and have only the Object features except when you'd cast the retrieved object to it's original type which can sometimes be very tricky and result in a ClassCastException.

Using List<String> list = new LinkedList() will get you rawtype warnings.

Math operations from string

The asker commented:

I figure that if I understand a problem well enough to write a program that can figure it out, I don't need to do the work manually.

If he's writing a math expression solver as a learning exercise, using eval() isn't going to help. Plus it's terrible design.

You might consider making a calculator using Reverse Polish Notation instead of standard math notation. It simplifies the parsing considerably. It would still be a good exercise

Show dialog from fragment?

You should use a DialogFragment instead.

How can I change the color of AlertDialog title and the color of the line under it

check this is useful for you...

public void setCustomTitle (View customTitleView)

you get detail from following link.

http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setCustomTitle%28android.view.View%29

CustomDialog.java

Dialog alert = new Dialog(this);
    alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
    alert.setContentView(R.layout.title);
    TextView msg = (TextView)alert.findViewById(R.id.textView1);
    msg.setText("Hello Friends.\nIP address : 111.111.1.111");
    alert.show();

title.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Set IP address"
    android:textColor="#ff0000"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<ImageView 
    android:layout_width="fill_parent"
    android:layout_height="2dp"
    android:layout_marginTop="5dp"
    android:background="#00ff00"
    />
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#775500"
    android:textAppearance="?android:attr/textAppearanceLarge" />

enter image description here

How to Set Active Tab in jQuery Ui

Simple jQuery solution - find the <a> element where href="x" and click it:

$('a[href="#tabs-2"]').click();

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

Alter and Assign Object Without Side Effects

This is a textbook case for a constructor function:

var myArray = [];

function myElement(id, value){
    this.id = id
    this.value = value
}

myArray[0] = new myElement(0,1)
myArray[1] = new myElement(2,3)
// or myArray.push(new myElement(1, 1))

Get name of current script in Python

import sys
print(sys.argv[0])

This will print foo.py for python foo.py, dir/foo.py for python dir/foo.py, etc. It's the first argument to python. (Note that after py2exe it would be foo.exe.)

How do I disable a Pylint warning?

You can also use the following command:

pylint --disable=C0321  test.py

My Pylint version is 0.25.1.

read file in classpath

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class readFile {
    /**
     * feel free to make any modification I have have been here so I feel you
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        File dir = new File(".");// read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }`enter code here`

}

Adding Permissions in AndroidManifest.xml in Android Studio?

Go to Android Manifest.xml and be sure to add the <uses-permission tag > inside the manifest tag but Outside of all other tags..

<manifest xlmns:android...>

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

This is an example of the permission of using Internet.

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

I didn't think this was possible: I had to delete flutter folder and reinstall it from scratch!

Pygame Drawing a Rectangle

here's how:

import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
pygame.quit()

Const in JavaScript: when to use it and is it necessary?

To integrate the previous answers, there's an obvious advantage in declaring constant variables, apart from the performance reason: if you accidentally try to change or re-declare them in the code, the program will respectively not change the value or throw an error.

For example, compare:

// Will output 'SECRET'

const x = 'SECRET'
if (x = 'ANOTHER_SECRET') {  // Warning! assigning a value variable in an if condition
    console.log (x)
}

with:

// Will output 'ANOTHER_SECRET'

var y = 'SECRET'
if (y = 'ANOTHER_SECRET') { 
    console.log (y)
}

or

// Will throw TypeError: const 'x' has already been declared

const x = "SECRET"

/*  complex code */

var x = 0

with

// Will reassign y and cause trouble

var y = "SECRET"

/*  complex code */

var y = 0

CORS - How do 'preflight' an httprequest?

During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.

For example, suppose the browser makes a request with the following headers:

Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header

Your server should then respond with the following headers:

Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header

Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.

Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

AngularJS $location not changing the path

setTimeout(function() { $location.path("/abc"); },0);

it should solve your problem.

javac: invalid target release: 1.8

Most of the time, these type of issues happen due to incorrect java version. Make sure your PATH and JAVA_HOME variables are pointing to the correct version.

Python: SyntaxError: non-keyword after keyword arg

To really get this clear, here's my for-beginners answer: You inputed the arguments in the wrong order.
A keyword argument has this style:

nullable=True, unique=False

A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:

name="Ricardo", fruit="chontaduro" 

This syntax error asks you to first put name="Ricardo" and all of its kind (non-keyword) before those like nullable=True.

How to count lines in a document?

cat file.log | wc -l | grep -oE '\d+'
  • grep -oE '\d+': In order to return the digit numbers ONLY.

Why shouldn't `&apos;` be used to escape single quotes?

&quot; is valid in both HTML5 and HTML4.

&apos; is valid in HTML5, but not HTML4. However, most browsers support &apos; for HTML4 anyway.