Programs & Examples On #Dynatree

Dynatree is a JavaScript tree view plugin for jQuery with support for persistence, keyboard, multiple selection, drag and drop, and dynamic Ajax loading.

Set custom attribute using JavaScript

Please use dataset

var article = document.querySelector('#electriccars'),
    data = article.dataset;

// data.columns -> "3"
// data.indexnumber -> "12314"
// data.parent -> "cars"

so in your case for setting data:

getElementById('item1').dataset.icon = "base2.gif";

How can I test that a variable is more than eight characters in PowerShell?

You can also use -match against a Regular expression. Ex:

if ($dbUserName -match ".{8}" )
{
    Write-Output " Please enter more than 8 characters "
    $dbUserName=read-host " Re-enter database user name"
}

Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.

How to enable named/bind/DNS full logging?

Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

Also make sure you’re checking correct directory if your bind is chrooted.

src absolute path problem

<img src="file://C:/wamp/www/site/img/mypicture.jpg"/>

String vs. StringBuilder

Yes, the performance difference is significant. See the KB article "How to improve string concatenation performance in Visual C#".

I have always tried to code for clarity first, and then optimize for performance later. That's much easier than doing it the other way around! However, having seen the enormous performance difference in my applications between the two, I now think about it a little more carefully.

Luckily, it's relatively straightforward to run performance analysis on your code to see where you're spending the time, and then to modify it to use StringBuilder where needed.

twitter bootstrap text-center when in xs mode

@media (max-width: 767px) {
    footer .text-right, 
    footer .text-left {
        text-align: center;
    } 
}

I updated @loddn's answer, making two changes

  • max-width of xs screens in bootstrap is 767px (768px is the start of sm screens)
  • (this one is a matter of preference) I used footer instead of col-* so that if the column widths change, the CSS doesn't need to be updated.

What is a "callable"?

To check function or method of class is callable or not that means we can call that function.

Class A:
    def __init__(self,val):
        self.val = val
    def bar(self):
        print "bar"

obj = A()      
callable(obj.bar)
True
callable(obj.__init___)
False
def foo(): return "s"
callable(foo)
True
callable(foo())
False

Check if element is in the list (contains)

std::list does not provide a search method. You can iterate over the list and check if the element exists or use std::find. But I think for your situation std::set is more preferable. The former will take O(n) time but later will take O(lg(n)) time to search.

You can simply use:

int my_var = 3;
std::set<int> mySet {1, 2, 3, 4};
if(mySet.find(myVar) != mySet.end()){
      //do whatever
}

Allowing Untrusted SSL Certificates with HttpClient

I don't have an answer, but I do have an alternative.

If you use Fiddler2 to monitor traffic AND enable HTTPS Decryption, your development environment will not complain. This will not work on WinRT devices, such as Microsoft Surface, because you cannot install standard apps on them. But your development Win8 computer will be fine.

To enable HTTPS encryption in Fiddler2, go to Tools > Fiddler Options > HTTPS (Tab) > Check "Decrypt HTTPS Traffic".

I'm going to keep my eye on this thread hoping for someone to have an elegant solution.

How to open a web page from my application?

The old school way ;)

public static void openit(string x) {
   System.Diagnostics.Process.Start("cmd", "/C start" + " " + x); 
}

Use: openit("www.google.com");

How do I convert datetime.timedelta to minutes, hours in Python?

datetime.timedelta(hours=1, minutes=10)
#python 2.7

Background position, margin-top?

 background-image: url(/images/poster.png);
 background-position: center;
 background-position-y: 50px;
 background-repeat: no-repeat;

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

I had the same issue, and the solution is very simple, just change to git bash from cmd or other windows command line tools. Windows sometimes does not work well with git npm dependencies.

git: updates were rejected because the remote contains work that you do not have locally

git pull --rebase origin master

git push origin master


git push -f origin master

