Programs & Examples On #Activitygroup

A screen that contains and runs multiple embedded activities

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

Possibly the smoothest and the simplest solution I found in my case was to avoid popping the offending fragment off the stack in response to activity result. So changing this call in my onActivityResult():

popMyFragmentAndMoveOn();

to this:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    public void run() {
        popMyFragmentAndMoveOn();
    }
}

helped in my case.

How to fix syntax error, unexpected T_IF error in php?

Here is the issue

  $total_result = $result->num_rows;

try this

<?php
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
    if ($result->num_rows > 0)
    {
        $total_result = $result->num_rows;
        $total_pages = ceil($total_result / $per_page);

        if(isset($_GET['page']) && is_numeric($_GET['page']))
        {
            $show_page = $_GET['page'];

            if ($show_page > 0 && $show_page <= $total_pages)
            {
                $start = ($show_page - 1) * $per_page;
                $end = $start + $per_page;
            }
            else
            {
                $start = 0;
                $end = $per_page;
            }               

        }
        else
        {
            $start = 0;
            $end = $per_page;
        }


        //display paginations
        echo "<p> View pages: ";
        for ($i=1; $i < $total_pages; $i++)
        { 
            if (isset($_GET['page']) && $_GET['page'] == $i)
            {
                echo  $i . " ";
            }
            else
            {
                echo "<a href='view-pag.php?$i'>" . $i . "</a> | ";
            }

        }
        echo "</p>";

    }
    else
    {
        echo "No result to display.";
    }

}
else
{
    echo "Error: " . $mysqli->error;
}


?>

What does PermGen actually stand for?

Not really related match to the original question, but may be someone will find it useful. PermGen is indeed an area in memory where Java used to keep its classes. So, many of us have came across OOM in PermGen, if there were, for example a lot of classes.

Since Java 8, PermGen area has been replaced by MetaSpace area, which is more efficient and is unlimited by default (or more precisely - limited by amount of native memory, depending on 32 or 64 bit jvm and OS virtual memory availability) . However it is possible to tune it in some ways, by for example specifying a max limit for the area. You can find more useful information in this blog post.

How can I convert a string with dot and comma into a float in Python

What about this?

 my_string = "123,456.908"
 commas_removed = my_string.replace(',', '') # remove comma separation
 my_float = float(commas_removed) # turn from string to float.

In short:

my_float = float(my_string.replace(',', ''))

SQL Inner join more than two tables

select * from Employee inner join [Order] 
On Employee.Employee_id=[Order].Employee_id
inner join Book 
On Book.Book_id=[Order].Book_id
inner join Book_Author
On Book_Author.Book_id=Book.Book_id
inner join Author
On Book_Author.Author_id=Author.Author_id;

git-diff to ignore ^M

Why do you get these ^M in your git diff?

In my case I was working on a project which was developed in Windows and I used OS X. When I changed some code, I saw ^M at the end of the lines I added in git diff. I think the ^M were showing up because they were different line endings than the rest of the file. Because the rest of the file was developed in Windows it used CR line endings, and in OS X it uses LF line endings.

Apparently, the Windows developer didn't use the option "Checkout Windows-style, commit Unix-style line endings" during the installation of Git.

So what should we do about this?

You can have the Windows users reinstall git and use the "Checkout Windows-style, commit Unix-style line endings" option. This is what I would prefer, because I see Windows as an exception in its line ending characters and Windows fixes its own issue this way.

If you go for this option, you should however fix the current files (because they're still using the CR line endings). I did this by following these steps:

  1. Remove all files from the repository, but not from your filesystem.

    git rm --cached -r .
    
  2. Add a .gitattributes file that enforces certain files to use a LF as line endings. Put this in the file:

    *.ext text eol=crlf
    

    Replace .ext with the file extensions you want to match.

  3. Add all the files again.

    git add .
    

    This will show messages like this:

    warning: CRLF will be replaced by LF in <filename>.
    The file will have its original line endings in your working directory.
    
  4. You could remove the .gitattributes file unless you have stubborn Windows users that don't want to use the "Checkout Windows-style, commit Unix-style line endings" option.

  5. Commit and push it all.

  6. Remove and checkout the applicable files on all the systems where they're used. On the Windows systems, make sure they now use the "Checkout Windows-style, commit Unix-style line endings" option. You should also do this on the system where you executed these tasks because when you added the files git said:

    The file will have its original line endings in your working directory.
    

    You can do something like this to remove the files:

    git ls | grep ".ext$" | xargs rm -f
    

    And then this to get them back with the correct line endings:

    git ls | grep ".ext$" | xargs git checkout
    

    Of course replacing .ext with the extension you want.

Now your project only uses LF characters for the line endings, and the nasty CR characters won't ever come back :).

The other option is to enforce windows style line endings. You can also use the .gitattributes file for this.

More info: https://help.github.com/articles/dealing-with-line-endings/#platform-all

How do I drop a foreign key constraint only if it exists in sql server?

In SQL Server 2016 you can use DROP IF EXISTS:

CREATE TABLE t(id int primary key, 
               parentid int
                    constraint tpartnt foreign key references t(id))
GO
ALTER TABLE t
DROP CONSTRAINT IF EXISTS tpartnt
GO
DROP TABLE IF EXISTS t

See http://blogs.msdn.com/b/sqlserverstorageengine/archive/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016.aspx

Remove a modified file from pull request

A pull request is just that: a request to merge one branch into another.

Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".

The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.

In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p should sort you out.

Ruby Arrays: select(), collect(), and map()

It looks like details is an array of hashes. So item inside of your block will be the whole hash. Therefore, to check the :qty key, you'd do something like the following:

details.select{ |item| item[:qty] != "" }

That will give you all items where the :qty key isn't an empty string.

official select documentation

Seconds CountDown Timer

Hey please add code in your project,it is easy and i think will solve your problem.

    int count = 10;

    private void timer1_Tick(object sender, EventArgs e)
    {
        count--;
        if (count != 0 && count > 0)
        {
            label1.Text = count / 60 + ":" + ((count % 60) >= 10 ? (count % 60).ToString() : "0" + (count % 60));
        }
        else
        {
            label1.Text = "game over";

        }

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer1 = new System.Windows.Forms.Timer();
        timer1.Interval = 1;

        timer1.Tick += new EventHandler(timer1_Tick);

    }

How to show uncommitted changes in Git and some Git diffs in detail

How to show uncommitted changes in Git

The command you are looking for is git diff.

git diff - Show changes between commits, commit and working tree, etc


Here are some of the options it expose which you can use

git diff (no parameters)
Print out differences between your working directory and the index.

git diff --cached:
Print out differences between the index and HEAD (current commit).

git diff HEAD:
Print out differences between your working directory and the HEAD.

git diff --name-only
Show only names of changed files.

git diff --name-status
Show only names and status of changed files.

git diff --color-words
Word by word diff instead of line by line.

Here is a sample of the output for git diff --color-words:

enter image description here


enter image description here

Android studio - Failed to find target android-18

I've had a similar problem occurr when I had both Eclipse, Android Studio and the standalone Android SDK installed (the problem lied where the AVD Manager couldn't find target images). I had been using Eclipse for Android development but have moved over to Android Studio, and quickly found that Android Studio couldn't find my previously created AVDs.

The problem could potentially lie in that Android Studio is looking at it's own Android SDK (found in C:\Users\username\AppData\Local\Android\android-studio\sdk) and not a previously installed standalone SDK, which I had installed at C:\adt\sdk.

Renaming Android Studio's SDK folder, in C:\Users... (only rename it, just in case things break) then creating a symbolic link between the Android Studio SDK location and a standalone Android SDK fixes this issue.

I also used the Link Shell Extension (http://schinagl.priv.at/nt/hardlinkshellext/linkshellextension.html) just to take the tedium out of creating symbolic links.

ImportError: No module named apiclient.discovery

Make sure you only have google-api-python-client installed. If you have apiclient installed, it will cause a collision. So, run the following:

sudo pip uninstall apiclient

What is the single most influential book every programmer should read?

Separately, I'd mention The Third Manifesto by Hugh Darwen and CJ Date. If you're interested in understanding data (which seems uncommon among programmers) this book is a must-read. It will also make you sad when you realize just how badly broken SQL is, but it'll also help you cope with that brokenness. Knowing how a tool is broken lets you design with those deficits in mind.

Hive: Filtering Data between Specified Dates when Date is a String

The great thing about yyyy-mm-dd date format is that there is no need to extract month() and year(), you can do comparisons directly on strings:

SELECT *
  FROM your_table
  WHERE your_date_column >= '2010-09-01' AND your_date_column <= '2013-08-31';

CKEditor instance already exists

you don't need to destroy the object CKeditor, you need remove() :

Change this :

CKEDITOR.instances['textarea_name'].destroy();

for that :

CKEDITOR.remove(CKEDITOR.instances['textarea_name']);

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Most efficient way to check for DBNull and then assign to a variable?

This is how I handle reading from DataRows

///<summary>
/// Handles operations for Enumerations
///</summary>
public static class DataRowUserExtensions
{
    /// <summary>
    /// Gets the specified data row.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataRow">The data row.</param>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public static T Get<T>(this DataRow dataRow, string key)
    {
        return (T) ChangeTypeTo<T>(dataRow[key]);
    }

    private static object ChangeTypeTo<T>(this object value)
    {
        Type underlyingType = typeof (T);
        if (underlyingType == null)
            throw new ArgumentNullException("value");

        if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
        {
            if (value == null)
                return null;
            var converter = new NullableConverter(underlyingType);
            underlyingType = converter.UnderlyingType;
        }

        // Try changing to Guid  
        if (underlyingType == typeof (Guid))
        {
            try
            {
                return new Guid(value.ToString());
            }
            catch

            {
                return null;
            }
        }
        return Convert.ChangeType(value, underlyingType);
    }
}

Usage example:

if (dbRow.Get<int>("Type") == 1)
{
    newNode = new TreeViewNode
                  {
                      ToolTip = dbRow.Get<string>("Name"),
                      Text = (dbRow.Get<string>("Name").Length > 25 ? dbRow.Get<string>("Name").Substring(0, 25) + "..." : dbRow.Get<string>("Name")),
                      ImageUrl = "file.gif",
                      ID = dbRow.Get<string>("ReportPath"),
                      Value = dbRow.Get<string>("ReportDescription").Replace("'", "\'"),
                      NavigateUrl = ("?ReportType=" + dbRow.Get<string>("ReportPath"))
                  };
}

Props to Monsters Got My .Net for ChageTypeTo code.

How to use icons and symbols from "Font Awesome" on Native Android Application

As all answers are great but I didn't want to use a library and each solution with just one line java code made my Activities and Fragments very messy. So I over wrote the TextView class as follows:

public class FontAwesomeTextView extends TextView {
private static final String TAG = "TextViewFontAwesome";
public FontAwesomeTextView(Context context) {
    super(context);
    init();
}

public FontAwesomeTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init();
}

private void setCustomFont(Context ctx, AttributeSet attrs) {
    TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
    String customFont = a.getString(R.styleable.TextViewPlus_customFont);
    setCustomFont(ctx, customFont);
    a.recycle();
}

private void init() {
    if (!isInEditMode()) {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fontawesome-webfont.ttf");
        setTypeface(tf);
    }
}

public boolean setCustomFont(Context ctx, String asset) {
    Typeface typeface = null;
    try {
        typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
    } catch (Exception e) {
        Log.e(TAG, "Unable to load typeface: "+e.getMessage());
        return false;
    }

    setTypeface(typeface);
    return true;
}
}

what you should do is copy the font ttf file into assets folder .And use this cheat sheet for finding each icons string.

hope this helps.

How to center a <p> element inside a <div> container?

You dont need absolute positioning Use

p {
 text-align: center;
line-height: 100px;

}

And adjust at will...

If text exceeds width and goes more than one line

In that case the adjust you can do is to include the display property in your rules as follows;

(I added a background for a better view of the example)

div
{
  width:300px;
  height:100px;  
  display: table; 
  background:#ccddcc;  
}


p {
  text-align:center; 
  vertical-align: middle;
  display: table-cell;   
}

Play with it in this JBin

enter image description here

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

I was having the same problem, with a value like 2016-08-8, then I solved adding a zero to have two digits days, and it works. Tested in chrome, firefox, and Edge

today:function(){
   var today = new Date();
   var d = (today.getDate() < 10 ? '0' : '' )+ today.getDate();
   var m = ((today.getMonth() + 1) < 10 ? '0' :'') + (today.getMonth() + 1);
   var y = today.getFullYear();
   var x = String(y+"-"+m+"-"+d); 
   return x;
}

