Programs & Examples On #Del

Delete an element from a dictionary

Simply call del d['key'].

However, in production, it is always a good practice to check if 'key' exists in d.

if 'key' in d:
    del d['key']

When is del useful in Python?

To add a few points to above answers: del x

Definition of x indicates r -> o (a reference r pointing to an object o) but del x changes r rather than o. It is an operation on the reference (pointer) to object rather than the object associated with x. Distinguishing between r and o is key here.

  • It removes it from locals().
  • Removes it from globals() if x belongs there.
  • Removes it from the stack frame (removes the reference physically from it, but the object itself resides in object pool and not in the stack frame).
  • Removes it from the current scope. It is very useful to limit the span of definition of a local variable, which otherwise can cause problems.
  • It is more about declaration of the name rather than definition of content.
  • It affects where x belongs to, not where x points to. The only physical change in memory is this. For example if x is in a dictionary or list, it (as a reference) is removed from there(and not necessarily from the object pool). In this example, the dictionary it belongs is the stack frame (locals()), which overlaps with globals().

Delete all objects in a list

tl;dr;

mylist.clear()  # Added in Python 3.3
del mylist[:]

are probably the best ways to do this. The rest of this answer tries to explain why some of your other efforts didn't work.


cpython at least works on reference counting to determine when objects will be deleted. Here you have multiple references to the same objects. a refers to the same object that c[0] references. When you loop over c (for i in c:), at some point i also refers to that same object. the del keyword removes a single reference, so:

for i in c:
   del i

creates a reference to an object in c and then deletes that reference -- but the object still has other references (one stored in c for example) so it will persist.

In the same way:

def kill(self):
    del self

only deletes a reference to the object in that method. One way to remove all the references from a list is to use slice assignment:

mylist = list(range(10000))
mylist[:] = []
print(mylist)

Apparently you can also delete the slice to remove objects in place:

del mylist[:]  #This will implicitly call the `__delslice__` or `__delitem__` method.

This will remove all the references from mylist and also remove the references from anything that refers to mylist. Compared that to simply deleting the list -- e.g.

mylist = list(range(10000))
b = mylist
del mylist
#here we didn't get all the references to the objects we created ...
print(b) #[0, 1, 2, 3, 4, ...]

Finally, more recent python revisions have added a clear method which does the same thing that del mylist[:] does.

mylist = [1, 2, 3]
mylist.clear()
print(mylist)

CSS transition with visibility not working

Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337

You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0 only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden, you can eliminate this problem:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:20px;_x000D_
}_x000D_
.menu {_x000D_
    visibility:hidden;_x000D_
    opacity:0;_x000D_
    transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
    _x000D_
    background:#eee;_x000D_
    width:100px;_x000D_
    margin:0;_x000D_
    padding:5px;_x000D_
    list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
    visibility:visible;_x000D_
    opacity:1;_x000D_
}
_x000D_
<div>_x000D_
  <a href="#">Open Menu</a>_x000D_
  <ul class="menu">_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Return the characters after Nth character in a string

If your numbers are always 4 digits long:

=RIGHT(A1,LEN(A1)-5) //'0001 Baseball' returns Baseball

If the numbers are variable (i.e. could be more or less than 4 digits) then:

=RIGHT(A1,LEN(A1)-FIND(" ",A1,1)) //'123456 Baseball’ returns Baseball

Angular2: How to load data before rendering the component?

update

original

When console.log(this.ev) is executed after this.fetchEvent();, this doesn't mean the fetchEvent() call is done, this only means that it is scheduled. When console.log(this.ev) is executed, the call to the server is not even made and of course has not yet returned a value.

Change fetchEvent() to return a Promise

     fetchEvent(){
        return  this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
     }

change ngOnInit() to wait for the Promise to complete

    ngOnInit() {
        this.fetchEvent().then(() =>
        console.log(this.ev)); // Now has value;
    }

This actually won't buy you much for your use case.

My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>

and in ngOnInit()

    isDataAvailable:boolean = false;

    ngOnInit() {
        this.fetchEvent().then(() =>
        this.isDataAvailable = true); // Now has value;
    }

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

Try this (edited):

ctx.Database.ExecuteSqlCommand(sql, new SqlParameter("FirstName", firstName), 
                                    new SqlParameter("Id", id));

Previous idea was wrong.

How do I fit an image (img) inside a div and keep the aspect ratio?

Try CSS:

img {
  object-fit: cover;
  height: 48px;
}

How to import an existing directory into Eclipse?

There is no need to create a Java project and let unnecessary Java dependencies and libraries to cling into the project. The question is regarding importing an existing directory into eclipse

Suppose the directory is present in C:/harley/mydir. What you have to do is the following:

  • Create a new project (Right click on Project explorer, select New -> Project; from the wizard list, select General -> Project and click next.)

  • Give to the project the same name of your target directory (in this case mydir)

  • Uncheck Use default location and give the exact location, for example C:/harley/mydir

  • Click on Finish

You are done. I do it this way.

Extract a part of the filepath (a directory) in Python

First, see if you have splitunc() as an available function within os.path. The first item returned should be what you want... but I am on Linux and I do not have this function when I import os and try to use it.

Otherwise, one semi-ugly way that gets the job done is to use:

>>> pathname = "\\C:\\mystuff\\project\\file.py"
>>> pathname
'\\C:\\mystuff\\project\\file.py'
>>> print pathname
\C:\mystuff\project\file.py
>>> "\\".join(pathname.split('\\')[:-2])
'\\C:\\mystuff'
>>> "\\".join(pathname.split('\\')[:-1])
'\\C:\\mystuff\\project'

which shows retrieving the directory just above the file, and the directory just above that.

pandas: to_numeric for multiple columns

You can use:

print df.columns[5:]
Index([u'2004', u'2005', u'2006', u'2007', u'2008', u'2009', u'2010', u'2011',
       u'2012', u'2013', u'2014'],
      dtype='object')

for col in  df.columns[5:]:
    df[col] = pd.to_numeric(df[col], errors='coerce')

print df
       GeoName      ComponentName  IndustryId  IndustryClassification  \
37926  Alabama  Real GDP by state           9                     213   
37951  Alabama  Real GDP by state          34                      42   
37932  Alabama  Real GDP by state          15                     327   

                                      Description  2004   2005   2006   2007  \
37926               Support activities for mining    99     98    117    117   
37951                            Wholesale  trade  9898  10613  10952  11034   
37932  Nonmetallic mineral products manufacturing   980    968    940   1084   

        2008  2009  2010  2011  2012  2013     2014  
37926    115    87    96    95   103   102      NaN  
37951  11075  9722  9765  9703  9600  9884  10199.0  
37932    861   724   714   701   589   641      NaN  

Another solution with filter:

print df.filter(like='20')
       2004   2005   2006   2007   2008  2009  2010  2011  2012  2013   2014
37926    99     98    117    117    115    87    96    95   103   102   (NA)
37951  9898  10613  10952  11034  11075  9722  9765  9703  9600  9884  10199
37932   980    968    940   1084    861   724   714   701   589   641   (NA)

for col in  df.filter(like='20').columns:
    df[col] = pd.to_numeric(df[col], errors='coerce')
print df
       GeoName      ComponentName  IndustryId  IndustryClassification  \
37926  Alabama  Real GDP by state           9                     213   
37951  Alabama  Real GDP by state          34                      42   
37932  Alabama  Real GDP by state          15                     327   

                                      Description  2004   2005   2006   2007  \
37926               Support activities for mining    99     98    117    117   
37951                            Wholesale  trade  9898  10613  10952  11034   
37932  Nonmetallic mineral products manufacturing   980    968    940   1084   

        2008  2009  2010  2011  2012  2013     2014  
37926    115    87    96    95   103   102      NaN  
37951  11075  9722  9765  9703  9600  9884  10199.0  
37932    861   724   714   701   589   641      NaN  

Join vs. sub-query

I just thinking about the same problem, but I am using subquery in the FROM part. I need connect and query from large tables, the "slave" table have 28 million record but the result is only 128 so small result big data! I am using MAX() function on it.

First I am using LEFT JOIN because I think that is the correct way, the mysql can optimalize etc. Second time just for testing, I rewrite to sub-select against the JOIN.

LEFT JOIN runtime: 1.12s SUB-SELECT runtime: 0.06s

18 times faster the subselect than the join! Just in the chokito adv. The subselect looks terrible but the result ...

Folder is locked and I can't unlock it

This was the first time I had this issue. I even tried to restart PC, without effect. This solves my problem:

Solution for me:

  1. Right Click on Project Working Directory.
  2. Navigate TortoiseSVN.
  3. Navigate To Clean Up.
  4. Leave all default options, and check Break Locks
  5. Click OK

This works for me. I was able to commit changes.

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

How to make an installer for my C# application?

There are several methods, two of which are as follows. Provide a custom installer or a setup project.

Here is how to create a custom installer

[RunInstaller(true)]
public class MyInstaller : Installer
{
    public HelloInstaller()
        : base()
    {
    }

    public override void Commit(IDictionary mySavedState)
    {
        base.Commit(mySavedState);
        System.IO.File.CreateText("Commit.txt");
    }

    public override void Install(IDictionary stateSaver)
    {
        base.Install(stateSaver);
        System.IO.File.CreateText("Install.txt");
    }

    public override void Uninstall(IDictionary savedState)
    {
        base.Uninstall(savedState);
        File.Delete("Commit.txt");
        File.Delete("Install.txt");
    }

    public override void Rollback(IDictionary savedState)
    {
        base.Rollback(savedState);
        File.Delete("Install.txt");
    }
}

To add a setup project

  • Menu file -> New -> Project --> Other Projects Types --> Setup and Deployment

  • Set properties of the project, using the properties window

The article How to create a Setup package by using Visual Studio .NET provides the details.

Turning multiple lines into one comma separated line

There are many ways it can be achieved. The tool you use mostly depends on your own preference or experience.

Using tr command:

tr '\n' ',' < somefile

Using awk:

awk -F'\n' '{if(NR == 1) {printf $0} else {printf ","$0}}' somefile

Asynchronous Process inside a javascript for loop

Any recommendation on how to fix this?

Several. You can use bind:

for (i = 0; i < j; i++) {
    asycronouseProcess(function (i) {
        alert(i);
    }.bind(null, i));
}

Or, if your browser supports let (it will be in the next ECMAScript version, however Firefox already supports it since a while) you could have:

for (i = 0; i < j; i++) {
    let k = i;
    asycronouseProcess(function() {
        alert(k);
    });
}