Warning git push -f origin master

  • forcefully pushes on existing repository and also delete previous repositories so if you don`t need previous versions than this might be helpful

TypeError: 'NoneType' object has no attribute '__getitem__'

move.CompleteMove() does not return a value (perhaps it just prints something). Any method that does not return a value returns None, and you have assigned None to self.values.

Here is an example of this:

>>> def hello(x):
...    print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>

You'll note y doesn't print anything, because its None (the only value that doesn't print anything on the interactive prompt).

Renaming the current file in Vim

sav person.haml_spec.rb | call delete(expand('#'))

How can I disable HREF if onclick is executed?

You can use this simple code:

<a href="" onclick="return false;">add new action</a><br>

Selecting text in an element (akin to highlighting with your mouse)

Jason's code can not be used for elements inside an iframe (as the scope differs from window and document). I fixed that problem and I modified it in order to be used as any other jQuery plugin (chainable):

Example 1: Selection of all text inside < code > tags with single click and add class "selected":

$(function() {
    $("code").click(function() {
        $(this).selText().addClass("selected");
    });
});

Example 2: On button click, select an element inside an Iframe:

$(function() {
    $("button").click(function() {
        $("iframe").contents().find("#selectme").selText();
    });
});

Note: remember that the iframe source should reside in the same domain to prevent security errors.

jQuery Plugin:

jQuery.fn.selText = function() {
    var obj = this[0];
    if ($.browser.msie) {
        var range = obj.offsetParent.createTextRange();
        range.moveToElementText(obj);
        range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = obj.ownerDocument.defaultView.getSelection();
        var range = obj.ownerDocument.createRange();
        range.selectNodeContents(obj);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if ($.browser.safari) {
        var selection = obj.ownerDocument.defaultView.getSelection();
        selection.setBaseAndExtent(obj, 0, obj, 1);
    }
    return this;
}

I tested it in IE8, Firefox, Opera, Safari, Chrome (current versions). I'm not sure if it works in older IE versions (sincerely I don't care).

How to respond to clicks on a checkbox in an AngularJS directive?

Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.

Two important pieces that are needed are:

    $scope.entities = [{
    "title": "foo",
    "id": 1
}, {
    "title": "bar",
    "id": 2
}, {
    "title": "baz",
    "id": 3
}];
$scope.selected = [];

How to declare a constant in Java

  1. You can use an enum type in Java 5 and onwards for the purpose you have described. It is type safe.
  2. A is an instance variable. (If it has the static modifier, then it becomes a static variable.) Constants just means the value doesn't change.
  3. Instance variables are data members belonging to the object and not the class. Instance variable = Instance field.

If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.

Java 5 and up enum type

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public String toString(){
    return this.color;
  }
}

If you wish to change the value of the enum you have created, provide a mutator method.

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public void setColor(String color){
    this.color = color;
  }

  public String toString(){
    return this.color;
  }
}

Example of accessing:

public static void main(String args[]){
  System.out.println(Color.RED.getColor());

  // or

  System.out.println(Color.GREEN);
}

VBScript How can I Format Date?

'for unique file names I use

Dim ts, logfile, thisScript

thisScript = LEFT(Wscript.ScriptName,LEN(Wscript.ScriptName)-4) ' assuming .vbs extension

ts = timeStamp
logfile = thisScript & "_" & ts

' ======
Function timeStamp() 
    timeStamp = Year(Now) & "-" & _
    Right("0" & Month(Now),2)  & "-" & _
    Right("0" & Day(Now),2)  & "_" & _  
    Right("0" & Hour(Now),2) & _
    Right("0" & Minute(Now),2) '    '& _    Right("0" & Second(Now),2) 
End Function
' ======

MongoDB running but can't connect using shell

If your mongoDB server(remote server)'s version is greater then 4.0.3, then you will face this issue. Hence you should replace your current mongo-client shell with below mongo :

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org

Then you mongo client will be able to connect your remove mongodb

How to break long string to multiple lines

I know that this is super-duper old, but on the off chance that someone comes looking for this, as of Visual Basic 14, Vb supports interpolation. Sooooo cool!

Example:

SQLQueryString = $"
   Insert into Employee values( 
       {txtEmployeeNo}, 
       {txtContractsStartDate},
       {txtSeatNo},
       {txtFloor},
       {txtLeaves}
)"

It works. Documentation Here

Edit: After writing this, I realized that the OP was talking about VBA. This will not work in VBA!!! However, I will leave this up here, because as someone new to VB, I stumbled upon this question looking for a solution to just this problem in VB.net. If this helps someone else, great.

Android studio logcat nothing to show


Try to close the project and re-open it .It worked for me. Logs will be reappear.

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

I'm pretty sure this isn't the BEST way, but you could set the MinimumSize and MaximimSize properties to the same value. That will stop it.

How to hide "Showing 1 of N Entries" with the dataTables.js library

try this for hide

$('#table_id').DataTable({
  "info": false
});

and try this for change label

$('#table_id').DataTable({
 "oLanguage": {
               "sInfo" : "Showing _START_ to _END_ of _TOTAL_ entries",// text you want show for info section
            },

});

Invoke-WebRequest, POST with parameters

Put your parameters in a hash table and pass them like this:

$postParams = @{username='me';moredata='qwerty'}
Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body $postParams

Convert a JSON String to a HashMap

If you hate recursion - using a Stack and javax.json to convert a Json String into a List of Maps:

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.json.Json;
import javax.json.stream.JsonParser;

public class TestCreateObjFromJson {
    public static List<Map<String,Object>> extract(InputStream is) {
        List extracted = new ArrayList<>();
        JsonParser parser = Json.createParser(is);

        String nextKey = "";
        Object nextval = "";
        Stack s = new Stack<>();
        while(parser.hasNext()) {
            JsonParser.Event event = parser.next();
            switch(event) {
                case START_ARRAY :  List nextList = new ArrayList<>();
                                    if(!s.empty()) {
                                        // If this is not the root object, add it to tbe parent object
                                        setValue(s,nextKey,nextList);
                                    }
                                    s.push(nextList);
                                    break;
                case START_OBJECT : Map<String,Object> nextMap = new HashMap<>();
                                    if(!s.empty()) {
                                        // If this is not the root object, add it to tbe parent object
                                        setValue(s,nextKey,nextMap);
                                    }
                                    s.push(nextMap);
                                    break;
                case KEY_NAME : nextKey = parser.getString();
                                break;
                case VALUE_STRING : setValue(s,nextKey,parser.getString());
                                    break;
                case VALUE_NUMBER : setValue(s,nextKey,parser.getLong());
                                    break;
                case VALUE_TRUE :   setValue(s,nextKey,true);
                                    break;
                case VALUE_FALSE :  setValue(s,nextKey,false);
                                    break;
                case VALUE_NULL :   setValue(s,nextKey,"");
                                    break;
                case END_OBJECT :   
                case END_ARRAY  :   if(s.size() > 1) {
                                        // If this is not a root object, move up
                                        s.pop(); 
                                    } else {
                                        // If this is a root object, add ir ro rhw final 
                                        extracted.add(s.pop()); 
                                    }
                default         :   break;
            }
        }

        return extracted;
    }

    private static void setValue(Stack s, String nextKey, Object v) {
        if(Map.class.isAssignableFrom(s.peek().getClass()) ) ((Map)s.peek()).put(nextKey, v);
        else ((List)s.peek()).add(v);
    }
}

How can I fetch all items from a DynamoDB table without specifying the primary key?

This C# code is to fetch all items from a dynamodb table using BatchGet or CreateBatchGet

        string tablename = "AnyTableName"; //table whose data you want to fetch

        var BatchRead = ABCContext.Context.CreateBatchGet<ABCTable>(  

            new DynamoDBOperationConfig
            {
                OverrideTableName = tablename; 
            });

        foreach(string Id in IdList) // in case you are taking string from input
        {
            Guid objGuid = Guid.Parse(Id); //parsing string to guid
            BatchRead.AddKey(objGuid);
        }

        await BatchRead.ExecuteAsync();
        var result = BatchRead.Results;

// ABCTable is the table modal which is used to create in dynamodb & data you want to fetch

How to remove empty cells in UITableView?

or you can call tableView method to set the footer height in 1 point, and it will add an last line, but you can hide it too, by setting footer background color.

code:

func tableView(tableView: UITableView,heightForFooterInSection section: Int) -> CGFloat {
     return 1
}

looks like last line

How to zip a file using cmd line?

If you are using Ubuntu Linux:

  1. Install zip

    sudo apt-get install zip
    
  2. Zip your folder:

    zip -r {filename.zip} {foldername}
    

If you are using Microsoft Windows:

Windows does not come with a command-line zip program, despite Windows Explorer natively supporting Zip files since the Plus! pack for Windows 98.

I recommend the open-source 7-Zip utility which includes a command-line executable and supports many different archive file types, especially its own *.7z format which offers superior compression ratios to traditional (PKZIP) *.zip files:

  1. Download 7-Zip from the 7-Zip home page

  2. Add the path to 7z.exe to your PATH environment variable. See this QA: How to set the path and environment variables in Windows

  3. Open a new command-prompt window and use this command to create a PKZIP *.zip file:

    7z a -tzip {yourfile.zip} {yourfolder}
    

Cross-platform Java:

If you have the Java JDK installed then you can use the jar utility to create Zip files, as *.jar files are essentially just renamed *.zip (PKZIP) files:

jar -cfM {yourfile.zip} {yourfolder}

Explanation: * -c compress * -f specify filename * -M do not include a MANIFEST file

Uncaught ReferenceError: $ is not defined error in jQuery

Scripts are loaded in the order you have defined them in the HTML.

Therefore if you first load:

<script type="text/javascript" src="./javascript.js"></script>

without loading jQuery first, then $ is not defined.

You need to first load jQuery so that you can use it.

I would also recommend placing your scripts at the bottom of your HTML for performance reasons.

Is there a simple, elegant way to define singletons?

There are also some interesting articles on the Google Testing blog, discussing why singleton are/may be bad and are an anti-pattern:

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

I had the same error, with URLs containing non-ascii chars (bytes with values > 128), my solution:

url = url.decode('utf8').encode('utf-8')

Note: utf-8, utf8 are simply aliases . Using only 'utf8' or 'utf-8' should work in the same way

In my case, worked for me, in Python 2.7, I suppose this assignment changed 'something' in the str internal representation--i.e., it forces the right decoding of the backed byte sequence in url and finally puts the string into a utf-8 str with all the magic in the right place. Unicode in Python is black magic for me. Hope useful

Calculate date from week number

Personally I'd take advantage of the culture info to get the day of the week and loop down to the culture's first day of the week. I'm not sure if I'm explaining it properly, here's an example:

    public DateTime GetFirstDayOfWeek(int year, int weekNumber)
    {
        return GetFirstDayOfWeek(year, weekNumber, Application.CurrentCulture);
    }

    public DateTime GetFirstDayOfWeek(int year, int weekNumber,
        System.Globalization.CultureInfo culture)
    {
        System.Globalization.Calendar calendar = culture.Calendar;
        DateTime firstOfYear = new DateTime(year, 1, 1, calendar);
        DateTime targetDay = calendar.AddWeeks(firstOfYear, weekNumber);
        DayOfWeek firstDayOfWeek = culture.DateTimeFormat.FirstDayOfWeek;

        while (targetDay.DayOfWeek != firstDayOfWeek)
        {
            targetDay = targetDay.AddDays(-1);
        }

        return targetDay;
    }

Find when a file was deleted in Git

Git log but you need to prefix the path with --

Eg:

dan-mac:test dani$ git log file1.txt
fatal: ambiguous argument 'file1.txt': unknown revision or path not in the working tree.

dan-mac:test dani$ git log -- file1.txt
 commit 0f7c4e1c36e0b39225d10b26f3dea40ad128b976
 Author: Daniel Palacio <[email protected]>
 Date:   Tue Jul 26 23:32:20 2011 -0500

 foo

Setting up Eclipse with JRE Path

You can add this line to eclipse.ini :

-vm 
D:/work/Java/jdk1.6.0_13/bin/javaw.exe  <-- change to your JDK actual path
-vmargs <-- needs to be after -vm <path>

But it's worth setting JAVA_HOME and JRE_HOME anyway because it may not work as if the path environment points to a different java version.

Because the next one to complain will be Maven, etc.

How can I split a string into segments of n characters?

function chunk(er){
return er.match(/.{1,75}/g).join('\n');
}

Above function is what I use for Base64 chunking. It will create a line break ever 75 characters.

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

Any future date in JavaScript (postman test uses JavaScript) can be retrieved as:

var dateNow = new Date();  
var twoWeeksFutureDate = new Date(dateNow.setDate(dateNow.getDate() + 14)).toISOString();

postman.setEnvironmentVariable("future-date", twoWeeksFutureDate);

How can I create a dynamically sized array of structs?

Every coder need to simplify their code to make it easily understood....even for beginners.

So array of structures using dynamically is easy, if you understand the concepts.

// Dynamically sized array of structures

#include <stdio.h>
#include <stdlib.h>

struct book 
{
    char name[20];
    int p;
};              //Declaring book structure

int main () 
{
    int n, i;      

    struct book *b;     // Initializing pointer to a structure
    scanf ("%d\n", &n);

    b = (struct book *) calloc (n, sizeof (struct book));   //Creating memory for array of structures dynamically

    for (i = 0; i < n; i++)
    {
        scanf ("%s %d\n", (b + i)->name, &(b + i)->p);  //Getting values for array of structures (no error check)
    }          

    for (i = 0; i < n; i++)
    {
        printf ("%s %d\t", (b + i)->name, (b + i)->p);  //Printing values in array of structures
    }

    scanf ("%d\n", &n);     //Get array size to re-allocate    
    b = (struct book *) realloc (b, n * sizeof (struct book));  //change the size of an array using realloc function
    printf ("\n");

    for (i = 0; i < n; i++)
    {
        printf ("%s %d\t", (b + i)->name, (b + i)->p);  //Printing values in array of structures
    }

    return 0;
}   

Visual Studio popup: "the operation could not be completed"

VS 2015 -> Deleting all the files in the ComponentModelCache worked for me:

C:\Users\**username**\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

This error can be resolved by adding MessageBoxOptions.ServiceNotification.

MessageBox.Show(msg, "Print Error", System.Windows.Forms.MessageBoxButtons.YesNo, 
   System.Windows.Forms.MessageBoxIcon.Error,     
   System.Windows.Forms.MessageBoxDefaultButton.Button1, 
   System.Windows.Forms.MessageBoxOptions.ServiceNotification); 

But it is not going to show any dialog box if your web application is installed on IIS or server.Because in IIS or server it is hosted on worker process which dont have any desktop.

Android Imagebutton change Image OnClick

<ImageButton android:src="@drawable/image_btn_src" ... />

image_btn_src.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/icon_pressed"/>
<item android:state_pressed="false" android:drawable="@drawable/icon_unpressed"/>
</selector>

Import SQL file by command line in Windows 7

If you are using Windows PowerShell you may get the error:

The '<' operator is reserved for future use.

In that case just type the command:

cmd

To switch to the cmd shell and then retype the command and it will work.

c:\xampp\mysql\bin\mysql -u root -p my_database < my_database_dump.sql

To get back to PowerShell type:

exit

Retaining file permissions with Git

In pre-commit/post-checkout an option would be to use "mtree" (FreeBSD), or "fmtree" (Ubuntu) utility which "compares a file hierarchy against a specification, creates a specification for a file hierarchy, or modifies a specification."

The default set are flags, gid, link, mode, nlink, size, time, type, and uid. This can be fitted to the specific purpose with -k switch.

Get encoding of a file in Windows

EncodingChecker

File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.

File Encoding Checker requires .NET 4 or above to run.

How to add a where clause in a MySQL Insert statement?

In an insert statement you wouldn't have an existing row to do a where claues on? You are inserting a new row, did you mean to do an update statment?

update users set username='JACK' and password='123' WHERE id='1';

Vagrant stuck connection timeout retrying

My solution to this issue was that my old laptop was taking wayyyyyyyyyyy too long to start up. I opened Virtual Box, connected to the box and waited for the screen to load. Took about 8 minutes.

Then it connected and mounted my folders and went ahead.

just be patient sometimes!

What is the standard Python docstring format?

Docstring conventions are in PEP-257 with much more detail than PEP-8.

However, docstrings seem to be far more personal than other areas of code. Different projects will have their own standard.

I tend to always include docstrings, because they tend to demonstrate how to use the function and what it does very quickly.

I prefer to keep things consistent, regardless of the length of the string. I like how to code looks when indentation and spacing are consistent. That means, I use:

def sq(n):
    """
    Return the square of n. 
    """
    return n * n

Over:

def sq(n):
    """Returns the square of n."""
    return n * n

And tend to leave off commenting on the first line in longer docstrings:

def sq(n):
    """
    Return the square of n, accepting all numeric types:

    >>> sq(10)
    100

    >>> sq(10.434)
    108.86835599999999

    Raises a TypeError when input is invalid:

    >>> sq(4*'435')
    Traceback (most recent call last):
      ...
    TypeError: can't multiply sequence by non-int of type 'str'

    """
    return n*n

Meaning I find docstrings that start like this to be messy.

def sq(n):
    """Return the squared result. 
    ...

What is a magic number, and why is it bad?

@eed3si9n: I'd even suggest that '1' is a magic number. :-)

A principle that's related to magic numbers is that every fact your code deals with should be declared exactly once. If you use magic numbers in your code (such as the password length example that @marcio gave, you can easily end up duplicating that fact, and when your understand of that fact changes you've got a maintenance problem.

How to call a parent class function from derived class function?

If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()

void Base::FooBar()
{
   printf("in Base\n");
}

void ChildOfBase::FooBar()
{
  Base::FooBar();
}

Integer value comparison

well i might be late on this but i would like to share something:

Given the input: System.out.println(isGreaterThanZero(-1));

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.compareTo(0) > 0;
}

Returns false

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.intValue() > 0;
}

Returns true So i think in yourcase 'compareTo' will be more accurate.

QtCreator: No valid kits found

No valid Kits found The problem occurs because qt-creator don't know the versions of your qt, your compiler or your debugger. First off, let's solve the Qt versions. It may normally solve the others too ;).

You try to create a new project, run select a kit and then there is no kit available in the list.

Follow the steps:

  1. Execute in your terminal the command: sudo apt-get install qt5-default to install qt version 5.
  2. Verify the version of your Qt and the location of your qmake file. Do this by executing in your terminal the command qmake --version. You may have a result similar to this line. QMake version 3.1 Using Qt version 5.9.5 in /usr/lib/x86_64-linux-gnu. What's important here is the location /usr/lib/x86_64-linux-gnu.
  3. Open your Qt-creator.
  4. Go to "Tools>Options" or "Outils>Options"
  5. Select the Qt Versions combobox and select and click "Add" or "Ajouter"
  6. Then find the qmake file in the location of step 2. Here /usr/lib/x86_64-linux-gnu/qt5/bin/ here you have the qmake file for qt5. Open it, click Apply.
  7. Go to "Kits" combobox. Select Desktop(by default) or Desktop(par défaut). Then scroll down to the button to select Qt version: and list down to select the version you just add. 8.Then apply all. Check your compiler and debugger and it's ok. You're done.

Yes I ...

Hope it's help ;)

Setting PHP tmp dir - PHP upload not working

The problem described here was solved by me quite a long time ago but I don't really remember what was the main reason that uploads weren't working. There were multiple things that needed fixing so the upload could work. I have created checklist that might help others having similar problems and I will edit it to make it as helpful as possible. As I said before on chat, I was working on embedded system, so some points may be skipped on non-embedded systems.

  • Check upload_tmp_dir in php.ini. This is directory where PHP stores temporary files while uploading.

  • Check open_basedir in php.ini. If defined it limits PHP read/write rights to specified path and its subdirectories. Ensure that upload_tmp_dir is inside this path.

  • Check post_max_size in php.ini. If you want to upload 20 Mbyte files, try something a little bigger, like post_max_size = 21M. This defines largest size of POST message which you are probably using during upload.

  • Check upload_max_filesize in php.ini. This specifies biggest file that can be uploaded.

  • Check memory_limit in php.ini. That's the maximum amount of memory a script may consume. It's quite obvious that it can't be lower than upload size (to be honest I'm not quite sure about it-PHP is probably buffering while copying temporary files).

  • Ensure that you're checking the right php.ini file that is one used by PHP on your webserver. The best solution is to execute script with directive described here http://php.net/manual/en/function.php-ini-loaded-file.php (php_ini_loaded_file function)

  • Check what user php runs as (See here how to do it: How to check what user php is running as? ). I have worked on different distros and servers. Sometimes it is apache, but sometimes it can be root. Anyway, check that this user has rights for reading and writing in the temporary directory and directory that you're uploading into. Check all directories in the path in case you're uploading into subdirectory (for example /dir1/dir2/-check both dir1 and dir2.

  • On embedded platforms you sometimes need to restrict writing to root filesystem because it is stored on flash card and this helps to extend life of this card. If you are using scripts to enable/disable file writes, ensure that you enable writing before uploading.

  • I had serious problems with PHP >5.4 upload monitoring based on sessions (as described here http://phpmaster.com/tracking-upload-progress-with-php-and-javascript/ ) on some platforms. Try something simple at first (like here: http://www.dzone.com/snippets/very-simple-php-file-upload ). If it works, you can try more sophisticated mechanisms.

  • If you make any changes in php.ini remember to restart server so the configuration will be reloaded.

Compare two Timestamp in java

if (!mytime.before(fromtime) && !mytime.after(totime))

substring index range

Like you I didn't find it came naturally. I normally still have to remind myself that

  • the length of the returned string is

    lastIndex - firstIndex

  • that you can use the length of the string as the lastIndex even though there is no character there and trying to reference it would throw an Exception

so

"University".substring(6, 10)

returns the 4-character string "sity" even though there is no character at position 10.

Recursive query in SQL Server

Something like this (not tested)

with match_groups as (

  select product_id, 
         matching_product_id,
         product_id as group_id
  from matches
  where product_id not in (select matching_product_id from matches)

  union all

  select m.product_id, m.matching_product_id, p.group_id
  from matches m
    join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;

How to create a delay in Swift?

Instead of a sleep, which will lock up your program if called from the UI thread, consider using NSTimer or a dispatch timer.

But, if you really need a delay in the current thread:

do {
    sleep(4)
}

This uses the sleep function from UNIX.

How to dispatch a Redux action with a timeout?

This may be a bit off-topic but I want to share it here because I simply wanted to remove Alerts from state after a given timeout i.e. auto hiding alerts/notifications.

I ended up using setTimeout() within the <Alert /> component, so that it can then call and dispatch a REMOVE action on given id.

export function Alert(props: Props) {
  useEffect(() => {
    const timeoutID = setTimeout(() => {
      dispatchAction({
        type: REMOVE,
        payload: {
          id: id,
        },
      });
    }, timeout ?? 2000);
    return () => clearTimeout(timeoutID);
  }, []);
  return <AlertComponent {...props} />;
}

String concatenation in MySQL

MySQL is different from most DBMSs use of + or || for concatenation. It uses the CONCAT function:

SELECT CONCAT(first_name, " ", last_name) AS Name FROM test.student

As @eggyal pointed out in comments, you can enable string concatenation with the || operator in MySQL by setting the PIPES_AS_CONCAT SQL mode.

PHP Checking if the current date is before or after a set date

if( strtotime($database_date) > strtotime('now') ) {
...

HTML/CSS - Adding an Icon to a button

You could add a span before the link with a specific class like so:

<div class="btn btn_red"><span class="icon"></span><a href="#">Crimson</a><span></span></div>

And then give that a specific width and a background image just like you are doing with the button itself.

.btn span.icon {
    background: url(imgs/icon.png) no-repeat;
    float: left;
    width: 10px;
    height: 40px;
}

I am no CSS guru but off the top of my head I think that should work.

How to rename a file using Python

If you are Using Windows and you want to rename your 1000s of files in a folder then: You can use the below code. (Python3)

import os

path = os.chdir(input("Enter the path of the Your Image Folder :  ")) #Here put the path of your folder where your images are stored

image_name = input("Enter your Image name : ") #Here, enter the name you want your images to have

i = 0

for file in os.listdir(path):

    new_file_name = image_name+"_" + str(i) + ".jpg" #here you can change the extention of your renmamed file.
    os.rename(file,new_file_name)

    i = i + 1

input("Renamed all Images!!")

Android, How to create option Menu

please see :==

private int group1Id = 1;

int homeId = Menu.FIRST;
int profileId = Menu.FIRST +1;
int searchId = Menu.FIRST +2;
int dealsId = Menu.FIRST +3;
int helpId = Menu.FIRST +4;
int contactusId = Menu.FIRST +5;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(group1Id, homeId, homeId, "").setIcon(R.drawable.home_menu);
    menu.add(group1Id, profileId, profileId, "").setIcon(R.drawable.profile_menu);
    menu.add(group1Id, searchId, searchId, "").setIcon(R.drawable.search_menu);
    menu.add(group1Id, dealsId, dealsId, "").setIcon(R.drawable.deals_menu);
    menu.add(group1Id, helpId, helpId, "").setIcon(R.drawable.help_menu);
    menu.add(group1Id, contactusId, contactusId, "").setIcon(R.drawable.contactus_menu);

    return super.onCreateOptionsMenu(menu); 
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 1:
        // write your code here
        Toast msg = Toast.makeText(MainHomeScreen.this, "Menu 1", Toast.LENGTH_LONG);
        msg.show();
        return true;

    case 2:
        // write your code here
        return true;

    case 3:
        // write your code here
        return true;

    case 4:
        // write your code here
        return true;

    case 5:
        // write your code here
        return true;

    case 6:
        // write your code here
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

For me the problem was that I was using different versions of Python in the same Eclipse project. My setup was not consistent with the Project Properties and the Run Configuration Python versions.

In Project > Properties > PyDev, I had the Interpreter set to Python2.7.11.

In Run Configurations > Interpreter, I was using the Default Interpreter. Changing it to Python 2.7.11 fixed the problem.

Join String list elements with a delimiter in one step

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

How do you get the footer to stay at the bottom of a Web page?

For this question many of the answers I have seen are clunky, hard to implement and inefficient so I thought I'd take a shot at it and come up with my own solution which is just a tiny bit of css and html

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.body {_x000D_
  min-height: calc(100% - 2rem);_x000D_
  width: 100%;_x000D_
  background-color: grey;_x000D_
}_x000D_
.footer {_x000D_
  height: 2rem;_x000D_
  width: 100%;_x000D_
  background-color: yellow;_x000D_
}
_x000D_
<body>_x000D_
  <div class="body">test as body</div>_x000D_
  <div class="footer">test as footer</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

this works by setting the height of the footer and then using css calc to work out the minimum height the page can be with the footer still at the bottom, hope this helps some people :)

Is there "\n" equivalent in VBscript?

As David and Remou pointed out, vbCrLf if you want a carriage-return-linefeed combination. Otherwise, Chr(13) and Chr(10) (although some VB-derivatives have vbCr and vbLf; VBScript may well have those, worth checking before using Chr).

How to implement a Navbar Dropdown Hover in Bootstrap v4?

<div style="width: 100%; overflow: scroll;"><table class="table table-striped table-bordered" style="font-size:12px">

Javascript Drag and drop for touch devices

You can use the Jquery UI for drag and drop with an additional library that translates mouse events into touch which is what you need, the library I recommend is https://github.com/furf/jquery-ui-touch-punch, with this your drag and drop from Jquery UI should work on touch devises

or you can use this code which I am using, it also converts mouse events into touch and it works like magic.

function touchHandler(event) {
    var touch = event.changedTouches[0];

    var simulatedEvent = document.createEvent("MouseEvent");
        simulatedEvent.initMouseEvent({
        touchstart: "mousedown",
        touchmove: "mousemove",
        touchend: "mouseup"
    }[event.type], true, true, window, 1,
        touch.screenX, touch.screenY,
        touch.clientX, touch.clientY, false,
        false, false, false, 0, null);

    touch.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init() {
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);
}

And in your document.ready just call the init() function

code found from Here

How to give ASP.NET access to a private key in a certificate in the certificate store?

For me, it was nothing more than re-importing the certificate with "Allow private key to be exported" checked.

I guess it is necessary, but it does make me nervous as it is a third party app accessing this certificate.

"Thinking in AngularJS" if I have a jQuery background?

They're apples and oranges. You don't want to compare them. They're two different things. AngularJs has already jQuery lite built in which allows you to perform basic DOM manipulation without even including the full blown jQuery version.

jQuery is all about DOM manipulation. It solves all the cross browser pain otherwise you will have to deal with but it's not a framework that allows you to divide your app into components like AngularJS.

A nice thing about AngularJs is that it allows you to separate/isolate the DOM manipulation in the directives. There are built-in directives ready for you to use such as ng-click. You can create your own custom directives that will contain all your view logic or DOM manipulation so you don't end up mingle DOM manipulation code in the controllers or services that should take care of the business logic.

Angular breaks down your app into - Controllers - Services - Views - etc.

and there is one more thing, that's the directive. It's an attribute you can attach to any DOM element and you can go nuts with jQuery within it without worrying about your jQuery ever conflicts with AngularJs components or messes up with its architecture.

I heard from a meetup I attended, one of the founders of Angular said they worked really hard to separate out the DOM manipulation so do not try to include them back in.

Rollback to an old Git commit in a public repo

You can find the commit id related to each commit in the commits section of GitHub/BitBucket/Gitlab. Its very simple, suppose your commit id is 5889575 then if you want to go back to this part in your code then you simply need to type

git checkout 5889575 .

This will take you to that point of time in your code.

Parse an URL in JavaScript

Try this:

var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]

Regular expression that doesn't contain certain string

In general it's a pain to write a regular expression not containing a particular string. We had to do this for models of computation - you take an NFA, which is easy enough to define, and then reduce it to a regular expression. The expression for things not containing "cat" was about 80 characters long.

Edit: I just finished and yes, it's:

aa([^a] | a[^a])aa

Here is a very brief tutorial. I found some great ones before, but I can't see them anymore.

check if a std::vector contains a certain object?

See question: How to find an item in a std::vector?

You'll also need to ensure you've implemented a suitable operator==() for your object, if the default one isn't sufficient for a "deep" equality test.

How to get unique values in an array

Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains and unique

_x000D_
_x000D_
Array.prototype.contains = function(v) {_x000D_
  for (var i = 0; i < this.length; i++) {_x000D_
    if (this[i] === v) return true;_x000D_
  }_x000D_
  return false;_x000D_
};_x000D_
_x000D_
Array.prototype.unique = function() {_x000D_
  var arr = [];_x000D_
  for (var i = 0; i < this.length; i++) {_x000D_
    if (!arr.contains(this[i])) {_x000D_
      arr.push(this[i]);_x000D_
    }_x000D_
  }_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];_x000D_
var uniques = duplicates.unique(); // result = [1,3,4,2,8]_x000D_
_x000D_
console.log(uniques);
_x000D_
_x000D_
_x000D_

For more reliability, you can replace contains with MDN's indexOf shim and check if each element's indexOf is equal to -1: documentation

How to find the width of a div using vanilla JavaScript?

Actually, you don't have to use document.getElementById("mydiv") .
You can simply use the id of the div, like:

var w = mydiv.clientWidth;
or
var w = mydiv.offsetWidth;
etc.

How to remove specific session in asp.net?

HttpContext.Current.Session.Remove("sessionname");

it works for me

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

How to Iterate over a Set/HashSet without an Iterator?

To demonstrate, consider the following set, which holds different Person objects:

Set<Person> people = new HashSet<Person>();
people.add(new Person("Tharindu", 10));
people.add(new Person("Martin", 20));
people.add(new Person("Fowler", 30));

Person Model Class

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //TODO - getters,setters ,overridden toString & compareTo methods

}
  1. The for statement has a form designed for iteration through Collections and arrays .This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read.
for(Person p:people){
  System.out.println(p.getName());
}
  1. Java 8 - java.lang.Iterable.forEach(Consumer)
people.forEach(p -> System.out.println(p.getName()));
default void forEach(Consumer<? super T> action)

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller. Implementation Requirements:

The default implementation behaves as if: 

for (T t : this)
     action.accept(t);

Parameters: action - The action to be performed for each element

Throws: NullPointerException - if the specified action is null

Since: 1.8

Server configuration by allow_url_fopen=0 in

Use this code in your php script (first lines)

ini_set('allow_url_fopen',1);

How to add double quotes to a string that is inside a variable?

In C# you can use:

 string1 = @"Your ""Text"" Here";
 string2 = "Your \"Text\" Here";

Angular2: Cannot read property 'name' of undefined

You just needed to read a little further and you would have been introduced to the *ngIf structural directive.

selectedHero.name doesn't exist yet because the user has yet to select a hero so it returns undefined.

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
  <div><label>id: </label>{{selectedHero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="selectedHero.name" placeholder="name"/>
  </div>
</div>

The *ngIf directive keeps selectedHero off the DOM until it is selected and therefore becomes truthy.

This document helped me understand structural directives.

Chaining multiple filter() in Django, is this a bug?

These two style of filtering are equivalent in most cases, but when query on objects base on ForeignKey or ManyToManyField, they are slightly different.

Examples from the documentation.

model
Blog to Entry is a one-to-many relation.

from django.db import models

class Blog(models.Model):
    ...

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    pub_date = models.DateField()
    ...

objects
Assuming there are some blog and entry objects here.
enter image description here

queries

Blog.objects.filter(entry__headline_contains='Lennon', 
    entry__pub_date__year=2008)
Blog.objects.filter(entry__headline_contains='Lennon').filter(
    entry__pub_date__year=2008)  
    

For the 1st query (single filter one), it match only blog1.

For the 2nd query (chained filters one), it filters out blog1 and blog2.
The first filter restricts the queryset to blog1, blog2 and blog5; the second filter restricts the set of blogs further to blog1 and blog2.

And you should realize that

We are filtering the Blog items with each filter statement, not the Entry items.

So, it's not the same, because Blog and Entry are multi-valued relationships.

Reference: https://docs.djangoproject.com/en/1.8/topics/db/queries/#spanning-multi-valued-relationships
If there is something wrong, please correct me.

Edit: Changed v1.6 to v1.8 since the 1.6 links are no longer available.

Search and replace a particular string in a file using Perl

Quick and dirty:

#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/<PREF>/ABCD/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);

Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.

JavaScript: client-side vs. server-side validation

JavaScript can be modified at runtime.

I suggest a pattern of creating a validation structure on the server, and sharing this with the client.

You'll need separate validation logic on both ends, ex:

"required" attributes on inputs client-side

field.length > 0 server-side.

But using the same validation specification will eliminate some redundancy (and mistakes) of mirroring validation on both ends.

Export MySQL data to Excel in PHP

try this code

data.php

    <table border="1">
<tr>
    <th>NO.</th>
    <th>NAME</th>
    <th>Major</th>
</tr>
<?php
//connection to mysql
mysql_connect("localhost", "root", ""); //server , username , password
mysql_select_db("codelution");

//query get data
$sql = mysql_query("SELECT * FROM student ORDER BY id ASC");
$no = 1;
while($data = mysql_fetch_assoc($sql)){
    echo '
    <tr>
        <td>'.$no.'</td>
        <td>'.$data['name'].'</td>
        <td>'.$data['major'].'</td>
    </tr>
    ';
    $no++;
}
?>

code for excel file

export.php

<?php
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=codelution-export.xls");
// Add data table
include 'data.php';
?>

if mysqli version

$sql="SELECT * FROM user_details";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
    $no = 1;
            while($data = mysqli_fetch_assoc($result))
            {echo '
    <tr>
        <<td>'.$no.'</td>
        <td>'.$data['name'].'</td>
        <td>'.$data['major'].'</td>

    </tr>
    ';
    $no++;

http://codelution.com/development/web/easy-ways-to-export-data-from-mysql-to-excel-with-php/

How to add option to select list in jQuery

Doing it this way has always worked for me, I hope this helps.

var ddl = $("#dropListBuilding");   
for (k = 0; k < buildings.length; k++)
   ddl.append("<option value='" + buildings[k]+ "'>" + buildings[k] + "</option>");

Add a column with a default value to an existing table in SQL Server

If you want to add multiple columns you can do it this way for example:

ALTER TABLE YourTable
    ADD Column1 INT NOT NULL DEFAULT 0,
        Column2 INT NOT NULL DEFAULT 1,
        Column3 VARCHAR(50) DEFAULT 'Hello'
GO

Get selected value in dropdown list using JavaScript

In 2015, in Firefox, the following also works.

e.options.selectedIndex

No value accessor for form control with name: 'recipient'

Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule

How to have jQuery restrict file types on upload?

This code works fine, but the only issue is if the file format is other than specified options, it shows an alert message but it displays the file name while it should be neglecting it.

$('#ff2').change(
                function () {
                    var fileExtension = ['jpeg', 'jpg', 'pdf'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                        alert("Only '.jpeg','.jpg','.pdf' formats are allowed.");
                        return false; }
});

How can I sort an ArrayList of Strings in Java?

You can use TreeSet that automatically order list values:

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {
        System.out.println("Tree Set Example!\n");

        TreeSet <String>tree = new TreeSet<String>();
        tree.add("aaa");
        tree.add("acbbb");
        tree.add("aab");
        tree.add("c");
        tree.add("a");

        Iterator iterator;
        iterator = tree.iterator();

        System.out.print("Tree set data: ");

        //Displaying the Tree set data
        while (iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
    }

}

I lastly add 'a' but last element must be 'c'.

Convert DateTime to long and also the other way around

There is a DateTime constructor that takes a long.

DateTime today = new DateTime(t); // where t represents long format of dateTime 

Using OpenGl with C#?

I think what @korona meant was since it's just a C API, you can consume it from C# directly with a heck of a lot of typing like this:

[DllImport("opengl32")]
public static extern void glVertex3f(float x, float y, float z);

You unfortunately would need to do this for every single OpenGL function you call, and is basically what Tao has done for you.

How to get only filenames within a directory using c#?

There are so many ways :)

1st Way:

string[] folders = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
string jsonString = JsonConvert.SerializeObject(folders);

2nd Way:

string[] folders = new DirectoryInfo(yourPath).GetDirectories().Select(d => d.Name).ToArray();

3rd Way:

string[] folders = 
    new DirectoryInfo(yourPath).GetDirectories().Select(delegate(DirectoryInfo di)
    {
        return di.Name;
    }).ToArray();

How to check if a string contains text from an array of substrings in JavaScript?

One line solution

substringsArray.some(substring=>yourBigString.includes(substring))

Returns true\false if substring exists\does'nt exist

Needs ES6 support

How to convert seconds to HH:mm:ss in moment.js

From this post I would try this to avoid leap issues

moment("2015-01-01").startOf('day')
    .seconds(s)
    .format('H:mm:ss');

I did not run jsPerf, but I would think this is faster than creating new date objects a million times

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

_x000D_
_x000D_
function pad(num) {_x000D_
    return ("0"+num).slice(-2);_x000D_
}_x000D_
function hhmmss(secs) {_x000D_
  var minutes = Math.floor(secs / 60);_x000D_
  secs = secs%60;_x000D_
  var hours = Math.floor(minutes/60)_x000D_
  minutes = minutes%60;_x000D_
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;_x000D_
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers_x000D_
}_x000D_
_x000D_
for (var i=60;i<=60*60*5;i++) {_x000D_
 document.write(hhmmss(i)+'<br/>');_x000D_
}_x000D_
_x000D_
_x000D_
/* _x000D_
function show(s) {_x000D_
  var d = new Date();_x000D_
  var d1 = new Date(d.getTime()+s*1000);_x000D_
  var  hms = hhmmss(s);_x000D_
  return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);_x000D_
}    _x000D_
*/
_x000D_
_x000D_
_x000D_

Finding the length of an integer in C

int intlen(int integer){
    int a;
    for(a = 1; integer /= 10; a++);
    return a;
}

How can I start PostgreSQL on Windows?

I found using

net start postgres_service_name

the only reliable way to operate Postgres on Windows

ImportError: No module named 'Queue'

I just copy the file name Queue.py in the */lib/python2.7/ to queue.py and that solved my problem.

How to write new line character to a file in Java

In EDIT 2:

while((line = bufferedReader.readLine()) != null)
{
  sb.append(line); //append the lines to the string
  sb.append('\n'); //append new line
} //end while

you are reading the text file, and appending a newline to it. Don't append newline, which will not show a newline in some simple-minded Windows editors like Notepad. Instead append the OS-specific line separator string using:

sb.append(System.lineSeparator()); (for Java 1.7 and 1.8) or sb.append(System.getProperty("line.separator")); (Java 1.6 and below)

Alternatively, later you can use String.replaceAll() to replace "\n" in the string built in the StringBuffer with the OS-specific newline character:

String updatedText = text.replaceAll("\n", System.lineSeparator())

but it would be more efficient to append it while you are building the string, than append '\n' and replace it later.

Finally, as a developer, if you are using notepad for viewing or editing files, you should drop it, as there are far more capable tools like Notepad++, or your favorite Java IDE.

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

You can use following git command to clone with custom directory name

git clone <git_repo_url> <your_custom_directory_name>

Note: You don't need to create your custom directory because it will create automatically

CSS: Position loading indicator in the center of the screen

Here is a solution using an overlay that inhibits along with material design spinner that you configure one time in your app and you can call it from anywhere.

app.component.html

(put this somewhere at the root level of your html)

<div class="overlay" [style.height.px]="height" [style.width.px]="width" *ngIf="message.plzWait$ | async">
        <mat-spinner class="plzWait"  mode="indeterminate"></mat-spinner>
</div>

app.component.css

.plzWait{
  position: relative;
  left: calc(50% - 50px);
  top:50%;

}
.overlay{
  position: absolute;
  top:0px;
  left:0px;
  width: 100%;
  height: 100%;
  background: black;
  opacity: .5;
  z-index: 999999;
}

app.component.ts

height = 0;
width = 0;
constructor(
    private message: MessagingService
  }
ngOnInit() {
    this.height = document.body.clientHeight;
    this.width = document.body.clientWidth;
  }

messaging.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
    providedIn: 'root',
  })
export class MessagingService {
    // Observable string sources
  private plzWaitObservable = new Subject<boolean>();


  // Public Observables you subscribe to
  public plzWait$ = this.plzWaitObservable.asObservable();

  public plzWait = (wait: boolean) => this.plzWaitObservable.next(wait);
}

Some other component

constructor(private message: MessagingService) { }
somefunction() {
    this.message.plzWait(true);
    setTimeout(() => {
            this.message.plzWait(false);
    }, 5000);
}

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

Difference between == (equal) and === (identical equal)

PHP provides two comparison operators to check equality of two values. The main difference between of these two is that '==' checks if the values of the two operands are equal or not. On the other hand, '===' checks the values as well as the type of operands are equal or not.

== (Equal)

=== (Identical equal)

Example =>

<?php 
    $val1 = 1234;
    $val2 = "1234";
    var_dump($val1 == $val2);// output => bool(true)
    //It checks only operands value
?> 


<?php 
    $val1 = 1234;
    $val2 = "1234";
    var_dump($val1 === $val2);// output => bool(false)
    //First it checks type then operands value
?> 

if we type cast $val2 to (int)$val2 or (string)$val1 then it returns true

   <?php 
        $val1 = 1234;
        $val2 = "1234";
        var_dump($val1 === (int)$val2);// output => bool(true)
        //First it checks type then operands value
    ?> 

OR

  <?php 
        $val1 = 1234;
        $val2 = "1234";
        var_dump($val1 === (int)$val2);// output => bool(true)
        //First it checks type then operands value
    ?> 

Default string initialization: NULL or Empty?

Why do you want your string to be initialized at all? You don't have to initialize a variable when you declare one, and IMO, you should only do so when the value you are assigning is valid in the context of the code block.

I see this a lot:

string name = null; // or String.Empty
if (condition)
{
  name = "foo";
}
else
{
  name = "bar";
}

return name;

Not initializing to null would be just as effective. Furthermore, most often you want a value to be assigned. By initializing to null, you can potentially miss code paths that don't assign a value. Like so:

string name = null; // or String.Empty
if (condition)
{
  name = "foo";
}
else if (othercondition)
{
  name = "bar";
}

return name; //returns null when condition and othercondition are false

When you don't initialize to null, the compiler will generate an error saying that not all code paths assign a value. Of course, this is a very simple example...

Matthijs

Purpose of ESI & EDI registers?

In addition to the registers being used for mass operations, they are useful for their property of being preserved through a function call (call-preserved) in 32-bit calling convention. The ESI, EDI, EBX, EBP, ESP are call-preserved whereas EAX, ECX and EDX are not call-preserved. Call-preserved registers are respected by C library function and their values persist through the C library function calls.

Jeff Duntemann in his assembly language book has an example assembly code for printing the command line arguments. The code uses esi and edi to store counters as they will be unchanged by the C library function printf. For other registers like eax, ecx, edx, there is no guarantee of them not being used by the C library functions.

https://www.amazon.com/Assembly-Language-Step-Step-Programming/dp/0470497025

See section 12.8 How C sees Command-Line Arguments.

Note that 64-bit calling conventions are different from 32-bit calling conventions, and I am not sure if these registers are call-preserved or not.

Set the Value of a Hidden field using JQuery

The selector should not be #input. That means a field with id="input" which is not your case. You want:

$('#chag_sort').val(sort2);

Or if your hidden input didn't have an unique id but only a name="chag_sort":

$('input[name="chag_sort"]').val(sort2);

Compute row average in pandas

If you are looking to average column wise. Try this,

df.drop('Region', axis=1).apply(lambda x: x.mean())

# it drops the Region column
df.drop('Region', axis=1,inplace=True)

Read lines from a file into a Bash array

Latest revision based on comment from BinaryZebra's comment and tested here. The addition of command eval allows for the expression to be kept in the present execution environment while the expressions before are only held for the duration of the eval.

Use $IFS that has no spaces\tabs, just newlines/CR

$ IFS=$'\r\n' GLOBIGNORE='*' command eval  'XYZ=($(cat /etc/passwd))'
$ echo "${XYZ[5]}"
sync:x:5:0:sync:/sbin:/bin/sync

Also note that you may be setting the array just fine but reading it wrong - be sure to use both double-quotes "" and braces {} as in the example above


Edit:

Please note the many warnings about my answer in comments about possible glob expansion, specifically gniourf-gniourf's comments about my prior attempts to work around

With all those warnings in mind I'm still leaving this answer here (yes, bash 4 has been out for many years but I recall that some macs only 2/3 years old have pre-4 as default shell)

Other notes:

Can also follow drizzt's suggestion below and replace a forked subshell+cat with

$(</etc/passwd)

The other option I sometimes use is just set IFS into XIFS, then restore after. See also Sorpigal's answer which does not need to bother with this

How to Change Font Size in drawString Java

Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...

Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);

You can also use TextAttribute.

Map<TextAttribute, Object> attributes = new HashMap<>();

attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);

g.setFont(myFont);

The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.

One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

I've tried both these and still get failure due to conflicts. At the end of my patience, I cloned master in another location, copied everything into the other branch and committed it. which let me continue. The "-X theirs" option should have done this for me, but it did not.

git merge -s recursive -X theirs master

error: 'merge' is not possible because you have unmerged files. hint: Fix them up in the work tree, hint: and then use 'git add/rm ' as hint: appropriate to mark resolution and make a commit, hint: or use 'git commit -a'. fatal: Exiting because of an unresolved conflict.

Getting the IP address of the current machine using Java

This is a working example of the ACCEPTED answer above! This NetIdentity class will store both the internal host ip, as well as the local loopback. If you're on a DNS based server, as mentioned above, you may need to add some more checks, or possible go the Configuration File Route.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * Class that allows a device to identify itself on the INTRANET.
 * 
 * @author Decoded4620 2016
 */
public class NetIdentity {

    private String loopbackHost = "";
    private String host = "";

    private String loopbackIp = "";
    private String ip = "";
    public NetIdentity(){

        try{
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

            while(interfaces.hasMoreElements()){
                NetworkInterface i = interfaces.nextElement();
                if(i != null){
                    Enumeration<InetAddress> addresses = i.getInetAddresses();
                    System.out.println(i.getDisplayName());
                    while(addresses.hasMoreElements()){
                        InetAddress address = addresses.nextElement();
                        String hostAddr = address.getHostAddress();

                        // local loopback
                        if(hostAddr.indexOf("127.") == 0 ){
                            this.loopbackIp = address.getHostAddress();
                            this.loopbackHost = address.getHostName();
                        }

                        // internal ip addresses (behind this router)
                        if( hostAddr.indexOf("192.168") == 0 || 
                                hostAddr.indexOf("10.") == 0 || 
                                hostAddr.indexOf("172.16") == 0 ){
                            this.host = address.getHostName();
                            this.ip = address.getHostAddress();
                        }


                        System.out.println("\t\t-" + address.getHostName() + ":" + address.getHostAddress() + " - "+ address.getAddress());
                    }
                }
            }
        }
        catch(SocketException e){

        }
        try{
            InetAddress loopbackIpAddress = InetAddress.getLocalHost();
            this.loopbackIp = loopbackIpAddress.getHostName();
            System.out.println("LOCALHOST: " + loopbackIp);
        }
        catch(UnknownHostException e){
            System.err.println("ERR: " + e.toString());
        }
    }

    public String getLoopbackHost(){
        return loopbackHost;
    }

    public String getHost(){
        return host;
    }
    public String getIp(){
        return ip;
    }
    public String getLoopbackIp(){
        return loopbackIp;
    }
}

When I run this code I actually get a print out like this:

    Software Loopback Interface 1
        -127.0.0.1:127.0.0.1 - [B@19e1023e
        -0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
        -VIKING.yourisp.com:192.168.1.142 - [B@64b8f8f4
        -fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
Intel Edison USB RNDIS Device
Driver for user-mode network applications
Cisco Systems VPN Adapter for 64-bit Windows
VirtualBox Host-Only Ethernet Adapter
        -VIKING:192.168.56.1 - [B@3cd1f1c8
        -VIKING:fe80:0:0:0:d599:3cf0:5462:cb7%eth4 - [B@3a4afd8d
LogMeIn Hamachi Virtual Ethernet Adapter
        -VIKING:25.113.118.39 - [B@1996cd68
        -VIKING:2620:9b:0:0:0:0:1971:7627 - [B@3339ad8e
        -VIKING:fe80:0:0:0:51bf:994d:4656:8486%eth5 - [B@555590
Bluetooth Device (Personal Area Network)
        -fe80:0:0:0:4c56:8009:2bca:e16b%eth6:fe80:0:0:0:4c56:8009:2bca:e16b%eth6 - [B@3c679bde
Bluetooth Device (RFCOMM Protocol TDI)
Intel(R) Ethernet Connection (2) I218-V
        -fe80:0:0:0:4093:d169:536c:7c7c%eth7:fe80:0:0:0:4093:d169:536c:7c7c%eth7 - [B@16b4a017
Microsoft Wi-Fi Direct Virtual Adapter
        -fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1:fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1 - [B@8807e25
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0000
VirtualBox Host-Only Ethernet Adapter-WFP Native MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0001
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0002
VirtualBox Host-Only Ethernet Adapter-VirtualBox NDIS Light-Weight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0003
VirtualBox Host-Only Ethernet Adapter-QoS Packet Scheduler-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0004
VirtualBox Host-Only Ethernet Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0000
Intel(R) Ethernet Connection (2) I218-V-WFP Native MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0001
Intel(R) Ethernet Connection (2) I218-V-Shrew Soft Lightweight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0002
Intel(R) Ethernet Connection (2) I218-V-VirtualBox NDIS Light-Weight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0003
Intel(R) Ethernet Connection (2) I218-V-QoS Packet Scheduler-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0004
Intel(R) Ethernet Connection (2) I218-V-WFP 802.3 MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-WFP Native MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-Virtual WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-Native WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Broadcom 802.11ac Network Adapter-Shrew Soft Lightweight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Broadcom 802.11ac Network Adapter-VirtualBox NDIS Light-Weight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-QoS Packet Scheduler-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0006
Broadcom 802.11ac Network Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0007
Microsoft Wi-Fi Direct Virtual Adapter-WFP Native MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-Native WiFi Filter Driver-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0002
Microsoft Wi-Fi Direct Virtual Adapter-Shrew Soft Lightweight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Microsoft Wi-Fi Direct Virtual Adapter-VirtualBox NDIS Light-Weight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Microsoft Wi-Fi Direct Virtual Adapter-QoS Packet Scheduler-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0006

For my use I'm setting up a Upnp Server, it helped to understand the 'pattern' that i was looking for. Some of the objects returned are Ethernet Adapters, Network Adapters, Virtual Network Adapters, Drivers, and VPN Client Adapters. Not everything has an Address either. So you'll want to skip out on interface objects that don't.

You can also add this to the loop for the current NetworkInterface i

while(interfaces.hasMoreElements()){
    Enumeration<InetAddress> addresses = i.getInetAddresses();
    System.out.println(i.getDisplayName());
    System.out.println("\t- name:" + i.getName());
    System.out.println("\t- idx:" + i.getIndex());
    System.out.println("\t- max trans unit (MTU):" + i.getMTU());
    System.out.println("\t- is loopback:" + i.isLoopback());
    System.out.println("\t- is PPP:" + i.isPointToPoint());
    System.out.println("\t- isUp:" + i.isUp());
    System.out.println("\t- isVirtual:" + i.isVirtual());
    System.out.println("\t- supportsMulticast:" + i.supportsMulticast());
}

And You'll see information in your output much like this:

Software Loopback Interface 1
    - name:lo
    - idx:1
    - max trans unit (MTU):-1
    - is loopback:true
    - is PPP:false
    - isUp:true
    - isVirtual:false
    - supportsMulticast:true
        -ADRESS: [127.0.0.1(VIKING-192.168.56.1)]127.0.0.1:127.0.0.1 - [B@19e1023e
        -ADRESS: [0:0:0:0:0:0:0:1(VIKING-192.168.56.1)]0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
    - name:wlan0
    - idx:2
    - max trans unit (MTU):1500
    - is loopback:false
    - is PPP:false
    - isUp:true
    - isVirtual:false
    - supportsMulticast:true
        -ADRESS: [VIKING.monkeybrains.net(VIKING-192.168.56.1)]VIKING.monkeybrains.net:192.168.1.142 - [B@64b8f8f4
        -ADRESS: [fe80:0:0:0:81fa:31d:21c9:85cd%wlan0(VIKING-192.168.56.1)]fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
    - name:eth0
    - idx:3
    - max trans unit (MTU):-1
    - is loopback:false
    - is PPP:false
    - isUp:false
    - isVirtual:false
    - supportsMulticast:true

How to print a list of symbols exported from a dynamic library

Use otool:

otool -TV your.dylib

OR

nm -g your.dylib

Difference between return and exit in Bash functions

In simple words (mainly for newbie in coding), we can say,

    `return`: exits the function,
    `exit()`: exits the program (called as process while running)

Also if you observed, this is very basic, but...,

    `return`: is the keyword
    `exit()`: is the function

Sticky and NON-Sticky sessions

When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.

However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.

Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.

If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.

To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.

As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html

How can I get a process handle by its name in C++?

Check out: MSDN Article

You can use GetModuleName (I think?) to get the name and check against that.

How can I start InternetExplorerDriver using Selenium WebDriver

Below steps are worked for me, Hope this will work for you as well,

  1. Open internet explorer.
  2. Navigate to Tools->Option
  3. Navigate to Security Tab
  4. Click on "Reset All Zones to Default level" button
  5. Now for all option like Internet,Intranet,Trusted Sites and Restricted Site enable "Enable Protected" mode check-box.
  6. Set IE zoom level to 100%
  7. then write below code in a java file and run

    System.setProperty("webdriver.ie.driver","path of your IE driver exe\IEDriverServer.exe");
    InternetExplorerDriver driver=new InternetExplorerDriver();
    driver.manage().window().maximize();
    Thread.Sleep(10100);
    driver.get("http://www.Google.com");
    Thread.Sleep(10000);
    

Failed to load resource: the server responded with a status of 404 (Not Found)

I have added app.UseStaticFiles(); this code in my startup.cs than it is fixed

How to present a modal atop the current view in Swift

The only way I able to get this to work was by doing this on the presenting view controller:

    func didTapButton() {
    self.definesPresentationContext = true
    self.modalTransitionStyle = .crossDissolve
    let yourVC = self.storyboard?.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
    let navController = UINavigationController(rootViewController: yourVC)
    navController.modalPresentationStyle = .overCurrentContext
    navController.modalTransitionStyle = .crossDissolve
    self.present(navController, animated: true, completion: nil)
}

How to draw a filled triangle in android canvas?

Ok I've done it. I'm sharing this code in case someone else will need it:

super.draw(canvas, mapView, true);

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

paint.setStrokeWidth(2);
paint.setColor(android.graphics.Color.RED);     
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);

Point point1_draw = new Point();        
Point point2_draw = new Point();    
Point point3_draw = new Point();

mapView.getProjection().toPixels(point1, point1_draw);
mapView.getProjection().toPixels(point2, point2_draw);
mapView.getProjection().toPixels(point3, point3_draw);

Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(point1_draw.x,point1_draw.y);
path.lineTo(point2_draw.x,point2_draw.y);
path.lineTo(point3_draw.x,point3_draw.y);
path.lineTo(point1_draw.x,point1_draw.y);
path.close();

canvas.drawPath(path, paint);

//canvas.drawLine(point1_draw.x,point1_draw.y,point2_draw.x,point2_draw.y, paint);

return true;

Thanks for the hint Nicolas!

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

I'm on Windows 10 and I saved my key with Windows1252 encoding and it worked for me. On another StackOverflow question some people were fixing this with UTF-8 with BOM.

In other words, it may be the file encoding.

How do I display a decimal value to 2 decimal places?

decimalVar.ToString("F");

This will:

  • Round off to 2 decimal places eg. 23.456 ? 23.46
  • Ensure that there are always 2 decimal places eg. 23 ? 23.00; 12.5 ? 12.50

Ideal for displaying currency.

Check out the documentation on ToString("F") (thanks to Jon Schneider).

Database Diagram Support Objects cannot be Installed ... no valid owner

you must enter as administrator right click to microsofft sql server management studio and run as admin

Which is faster: multiple single INSERTs or one multiple-row INSERT?

https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html

The time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:

  • Connecting: (3)
  • Sending query to server: (2)
  • Parsing query: (2)
  • Inserting row: (1 × size of row)
  • Inserting indexes: (1 × number of indexes)
  • Closing: (1)

From this it should be obvious, that sending one large statement will save you an overhead of 7 per insert statement, which in further reading the text also says:

If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements.

Runtime vs. Compile time

Hmm, ok well, runtime is used to describe something that occurs when a program is running.

Compile time is used to describe something that occurs when a program is being built (usually, by a compiler).

Volatile vs Static in Java

In simple terms,

  1. static : static variables are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory

  2. volatile: This keyword is applicable to both class and instance variables.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads

Have a look at this article by Javin Paul to understand volatile variables in a better way.

enter image description here

In absence of volatile keyword, the value of variable in each thread's stack may be different. By making the variable as volatile, all threads will get same value in their working memory and memory consistency errors have been avoided.

Here the term variable can be either static (class) variable or instance (object) variable.

Regarding your query :

Anyway a static variable value is also going to be one value for all threads, then why should we go for volatile?

If I need instance variable in my application, I can't use static variable. Even in case of static variable, consistency is not guaranteed due to Thread cache as shown in the diagram.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.

What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change => memory consistency errors are still possible with volatile variables. To avoid side effects, you have to use synchronized variables. But there is a better solution in java.

Using simple atomic variable access is more efficient than accessing these variables through synchronized code

Some of the classes in the java.util.concurrent package provide atomic methods that do not rely on synchronization.

Refer to this high level concurrency control article for more details.

Especially have a look at Atomic variables.

Related SE questions:

Volatile Vs Atomic

Volatile boolean vs AtomicBoolean

Difference between volatile and synchronized in Java

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

Draw Circle using css alone

Yep, draw a box and give it a border radius that is half the width of the box:

#circle {
    background: #f00;
    width: 200px;
    height: 200px;
    border-radius: 50%;
}

Working demo:

http://jsfiddle.net/DsW9h/1/

_x000D_
_x000D_
#circle {_x000D_
    background: #f00;_x000D_
    width: 200px;_x000D_
    height: 200px;_x000D_
    border-radius: 50%;_x000D_
}
_x000D_
<div id="circle"></div>
_x000D_
_x000D_
_x000D_

Update values from one column in same table to another in SQL Server

You put select query before update queries, so you just see initial data. Put select * from stuff; to the end of list.

Check if passed argument is file or directory in Bash

Using the "file" command may be useful for this:

#!/bin/bash
check_file(){

if [ -z "${1}" ] ;then
 echo "Please input something"
 return;
fi

f="${1}"
result="$(file $f)"
if [[ $result == *"cannot open"* ]] ;then
        echo "NO FILE FOUND ($result) ";
elif [[ $result == *"directory"* ]] ;then
        echo "DIRECTORY FOUND ($result) ";
else
        echo "FILE FOUND ($result) ";
fi

}

check_file "${1}"

Output examples :

$ ./f.bash login
DIRECTORY FOUND (login: directory) 
$ ./f.bash ldasdas
NO FILE FOUND (ldasdas: cannot open `ldasdas' (No such file or  directory)) 
$ ./f.bash evil.php 
FILE FOUND (evil.php: PHP script, ASCII text) 