how to declare global variable in SQL Server..?

It is not possible to declare global variables in SQL Server. Sql server has a concept of global variables, but they are system defined and can not be extended.

obviously you can do all kinds of tricks with the SQL you are sending - SqlCOmmand has such a variable replacement mechanism for example - BEFORE you send it to SqlServer, but that is about it.

Bootstrap 3.0 Popovers and tooltips

Working with BOOTSTRAP 3 : Short and Simple

Check - JS Fiddle

HTML

<div id="myDiv">
<button class="btn btn-large btn-danger" data-toggle="tooltip" data-placement="top" title="" data-original-title="Tooltip on top">Tooltip on top</button>    
</div>

Javascript

$(function () { 
    $("[data-toggle='tooltip']").tooltip(); 
});

How to load an ImageView by URL in Android?

imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside

Call apply-like function on each row of dataframe with multiple arguments from each row

Here is an alternate approach. It is more intuitive.

One key aspect I feel some of the answers did not take into account, which I point out for posterity, is apply() lets you do row calculations easily, but only for matrix (all numeric) data

operations on columns are possible still for dataframes:

as.data.frame(lapply(df, myFunctionForColumn()))

To operate on rows, we make the transpose first.

tdf<-as.data.frame(t(df))
as.data.frame(lapply(tdf, myFunctionForRow()))

The downside is that I believe R will make a copy of your data table. Which could be a memory issue. (This is truly sad, because it is programmatically simple for tdf to just be an iterator to the original df, thus saving memory, but R does not allow pointer or iterator referencing.)

Also, a related question, is how to operate on each individual cell in a dataframe.

newdf <- as.data.frame(lapply(df, function(x) {sapply(x, myFunctionForEachCell()}))

Nginx not picking up site in sites-enabled?

I had the same problem. It was because I had accidentally used a relative path with the symbolic link.

Are you sure you used full paths, e.g.:

ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf

How to change checkbox's border style in CSS?

I suggest using "outline" instead of "border". For example: outline: 1px solid #1e5180.

How to draw checkbox or tick mark in GitHub Markdown table?

Now emojis are supported! :white_check_mark: / :heavy_check_mark: gives a good impression and is widely supported:

Function | MySQL / MariaDB | PostgreSQL | SQLite
:------------ | :-------------| :-------------| :-------------
substr | :heavy_check_mark: |  :white_check_mark: | :heavy_check_mark:

renders to (here on older chromium 65.0.3x) :

enter image description here

Short description of the scoping rules?

Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply.)

LEGB Rule

  • Local — Names assigned in any way within a function (def or lambda), and not declared global in that function

  • Enclosing-function — Names assigned in the local scope of any and all statically enclosing functions (def or lambda), from inner to outer

  • Global (module) — Names assigned at the top-level of a module file, or by executing a global statement in a def within the file

  • Built-in (Python) — Names preassigned in the built-in names module: open, range, SyntaxError, etc

So, in the case of

code1
class Foo:
    code2
    def spam():
        code3
        for code4:
            code5
            x()

The for loop does not have its own namespace. In LEGB order, the scopes would be

  • L: Local in def spam (in code3, code4, and code5)
  • E: Any enclosing functions (if the whole example were in another def)
  • G: Were there any x declared globally in the module (in code1)?
  • B: Any builtin x in Python.

x will never be found in code2 (even in cases where you might expect it would, see Antti's answer or here).

Deleting queues in RabbitMQ

You assert that a queue exists (and create it if it does not) by using queue.declare. If you originally set auto-delete to false, calling queue.declare again with autodelete true will result in a soft error and the broker will close the channel.

You need to use queue.delete now in order to delete it.

See the API documentation for details:

If you use another client, you'll need to find the equivalent method. Since it's part of the protocol, it should be there, and it's probably part of Channel or the equivalent.

You might also want to have a look at the rest of the documentation, in particular the Geting Started section which covers a lot of common use cases.

Finally, if you have a question and can't find the answer elsewhere, you should try posting on the RabbitMQ Discuss mailing list. The developers do their best to answer all questions asked there.

How to keep footer at bottom of screen

You could use position:fixed; to bottom.

eg:

#footer{
 position:fixed;
 bottom:0;
 left:0;
}

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Command to find information about CPUs on a UNIX machine

The nproc command shows the number of processing units available:
$ nproc

Sample outputs: 4

lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
$ lscpu

Sample outputs:

Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 1
Core(s) per socket: 4
CPU socket(s): 2
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 15
Stepping: 7
CPU MHz: 1866.669
BogoMIPS: 3732.83
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 4096K
NUMA node0 CPU(s): 0-7

Using Thymeleaf when the value is null

You can use 'th:if' together with 'th:text'

<span th:if="${someObject.someProperty != null}" th:text="${someObject.someProperty}">someValue</span>

How does strtok() split the string into tokens in C?

strtok() divides the string into tokens. i.e. starting from any one of the delimiter to next one would be your one token. In your case, the starting token will be from "-" and end with next space " ". Then next token will start from " " and end with ",". Here you get "This" as output. Similarly the rest of the string gets split into tokens from space to space and finally ending the last token on "."

How to check if a string contains only digits in Java

Try

String regex = "[0-9]+";

or

String regex = "\\d+";

As per Java regular expressions, the + means "one or more times" and \d means "a digit".

Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d in a java String gives you the actual result: \d

References:


Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.

Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:

String regex = "\\d+";

// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));

// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));

Question 1:

Isn't it necessary to add ^ and $ to the regex, so it won't match "aa123bb" ?

No. In java, the matches method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$ (even though it is also correct). Please see the last negative test case.

Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find method instead, described in detail here:

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

Question 2:

Won't this regex also match the empty string, "" ?*

No. A regex \\d* would match the empty string, but \\d+ does not. The star * means zero or more, whereas the plus + means one or more. Please see the first negative test case.

Question 3

Isn't it faster to compile a regex Pattern?

Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches, and so if performance implications are important then a Pattern can be compiled and used like this:

Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());

What is the difference between compare() and compareTo()?

Use Comparable interface for sorting on the basis of more than one value like age,name,dept_name... For one value use Comparator interface

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

Most efficient way to increment a Map value in Java

The simple and easy way in java 8 is the following:

final ConcurrentMap<String, AtomicLong> map = new ConcurrentHashMap<String, AtomicLong>();
    map.computeIfAbsent("foo", key -> new AtomicLong(0)).incrementAndGet();

Android, getting resource ID from string?

A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.

int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);

Different ways of clearing lists

Clearing a list in place will affect all other references of the same list.

For example, this method doesn't affect other references:

>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]

But this one does:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]      # equivalent to   del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True

You could also do:

>>> a[:] = []

Add a common Legend for combined ggplots

I suggest using cowplot. From their R vignette:

# load cowplot
library(cowplot)

# down-sampled diamonds data set
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]

# Make three plots.
# We set left and right margins to 0 to remove unnecessary spacing in the
# final plot arrangement.
p1 <- qplot(carat, price, data=dsamp, colour=clarity) +
   theme(plot.margin = unit(c(6,0,6,0), "pt"))
p2 <- qplot(depth, price, data=dsamp, colour=clarity) +
   theme(plot.margin = unit(c(6,0,6,0), "pt")) + ylab("")
p3 <- qplot(color, price, data=dsamp, colour=clarity) +
   theme(plot.margin = unit(c(6,0,6,0), "pt")) + ylab("")

# arrange the three plots in a single row
prow <- plot_grid( p1 + theme(legend.position="none"),
           p2 + theme(legend.position="none"),
           p3 + theme(legend.position="none"),
           align = 'vh',
           labels = c("A", "B", "C"),
           hjust = -1,
           nrow = 1
           )

# extract the legend from one of the plots
# (clearly the whole thing only makes sense if all plots
# have the same legend, so we can arbitrarily pick one.)
legend_b <- get_legend(p1 + theme(legend.position="bottom"))

# add the legend underneath the row we made earlier. Give it 10% of the height
# of one plot (via rel_heights).
p <- plot_grid( prow, legend_b, ncol = 1, rel_heights = c(1, .2))
p

combined plots with legend at bottom

Continue For loop

For i=1 To 10
    Do 
        'Do everything in here and

        If I_Dont_Want_Finish_This_Loop Then
            Exit Do
        End If 

        'Of course, if I do want to finish it,
        'I put more stuff here, and then...

    Loop While False 'quit after one loop
Next i

How to get the part of a file after the first line that matches a regular expression?

Alternatives to the excellent sed answer by jfgagne, and which don't include the matching line :

Using a batch to copy from network drive to C: or D: drive

Just do the following change

echo off
cls

echo Would you like to do a backup?

pause

copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER

pause

Determine which element the mouse pointer is on top of in JavaScript

The target of the mousemove DOM event is the top-most DOM element under the cursor when the mouse moves:

(function(){
    //Don't fire multiple times in a row for the same element
    var prevTarget=null;
    document.addEventListener('mousemove', function(e) {
        //This will be the top-most DOM element under cursor
        var target=e.target;
        if(target!==prevTarget){
            console.log(target);
            prevTarget=target;
        }
    });
})();

This is similar to @Philip Walton's solution, but doesn't require jQuery or a setInterval.

Disable all table constraints in Oracle

It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL*Plus or put this thing into a package or procedure. The join to USER_TABLES is there to avoid view constraints.

It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc). You should think about putting constraint_type in the WHERE clause.

BEGIN
  FOR c IN
  (SELECT c.owner, c.table_name, c.constraint_name
   FROM user_constraints c, user_tables t
   WHERE c.table_name = t.table_name
   AND c.status = 'ENABLED'
   AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P')
   ORDER BY c.constraint_type DESC)
  LOOP
    dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name);
  END LOOP;
END;
/

Enabling the constraints again is a bit tricker - you need to enable primary key constraints before you can reference them in a foreign key constraint. This can be done using an ORDER BY on constraint_type. 'P' = primary key, 'R' = foreign key.

BEGIN
  FOR c IN
  (SELECT c.owner, c.table_name, c.constraint_name
   FROM user_constraints c, user_tables t
   WHERE c.table_name = t.table_name
   AND c.status = 'DISABLED'
   ORDER BY c.constraint_type)
  LOOP
    dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" enable constraint ' || c.constraint_name);
  END LOOP;
END;
/

How to define a Sql Server connection string to use in VB.NET?

Use the following Imports

Imports System.Data.SqlClient
Imports System.Data.Sql

Public SQLConn As New SqlConnection With {.ConnectionString = "Server=Desktop1[enter image description here][1];Database=Infostudio; Trusted_Connection=true;"}

Full string: enter image description here

C# Threading - How to start and stop a thread

This is how I do it...

public class ThreadA {
    public ThreadA(object[] args) {
        ...
    }
    public void Run() {
        while (true) {
            Thread.sleep(1000); // wait 1 second for something to happen.
            doStuff();
            if(conditionToExitReceived) // what im waiting for...
                break;
        }
        //perform cleanup if there is any...
    }
}

Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)

private void FireThread(){
    Thread thread = new Thread(new ThreadStart(this.startThread));
    thread.start();
}
private void (startThread){
    new ThreadA(args).Run();
}

The thread is created by calling "FireThread()"

The newly created thread will run until its condition to stop is met, then it dies...

You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...

Best to read through : This MSDN Article

Is there a standardized method to swap two variables in Python?

I know three ways to swap variables, but a, b = b, a is the simplest. There is

XOR (for integers)

x = x ^ y
y = y ^ x
x = x ^ y

Or concisely,

x ^= y
y ^= x
x ^= y

Temporary variable

w = x
x = y
y = w
del w

Tuple swap

x, y = y, x

Python: Find a substring in a string and returning the index of the substring

Not directly answering the question but I got a similar question recently where I was asked to count the number of times a sub-string is repeated in a given string. Here is the function I wrote:

def count_substring(string, sub_string):
    cnt = 0
    len_ss = len(sub_string)
    for i in range(len(string) - len_ss + 1):
        if string[i:i+len_ss] == sub_string:
            cnt += 1
    return cnt

The find() function probably returns the index of the fist occurrence only. Storing the index in place of just counting, can give us the distinct set of indices the sub-string gets repeated within the string.

Disclaimer: I am 'extremly' new to Python programming.

Running Google Maps v2 on the Android emulator