Or, you could do the job of bind manually (in case the browser doesn't support it, but I would say you can implement a shim in that case, it should be in the link above):

for (i = 0; i < j; i++) {
    asycronouseProcess(function(i) {
        return function () {
            alert(i)
        }
    }(i));
}

I usually prefer let when I can use it (e.g. for Firefox add-on); otherwise bind or a custom currying function (that doesn't need a context object).

Clear Cache in Android Application programmatically

I think you're supposed to place clearApplicationData() before the super.OnDestroy().

Your app can't process any methods when it has been shut down.

OS X Terminal Colors

You can use the Linux based syntax in one of your startup scripts. Just tested this on an OS X Mountain Lion box.

eg. in your ~/.bash_profile

export TERM="xterm-color" 
export PS1='\[\e[0;33m\]\u\[\e[0m\]@\[\e[0;32m\]\h\[\e[0m\]:\[\e[0;34m\]\w\[\e[0m\]\$ '

This gives you a nice colored prompt. To add the colored ls output, you can add alias ls="ls -G".

To test, just run a source ~/.bash_profile to update your current terminal.

Side note about the colors: The colors are preceded by an escape sequence \e and defined by a color value, composed of [style;color+m] and wrapped in an escaped [] sequence. eg.

  • red = \[\e[0;31m\]
  • bold red (style 1) = \[\e[1;31m\]
  • clear coloring = \[\e[0m\]

I always add a slightly modified color-scheme in the root's .bash_profile to make the username red, so I always see clearly if I'm logged in as root (handy to avoid mistakes if I have many terminal windows open).

In /root/.bash_profile:

PS1='\[\e[0;31m\]\u\[\e[0m\]@\[\e[0;32m\]\h\[\e[0m\]:\[\e[0;34m\]\w\[\e[0m\]\$ '

For all my SSH accounts online I make sure to put the hostname in red, to distinguish if I'm in a local or remote terminal. Just edit the .bash_profile file in your home dir on the server.. If there is no .bash_profile file on the server, you can create it and it should be sourced upon login.

If this is not working as expected for you, please read some of the comments below since I'm not using MacOS very often..

If you want to do this on a remote server, check if the ~/.bash_profile file exists. If not, simply create it and it should be automatically sourced upon your next login.

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

In your top level build.gradle you seem to have the code

android {
   compileSdkVersion 19
   buildToolsVersion "19.1" 
}

You can't have this code at the top level build.gradle because the android build plugin isn't loaded just yet. You can define the compile version and build tools version in the app level build.gradle.

Is it possible to get the index you're sorting over in Underscore.js?

More generally, under most circumstances, underscore functions that take a list and argument as the first two arguments, provide access to the list index as the next to last argument to the iterator. This is an important distinction when it comes to the two underscore functions, _.reduce and _.reduceRight, that take 'memo' as their third argument -- in the case of these two the index will not be the second argument, but the third:

var destination = (function() {
    var fields = ['_333st', 'offroad', 'fbi'];
    return _.reduce(waybillInfo.destination.split(','), function(destination, segment, index) {
        destination[fields[index]] = segment;
        return destination;
    }, {});
})();

console.log(destination);            
/*
_333st: "NYARFTW  TX"
fbi: "FTWUP"
offroad: "UP"

The following is better of course but not demonstrate my point:
var destination = _.object(['_333st', 'offroad', 'fbi'], waybillInfo.destination.split(','));
*/

So if you wanted you could get the index using underscore itself: _.last(_.initial(arguments)). A possible exception (I haven't tried) is _.map, as it can take an object instead of a list: "If list is a JavaScript object, iterator's arguments will be (value, key, list)." -- see: http://underscorejs.org/#map

Create list or arrays in Windows Batch

Sometimes the array element may be very long, at that time you can create an array in this way:

set list=a
set list=%list%;b 
set list=%list%;c 
set list=%list%;d

Then show it:

@echo off
for %%a in (%list%) do ( 
 echo %%a
 echo/
)

SQL Server - Adding a string to a text column (concat equivalent)

To Join two string in SQL Query use function CONCAT(Express1,Express2,...)

Like....

SELECT CODE, CONCAT(Rtrim(FName), " " , TRrim(LName)) as Title FROM MyTable

Best way to add Activity to an Android project in Eclipse?

I have create a eclipse plugin to create activity in one click .

Just download the Plugin from https://docs.google.com/file/d/0B63U_IjxUP_GMkdYZzc1Y3lEM1U/edit?usp=sharing

Paste the plugin in the dropins folder in Eclipse and restart eclipse

For more details please see my blog
http://shareatramachandran.blogspot.in/2013/06/android-activity-plugin-for-eclispe.html

Need your comment on this if it was helpful...

SQL select join: is it possible to prefix all columns as 'prefix.*'?

There is no SQL standard for this.

However With code generation (either on demand as the tables are created or altered or at runtime), you can do this quite easily:

CREATE TABLE [dbo].[stackoverflow_329931_a](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [col2] [nchar](10) NULL,
    [col3] [nchar](10) NULL,
    [col4] [nchar](10) NULL,
 CONSTRAINT [PK_stackoverflow_329931_a] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[stackoverflow_329931_b](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [col2] [nchar](10) NULL,
    [col3] [nchar](10) NULL,
    [col4] [nchar](10) NULL,
 CONSTRAINT [PK_stackoverflow_329931_b] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

DECLARE @table1_name AS varchar(255)
DECLARE @table1_prefix AS varchar(255)
DECLARE @table2_name AS varchar(255)
DECLARE @table2_prefix AS varchar(255)
DECLARE @join_condition AS varchar(255)
SET @table1_name = 'stackoverflow_329931_a'
SET @table1_prefix = 'a_'
SET @table2_name = 'stackoverflow_329931_b'
SET @table2_prefix = 'b_'
SET @join_condition = 'a.[id] = b.[id]'

DECLARE @CRLF AS varchar(2)
SET @CRLF = CHAR(13) + CHAR(10)

DECLARE @a_columnlist AS varchar(MAX)
DECLARE @b_columnlist AS varchar(MAX)
DECLARE @sql AS varchar(MAX)

SELECT @a_columnlist = COALESCE(@a_columnlist + @CRLF + ',', '') + 'a.[' + COLUMN_NAME + '] AS [' + @table1_prefix + COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table1_name
ORDER BY ORDINAL_POSITION

SELECT @b_columnlist = COALESCE(@b_columnlist + @CRLF + ',', '') + 'b.[' + COLUMN_NAME + '] AS [' + @table2_prefix + COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table2_name
ORDER BY ORDINAL_POSITION

SET @sql = 'SELECT ' + @a_columnlist + '
,' + @b_columnlist + '
FROM [' + @table1_name + '] AS a
INNER JOIN [' + @table2_name + '] AS b
ON (' + @join_condition + ')'

PRINT @sql
-- EXEC (@sql)

Convert String with Dot or Comma as decimal separator to number in JavaScript

Do a replace first:

parseFloat(str.replace(',','.').replace(' ',''))

Hide all warnings in ipython

I hide the warnings in the pink boxes by running the following code in a cell:

from IPython.display import HTML
HTML('''<script>
code_show_err=false; 
function code_toggle_err() {
 if (code_show_err){
 $('div.output_stderr').hide();
 } else {
 $('div.output_stderr').show();
 }
 code_show_err = !code_show_err
} 
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')

multiple packages in context:component-scan, spring config

Another general Annotation approach:

@ComponentScan(basePackages = {"x.y.z"})

Can I configure a subdomain to point to a specific port on my server

I... don't think so. You can redirect the subdomain (such as blah.something.com) to point to something.com:25566, but I don't think you can actually set up the subdomain to be on a different port like that. I could be wrong, but it'd probably be easier to use a simple .htaccess or something to check %{HTTP_HOST} and redirect according to the subdomain.

How to Delete node_modules - Deep Nested Folder in Windows

Its too easy.

Just delete all folders inside node_modules and then delete actual node_module folder.

This Works for me. Best luck....

jQuery loop over JSON result from AJAX Success?

you can remove the outer loop and replace this with data.data:

$.each(data.data, function(k, v) {
    /// do stuff
});

You were close:

$.each(data, function() {
  $.each(this, function(k, v) {
    /// do stuff
  });
});

You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.

How to change the background color on a Java panel?

setBackground() is the right method to use. Did you repaint after you changed it? If you change it before you make the panel (or its containing frame) visible it should work

Statistics: combinations in Python

Here's another alternative. This one was originally written in C++, so it can be backported to C++ for a finite-precision integer (e.g. __int64). The advantage is (1) it involves only integer operations, and (2) it avoids bloating the integer value by doing successive pairs of multiplication and division. I've tested the result with Nas Banov's Pascal triangle, it gets the correct answer:

def choose(n,r):
  """Computes n! / (r! (n-r)!) exactly. Returns a python long int."""
  assert n >= 0
  assert 0 <= r <= n

  c = 1L
  denom = 1
  for (num,denom) in zip(xrange(n,n-r,-1), xrange(1,r+1,1)):
    c = (c * num) // denom
  return c

Rationale: To minimize the # of multiplications and divisions, we rewrite the expression as

    n!      n(n-1)...(n-r+1)
--------- = ----------------
 r!(n-r)!          r!

To avoid multiplication overflow as much as possible, we will evaluate in the following STRICT order, from left to right:

n / 1 * (n-1) / 2 * (n-2) / 3 * ... * (n-r+1) / r

We can show that integer arithmatic operated in this order is exact (i.e. no roundoff error).

read complete file without using loop in java

Since Java 11 you can do it even simpler:

import java.nio.file.Files;

Files.readString(Path path);
Files.readString?(Path path, Charset cs)

Source: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)

Ajax LARAVEL 419 POST error

In laravel you can use view render. ex. $returnHTML = view('myview')->render(); myview.blade.php contains your blade code

Git - Undo pushed commits

What I do in these cases is:

  • In the server, move the cursor back to the last known good commit:

    git push -f origin <last_known_good_commit>:<branch_name>
    
  • Locally, do the same:

    git reset --hard <last_known_good_commit>
    #         ^^^^^^
    #         optional
    



See a full example on a branch my_new_branch that I created for this purpose:

$ git branch
my_new_branch

This is the recent history after adding some stuff to myfile.py:

$ git log
commit 80143bcaaca77963a47c211a9cbe664d5448d546
Author: me
Date:   Wed Mar 23 12:48:03 2016 +0100

    Adding new stuff in myfile.py

commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date:   Tue Mar 18 12:46:59 2016 +0100

    Initial commit

I want to get rid of the last commit, which was already pushed, so I run:

$ git push -f origin b4zad078237fa48746a4feb6517fa409f6bf238e:my_new_branch
Total 0 (delta 0), reused 0 (delta 0)
To [email protected]:me/myrepo.git
 + 80143bc...b4zad07 b4zad078237fa48746a4feb6517fa409f6bf238e -> my_new_branch (forced update)

Nice! Now I see the file that was changed on that commit (myfile.py) shows in "not staged for commit":

$ git status
On branch my_new_branch
Your branch is up-to-date with 'origin/my_new_branch'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   myfile.py

no changes added to commit (use "git add" and/or "git commit -a")

Since I don't want these changes, I just move the cursor back locally as well:

$ git reset --hard b4zad078237fa48746a4feb6517fa409f6bf238e
HEAD is now at b4zad07 Initial commit

So now HEAD is in the previous commit, both in local and remote:

$ git log
commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date:   Tue Mar 18 12:46:59 2016 +0100

    Initial commit

Binding value to input in Angular JS

{{widget.title}} Try this it will work

Upload files from Java client to a HTTP server

public static String simSearchByImgURL(int  catid ,String imgurl) throws IOException{
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String result =null;
    try {
        HttpPost httppost = new HttpPost("http://api0.visualsearchapi.com:8084/vsearchtech/api/v1.0/apisim_search");
        StringBody catidBody = new StringBody(catid+"" , ContentType.TEXT_PLAIN);
        StringBody keyBody = new StringBody(APPKEY , ContentType.TEXT_PLAIN);
        StringBody langBody = new StringBody(LANG , ContentType.TEXT_PLAIN);
        StringBody fmtBody = new StringBody(FMT , ContentType.TEXT_PLAIN);
        StringBody imgurlBody = new StringBody(imgurl , ContentType.TEXT_PLAIN);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart("apikey", keyBody).addPart("catid", catidBody)
        .addPart("lang", langBody)
        .addPart("fmt", fmtBody)
        .addPart("imgurl", imgurlBody);
        HttpEntity reqEntity =  builder.build();
        httppost.setEntity(reqEntity);
        response = httpClient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
           // result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
            String charset = "UTF-8";   
          String content=EntityUtils.toString(response.getEntity(), charset);   
            System.out.println(content);
        }
        EntityUtils.consume(resEntity);
    }catch(Exception e){
        e.printStackTrace();
    }finally {
        response.close();
        httpClient.close();
    }
    return result;
}

What is the best place for storing uploaded images, SQL database or disk file system?

If they are small files that will not need to be edited then option B is not a bad option. I prefer this to writing logic to store files and deal with crazy directory structure issues. Having a lot of files in one directory is bad. emkay?

If the files are large or require constant editing, especially from programs like office, then option A is your best bet.

For most cases, it's a matter of preference, but if you go option A, just make re the directories don't have too many files in them. If you choose option B, then make the table with the BLOBed data be in it's own database and/or file group. This will help with maintenance, especially backups/restores. Your regular data is probably fairly small, while your image data will be huge over time.

Alter column in SQL Server

Try this one.

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

How to get number of entries in a Lua table?

local function CountedTable(x)
    assert(type(x) == 'table', 'bad parameter #1: must be table')

    local new_t = {}
    local mt = {}

    -- `all` will represent the number of both
    local all = 0
    for k, v in pairs(x) do
        all = all + 1
    end

    mt.__newindex = function(t, k, v)
        if v == nil then
            if rawget(x, k) ~= nil then
                all = all - 1
            end
        else
            if rawget(x, k) == nil then
                all = all + 1
            end
        end

        rawset(x, k, v)
    end

    mt.__index = function(t, k)
        if k == 'totalCount' then return all
        else return rawget(x, k) end
    end

    return setmetatable(new_t, mt)
end

local bar = CountedTable { x = 23, y = 43, z = 334, [true] = true }

assert(bar.totalCount == 4)
assert(bar.x == 23)
bar.x = nil
assert(bar.totalCount == 3)
bar.x = nil
assert(bar.totalCount == 3)
bar.x = 24
bar.x = 25
assert(bar.x == 25)
assert(bar.totalCount == 4)

How do I iterate through the files in a directory in Java?

Check out the FileUtils class in Apache Commons - specifically iterateFiles:

Allows iteration over the files in given directory (and optionally its subdirectories).

What's the equivalent of Java's Thread.sleep() in JavaScript?

The simple answer is that there is no such function.

The closest thing you have is:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

Here are a couple of other SO questions that deal with threads in JavaScript:

And this question may also be helpful:

IOPub data rate exceeded in Jupyter notebook (when viewing image)

I ran into this using networkx and bokeh

This works for me in Windows 7 (taken from here):

  1. To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:

    $ jupyter notebook --generate-config

  2. Open the file and search for c.NotebookApp.iopub_data_rate_limit

  3. Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000 and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000

This unforgiving default config is popping up in a lot of places. See git issues:

It looks like it might get resolved with the 5.1 release

Update:

Jupyter notebook is now on release 5.2.2. This problem should have been resolved. Upgrade using conda or pip.

The import javax.servlet can't be resolved

If not done yet, you need to integrate Tomcat in your Servers view. Rightclick there and choose New > Server. Select the appropriate Tomcat version from the list and complete the wizard.

When you create a new Dynamic Web Project, you should select the integrated server from the list as Targeted Runtime in the 1st wizard step.

Or when you have an existing Dynamic Web Project, you can set/change it in Targeted Runtimes entry in project's properties. Eclipse will then automagically add all its libraries to the build path (without having a copy of them in the project!).

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

How can I insert multiple rows into oracle with a sequence value?

It does not work because sequence does not work in following scenarios:

  • In a WHERE clause
  • In a GROUP BY or ORDER BY clause
  • In a DISTINCT clause
  • Along with a UNION or INTERSECT or MINUS
  • In a sub-query

Source: http://www.orafaq.com/wiki/ORA-02287

However this does work:

insert into table_name
            (col1, col2)
  select my_seq.nextval, inner_view.*
    from (select 'some value' someval
            from dual
          union all
          select 'another value' someval
            from dual) inner_view;

Try it out:

create table table_name(col1 varchar2(100), col2 varchar2(100));

create sequence vcert.my_seq
start with 1
increment by 1
minvalue 0;

select * from  table_name;

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Short answer:

There is no difference in semantic.

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Further reading:

RequestMapping can be used at class level:

This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.

while GetMapping only applies to method:

Annotation for mapping HTTP GET requests onto specific handler methods.


https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

Linear regression with matplotlib / numpy

Another quick and dirty answer is that you can just convert your list to an array using:

import numpy as np
arr = np.asarray(listname)

Grant Select on a view not base table when base table is in a different database

As you state in one of your comments that the table in question is in a different database, then ownership chaining applies. I suspect there is a break in the chain somewhere - check that link for full details.

how to set cursor style to pointer for links without hrefs

Give them all a common class (for instance link). Then add in css-file:

.link { cursor: pointer; }

Or as @mxmissile suggested, do it inline with style="cursor: pointer;"

Check if a given key already exists in a dictionary

You don't have to call keys:

if 'key1' in dict:
  print("blah")
else:
  print("boo")

That will be much faster as it uses the dictionary's hashing as opposed to doing a linear search, which calling keys would do.

Unable instantiate android.gms.maps.MapFragment

I think it is worth mentioning (after I spent over an hour pulling out my hair) that if you are using MapFragment you cannot use FragmentActivity (SupportMapFragment will function fine in this environment). I was just about ready to give up on it.

Set default option in mat-select

Working StackBlitz

No need to use ngModel or Forms

In your html:

 <mat-form-field>
  <mat-select [(value)]="selected" placeholder="Mode">
    <mat-option value="domain">Domain</mat-option>
    <mat-option value="exact">Exact</mat-option>
  </mat-select>
</mat-form-field>

and in your component just set your public property selected to the default:

selected = 'domain';

Password encryption/decryption code in .NET

First create a class like:

public class Encryption
    { 
        public static string Encrypt(string clearText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return clearText;
        }

        public static string Decrypt(string cipherText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }
    }

**In Controller **

add reference for this encryption class:

using testdemo.Models

public ActionResult Index() {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string text)
        {
            if (Request["txtEncrypt"] != null)
            {
                string getEncryptionCode = Request["txtEncrypt"];
                string DecryptCode = Encryption.Decrypt(HttpUtility.UrlDecode(getEncryptionCode));
                ViewBag.GetDecryptCode = DecryptCode;
                return View();
            }
            else {
                string getDecryptCode = Request["txtDecrypt"];
                string EncryptionCode = HttpUtility.UrlEncode(Encryption.Encrypt(getDecryptCode));
                ViewBag.GetEncryptionCode = EncryptionCode;
                return View();
            }

        }

In View

<h2>Decryption Code</h2>
@using (Html.BeginForm())
{
    <table class="table-bordered table">
        <tr>
            <th>Encryption Code</th>
            <td><input type="text" id="txtEncrypt" name="txtEncrypt" placeholder="Enter Encryption Code" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <span style="color:red">@ViewBag.GetDecryptCode</span>
            </td>
        </tr>
        <tr>
                <td colspan="2">
                    <input type="submit" id="btnEncrypt" name="btnEncrypt"value="Decrypt to Encrypt code" />
                </td>
            </tr>
    </table>
}
    <br />
    <br />
    <br />
    <h2>Encryption Code</h2>
@using (Html.BeginForm())
{
    <table class="table-bordered table">
        <tr>
            <th>Decryption Code</th>
            <td><input type="text" id="txtDecrypt" name="txtDecrypt" placeholder="Enter Decryption Code" /></td>
        </tr>

        <tr>
            <td colspan="2">
                <span style="color:red">@ViewBag.GetEncryptionCode</span>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" id="btnDecryt" name="btnDecryt" value="Encrypt to Decrypt code" />
            </td>
        </tr>
    </table>
}

Read entire file in Scala?

For faster overall reading / uploading a (large) file, consider increasing the size of bufferSize (Source.DefaultBufSize set to 2048), for instance as follows,

val file = new java.io.File("myFilename")
io.Source.fromFile(file, bufferSize = Source.DefaultBufSize * 2)

Note Source.scala. For further discussion see Scala fast text file read and upload to memory.

Exception in thread "main" java.util.NoSuchElementException

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results.

The solution: For console apps, use a single Scanner to read from System.in.

Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine().

See: Do not create multiple buffered wrappers on a single InputStream

Getting value from table cell in JavaScript...not jQuery

the above guy was close but here is what you want:

       var table = document.getElementById(tableID);
       var rowCount = table.rows.length;        
         for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            alert(table.rows[r].cells[c].firstChild.value);
        }
    }
        }catch(e) {
            alert(e);
        }

JSON Invalid UTF-8 middle byte

I got this exception when in the Java Client Application I was serializing a JSON like this

String json = mapper.writeValueAsString(contentBean);

and on the Server Side I was using Spring Boot as REST Endpoint. Exception was:

nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0xaa

My problem was, that I was not setting the correct encoding on the HTTP Client. This solved my problem:

updateRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity entity= new StringEntity(json, "UTF-8");
updateRequest.setEntity(entity);

Android set content type HttpPost

Shell script "for" loop syntax

If the seq command available on your system:

for i in `seq 2 $max`
do
  echo "output: $i"
done

If not, then use poor man's seq with perl:

seq=`perl -e "\$,=' ';print 2..$max"`
for i in $seq
do
  echo "output: $i"
done

Watch those quote marks.

The transaction manager has disabled its support for remote/network transactions

I was having this issue with a linked server in SSMS while trying to create a stored procedure.

On the linked server, I changed the server option "Enable Promotion on Distributed Transaction" to False.

Screenshot of Server Options

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

dmidecode -t 17 | grep  Size:

Adding all above values displayed after "Size: " will give exact total physical size of all RAM sticks in server.

Python: For each list element apply a function across the list

Doing it the mathy way...

nums = [1, 2, 3, 4, 5]
min_combo = (min(nums), max(nums))

Unless, of course, you have negatives in there. In that case, this won't work because you actually want the min and max absolute values - the numerator should be close to zero, and the denominator far from it, in either direction. And double negatives would break it.

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

In my case, I have macport installed already. I simply updated my macport:

sudo port selfupdate

sudo port upgrade outdated

Then install apache-ant:

sudo port install apache-ant

Finally, I add ant to my alias list in my .bash_profile:

alias ant='/opt/local/bin/ant'

Then you are all set.

How to add app icon within phonegap projects?

FAQ: ICON / SPLASH SCREEN (Cordova 5.x / 2015)

I present my answer as a general FAQ that may help you to solve many problems I've encountered while dealing with icons/splash screens. You may find out like me that the documentation is not always very clear nor up to date. This will probably go to StackOverflow documentation when available.

First: answering the question

How can I add custom app icons for iOS and Android with phonegap?

In your version of Cordova the icon tag is useless. It is not even documented in Cordova 3.0.0. You should use the documentation version that fits the cli you are using and not the latest one!

The icon tag does not work for Android at all before the version 3.5.0 according to what I can see in the different versions of the documentation. In 3.4.0 they still advice to manually copy the files

In newer versions: your config.xml looks better for newer Cordova versions. However there are still many things you may want to know. If you decide to upgrade here are some useful things to modify:

  • You don't need the gap: namespace
  • You need <preference name="SplashScreen" value="screen" /> for Android

Here are more details of the questions you might ask yourself when trying to deal with icons and splash screen:

Can I use an old version of Cordova / Phonegap

No, the icon/splashscreen feature was not in former versions of Cordova so you must use a recent version. In former versions, only Phonegap Build did handle the icons/splash screen so building locally and handling icons was only possible with a hook. I don't know the minimum version to use this feature but with 5.1.1 it works fine in both Cordova/Phonegap cli. With Cordova 3.5 it didn't work for me.

Edit: for Android you must use at least 3.5.0

How can I debug the build process about icons?

The cli use a CP command. If you provide an invalid icon path, it will show a cp error:

sebastien@sebastien-xps:cordova (dev *+$%)$ cordova run android --device
cp: no such file or directory: /home/sebastien/Desktop/Stample-react/cordova/res/www/stample_splash.png

Edit: you have use cordova build <platform> --verbose to get logs of cp command usage to see where your icons gets copied

The icons should go in a folder according to the config. For me it goes in many subfolders in : platforms/android/build/intermediates/res/armv7/debug/drawable-hdpi-v4/icon.png

Then you can find the APK, and open it as a zip archive to check the icons are present. They must be in a res/drawable* folder because it's a special folder for Android.

Where should I put the icons/splash screens in my project?

In many examples you will find the icons/splash screens are declared inside a res folder. This res is a special Android folder in the output APK, but it does not mean you have to use a res folder in your project.

You can put your icon anywhere, but the path you use must be relative to the root of the project, and not www so take care! This is documented, but not clearly because all the examples are using res and you don't know where this folder is :(

I mean if you put the icon in www/icon.png you absolutly must include www in your path.

Edit Mars 2016: after upgrading my versions, now it seems that icons are relative to www folder but documentation has not been changed (issue)

Does <icon src="icon.png"/> work?

No it does not!.

On Android, it seems it used to work before (when the density attribute was not supported yet?) but not anymore. See this Cordova issue

On iOS, it seems using this global declaration may override more specific declarations so take care and build with --verbose to ensure everything works as expected.

Can I use the same icon/splash screen file for all the densities.

Yes you can. You can even use the same file for both the icon, and splash screen (just to test!). I have used a "big" icon file of 65kb without any problem.

What's the difference when using the platform tag vs the platform attribute

<icon src="icon.png" platform="android" density="ldpi" />

is the same as

<platform name="android">
    <icon src="www/stample_icon.png" density="ldpi" />
</platform>

Should I use the gap: namespace if using Phonegap?

In my experience new versions of Phonegap or Cordova are both able to understand icon declarations without using any gap: xml namespace.

However I'm still waiting for a valid answer here: cordova/phonegap plugin add VS config.xml

As far as I understand, some features with the gap: namespace may be available earlier in PhonegapBuild, then in Phonegap and then being ported to Cordova (?)

Is <preference name="SplashScreen" value="screen" /> required?

At least for Android yes it is. I opened an issue with additional explainations.

Does icon declaration order matters?

Yes it does! It may not have any impact on Android but it has on iOS according to my tests. This is unexpected and undocumented behavior so I opened another issue.

Do I need cordova-plugin-splashscreen?

Yes this is absolutly required if you want the splash screen to work. The documentation is not clear (issue) and let us think that the plugin is required only to offer a splash screen javascript API.

How can I resize the images for all width/height/densities fastly

There are tools to help you do that. The best one for me is http://makeappicon.com/ but it requires to provide an email address.

Other possible solutions are:

Can you give me an example config?

Yes. Here's my real config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="co.x" version="0.2.6" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>x</name>
    <description>
        x
    </description>
    <author email="[email protected]" href="https://x.co">
        x
    </author>
    <content src="index.html" />
    <preference name="permissions"                  value="none" />
    <preference name="webviewbounce"                value="false" />
    <preference name="StatusBarOverlaysWebView"     value="false" />
    <preference name="StatusBarBackgroundColor"     value="#0177C6" />
    <preference name="detect-data-types"            value="true" />
    <preference name="stay-in-webview"              value="false" />
    <preference name="android-minSdkVersion"        value="14" />
    <preference name="android-targetSdkVersion"     value="22" />
    <preference name="phonegap-version"             value="cli-5.1.1" />

    <preference name="SplashScreenDelay"            value="10000" />
    <preference name="SplashScreen"                 value="screen" />


    <plugin name="cordova-plugin-device"                spec="1.0.1" />
    <plugin name="cordova-plugin-console"               spec="1.0.1" />
    <plugin name="cordova-plugin-whitelist"             spec="1.1.0" />
    <plugin name="cordova-plugin-crosswalk-webview"     spec="1.2.0" />
    <plugin name="cordova-plugin-statusbar"             spec="1.0.1" />
    <plugin name="cordova-plugin-screen-orientation"    spec="1.3.6" />
    <plugin name="cordova-plugin-splashscreen"          spec="2.1.0" />

    <access origin="http://*" />
    <access origin="https://*" />

    <access launch-external="yes" origin="tel:*" />
    <access launch-external="yes" origin="geo:*" />
    <access launch-external="yes" origin="mailto:*" />
    <access launch-external="yes" origin="sms:*" />
    <access launch-external="yes" origin="market:*" />

    <platform name="android">
        <icon src="www/stample_icon.png" density="ldpi" />
        <icon src="www/stample_icon.png" density="mdpi" />
        <icon src="www/stample_icon.png" density="hdpi" />
        <icon src="www/stample_icon.png" density="xhdpi" />
        <icon src="www/stample_icon.png" density="xxhdpi" />
        <icon src="www/stample_icon.png" density="xxxhdpi" />
        <splash src="www/stample_splash.png" density="land-hdpi"/>
        <splash src="www/stample_splash.png" density="land-ldpi"/>
        <splash src="www/stample_splash.png" density="land-mdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="port-hdpi"/>
        <splash src="www/stample_splash.png" density="port-ldpi"/>
        <splash src="www/stample_splash.png" density="port-mdpi"/>
        <splash src="www/stample_splash.png" density="port-xhdpi"/>
        <splash src="www/stample_splash.png" density="port-xxhdpi"/>
        <splash src="www/stample_splash.png" density="port-xxxhdpi"/>
    </platform>

    <platform name="ios">
        <icon src="www/stample_icon.png" width="180" height="180" />
        <icon src="www/stample_icon.png" width="60" height="60" />
        <icon src="www/stample_icon.png" width="120" height="120" />
        <icon src="www/stample_icon.png" width="76" height="76" />
        <icon src="www/stample_icon.png" width="152" height="152" />
        <icon src="www/stample_icon.png" width="40" height="40" />
        <icon src="www/stample_icon.png" width="80" height="80" />
        <icon src="www/stample_icon.png" width="57" height="57" />
        <icon src="www/stample_icon.png" width="114" height="114" />
        <icon src="www/stample_icon.png" width="72" height="72" />
        <icon src="www/stample_icon.png" width="144" height="144" />
        <icon src="www/stample_icon.png" width="29" height="29" />
        <icon src="www/stample_icon.png" width="58" height="58" />
        <icon src="www/stample_icon.png" width="50" height="50" />
        <icon src="www/stample_icon.png" width="100" height="100" />
        <splash src="www/stample_splash.png" width="320" height="480"/>
        <splash src="www/stample_splash.png" width="640" height="960"/>
        <splash src="www/stample_splash.png" width="768" height="1024"/>
        <splash src="www/stample_splash.png" width="1536" height="2048"/>
        <splash src="www/stample_splash.png" width="1024" height="768"/>
        <splash src="www/stample_splash.png" width="2048" height="1536"/>
        <splash src="www/stample_splash.png" width="640" height="1136"/>
        <splash src="www/stample_splash.png" width="750" height="1334"/>
        <splash src="www/stample_splash.png" width="1242" height="2208"/>
        <splash src="www/stample_splash.png" width="2208" height="1242"/>
    </platform>

    <allow-intent href="*" />
    <engine name="browser" spec="^3.6.0" />
    <engine name="android" spec="^4.0.2" />
</widget>

A good source of examples are starter kits. Like phonegap-start or Ionic starter

Use tab to indent in textarea

Multiple-line indetation script based on @kasdega solution.

$('textarea').on('keydown', function (e) {
    var keyCode = e.keyCode || e.which;

    if (keyCode === 9) {
        e.preventDefault();
        var start = this.selectionStart;
        var end = this.selectionEnd;
        var val = this.value;
        var selected = val.substring(start, end);
        var re = /^/gm;
        var count = selected.match(re).length;


        this.value = val.substring(0, start) + selected.replace(re, '\t') + val.substring(end);
        this.selectionStart = start;
        this.selectionEnd = end + count;
    }
});

Scheduling recurring task in Android

I am not sure but as per my knowledge I share my views. I always accept best answer if I am wrong .

Alarm Manager

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.

Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

Timer

timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        synchronized public void run() {

            \\ here your todo;
            }

        }, TimeUnit.MINUTES.toMillis(1), TimeUnit.MINUTES.toMillis(1));

Timer has some drawbacks that are solved by ScheduledThreadPoolExecutor. So it's not the best choice

ScheduledThreadPoolExecutor.

You can use java.util.Timer or ScheduledThreadPoolExecutor (preferred) to schedule an action to occur at regular intervals on a background thread.

Here is a sample using the latter:

ScheduledExecutorService scheduler =
    Executors.newSingleThreadScheduledExecutor();

scheduler.scheduleAtFixedRate
      (new Runnable() {
         public void run() {
            // call service
         }
      }, 0, 10, TimeUnit.MINUTES);

So I preferred ScheduledExecutorService

But Also think about that if the updates will occur while your application is running, you can use a Timer, as suggested in other answers, or the newer ScheduledThreadPoolExecutor. If your application will update even when it is not running, you should go with the AlarmManager.

The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.

Take note that if you plan on updating when your application is turned off, once every ten minutes is quite frequent, and thus possibly a bit too power consuming.

How to detect a docker daemon port

Try add -H tcp://0.0.0.0:2375(at end of Execstart line) instead of -H 0.0.0.0:2375.

Securing a password in a properties file

The poor mans compromise solution is to use a simplistic multi signature approach.

For Example the DBA sets the applications database password to a 50 character random string. TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU

He or she give half the password to the application developer who then hard codes it into the java binary.

private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"

The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.

java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU

When the application starts it uses pass1 + pass2 and connects to the database.

This solution has many advantages with out the downfalls mentioned.

You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.

The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.

The source code can also be semi public as reading it and the password will not give you application access.

You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.

Executing JavaScript without a browser?

Well there is JavaScript as OSA, an extension that provides JavaScript as an alternative to appleScript. I've been using that about 10 years ago, don't know if it's still working with current OS versions

Using Composer's Autoload

There also other ways to use the composer autoload features. Ways that can be useful to load packages without namespaces or packages that come with a custom autoload function.

For example if you want to include a single file that contains an autoload function as well you can use the "files" directive as follows:

"autoload": {
    "psr-0": {
        "": "src/",
        "SymfonyStandard": "app/"
    },
    "files": ["vendor/wordnik/wordnik-php/wordnik/Swagger.php"]
},

And inside the Swagger.php file we got:

function swagger_autoloader($className) {
    $currentDir = dirname(__FILE__);
    if (file_exists($currentDir . '/' . $className . '.php')) {
        include $currentDir . '/' . $className . '.php';
    } elseif (file_exists($currentDir . '/models/' . $className . '.php')) {
        include $currentDir . '/models/' . $className . '.php';
    }
}
spl_autoload_register('swagger_autoloader');

https://getcomposer.org/doc/04-schema.md#files

Otherwise you may want to use a classmap reference:

{
    "autoload": {
        "classmap": ["src/", "lib/", "Something.php"]
    }
}

https://getcomposer.org/doc/04-schema.md#classmap

Note: during your tests remember to launch the composer dump-autoload command or you won't see any change!

./composer.phar dump-autoload

Happy autoloading =)

How do you use script variables in psql?

I solved it with a temp table.

CREATE TEMP TABLE temp_session_variables (
    "sessionSalt" TEXT
);
INSERT INTO temp_session_variables ("sessionSalt") VALUES (current_timestamp || RANDOM()::TEXT);

This way, I had a "variable" I could use over multiple queries, that is unique for the session. I needed it to generate unique "usernames" while still not having collisions if importing users with the same user name.

.substring error: "is not a function"

You can use substr

for example:

new Date().getFullYear().toString().substr(-2)

Cast object to T

You could require the type to be a reference type :

 private static T ReadData<T>(XmlReader reader, string value) where T : class
 {
     reader.MoveToAttribute(value);
     object readData = reader.ReadContentAsObject();
     return (T)readData;
 }

And then do another that uses value types and TryParse...

 private static T ReadDataV<T>(XmlReader reader, string value) where T : struct
 {
     reader.MoveToAttribute(value);
     object readData = reader.ReadContentAsObject();
     int outInt;
     if(int.TryParse(readData, out outInt))
        return outInt
     //...
 }

Android Horizontal RecyclerView scroll Direction

Try this in fragment :

layoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);

mRecyclerView.setLayoutManager(layoutManager);

How to properly make a http web GET request

Servers sometimes compress their responses to save on bandwidth, when this happens, you need to decompress the response before attempting to read it. Fortunately, the .NET framework can do this automatically, however, we have to turn the setting on.

Here's an example of how you could achieve that.

string html = string.Empty;
string url = @"https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    html = reader.ReadToEnd();
}

Console.WriteLine(html);

GET

public string Get(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

GET async

public async Task<string> GetAsync(string uri)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

POST
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public string Post(string uri, string data, string contentType, string method = "POST")
{
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
    {
        requestBody.Write(dataBytes, 0, dataBytes.Length);
    }

    using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

    

POST async
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC

public async Task<string> PostAsync(string uri, string data, string contentType, string method = "POST")
{
    byte[] dataBytes = Encoding.UTF8.GetBytes(data);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    request.ContentLength = dataBytes.Length;
    request.ContentType = contentType;
    request.Method = method;

    using(Stream requestBody = request.GetRequestStream())
    {
        await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);
    }

    using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    using(Stream stream = response.GetResponseStream())
    using(StreamReader reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

Determine whether a key is present in a dictionary

My answer is "neither one".

I believe the most "Pythonic" way to do things is to NOT check beforehand if the key is in a dictionary and instead just write code that assumes it's there and catch any KeyErrors that get raised because it wasn't.

This is usually done with enclosing the code in a try...except clause and is a well-known idiom usually expressed as "It's easier to ask forgiveness than permission" or with the acronym EAFP, which basically means it is better to try something and catch the errors instead for making sure everything's OK before doing anything. Why validate what doesn't need to be validated when you can handle exceptions gracefully instead of trying to avoid them? Because it's often more readable and the code tends to be faster if the probability is low that the key won't be there (or whatever preconditions there may be).

Of course, this isn't appropriate in all situations and not everyone agrees with the philosophy, so you'll need to decide for yourself on a case-by-case basis. Not surprisingly the opposite of this is called LBYL for "Look Before You Leap".

As a trivial example consider:

if 'name' in dct:
    value = dct['name'] * 3
else:
    logerror('"%s" not found in dictionary, using default' % name)
    value = 42

vs

try:
    value = dct['name'] * 3
except KeyError:
    logerror('"%s" not found in dictionary, using default' % name)
    value = 42

Although in the case it's almost exactly the same amount of code, the second doesn't spend time checking first and is probably slightly faster because of it (try...except block isn't totally free though, so it probably doesn't make that much difference here).

Generally speaking, testing in advance can often be much more involved and the savings gain from not doing it can be significant. That said, if 'name' in dict: is better for the reasons stated in the other answers.

If you're interested in the topic, this message titled "EAFP vs LBYL (was Re: A little disappointed so far)" from the Python mailing list archive probably explains the difference between the two approached better than I have here. There's also a good discussion about the two approaches in the book Python in a Nutshell, 2nd Ed by Alex Martelli in chapter 6 on Exceptions titled Error-Checking Strategies. (I see there's now a newer 3rd edition, publish in 2017, which covers both Python 2.7 and 3.x).

Convert date yyyyMMdd to system.datetime format

string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
                                        "yyyyMMdd",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.None);

How to redirect a page using onclick event in php?

you are using onclick which is javascript event. there is two ways

Javascript

<input type="button" value="Home" class="homebutton" id="btnHome" 
onClick="window.location = 'http://google.com'" />

Or PHP

create another page as redirect.php and put

<?php header('location : google.com') ?>

and insert this link on any page within the same directory

<a href="redirect.php">google<a/>

hope this helps its simplest!!

How to fix "Incorrect string value" errors?

"\xE4\xC5\xCC\xC9\xD3\xD8" isn't valid UTF-8. Tested using Python:

>>> "\xE4\xC5\xCC\xC9\xD3\xD8".decode("utf-8")
...
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-2: invalid data

If you're looking for a way to avoid decoding errors within the database, the cp1252 encoding (aka "Windows-1252" aka "Windows Western European") is the most permissive encoding there is - every byte value is a valid code point.

Of course it's not going to understand genuine UTF-8 any more, nor any other non-cp1252 encoding, but it sounds like you're not too concerned about that?

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

I faced the same issue in my scenario as follow:

I created textbook table first with

create table textbook(txtbk_isbn varchar2(13)
primary key,txtbk_title varchar2(40),
txtbk_author varchar2(40) );

Then chapter table:

create table chapter(txtbk_isbn varchar2(13),chapter_title varchar2(40), constraint pk_chapter primary key(txtbk_isbn,chapter_title), constraint chapter_txtbook foreign key (txtbk_isbn) references textbook (txtbk_isbn));

Then topic table:

create table topic(topic_id varchar2(20) primary key,topic_name varchar2(40));

Now when I wanted to create a relationship called chapter_topic between chapter (having composite primary key) and topic (having single column primary key), I faced issue with following query:

create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20), primary key (txtbk_isbn, chapter_title, topic_id), foreign key (txtbk_isbn) references textbook(txtbk_isbn), foreign key (chapter_title) references chapter(chapter_title), foreign key (topic_id) references topic (topic_id));

The solution was to refer to composite foreign key as below:

create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20), primary key (txtbk_isbn, chapter_title, topic_id), foreign key (txtbk_isbn, chapter_title) references chapter(txtbk_isbn, chapter_title), foreign key (topic_id) references topic (topic_id));

Thanks to APC post in which he mentioned in his post a statement that:

Common reasons for this are
- the parent lacks a constraint altogether
- the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.
- the referenced PK constraint exists but is DISABLED

Stopword removal with NLTK

There is an in-built stopword list in NLTK made up of 2,400 stopwords for 11 languages (Porter et al), see http://nltk.org/book/ch02.html

>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> stop = set(stopwords.words('english'))
>>> sentence = "this is a foo bar sentence"
>>> print([i for i in sentence.lower().split() if i not in stop])
['foo', 'bar', 'sentence']
>>> [i for i in word_tokenize(sentence.lower()) if i not in stop] 
['foo', 'bar', 'sentence']

I recommend looking at using tf-idf to remove stopwords, see Effects of Stemming on the term frequency?

How to retrieve available RAM from Windows command line?

Just in case you need this functionality in a Java program, you might want to look at the sigar API: http://www.hyperic.com/products/sigar

Actually, this is no answer to the question, I know, but a hint so you don't have to reinvent the wheel.

How to start automatic download of a file in Internet Explorer?

Back to the roots, i use this:

<meta http-equiv="refresh" content="0; url=YOURFILEURL"/>

Maybe not WC3 conform but works perfect on all browsers, no HTML5/JQUERY/Javascript.

Greetings Tom :)

How to pass object from one component to another in Angular 2?

Component 2, the directive component can define a input property (@input annotation in Typescript). And Component 1 can pass that property to the directive component from template.

See this SO answer How to do inter communication between a master and detail component in Angular2?

and how input is being passed to child components. In your case it is directive.

java: How can I do dynamic casting of a variable from one type to another?

You'll need to write sort of ObjectConverter for this. This is doable if you have both the object which you want to convert and you know the target class to which you'd like to convert to. In this particular case you can get the target class by Field#getDeclaringClass().

You can find here an example of such an ObjectConverter. It should give you the base idea. If you want more conversion possibilities, just add more methods to it with the desired argument and return type.

How to measure time taken by a function to execute

In my case, I perfer to use @ grammar suger and compile it with babel.
The problem of this method is that function has to be inside object.

Sample JS Code

function timer() {
    return (target, propertyKey, descriptor) => {
        const start = Date.now();
        let oldFunc = descriptor.value;

        descriptor.value = async function (){
            var result = await oldFunc.apply(this, arguments);
            console.log(Date.now() - start);
            return result;
        }
    }
}

// Util function 
function delay(timeout) {
    return new Promise((resolve) => setTimeout(() => {
        resolve();
    }, timeout));
}

class Test {
    @timer()
    async test(timout) {
        await delay(timout)
        console.log("delay 1");
        await delay(timout)
        console.log("delay 2");
    }
}

const t = new Test();
t.test(1000)
t.test(100)

.babelrc (for babel 6)

 {
    "plugins": [
        "transform-decorators-legacy"
    ]
 }

Difference between File.separator and slash in paths

As the gentlemen described the difference with variant details.

I would like to recommend the use of the Apache Commons io api, class FilenameUtils when dealing with files in a program with the possibility of deploying on multiple OSs.

Remove IE10's "clear field" X button on certain inputs?

I think it's worth noting that all the style and CSS based solutions don't work when a page is running in compatibility mode. The compatibility mode renderer ignores the ::-ms-clear element, even though the browser shows the x.

If your page needs to run in compatibility mode, you may be stuck with the X showing.

In my case, I am working with some third party data bound controls, and our solution was to handle the "onchange" event and clear the backing store if the field is cleared with the x button.

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

Enums in Javascript with ES6

As mentioned above, you could also write a makeEnum() helper function:

function makeEnum(arr){
    let obj = {};
    for (let val of arr){
        obj[val] = Symbol(val);
    }
    return Object.freeze(obj);
}

Use it like this:

const Colors = makeEnum(["red","green","blue"]);
let startColor = Colors.red; 
console.log(startColor); // Symbol(red)

if(startColor == Colors.red){
    console.log("Do red things");
}else{
    console.log("Do non-red things");
}

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

Is it possible to ping a server from Javascript?

I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/

How do you clone a Git repository into a specific folder?

If you want to clone into the current folder, you should try this:

git clone https://github.com/example/example.git ./

Why doesn't java.util.Set have get(int index)?

That is because Set only guarantees uniqueness, but says nothing about the optimal access or usage patterns. Ie, a Set can be a List or a Map, each of which have very different retrieval characteristics.

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

It's a table-valued function, but you're using it as a scalar function.

Try:

where Emp_Id IN (SELECT i.items FROM dbo.Splitfn(@Id,',') AS i)

But... also consider changing your function into an inline TVF, as it'll perform better.

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

I have the same problem and having position: absolute in your .ui-dialog{} css was not enough. I noticed that position: relative was being set on the actual element's direct style, so the .ui-dialog css definition was getting overwritten. Setting position: absolute on the div I was going to make a dialog statically also did not work.

In the end I changed two placed in my local jQuery to make this work.

I changed the following line in jQuery to be:

elem.style.position = "absolute";

at https://github.com/jquery/jquery/blob/1.8.0/src/offset.js#L62

Also, since my dialog was set to draggable, I had to change this line as well in jQuery-ui to be:

this.element[0].style.position = 'absolute';

at https://github.com/jquery/jquery-ui/blob/1-8-stable/ui/jquery.ui.draggable.js#L48

Perhaps going through the style I have more thoroughly would fix things, but thought I'd share how I got this working.

How to add "active" class to Html.ActionLink in ASP.NET MVC

Add '.ToString' to improve comparing on ASP.NET MVC

<ul class="nav navbar-nav">
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>

--

number_format() with MySQL

You need this:

CONCAT(REPLACE(FORMAT(number,0),',','.'),',',SUBSTRING_INDEX(FORMAT(number,2),'.',-1))

Is there a way to detect if a browser window is not currently active?

This is an adaptation of the answer from Andy E.

This will do a task e.g. refresh the page every 30 seconds, but only if the page is visible and focused.

If visibility can't be detected, then only focus will be used.

If the user focuses the page, then it will update immediately

The page won't update again until 30 seconds after any ajax call

var windowFocused = true;
var timeOut2 = null;

$(function(){
  $.ajaxSetup ({
    cache: false
  });
  $("#content").ajaxComplete(function(event,request, settings){
       set_refresh_page(); // ajax call has just been made, so page doesn't need updating again for 30 seconds
   });
  // check visibility and focus of window, so as not to keep updating unnecessarily
  (function() {
      var hidden, change, vis = {
              hidden: "visibilitychange",
              mozHidden: "mozvisibilitychange",
              webkitHidden: "webkitvisibilitychange",
              msHidden: "msvisibilitychange",
              oHidden: "ovisibilitychange" /* not currently supported */
          };
      for (hidden in vis) {
          if (vis.hasOwnProperty(hidden) && hidden in document) {
              change = vis[hidden];
              break;
          }
      }
      document.body.className="visible";
      if (change){     // this will check the tab visibility instead of window focus
          document.addEventListener(change, onchange,false);
      }

      if(navigator.appName == "Microsoft Internet Explorer")
         window.onfocus = document.onfocusin = document.onfocusout = onchangeFocus
      else
         window.onfocus = window.onblur = onchangeFocus;

      function onchangeFocus(evt){
        evt = evt || window.event;
        if (evt.type == "focus" || evt.type == "focusin"){
          windowFocused=true; 
        }
        else if (evt.type == "blur" || evt.type == "focusout"){
          windowFocused=false;
        }
        if (evt.type == "focus"){
          update_page();  // only update using window.onfocus, because document.onfocusin can trigger on every click
        }

      }

      function onchange () {
        document.body.className = this[hidden] ? "hidden" : "visible";
        update_page();
      }

      function update_page(){
        if(windowFocused&&(document.body.className=="visible")){
          set_refresh_page(1000);
        }
      }


  })();
  set_refresh_page();
})

function get_date_time_string(){
  var d = new Date();
  var dT = [];
  dT.push(d.getDate());
  dT.push(d.getMonth())
  dT.push(d.getFullYear());
  dT.push(d.getHours());
  dT.push(d.getMinutes());
  dT.push(d.getSeconds());
  dT.push(d.getMilliseconds());
  return dT.join('_');
}

function do_refresh_page(){

// do tasks here

// e.g. some ajax call to update part of the page.

// (date time parameter will probably force the server not to cache)

//      $.ajax({
//        type: "POST",
//        url: "someUrl.php",
//        data: "t=" + get_date_time_string()+"&task=update",
//        success: function(html){
//          $('#content').html(html);
//        }
//      });

}

function set_refresh_page(interval){
  interval = typeof interval !== 'undefined' ? interval : 30000; // default time = 30 seconds
  if(timeOut2 != null) clearTimeout(timeOut2);
  timeOut2 = setTimeout(function(){
    if((document.body.className=="visible")&&windowFocused){
      do_refresh_page();
    }
    set_refresh_page();
  }, interval);
}

Could not install packages due to an EnvironmentError: [Errno 13]

try this command line below for MacOS to check user's permission.

$ sudo python -m pip install --user --upgrade pip

Is there a way to detach matplotlib plots so that the computation can continue?

My answer is a little off topic, but I just decided to get away from matplotlib in my application because of the problem that is stated in this question.

Alternatively, you can use plotly. It does not block the process.

null terminating a string

Be very careful: NULL is a macro used mainly for pointers. The standard way of terminating a string is:

char *buffer;
...
buffer[end_position] = '\0';

This (below) works also but it is not a big difference between assigning an integer value to a int/short/long array and assigning a character value. This is why the first version is preferred and personally I like it better.

buffer[end_position] = 0; 

mysql query order by multiple items

SELECT id, user_id, video_name
FROM sa_created_videos
ORDER BY LENGTH(id) ASC, LENGTH(user_id) DESC

How to display hexadecimal numbers in C?

i use it like this:

printf("my number is 0x%02X\n",number);
// output: my number is 0x4A

Just change number "2" to any number of chars You want to print ;)

Log4net does not write the log in the log file

There are a few ways to use log4net. I found it is useful while I was searching for a solution. The solution is described here: https://www.hemelix.com/log4net/

Spring configure @ResponseBody JSON format

Yes but what happens if you start using mixins for example, you cant be having ObjectMapper as a singleton because you will be applying the configuration globally. So you will be adding or setting the mixin classes on the same ObjectMapper instance?

Delete statement in SQL is very slow

Things that can cause a delete to be slow:

  • deleting a lot of records
  • many indexes
  • missing indexes on foreign keys in child tables. (thank you to @CesarAlvaradoDiaz for mentioning this in the comments)
  • deadlocks and blocking
  • triggers
  • cascade delete (those ten parent records you are deleting could mean millions of child records getting deleted)
  • Transaction log needing to grow
  • Many Foreign keys to check

So your choices are to find out what is blocking and fix it or run the deletes in off hours when they won't be interfering with the normal production load. You can run the delete in batches (useful if you have triggers, cascade delete, or a large number of records). You can drop and recreate the indexes (best if you can do that in off hours too).

Retrieve WordPress root directory path?

You can use get_site_url() function to get the base url of the wordpress site.

For more information, please visit http://codex.wordpress.org/Function_Reference/get_site_url

Angular2: child component access parent class variable/function

The main article in the Angular2 documentation on this subject is :

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child

It covers the following:

  • Pass data from parent to child with input binding

  • Intercept input property changes with a setter

  • Intercept input property changes with ngOnChanges

  • Parent listens for child event

  • Parent interacts with child via a local variable

  • Parent calls a ViewChild

  • Parent and children communicate via a service

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

Open web.config,then Change

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>

To

<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" timeout="2880" />
</authentication>

change to ~/Default.aspx

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

Project with path ':mypath' could not be found in root project 'myproject'

It's not enough to have just compile project("xy") dependency. You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).

Create a settings.gradle file in the root of your project and add this:

include ':progressfragment'

to that file. Then sync Gradle and it should work.

Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.

Check if value exists in column in VBA

Just to modify scott's answer to make it a function:

Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant

    Dim LookAtWhat As Integer

    If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart

    With RngIn
        Set FindFirstInRange = .Find(What:=FindString, _
                                     After:=.Cells(.Cells.Count), _
                                     LookIn:=xlValues, _
                                     LookAt:=LookAtWhat, _
                                     SearchOrder:=xlByRows, _
                                     SearchDirection:=xlNext, _
                                     MatchCase:=UseCase)

        If FindFirstInRange Is Nothing Then FindFirstInRange = False

    End With

End Function

This returns FALSE if the value isn't found, and if it's found, it returns the range.

You can optionally tell it to be case-sensitive, and/or to allow partial-word matches.

I took out the TRIM because you can add that beforehand if you want to.

An example:

MsgBox FindFirstInRange(StringToFind, Range("2:2"), TRUE, FALSE).Address

That does a case-sensitive, partial-word search on the 2nd row and displays a box with the address. The following is the same search, but a whole-word search that is not case-sensitive:

MsgBox FindFirstInRange(StringToFind, Range("2:2")).Address

You can easily tweak this function to your liking or change it from a Variant to to a boolean, or whatever, to speed it up a little.

Do note that VBA's Find is sometimes slower than other methods like brute-force looping or Match, so don't assume that it's the fastest just because it's native to VBA. It's more complicated and flexible, which also can make it not always as efficient. And it has some funny quirks to look out for, like the "Object variable or with block variable not set" error.

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

The easiest way I have found to have the proper "directory" structure appear under the drawable folder for my icons is this:

  1. Right click "Drawable"
  2. Click on "New", then "Image Asset"
  3. Change "Asset Type" to "Action Bar and Tab Icons"
  4. For "Foreground" choose "ClipArt"
  5. For "Clipart" click and "Choose" button and pick any icon
  6. For "Resource Name" type in you icon file name

Now the pseudo-directories have been created for you under the Drawable folder in the Android view. Open up the true directories on your file system "main/res/drawable-xxhdpi", "main/res/drawable-xhdpi" and replace the icons in each folder with your own of the proper density.

How do I find out my root MySQL password?

MySQL 5.5 on Ubuntu 14.04 required slightly different commands as recommended here. In a nutshell:

sudo /etc/init.d/mysql stop
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
mysql -u root

And then from the MySQL prompt

FLUSH PRIVILEGES;
SET PASSWORD FOR root@'localhost' = PASSWORD('password');
UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
FLUSH PRIVILEGES;

And the cited source offers an alternate method as well.

What is a "static" function in C?

A static function is one that can be called on the class itself, as opposed to an instance of the class.

For example a non-static would be:

Person* tom = new Person();
tom->setName("Tom");

This method works on an instance of the class, not the class itself. However you can have a static method that can work without having an instance. This is sometimes used in the Factory pattern:

Person* tom = Person::createNewPerson();

Setting onClickListener for the Drawable right of an EditText

public class CustomEditText extends androidx.appcompat.widget.AppCompatEditText {

    private Drawable drawableRight;
    private Drawable drawableLeft;
    private Drawable drawableTop;
    private Drawable drawableBottom;

    int actionX, actionY;

    private DrawableClickListener clickListener;

    public CustomEditText (Context context, AttributeSet attrs) {
        super(context, attrs);
        // this Contructure required when you are using this view in xml
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);        
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    public void setCompoundDrawables(Drawable left, Drawable top,
            Drawable right, Drawable bottom) {
        if (left != null) {
            drawableLeft = left;
        }
        if (right != null) {
            drawableRight = right;
        }
        if (top != null) {
            drawableTop = top;
        }
        if (bottom != null) {
            drawableBottom = bottom;
        }
        super.setCompoundDrawables(left, top, right, bottom);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Rect bounds;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            actionX = (int) event.getX();
            actionY = (int) event.getY();
            if (drawableBottom != null
                    && drawableBottom.getBounds().contains(actionX, actionY)) {
                clickListener.onClick(DrawablePosition.BOTTOM);
                return super.onTouchEvent(event);
            }

            if (drawableTop != null
                    && drawableTop.getBounds().contains(actionX, actionY)) {
                clickListener.onClick(DrawablePosition.TOP);
                return super.onTouchEvent(event);
            }

            // this works for left since container shares 0,0 origin with bounds
            if (drawableLeft != null) {
                bounds = null;
                bounds = drawableLeft.getBounds();

                int x, y;
                int extraTapArea = (int) (13 * getResources().getDisplayMetrics().density  + 0.5);

                x = actionX;
                y = actionY;

                if (!bounds.contains(actionX, actionY)) {
                    /** Gives the +20 area for tapping. */
                    x = (int) (actionX - extraTapArea);
                    y = (int) (actionY - extraTapArea);

                    if (x <= 0)
                        x = actionX;
                    if (y <= 0)
                        y = actionY;

                    /** Creates square from the smallest value */
                    if (x < y) {
                        y = x;
                    }
                }

                if (bounds.contains(x, y) && clickListener != null) {
                    clickListener
                            .onClick(DrawableClickListener.DrawablePosition.LEFT);
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;

                }
            }

            if (drawableRight != null) {

                bounds = null;
                bounds = drawableRight.getBounds();

                int x, y;
                int extraTapArea = 13;

                /**
                 * IF USER CLICKS JUST OUT SIDE THE RECTANGLE OF THE DRAWABLE
                 * THAN ADD X AND SUBTRACT THE Y WITH SOME VALUE SO THAT AFTER
                 * CALCULATING X AND Y CO-ORDINATE LIES INTO THE DRAWBABLE
                 * BOUND. - this process help to increase the tappable area of
                 * the rectangle.
                 */
                x = (int) (actionX + extraTapArea);
                y = (int) (actionY - extraTapArea);

                /**Since this is right drawable subtract the value of x from the width 
                * of view. so that width - tappedarea will result in x co-ordinate in drawable bound. 
                */
                x = getWidth() - x;
                
                 /*x can be negative if user taps at x co-ordinate just near the width.
                 * e.g views width = 300 and user taps 290. Then as per previous calculation
                 * 290 + 13 = 303. So subtract X from getWidth() will result in negative value.
                 * So to avoid this add the value previous added when x goes negative.
                 */
                 
                if(x <= 0){
                    x += extraTapArea;
                }
                
                 /* If result after calculating for extra tappable area is negative.
                 * assign the original value so that after subtracting
                 * extratapping area value doesn't go into negative value.
                 */               
                 
                if (y <= 0)
                    y = actionY;                

                /**If drawble bounds contains the x and y points then move ahead.*/
                if (bounds.contains(x, y) && clickListener != null) {
                    clickListener
                            .onClick(DrawableClickListener.DrawablePosition.RIGHT);
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;
                }
                return super.onTouchEvent(event);
            }           

        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        drawableRight = null;
        drawableBottom = null;
        drawableLeft = null;
        drawableTop = null;
        super.finalize();
    }

    public void setDrawableClickListener(DrawableClickListener listener) {
        this.clickListener = listener;
    }

}

Also Create an Interface with

public interface DrawableClickListener {

    public static enum DrawablePosition { TOP, BOTTOM, LEFT, RIGHT };
    public void onClick(DrawablePosition target); 
    }

Still if u need any help, comment

Also set the drawableClickListener on the view in activity file.

editText.setDrawableClickListener(new DrawableClickListener() {
        
         
        public void onClick(DrawablePosition target) {
            switch (target) {
            case LEFT:
                //Do something here
                break;

            default:
                break;
            }
        }
        
    });

Uncaught TypeError: (intermediate value)(...) is not a function

When I create a root class, whose methods I defined using the arrow functions. When inheriting and overwriting the original function I noticed the same issue.

class C {
  x = () => 1; 
 };
 
class CC extends C {
  x = (foo) =>  super.x() + foo;
};

let add = new CC;
console.log(add.x(4));

this is solved by defining the method of the parent class without arrow functions

class C {
  x() { 
    return 1; 
  }; 
 };
 
class CC extends C {
  x = foo =>  super.x() + foo;
};

let add = new CC;
console.log(add.x(4));

You have not concluded your merge (MERGE_HEAD exists)

If you are sure that you already resolved all merge conflicts:

rm -rf .git/MERGE*

And the error will disappear.

What is Java EE?

J(2)EE, strictly speaking, is a set of APIs (as the current top answer has it) which enable a programmer to build distributed, transactional systems. The idea was to abstract away the complicated distributed, transactional bits (which would be implemented by a Container such as WebSphere or Weblogic), leaving the programmer to develop business logic free from worries about storage mechanisms and synchronization.

In reality, it was a cobbled-together, design-by-committee mish-mash, which was pushed pretty much for the benefit of vendors like IBM, Oracle and BEA so they could sell ridicously over-complicated, over-engineered, over-useless products. Which didn't have the most basic features (such as scheduling)!

J2EE was a marketing construct.

Getting all types that implement an interface

There are many valid answers already but I'd like to add anther implementation as a Type extension and a list of unit tests to demonstrate different scenarios:

public static class TypeExtensions
{
    public static IEnumerable<Type> GetAllTypes(this Type type)
    {
        var typeInfo = type.GetTypeInfo();
        var allTypes = GetAllImplementedTypes(type).Concat(typeInfo.ImplementedInterfaces);
        return allTypes;
    }

    private static IEnumerable<Type> GetAllImplementedTypes(Type type)
    {
        yield return type;
        var typeInfo = type.GetTypeInfo();
        var baseType = typeInfo.BaseType;
        if (baseType != null)
        {
            foreach (var foundType in GetAllImplementedTypes(baseType))
            {
                yield return foundType;
            }
        }
    }
}

This algorithm supports the following scenarios:

public static class GetAllTypesTests
{
    public class Given_A_Sample_Standalone_Class_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(SampleStandalone);

            _expectedTypes =
                new List<Type>
                {
                    typeof(SampleStandalone),
                    typeof(object)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Abstract_Base_Class_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(SampleBase);

            _expectedTypes =
                new List<Type>
                {
                    typeof(SampleBase),
                    typeof(object)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Child_Class_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(SampleChild);

            _expectedTypes =
                new List<Type>
                {
                    typeof(SampleChild),
                    typeof(SampleBase),
                    typeof(object)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Base_Interface_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(ISampleBase);

            _expectedTypes =
                new List<Type>
                {
                    typeof(ISampleBase)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Child_Interface_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(ISampleChild);

            _expectedTypes =
                new List<Type>
                {
                    typeof(ISampleBase),
                    typeof(ISampleChild)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Implementation_Class_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        protected override void Given()
        {
            _sut = typeof(SampleImplementation);

            _expectedTypes =
                new List<Type>
                {
                    typeof(SampleImplementation),
                    typeof(SampleChild),
                    typeof(SampleBase),
                    typeof(ISampleChild),
                    typeof(ISampleBase),
                    typeof(object)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    public class Given_A_Sample_Interface_Instance_Type_When_Getting_All_Types
        : Given_When_Then_Test
    {
        private Type _sut;
        private IEnumerable<Type> _expectedTypes;
        private IEnumerable<Type> _result;

        class Foo : ISampleChild { }

        protected override void Given()
        {
            var foo = new Foo();
            _sut = foo.GetType();

            _expectedTypes =
                new List<Type>
                {
                    typeof(Foo),
                    typeof(ISampleChild),
                    typeof(ISampleBase),
                    typeof(object)
                };
        }

        protected override void When()
        {
            _result = _sut.GetAllTypes();
        }

        [Fact]
        public void Then_It_Should_Return_The_Right_Type()
        {
            _result.Should().BeEquivalentTo(_expectedTypes);
        }
    }

    sealed class SampleStandalone { }
    abstract class SampleBase { }
    class SampleChild : SampleBase { }
    interface ISampleBase { }
    interface ISampleChild : ISampleBase { }
    class SampleImplementation : SampleChild, ISampleChild { }
}

How to send email from SQL Server?

In-order to make SQL server send email notification you need to create mail profile from Management, database mail.

1) User Right click to get the mail profile menu and choose configure database mail

2)choose the first open (set up a database mail by following the following tasks) and press next Note: if the SMTP is not configured please refer the the URL below

http://www.symantec.com/business/support/index?page=content&id=TECH86263

3) in the second screen fill the the profile name and add SMTP account, then press next

4) choose the type of mail account ( public or private ) then press next

5) change the parameters that related to the sending mail options, and press next 6) press finish

Now to make SQL server send an email if action X happened you can do that via trigger or job ( This is the common ways not the only ones).

1) you can create Job from SQL server agent, then right click on operators and check mails (fill the your email for example) and press OK after that right click Jobs and choose new job and fill the required info as well as the from steps, name, ...etc and from notification tab select the profile you made.

2) from triggers please refer to the example below.

AS
declare @results varchar(max)
declare @subjectText varchar(max)
declare @databaseName VARCHAR(255)
SET @subjectText = 'your subject'
SET @results = 'your results'
-- write the Trigger JOB
EXEC msdb.dbo.sp_send_dbmail
 @profile_name = 'SQLAlerts',
 @recipients = '[email protected]',
 @body = @results,
 @subject = @subjectText,
 @exclude_query_output = 1 --Suppress 'Mail Queued' message
GO

What is the functionality of setSoTimeout and how it works?

The JavaDoc explains it very well:

With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

SO_TIMEOUT is the timeout that a read() call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read() call will block until at least 1 byte could be read.

The action or event has been blocked by Disabled Mode

No. Go to database tools (for 2007) and click checkmark on the Message Bar. Then, after the message bar apears, click on Options, and then Enable. Hope this helps.

Dimitri

Should I use <i> tag for icons instead of <span>?

I take a totally different approach to everyone else's answers here altogether. Let me prefix my solution and argue by stating that sometimes standards and conventions are meant to be broken, especially in the context of the standard HTML lexical tag definitions.

There's nothing to stop you from creating custom elements that are self-descriptive to it's very purpose.

Both modern browsers and even IE 6+ (w/ shim) can support things like:

<icon class="plus">

or

<icon-add>

Just make sure to normalize the tag:

 icon { display:block; margin:0; padding:0; border:0; ... }

and use a shim if you need to support IE9 or earlier (see post below).

Check out this StackOverflow Post:

Is there a way to create your own html tag in HTML5

To further my argument, both Google's Angular Directives and the new Polymer projects utilize the concept of custom HTML tags.

How do I stop a program when an exception is raised in Python?

import sys

try:
    import feedparser
except:
    print "Error: Cannot import feedparser.\n" 
    sys.exit(1)

Here we're exiting with a status code of 1. It is usually also helpful to output an error message, write to a log, and clean up.

How do I remove/delete a folder that is not empty?

With os.walk I would propose the solution which consists of 3 one-liner Python calls:

python -c "import sys; import os; [os.chmod(os.path.join(rs,d), 0o777) for rs,ds,fs in os.walk(_path_) for d in ds]"
python -c "import sys; import os; [os.chmod(os.path.join(rs,f), 0o777) for rs,ds,fs in os.walk(_path_) for f in fs]"
python -c "import os; import shutil; shutil.rmtree(_path_, ignore_errors=False)"

The first script chmod's all sub-directories, the second script chmod's all files. Then the third script removes everything with no impediments.

I have tested this from the "Shell Script" in a Jenkins job (I did not want to store a new Python script into SCM, that's why searched for a one-line solution) and it worked for Linux and Windows.

matplotlib has no attribute 'pyplot'

pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

p = plt.plot(...)

How to disable or enable viewpager swiping in android

For disabling swiping

mViewPager.beginFakeDrag();

For enable swiping

if (mViewPager.isFakeDragging()) mViewPager.endFakeDrag();

Difference between attr_accessor and attr_accessible

attr_accessor is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname and you can use this field in your View, or model, if you wanted, but mostly in your View.

Let's consider the following example

class Address
    attr_reader :street
    attr_writer :street  
    def initialize
        @street = ""
    end
end

Here we have used attr_reader (readable attribute) and attr_writer (writable attribute) for accessing purpose. But we can achieve the same functionality using attr_accessor. In short, attr_accessor provides access to both getter and setter methods.

So modified code is as below

class Address
    attr_accessor :street  
    def initialize
        @street = ""
    end
end

attr_accessible allows you to list all the columns you want to allow Mass Assignment. The opposite of this is attr_protected which means this field I do NOT want anyone to be allowed to Mass Assign to. More than likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like.

Clearing content of text file using C#

File.WriteAllText(path, String.Empty);

Alternatively,

File.Create(path).Close();

How do I split a multi-line string into multiple lines?

inputString.splitlines()

Will give you a list with each item, the splitlines() method is designed to split each line into a list element.

Merging two images with PHP

The GD Image Manipulation Library in PHP is probably the best for working with images in PHP. Try one of the imagecopy functions (imagecopy, imagecopymerge, ...). Each of them combine 2 images in different ways. See the php documentation on imagecopy for more information.

Objective C - Assign, Copy, Retain

  1. assign

    • assign is a default property attribute
    • assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
  2. copy:

    • copy is required when the object is mutable
    • copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
    • you need to release the object when finished with it because you are retaining the copy
  3. retain:

    • specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
    • if you write retain it will auto work like strong
    • Methods like “alloc” include an implicit “retain”

No suitable records were found verify your bundle identifier is correct

if your app transfer other account. You should rearrange Signing section for the corrcet team(new team)

How to dump only specific tables from MySQL?

Usage: mysqldump [OPTIONS] database [tables]

i.e.

mysqldump -u username -p db_name table1_name table2_name table3_name > dump.sql

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

Efficient way to Handle ResultSet in Java

A couple of things to enhance the other answers. First, you should never return a HashMap, which is a specific implementation. Return instead a plain old java.util.Map. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).

How to increase Heap size of JVM

Java command line parameters

-Xms: initial heap size
-Xmx: Maximum heap size

if you are using Tomcat. Update CATALINA_OPTS environment variable

export CATALINA_OPTS=-Xms16m -Xmx256m;

Getting an odd error, SQL Server query using `WITH` clause

always use with statement like ;WITH then you'll never get this error. The WITH command required a ; between it and any previous command, by always using ;WITH you'll never have to remember to do this.

see WITH common_table_expression (Transact-SQL), from the section Guidelines for Creating and Using Common Table Expressions:

When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon.

Getting the docstring from a function

You can also use inspect.getdoc. It cleans up the __doc__ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.

How to split strings into text and number?

Yet Another Option:

>>> [re.split(r'(\d+)', s) for s in ('foofo21', 'bar432', 'foobar12345')]
[['foofo', '21', ''], ['bar', '432', ''], ['foobar', '12345', '']]

Why compile Python code?

Yep, performance is the main reason and, as far as I know, the only reason.

If some of your files aren't getting compiled, maybe Python isn't able to write to the .pyc file, perhaps because of the directory permissions or something. Or perhaps the uncompiled files just aren't ever getting loaded... (scripts/modules only get compiled when they first get loaded)

pandas three-way joining multiple dataframes on columns

Simple Solution:

If the column names are similar:

 df1.merge(df2,on='col_name').merge(df3,on='col_name')

If the column names are different:

df1.merge(df2,left_on='col_name1', right_on='col_name2').merge(df3,left_on='col_name1', right_on='col_name3').drop(columns=['col_name2', 'col_name3']).rename(columns={'col_name1':'col_name'})

How are environment variables used in Jenkins with Windows Batch Command?

I should this On Windows, environment variable expansion is %BUILD_NUMBER%

Google Maps shows "For development purposes only"

As Victoria wrote, Google Maps is no longer free, but you can switch your map provider. You may be interested in OpenStreetMap, there is an easy way to use it on your site described here: https://handyman.dulare.com/switching-from-google-maps-to-openstreetmap/

Unfortunately, on the OpenStreetMap, there is no easy way to provide directions from one point to another, there is also no street view.

"Uncaught Error: [$injector:unpr]" with angular after deployment

If you have separated files for angular app\resources\directives and other stuff then you can just disable minification of your angular app bundle like this (use new Bundle() instead of ScriptBundle() in your bundle config file):

bundles.Add(
new Bundle("~/bundles/angular/SomeBundleName").Include(
               "~/Content/js/angular/Pages/Web/MainPage/angularApi.js",
               "~/Content/js/angular/Pages/Web/MainPage/angularApp.js",
               "~/Content/js/angular/Pages/Web/MainPage/angularCtrl.js"));

And angular app would appear in bundle unmodified.

Missing MVC template in Visual Studio 2015

I had the same issue with the MVC template not appearing in VS2015.

I checked Web Developer Tools when originally installing. It was still checked when trying to Modify the install. I tried unchecking and updating the install but next time I went back to Modify, it was still checked. And still no MVC template.

I got it working by uninstalling: Microsoft ASP.NET Web Frameworks and Tools 2015 via the Programs and Features windows and re-installing. Here's the link for those who don't have it.

How to use CSS to surround a number with a circle?

You can use the border-radius for this:

<html>
  <head>
    <style type="text/css">

    .round
    {
        -moz-border-radius: 15px;
        border-radius: 15px;
        padding: 5px;
        border: 1px solid #000;
    }

  </style>
  </head>  
  <body>   
    <span class="round">30</span>
  </body>
</html>  

Play with the border radius and the padding values until you are satisfied with the result.

But this won't work in all browsers. I guess IE still does not support rounded corners.

Why is this rsync connection unexpectedly closed on Windows?

I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.

On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.

I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.

failed to lazily initialize a collection of role

It's possible that you're not fetching the Joined Set. Be sure to include the set in your HQL:

public List<Node> getAll() {
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("FROM Node as n LEFT JOIN FETCH n.nodeValues LEFT JOIN FETCH n.nodeStats");
    return  query.list();
}

Where your class has 2 sets like:

public class Node implements Serializable {

@OneToMany(fetch=FetchType.LAZY)
private Set<NodeValue> nodeValues;

@OneToMany(fetch=FetchType.LAZY)
private Set<NodeStat> nodeStats;

}

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Even when you asked finally for the opposite, to reform 0s and 1s into Trues and Falses, however, I post an answer about how to transform falses and trues into ones and zeros (1s and 0s), for a whole dataframe, in a single line.

Example given

df <- structure(list(p1_1 = c(TRUE, FALSE, FALSE, NA, TRUE, FALSE, 
                NA), p1_2 = c(FALSE, TRUE, FALSE, NA, FALSE, NA, 
                TRUE), p1_3 = c(TRUE, 
                TRUE, FALSE, NA, NA, FALSE, TRUE), p1_4 = c(FALSE, NA, 
                FALSE,  FALSE, TRUE, FALSE, NA), p1_5 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_6 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_7 = c(TRUE, NA, 
                FALSE, TRUE, NA, FALSE, TRUE), p1_8 = c(FALSE, 
                FALSE, NA, FALSE, TRUE, FALSE, NA), p1_9 = c(TRUE, 
                FALSE,  NA, FALSE, FALSE, NA, TRUE), p1_10 = c(TRUE, 
                FALSE, NA, FALSE, FALSE, NA, TRUE), p1_11 = c(FALSE, 
                FALSE, NA, FALSE, NA, FALSE, TRUE)), .Names = 
                c("p1_1", "p1_2", "p1_3", "p1_4", "p1_5", "p1_6", 
                "p1_7", "p1_8", "p1_9", "p1_10", "p1_11"), row.names = 
                 c(NA, -7L), class = "data.frame")

   p1_1  p1_2  p1_3  p1_4  p1_5  p1_6  p1_7  p1_8  p1_9 p1_10 p1_11
1  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE
2 FALSE  TRUE  TRUE    NA    NA    NA    NA FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE    NA    NA    NA    NA
4    NA    NA    NA FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
5  TRUE FALSE    NA  TRUE FALSE FALSE    NA  TRUE FALSE FALSE    NA
6 FALSE    NA FALSE FALSE    NA    NA FALSE FALSE    NA    NA FALSE
7    NA  TRUE  TRUE    NA  TRUE  TRUE  TRUE    NA  TRUE  TRUE  TRUE

Then by running that: df * 1 all Falses and Trues are trasnformed into 1s and 0s. At least, this was happen in the R version that I have (R version 3.4.4 (2018-03-15) ).

> df*1
  p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1    1    0    1    0    1    1    1    0    1     1     0
2    0    1    1   NA   NA   NA   NA    0    0     0     0
3    0    0    0    0    0    0    0   NA   NA    NA    NA
4   NA   NA   NA    0    1    1    1    0    0     0     0
5    1    0   NA    1    0    0   NA    1    0     0    NA
6    0   NA    0    0   NA   NA    0    0   NA    NA     0
7   NA    1    1   NA    1    1    1   NA    1     1     1

I do not know if it a total "safe" command, under all different conditions / dfs.

To compare two elements(string type) in XSLT?

First of all, the provided long code:

    <xsl:choose>
        <xsl:when test="OU_NAME='OU_ADDR1'">   --comparing two elements coming from XML             
            <!--remove if  adrees already contain  operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="OU_NAME"/>
            <fo:block/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:otherwise>
    </xsl:choose>

is equivalent to this, much shorter code:

<xsl:if test="not(OU_NAME='OU_ADDR1)'">
              <xsl:value-of select="OU_NAME"/>
        </xsl:if>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>

Now, to your question:

how to compare two elements coming from xml as string

In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator = and the function not() together with the operator =.

$str1 = $str2

evaluates to true() exactly when the string $str1 is equal to the string $str2.

not($str1 = $str2)

evaluates to true() exactly when the string $str1 is not equal to the string $str2.

There is also the != operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.

Now, the rules for comparing two element nodes are similar:

$el1 = $el2

evaluates to true() exactly when the string value of $el1 is equal to the string value of $el2.

not($el1 = $el2)

evaluates to true() exactly when the string value of $el1 is not equal to the string value of $el2.

However, if one of the operands of = is a node-set, then

 $ns = $str

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string $str

$ns1 = $ns2

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string value of some node from $ns2

Therefore, the expression:

OU_NAME='OU_ADDR1'

evaluates to true() only when there is at least one element child of the current node that is named OU_NAME and whose string value is the string 'OU_ADDR1'.

This is obviously not what you want!

Most probably you want:

OU_NAME=OU_ADDR1

This expression evaluates to true exactly there is at least one OU_NAME child of the current node and one OU_ADDR1 child of the current node with the same string value.

Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt, le, eq, gt, ge and the inherited from XPath 1.0 general comparison operator =.

Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.

android edittext onchange listener

Anyone using ButterKnife. You can use like:

@OnTextChanged(R.id.zip_code)
void onZipCodeTextChanged(CharSequence zipCode, int start, int count, int after) {

}

Remove decimal values using SQL query

Simply update with a convert/cast to INT:

UPDATE YOUR_TABLE
SET YOUR_COLUMN = CAST(YOUR_COLUMN AS INT)
WHERE -- some condition is met if required

Or convert:

UPDATE YOUR_TABLE
SET YOUR_COLUMN = CONVERT(INT, YOUR_COLUMN)
WHERE -- some condition is met if required

To test you can do this:

SELECT YOUR_COLUMN AS CurrentValue,
       CAST(YOUR_COLUMN AS INT) AS NewValue
FROM YOUR_TABLE

Spring @PropertySource using YAML

Another option is to set the spring.config.location through @TestPropertySource:

@TestPropertySource(properties = { "spring.config.location = classpath:<path-to-your-yml-file>" }

Wait until an HTML5 video loads

call function on load:

<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">

get video duration

var video = document.getElementById("video");
var duration = video.duration;

With arrays, why is it the case that a[5] == 5[a]?

I just find out this ugly syntax could be "useful", or at least very fun to play with when you want to deal with an array of indexes which refer to positions into the same array. It can replace nested square brackets and make the code more readable !

int a[] = { 2 , 3 , 3 , 2 , 4 };
int s = sizeof a / sizeof *a;  //  s == 5

for(int i = 0 ; i < s ; ++i) {  
           
    cout << a[a[a[i]]] << endl;
    // ... is equivalent to ...
    cout << i[a][a][a] << endl;  // but I prefer this one, it's easier to increase the level of indirection (without loop)
    
}

Of course, I'm quite sure that there is no use case for that in real code, but I found it interesting anyway :)

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"

For more examples see:

?SpecialCharacters

Your problem can be solved this way:

library(rebus)
grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

char_class("?")
## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

literal(".")
## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

TypeError: Object of type 'bytes' is not JSON serializable

I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json). my_json_object in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.

The way I ended up solving it: the write_to_file.json will have everything up to the bytes object that is causing the issue.

In my particular case this was a line obtained through

for line in text:
    json_object['line'] = line.strip()

I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:

for line in text:
    json_object['line'] = line.strip().decode()

How do I update the password for Git?

you can change password through command line in 2 places, following would edit credentials to connect the repo

git config --edit 

The credentials also can be changed at global using global parameter like below

 git config --global --add user.password "XXXX"

or set the credentials helper with

git config --global credential.helper wincred

but if you have repo level credentials set the use the first command

git config --edit

How to run a maven created jar file using just the command line

I am not sure in your case. But as I know to run any jar file from cmd we can use following command:

Go up to the directory where your jar file is saved:

java -jar <jarfilename>.jar

But you can check following links. I hope it'll help you:

Run Netbeans maven project from command-line?

http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html

How do I view cookies in Internet Explorer 11 using Developer Tools

Not quite an answer (not “using Developer Tools”), but there is a third-party tool for it: IECookiesView from NirSoft. Hope this helps someone.

screenshot

image taken from Softpedia

MySQL SELECT DISTINCT multiple columns

Taking a guess at the results you want so maybe this is the query you want then

SELECT DISTINCT a FROM my_table
UNION 
SELECT DISTINCT b FROM my_table
UNION
SELECT DISTINCT c FROM my_table
UNION
SELECT DISTINCT d FROM my_table

Bootstrap 4 - Glyphicons migration?

Go to

https://github.com/Darkseal/bootstrap4-glyphicons

download and include in your code

<link href="bootstrap4-glyphicons/css/bootstrap-glyphicons.css" rel="stylesheet">

Pygame Drawing a Rectangle

import pygame, sys
from pygame.locals import *

def main():
    pygame.init()

    DISPLAY=pygame.display.set_mode((500,400),0,32)

    WHITE=(255,255,255)
    BLUE=(0,0,255)

    DISPLAY.fill(WHITE)

    pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))

    while True:
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

main()

This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect to go about this, and you add the DISPLAY constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.

Look up pygame.org for more info

Difference between a Structure and a Union

Here's the short answer: a struct is a record structure: each element in the struct allocates new space. So, a struct like

struct foobarbazquux_t {
    int foo;
    long bar;
    double baz; 
    long double quux;
}

allocates at least (sizeof(int)+sizeof(long)+sizeof(double)+sizeof(long double)) bytes in memory for each instance. ("At least" because architecture alignment constraints may force the compiler to pad the struct.)

On the other hand,

union foobarbazquux_u {
    int foo;
    long bar;
    double baz; 
    long double quux;
}

allocates one chunk of memory and gives it four aliases. So sizeof(union foobarbazquux_u) = max((sizeof(int),sizeof(long),sizeof(double),sizeof(long double)), again with the possibility of some addition for alignments.

Print number of keys in Redis

After Redis 2.6, the result of INFO command are splitted by sections. In the "keyspace" section, there are "keys" and "expired keys" fields to tell how many keys are there.

How to get the public IP address of a user in C#

Combination of all of these suggestions, and the reasons behind them. Feel free to add more test cases too. If getting the client IP is of utmost importance, than you might wan to get all of theses are run some comparisons on which result might be more accurate.

Simple check of all suggestions in this thread plus some of my own code...

    using System.IO;
    using System.Net;

    public string GetUserIP()
    {
        string strIP = String.Empty;
        HttpRequest httpReq = HttpContext.Current.Request;

        //test for non-standard proxy server designations of client's IP
        if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)
        {
            strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();
        }
        else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        //test for host address reported by the server
        else if
        (
            //if exists
            (httpReq.UserHostAddress.Length != 0)
            &&
            //and if not localhost IPV6 or localhost name
            ((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))
        )
        {
            strIP = httpReq.UserHostAddress;
        }
        //finally, if all else fails, get the IP from a web scrape of another server
        else
        {
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                strIP = sr.ReadToEnd();
            }
            //scrape ip from the html
            int i1 = strIP.IndexOf("Address: ") + 9;
            int i2 = strIP.LastIndexOf("</body>");
            strIP = strIP.Substring(i1, i2 - i1);
        }
        return strIP;
    }

Formatting a double to two decimal places

Well, depending on your needs you can choose any of the following. Out put is written against each method

You can choose the one you need

This will round

decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58

This will ensure that 2 decimal places are written.

d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50

if you want to write commas you can use this

d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54

if you want to return the rounded of decimal value you can do this

d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58

I ran into a merge conflict. How can I abort the merge?

Since Git 1.6.1.3 git checkout has been able to checkout from either side of a merge:

git checkout --theirs _widget.html.erb

How do I instantiate a Queue object in java?

Queue is an interface; you can't explicitly construct a Queue. You'll have to instantiate one of its implementing classes. Something like:

Queue linkedList = new LinkedList();

Here's a link to the Java tutorial on this subject.

How to download fetch response in react as file

This worked for me.

const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};

fetch(`${url}`, requestOptions)
.then((res) => {
    return res.blob();
})
.then((blob) => {
    const href = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = href;
    link.setAttribute('download', 'config.json'); //or any other extension
    document.body.appendChild(link);
    link.click();
})
.catch((err) => {
    return Promise.reject({ Error: 'Something Went Wrong', err });
})

"date(): It is not safe to rely on the system's timezone settings..."

I am hosting my EC2 and S3 bucket in us-west-2 (Oregon) region. When I was calling $s3client->listBuckets() to list existing buckets in my php, I was getting exception - "Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings...". I made below changes to make it work. Sharing these details in case someone is facing similar issue and any of above answers have not helped.

  1. Based on documentation @ AWS Configuring Network Time Protocol (NTP), I confirmed ntpd service status is fine by running ntpstat command. If you get error, this link helps you to know what is going wrong.
  2. Opened /etc/php.ini file (some may have it in different path based on version of php installed) and found that date.timezone was not set to any value and also it was commented by default. I un-commented by removing ';' before this line and set its value to "UTC" and saved the file.
  3. Restarted http and ntp daemons using sudo service httpd restart and sudo service ntpd restart commands.

After this I am able to list buckets successfully without any exception. Hope this helps.

Laravel 5 route not defined, while it is?

This thread is old but was the first one to come up so I thought id share my solution too. Apart from having named routes in your routes.php file. This error can also occur when you have duplicate URLs in your routes file, but with different names, the error can be misleading in this scenario. Example

Route::any('official/form/reject-form', 'FormStatus@rejectForm')->name('reject-form');  


Route::any('official/form/accept-form', 'FormStatus@acceptForm')->name('accept-form');

Changing one of the names solves the problem. Copy pasting and fatigue will get you to this problem :).

Change drive in git bash for windows

TL;DR; for Windows users:

(Quotation marks not needed if path has no blank spaces)

Git Bash: cd "/C/Program Files (x86)/Android" // macOS/Linux syntax

Cmd.exe: cd "C:\Program Files (x86)\Android" // windows syntax


When using git bash on windows, you have to:

  • remove the colon after the drive letter
  • replace your back-slashes with forward-slashes
  • If you have blank spaces in your path: Put quotation marks at beginning and end of the path

Git Bash: cd "/C/Program Files (x86)/Android" // macOS/Linux syntax

Cmd.exe: cd "C:\Program Files (x86)\Android" // windows syntax

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

You can have better performance by using the following method:

SELECT COUNT(1) FROM (SELECT /*+FIRST_ROWS*/ column_name 
FROM table_name 
WHERE column_name = 'xxxxx' AND ROWNUM = 1);

How to strip a specific word from a string?

If want to remove the word from only the start of the string, then you could do:

  string[string.startswith(prefix) and len(prefix):]  

Where string is your string variable and prefix is the prefix you want to remove from your string variable.

For example:

  >>> papa = "papa is a good man. papa is the best."  
  >>> prefix = 'papa'
  >>> papa[papa.startswith(prefix) and len(prefix):]
  ' is a good man. papa is the best.'

How to set the width of a RaisedButton in Flutter?

You need to use an Expanded Widget. But, if your button is on a column, the Expanded Widget fills the rest of the column. So, you need to enclose the Expanded Widget within a row.

Row(children: <Widget>[
Expanded(
  flex: 1,
  child: RaisedButton(
    child: Text("Your Text"),
      onPressed: _submitForm,
    ),
  ),),])

How do I fix "Expected to return a value at the end of arrow function" warning?

The problem seems to be that you are not returning something in the event that your first if-case is false.

The error you are getting states that your arrow function (comment) => { doesn't have a return statement. While it does for when your if-case is true, it does not return anything for when it's false.

return this.props.comments.map((comment) => {
  if (comment.hasComments === true) {
    return (
      <div key={comment.id}>
        <CommentItem className="MainComment" />
        {this.props.comments.map(commentReply => {
          if (commentReply.replyTo === comment.id) { 
            return (
              <CommentItem className="SubComment"/>
            )
          }
        })
        }
      </div>
    )
  } else {
     //return something here.
  }
});

edit you should take a look at Kris' answer for how to better implement what you are trying to do.

Comparing two byte arrays in .NET

Let's add one more!

Recently Microsoft released a special NuGet package, System.Runtime.CompilerServices.Unsafe. It's special because it's written in IL, and provides low-level functionality not directly available in C#.

One of its methods, Unsafe.As<T>(object) allows casting any reference type to another reference type, skipping any safety checks. This is usually a very bad idea, but if both types have the same structure, it can work. So we can use this to cast a byte[] to a long[]:

bool CompareWithUnsafeLibrary(byte[] a1, byte[] a2)
{
    if (a1.Length != a2.Length) return false;

    var longSize = (int)Math.Floor(a1.Length / 8.0);
    var long1 = Unsafe.As<long[]>(a1);
    var long2 = Unsafe.As<long[]>(a2);

    for (var i = 0; i < longSize; i++)
    {
        if (long1[i] != long2[i]) return false;
    }

    for (var i = longSize * 8; i < a1.Length; i++)
    {
        if (a1[i] != a2[i]) return false;
    }

    return true;
}

Note that long1.Length would still return the original array's length, since it's stored in a field in the array's memory structure.

This method is not quite as fast as other methods demonstrated here, but it is a lot faster than the naive method, doesn't use unsafe code or P/Invoke or pinning, and the implementation is quite straightforward (IMO). Here are some BenchmarkDotNet results from my machine:

BenchmarkDotNet=v0.10.3.0, OS=Microsoft Windows NT 6.2.9200.0
Processor=Intel(R) Core(TM) i7-4870HQ CPU 2.50GHz, ProcessorCount=8
Frequency=2435775 Hz, Resolution=410.5470 ns, Timer=TSC
  [Host]     : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0
  DefaultJob : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0

                 Method |          Mean |    StdDev |
----------------------- |-------------- |---------- |
          UnsafeLibrary |   125.8229 ns | 0.3588 ns |
          UnsafeCompare |    89.9036 ns | 0.8243 ns |
           JSharpEquals | 1,432.1717 ns | 1.3161 ns |
 EqualBytesLongUnrolled |    43.7863 ns | 0.8923 ns |
              NewMemCmp |    65.4108 ns | 0.2202 ns |
            ArraysEqual |   910.8372 ns | 2.6082 ns |
          PInvokeMemcmp |    52.7201 ns | 0.1105 ns |

I've also created a gist with all the tests.

.htaccess redirect www to non-www with SSL/HTTPS

To me was better hardcoding "example.com" as string, so I need less rules, even you can use it to redirect from .org to .com or similar too:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
  RewriteRule ^ https://example.com%{REQUEST_URI} [L,NE,R=301]
</IfModule>

How to write LDAP query to test if user is member of a group?

You should be able to create a query with this filter here:

(&(objectClass=user)(sAMAccountName=yourUserName)
  (memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))

and when you run that against your LDAP server, if you get a result, your user "yourUserName" is indeed a member of the group "CN=YourGroup,OU=Users,DC=YourDomain,DC=com

Try and see if this works!

If you use C# / VB.Net and System.DirectoryServices, this snippet should do the trick:

DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=yourcompany,dc=com");

DirectorySearcher srch = new DirectorySearcher(rootEntry);
srch.SearchScope = SearchScope.Subtree;

srch.Filter = "(&(objectClass=user)(sAMAccountName=yourusername)(memberOf=CN=yourgroup,OU=yourOU,DC=yourcompany,DC=com))";

SearchResultCollection res = srch.FindAll();

if(res == null || res.Count <= 0) {
    Console.WriteLine("This user is *NOT* member of that group");
} else {
    Console.WriteLine("This user is INDEED a member of that group");
}

Word of caution: this will only test for immediate group memberships, and it will not test for membership in what is called the "primary group" (usually "cn=Users") in your domain. It does not handle nested memberships, e.g. User A is member of Group A which is member of Group B - that fact that User A is really a member of Group B as well doesn't get reflected here.

Marc

Python `if x is not None` or `if not x is None`?

Both Google and Python's style guide is the best practice:

if x is not None:
    # Do something about x

Using not x can cause unwanted results.

See below:

>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0]         # You don't want to fall in this one.
>>> not x
False

You may be interested to see what literals are evaluated to True or False in Python:


Edit for comment below:

I just did some more testing. not x is None doesn't negate x first and then compared to None. In fact, it seems the is operator has a higher precedence when used that way:

>>> x
[0]
>>> not x is None
True
>>> not (x is None)
True
>>> (not x) is None
False

Therefore, not x is None is just, in my honest opinion, best avoided.


More edit:

I just did more testing and can confirm that bukzor's comment is correct. (At least, I wasn't able to prove it otherwise.)

This means if x is not None has the exact result as if not x is None. I stand corrected. Thanks bukzor.

However, my answer still stands: Use the conventional if x is not None. :]

How do you format a Date/Time in TypeScript?

One more to add @kamalakar's answer, need to import the same in app.module and add DateFormatPipe to providers.

    import {DateFormatPipe} from './DateFormatPipe';
    @NgModule
    ({ declarations: [],  
        imports: [],
        providers: [DateFormatPipe]
    })

Combine Multiple child rows into one row MYSQL

If you really need multiple columns in your result, and the amount of options is limited, you can even do this:

select
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  if(ordered_options.id=1,Ordered_Options.Value,null) as `Option1`,
  if(ordered_options.id=2,Ordered_Options.Value,null) as `Option2`,
  if(ordered_options.id=43,Ordered_Options.Value,null) as `Option43`,
  if(ordered_options.id=44,Ordered_Options.Value,null) as `Option44`,
  GROUP_CONCAT(if(ordered_options.id not in (1,2,43,44),Ordered_Options.Value,null)) as `OtherOptions`
from
  ordered_item,
  ordered_options
where
  ordered_item.id=ordered_options.ordered_item_id
group by
  ordered_item.id

Get folder name from full file path

Try this

var myFolderName = @"c:\projects\roott\wsdlproj\devlop\beta2\text";
var result = Path.GetFileName(myFolderName);

Visually managing MongoDB documents and collections

Here are some popular MongoDB GUI administration tools:

Open source

  • dbKoda - cross-platform, tabbed editor with auto-complete, syntax highlighting and code formatting (plus auto-save, something Studio 3T doesn't support), visual tools (explain plan, real-time performance dashboard, query and aggregation pipeline builder), profiling manager, storage analyzer, index advisor, convert MongoDB commands to Node.js syntax etc. Lacks in-place document editing and the ability to switch themes.

    dbKoda screenshot

  • Nosqlclient - multiple shell output tabs, autocomplete, schema analyzer, index management, user/role management, live monitoring, and other features. Electron/Meteor.js-based, actively developed on GitHub.

  • adminMongo - web-based or Electron app. Supports server monitoring and document editing.

Closed source

  • NoSQLBoosterfull-featured shell-centric cross-platform GUI tool for MongoDB v2.2-4. Free, Personal, and Commercial editions (feature comparison matrix).
  • MongoDB Compass – provides a graphical user interface that allows you to visualize your schema and perform ad-hoc find queries against the database – all with zero knowledge of MongoDB's query language. Developed by MongoDB, Inc. No update queries or access to the shell.
  • Studio 3T, formerly MongoChef – a multi-platform in-place data browser and editor desktop GUI for MongoDB (Core version is free for personal and non-commercial use). Last commit: 2017-Jul-24
  • Robo 3T – acquired by Studio 3T. A shell-centric cross-platform open source MongoDB management tool. Shell-related features only, e.g. multiple shells and results, autocomplete. No export/ import or other features are mentioned. Last commit: 2017-Jul-04

  • HumongouS.io – web-based interface with CRUD features, a chart builder and some collaboration capabilities. 14-day trial.

  • Database Master – a Windows based MongoDB Management Studio, supports also RDBMS. (not free)
  • SlamData - an open source web-based user-interface that allows you to upload and download data, run queries, build charts, explore data.

Abandoned projects

  • RockMongo – a MongoDB administration tool, written in PHP5. Allegedly the best in the PHP world. Similar to PHPMyAdmin. Last version: 2015-Sept-19
  • Fang of Mongo – a web-based UI built with Django and jQuery. Last commit: 2012-Jan-26, in a forked project.
  • Opricot – a browser-based MongoDB shell written in PHP. Latest version: 2010-Sep-21
  • Futon4Mongo – a clone of the CouchDB Futon web interface for MongoDB. Last commit: 2010-Oct-09
  • MongoVUE – an elegant GUI desktop application for Windows. Free and non-free versions. Latest version: 2014-Jan-20
  • UMongo – a full-featured open-source MongoDB server administration tool for Linux, Windows, Mac; written in Java. Last commit 2014-June
  • Mongo3 – a Ruby/Sinatra-based interface for cluster management. Last commit: Apr 16, 2013

How to send HTTP request in java?

There's a great link about sending a POST request here by Example Depot::

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}

If you want to send a GET request you can modify the code slightly to suit your needs. Specifically you have to add the parameters inside the constructor of the URL. Then, also comment out this wr.write(data);

One thing that's not written and you should beware of, is the timeouts. Especially if you want to use it in WebServices you have to set timeouts, otherwise the above code will wait indefinitely or for a very long time at least and it's something presumably you don't want.

Timeouts are set like this conn.setReadTimeout(2000); the input parameter is in milliseconds

Best way to get child nodes

Don't let white space fool you. Just test this in a console browser.

Use native javascript. Here is and example with two 'ul' sets with the same class. You don't need to have your 'ul' list all in one line to avoid white space just use your array count to jump over white space.

How to get around white space with querySelector() then childNodes[] js fiddle link: https://jsfiddle.net/aparadise/56njekdo/

var y = document.querySelector('.list');
var myNode = y.childNodes[11].style.backgroundColor='red';

<ul class="list">
    <li>8</li>
    <li>9</li>
    <li>100</li>
</ul>

<ul class="list">
    <li>ABC</li>
    <li>DEF</li>
    <li>XYZ</li>
</ul>

Android XML Percent Symbol

A tricky method: using small percent sign as below

 <string name="zone_50">Fat Burning (50&#65130; to 60&#65130;)</string> 

Percent Sign on Wikipedia

Unzip All Files In A Directory

To unzip all files in a directory just type this cmd in terminal:

unzip '*.zip'

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;

you might want to use CEIL() if A is always a floating point value > 0 and <= 2

Assigning a function to a variable

I don't know what is the value/usefulness of renaming a function and call it with the new name. But using a string as function name, e.g. obtained from the command line, has some value/usefulness:

import sys
fun = eval(sys.argv[1])
fun()

In the present case, fun = x.

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).