FYI: the answers above work but you can use -s to help in weird situations by checking for a valid file first:

#!/bin/bash

check_file(){
    local file="${1}"
    [[ -s "${file}" ]] || { echo "is not valid"; return; } 
    [[ -d "${file}" ]] && { echo "is a directory"; return; }
    [[ -f "${file}" ]] && { echo "is a file"; return; }
}

check_file ${1}

PostgreSQL: insert from another table

For referential integtity :

insert into  main_tbl (col1, ref1, ref2, createdby)
values ('col1_val',
        (select ref1 from ref1_tbl where lookup_val = 'lookup1'),
        (select ref2 from ref2_tbl where lookup_val = 'lookup2'),
        'init-load'
       );

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Bootstrap 4 (^beta) has changed the classes for responsive hiding/showing elements. See this link for correct classes to use: http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

Sum of values in an array using jQuery

To also handle floating point numbers:

  • (Older) JavaScript:

    var arr = ["20.0","40.1","80.2","400.3"],
        n   = arr.length,
        sum = 0;
    while(n--)
       sum += parseFloat(arr[n]) || 0;
    
  • ECMA 5.1/6:

    var arr = ["20.0","40.1","80.2","400.3"],
        sum = 0;
    arr.forEach(function(num){sum+=parseFloat(num) || 0;});
    
  • ES6:

    var sum = ["20.0","40.1","80.2","400.3"].reduce((pv,cv)=>{
       return pv + (parseFloat(cv)||0);
    },0);
    

    The reduce() is available in older ECMAScript versions, the arrow function is what makes this ES6-specific.

    I'm passing in 0 as the first pv value, so I don't need parseFloat around it — it'll always hold the previous sum, which will always be numeric. Because the current value, cv, can be non-numeric (NaN), we use ||0 on it to skip that value in the array. This is terrific if you want to break up a sentence and get the sum of the numbers in it. Here's a more detailed example:

    let num_of_fruits = `
       This is a sentence where 1.25 values are oranges 
       and 2.5 values are apples. How many fruits are 
       there?
    `.split(/\s/g).reduce((p,c)=>p+(parseFloat(c)||0), 0); 
    
    // num_of_fruits == 3.75
    

  • jQuery:

    var arr = ["20.0","40.1","80.2","400.3"],
        sum = 0;
    $.each(arr,function(){sum+=parseFloat(this) || 0;});
    