I am able to have my emulator to run my app with Google Map V.2 (with Google Play Service V.4). I followed steps that others suggested with some failures, however I learned from it and somehow make it work. This is how:

  1. First of all: You must have coded your map app. correctly with all the appropriate permissions setup in your metafile XML, and have Google Play Services APK part of your app. To verify this is true, you must run your app on REAL device and know it works with its map there. Then you can proceed to process your emulator as shown below.

  2. Create a new emulator, or use your existing emulator with specs:

    • Target Name = Android 4.1.2
    • API Level = 16
    • CPU = Any. However, I found ARM is much faster/responsive than x86
    • Have enough RAM memory and space MB
  3. Run you emulator (your target emulator must be running!)

  4. Download the following APKs (available via dropbox per 4/2/2013) to your local directory (scan for virus!):

  5. Install these two APK into your running (target) emulator with ADB command:

    DOS/Console Prompt> adb -e install [path-to-APK-file]

    NOTE: Possibly, you have had these APKs installed in your emulator during this trial-error, and need to re-install for some reason. You must uninstall them first by: adb -e uninstall (com.google.android.gms or com.android.vending)

  6. Here, it is where things could get tricky. You think you were done, but when you open your app with Map again, but all you get is an error saying something in the form of: "Google Play services out of date. Requires 2012100 but found 2010110", and may see a button to "Update" Google Play. If this is the case, do NOT attempt to click the update button since it won't do anything. I got this error too, and I resolved it by both of these additional steps:

    • Clean-rebuild-reinstall my app into the emulator
    • Shutdown my emulator and re-start it.
  7. That's it, it works now nicely.

Xcode iOS 8 Keyboard types not supported

Go to iOS Simulator-> Hardware-> Keyboard -> Uncheck the Connect Hardware Keyboard Option. This will fix the issue.

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

Foreign Key to non-primary key

As others have pointed out, ideally, the foreign key would be created as a reference to a primary key (usually an IDENTITY column). However, we don't live in an ideal world, and sometimes even a "small" change to a schema can have significant ripple effects to the application logic.

Consider the case of a Customer table with a SSN column (and a dumb primary key), and a Claim table that also contains a SSN column (populated by business logic from the Customer data, but no FK exists). The design is flawed, but has been in use for several years, and three different applications have been built on the schema. It should be obvious that ripping out Claim.SSN and putting in a real PK-FK relationship would be ideal, but would also be a significant overhaul. On the other hand, putting a UNIQUE constraint on Customer.SSN, and adding a FK on Claim.SSN, could provide referential integrity, with little or no impact on the applications.

Don't get me wrong, I'm all for normalization, but sometimes pragmatism wins over idealism. If a mediocre design can be helped with a band-aid, surgery might be avoided.

Why docker container exits immediately

I would like to extend or dare I say, improve answer mentioned by camposer

When you run

docker run -dit ubuntu

you are basically running the container in background in interactive mode.

When you attach and exit the container by CTRL+D (most common way to do it), you stop the container because you just killed the main process which you started your container with the above command.

Making advantage of an already running container, I would just fork another process of bash and get a pseudo TTY by running:

docker exec -it <container ID> /bin/bash

How to use DISTINCT and ORDER BY in same SELECT statement?

2) Order by CreationDate is very important

The original results indicated that "test3" had multiple results...

It's very easy to start using MAX all the time to remove duplicates in Group By's... and forget or ignore what the underlying question is...

The OP presumably realised that using MAX was giving him the last "created" and using MIN would give the first "created"...

Extract subset of key-value pairs from Python dictionary object?

Using map (halfdanrump's answer) is best for me, though haven't timed it...

But if you go for a dictionary, and if you have a big_dict:

  1. Make absolutely certain you loop through the the req. This is crucial, and affects the running time of the algorithm (big O, theta, you name it)
  2. Write it generic enough to avoid errors if keys are not there.

so e.g.:

big_dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w']

{k:big_dict.get(k,None) for k in req )
# or 
{k:big_dict[k] for k in req if k in big_dict)

Note that in the converse case, that the req is big, but my_dict is small, you should loop through my_dict instead.

In general, we are doing an intersection and the complexity of the problem is O(min(len(dict)),min(len(req))). Python's own implementation of intersection considers the size of the two sets, so it seems optimal. Also, being in c and part of the core library, is probably faster than most not optimized python statements. Therefore, a solution that I would consider is:

dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w',...................]

{k:dic[k] for k in set(req).intersection(dict.keys())}

It moves the critical operation inside python's c code and will work for all cases.

Confused about stdin, stdout and stderr?

Here is a lengthy article on stdin, stdout and stderr:

To summarize:

Streams Are Handled Like Files

Streams in Linux—like almost everything else—are treated as though they were files. You can read text from a file, and you can write text into a file. Both of these actions involve a stream of data. So the concept of handling a stream of data as a file isn’t that much of a stretch.

Each file associated with a process is allocated a unique number to identify it. This is known as the file descriptor. Whenever an action is required to be performed on a file, the file descriptor is used to identify the file.

These values are always used for stdin, stdout, and stderr:

0: stdin
1: stdout
2: stderr

Ironically I found this question on stack overflow and the article above because I was searching for information on abnormal / non-standard streams. So my search continues.

How to add facebook share button on my website?

Share Dialog without requiring Facebook login

You can Trigger a Share Dialog using the FB.ui function with the share method parameter to share a link. This dialog is available in the Facebook SDKs for JavaScript, iOS, and Android by performing a full redirect to a URL.

You can trigger this call:

FB.ui({
  method: 'share',
  href: 'https://developers.facebook.com/docs/', // Link to share
}, function(response){});

You can also include open graph meta tags on the page at this URL to customise the story that is shared back to Facebook.

Note that response.error_message will appear only if someone using your app has authenticated your app with Facebook Login.

Also you can directly share link with call by having Javascript Facebook SDK.

https://www.facebook.com/dialog/share&app_id=145634995501895&display=popup&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F&redirect_uri=https%3A%2F%2Fdevelopers.facebook.com%2Ftools%2Fexplorer

https://www.facebook.com/dialog/share&app_id={APP_ID}&display=popup&href={LINK_TO_SHARE}&redirect_uri={REDIRECT_AFTER_SHARE}
  • app_id => Your app's unique identifier. (Required.)

  • redirect_uri => The URL to redirect to after a person clicks a button on the dialog. Required when using URL redirection.

  • display => Determines how the dialog is rendered.

If you are using the URL redirect dialog implementation, then this will be a full page display, shown within Facebook.com. This display type is called page. If you are using one of our iOS or Android SDKs to invoke the dialog, this is automatically specified and chooses an appropriate display type for the device. If you are using the Facebook SDK for JavaScript, this will default to a modal iframe type for people logged into your app or async when using within a game on Facebook.com, and a popup window for everyone else. You can also force the popup or page types when using the Facebook SDK for JavaScript, if necessary. Mobile web apps will always default to the touch display type. share Parameters

  • href => The link attached to this post. Required when using method share. Include open graph meta tags in the page at this URL to customize the story that is shared.

Get element of JS object with an index

Object.keys(city)[0];   //return the key name at index 0
Object.values(city)[0]  //return the key values at index 0

Getting the current date in visual Basic 2008

You may just want:

Dim regDate As Date = Date.Today()

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

What is considered a good response time for a dynamic, personalized web application?

There's a great deal of research on this. Here's a quick summary.

Response Times: The 3 Important Limits

by Jakob Nielsen on January 1, 1993

Summary: There are 3 main time limits (which are determined by human perceptual abilities) to keep in mind when optimizing web and application performance.

Excerpt from Chapter 5 in my book Usability Engineering, from 1993:

The basic advice regarding response times has been about the same for thirty years [Miller 1968; Card et al. 1991]:

  • 0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.
  • 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.
  • 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

What's the best three-way merge tool?

Meld Diff Viewer

I have had only good experiences working with Meld. I use it when I have to do messy code merges between branches. It is simple to use and has a clean interface.

  • Open Source
  • Linux, Windows and MacOS Supported
  • Multiple File Diff
  • Three-way Compare Support

In Ubuntu, install is as simple as: sudo apt-get install meld

enter image description here

How can I define a composite primary key in SQL?

Just for clarification: a table can have at most one primary key. A primary key consists of one or more columns (from that table). If a primary key consists of two or more columns it is called a composite primary key. It is defined as follows:

CREATE TABLE voting (
  QuestionID NUMERIC,
  MemberID NUMERIC,
  PRIMARY KEY (QuestionID, MemberID)
);

The pair (QuestionID,MemberID) must then be unique for the table and neither value can be NULL. If you do a query like this:

SELECT * FROM voting WHERE QuestionID = 7

it will use the primary key's index. If however you do this:

SELECT * FROM voting WHERE MemberID = 7

it won't because to use a composite index requires using all the keys from the "left". If an index is on fields (A,B,C) and your criteria is on B and C then that index is of no use to you for that query. So choose from (QuestionID,MemberID) and (MemberID,QuestionID) whichever is most appropriate for how you will use the table.

If necessary, add an index on the other:

CREATE UNIQUE INDEX idx1 ON voting (MemberID, QuestionID);

How to access your website through LAN in ASP.NET

You may also need to enable the World Wide Web Service inbound firewall rule.

On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules

Find World Wide Web Services (HTTP Traffic-In) in the list and select to enable the rule. Change is pretty much immediate.

Selenium WebDriver How to Resolve Stale Element Reference Exception?

Use webdriverwait with ExpectedCondition in try catch block with for loop EX: for python

for i in range(4):
    try:
        element = WebDriverWait(driver, 120).until( \
                EC.presence_of_element_located((By.XPATH, 'xpath')))
        element.click()    
        break
    except StaleElementReferenceException:
        print "exception "

How to configure CORS in a Spring Boot + Spring Security application?

Found an easy solution for Spring-Boot, Spring-Security and Java-based config:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().configurationSource(new CorsConfigurationSource() {
            @Override
            public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
                return new CorsConfiguration().applyPermitDefaultValues();
            }
        });
    }
}

How to add a local repo and treat it as a remote repo

You have your arguments to the remote add command reversed:

git remote add <NAME> <PATH>

So:

git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git

See git remote --help for more information.

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

In this particular case (assuming that the Class#forName() didn't throw an exception; your code is namely continuing with running instead of throwing the exception), this SQLException means that Driver#acceptsURL() has returned false for any of the loaded drivers.

And indeed, your JDBC URL is wrong:

String url = "'jdbc:mysql://localhost:3306/mysql";

Remove the singlequote:

String url = "jdbc:mysql://localhost:3306/mysql";

See also:

Send POST data on redirect with JavaScript/jQuery?

This is quite handy to use:

var myRedirect = function(redirectUrl, arg, value) {
  var form = $('<form action="' + redirectUrl + '" method="post">' +
  '<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
  $('body').append(form);
  $(form).submit();
};

then use it like:

myRedirect("/yourRedirectingUrl", "arg", "argValue");

How do you get AngularJS to bind to the title attribute of an A tag?

Sometimes it is not desirable to use interpolation on title attribute or on any other attributes as for that matter, because they get parsed before the interpolation takes place. So:

<!-- dont do this -->
<!-- <a title="{{product.shortDesc}}" ...> -->

If an attribute with a binding is prefixed with the ngAttr prefix (denormalized as ng-attr-) then during the binding will be applied to the corresponding unprefixed attribute. This allows you to bind to attributes that would otherwise be eagerly processed by browsers. The attribute will be set only when the binding is done. The prefix is then removed:

<!-- do this -->
<a ng-attr-title="{{product.shortDesc}}" ...>

(Ensure that you are not using a very earlier version of Angular). Here's a demo fiddle using v1.2.2:

Fiddle

UITableView, Separator color where to set?

Try + (instancetype)appearance of UITableView:

Objective-C:

[[UITableView appearance] setSeparatorColor:[UIColor blackColor]]; // set your desired colour in place of "[UIColor blackColor]"

Swift 3.0:

UITableView.appearance().separatorColor = UIColor.black // set your desired colour in place of "UIColor.black"

Note: Change will reflect to all tables used in application.

Range of values in C Int and Long 32 - 64 bits

It is better to include stdlib.h. Since without stdlibg it takes long as long

How to get the host name of the current machine as defined in the Ansible hosts file?

This is an alternative:

- name: Install this only for local dev machine
  pip: name=pyramid
  delegate_to: localhost

Time complexity of accessing a Python dict

As others have pointed out, accessing dicts in Python is fast. They are probably the best-oiled data structure in the language, given their central role. The problem lies elsewhere.

How many tuples are you memoizing? Have you considered the memory footprint? Perhaps you are spending all your time in the memory allocator or paging memory.

javascript cell number validation

This function check the special chars on key press and eliminates the value if it is not a number

function mobilevalid(id) {

    var feild = document.getElementById(id);

    if (isNaN(feild.value) == false) {
        if (feild.value.length == 1) {
            if (feild.value < 7) {
                feild.value = "";
            }
        } else if (feild.value.length > 10) {
            feild.value = feild.value.substr(0, feild.value.length - 1);
        }
        if (feild.value.charAt(0) < 7) {
            feild.value = "";
        }
    } else {
        feild.value = "";
    }

}

How do I find the absolute position of an element using jQuery?

.offset() will return the offset position of an element as a simple object, eg:

var position = $(element).offset(); // position = { left: 42, top: 567 }

You can use this return value to position other elements at the same spot:

$(anotherElement).css(position)

In Python, how do you convert a `datetime` object to seconds?

For the special date of January 1, 1970 there are multiple options.

For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a timedelta object, which as of Python 2.7 has a total_seconds() function.

>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0

The starting date is usually specified in UTC, so for proper results the datetime you feed into this formula should be in UTC as well. If your datetime isn't in UTC already, you'll need to convert it before you use it, or attach a tzinfo class that has the proper offset.

As noted in the comments, if you have a tzinfo attached to your datetime then you'll need one on the starting date as well or the subtraction will fail; for the example above I would add tzinfo=pytz.utc if using Python 2 or tzinfo=timezone.utc if using Python 3.

Python Function to test ping

Here is a simplified function that returns a boolean and has no output pushed to stdout:

import subprocess, platform
def pingOk(sHost):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)

    except Exception, e:
        return False

    return True

How do I check if an element is hidden in jQuery?

This may work:

expect($("#message_div").css("display")).toBe("none");

Command not found when using sudo

Permission denied

In order to run a script the file must have an executable permission bit set.

In order to fully understand Linux file permissions you can study the documentation for the chmod command. chmod, an abbreviation of change mode, is the command that is used to change the permission settings of a file.

To read the chmod documentation for your local system , run man chmod or info chmod from the command line. Once read and understood you should be able to understand the output of running ...

ls -l foo.sh

... which will list the READ, WRITE and EXECUTE permissions for the file owner, the group owner and everyone else who is not the file owner or a member of the group to which the file belongs (that last permission group is sometimes referred to as "world" or "other")

Here's a summary of how to troubleshoot the Permission Denied error in your case.

$ ls -l foo.sh                    # Check file permissions of foo
-rw-r--r-- 1 rkielty users 0 2012-10-21 14:47 foo.sh 
    ^^^ 
 ^^^ | ^^^   ^^^^^^^ ^^^^^
  |  |  |       |       | 
Owner| World    |       |
     |          |    Name of
   Group        |     Group
             Name of 
              Owner 

Owner has read and write access rw but the - indicates that the executable permission is missing

The chmod command fixes that. (Group and other only have read permission set on the file, they cannot write to it or execute it)

$ chmod +x foo.sh               # The owner can set the executable permission on foo.sh
$ ls -l foo.sh                  # Now we see an x after the rw 
-rwxr-xr-x 1 rkielty users 0 2012-10-21 14:47 foo.sh
   ^  ^  ^

foo.sh is now executable as far as Linux is concerned.

Using sudo results in Command not found

When you run a command using sudo you are effectively running it as the superuser or root.

The reason that the root user is not finding your command is likely that the PATH environment variable for root does not include the directory where foo.sh is located. Hence the command is not found.

The PATH environment variable contains a list of directories which are searched for commands. Each user sets their own PATH variable according to their needs. To see what it is set to run

env | grep ^PATH

Here's some sample output of running the above env command first as an ordinary user and then as the root user using sudo

rkielty@rkielty-laptop:~$ env | grep ^PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

rkielty@rkielty-laptop:~$ sudo env | grep ^PATH
[sudo] password for rkielty: 
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin

Note that, although similar, in this case the directories contained in the PATH the non-privileged user (rkielty) and the super user are not the same.

The directory where foo.sh resides is not present in the PATH variable of the root user, hence the command not found error.

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

SSMS only allows unlimited data for XML data. This is not the default and needs to be set in the options.

enter image description here

One trick which might work in quite limited circumstances is simply naming the column in a special manner as below so it gets treated as XML data.

DECLARE @S varchar(max) = 'A'

SET @S =  REPLICATE(@S,100000) + 'B' 

SELECT @S as [XML_F52E2B61-18A1-11d1-B105-00805F49916B]

In SSMS (at least versions 2012 to current of 18.3) this displays the results as below

enter image description here

Clicking on it opens the full results in the XML viewer. Scrolling to the right shows the last character of B is preserved,

However this does have some significant problems. Adding extra columns to the query breaks the effect and extra rows all become concatenated with the first one. Finally if the string contains characters such as < opening the XML viewer fails with a parsing error.

A more robust way of doing this that avoids issues of SQL Server converting < to &lt; etc or failing due to these characters is below (credit Adam Machanic here).

DECLARE @S varchar(max)

SELECT @S = ''

SELECT @S = @S + '
' + OBJECT_DEFINITION(OBJECT_ID) FROM SYS.PROCEDURES

SELECT @S AS [processing-instruction(x)] FOR XML PATH('')

How to refresh materialized view in oracle

You can refresh a materialized view completely as follows:

EXECUTE  
DBMS_SNAPSHOT.REFRESH('Materialized_VIEW_OWNER_NAME.Materialized_VIEW_NAME','COMPLETE');

Why doesn't Java allow overriding of static methods?

By overriding we can create a polymorphic nature depending on the object type. Static method has no relation with object. So java can not support static method overriding.

What's the difference between using "let" and "var"?

I want to link these keywords to the Execution Context, because the Execution Context is important in all of this. The Execution Context has two phases: a Creation Phase and Execution Phase. In addition, each Execution Context has a Variable Environment and Outer Environment (its Lexical Environment).

During the Creation Phase of an Execution Context, var, let and const will still store its variable in memory with an undefined value in the Variable Environment of the given Execution Context. The difference is in the Execution Phase. If you use reference a variable defined with var before it is assigned a value, it will just be undefined. No exception will be raised.

However, you cannot reference the variable declared with let or const until it is declared. If you try to use it before it is declared, then an exception will be raised during the Execution Phase of the Execution Context. Now the variable will still be in memory, courtesy of the Creation Phase of the Execution Context, but the Engine will not allow you to use it:

function a(){
    b;
    let b;
}
a();
> Uncaught ReferenceError: b is not defined

With a variable defined with var, if the Engine cannot find the variable in the current Execution Context's Variable Environment, then it will go up the scope chain (the Outer Environment) and check the Outer Environment's Variable Environment for the variable. If it cannot find it there, it will continue searching the Scope Chain. This is not the case with let and const.

The second feature of let is it introduces block scope. Blocks are defined by curly braces. Examples include function blocks, if blocks, for blocks, etc. When you declare a variable with let inside of a block, the variable is only available inside of the block. In fact, each time the block is run, such as within a for loop, it will create a new variable in memory.

ES6 also introduces the const keyword for declaring variables. const is also block scoped. The difference between let and const is that const variables need to be declared using an initializer, or it will generate an error.

And, finally, when it comes to the Execution Context, variables defined with var will be attached to the 'this' object. In the global Execution Context, that will be the window object in browsers. This is not the case for let or const.

What does "#pragma comment" mean?

The answers and the documentation provided by MSDN is the best, but I would like to add one typical case that I use a lot which requires the use of #pragma comment to send a command to the linker at link time for example

#pragma comment(linker,"/ENTRY:Entry")

tell the linker to change the entry point form WinMain() to Entry() after that the CRTStartup going to transfer controll to Entry()

How to create a file with a given size in Linux?

You can do it programmatically:

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main() {
    int fd = creat("/tmp/foo.txt", 0644);
    ftruncate(fd, SIZE_IN_BYTES);
    close(fd);
    return 0;
}

This approach is especially useful to subsequently mmap the file into memory.

use the following command to check that the file has the correct size:

# du -B1 --apparent-size /tmp/foo.txt

Be careful:

# du /tmp/foo.txt

will probably print 0 because it is allocated as Sparse file if supported by your filesystem.

see also: man 2 open and man 2 truncate

ASP.Net which user account running Web Service on IIS 7?

Look at the Identity of the Application Pool that's running your application. By default it will be the Network Service account, but you can change this.

At least that's how it works on 2003 server, don't know if some details have changed for 2008 server.

Where does Jenkins store configuration files for the jobs it runs?

On Linux one can find the home directory of Jenkins looking for a file, that Jenkins' home contains, e.g.:

$ find / -name "config.xml" | grep "jenkins"
/var/lib/jenkins/config.xml

SASS :not selector

I tried re-creating this, and .someclass.notip was being generated for me but .someclass:not(.notip) was not, for as long as I did not have the @mixin tip() defined. Once I had that, it all worked.

http://sassmeister.com/gist/9775949

$dropdown-width: 100px;
$comp-tip: true;

@mixin tip($pos:right) {

}

@mixin dropdown-pos($pos:right) {
  &:not(.notip) {
    @if $comp-tip == true{
      @if $pos == right {
        top:$dropdown-width * -0.6;
        background-color: #f00;
        @include tip($pos:$pos);
      }
    }
  }
  &.notip {
    @if $pos == right {
      top: 0;
      left:$dropdown-width * 0.8;
      background-color: #00f;
    }
  }
}

.someclass { @include dropdown-pos(); }

EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'. it what I get when I remove @mixin tip($pos:right) { }

Default passwords of Oracle 11g?

Login into the machine as oracle login user id( where oracle is installed)..

  1. Add ORACLE_HOME = <Oracle installation Directory> in Environment variable

  2. Open a command prompt

  3. Change the directory to %ORACLE_HOME%\bin

  4. type the command sqlplus /nolog

  5. SQL> connect /as sysdba

  6. SQL> alter user SYS identified by "newpassword";

One more check, while oracle installation and database confiuration assistant setup, if you configure any database then you might have given password and checked the same password for all other accounts.. If so, then you try with the password which you have given in your database configuration assistant setup.

Hope this will work for you..

Why doesn't CSS ellipsis work in table cell?

It's also important to put

table-layout:fixed;

Onto the containing table, so it operates well in IE9 (if your utilize max-width) as well.

Best way to do a PHP switch with multiple values per case?

maybe

        switch ($variable) {
        case 0:
            exit;
            break;
        case (1 || 3 || 4 || 5 || 6):
            die(var_dump('expression'));
        default:
            die(var_dump('default'));
            # code...
            break;
    }

Installation of SQL Server Business Intelligence Development Studio

This worked for me:

Start /wait setup.exe /qb  ADDLOCAL=SQL_DTS,Client_Components,Connectivity,SQL_Tools90,SQL_WarehouseDevWorkbench,SQLXML,Tools_Legacy,SQL_Documentation,SQL_BooksOnline

Based off this TechNet Article:

https://technet.microsoft.com/en-us/library/ms144259(v=sql.90).aspx

How to get tf.exe (TFS command line client)?

I'm in a virtual machine, and am trying to keep my VHD as small as possible, so I find Team Explorer is a really heavyweight solution (300+ MB install). As an alternative, I've had some luck copying a minimal set of EXEs/DLLs from a Team Explorer installation to a clean machine (.NET 4.0 is still required, of course).

I've only tried a handful of operations so far, but this set of files (about 8.5 MB) has been enough to get basic source-control functionality via tf.exe:

  • TF.exe
  • TF.exe.config
  • Microsoft.TeamFoundation.dll
  • Microsoft.TeamFoundation.Client.dll
  • Microsoft.TeamFoundation.Common.dll
  • Microsoft.TeamFoundation.Common.Library.dll
  • Microsoft.TeamFoundation.VersionControl.Client.dll
  • Microsoft.TeamFoundation.VersionControl.Common.dll
  • Microsoft.TeamFoundation.VersionControl.Controls.dll

(It should go without saying that this is a completely unsupported solution, and it doesn't free you from the normal TFS licensing requirements.)

Depending on the operations you perform, you may find that additional DLLs are required. Fortunately, tf.exe will produce a nice error message telling you exactly which ones are missing.

How to extract custom header value in Web API message handler?

One line solution

var id = request.Headers.GetValues("MyCustomID").FirstOrDefault();

How to select count with Laravel's fluent query builder?

$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

What is the default database path for MongoDB?

The Windows x64 installer shows the a path in the installer UI/wizard.

You can confirm which path it used later, by opening your mongod.cfg file. My mongod.cfg was located here C:\Program Files\MongoDB\Server\4.0\bin\mongod.cfg (change for your version of MongoDB!

When I opened my mongd.cfg I found this line, showing the default db path:

dbPath: C:\Program Files\MongoDB\Server\4.0\data

However, this caused an error when trying to run mongod, which was still expecting to find C:\data\db:

2019-05-05T09:32:36.084-0700 I STORAGE [initandlisten] exception in initAndListen: NonExistentPath: Data directory C:\data\db\ not found., terminating

You could pass mongod a --dbpath=... parameter. In my case:

mongod --dbpath="C:\Program Files\MongoDB\Server\4.0\data"

jQuery autohide element after 5 seconds

$(function() {
    // setTimeout() function will be fired after page is loaded
    // it will wait for 5 sec. and then will fire
    // $("#successMessage").hide() function
    setTimeout(function() {
        $("#successMessage").hide('blind', {}, 500)
    }, 5000);
});

Note: In order to make you jQuery function work inside setTimeout you should wrap it inside

function() { ... }

In Angular, how to pass JSON object/array into directive?

What you need is properly a service:

.factory('DataLayer', ['$http',

    function($http) {

        var factory = {};
        var locations;

        factory.getLocations = function(success) {
            if(locations){
                success(locations);
                return;
            }
            $http.get('locations/locations.json').success(function(data) {
                locations = data;
                success(locations);
            });
        };

        return factory;
    }
]);

The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

Use this service DataLayer in your controller and directive is ok as following:

appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
    DataLayer.getLocations(function(data){
        $scope.locations = data;
    });
});

.directive('map', function(DataLayer) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            DataLayer.getLocations(function(data) {
                angular.forEach(data, function(location, key){
                    //do something
                });
            });
        }
    };
});

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