What the above gets you:

  • ability to input any kind of value into the array; number or numeric string(123 or "123"), floating point string or number ("123.4" or 123.4), or even text (abc)
  • only adds the valid numbers and/or numeric strings, neglecting any bare text (eg [1,'a','2'] sums to 3)

Can I redirect the stdout in python into some sort of string buffer?

Here's another take on this. contextlib.redirect_stdout with io.StringIO() as documented is great, but it's still a bit verbose for every day use. Here's how to make it a one-liner by subclassing contextlib.redirect_stdout:

import sys
import io
from contextlib import redirect_stdout

class capture(redirect_stdout):

    def __init__(self):
        self.f = io.StringIO()
        self._new_target = self.f
        self._old_targets = []  # verbatim from parent class

    def __enter__(self):
        self._old_targets.append(getattr(sys, self._stream))  # verbatim from parent class
        setattr(sys, self._stream, self._new_target)  # verbatim from parent class
        return self  # instead of self._new_target in the parent class

    def __repr__(self):
        return self.f.getvalue()  

Since __enter__ returns self, you have the context manager object available after the with block exits. Moreover, thanks to the __repr__ method, the string representation of the context manager object is, in fact, stdout. So now you have,

with capture() as message:
    print('Hello World!')
print(str(message)=='Hello World!\n')  # returns True