You can try with the following way,

 <parent>
    <groupId></groupId>
    <artifactId></artifactId>
    <version></version>
  </parent>

So that the parent jar will be fetching from the repository.

Add/remove class with jquery based on vertical scroll?

Here's pure javascript example of handling classes during scrolling.

You'd probably want to throttle handling scroll events, more so as handler logic gets more complex, in that case throttle from lodash lib comes in handy.

And if you're doing spa, keep in mind that you need to clear event listeners with removeEventListener once they're not needed (eg during onDestroy lifecycle hook of your component, like destroyed() for Vue, or maybe return function of useEffect hook for React).

_x000D_
_x000D_
const navbar = document.getElementById('navbar')_x000D_
_x000D_
// OnScroll event handler_x000D_
const onScroll = () => {_x000D_
_x000D_
  // Get scroll value_x000D_
  const scroll = document.documentElement.scrollTop_x000D_
_x000D_
  // If scroll value is more than 0 - add class_x000D_
  if (scroll > 0) {_x000D_
    navbar.classList.add("scrolled");_x000D_
  } else {_x000D_
    navbar.classList.remove("scrolled")_x000D_
  }_x000D_
}_x000D_
_x000D_
// Optional - throttling onScroll handler at 100ms with lodash_x000D_
const throttledOnScroll = _.throttle(onScroll, 100, {})_x000D_
_x000D_
// Use either onScroll or throttledOnScroll_x000D_
window.addEventListener('scroll', onScroll)
_x000D_
#navbar {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  width: 100%;_x000D_
  height: 60px;_x000D_
  background-color: #89d0f7;_x000D_
  box-shadow: 0px 5px 0px rgba(0, 0, 0, 0);_x000D_
  transition: box-shadow 500ms;_x000D_
}_x000D_
_x000D_
#navbar.scrolled {_x000D_
  box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);_x000D_
}_x000D_
_x000D_
#content {_x000D_
  height: 3000px;_x000D_
  margin-top: 60px;_x000D_
}
_x000D_
<!-- Optional - lodash library, used for throttlin onScroll handler-->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>_x000D_
<header id="navbar"></header>_x000D_
<div id="content"></div>
_x000D_
_x000D_
_x000D_

How to recursively delete an entire directory with PowerShell 2.0?

Deleting an entire folder tree sometimes works and sometimes fails with "Directory not empty" errors. Subsequently attempting to check if the folder still exists can result in "Access Denied" or "Unauthorized Access" errors. I do not know why this happens, though some insight may be gained from this StackOverflow posting.

I have been able to get around these issues by specifying the order in which items within the folder are deleted, and by adding delays. The following runs well for me:

# First remove any files in the folder tree
Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Where-Object { -not ($_.psiscontainer) } | Remove-Item –Force

# Then remove any sub-folders (deepest ones first).    The -Recurse switch may be needed despite the deepest items being deleted first.
ForEach ($Subfolder in Get-ChildItem -LiteralPath $FolderToDelete -Recurse -Force | Select-Object FullName, @{Name="Depth";Expression={($_.FullName -split "\\").Count}} | Sort-Object -Property @{Expression="Depth";Descending=$true}) { Remove-Item -LiteralPath $Subfolder.FullName -Recurse -Force }

# Then remove the folder itself.  The -Recurse switch is sometimes needed despite the previous statements.
Remove-Item -LiteralPath $FolderToDelete -Recurse -Force

# Finally, give Windows some time to finish deleting the folder (try not to hurl)
Start-Sleep -Seconds 4

A Microsoft TechNet article Using Calculated Properties in PowerShell was helpful to me in getting a list of sub-folders sorted by depth.

Similar reliability issues with RD /S /Q can be solved by running DEL /F /S /Q prior to RD /S /Q and running the RD a second time if necessary - ideally with a pause in between (i.e. using ping as shown below).

DEL /F /S /Q "C:\Some\Folder\to\Delete\*.*" > nul
RD /S /Q "C:\Some\Folder\to\Delete" > nul
if exist "C:\Some\Folder\to\Delete"  ping -4 -n 4 127.0.0.1 > nul
if exist "C:\Some\Folder\to\Delete"  RD /S /Q "C:\Some\Folder\to\Delete" > nul

Java: Reading a file into an array

Here is some example code to help you get started:

package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}

And an example unit test:

package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Hope this helps.

Javascript "Uncaught TypeError: object is not a function" associativity question

Your code experiences a case where the Automatic Semicolon Insertion (ASI) process doesn't happen.

You should never rely on ASI. You should use semicolons to properly separate statements:

var postTypes = new Array('hello', 'there'); // <--- Place a semicolon here!!

(function() { alert('hello there') })();

Your code was actually trying to invoke the array object.

Inheritance and Overriding __init__ in python

Yes, you must call __init__ for each parent class. The same goes for functions, if you are overriding a function that exists in both parents.

Postgresql -bash: psql: command not found

It can be due to psql not being in PATH

$ locate psql
/usr/lib/postgresql/9.6/bin/psql

Then create a link in /usr/bin

ln -s /usr/lib/postgresql/9.6/bin/psql /usr/bin/psql

Then try to execute psql it should work.

Java generating Strings with placeholders

See String.format method.

String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true

When to use single quotes, double quotes, and backticks in MySQL

The string literals in MySQL and PHP are the same.

A string is a sequence of bytes or characters, enclosed within either single quote (“'”) or double quote (“"”) characters.

So if your string contains single quotes, then you could use double quotes to quote the string, or if it contains double quotes, then you could use single quotes to quote the string. But if your string contains both single quotes and double quotes, you need to escape the one that used to quote the string.

Mostly, we use single quotes for an SQL string value, so we need to use double quotes for a PHP string.

$query = "INSERT INTO table (id, col1, col2) VALUES (NULL, 'val1', 'val2')";

And you could use a variable in PHP's double-quoted string:

$query = "INSERT INTO table (id, col1, col2) VALUES (NULL, '$val1', '$val2')";

But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)

what's the default value of char?

'\u0000' stands for null . So if you print an uninitialized char variable , you'll get nothing.

How to disable CSS in Browser for testing purposes

Another way to achieve @David Baucum's solution in fewer steps:

  1. Right click -> inspect element
  2. Click on the stylesheet's name that affect your element (just on the right side of the declaration)
  3. Highlight all of the text and hit delete.

It could be handier in some cases.

Row names & column names in R

I think that using colnames and rownames makes the most sense; here's why.

Using names has several disadvantages. You have to remember that it means "column names", and it only works with data frame, so you'll need to call colnames whenever you use matrices. By calling colnames, you only have to remember one function. Finally, if you look at the code for colnames, you will see that it calls names in the case of a data frame anyway, so the output is identical.

rownames and row.names return the same values for data frame and matrices; the only difference that I have spotted is that where there aren't any names, rownames will print "NULL" (as does colnames), but row.names returns it invisibly. Since there isn't much to choose between the two functions, rownames wins on the grounds of aesthetics, since it pairs more prettily withcolnames. (Also, for the lazy programmer, you save a character of typing.)

How to serialize an Object into a list of URL query parameters?

Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&')

Ignore 'Security Warning' running script from command line

If you're running into this error from a downloaded powershell script, you can unblock the script this way:

  1. Right-click on the .ps1 file in question, and select Properties

  2. Click Unblock in the file properties

    enter image description here

  3. Click OK

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

Tried most of the above and nothing worked. Then turned off the VPN software (NordVPN) and everything was fine.

How to make a window always stay on top in .Net?

The following code makes the window always stay on top as well as make it frameless.

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace StayOnTop
{
    public partial class Form1 : Form
    {
        private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        private const UInt32 SWP_NOSIZE = 0x0001;
        private const UInt32 SWP_NOMOVE = 0x0002;
        private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        public Form1()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
            TopMost = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetWindowPos(this.Handle, HWND_TOPMOST, 100, 100, 300, 300, TOPMOST_FLAGS);
        }

        protected override void WndProc(ref Message m)
        {
            const int RESIZE_HANDLE_SIZE = 10;

            switch (m.Msg)
            {
                case 0x0084/*NCHITTEST*/ :
                    base.WndProc(ref m);

                    if ((int)m.Result == 0x01/*HTCLIENT*/)
                    {
                        Point screenPoint = new Point(m.LParam.ToInt32());
                        Point clientPoint = this.PointToClient(screenPoint);
                        if (clientPoint.Y <= RESIZE_HANDLE_SIZE)
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)13/*HTTOPLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)12/*HTTOP*/ ;
                            else
                                m.Result = (IntPtr)14/*HTTOPRIGHT*/ ;
                        }
                        else if (clientPoint.Y <= (Size.Height - RESIZE_HANDLE_SIZE))
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)10/*HTLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)2/*HTCAPTION*/ ;
                            else
                                m.Result = (IntPtr)11/*HTRIGHT*/ ;
                        }
                        else
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)16/*HTBOTTOMLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)15/*HTBOTTOM*/ ;
                            else
                                m.Result = (IntPtr)17/*HTBOTTOMRIGHT*/ ;
                        }
                    }
                    return;
            }
            base.WndProc(ref m);
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style |= 0x20000; // <--- use 0x20000
                return cp;
            }
        }
    }
}

Compare two folders which has many files inside contents

To get summary of new/missing files, and which files differ:

diff -arq folder1 folder2

a treats all files as text, r recursively searched subdirectories, q reports 'briefly', only when files differ

Change language for bootstrap DateTimePicker

i think you have to set it in the options:

$(".form_datetime").datetimepicker({
    isRTL: false,
    format: 'dd.mm.yyyy hh:ii',
    autoclose:true,
    language: 'ru'
});

if its not working, be sure that:

$.fn.datetimepicker.dates['en'] = {
    days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
    daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
    months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    today: "Today"
};

is defined for 'ru'

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Another option is to add the M2_HOME variable at: IntelliJ IDEA=>Preferences=>IDE Settings=>Path Variables

After a restart of IntelliJ, IntelliJ IDEA=>Preferences=>Project Settings=>Maven=>Maven home directory should be set to your M2_HOME variable.

How to setup virtual environment for Python in VS Code?

I fixed the issue without changing the python path as that did not seem like the right solution for me. The following solution worked for me, hopefully it works for you as well :))

  1. Open cmd in windows / shell in Linux/Mac.
  2. Activate your virtualenv (using source activate / activate.bat / activate.ps1 if using power shell)

    C:\Users\<myUserName>\Videos\myFolder>django-project\Scripts\activate.bat (django-project) C:\Users\<myUserName>\Videos\myFolder>

  3. Navigate to your project directory and open vscode there.

    (django-project) C:\Users\prash\Videos\myFolder\projects>code .

  4. in VS Code, goto File --> Preferences --> Settings (dont worry you dont need to open the json file)

  5. In the setting search bar search for virtual / venv and hit enter. You should find the below in the search bar:

Python: Venv Folders Folders in your home directory to look into for virtual environments (supports pyenv, direnv and virtualenvwrapper by default).

  1. Add item, and then enter the path of the scripts of your virtuanenv which has the activate file in it. For example in my system, it is:

    C:\Users\<myUserName>\Videos\myFolder\django-project\Scripts\

  2. Save it and restart VS Code.

  3. To restart, open cmd again, navigate to your project path and open vs code. (Note that your venv should be activated in cmd before you open vs code from cmd)

Command to open vs code from cmd:

code .

How to setup virtualenv in VS code

Convert Text to Uppercase while typing in Text box

if you can use LinqToObjects in your Project

private YourTextBox_TextChanged ( object sender, EventArgs e)
{
   return YourTextBox.Text.Where(c=> c.ToUpper());
}

An if you can't use LINQ (e.g. your project's target FW is .NET Framework 2.0) then

private YourTextBox_TextChanged ( object sender, EventArgs e)
{
   YourTextBox.Text = YourTextBox.Text.ToUpper();
}

Why Text_Changed Event ?

There are few user input events in framework..

1-) OnKeyPressed fires (starts to work) when user presses to a key from keyboard after the key pressed and released

2-) OnKeyDown fires when user presses to a key from keyboard during key presses

3-) OnKeyUp fires when user presses to a key from keyboard and key start to release (user take up his finger from key)

As you see, All three are about keyboard event..So what about if the user copy and paste some data to the textbox?

if you use one of these keyboard events then your code work when and only user uses keyboard..in example if user uses a screen keyboard with mouse click or copy paste the data your code which implemented in keyboard events never fires (never start to work)

so, and Fortunately there is another option to work around : The Text Changed event..

Text Changed event don't care where the data comes from..Even can be a copy-paste, a touchscreen tap (like phones or tablets), a virtual keyboard, a screen keyboard with mouse-clicks (some bank operations use this to much more security, or may be your user would be a disabled person who can't press to a standard keyboard) or a code-injection ;) ..

No Matter !

Text Changed event just care about is there any changes with it's responsibility component area ( here, Your TextBox's Text area) or not..

If there is any change occurs, then your code which implemented under Text changed event works..

Does Spring Data JPA have any way to count entites using method name resolving?

According to Abel, after the version 1.4 (tested in version 1.4.3.RELEASE) is possible doing this way:

public long countByName(String name);

How do I view an older version of an SVN file?

To directly answer the question of how to "get a copy of that file":

svn cat -r 666 file > file_r666

then you can view the newly created file_r666 with any viewer or comparison program, e.g.

kompare file_r666 file

nicely shows the differences.

I posted the answer because the accepted answer's commands do actually not give a copy of the file and because svn cat -r 666 file | vim does not work with my system (Vim: Error reading input, exiting...)

How to remove index.php from URLs?

Hi I'm late to the party.. just wanted to point out that the instructions from http://davidtsadler.com/archives/2012/06/03/how-to-install-magento-on-ubuntu/ were really useful.

I had Ubuntu server installed with Apache, MySql and Php so I thought I could jump to the heading Creating the directory from which Magento will be served from and I reached the same problem as the OP, i.e. I had 'index.php' needed in all the URLs (or I would get 404 not found). I then went back to Installing and configuring the Apache HTTP server and after restarting apache it works perfectly.

For reference, I was missing:

sudo bash -c "cat >> /etc/apache2/conf.d/servername.conf <<EOF
ServerName localhost
EOF"

... and

sudo a2enmod rewrite
sudo service apache2 restart

Hope this helps

How can I start an interactive console for Perl?

Sepia and PDE have also own REPLs (for GNU Emacs).

convert a char* to std::string

Pass it in through the constructor:

const char* dat = "my string!";
std::string my_string( dat );

You can use the function string.c_str() to go the other way:

std::string my_string("testing!");
const char* dat = my_string.c_str();

Find out the history of SQL queries

    select v.SQL_TEXT,
           v.PARSING_SCHEMA_NAME,
           v.FIRST_LOAD_TIME,
           v.DISK_READS,
           v.ROWS_PROCESSED,
           v.ELAPSED_TIME,
           v.service
      from v$sql v
where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss')>ADD_MONTHS(trunc(sysdate,'MM'),-2)

where clause is optional. You can sort the results according to FIRST_LOAD_TIME and find the records up to 2 months ago.

Getting result of dynamic SQL into a variable for sql-server

this could be a solution?

declare @step2cmd nvarchar(200)
DECLARE @rcount NUMERIC(18,0)   
set @step2cmd = 'select count(*) from uat.ap.ztscm_protocollo' --+ @nometab
EXECUTE @rcount=sp_executesql @step2cmd
select @rcount

How do I create a crontab through a script

I have written a crontab deploy tool in python: https://github.com/monklof/deploycron

pip install deploycron

Install your crontab is very easy, this will merge the crontab into the system's existing crontab.

from deploycron import deploycron
deploycron(content="* * * * * echo hello > /tmp/hello")

Error C1083: Cannot open include file: 'stdafx.h'

There are two solutions for it.

Solution number one: 1.Recreate the project. While creating a project ensure that precompiled header is checked(Application settings... *** Do not check empty project)

Solution Number two: 1.Create stdafx.h and stdafx.cpp in your project 2 Right click on project -> properties -> C/C++ -> Precompiled Headers 3.select precompiled header to create(/Yc) 4.Rebuild the solution

Drop me a message if you encounter any issue.

Google Maps API OVER QUERY LIMIT per second limit

The geocoder has quota and rate limits. From experience, you can geocode ~10 locations without hitting the query limit (the actual number probably depends on server loading). The best solution is to delay when you get OVER_QUERY_LIMIT errors, then retry. See these similar posts:

Returning binary file from controller in ASP.NET Web API

Try using a simple HttpResponseMessage with its Content property set to a StreamContent:

// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;

public HttpResponseMessage Post(string version, string environment,
    string filetype)
{
    var path = @"C:\Temp\test.exe";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

A few things to note about the stream used:

  • You must not call stream.Dispose(), since Web API still needs to be able to access it when it processes the controller method's result to send data back to the client. Therefore, do not use a using (var stream = …) block. Web API will dispose the stream for you.

  • Make sure that the stream has its current position set to 0 (i.e. the beginning of the stream's data). In the above example, this is a given since you've only just opened the file. However, in other scenarios (such as when you first write some binary data to a MemoryStream), make sure to stream.Seek(0, SeekOrigin.Begin); or set stream.Position = 0;

  • With file streams, explicitly specifying FileAccess.Read permission can help prevent access rights issues on web servers; IIS application pool accounts are often given only read / list / execute access rights to the wwwroot.

How to set the color of an icon in Angular Material?

color="white" is not a known attribute to Angular Material.

color attribute can changed to primary, accent, and warn. as said in this doc

your icon inside button works because its parent class button has css class of color:white, or may be your color="accent" is white. check the developer tools to find it.

By default, icons will use the current font color

How to access child's state in React?

Just before I go into detail about how you can access the state of a child component, please make sure to read Markus-ipse's answer regarding a better solution to handle this particular scenario.

If you do indeed wish to access the state of a component's children, you can assign a property called ref to each child. There are now two ways to implement references: Using React.createRef() and callback refs.

Using React.createRef()

This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.

You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the ref attribute.

class FormEditor extends React.Component {
  constructor(props) {
    super(props);
    this.FieldEditor1 = React.createRef();
  }
  render() {
    return <FieldEditor ref={this.FieldEditor1} />;
  }
}

In order to access this kind of ref, you'll need to use:

const currentFieldEditor1 = this.FieldEditor1.current;

This will return an instance of the mounted component so you can then use currentFieldEditor1.state to access the state.

Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. <div ref={this.divRef} />) then this.divRef.current will return the underlying DOM element instead of a component instance.

Callback Refs

This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.

For example:

<FieldEditor
    ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
    {...props}
/>

In these examples the reference is stored on the parent component. To call this component in your code, you can use:

this.fieldEditor1

and then use this.fieldEditor1.state to get the state.

One thing to note, make sure your child component has rendered before you try to access it ^_^

As above, if you use these references on a DOM node instead of a component (e.g. <div ref={(divRef) => {this.myDiv = divRef;}} />) then this.divRef will return the underlying DOM element instead of a component instance.

Further Information

If you want to read more about React's ref property, check out this page from Facebook.

Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's state to "make things happen".

Hope this helps ^_^

Edit: Added React.createRef() method for creating refs. Removed ES5 code.

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

How to use MD5 in javascript to transmit a password

crypto-js is a rich javascript library containing many cryptography algorithms.

All you have to do is just call CryptoJS.MD5(password)

$.post(
  'includes/login.php', 
  { user: username, pass: CryptoJS.MD5(password) },
  onLogin, 
  'json' );

How to import NumPy in the Python shell

The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

I had the same problem, today 2016 - october - 06 I solved with this:

I changed all dependencies that began with 9.?.? to 9.6.1 I compiled with sdk version 24 and target version 17.

There is another packages in my solution because I used more things then only authentication.

After changed your build.gradle (Module:app) with the code below do it:

  1. Put your package NAME in the line with the words applicationId "com.YOUR_PACKAGE_HERE"

  2. Synchronize your project (Ctrl+alt+v) and Build Again.

This is the code of the file buid.gradle (Module:app) that worked for me:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.3"
    defaultConfig {
        applicationId "com.YOUR_PACKAGE_HERE"
        minSdkVersion 24
        targetSdkVersion 17
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.google.firebase:firebase-core:9.6.1'
    compile 'com.google.firebase:firebase-database:9.6.1'

    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'

    compile 'com.google.firebase:firebase-crash:9.6.1'
    testCompile 'junit:junit:4.12'

    compile 'com.google.firebase:firebase-messaging:9.6.1'

    compile 'com.google.firebase:firebase-ads:9.6.1'


    compile 'com.google.firebase:firebase-auth:9.6.1'


    compile 'com.google.android.gms:play-services:9.6.1'

}
apply plugin: 'com.google.gms.google-services'

How to include clean target in Makefile?

In makefile language $@ means "name of the target", so rm -f $@ translates to rm -f clean.

You need to specify to rm what exactly you want to delete, like rm -f *.o code1 code2

how to change color of TextinputLayout's label and edittext underline android

Based on Fedor Kazakov and others answers, I created a default config.

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="Widget.Design.TextInputLayout" parent="AppTheme">
        <item name="hintTextAppearance">@style/AppTheme.TextFloatLabelAppearance</item>
        <item name="errorTextAppearance">@style/AppTheme.TextErrorAppearance</item>
        <item name="counterTextAppearance">@style/TextAppearance.Design.Counter</item>
        <item name="counterOverflowTextAppearance">@style/TextAppearance.Design.Counter.Overflow</item>
    </style>

    <style name="AppTheme.TextFloatLabelAppearance" parent="TextAppearance.Design.Hint">
        <!-- Floating label appearance here -->
        <item name="android:textColor">@color/colorAccent</item>
        <item name="android:textSize">20sp</item>
    </style>

    <style name="AppTheme.TextErrorAppearance" parent="TextAppearance.Design.Error">
        <!-- Error message appearance here -->
        <item name="android:textColor">#ff0000</item>
        <item name="android:textSize">20sp</item>
    </style>

</resources>

activity_layout.xml

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.AppCompatEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Text hint here"
        android:text="5,2" />

</android.support.design.widget.TextInputLayout>

Focused:

Focused

Without focus:

Without focus

Error message:

enter image description here

javac: invalid target release: 1.8

For IntelliJ14 you may have to change the bytecode version w.r.t. the JDK you are using (in the global settings):

enter image description here

BULK INSERT with identity (auto-increment) column

You have to do bulk insert with format file:

   BULK INSERT Employee FROM 'path\tempFile.csv ' 
   WITH (FORMATFILE = 'path\tempFile.fmt');

where format file (tempFile.fmt) looks like this:

11.0
2
1 SQLCHAR 0 50 "\t"  2  Name   SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 50 "\r\n" 3  Address  SQL_Latin1_General_CP1_CI_AS

more details here - http://msdn.microsoft.com/en-us/library/ms179250.aspx

Android SDK location

Just add a new empty directory that path is “/Users/username/Library/Android/sdk”. Then reopen it.

Where Sticky Notes are saved in Windows 10 1607

Use this document to transfer Sticky Notes data file StickyNotes.snt to the new format

http://www.winhelponline.com/blog/recover-backup-sticky-notes-data-file-windows-10/

Restore:

%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState

  • Close Sticky Notes
  • Create a new folder named Legacy
  • Under the Legacy folder, copy your existing StickyNotes.snt, and rename it to ThresholdNotes.snt
  • Start the Sticky Notes app. It reads the legacy .snt file and transfers the content to the database file automatically.

Backup

just backup following file.

%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite

How many significant digits do floats and doubles have in java?

From java specification :

The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New York).