Accessing members of items in a JSONArray with Java

Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.

import org.json.JSONArray;
import org.json.JSONObject;

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}

If the iteration is only one time, (no need to .collect)

    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });

How to stop the task scheduled in java.util.Timer class

Keep a reference to the timer somewhere, and use:

timer.cancel();
timer.purge();

to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.

private static int count = 0;
public static void run() {
     count++;
     if (count >= 6) {
         timer.cancel();
         timer.purge();
         return;
     }

     ... perform task here ....

}

Mysql adding user for remote access

An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.

How to do sed like text replace with python?

Here's a one-module Python replacement for perl -p:

# Provide compatibility with `perl -p`

# Usage:
#
#     python -mloop_over_stdin_lines '<program>'

# In, `<program>`, use the variable `line` to read and change the current line.

# Example:
#
#         python -mloop_over_stdin_lines 'line = re.sub("pattern", "replacement", line)'

# From the perlrun documentation:
#
#        -p   causes Perl to assume the following loop around your
#             program, which makes it iterate over filename arguments
#             somewhat like sed:
# 
#               LINE:
#                 while (<>) {
#                     ...             # your program goes here
#                 } continue {
#                     print or die "-p destination: $!\n";
#                 }
# 
#             If a file named by an argument cannot be opened for some
#             reason, Perl warns you about it, and moves on to the next
#             file. Note that the lines are printed automatically. An
#             error occurring during printing is treated as fatal. To
#             suppress printing use the -n switch. A -p overrides a -n
#             switch.
# 
#             "BEGIN" and "END" blocks may be used to capture control
#             before or after the implicit loop, just as in awk.
# 