As it's hard to do anything with numbers without understanding IEEE754 basics, here's another link.

It's important to understand that the precision isn't uniform and that this isn't an exact storage of the numbers as is done for integers.

An example :

double a = 0.3 - 0.1;
System.out.println(a);          

prints

0.19999999999999998

If you need arbitrary precision (for example for financial purposes) you may need Big Decimal.

Remove all the children DOM elements in div

From the dojo API documentation:

dojo.html._emptyNode(node);

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

LINUX: Link all files from one to another directory

The posted solutions will not link any hidden files. To include them, try this:

cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib not /mnt/usr/lib), you could do this:

cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done

How to check if a String contains any letter from a to z?

You can look for regular expression

Regex.IsMatch(str, @"^[a-zA-Z]+$");

I have Python on my Ubuntu system, but gcc can't find Python.h

locate Python.h

If the output is empty, then find your python version

python --version

lets say it is X.x i.e 2.7 or 3.6, 3.7, 3.8 Then with the same version install header files and static libraries for python

sudo apt-get install pythonX.x-dev

indexOf Case Sensitive?

What are you doing with the index value once returned?

If you are using it to manipulate your string, then could you not use a regular expression instead?

import static org.junit.Assert.assertEquals;    
import org.junit.Test;

public class StringIndexOfRegexpTest {

    @Test
    public void testNastyIndexOfBasedReplace() {
        final String source = "Hello World";
        final int index = source.toLowerCase().indexOf("hello".toLowerCase());
        final String target = "Hi".concat(source.substring(index
                + "hello".length(), source.length()));
        assertEquals("Hi World", target);
    }

    @Test
    public void testSimpleRegexpBasedReplace() {
        final String source = "Hello World";
        final String target = source.replaceFirst("(?i)hello", "Hi");
        assertEquals("Hi World", target);
    }
}

MySQLi prepared statements error reporting

Each method of mysqli can fail. You should test each return value. If one fails, think about whether it makes sense to continue with an object that is not in the state you expect it to be. (Potentially not in a "safe" state, but I think that's not an issue here.)

Since only the error message for the last operation is stored per connection/statement you might lose information about what caused the error if you continue after something went wrong. You might want to use that information to let the script decide whether to try again (only a temporary issue), change something or to bail out completely (and report a bug). And it makes debugging a lot easier.

$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
  // and since all the following operations need a valid/ready statement object
  // it doesn't make sense to go on
  // you might want to use a more sophisticated mechanism than die()
  // but's it's only an example
  die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}

$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
  // again execute() is useless if you can't bind the parameters. Bail out somehow.
  die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}

$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
  die('execute() failed: ' . htmlspecialchars($stmt->error));
}

$stmt->close();

Just a few notes six years later...

The mysqli extension is perfectly capable of reporting operations that result in an (mysqli) error code other than 0 via exceptions, see mysqli_driver::$report_mode.
die() is really, really crude and I wouldn't use it even for examples like this one anymore.
So please, only take away the fact that each and every (mysql) operation can fail for a number of reasons; even if the exact same thing went well a thousand times before....

Rendering partial view on button click in ASP.NET MVC

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val();
  $('#searchResults').load(url, { searchText: keyWord });
})

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
{
  var model = // build list based on parameter searchText
   return PartialView("SearchResults", model);
}

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.

Edit

Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
  if (!$(this).valid()) { 
    return false; // prevent the ajax call if validation errors
  }
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false; // prevent the default submit action
})

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
  var model = // build list based on the properties of criteria
  return PartialView("SearchResults", model);
}

How to clear/remove observable bindings in Knockout.js?

For a project I'm working on, I wrote a simple ko.unapplyBindings function that accepts a jQuery node and the remove boolean. It first unbinds all jQuery events as ko.cleanNode method doesn't take care of that. I've tested for memory leaks, and it appears to work just fine.

ko.unapplyBindings = function ($node, remove) {
    // unbind events
    $node.find("*").each(function () {
        $(this).unbind();
    });

    // Remove KO subscriptions and references
    if (remove) {
        ko.removeNode($node[0]);
    } else {
        ko.cleanNode($node[0]);
    }
};

How to list records with date from the last 10 days?

Yes this does work in PostgreSQL (assuming the column "date" is of datatype date) Why don't you just try it?

The standard ANSI SQL format would be:

SELECT Table.date 
FROM Table 
WHERE date > current_date - interval '10' day;

I prefer that format as it makes things easier to read (but it is the same as current_date - 10).

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

git: Switch branch and ignore any changes without committing

To switch to other branch without committing the changes when git stash doesn't work. You can use the below command:

git checkout -f branch-name

Draw horizontal rule in React Native

This is how i solved divider with horizontal lines and text in the midddle:

<View style={styles.divider}>
  <View style={styles.hrLine} />
  <Text style={styles.dividerText}>OR</Text>
  <View style={styles.hrLine} />
</View>

And styles for this:

import { Dimensions, StyleSheet } from 'react-native'

const { width } = Dimensions.get('window')

const styles = StyleSheet.create({
divider: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 10,
  },
  hrLine: {
    width: width / 3.5,
    backgroundColor: 'white',
    height: 1,
  },
  dividerText: {
    color: 'white',
    textAlign: 'center',
    width: width / 8,
  },
})

Reset the database (purge all), then seed a database

on Rails 6 you can now do something like

rake db:seed:replant This Truncates tables of each database for current environment and loads the seeds

https://blog.saeloun.com/2019/09/30/rails-6-adds-db-seed-replant-task-and-db-truncate_all.html