import re
import sys

for line in sys.stdin:
    exec(sys.argv[1], globals(), locals())
    try:
        print line,
    except:
        sys.exit('-p destination: $!\n')

Cache busting via params

Found a comparison of the 2 techniques (query string vs file name) here:

Version as a querystring has two problems.

First, it may not always be a browser that implements caching through which we need to bust. It is said that certain (possibly older) proxies do ignore the querystring with respect to their caching behavior.

Second, in certain more complex deployment scenarios, where you have multiple frontend and/or multiple backend servers, an upgrade is anything but instantaneous. You need to be able to serve both the old and the new version of your assets at the same time. See for example how this affects you when using Google App Engine.

Rounded corners for <input type='text' /> using border-radius.htc for IE

    border-bottom-color: #b3b3b3;
    border-bottom-left-radius: 3px;
    border-bottom-right-radius: 3px;
    border-bottom-style: solid;
    border-bottom-width: 1px;
    border-left-color: #b3b3b3;
    border-left-style: solid;
    border-left-width: 1px;
    border-right-color: #b3b3b3;
    border-right-style: solid;
    border-right-width: 1px;
    border-top-color: #b3b3b3;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    border-top-style: solid;
    border-top-width: 1px;

...Who cares IE6 we are in 2011 upgrade and wake up please!

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

Everything is much easier in Swift 3.0 Xcode 8

Using the code below in App Delegate file, after

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

insert this:

UINavigationBar.appearance().barStyle = .black

UINavigationBar.appearance().barTintColor = UIColor(red: 230, green: 32, blue: 31, alpha: 1.0)

What is the Windows version of cron?

Is there also a way to invoke this feature (which based on answers is called the Task Scheduler) programatically [...]?

Task scheduler API on MSDN.

Get selected row item in DataGrid WPF

use your Model class to get row values selected from datagrid like,

        XDocument xmlDoc = XDocument.Load(filepath);

        if (tablet_DG.SelectedValue == null)
        {
            MessageBox.Show("select any record from list..!", "select atleast one record", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
        }
        else
        {
            try
            {
                string tabletID = "";

                 /*here i have used my model class named as TabletMode*/

                var row_list = (TabletModel)tablet_DG.SelectedItem; 
                 tabletID= row_list.TabletID;

                var items = from item in xmlDoc.Descendants("Tablet")
                            where item.Element("TabletID").Value == tabletID
                            select item;

                foreach (var item in items)
                {
                    item.SetElementValue("Instance",row_list.Instance);
                    item.SetElementValue("Database",row_list.Database);
                }

                xmlDoc.Save(filepath);
                MessageBox.Show("Details Updated..!"
                + Environment.NewLine + "TabletId: " +row_list.TabletID + Environment.NewLine
                + "Instance:" + row_list.Instance + Environment.NewLine + "Database:" + row_list.Database, "", MessageBoxButton.YesNoCancel, MessageBoxImage.Information);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace);
            }
        }

Get Insert Statement for existing row in MySQL

You can create a SP with the code below - it supports NULLS as well.

select 'my_table_name' into @tableName;

/*find column names*/
select GROUP_CONCAT(column_name SEPARATOR ', ') from information_schema.COLUMNS
where table_schema =DATABASE()
and table_name = @tableName
group by table_name
into @columns
;

/*wrap with IFNULL*/
select replace(@columns,',',',IFNULL(') into @selectColumns;
select replace(@selectColumns,',IFNULL(',',\'~NULL~\'),IFNULL(') into @selectColumns;

select concat('IFNULL(',@selectColumns,',\'~NULL~\')') into @selectColumns;