$ rails db:seed:replant --trace
** Invoke db:seed:replant (first_time)
** Invoke db:load_config (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:load_config
** Invoke db:truncate_all (first_time)
** Invoke db:load_config
** Invoke db:check_protected_environments (first_time)
** Invoke db:load_config
** Execute db:check_protected_environments
** Execute db:truncate_all
** Invoke db:seed (first_time)
** Invoke db:load_config
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke db:load_config
** Execute db:abort_if_pending_migrations
** Execute db:seed:replant

Check whether $_POST-value is empty

If the form was successfully submitted, $_POST['userName'] should always be set, though it may contain an empty string, which is different from not being set at all. Instead check if it is empty()

if (isset($_POST['submit'])) {
    if (empty($_POST['userName'])) {
        $username = 'Anonymous';
    } else { 
        $username = $_POST['userName'];
    }
}

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

How to add a right button to a UINavigationController?

Try this.It work for me.

Navigation bar and also added background image to right button.

 UIBarButtonItem *Savebtn=[[UIBarButtonItem alloc]initWithImage:[[UIImage    
 imageNamed:@"bt_save.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] 
 style:UIBarButtonItemStylePlain target:self action:@selector(SaveButtonClicked)];
 self.navigationItem.rightBarButtonItem=Savebtn;

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Check whether a path is valid in Python without creating a file at the path's target

open(filename,'r')   #2nd argument is r and not w

will open the file or give an error if it doesn't exist. If there's an error, then you can try to write to the path, if you can't then you get a second error

try:
    open(filename,'r')
    return True
except IOError:
    try:
        open(filename, 'w')
        return True
    except IOError:
        return False

Also have a look here about permissions on windows

How do you round a number to two decimal places in C#?

Wikipedia has a nice page on rounding in general.

All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms. For example, the Math.Round() (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use round-to-even. The Ceiling() and Floor() methods are related.

You can round with custom numeric formatting as well.

Note that Decimal.Round() uses a different method than Math.Round();

Here is a useful post on the banker's rounding algorithm. See one of Raymond's humorous posts here about rounding...

How to get the Android Emulator's IP address?

public String getLocalIpAddress() {

    try {
        for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

Installed Java 7 on Mac OS X but Terminal is still using version 6

Simple Solution

export PATH="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin:$PATH"

Detecting installed programs via registry

User-specific settings should be written to HKCU\Software, machine-specific settings to HKLM\Software. Under these keys, structure [software vendor name]\[application name] (e.g. HKLM\Software\Microsoft\Internet Explorer) may be the most common, but that's just a convention, not a law of nature.

Many (most?) applications also add their uninstall entries to HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\[app name], but again, not all applications do this.

These are the most important keys; however, contents of the registry do not have to represent the installed software exactly - maybe the application was installed once, but then was manually deleted, or maybe the uninstaller didn't remove all traces of it. If you want to be sure, check the filesystem to see if the application still exists where its registry entries say it is.

Edit:

If you're a member of the group Administrators, you can check the HKEY_USERS hive - each user's HKCU actually resides there (you'll need to know the user SID, or go through all of them).

Note: As @Brian Ensink says, "installed" is a bit of a vague concept - are we trying to find what the user could run? Some software doesn't even write to the Registry at all: search for "portable apps" to see apps that have been specifically modified to run directly from media (CD/USB) and not to leave any traces on the computer. We may also have to scan the disks, and network disks, and anything the user downloads, and world-accessible Windows shares in the Internet (yes, such things exist legitimately - \\live.sysinternals.com\tools comes to mind). In this direction, there's no real limit of what the user can run, unless prevented by system policies.

What does "Error: object '<myvariable>' not found" mean?

I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.

Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!

Hope to help

How do you detect where two line segments intersect?

Based on t3chb0t's answer:

int intersezione_linee(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int& p_x, int& p_y)
{
   //L1: estremi (x1,y1)(x2,y2) L2: estremi (x3,y3)(x3,y3)
   int d;
   d = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4);
   if(!d)
       return 0;
   p_x = ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4))/d;
   p_y = ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4))/d;
   return 1;
}

int in_bounding_box(int x1, int y1, int x2, int y2, int p_x, int p_y)
{
    return p_x>=x1 && p_x<=x2 && p_y>=y1 && p_y<=y2;

}

int intersezione_segmenti(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int& p_x, int& p_y)
{
    if (!intersezione_linee(x1,y1,x2,y2,x3,y3,x4,y4,p_x,p_y))
        return 0;

    return in_bounding_box(x1,y1,x2,y2,p_x,p_y) && in_bounding_box(x3,y3,x4,y4,p_x,p_y);
}

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

How to debug Spring Boot application with Eclipse?

How to debug a remote staging or production Spring Boot application

Server-side

Let's assume you have successfully followed Spring Boot's guide on setting up your Spring Boot application as a service. Your application artifact resides in /srv/my-app/my-app.war, accompanied by a configuration file /srv/my-app/my-app.conf:

# This is file my-app.conf
# What can you do in this .conf file? The my-app.war is prepended with a SysV init.d script
# (yes, take a look into the war file with a text editor). As my-app.war is symlinked in the init.d directory, that init.d script
# gets executed. One of its step is actually `source`ing this .conf file. Therefore we can do anything in this .conf file that
# we can also do in a regular shell script.

JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,address=localhost:8002,server=y,suspend=n"
export SPRING_PROFILES_ACTIVE=staging

When you restart your Spring Boot application with sudo service my-app restart, then in its log file located at /var/log/my-app.log should be a line saying Listening for transport dt_socket at address: 8002.

Client-side (developer machine)

Open an SSH port-forwarding tunnel to the server: ssh -L 8002:localhost:8002 [email protected]. Keep this SSH session running.

In Eclipse, from the toolbar, select Run -> Debug Configurations -> select Remote Java Application -> click the New button -> select as Connection Type Standard (Socket Attach), as Host localhost, and as Port 8002 (or whatever you have configured in the steps before). Click Apply and then Debug.

The Eclipse debugger should now connect to the remote server. Switching to the Debug perspective should show the connected JVM and its threads. Breakpoints should fire as soon as they are remotely triggered.

How to install python3 version of package via pip on Ubuntu?

The easiest way to install latest pip2/pip3 and corresponding packages:

curl https://bootstrap.pypa.io/get-pip.py | python2
pip2 install package-name    

curl https://bootstrap.pypa.io/get-pip.py | python3
pip3 install package-name

Note: please run these commands as root

How do I read any request header in PHP

if only one key is required to retrieved, For example "Host" address is required, then we can use

apache_request_headers()['Host']

So that we can avoid loops and put it inline to the echo outputs

Saving the PuTTY session logging

This is a bit confusing, but follow these steps to save the session.

  1. Category -> Session -> enter public IP in Host and 22 in port.
  2. Connection -> SSH -> Auth -> select the .ppk file
  3. Category -> Session -> enter a name in Saved Session -> Click Save

To open the session, double click on particular saved session.

How do you remove duplicates from a list whilst preserving order?

Borrowing the recursive idea used in definining Haskell's nub function for lists, this would be a recursive approach:

def unique(lst):
    return [] if lst==[] else [lst[0]] + unique(filter(lambda x: x!= lst[0], lst[1:]))

e.g.:

In [118]: unique([1,5,1,1,4,3,4])
Out[118]: [1, 5, 4, 3]

I tried it for growing data sizes and saw sub-linear time-complexity (not definitive, but suggests this should be fine for normal data).

In [122]: %timeit unique(np.random.randint(5, size=(1)))
10000 loops, best of 3: 25.3 us per loop

In [123]: %timeit unique(np.random.randint(5, size=(10)))
10000 loops, best of 3: 42.9 us per loop

In [124]: %timeit unique(np.random.randint(5, size=(100)))
10000 loops, best of 3: 132 us per loop

In [125]: %timeit unique(np.random.randint(5, size=(1000)))
1000 loops, best of 3: 1.05 ms per loop

In [126]: %timeit unique(np.random.randint(5, size=(10000)))
100 loops, best of 3: 11 ms per loop

I also think it's interesting that this could be readily generalized to uniqueness by other operations. Like this:

import operator
def unique(lst, cmp_op=operator.ne):
    return [] if lst==[] else [lst[0]] + unique(filter(lambda x: cmp_op(x, lst[0]), lst[1:]), cmp_op)

For example, you could pass in a function that uses the notion of rounding to the same integer as if it was "equality" for uniqueness purposes, like this:

def test_round(x,y):
    return round(x) != round(y)

then unique(some_list, test_round) would provide the unique elements of the list where uniqueness no longer meant traditional equality (which is implied by using any sort of set-based or dict-key-based approach to this problem) but instead meant to take only the first element that rounds to K for each possible integer K that the elements might round to, e.g.:

In [6]: unique([1.2, 5, 1.9, 1.1, 4.2, 3, 4.8], test_round)
Out[6]: [1.2, 5, 1.9, 4.2, 3]

How to modify a global variable within a function in bash?

A solution to this problem, without having to introduce complex functions and heavily modify the original one, is to store the value in a temporary file and read / write it when needed.

This approach helped me greatly when I had to mock a bash function called multiple times in a bats test case.

For example, you could have:

# Usage read_value path_to_tmp_file
function read_value {
  cat "${1}"
}

# Usage: set_value path_to_tmp_file the_value
function set_value {
  echo "${2}" > "${1}"
}
#----

# Original code:

function test1() {
  e=4
  set_value "${tmp_file}" "${e}"
  echo "hello"
}


# Create the temp file
# Note that tmp_file is available in test1 as well
tmp_file=$(mktemp)

# Your logic
e=2
# Store the value
set_value "${tmp_file}" "${e}"

# Run test1
test1

# Read the value modified by test1
e=$(read_value "${tmp_file}")
echo "$e"

The drawback is that you might need multiple temp files for different variables. And also you might need to issue a sync command to persist the contents on the disk between one write and read operations.

SQL Server - copy stored procedures from one db to another

Late one but gives more details that might be useful…

Here is a list of things you can do with advantages and disadvantages

Generate scripts using SSMS

  • Pros: extremely easy to use and supported by default
  • Cons: scripts might not be in the correct execution order and you might get errors if stored procedure already exists on secondary database. Make sure you review the script before executing.

Third party tools

  • Pros: tools such as ApexSQL Diff (this is what I use but there are many others like tools from Red Gate or Dev Art) will compare two databases in one click and generate script that you can execute immediately
  • Cons: these are not free (most vendors have a fully functional trial though)

System Views

  • Pros: You can easily see which stored procedures exist on secondary server and only generate those you don’t have.
  • Cons: Requires a bit more SQL knowledge

Here is how to get a list of all procedures in some database that don’t exist in another database

select *
from DB1.sys.procedures P
where P.name not in 
 (select name from DB2.sys.procedures P2)

How to divide flask app into multiple py files?

Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files.

I created a Gist with the code for doing this:

https://gist.github.com/Jaza/61f879f577bc9d06029e

As far as I'm aware, this is the only feasible way to divide up a Blueprint at the moment. It's not possible to create "sub-blueprints" in Flask, although there's an issue open with a lot of discussion about this:

https://github.com/mitsuhiko/flask/issues/593

Also, even if it were possible (and it's probably do-able using some of the snippets from that issue thread), sub-blueprints may be too restrictive for your use case anyway - e.g. if you don't want all the routes in a sub-module to have the same URL sub-prefix.

How to write text on a image in windows using python opencv2

This code uses cv2.putText to overlay text on an image. You need NumPy and OpenCV installed.

import numpy as np
import cv2

# Create a black image
img = np.zeros((512,512,3), np.uint8)

# Write some Text

font                   = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (10,500)
fontScale              = 1
fontColor              = (255,255,255)
lineType               = 2

cv2.putText(img,'Hello World!', 
    bottomLeftCornerOfText, 
    font, 
    fontScale,
    fontColor,
    lineType)

#Display the image
cv2.imshow("img",img)

#Save image
cv2.imwrite("out.jpg", img)

cv2.waitKey(0)

Is < faster than <=?

Only if the people who created the computers are bad with boolean logic. Which they shouldn't be.

Every comparison (>= <= > <) can be done in the same speed.

What every comparison is, is just a subtraction (the difference) and seeing if it's positive/negative.
(If the msb is set, the number is negative)

How to check a >= b? Sub a-b >= 0 Check if a-b is positive.
How to check a <= b? Sub 0 <= b-a Check if b-a is positive.
How to check a < b? Sub a-b < 0 Check if a-b is negative.
How to check a > b? Sub 0 > b-a Check if b-a is negative.

Simply put, the computer can just do this underneath the hood for the given op:

a >= b == msb(a-b)==0
a <= b == msb(b-a)==0
a > b == msb(b-a)==1
a < b == msb(a-b)==1

and of course the computer wouldn't actually need to do the ==0 or ==1 either.
for the ==0 it could just invert the msb from the circuit.

Anyway, they most certainly wouldn't have made a >= b be calculated as a>b || a==b lol

Easy way to build Android UI?

Droiddraw is good. I have been using it since long and haven't faced any issues yet (though it crashes sometimes, but thats ok)

TypeError: 'str' object cannot be interpreted as an integer

x = int(input("Give starting number: "))
y = int(input("Give ending number: "))

for i in range(x, y):
    print(i)

This outputs:

i have uploaded the output with the code

how to toggle (hide/show) a table onClick of <a> tag in java script

Try

<script>
  function toggleTable()
    {

    var status = document.getElementById("loginTable").style.display;

    if (status == 'block') {
      document.getElementById("loginTable").style.display="none";
    } else {
      document.getElementById("loginTable").style.display="block";
    }
  }
</script>

No restricted globals

Use react-router-dom library.

From there, import useLocation hook if you're using functional components:

import { useLocation } from 'react-router-dom';

Then append it to a variable:

Const location = useLocation();

You can then use it normally:

location.pathname

P.S: the returned location object has five properties only:

{ hash: "", key: "", pathname: "/" search: "", state: undefined__, }

How to create dynamic href in react render function?

You can use ES6 backtick syntax too

<a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a>

More info on es6 template literals

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

For the Swift-inclined:

if let registration: AnyObject = NSClassFromString("UIUserNotificationSettings") { // iOS 8+
    let notificationTypes: UIUserNotificationType = (.Alert | .Badge | .Sound)
    let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)

    application.registerUserNotificationSettings(notificationSettings)
} else { // iOS 7
    application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound)
}

Colouring plot by factor in R

Like Maiasaura, I prefer ggplot2. The transparent reference manual is one of the reasons. However, this is one quick way to get it done.

require(ggplot2)
data(diamonds)
qplot(carat, price, data = diamonds, colour = color)
# example taken from Hadley's ggplot2 book

And cause someone famous said, plot related posts are not complete without the plot, here's the result:

enter image description here

Here's a couple of references: qplot.R example, note basically this uses the same diamond dataset I use, but crops the data before to get better performance.

http://ggplot2.org/book/ the manual: http://docs.ggplot2.org/current/

How to check if a variable is null or empty string or all whitespace in JavaScript?

You can use if(addr && (addr = $.trim(addr)))

This has the advantage of actually removing any outer whitespace from addr instead of just ignoring it when performing the check.

Reference: http://api.jquery.com/jQuery.trim/

Error while trying to run project: Unable to start program. Cannot find the file specified

I just re-ran into the same issue: Console App, Visual Studio 2013, 64 bit OS. The project's settings was set to "Any CPU", I created a new configuration for x86 and VS was happy.

  • In Your Solution Explorer, Right Click your solution (.sln), choose "Configuration Manager"
  • Active Solution Platform: If it's saying "Any CPU", click the drop down arrow and choose ""
  • In the "Type or select the new platform", enter "x86"
  • Now, make sure that the "Active solution platform" is set to x86
  • Run (F5)

How to type a new line character in SQL Server Management Studio

I had trouble initially (don't know why) but I finally got the following to work with SSMS for SQL Server 2008.

Insert ALT-13 then ALT-10 where desired in your text in a varchar type column (music symbol and square appear and save when you leave the row). Initially you'll get a warning(!) to the left of the row after leaving it. Just re-excecute your SELECT statement. The symbols and warning will disappear but the CR/LF is saved. You must include ALT-13 if you want the text displayed properly in HTML. To quickly determine if this worked, copy the saved text from SSMS to Notepad.

Alternatively, if you can't get this to work, you can do the same thing starting with an nvarchar column. However the symbols will be saved as text so you must convert the column to varchar when you're done to convert the symbols to CR/LFs.

If you want to copy & paste text from another source (another row or table, HTML, Notepad, etc.) and not have your text truncated at the first CR, I found that the solution (Programmer's Notepad) referred to at the following link works with SSMS for SQL Server 2008 using varchar & nvarchar column types.

http://dbaspot.com/sqlserver-programming/409451-how-i-enter-linefeed-when-modifying-text-field-2.html#post1523145

The author of the post (dbaspot) mentions something about creating SQL queries - not sure what he means. Just follow the intructions about Programmer's Notepad and you can copy & paste text to and from SSMS and retain the LFs both ways (using Programmer's Notepad, not Notepad). To have the text display properly in HTML you must add CRs to the text copied to SSMS. The best way to do this is by executing an UPDATE statement using the REPLACE function to add CRs as follows:

UPDATE table_name
SET column_name = REPLACE(column_name , CHAR(10), CHAR(13) + CHAR(10)).

SQL RANK() over PARTITION on joined tables

As the rank doesn't depend at all from the contacts

RANKED_RSLTS

 QRY_ID  |  RES_ID  |  SCORE |  RANK
-------------------------------------
   A     |    1     |    15  |   3
   A     |    2     |    32  |   1
   A     |    3     |    29  |   2
   C     |    7     |    61  |   1
   C     |    9     |    30  |   2

Thus :

SELECT
    C.*
    ,R.SCORE
    ,MYRANK
FROM CONTACTS C LEFT JOIN
(SELECT  *,
 MYRANK = RANK() OVER (PARTITION BY QRY_ID ORDER BY SCORE DESC)
  FROM RSLTS)  R
ON C.RES_ID = R.RES_ID
AND C.QRY_ID = R.QRY_ID

Access-Control-Allow-Origin: * in tomcat

The issue arose because of not including jar file as part of the project. I was just including it in tomcat lib. Using the below in web.xml works now:

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>
        org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
</filter>

 <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>

    <init-param>
        <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportsCredentials</param-name>
        <param-value>false</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedHeaders</param-name>
        <param-value>accept, authorization, origin</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedMethods</param-name>
        <param-value>GET, POST, HEAD, OPTIONS</param-value>
    </init-param>
</filter>


<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

And the below in your project dependency:

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>1.3.2</version>
</dependency>

Python threading.timer - repeat function every 'n' seconds

I like right2clicky's answer, especially in that it doesn't require a Thread to be torn down and a new one created every time the Timer ticks. In addition, it's an easy override to create a class with a timer callback that gets called periodically. That's my normal use case:

class MyClass(RepeatTimer):
    def __init__(self, period):
        super().__init__(period, self.on_timer)

    def on_timer(self):
        print("Tick")


if __name__ == "__main__":
    mc = MyClass(1)
    mc.start()
    time.sleep(5)
    mc.cancel()

Sum values from an array of key-value pairs in JavaScript

Or in ES6

values.reduce((a, b) => a + b),

example:

[1,2,3].reduce((a, b)=>a+b) // return 6