/*RETRIEVE COLUMN DATA FIELDS BY PK*/
SELECT
  CONCAT(
    'SELECT CONCAT_WS(','''\'\',\'\''',' ,
    @selectColumns,
    ') AS all_columns FROM ',@tableName, ' where id = 5 into @values;'
    )
INTO @sql;

PREPARE stmt FROM @sql;
EXECUTE stmt;

/*Create Insert Statement*/
select CONCAT('insert into ',@tableName,' (' , @columns ,') values (\'',@values,'\')') into @prepared;

/*UNWRAP NULLS*/
select replace(@prepared,'\'~NULL~\'','NULL') as statement;

Maven: Command to update repository after adding dependency to POM

Pay attention to your dependency scope I was having the issue where when I invoke clean compile via Intellij, the pom would get downloaded, but the jar would not. There was a xxx.jar.lastUpdated file created. Then realized that the dependency scope was test, but I was triggering the compile. I deleted the repos, and triggered the mvn test, and issue was resolved.

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Both of these operations restore a set of files to a previous state and are essentially faster, safer ways of undoing mistakes than using the p4 obliterate command (and you don't need admin access to use them).

In the case of "Rollback...", this could be any number of files, even an entire depot. You can tell it to rollback to a specific revision, changelist, or label. The files are restored to the state they were in at the time of creation of that revision, changelist, or label.

In the case of "Back Out Submitted Changelist #####", the restore operation is restricted to the files that were submitted in changelist #####. Those files are restored to the state they were in before you submitted that changelist, provided no changes have been made to those files since. If subsequent changes have been made to any of those files, Perforce will tell you that those files are now out of date. You will have to sync to the head revision and then resolve the differences. This way you don't inadvertently clobber any changes that you actually want to keep.

Both operations work by essentially submitting old revisions as new revisions. When you perform a "Rollback...", you are restoring the files to the state they were in at a specific point in time, regardless of what has happened to them since. When you perform a "Back out...", you are attempting to undo the changes you made at a specific point in time, while maintaining the changes that have occurred since.

How to install Intellij IDEA on Ubuntu?

try simple way to install intellij idea

Install IntelliJ on Ubuntu using Ubuntu Make

You need to install Ubuntu Make first. If you are using Ubuntu 16.04, 18.04 or a higher version, you can install Ubuntu Make using the command below:

  1. sudo apt install ubuntu-make

Once you have Ubuntu Make installed, you can use the command below to install IntelliJ IDEA Community edition:

  1. umake ide idea

To install the IntelliJ IDEA Ultimate edition, use the command below:

  1. umake ide idea-ultimate

To remove IntelliJ IDEA installed via Ubuntu Make, use the command below for your respective versions:

  1. umake -r ide idea
  2. umake -r ide idea-ultimate

you may visit for more option.

https://itsfoss.com/install-intellij-ubuntu-linux/

How to find if element with specific id exists or not

You can simply use if(yourElement)

_x000D_
_x000D_
var a = document.getElementById("elemA");_x000D_
var b = document.getElementById("elemB");_x000D_
_x000D_
if(a)_x000D_
  console.log("elemA exists");_x000D_
else_x000D_
  console.log("elemA does not exist");_x000D_
  _x000D_
if(b)_x000D_
  console.log("elemB exists");_x000D_
else_x000D_
  console.log("elemB does not exist");
_x000D_
<div id="elemA"></div>
_x000D_
_x000D_
_x000D_

What does \d+ mean in regular expression terms?

\d is a digit (a character in the range 0-9), and + means 1 or more times. So, \d+ is 1 or more digits.

This is about as simple as regular expressions get. You should try reading up on regular expressions a little bit more. Google has a lot of results for regular expression tutorial, for instance. Or you could try using a tool like the free Regex Coach that will let you enter a regular expression and sample text, then indicate what (if anything) matches the regex.

Evenly space multiple views within a container view

I found a perfect and simple method. The auto layout does not allow you to resize the spaces equally, but it does allow you to resize views equally. Simply put some invisible views in between your fields and tell auto layout to keep them the same size. It works perfectly!

Initial XIB

Stretched XIB

One thing of note though; when I reduced the size in the interface designer, sometimes it got confused and left a label where it was, and it had a conflict if the size was changed by an odd amount. Otherwise it worked perfectly.

edit: I found that the conflict became a problem. Because of that, I took one of the spacing constraints, deleted it and replaced it with two constraints, a greater-than-or-equal and a less-than-or-equal. Both were the same size and had a much lower priority than the other constraints. The result was no further conflict.

Error: Local workspace file ('angular.json') could not be found

I also faced same issue and i just executed below command.

ng update @angular/cli --migrate-only --from=1.6.4

It simply delete angular-cli.json and create angular.json. You can find this in logs.

Once you start execution. You will be able to see below logs in your terminal.

        Updating karma configuration
        Updating configuration
        Removing old config file (.angular-cli.json)
        Writing config file (angular.json)
        Some configuration options have been changed, please make sure to update any                                     
        npm scripts which you may have modified.
        DELETE .angular-cli.json
        CREATE angular.json (3599 bytes)
        UPDATE karma.conf.js (962 bytes)
        UPDATE src/tsconfig.spec.json (324 bytes)
        UPDATE package.json (1405 bytes)
        UPDATE tsconfig.json (407 bytes)
        UPDATE tslint.json (3026 bytes)

usr/bin/ld: cannot find -l<nameOfTheLibrary>

This error may also be brought about if the symbolic link is to a dynamic library, .so, but for legacy reasons -static appears among the link flags. If so, try removing it.

Specify an SSH key for git push for a given domain

Another alternative is to use ssh-ident, to manage your ssh identities.

It automatically loads and uses different keys based on your current working directory, ssh options, and so on... which means you can easily have a work/ directory and private/ directory that transparently end up using different keys and identities with ssh.

Not able to pip install pickle in python 3.6

import pickle

intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()

Test your pickle quickly. pickle is a part of standard python library and available by default.

How can I format the output of a bash command in neat columns

While awk's printf can be used, you may want to look into pr or (on BSDish systems) rs for formatting.

logger configuration to log to file and print to stdout

Logging to stdout and rotating file with different levels and formats:

import logging
import logging.handlers
import sys

if __name__ == "__main__":

    # Change root logger level from WARNING (default) to NOTSET in order for all messages to be delegated.
    logging.getLogger().setLevel(logging.NOTSET)

    # Add stdout handler, with level INFO
    console = logging.StreamHandler(sys.stdout)
    console.setLevel(logging.INFO)
    formater = logging.Formatter('%(name)-13s: %(levelname)-8s %(message)s')
    console.setFormatter(formater)
    logging.getLogger().addHandler(console)

    # Add file rotating handler, with level DEBUG
    rotatingHandler = logging.handlers.RotatingFileHandler(filename='rotating.log', maxBytes=1000, backupCount=5)
    rotatingHandler.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    rotatingHandler.setFormatter(formatter)
    logging.getLogger().addHandler(rotatingHandler)

    log = logging.getLogger("app." + __name__)

    log.debug('Debug message, should only appear in the file.')
    log.info('Info message, should appear in file and stdout.')
    log.warning('Warning message, should appear in file and stdout.')
    log.error('Error message, should appear in file and stdout.')

How do you do a limit query in JPQL or HQL?

You can easily use pagination for this.

    @QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value = "true") })
    @Query("select * from a_table order by a_table_column desc")
    List<String> getStringValue(Pageable pageable);

you have to pass new PageRequest(0, 1)to fetch records and from the list fetch the first record.

implements Closeable or implements AutoCloseable

It seems to me that you are not very familiar with interfaces. In the code you have posted, you don't need to implement AutoCloseable.

You only have to (or should) implement Closeable or AutoCloseable if you are about to implement your own PrintWriter, which handles files or any other resources which needs to be closed.

In your implementation, it is enough to call pw.close(). You should do this in a finally block:

PrintWriter pw = null;
try {
   File file = new File("C:\\test.txt");
   pw = new PrintWriter(file);
} catch (IOException e) {
   System.out.println("bad things happen");
} finally {
   if (pw != null) {
      try {
         pw.close();
      } catch (IOException e) {
      }
   }
}

The code above is Java 6 related. In Java 7 this can be done more elegantly (see this answer).

How to get a password from a shell script without echoing

I found to be the the askpass command useful

password=$(/lib/cryptsetup/askpass "Give a password")

Every input character is replaced by *. See: Give a password ****

Using Mockito, how do I verify a method was a called with a certain argument?

First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:

ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");

Then inject the mock into m_orderSvc and call your method.

m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work(); 

Finally, verify that the mock was called properly:

verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");

Does java have a int.tryparse that doesn't throw an exception for bad data?

Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.

See here for the groupid/artifactid.

How do you check in python whether a string contains only numbers?

There are 2 methods that I can think of to check whether a string has all digits of not

Method 1(Using the built-in isdigit() function in python):-

>>>st = '12345'
>>>st.isdigit()
True
>>>st = '1abcd'
>>>st.isdigit()
False

Method 2(Performing Exception Handling on top of the string):-

st="1abcd"
try:
    number=int(st)
    print("String has all digits in it")
except:
    print("String does not have all digits in it")

The output of the above code will be:

String does not have all digits in it

How can I connect to MySQL in Python 3 on Windows?

You should probably use pymysql - Pure Python MySQL client instead.
It works with Python 3.x, and doesn't have any dependencies.

This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol.

Example:

import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for r in cur:
    print(r)
cur.close()
conn.close()

How do I compare 2 rows from the same table (SQL Server)?

Some people find the following alternative syntax easier to see what is going on:

select t1.value,t2.value
from MyTable t1
    inner join MyTable t2 on
        t1.id = t2.id
where t1.id = @id

How to uncheck a checkbox in pure JavaScript?

You will need to assign an ID to the checkbox:

<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">

and then in JavaScript:

document.getElementById("checkboxId").checked = false;

"No rule to make target 'install'"... But Makefile exists

I also came across the same error. Here is the fix: If you are using Cmake-GUI:

  1. Clean the cache of the loaded libraries in Cmake-GUI File menu.
  2. Configure the libraries.
  3. Generate the Unix file.

If you missed the 3rd step:

*** No rule to make target `install'. Stop.

error will occur.

Upload Progress Bar in PHP

Implementation of the upload progress bar is easy and doesn't require any additional PHP extension, JavaScript or Flash. But you need PHP 5.4 and newer.

You have to enable collecting of the upload progress information by setting the directive session.upload_progress.enabled to On in php.ini.

Then add a hidden input to the HTML upload form just before any other file inputs. HTML attribute name of that hidden input should be the same as the value of the directive session.upload_progress.name from php.ini (eventually preceded by session.upload_progress.prefix). The value attribute is up to you, it will be used as part of the session key.

HTML form could looks like this:

<form action="upload.php" method="POST" enctype="multipart/form-data">
   <input type="hidden" name="<?php echo ini_get('session.upload_progress.prefix').ini_get('session.upload_progress.name'); ?>" value="myupload" />
   <input type="file" name="file1" />
   <input type="submit" />
</form>

When you send this form, PHP should create a new key in the $_SESSION superglobal structure which will be populated with the upload status information. The key is concatenated name and value of the hidden input.

In PHP you can take a look at populated upload information:

var_dump($_SESSION[
    ini_get('session.upload_progress.prefix')
   .ini_get('session.upload_progress.name')
   .'_myupload'
]);

The output will look similarly to the following:

$_SESSION["upload_progress_myupload"] = array(
  "start_time" => 1234567890,   // The request time
  "content_length" => 57343257, // POST content length
  "bytes_processed" => 54321,   // Amount of bytes received and processed
  "done" => false,              // true when the POST handler has finished, successfully or not
  "files" => array(
    0 => array(
      "field_name" => "file1",    // Name of the <input /> field
      // The following 3 elements equals those in $_FILES
      "name" => "filename.ext",
      "tmp_name" => "/tmp/phpxxxxxx",
      "error" => 0,
      "done" => false,            // True when the POST handler has finished handling this file
      "start_time" => 1234567890, // When this file has started to be processed
      "bytes_processed" => 54321, // Number of bytes received and processed for this file
    )
  )
);

There is all the information needed to create a progress bar — you have the information if the upload is still in progress, the information how many bytes is going to be transferred in total and how many bytes has been transferred already.

To present the upload progress to the user, write an another PHP script than the uploading one, which will only look at the upload information in the session and return it in the JSON format, for example. This script can be called periodically, for example every second, using AJAX and information presented to the user.

You are even able to cancel the upload by setting the $_SESSION[$key]['cancel_upload'] to true.

For detailed information, additional settings and user's comments see PHP manual.

Get div height with plain JavaScript

jsFiddle

var element = document.getElementById('element');
alert(element.offsetHeight);

How to list only files and not directories of a directory Bash?

Listing content of some directory, without subdirectories

I like using ls options, for sample:

  • -l use a long listing format
  • -t sort by modification time, newest first
  • -r reverse order while sorting
  • -F, --classify append indicator (one of */=>@|) to entries
  • -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc...

Sometime --color and all others. (See ls --help)

Listing everything but folders

This will show files, symlinks, devices, pipe, sockets etc.

so

find /some/path -maxdepth 1 ! -type d

could be sorted by date easily:

find /some/path -maxdepth 1 ! -type d -exec ls -hltrF {} +

Listing files only:

or

find /some/path -maxdepth 1 -type f

sorted by size:

find /some/path -maxdepth 1 -type f -exec ls -lSF --color {} +

Prevent listing of hidden entries:

To not show hidden entries, where name begin by a dot, you could add ! -name '.*':

find /some/path -maxdepth 1 ! -type d ! -name '.*' -exec ls -hltrF {} +

Then

You could replace /some/path by . to list for current directory or .. for parent directory.

Calculate days between two Dates in Java 8

Get number of days before Christmas from current day , try this

System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));

Writing to a new file if it doesn't exist, and appending to a file if it does

It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".

import os
player = 'bob'

filename = player+'.txt'

if os.path.exists(filename):
    append_write = 'a' # append if already exists
else:
    append_write = 'w' # make a new file if not

highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()

Twitter Bootstrap date picker

You used data-datepicker="datepicker" It must be date-provide="datepicker"

Also, you included 2 bootstrap stylesheets bootstrap.css and bootstrap.min.css

I also prefer to use bootstrap-datepicker3.min.css than datepicker.less

Full Html:

<html>
    <head>
    <title>DatePicker Demo</title>
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="css/bootstrap-datepicker3.min.css">
    <script src="js/jquery-1.7.1.js"></script>
    <script src="js/bootstrap-datepicker.js"></script>
    </head>
    <body>
        <form>
            <div class="input">
                <input data-provide="datepicker" class="small" type="text" value="01/05/2011">
            </div>
        </form>
    </body>
</html>

Get skin path in Magento?

First note that

Mage::getBaseDir('skin')

returns only path to skin directory of your Magento install (/your/magento/dir/skin).

You can access absolute path to currently used skin directory using:

Mage::getDesign()->getSkinBaseDir()

This method accepts an associative array as optional parameter to modify result.

Following keys are recognized:

  • _area frontend (default) or adminhtml
  • _package your package
  • _theme your theme
  • _relative when this is set (as an key) path relative to Mage::getBaseDir('skin') is returned.

So in your case correct answer would be:

require(Mage::getDesign()->getSkinBaseDir().DS.'myfunc.php');

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'];

But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.

Notice: Undefined index: HTTP_REFERER

React - How to force a function component to render?

Official FAQ ( https://reactjs.org/docs/hooks-faq.html#is-there-something-like-forceupdate ) now recommends this way if you really need to do it:

  const [ignored, forceUpdate] = useReducer(x => x + 1, 0);

  function handleClick() {
    forceUpdate();
  }

How to make a div have a fixed size?

Use this style

<div class="form-control"
     style="height:100px;
     width:55%;
     overflow:hidden;
     cursor:pointer">
</div>

Get the first element of an array

A kludgy way is:

$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );

function get_first ($foo) {
    foreach ($foo as $k=>$v){
        return $v;
    }
}

print get_first($foo);

get UTC time in PHP

Obtaining UTC date

gmdate("Y-m-d H:i:s");

Obtaining UTC timestamp

time();

The result will not be different even you have date_default_timezone_set on your code.

How can I write text on a HTML5 canvas element?

Depends on what you want to do with it I guess. If you just want to write some normal text you can use .fillText().

Force index use in Oracle

If you think the performance of the query will be better using the index, how could you force the query to use the index?

First you would of course verify that the index gave a better result for returning the complete data set, right?

The index hint is the key here, but the more up to date way of specifying it is with the column naming method rather than the index naming method. In your case you would use:

select /*+ index(table_name (column_having_index)) */ *
from   table_name
where  column_having_index="some value"; 

In more complex cases you might ...

select /*+ index(t (t.column_having_index)) */ *
from   my_owner.table_name t,
       ...
where  t.column_having_index="some value"; 

With regard to composite indexes, I'm not sure that you need to specify all columns, but it seems like a good idea. See the docs here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#autoId18 on multiple index_specs and use of index_combine for multiple indexes, and here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#BABGFHCH for the specification of multiple columns in the index_spec.

Convert floats to ints in Pandas?

Use the pandas.DataFrame.astype(<type>) function to manipulate column dtypes.

>>> df = pd.DataFrame(np.random.rand(3,4), columns=list("ABCD"))
>>> df
          A         B         C         D
0  0.542447  0.949988  0.669239  0.879887
1  0.068542  0.757775  0.891903  0.384542
2  0.021274  0.587504  0.180426  0.574300
>>> df[list("ABCD")] = df[list("ABCD")].astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0

EDIT:

To handle missing values:

>>> df
          A         B     C         D
0  0.475103  0.355453  0.66  0.869336
1  0.260395  0.200287   NaN  0.617024
2  0.517692  0.735613  0.18  0.657106
>>> df[list("ABCD")] = df[list("ABCD")].fillna(0.0).astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0

How to choose between Hudson and Jenkins?

I've got two points to add. One, Hudson/Jenkins is all about the plugins. Plugin developers have moved to Jenkins and so should we, the users. Two, I am not personally a big fan of Oracle's products. In fact, I avoid them like the plague. For the money spent on licensing and hardware for an Oracle solution you can hire twice the engineering staff and still have some left over to buy beer every Friday :)

Oracle SQL Query for listing all Schemas in a DB

Below sql lists all the schema in oracle that are created after installation ORACLE_MAINTAINED='N' is the filter. This column is new in 12c.

select distinct username,ORACLE_MAINTAINED from dba_users where ORACLE_MAINTAINED='N';

Editing an item in a list<T>

class1 item = lst[index];
item.foo = bar;

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

Even if you don't have any third party editor (Notepad++ etc.) then also you can create files with dot as prefix.

To create .htaccess file, first create htaccess.txt file with Context Menu > New Text Document.

Then press Alt + D (Windows 7) and Ctrl + C to copy the path from the Address bar of Windows Explorer.

Then go to command line and type code as below to rename your file:

rename C:\path\to\htaccess.txt .htaccess

Now you have a blank .htaccess without opening it in any editor.

Hope this helps you out.

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

Depending on how well the makefile/configure script/autofoo magic of the program in question is the following might solve your problem:

make uninstall

The problem is that you should execute this on the source tree of the version you've got installed and with exactly the same configuration that you used for installing.

Component is part of the declaration of 2 modules

I had the same error but I discovered that when you import an AddEventModule, you can't import an AddEvent module as it would present an error in this case.

cordova Android requirements failed: "Could not find an installed version of Gradle"

For Windows:

-Download last version of Gradle (https://gradle.org/releases)

-Create a folder and unzip files (I use C:\Program Files (x86)\gradle)

-Copy the path with the bin directory included (C:\Program Files (x86)\gradle\bin)

-Set the path C:\Program Files (x86)\gradle\bin (in my exemple) to "Path Environment Variables"

Variable name "Path" and variable value "C:\Program Files (x86)\gradle\bin" for both: User Variable table and System Variables table

You may need to reopen the "Prompt commad line"

To test, type gradle in prompt.

What's causing my java.net.SocketException: Connection reset?

In my case, this was because my Tomcat was set with an insufficient maxHttpHeaderSize for a particularly complicated SOLR query.

Hope this helps someone out there!

Combine multiple JavaScript files into one JS file

Script grouping is counterproductive, you should load them in parallel using something like http://yepnopejs.com/ or http://headjs.com

Convert True/False value read from file to boolean

If your data is from json, you can do that

import json

json.loads('true')

True

HTTP Error 503, the service is unavailable

Check your application's respective Application Framework Pool - it could be stopped. If it is, start it and check again.

If you're still experiencing issues you can also check out Event Viewer to find the cause of that error in order to troubleshoot more.

How to iterate std::set?

How do you iterate std::set?

int main(int argc,char *argv[]) 
{
    std::set<int> mset;
    mset.insert(1); 
    mset.insert(2);
    mset.insert(3);

    for ( auto it = mset.begin(); it != mset.end(); it++ )
        std::cout << *it;
}

Checking for empty or null List<string>

Assuming that the list is never null, the following code checks if the list is empty and adds a new element if empty:

if (!myList.Any())
{
    myList.Add("new item");
}

If it is possible that the list is null, a null check must be added before the Any() condition:

if (myList != null && !myList.Any())
{
    myList.Add("new item");
}

In my opinion, using Any() instead of Count == 0 is preferable since it better expresses the intent of checking if the list has any element or is empty. However, considering the performance of each approach, using Any() is generally slower than Count.

How to refresh activity after changing language (Locale) inside application

Call this method to change app locale:

public void settingLocale(Context context, String language) {

    Locale locale;

    Configuration config = new Configuration();

     if(language.equals(LANGUAGE_ENGLISH)) {

        locale = new Locale("en");

        Locale.setDefault(locale);

        config.locale = locale;

    }else if(language.equals(LANGUAGE_ARABIC)){

        locale = new Locale("hi");

        Locale.setDefault(locale);

        config.locale = locale;

    }

    context.getResources().updateConfiguration(config, null);

    // Here again set the text on view to reflect locale change

    // and it will pick resource from new locale

    tv1.setText(R.string.one); //tv1 is textview in my activity

}

Note: Put your strings in value and values- folder.

VBA: How to delete filtered rows in Excel?

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

React Router with optional path parameter

For any React Router v4 users arriving here following a search, optional parameters in a <Route> are denoted with a ? suffix.

Here's the relevant documentation:

https://reacttraining.com/react-router/web/api/Route/path-string

path: string

Any valid URL path that path-to-regexp understands.

    <Route path="/users/:id" component={User}/>

https://www.npmjs.com/package/path-to-regexp#optional

Optional

Parameters can be suffixed with a question mark (?) to make the parameter optional. This will also make the prefix optional.

Simple example of a paginated section of a site that can be accessed with or without a page number.

    <Route path="/section/:page?" component={Section} />

Replace all non-alphanumeric characters in a string

Regex to the rescue!

import re

s = re.sub('[^0-9a-zA-Z]+', '*', s)

Example:

>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'