Programs & Examples On #Nant

NAnt is a build tool for .Net, aiming to support all the various versions of the .Net framework, including all versions of Microsoft .NET, Compact Framework and Silverlight, Mono and Moonlight. Additionally, there is a contribution project called NAntContrib, adding support for additional .Net tools (FxCop, NGen, GacUtil, Wsdl, XSD, MSBuild) and systems like PVCS, StarTeam, Visual SourceSafe, Surround SCM and Microsoft BizTalk.

How to use 'git pull' from the command line?

One more option is to add the path of the privatekey file like this in terminal:

ssh-add "path to the privatekeyfile"

and then execute the pull command

Python extending with - using super() Python 3 vs Python 2

Another python3 implementation that involves the use of Abstract classes with super(). You should remember that

super().__init__(name, 10)

has the same effect as

Person.__init__(self, name, 10)

Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it. Hence super()gets translated to Person and then if you include the hidden self, you get the above code frag.

from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

    @abstractmethod
    def showName(self):
        pass

    @abstractmethod
    def showAge(self):
        pass


class Man(Person):

    def __init__(self, name, height):
        self.height = height
        # Person.__init__(self, name, 10)
        super().__init__(name, 10)  # same as Person.__init__(self, name, 10)
        # basically used to call the superclass init . This is used incase you want to call subclass init
        # and then also call superclass's init.
        # Since there's a hidden self in the super's parameters, when it's is called,
        # the superclasses attributes are a part of the same object that was sent out in the super() method

    def showIdentity(self):
        return self.name, self.age, self.height

    def showName(self):
        pass

    def showAge(self):
        pass


a = Man("piyush", "179")
print(a.showIdentity())

Using Python's ftplib to get a directory listing, portably

The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers.

import ftplib
f = ftplib.FTP()
f.connect("localhost")
f.login()
ls = []
f.retrlines('MLSD', ls.append)
for entry in ls:
    print entry

The code above will print:

modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests
modify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2
modify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd
modify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart
...

Starting from python 3.3, ftplib will provide a specific method to do this:

How to grant all privileges to root user in MySQL 8.0

Check out your username and domain is the same as created before. Mysql select account by the two colums in user table.If it is different, mysql may think you want to create a new account by grant,which is not supported after 8.0 version.

Finding common rows (intersection) in two Pandas dataframes

If I understand you correctly, you can use a combination of Series.isin() and DataFrame.append():

In [80]: df1
Out[80]:
   rating  user_id
0       2  0x21abL
1       1  0x21abL
2       1   0xdafL
3       0  0x21abL
4       4  0x1d14L
5       2  0x21abL
6       1  0x21abL
7       0   0xdafL
8       4  0x1d14L
9       1  0x21abL

In [81]: df2
Out[81]:
   rating      user_id
0       2      0x1d14L
1       1    0xdbdcad7
2       1      0x21abL
3       3      0x21abL
4       3      0x21abL
5       1  0x5734a81e2
6       2      0x1d14L
7       0       0xdafL
8       0      0x1d14L
9       4  0x5734a81e2

In [82]: ind = df2.user_id.isin(df1.user_id) & df1.user_id.isin(df2.user_id)

In [83]: ind
Out[83]:
0     True
1    False
2     True
3     True
4     True
5    False
6     True
7     True
8     True
9    False
Name: user_id, dtype: bool

In [84]: df1[ind].append(df2[ind])
Out[84]:
   rating  user_id
0       2  0x21abL
2       1   0xdafL
3       0  0x21abL
4       4  0x1d14L
6       1  0x21abL
7       0   0xdafL
8       4  0x1d14L
0       2  0x1d14L
2       1  0x21abL
3       3  0x21abL
4       3  0x21abL
6       2  0x1d14L
7       0   0xdafL
8       0  0x1d14L

This is essentially the algorithm you described as "clunky", using idiomatic pandas methods. Note the duplicate row indices. Also, note that this won't give you the expected output if df1 and df2 have no overlapping row indices, i.e., if

In [93]: df1.index & df2.index
Out[93]: Int64Index([], dtype='int64')

In fact, it won't give the expected output if their row indices are not equal.

jQuery: count number of rows in a table

Here's my take on it:

//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
    return $('tr', $(this).find('tbody')).length;
};

USAGE:

var rowCount = $('#productTypesTable').rowCount();

How do you find out the type of an object (in Swift)?

Old question, but this works for my need (Swift 5.x):

print(type(of: myObjectName))

Context.startForegroundService() did not then call Service.startForeground()

Ok, something I noticed on this that might help a few others too. This is strictly from testing to see if I could figure out how to fix the occurrences I am seeing. For simplicity sake, let's say I have a method that calls this from the presenter.

context.startForegroundService(new Intent(context, TaskQueueExecutorService.class));

try {
    Thread.sleep(10000);
} catch (InterruptedException e) {
    e.printStackTrace();
}       

This will crash with the same error. The Service will NOT start until the method is complete, therefore no onCreate() in the service.

So even if you update the UI off the main thread, IF you have anything that might hold up that method after it, it won't start on time and give you the dreaded Foreground Error. In my case we were loading some things onto a queue and each called startForegroundService, but some logic was involved with each in the background. So if the logic took too long to finish that method since they were called back to back, crash time. The old startService just ignored it and went on it's way and since we called it each time, the next round would finish up.

This left me wondering, if I called the service from a thread in the background, could it not be fully bound on the start and run immediately, so I started experimenting. Even though this does NOT start it immediately, it does not crash.

new Handler(Looper.getMainLooper()).post(new Runnable() {
        public void run() {
               context.startForegroundService(new Intent(context, 
           TaskQueueExecutorService.class));
               try {
                   Thread.sleep(10000);
               } catch (InterruptedException e) {
                  e.printStackTrace();
              }       
        }
});

I will not pretend to know why it does not crash although I suspect this forces it to wait until the main thread can handle it in a timely fashion. I know it's not ideal to tie it to the main thread, but since my usage calls it in the background, I'm not real concerned if it waits until it can complete rather than crash.

How to wait for the 'end' of 'resize' event and only then perform an action?

This is the code that I write according to @Mark Coleman answer:

$(window).resize(function() {
    clearTimeout(window.resizedFinished);
    window.resizedFinished = setTimeout(function(){
        console.log('Resized finished.');
    }, 250);
});

Thanks Mark!

How can I make sticky headers in RecyclerView? (Without external lib)

The answer has already been here. If you don't want to use any library, you can follow these steps:

  1. Sort list with data by name
  2. Iterate via list with data, and in place when current's item first letter != first letter of next item, insert "special" kind of object.
  3. Inside your Adapter place special view when item is "special".

Explanation:

In onCreateViewHolder method we can check viewType and depending on the value (our "special" kind) inflate a special layout.

For example:

public static final int TITLE = 0;
public static final int ITEM = 1;

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (context == null) {
        context = parent.getContext();
    }
    if (viewType == TITLE) {
        view = LayoutInflater.from(context).inflate(R.layout.recycler_adapter_title, parent,false);
        return new TitleElement(view);
    } else if (viewType == ITEM) {
        view = LayoutInflater.from(context).inflate(R.layout.recycler_adapter_item, parent,false);
        return new ItemElement(view);
    }
    return null;
}

where class ItemElement and class TitleElement can look like ordinary ViewHolder :

public class ItemElement extends RecyclerView.ViewHolder {
//TextView text;

public ItemElement(View view) {
    super(view);
   //text = (TextView) view.findViewById(R.id.text);

}

So the idea of all of that is interesting. But i am interested if it's effectively, cause we need to sort the data list. And i think this will take the speed down. If any thoughts about it, please write me :)

And also the opened question : is how to hold the "special" layout on the top, while the items are recycling. Maybe combine all of that with CoordinatorLayout.

CREATE TABLE LIKE A1 as A2

CREATE TABLE new_table LIKE old_table;

or u can use this

CREATE TABLE new_table as SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by];

In C# check that filename is *possibly* valid (not that it exists)

There are several methods you could use that exist in the System.IO namespace:

Directory.GetLogicalDrives() // Returns an array of strings like "c:\"
Path.GetInvalidFileNameChars() // Returns an array of characters that cannot be used in a file name
Path.GetInvalidPathChars() // Returns an array of characters that cannot be used in a path.

As suggested you could then do this:

bool IsValidFilename(string testName) {
    string regexString = "[" + Regex.Escape(Path.GetInvalidPathChars()) + "]";
    Regex containsABadCharacter = new Regex(regexString);
    if (containsABadCharacter.IsMatch(testName)) {
        return false;
    }

    // Check for drive
    string pathRoot = Path.GetPathRoot(testName);
    if (Directory.GetLogicalDrives().Contains(pathRoot)) {
        // etc
    }

    // other checks for UNC, drive-path format, etc

    return true;
}

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

INSERT INTO mytable(col1,col2) 
    SELECT 'val1','val2' 
    WHERE NOT EXISTS (SELECT 1 FROM mytable WHERE col1='val1')

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

how to zip a folder itself using java

Using zip4j you can simply do this

ZipFile zipfile = new ZipFile(new File("D:\\reports\\january\\filename.zip"));
zipfile.addFolder(new File("D:\\reports\\january\\"));

It will archive your folder and everything in it.

Use the .extractAll method to get it all out:

zipfile.extractAll("D:\\destination_directory");

JavaScript/jQuery to download file via POST with JSON data

I have been awake for two days now trying to figure out how to download a file using jquery with ajax call. All the support i got could not help my situation until i try this.

Client Side

_x000D_
_x000D_
function exportStaffCSV(t) {_x000D_
   _x000D_
    var postData = { checkOne: t };_x000D_
    $.ajax({_x000D_
        type: "POST",_x000D_
        url: "/Admin/Staff/exportStaffAsCSV",_x000D_
        data: postData,_x000D_
        success: function (data) {_x000D_
            SuccessMessage("file download will start in few second..");_x000D_
            var url = '/Admin/Staff/DownloadCSV?data=' + data;_x000D_
            window.location = url;_x000D_
        },_x000D_
       _x000D_
        traditional: true,_x000D_
        error: function (xhr, status, p3, p4) {_x000D_
            var err = "Error " + " " + status + " " + p3 + " " + p4;_x000D_
            if (xhr.responseText && xhr.responseText[0] == "{")_x000D_
                err = JSON.parse(xhr.responseText).Message;_x000D_
            ErrorMessage(err);_x000D_
        }_x000D_
    });_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

Server Side

 [HttpPost]
    public string exportStaffAsCSV(IEnumerable<string> checkOne)
    {
        StringWriter sw = new StringWriter();
        try
        {
            var data = _db.staffInfoes.Where(t => checkOne.Contains(t.staffID)).ToList();
            sw.WriteLine("\"First Name\",\"Last Name\",\"Other Name\",\"Phone Number\",\"Email Address\",\"Contact Address\",\"Date of Joining\"");
            foreach (var item in data)
            {
                sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\"",
                    item.firstName,
                    item.lastName,
                    item.otherName,
                    item.phone,
                    item.email,
                    item.contact_Address,
                    item.doj
                    ));
            }
        }
        catch (Exception e)
        {

        }
        return sw.ToString();

    }

    //On ajax success request, it will be redirected to this method as a Get verb request with the returned date(string)
    public FileContentResult DownloadCSV(string data)
    {
        return File(new System.Text.UTF8Encoding().GetBytes(data), System.Net.Mime.MediaTypeNames.Application.Octet, filename);
        //this method will now return the file for download or open.
    }

Good luck.

Difference between string and text in rails?

If you are using oracle... STRING will be created as VARCHAR(255) column and TEXT, as a CLOB.

NATIVE_DATABASE_TYPES = {
    primary_key: "NUMBER(38) NOT NULL PRIMARY KEY",
    string: { name: "VARCHAR2", limit: 255 },
    text: { name: "CLOB" },
    ntext: { name: "NCLOB" },
    integer: { name: "NUMBER", limit: 38 },
    float: { name: "BINARY_FLOAT" },
    decimal: { name: "DECIMAL" },
    datetime: { name: "TIMESTAMP" },
    timestamp: { name: "TIMESTAMP" },
    timestamptz: { name: "TIMESTAMP WITH TIME ZONE" },
    timestampltz: { name: "TIMESTAMP WITH LOCAL TIME ZONE" },
    time: { name: "TIMESTAMP" },
    date: { name: "DATE" },
    binary: { name: "BLOB" },
    boolean: { name: "NUMBER", limit: 1 },
    raw: { name: "RAW", limit: 2000 },
    bigint: { name: "NUMBER", limit: 19 }
}

https://github.com/rsim/oracle-enhanced/blob/master/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb

What happened to Lodash _.pluck?

If you really want _.pluck support back, you can use a mixin:

const _ = require("lodash")

_.mixin({
    pluck: _.map
})

Because map now supports a string (the "iterator") as an argument instead of a function.

Use CASE statement to check if column exists in table - SQL Server

Try this one -

SELECT *
FROM ...
WHERE EXISTS(SELECT 1 
        FROM sys.columns c
        WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
            AND c.name = 'ModifiedByUser'
    )

How to install SQL Server Management Studio 2012 (SSMS) Express?

Good evening,

The previous clues to get SQLManagementStudio_x64_ENU.exe runing didn't work as stated for me. After a while of searching, trying, retrying again and again, I finally figured it out. When executing SQLManagementStudio_x64_ENU.exe on my Windows seven system, I kept runing into compatibility issues. The trick is to run SQLManagementStudio_x64_ENU.exe in compatibility mode with Windows XP SP2. Edit the installer properties and enable compatibility mode with XP (service pack 2), then you'll be able to access Mr Doug (answered Mar 4 at 15:09) resolution.

Cheers.

Display text on MouseOver for image in html

You can use CSS hover in combination with an image background.

CSS

   .image
{
    background:url(images/back.png);
    height:100px;
    width:100px;
    display: block;
    float:left;
}

.image  a {
    display: none;
}

.image  a:hover {
    display: block;
}

HTML

<div class="image"><a href="#">Text you want on mouseover</a></div>

Get Mouse Position

If you're using Swing as your UI layer, you can use a Mouse-Motion Listener for this.

Do sessions really violate RESTfulness?

HTTP transaction, basic access authentication, is not suitable for RBAC, because basic access authentication uses the encrypted username:password every time to identify, while what is needed in RBAC is the Role the user wants to use for a specific call. RBAC does not validate permissions on username, but on roles.

You could tric around to concatenate like this: usernameRole:password, but this is bad practice, and it is also inefficient because when a user has more roles, the authentication engine would need to test all roles in concatenation, and that every call again. This would destroy one of the biggest technical advantages of RBAC, namely a very quick authorization-test.

So that problem cannot be solved using basic access authentication.

To solve this problem, session-maintaining is necessary, and that seems, according to some answers, in contradiction with REST.

That is what I like about the answer that REST should not be treated as a religion. In complex business cases, in healthcare, for example, RBAC is absolutely common and necessary. And it would be a pity if they would not be allowed to use REST because all REST-tools designers would treat REST as a religion.

For me there are not many ways to maintain a session over HTTP. One can use cookies, with a sessionId, or a header with a sessionId.

If someone has another idea I will be glad to hear it.

How do you dynamically allocate a matrix?

Here is the most clear & intuitive way i know to allocate a dynamic 2d array in C++. Templated in this example covers all cases.

template<typename T> T** matrixAllocate(int rows, int cols, T **M)
{
    M = new T*[rows];
    for (int i = 0; i < rows; i++){
        M[i] = new T[cols];
    }
    return M;
}

... 

int main()
{
    ...
    int** M1 = matrixAllocate<int>(rows, cols, M1);
    double** M2 = matrixAllocate(rows, cols, M2);
    ...
}

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

When using Object.keys, the following works:

Object.keys(this)
    .forEach(key => {
      console.log(this[key as keyof MyClass]);
    });

How to read large text file on windows?

I just used less on top of Cygwin to read a 3GB file, though I ended up using grep to find what I needed in it.

(less is more, but better.)

See this answer for more details on less: https://stackoverflow.com/a/1343576/1005039

Maven with Eclipse Juno

All the info you need, is provided in the release announcement for m2e 1.1:

m2e 1.1 has been released as part of Eclipse Juno simultaneous release today.

[...]

m2e 1.1 is already included in "Eclipse IDE for Java Developers" package available from http://eclipse.org/downloads/ or it can be installed from Eclipse Juno release repository [2]. Eclipse 3.7/Indigo users can install the new version from m2e release repository [3]

[...]

[2] http://download.eclipse.org/releases/juno

[3] http://download.eclipse.org/technology/m2e/releases

Format numbers in django templates

Building on other answers, to extend this to floats, you can do:

{% load humanize %}
{{ floatvalue|floatformat:2|intcomma }}

Documentation: floatformat, intcomma.

How can I get last characters of a string

Last 5

_x000D_
_x000D_
var id="ctl03_Tabs1";_x000D_
var res = id.charAt(id.length-5)_x000D_
alert(res);
_x000D_
_x000D_
_x000D_

Last

_x000D_
_x000D_
   _x000D_
 var id="ctl03_Tabs1";_x000D_
 var res = id.charAt(id.length-1)_x000D_
alert(res);
_x000D_
_x000D_
_x000D_

Set mouse focus and move cursor to end of input using jQuery

It will be different for different browsers:

This works in ff:

    var t =$("#INPUT");
    var l=$("#INPUT").val().length;
    $(t).focus();

    var r = $("#INPUT").get(0).createTextRange();
    r.moveStart("character", l); 
    r.moveEnd("character", l);      
    r.select();

More details are in these articles here at SitePoint, AspAlliance.

Java's L number (long) specification

There are specific suffixes for long (e.g. 39832L), float (e.g. 2.4f) and double (e.g. -7.832d).

If there is no suffix, and it is an integral type (e.g. 5623), it is assumed to be an int. If it is not an integral type (e.g. 3.14159), it is assumed to be a double.

In all other cases (byte, short, char), you need the cast as there is no specific suffix.

The Java spec allows both upper and lower case suffixes, but the upper case version for longs is preferred, as the upper case L is less easy to confuse with a numeral 1 than the lower case l.

See the JLS section 3.10 for the gory details (see the definition of IntegerTypeSuffix).

Https to http redirect using htaccess

You can use the following rule to redirect from https to http :

 RewriteEngine On


RewriteCond %{HTTPS} ^on$
RewriteRule ^(.*)$ http://example.com/$1 [NC,L,R]

Explanation :

RewriteCond %{HTTPS} ^on$

Checks if the HTTPS is on (Request is made using https)

Then

RewriteRule ^(.*)$ http://example.com/$1 [NC,L,R]

Redirect any request (https://example.com/foo) to http://example.com/foo .

  • $1 is part of the regex in RewriteRule pattern, it contains whatever value was captured in (.+) , in this case ,it captures the full request_uri everything after the domain name.

  • [NC,L,R] are the flags, NC makes the uri case senstive, you can use both uppercase or lowercase letters in the request.

L flag tells the server to stop proccessing other rules if the currunt rule has matched, it is important to use the L flag to avoid rule confliction when you have more then on rules in a block.

R flag is used to make an external redirection.

Count unique values using pandas groupby

I know it has been a while since this was posted, but I think this will help too. I wanted to count unique values and filter the groups by number of these unique values, this is how I did it:

df.groupby('group').agg(['min','max','count','nunique']).reset_index(drop=False)

Best way to Bulk Insert from a C# DataTable

Here's how I do it using a DataTable. This is a working piece of TEST code.

using (SqlConnection con = new SqlConnection(connStr))
{
    con.Open();

    // Create a table with some rows. 
    DataTable table = MakeTable();

    // Get a reference to a single row in the table. 
    DataRow[] rowArray = table.Select();

    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
    {
        bulkCopy.DestinationTableName = "dbo.CarlosBulkTestTable";

        try
        {
            // Write the array of rows to the destination.
            bulkCopy.WriteToServer(rowArray);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

}//using

jQuery trigger file input

Try this, it's a hack. the Position:absolute is for Chrome and trigger('change') is for IE.

var hiddenFile = $("<input type=\"file\" name=\"file\" id=\"file1\" style=\"position:absolute;left:-9999px\" />");
$('body').append(hiddenFile);

$('#aPhotoUpload').click(function () {
    hiddenFile.trigger('click');
    if ($.browser.msie)
        hiddenFile.trigger('change');
});

hiddenFile.change(function (e) {
    alert('TODO');
});

Get the string value from List<String> through loop for display

Answer if you only want to use for each loop ..

for (WebElement s : options) {
    int i = options.indexOf(s);
    System.out.println(options.get(i).getText());
}

Count number of occurrences for each unique value

You should change the query to:

SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col

This vl works correctly.

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

What is the best way to manage a user's session in React?

There is a React module called react-client-session that makes storing client side session data very easy. The git repo is here.

This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).

  1. Cookie
  2. localStorage
  3. sessionStorage

After installing, just set the desired store type where you mount the root component ...

import ReactSession from 'react-client-session';

ReactSession.setStoreType("localStorage");

... and set/get key value pairs from anywhere in your app:

import ReactSession from 'react-client-session';

ReactSession.set("username", "Bob");
ReactSession.get("username");  // Returns "Bob"

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

You can try the code below, it works perfectly.

Here we share to some specific apps, that are Facebook, Messenger, Twitter, Google Plus and Gmail.

public void shareIntentSpecificApps() {
        List<Intent> intentShareList = new ArrayList<Intent>();
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(shareIntent, 0);

        for (ResolveInfo resInfo : resolveInfoList) {
            String packageName = resInfo.activityInfo.packageName;
            String name = resInfo.activityInfo.name;
            Log.d(TAG, "Package Name : " + packageName);
            Log.d(TAG, "Name : " + name);

            if (packageName.contains("com.facebook") ||
                    packageName.contains("com.twitter.android") ||
                    packageName.contains("com.google.android.apps.plus") ||
                    packageName.contains("com.google.android.gm")) {

                if (name.contains("com.twitter.android.DMActivity")) {
                    continue;
                }

                Intent intent = new Intent();
                intent.setComponent(new ComponentName(packageName, name));
                intent.setAction(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, "Your Subject");
                intent.putExtra(Intent.EXTRA_TEXT, "Your Content");
                intentShareList.add(intent);
            }
        }

        if (intentShareList.isEmpty()) {
            Toast.makeText(MainActivity.this, "No apps to share !", Toast.LENGTH_SHORT).show();
        } else {
            Intent chooserIntent = Intent.createChooser(intentShareList.remove(0), "Share via");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentShareList.toArray(new Parcelable[]{}));
            startActivity(chooserIntent);
        }
    }

Getting Access Denied when calling the PutObject operation with bucket-level permission

Error : An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

I solved the issue by passing Extra Args parameter as PutObjectAcl is disabled by company policy.

s3_client.upload_file('./local_file.csv', 'bucket-name', 'path', ExtraArgs={'ServerSideEncryption': 'AES256'})

Convert a python dict to a string and back

I use json:

import json

# convert to string
input = json.dumps({'id': id })

# load to dict
my_dict = json.loads(input) 

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.

There are different types of joins available in SQL:

INNER JOIN: returns rows when there is a match in both tables.

LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.

RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.

FULL JOIN: It combines the results of both left and right outer joins.

The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.

SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.

CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.

WE can take each first four joins in Details :

We have two tables with the following values.

TableA

id  firstName                  lastName
.......................................
1   arun                        prasanth                 
2   ann                         antony                   
3   sruthy                      abc                      
6   new                         abc                                           

TableB

id2 age Place
................
1   24  kerala
2   24  usa
3   25  ekm
5   24  chennai

....................................................................

INNER JOIN

Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
 INNER JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
 INNER JOIN TableB
    ON TableA.id = TableB.id2;

Result Will Be

firstName       lastName       age  Place
..............................................
arun            prasanth        24  kerala
ann             antony          24  usa
sruthy          abc             25  ekm

LEFT JOIN

Note : will give all selected rows in TableA, plus any common selected rows in TableB.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
  LEFT JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
  LEFT JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age   Place
...............................................................................
arun                        prasanth                    24    kerala
ann                         antony                      24    usa
sruthy                      abc                         25    ekm
new                         abc                         NULL  NULL

RIGHT JOIN

Note : will give all selected rows in TableB, plus any common selected rows in TableA.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
 RIGHT JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
 RIGHT JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age     Place
...............................................................................
arun                        prasanth                    24     kerala
ann                         antony                      24     usa
sruthy                      abc                         25     ekm
NULL                        NULL                        24     chennai

FULL JOIN

Note :It will return all selected values from both tables.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
  FULL JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
  FULL JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age    Place
...............................................................................
arun                        prasanth                    24    kerala
ann                         antony                      24    usa
sruthy                      abc                         25    ekm
new                         abc                         NULL  NULL
NULL                        NULL                        24    chennai

Interesting Fact

For INNER joins the order doesn't matter

For (LEFT, RIGHT or FULL) OUTER joins,the order matter

Better to go check this Link it will give you interesting details about join order

Equivalent to 'app.config' for a library (DLL)

I faced the same problem and resolved it by creating a static class Parameters after adding an Application Configuration File to the project:

public static class Parameters
{
    // For a Web Application
    public static string PathConfig { get; private set; } =
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "web.config");

    // For a Class Library
    public static string PathConfig { get; private set; } =
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", "LibraryName.dll.config");

    public static string GetParameter(string paramName)
    {
        string paramValue = string.Empty;

        using (Stream stream = File.OpenRead(PathConfig))
        {
            XDocument xdoc = XDocument.Load(stream);

            XElement element = xdoc.Element("configuration").Element("appSettings").Elements().First(a => a.Attribute("key").Value == paramName);
            paramValue = element.Attribute("value").Value;
        }

        return paramValue;
    }
}

Then get a parameter like this:

Parameters.GetParameter("keyName");

Can "git pull --all" update all my local branches?

The script from @larsmans, a bit improved:

#!/bin/sh

set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
  if ["$branch" -ne "$CURRENT"]; then
    git checkout "$branch" || exit 1
    git rebase "origin/$branch" || exit 1
  fi
done
git checkout "$CURRENT" || exit 1
git rebase "origin/$CURRENT" || exit 1

This, after it finishes, leaves working copy checked out from the same branch as it was before the script was called.

The git pull version:

#!/bin/sh

set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
  if ["$branch" -ne "$CURRENT"]; then
    git checkout "$branch" || exit 1
    git pull || exit 1
  fi
done
git checkout "$CURRENT" || exit 1
git pull || exit 1

How to get substring of NSString?

Option 1:

NSString *haystack = @"value:hello World:value";
NSString *haystackPrefix = @"value:";
NSString *haystackSuffix = @":value";
NSRange needleRange = NSMakeRange(haystackPrefix.length,
                                  haystack.length - haystackPrefix.length - haystackSuffix.length);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle); // -> "hello World"

Option 2:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^value:(.+?):value$" options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)];
NSRange needleRange = [match rangeAtIndex: 1];
NSString *needle = [haystack substringWithRange:needleRange];

This one might be a bit over the top for your rather trivial case though.

Option 3:

NSString *needle = [haystack componentsSeparatedByString:@":"][1];

This one creates three temporary strings and an array while splitting.


All snippets assume that what's searched for is actually contained in the string.

For loop for HTMLCollection elements

As of March 2016, in Chrome 49.0, for...of works for HTMLCollection:

this.headers = this.getElementsByTagName("header");

for (var header of this.headers) {
    console.log(header); 
}

See here the documentation.

But it only works if you apply the following workaround before using the for...of:

HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];

The same is necessary for using for...of with NodeList:

NamedNodeMap.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];

I believe/hope for...of will soon work without the above workaround. The open issue is here:

https://bugs.chromium.org/p/chromium/issues/detail?id=401699

Update: See Expenzor's comment below: This has been fixed as of April 2016. You don't need to add HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator]; to iterate over an HTMLCollection with for...of

How do I fix this "TypeError: 'str' object is not callable" error?

You are trying to use the string as a function:

"Your new price is: $"(float(price) * 0.1)

Because there is nothing between the string literal and the (..) parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:

>>> "Hello World!"(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Seems you forgot to concatenate (and call str()):

easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))

The next line needs fixing as well:

easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))

Alternatively, use string formatting with str.format():

easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))

where {:02.2f} will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.

MySQL INSERT INTO ... VALUES and SELECT

Use an insert ... select query, and put the known values in the select:

insert into table1
select 'A string', 5, idTable2
from table2
where ...

How do I update Anaconda?

root is the old (pre-conda 4.4) name for the main environment; after conda 4.4, it was renamed to be base. source

What 95% of people actually want

In most cases what you want to do when you say that you want to update Anaconda is to execute the command:

conda update --all

(But this should be preceeded by conda update -n base conda so you have the latest conda version installed)

This will update all packages in the current environment to the latest version -- with the small print being that it may use an older version of some packages in order to satisfy dependency constraints (often this won't be necessary and when it is necessary the package plan solver will do its best to minimize the impact).

This needs to be executed from the command line, and the best way to get there is from Anaconda Navigator, then the "Environments" tab, then click on the triangle beside the base environment, selecting "Open Terminal":

Open terminal from Navigator

This operation will only update the one selected environment (in this case, the base environment). If you have other environments you'd like to update you can repeat the process above, but first click on the environment. When it is selected there is a triangular marker on the right (see image above, step 3). Or from the command line you can provide the environment name (-n envname) or path (-p /path/to/env), for example to update your dspyr environment from the screenshot above:

conda update -n dspyr --all

Update individual packages

If you are only interested in updating an individual package then simply click on the blue arrow or blue version number in Navigator, e.g. for astroid or astropy in the screenshot above, and this will tag those packages for an upgrade. When you are done you need to click the "Apply" button:

Apply to update individual packages

Or from the command line:

conda update astroid astropy

Updating just the packages in the standard Anaconda Distribution

If you don't care about package versions and just want "the latest set of all packages in the standard Anaconda Distribution, so long as they work together", then you should take a look at this gist.

Why updating the Anaconda package is almost always a bad idea

In most cases updating the Anaconda package in the package list will have a surprising result: you may actually downgrade many packages (in fact, this is likely if it indicates the version as custom). The gist above provides details.

Leverage conda environments

Your base environment is probably not a good place to try and manage an exact set of packages: it is going to be a dynamic working space with new packages installed and packages randomly updated. If you need an exact set of packages then create a conda environment to hold them. Thanks to the conda package cache and the way file linking is used doing this is typically i) fast and ii) consumes very little additional disk space. E.g.

conda create -n myspecialenv -c bioconda -c conda-forge python=3.5 pandas beautifulsoup seaborn nltk

The conda documentation has more details and examples.

pip, PyPI, and setuptools?

None of this is going to help with updating packages that have been installed from PyPI via pip or any packages installed using python setup.py install. conda list will give you some hints about the pip-based Python packages you have in an environment, but it won't do anything special to update them.

Commercial use of Anaconda or Anaconda Enterprise

It is pretty much exactly the same story, with the exception that you may not be able to update the base environment if it was installed by someone else (say to /opt/anaconda/latest). If you're not able to update the environments you are using you should be able to clone and then update:

conda create -n myenv --clone base
conda update -n myenv --all

WPF MVVM: How to close a window

We have the name property in the .xaml definition:

x:Name="WindowsForm"

Then we have the button:

<Button Command="{Binding CloseCommand}" 
CommandParameter="{Binding ElementName=WindowsForm}" />

Then in the ViewModel:

public DelegateCommand <Object>  CloseCommand { get; private set; }

Constructor for that view model:
this.CloseCommand = new DelegateCommand<object>(this.CloseAction);

Then at last, the action method:

private void CloseAction (object obj)
{
  Window Win = obj as Window;
  Win.Close();

}

I used this code to close a pop-up window from an application..

offsetting an html anchor to adjust for fixed header

As @moeffju suggests, this can be achieved with CSS. The issue I ran into (which I'm surprised I haven't seen discussed) is the trick of overlapping previous elements with padding or a transparent border prevents hover and click actions at the bottom of those sections because the following one comes higher in the z-order.

The best fix I found was to place section content in a div that is at z-index: 1:

// Apply to elements that serve as anchors
.offset-anchor {
  border-top: 75px solid transparent;
  margin: -75px 0 0;
  -webkit-background-clip: padding-box;
  -moz-background-clip: padding;
  background-clip: padding-box;
}

// Because offset-anchor causes sections to overlap the bottom of previous ones,
// we need to put content higher so links aren't blocked by the transparent border.
.container {
  position: relative;
  z-index: 1;
}

Inline SVG in CSS

On Mac/Linux, you can easily convert a SVG file to a base64 encoded value for CSS background attribute with this simple bash command:

echo "background: transparent url('data:image/svg+xml;base64,"$(openssl base64 < path/to/file.svg)"') no-repeat center center;"

Tested on Mac OS X. This way you also avoid the URL escaping mess.

Remember that base64 encoding an SVG file increase its size, see css-tricks.com blog post.

Looping over a list in Python

You may as well use for x in values rather than for x in values[:]; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3...

The code only prints one item per value of x - and x is iterating over the elements of values, which are the sublists. So it will only print each sublist once.

How to access html form input from asp.net code behind

What I'm guessing is that you need to set those input elements to runat="server".

So you won't be able to access the control

<input type="text" name="email" id="myTextBox" />

But you'll be able to work with

<input type="text" name="email" id="myTextBox" runat="server" />

And read from it by using

string myStringFromTheInput = myTextBox.Value;

jQuery hasAttr checking to see if there is an attribute on an element

If you will be checking the existence of attributes frequently, I would suggest creating a hasAttr function, to use as you hypothesized in your question:

$.fn.hasAttr = function(name) {  
   return this.attr(name) !== undefined;
};

$(document).ready(function() {
    if($('.edit').hasAttr('id')) {
        alert('true');
    } else {
        alert('false');
    }
});

<div class="edit" id="div_1">Test field</div>

How to add a bot to a Telegram Group?

Edit: now there is yet an easier way to do this - when creating your group, just mention the full bot name (eg. @UniversalAgent1Bot) and it will list it as you type. Then you can just tap on it to add it.

Old answer:

  1. Create a new group from the menu. Don't add any bots yet
  2. Find the bot (for instance you can go to Contacts and search for it)
  3. Tap to open
  4. Tap the bot name on the top bar. Your page becomes like this: Telegram bot settings
  5. Now, tap the triple ... and you will get the Add to Group button: Adding the bot
  6. Now select your group and add the bot - and confirm the addition

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

That won't work in IE<9 though, however, you can make IEs support that using:

CSS3Pie

PIE makes Internet Explorer 6-8 capable of rendering several of the most useful CSS3 decoration features.

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

How to count check-boxes using jQuery?

Assume that you have a tr row with multiple checkboxes in it, and you want to count only if the first checkbox is checked.

You can do that by giving a class to the first checkbox

For example class='mycxk' and you can count that using the filter, like this

$('.mycxk').filter(':checked').length

How to state in requirements.txt a direct github source

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here's my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation

What's the most concise way to read query parameters in AngularJS?

Good that you've managed to get it working with the html5 mode but it is also possible to make it work in the hashbang mode.

You could simply use:

$location.search().target

to get access to the 'target' search param.

For the reference, here is the working jsFiddle: http://web.archive.org/web/20130317065234/http://jsfiddle.net/PHnLb/7/

_x000D_
_x000D_
var myApp = angular.module('myApp', []);_x000D_
_x000D_
function MyCtrl($scope, $location) {_x000D_
_x000D_
    $scope.location = $location;_x000D_
    $scope.$watch('location.search()', function() {_x000D_
        $scope.target = ($location.search()).target;_x000D_
    }, true);_x000D_
_x000D_
    $scope.changeTarget = function(name) {_x000D_
        $location.search('target', name);_x000D_
    }_x000D_
}
_x000D_
<div ng-controller="MyCtrl">_x000D_
_x000D_
    <a href="#!/test/?target=Bob">Bob</a>_x000D_
    <a href="#!/test/?target=Paul">Paul</a>_x000D_
    _x000D_
    <hr/>    _x000D_
    URL 'target' param getter: {{target}}<br>_x000D_
    Full url: {{location.absUrl()}}_x000D_
    <hr/>_x000D_
    _x000D_
    <button ng-click="changeTarget('Pawel')">target=Pawel</button>_x000D_
    _x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting the parent div of element

I had to do recently something similar, I used this snippet:

const getNode = () =>
  for (let el = this.$el; el && el.parentNode; el = el.parentNode){
    if (/* insert your condition here */) return el;
  }
  return null
})

The function will returns the element that fulfills your condition. It was a CSS class on the element that I was looking for. If there isn't such element then it will return null

In case somebody would look for multiple elements it only returns closest parent to the element that you provided.

My example was:

if (el.classList?.contains('o-modal')) return el;

I used it in a vue component (this.$el) change that to your document.getElementById function and you're good to go. Hope it will be useful for some people ??

How do I check whether a checkbox is checked in jQuery?

if( undefined == $('#isAgeSelected').attr('checked') ) {
    $("#txtAge").hide();
} else {
    $("#txtAge").show();
}

How does a hash table work?

The Basic Idea

Why do people use dressers to store their clothing? Besides looking trendy and stylish, they have the advantage that every article of clothing has a place where it's supposed to be. If you're looking for a pair of socks, you just check the sock drawer. If you're looking for a shirt, you check the drawer that has your shirts in it. It doesn't matter, when you're looking for socks, how many shirts you have or how many pairs of pants you own, since you don't need to look at them. You just look in the sock drawer and expect to find socks there.

At a high level, a hash table is a way of storing things that is (kinda sorta ish) like a dresser for clothing. The basic idea is the following:

  • You get some number of locations (drawers) where items can be stored.
  • You come up with some rule that tells you which location (drawer) each item belongs.
  • When you need to find something, you use that rule to determine which drawer to look into.

The advantage of a system like this is that, assuming your rule isn't too complicated and you have an appropriate number of drawers, you can find what you're looking for pretty quickly by simply looking in the right place.

When you're putting your clothes away, the "rule" you use might be something like "socks go in the top left drawer, and shirts go in the large middle drawer, etc." When you're storing more abstract data, though, we use something called a hash function to do this for us.

A reasonable way to think about a hash function is as a black box. You put data in one side, and a number called the hash code comes out of the other. Schematically, it looks something like this:

              +---------+
            |\|   hash  |/| --> hash code
   data --> |/| function|\|
              +---------+

All hash functions are deterministic: if you put the same data into the function multiple times, you'll always get the same value coming out the other side. And a good hash function should look more or less random: small changes to the input data should give wildly different hash codes. For example, the hash codes for the string "pudu" and for the string "kudu" will likely be wildly different from one another. (Then again, it's possible that they're the same. After all, if a hash function's outputs should look more or less random, there's a chance we get the same hash code twice.)

How exactly do you build a hash function? For now, let's go with "decent people shouldn't think too much about that." Mathematicians have worked out better and worse ways to design hash functions, but for our purposes we don't really need to worry too much about the internals. It's plenty good to just think of a hash function as a function that's

  • deterministic (equal inputs give equal outputs), but
  • looks random (it's hard to predict one hash code given another).

Once we have a hash function, we can build a very simple hash table. We'll make an array of "buckets," which you can think of as being analogous to drawers in our dresser. To store an item in the hash table, we'll compute the hash code of the object and use it as an index in the table, which is analogous to "pick which drawer this item goes in." Then, we put that data item inside the bucket at that index. If that bucket was empty, great! We can put the item there. If that bucket is full, we have some choices of what we can do. A simple approach (called chained hashing) is to treat each bucket as a list of items, the same way that your sock drawer might store multiple socks, and then just add the item to the list at that index.

To look something up in a hash table, we use basically the same procedure. We begin by computing the hash code for the item to look up, which tells us which bucket (drawer) to look in. If the item is in the table, it has to be in that bucket. Then, we just look at all the items in the bucket and see if our item is in there.

What's the advantage of doing things this way? Well, assuming we have a large number of buckets, we'd expect that most buckets won't have too many things in them. After all, our hash function kinda sorta ish looks like it has random outputs, so the items are distributed kinda sorta ish evenly across all the buckets. In fact, if we formalize the notion of "our hash function looks kinda random," we can prove that the expected number of items in each bucket is the ratio of the total number of items to the total number of buckets. Therefore, we can find the items we're looking for without having to do too much work.

The Details

Explaining how "a hash table" works is a bit tricky because there are many flavors of hash tables. This next section talks about a few general implementation details common to all hash tables, plus some specifics of how different styles of hash tables work.

A first question that comes up is how you turn a hash code into a table slot index. In the above discussion, I just said "use the hash code as an index," but that's actually not a very good idea. In most programming languages, hash codes work out to 32-bit or 64-bit integers, and you aren't going to be able to use those directly as bucket indices. Instead, a common strategy is to make an array of buckets of some size m, compute the (full 32- or 64-bit) hash codes for your items, then mod them by the size of the table to get an index between 0 and m-1, inclusive. The use of modulus works well here because it's decently fast and does a decent job spreading the full range of hash codes across a smaller range.

(You sometimes see bitwise operators used here. If your table has a size that's a power of two, say, 2k, then computing the bitwise AND of the hash code and then umber 2k - 1 is equivalent to computing a modulus, and it's significantly faster.)

The next question is how to pick the right number of buckets. If you pick too many buckets, then most buckets will be empty or have few elements (good for speed - you only have to check a few items per bucket), but you'll use a bunch of space simply storing the buckets (not so great, though maybe you can afford it). The flip side of this holds true as well - if you have too few buckets, then you'll have more elements per bucket on average, making lookups take longer, but you'll use less memory.

A good compromise is to dynamically change the number of buckets over the lifetime of the hash table. The load factor of a hash table, typically denoted a, is the ratio of the number of elements to the number of buckets. Most hash tables pick some maximum load factor. Once the load factor crosses this limit, the hash table increases its number of slots (say, by doubling), then redistributes the elements from the old table into the new one. This is called rehashing. Assuming the maximum load factor in the table is a constant, this ensures that, assuming you have a good hash function, the expected cost of doing a lookup remains O(1). Insertions now have an amortized expected cost of O(1) because of the cost of periodically rebuilding the table, as is the case with deletions. (Deletions can similarly compact the table if the load factor gets too small.)

Hashing Strategies

Up to this point, we've been talking about chained hashing, which is one of many different strategies for building a hash table. As a reminder, chained hashing kinda sorta looks like a clothing dresser - each bucket (drawer) can hold multiple items, and when you do a lookup you check all of those items.

However, this isn't the only way to build a hash table. There's another family of hash tables that use a strategy called open addressing. The basic idea behind open addressing is to store an array of slots, where each slot can either be empty or hold exactly one item.

In open addressing, when you perform an insertion, as before, you jump to some slot whose index depends on the hash code computed. If that slot is free, great! You put the item there, and you're done. But what if the slot is already full? In that case, you use some secondary strategy to find a different free slot in which to store the item. The most common strategy for doing this uses an approach called linear probing. In linear probing, if the slot you want is already full, you simply shift to the next slot in the table. If that slot is empty, great! You can put the item there. But if that slot is full, you then move to the next slot in the table, etc. (If you hit the end of the table, just wrap back around to the beginning).

Linear probing is a surprisingly fast way to build a hash table. CPU caches are optimized for locality of reference, so memory lookups in adjacent memory locations tend to be much faster than memory lookups in scattered locations. Since a linear probing insertion or deletion works by hitting some array slot and then walking linearly forward, it results in few cache misses and ends up being a lot faster than what the theory normally predicts. (And it happens to be the case that the theory predicts it's going to be very fast!)

Another strategy that's become popular recently is cuckoo hashing. I like to think of cuckoo hashing as the "Frozen" of hash tables. Instead of having one hash table and one hash function, we have two hash tables and two hash functions. Each item can be in exactly one of two places - it's either in the location in the first table given by the first hash function, or it's in the location in the second table given by the second hash function. This means that lookups are worst-case efficient, since you only have to check two spots to see if something is in the table.

Insertions in cuckoo hashing use a different strategy than before. We start off by seeing if either of the two slots that could hold the item are free. If so, great! We just put the item there. But if that doesn't work, then we pick one of the slots, put the item there, and kick out the item that used to be there. That item has to go somewhere, so we try putting it in the other table at the appropriate slot. If that works, great! If not, we kick an item out of that table and try inserting it into the other table. This process continues until everything comes to rest, or we find ourselves trapped in a cycle. (That latter case is rare, and if it happens we have a bunch of options, like "put it in a secondary hash table" or "choose new hash functions and rebuild the tables.")

There are many improvements possible for cuckoo hashing, such as using multiple tables, letting each slot hold multiple items, and making a "stash" that holds items that can't fit anywhere else, and this is an active area of research!

Then there are hybrid approaches. Hopscotch hashing is a mix between open addressing and chained hashing that can be thought of as taking a chained hash table and storing each item in each bucket in a slot near where the item wants to go. This strategy plays well with multithreading. The Swiss table uses the fact that some processors can perform multiple operations in parallel with a single instruction to speed up a linear probing table. Extendible hashing is designed for databases and file systems and uses a mix of a trie and a chained hash table to dynamically increase bucket sizes as individual buckets get loaded. Robin Hood hashing is a variant of linear probing in which items can be moved after being inserted to reduce the variance in how far from home each element can live.

Further Reading

For more information about the basics of hash tables, check out these lecture slides on chained hashing and these follow-up slides on linear probing and Robin Hood hashing. You can learn more about cuckoo hashing here and about theoretical properties of hash functions here.

Getting the minimum of two values in SQL

Here is a trick if you want to calculate maximum(field, 0):

SELECT (ABS(field) + field)/2 FROM Table

returns 0 if field is negative, else, return field.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Change Title of Javascript Alert

As others have said, you can't do that either using alert()or confirm().

You can, however, create an external HTML document containing your error message and an OK button, set its <title> element to whatever you want, then display it in a modal dialog box using showModalDialog().

jQuery - Increase the value of a counter when a button is clicked

Several of the suggestions above use global variables. This is not a good solution for the problem. The count is specific to one element, and you can use jQuery's data function to bind an item of data to an element:

$('#counter').data('count', 0);
$('#update').click(function(){
    $('#counter').html(function(){
        var $this = $(this),
            count = $this.data('count') + 1;

        $this.data('count', count);
        return count;
    });
});

Note also that this uses the callback syntax of html to make the code more fluent and fast.

Description for event id from source cannot be found

If you open the Event Log viewer before the event source is created, for example while installing a service, you'll get that error message. You don't need to restart the OS: you simply have to close and open the event viewer.

NOTE: I don't provide a custom messages file. The creation of the event source uses the default configuration, as shown on Matt's answer.

What is the best method to merge two PHP objects?

This snippet of code will recursively convert that data to a single type (array or object) without the nested foreach loops. Hope it helps someone!

Once an Object is in array format you can use array_merge and convert back to Object if you need to.

abstract class Util {
    public static function object_to_array($d) {
        if (is_object($d))
            $d = get_object_vars($d);

        return is_array($d) ? array_map(__METHOD__, $d) : $d;
    }

    public static function array_to_object($d) {
        return is_array($d) ? (object) array_map(__METHOD__, $d) : $d;
    }
}

Procedural way

function object_to_array($d) {
    if (is_object($d))
        $d = get_object_vars($d);

    return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}

function array_to_object($d) {
    return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}

All credit goes to: Jason Oakley

Versioning SQL Server database

I'm also using a version in the database stored via the database extended properties family of procedures. My application has scripts for each version step (ie. move from 1.1 to 1.2). When deployed, it looks at the current version and then runs the scripts one by one until it reaches the last app version. There is no script that has the straight 'final' version, even deploy on a clean DB does the deploy via a series of upgrade steps.

Now what I like to add is that I've seen two days ago a presentation on the MS campus about the new and upcoming VS DB edition. The presentation was focused specifically on this topic and I was blown out of the water. You should definitely check it out, the new facilities are focused on keeping schema definition in T-SQL scripts (CREATEs), a runtime delta engine to compare deployment schema with defined schema and doing the delta ALTERs and integration with source code integration, up to and including MSBUILD continuous integration for automated build drops. The drop will contain a new file type, the .dbschema files, that can be taken to the deployment site and a command line tool can do the actual 'deltas' and run the deployment. I have a blog entry on this topic with links to the VSDE downloads, you should check them out: http://rusanu.com/2009/05/15/version-control-and-your-database/

Create zip file and ignore directory structure

Alternatively, you could create a temporary symbolic link to your file:

ln -s /data/to/zip/data.txt data.txt
zip /dir/to/file/newZip !$
rm !$

This works also for a directory.

grant remote access of MySQL database from any IP address

Use this command:

GRANT ALL ON yourdatabasename.* TO root@'%' IDENTIFIED BY 'yourRootPassword';

Then:

FLUSH PRIVILEGES; 

Then comment out the below line in file "/etc/mysql/mysql.conf.d/mysqld.cnf" (is required!):

bind-address = 127.0.0.1 

Works for me!

How to update column value in laravel

You may try this:

Page::where('id', $id)->update(array('image' => 'asdasd'));

There are other ways too but no need to use Page::find($id); in this case. But if you use find() then you may try it like this:

$page = Page::find($id);

// Make sure you've got the Page model
if($page) {
    $page->image = 'imagepath';
    $page->save();
}

Also you may use:

$page = Page::findOrFail($id);

So, it'll throw an exception if the model with that id was not found.

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

get the compatible version of this jar slf4j-jdk14 and add it as a dependency. this solved the problem for me.

When should a class be Comparable and/or Comparator?

Comparable is for providing a default ordering on data objects, for example if the data objects have a natural order.

A Comparator represents the ordering itself for a specific use.

How do you completely remove Ionic and Cordova installation from mac?

Here the command to remove cordova and ionic from your machine

npm uninstall cordova ionic

Checking if my Windows application is running

Enter a guid in your assembly data. Add this guid to the registry. Enter a reg key where the application read it's own name and add the name as value there.

The other task watcher read the reg key and knows the app name.

How to parse a String containing XML in Java and retrieve the value of the root node?

There is doing XML reading right, or doing the dodgy just to get by. Doing it right would be using proper document parsing.

Or... dodgy would be using custom text parsing with either wisuzu's response or using regular expressions with matchers.

ng serve not detecting file changes automatically

This may help if it is the same problem I had. Trying to use ng serve and ng build --watch sometimes worked but mostly they were not watching for code changes and I thought it was something to do with ng.

Then I remembered a problem I had a while back with inotify watches

I ran this on my Ubuntu machine and it seems to have kicked in and watching code changes:

echo fs.inotify.max_user_watches=524288 | sudo tee /etc/sysctl.d/40-max-user-watches.conf && sudo sysctl --system

credit goes to Scott Smith

How do I insert an image in an activity with android studio?

I'll Explain how to add an image using Android studio(2.3.3). First you need to add the image into res/drawable folder in the project. Like below

enter image description here


Now in go to activity_main.xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView.

enter image description here

It will prompt you Resources dialog box. In there select Drawable under the project section you can see your image. Like below

enter image description here

Select the image you want press Ok you can see the image on the Design view. If you want it configure using xml it would look like below.

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/homepage"
        tools:layout_editor_absoluteX="55dp"
        tools:layout_editor_absoluteY="130dp" />

You need to give image location using

app:srcCompat="@drawable/imagename"

Check if a Bash array contains a value

How to check if a Bash Array contains a value


False positive match

array=(a1 b1 c1 d1 ee)

[[ ${array[*]} =~ 'a' ]] && echo 'yes' || echo 'no'
# output:
yes

[[ ${array[*]} =~ 'a1' ]] && echo 'yes' || echo 'no'
# output:
yes

[[ ${array[*]} =~ 'e' ]] && echo 'yes' || echo 'no'
# output:
yes

[[ ${array[*]} =~ 'ee' ]] && echo 'yes' || echo 'no'
# output:
yes

Exact match

In order to look for an exact match, your regex pattern needs to add extra space before and after the value like (^|[[:space:]])"VALUE"($|[[:space:]])

# Exact match

array=(aa1 bc1 ac1 ed1 aee)

if [[ ${array[*]} =~ (^|[[:space:]])"a"($|[[:space:]]) ]]; then
    echo "Yes";
else
    echo "No";
fi
# output:
No

if [[ ${array[*]} =~ (^|[[:space:]])"ac1"($|[[:space:]]) ]]; then
    echo "Yes";
else
    echo "No";
fi
# output:
Yes

find="ac1"
if [[ ${array[*]} =~ (^|[[:space:]])"$find"($|[[:space:]]) ]]; then
    echo "Yes";
else
    echo "No";
fi
# output:
Yes

For more usage examples the source of examples are here

Using G++ to compile multiple .cpp and .h files

As rebenvp said I used:

g++ *.cpp -o output

And then do this for output:

./output

But a better solution is to use make file. Read here to know more about make files.

Also make sure that you have added the required .h files in the .cpp files.

Bootstrap 3 .col-xs-offset-* doesn't work?

instead of using col-md-offset-4 use instead offset-md-4, you no longer have to use col when you're offsetting. In your case use offset-xs-1 and this will work. make sure you've called the bootstrap.css folder into your html as follows .

Java collections maintaining insertion order

I can't cite a reference, but by design the List and Set implementations of the Collection interface are basically extendable Arrays. As Collections by default offer methods to dynamically add and remove elements at any point -- which Arrays don't -- insertion order might not be preserved. Thus, as there are more methods for content manipulation, there is a need for special implementations that do preserve order.

Another point is performance, as the most well performing Collection might not be that, which preserves its insertion order. I'm however not sure, how exactly Collections manage their content for performance increases.

So, in short, the two major reasons I can think of why there are order-preserving Collection implementations are:

  1. Class architecture
  2. Performance

Submitting a form on 'Enter' with jQuery?

In HTML codes:

<form action="POST" onsubmit="ajax_submit();return false;">
    <b>First Name:</b> <input type="text" name="firstname" id="firstname">
    <br>
    <b>Last Name:</b> <input type="text" name="lastname" id="lastname">
    <br>
    <input type="submit" name="send" onclick="ajax_submit();">
</form>

In Js codes:

function ajax_submit()
{
    $.ajax({
        url: "submit.php",
        type: "POST",
        data: {
            firstname: $("#firstname").val(),
            lastname: $("#lastname").val()
        },
        dataType: "JSON",
        success: function (jsonStr) {
            // another codes when result is success
        }
    });
}

Selecting fields from JSON output

Assuming you are dealing with a JSON-string in the input, you can parse it using the json package, see the documentation.

In the specific example you posted you would need

x = json.loads("""{
 "accountWide": true,
 "criteria": [
     {
         "description": "some description",
         "id": 7553,
         "max": 1,
         "orderIndex": 0
     }
  ]
 }""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']

Illegal Escape Character "\"

Use "\\" to escape the \ character.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Bash script to check running process

This trick works for me. Hope this could help you. Let's save the followings as checkRunningProcess.sh

#!/bin/bash
ps_out=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
    echo "Running"
else
    echo "Not Running"
fi

Make the checkRunningProcess.sh executable.And then use it.
Example to use.

20:10 $ checkRunningProcess.sh proxy.py
Running
20:12 $ checkRunningProcess.sh abcdef
Not Running

How to install python modules without root access?

Install Python package without Admin rights

import sys

!{sys.executable} -m pip install package_name

Example

import sys

!{sys.executable} -m pip install kivy

Reference: https://docs.python.org/3.4/library/sys.html#sys.executable

grep a tab in UNIX

On ksh I used

grep "[^I]" testfile

Is there a simple, elegant way to define singletons?

The Singleton Pattern implemented with Python courtesy of ActiveState.

It looks like the trick is to put the class that's supposed to only have one instance inside of another class.

Remove specific commit

There are four ways of doing so:

  • Clean way, reverting but keep in log the revert:

    git revert --strategy resolve <commit>
    
  • Harsh way, remove altogether only the last commit:

    git reset --soft "HEAD^"
    

Note: Avoid git reset --hard as it will also discard all changes in files since the last commit. If --soft does not work, rather try --mixed or --keep.

  • Rebase (show the log of the last 5 commits and delete the lines you don't want, or reorder, or squash multiple commits in one, or do anything else you want, this is a very versatile tool):

    git rebase -i HEAD~5
    

And if a mistake is made:

git rebase --abort
  • Quick rebase: remove only a specific commit using its id:

    git rebase --onto commit-id^ commit-id
    
  • Alternatives: you could also try:

    git cherry-pick commit-id
    
  • Yet another alternative:

    git revert --no-commit
    
  • As a last resort, if you need full freedom of history editing (eg, because git don't allow you to edit what you want to), you can use this very fast open source application: reposurgeon.

Note: of course, all these changes are done locally, you should git push afterwards to apply the changes to the remote. And in case your repo doesn't want to remove the commit ("no fast-forward allowed", which happens when you want to remove a commit you already pushed), you can use git push -f to force push the changes.

Note2: if working on a branch and you need to force push, you should absolutely avoid git push --force because this may overwrite other branches (if you have made changes in them, even if your current checkout is on another branch). Prefer to always specify the remote branch when you force push: git push --force origin your_branch.

How to set column widths to a jQuery datatable?

by using css we can easily add width to the column.

here im adding first column width to 300px on header (thead)

_x000D_
_x000D_
::ng-deep  table thead tr:last-child th:nth-child(1) {_x000D_
    width: 300px!important;_x000D_
}
_x000D_
_x000D_
_x000D_

now add same width to tbody first column by,

_x000D_
_x000D_
  <table datatable class="display table ">_x000D_
            <thead>_x000D_
            <tr>_x000D_
                <th class="text-left" style="width: 300px!important;">name</th>_x000D_
            </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
           _x000D_
            <tr>_x000D_
                <td class="text-left" style="width: 300px!important;">jhon mathew</td>_x000D_
                _x000D_
            </tr>_x000D_
            </tbody>_x000D_
        </table>_x000D_
       
_x000D_
_x000D_
_x000D_

by this way you can easily change width by changing the order of nth child. if you want 3 column then ,add nth-child(3)

How to tell if JRE or JDK is installed

Normally a jdk installation has javac in the environment path variables ... so if you check for javac in the path, that's pretty much a good indicator that you have a jdk installed.

Converting a Uniform Distribution to a Normal Distribution

The standard Python library module random has what you want:

normalvariate(mu, sigma)
Normal distribution. mu is the mean, and sigma is the standard deviation.

For the algorithm itself, take a look at the function in random.py in the Python library.

The manual entry is here

Apache error: _default_ virtualhost overlap on port 443

On a vanilla Apache2 install in CentOS, when you install mod_ssl it will automatically add a configuration file in:

{apache_dir}/conf.d/ssl.conf

This configuration file contains a default virtual host definition for port 443, named default:443. If you also have your own virtual host definition for 443 (i.e. in httpd.conf) then you will have a confict. Since the conf.d files are included first, they will win over yours.

To solve the conflict you can either remove the virtual host definition from conf.d/ssl.conf or update it to your own settings.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

In my case I was getting this error because the option (HttpActivation) was not enabled. Windows features dialog box showing HTTP Activation under WCF Services under .NET Framework 4.6 Advanced Services

2 column div layout: right column with fixed width, left fluid

See http://www.alistapart.com/articles/negativemargins/ , this is exactly what you need (example 4 there).

<div id="container">
    <div id="content">
        <h1>content</h1>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.  Phasellus varius eleifend tellus. Suspendisse potenti. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Nulla facilisi. Sed wisi lectus, placerat nec, mollis quis, posuere eget, arcu.</p>
        <p class="last">Donec euismod. Praesent mauris mi, adipiscing non, mollis eget, adipiscing ac, erat. Integer nonummy mauris sit amet metus. In adipiscing, ligula ultrices dictum vehicula, eros turpis lacinia libero, sed aliquet urna diam sed tellus. Etiam semper sapien eget metus.</p>
    </div>
</div>

<div id="sidebar">
    <h1>sidebar</h1>
    <ul>
        <li>link one</li>
        <li>link two</li>
    </ul>
</div>

#container {
    width: 100%;
    background: #f1f2ea url(background.gif) repeat-y right;
    float: left;
    margin-right: -200px;
}
#content {
    background: #f1f2ea;
    margin-right: 200px;
}
#sidebar {
    width: 200px;
    float: right;

How to convert a multipart file to File?

Although the accepted answer is correct but if you are just trying to upload your image to cloudinary, there's a better way:

Map upload = cloudinary.uploader().upload(multipartFile.getBytes(), ObjectUtils.emptyMap());

Where multipartFile is your org.springframework.web.multipart.MultipartFile.

How to dynamically create generic C# object using reflection?

It seems to me the last line of your example code should simply be:

Task<Item> itsMe = o as Task<Item>;

Or am I missing something?

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

Regional independent solution generating the ISO date format:

rem save the existing format definition
for /f "skip=2 tokens=3" %%a in ('reg query "HKCU\Control Panel\International" /v sShortDate') do set FORMAT=%%a
rem set ISO specific format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d yyyy-MM-dd 1>nul:
rem query the date in the ISO specific format 
set ISODATE=%DATE%
rem restore previous format definition
reg add "HKCU\Control Panel\International" /v sShortDate /t REG_SZ /f /d %FORMAT% 1>nul:

What could still be optimized: Other processes might get confused if using the date format in the short period while it is modified. So parsing the output according to the existing format string could be 'safer' - but will be more complicated

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

The proper solution is the one provided by @Jojo.Lechelt.

However if you don't want to commit for any reason and still want to pull the changes,you may save your changes somewhere else,replace the conflicting file with HEAD revision and then pull.

Later you can paste your changes again and compare it with HEAD and incorporate other people changes into your file.

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

I suggest you use TO_CHAR() when converting to string. In order to do that, you need to build a date first.

SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
    (SELECT EXTRACT( DAY FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
        FROM DUAL
        )) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )), 09) AS MONTH, EXTRACT(YEAR FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )) AS YEAR
    FROM DUAL
    );

Can't connect to local MySQL server through socket homebrew

After a restart I could not connect with the local mariadb, a search also brought me to this page and I wanted to share my solution with you.

I noticed that the directory my.cnf.d in /usr/local/etc/ is missing.

This is a known bug with homebrew that is described and solved there. https://github.com/Homebrew/homebrew-core/issues/36801

fast way to fix: mkdir /usr/local/etc/my.cnf.d

How do you create an asynchronous HTTP request in JAVA?

You may want to take a look at this question: Asynchronous IO in Java?

It looks like your best bet, if you don't want to wrangle the threads yourself is a framework. The previous post mentions Grizzly, https://grizzly.dev.java.net/, and Netty, http://www.jboss.org/netty/.

From the netty docs:

The Netty project is an effort to provide an asynchronous event-driven network application framework and tools for rapid development of maintainable high performance & high scalability protocol servers & clients.

How to get AM/PM from a datetime in PHP

It is quite easy. Assuming you have a field(dateposted) with the type "timestamp" in your database table already queried and you want to display it, have it formated and also have the AM/PM, all you need do is shown below.

     <?php
     echo date("F j, Y h:m:s A" ,strtotime($row_rshearing['dateposted'])); 


    ?>

Note: Your OUTPUT should look some what like this depending on the date posted

May 21, 2014 03:05:27 PM

babel-loader jsx SyntaxError: Unexpected token

The following way has helped me (includes react-hot, babel loaders and es2015, react presets):

loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loaders: ['react-hot', 'babel?presets[]=es2015&presets[]=react']
      }
]

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this

SELECT IF(
      count(*) > 15,
      'good',
      IF(
          count(*) > 10,
          'average',
          'poor'
        ) 
      ) as data_count 
      FROM companies

Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.

How to force DNS refresh for a website?

It might be possible to delete the Zone Record entirely, then recreate it exactly as you want it. Perhaps this will force a full propagation. If I'm wrong, somebody tell me and I'll delete this suggestion. Also, I don't know how to save a Zone Record and recreate it using WHM or any other tool.

I do know that when I deleted a hosting account today and recreated it, the original Zone Record seemed to be propagated instantly to a DNS resolver up the line from my computer. That is good evidence it works.

Understanding Apache's access log

You seem to be using the combined log format.

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined

  • %h is the remote host (ie the client IP)
  • %l is the identity of the user determined by identd (not usually used since not reliable)
  • %u is the user name determined by HTTP authentication
  • %t is the time the request was received.
  • %r is the request line from the client. ("GET / HTTP/1.0")
  • %>s is the status code sent from the server to the client (200, 404 etc.)
  • %b is the size of the response to the client (in bytes)
  • Referer is the Referer header of the HTTP request (containing the URL of the page from which this request was initiated) if any is present, and "-" otherwise.
  • User-agent is the browser identification string.

The complete(?) list of formatters can be found here. The same section of the documentation also lists other common log formats; readers whose logs don't look quite like this one may find the pattern their Apache configuration is using listed there.

How does "cat << EOF" work in bash?

Long story short, EOF marker(but a different literal can be used as well) is a heredoc format that allows you to provide your input as multiline. A lot of confusion comes from how cat actually works it seems. You can use cat with >> or > as follows:

$ cat >> temp.txt
line 1
line 2

While cat can be used this way when writing manually into console, it's not convenient if I want to provide the input in a more declarative way so that it can be reused by tools and also to keep indentations, whitespaces, etc.
Heredoc allows to define your entire input as if you are not working with stdin but typing in a separate text editor. This is what Wikipedia article means by:

it is a section of a source code file that is treated as if it were a separate file.

Python str vs unicode types

Unicode and encodings are completely different, unrelated things.

Unicode

Assigns a numeric ID to each character:

  • 0x41 ? A
  • 0xE1 ? á
  • 0x414 ? ?

So, Unicode assigns the number 0x41 to A, 0xE1 to á, and 0x414 to ?.

Even the little arrow ? I used has its Unicode number, it's 0x2192. And even emojis have their Unicode numbers, is 0x1F602.

You can look up the Unicode numbers of all characters in this table. In particular, you can find the first three characters above here, the arrow here, and the emoji here.

These numbers assigned to all characters by Unicode are called code points.

The purpose of all this is to provide a means to unambiguously refer to a each character. For example, if I'm talking about , instead of saying "you know, this laughing emoji with tears", I can just say, Unicode code point 0x1F602. Easier, right?

Note that Unicode code points are usually formatted with a leading U+, then the hexadecimal numeric value padded to at least 4 digits. So, the above examples would be U+0041, U+00E1, U+0414, U+2192, U+1F602.

Unicode code points range from U+0000 to U+10FFFF. That is 1,114,112 numbers. 2048 of these numbers are used for surrogates, thus, there remain 1,112,064. This means, Unicode can assign a unique ID (code point) to 1,112,064 distinct characters. Not all of these code points are assigned to a character yet, and Unicode is extended continuously (for example, when new emojis are introduced).

The important thing to remember is that all Unicode does is to assign a numerical ID, called code point, to each character for easy and unambiguous reference.

Encodings

Map characters to bit patterns.

These bit patterns are used to represent the characters in computer memory or on disk.

There are many different encodings that cover different subsets of characters. In the English-speaking world, the most common encodings are the following:

ASCII

Maps 128 characters (code points U+0000 to U+007F) to bit patterns of length 7.

Example:

  • a ? 1100001 (0x61)

You can see all the mappings in this table.

ISO 8859-1 (aka Latin-1)

Maps 191 characters (code points U+0020 to U+007E and U+00A0 to U+00FF) to bit patterns of length 8.

Example:

  • a ? 01100001 (0x61)
  • á ? 11100001 (0xE1)

You can see all the mappings in this table.

UTF-8

Maps 1,112,064 characters (all existing Unicode code points) to bit patterns of either length 8, 16, 24, or 32 bits (that is, 1, 2, 3, or 4 bytes).

Example:

  • a ? 01100001 (0x61)
  • á ? 11000011 10100001 (0xC3 0xA1)
  • ? ? 11100010 10001001 10100000 (0xE2 0x89 0xA0)
  • ? 11110000 10011111 10011000 10000010 (0xF0 0x9F 0x98 0x82)

The way UTF-8 encodes characters to bit strings is very well described here.

Unicode and Encodings

Looking at the above examples, it becomes clear how Unicode is useful.

For example, if I'm Latin-1 and I want to explain my encoding of á, I don't need to say:

"I encode that a with an aigu (or however you call that rising bar) as 11100001"

But I can just say:

"I encode U+00E1 as 11100001"

And if I'm UTF-8, I can say:

"Me, in turn, I encode U+00E1 as 11000011 10100001"

And it's unambiguously clear to everybody which character we mean.

Now to the often arising confusion

It's true that sometimes the bit pattern of an encoding, if you interpret it as a binary number, is the same as the Unicode code point of this character.

For example:

  • ASCII encodes a as 1100001, which you can interpret as the hexadecimal number 0x61, and the Unicode code point of a is U+0061.
  • Latin-1 encodes á as 11100001, which you can interpret as the hexadecimal number 0xE1, and the Unicode code point of á is U+00E1.

Of course, this has been arranged like this on purpose for convenience. But you should look at it as a pure coincidence. The bit pattern used to represent a character in memory is not tied in any way to the Unicode code point of this character.

Nobody even says that you have to interpret a bit string like 11100001 as a binary number. Just look at it as the sequence of bits that Latin-1 uses to encode the character á.

Back to your question

The encoding used by your Python interpreter is UTF-8.

Here's what's going on in your examples:

Example 1

The following encodes the character á in UTF-8. This results in the bit string 11000011 10100001, which is saved in the variable a.

>>> a = 'á'

When you look at the value of a, its content 11000011 10100001 is formatted as the hex number 0xC3 0xA1 and output as '\xc3\xa1':

>>> a
'\xc3\xa1'

Example 2

The following saves the Unicode code point of á, which is U+00E1, in the variable ua (we don't know which data format Python uses internally to represent the code point U+00E1 in memory, and it's unimportant to us):

>>> ua = u'á'

When you look at the value of ua, Python tells you that it contains the code point U+00E1:

>>> ua
u'\xe1'

Example 3

The following encodes Unicode code point U+00E1 (representing character á) with UTF-8, which results in the bit pattern 11000011 10100001. Again, for output this bit pattern is represented as the hex number 0xC3 0xA1:

>>> ua.encode('utf-8')
'\xc3\xa1'

Example 4

The following encodes Unicode code point U+00E1 (representing character á) with Latin-1, which results in the bit pattern 11100001. For output, this bit pattern is represented as the hex number 0xE1, which by coincidence is the same as the initial code point U+00E1:

>>> ua.encode('latin1')
'\xe1'

There's no relation between the Unicode object ua and the Latin-1 encoding. That the code point of á is U+00E1 and the Latin-1 encoding of á is 0xE1 (if you interpret the bit pattern of the encoding as a binary number) is a pure coincidence.

How to get the nth element of a python list or a default if not available

try:
   a = b[n]
except IndexError:
   a = default

Edit: I removed the check for TypeError - probably better to let the caller handle this.

undefined reference to WinMain@16 (codeblocks)

  1. You need to open the project file of your program and it should appear on Management panel.

  2. Right click on the project file, then select add file. You should add the 3 source code (secrypt.h, secrypt.cpp, and the trial.cpp)

  3. Compile and enjoy. Hope, I could help you.

Java equivalent to #region in C#

I usually need this for commented code so I use curly brackets at start and end of that.

{
// Code
// Code
// Code
// Code
}

It could be used for code snippets but can create problems in some code because it changes the scope of variable.

HttpClient.GetAsync(...) never returns when using await/async

You are misusing the API.

Here's the situation: in ASP.NET, only one thread can handle a request at a time. You can do some parallel processing if necessary (borrowing additional threads from the thread pool), but only one thread would have the request context (the additional threads do not have the request context).

This is managed by the ASP.NET SynchronizationContext.

By default, when you await a Task, the method resumes on a captured SynchronizationContext (or a captured TaskScheduler, if there is no SynchronizationContext). Normally, this is just what you want: an asynchronous controller action will await something, and when it resumes, it resumes with the request context.

So, here's why test5 fails:

  • Test5Controller.Get executes AsyncAwait_GetSomeDataAsync (within the ASP.NET request context).
  • AsyncAwait_GetSomeDataAsync executes HttpClient.GetAsync (within the ASP.NET request context).
  • The HTTP request is sent out, and HttpClient.GetAsync returns an uncompleted Task.
  • AsyncAwait_GetSomeDataAsync awaits the Task; since it is not complete, AsyncAwait_GetSomeDataAsync returns an uncompleted Task.
  • Test5Controller.Get blocks the current thread until that Task completes.
  • The HTTP response comes in, and the Task returned by HttpClient.GetAsync is completed.
  • AsyncAwait_GetSomeDataAsync attempts to resume within the ASP.NET request context. However, there is already a thread in that context: the thread blocked in Test5Controller.Get.
  • Deadlock.

Here's why the other ones work:

  • (test1, test2, and test3): Continuations_GetSomeDataAsync schedules the continuation to the thread pool, outside the ASP.NET request context. This allows the Task returned by Continuations_GetSomeDataAsync to complete without having to re-enter the request context.
  • (test4 and test6): Since the Task is awaited, the ASP.NET request thread is not blocked. This allows AsyncAwait_GetSomeDataAsync to use the ASP.NET request context when it is ready to continue.

And here's the best practices:

  1. In your "library" async methods, use ConfigureAwait(false) whenever possible. In your case, this would change AsyncAwait_GetSomeDataAsync to be var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
  2. Don't block on Tasks; it's async all the way down. In other words, use await instead of GetResult (Task.Result and Task.Wait should also be replaced with await).

That way, you get both benefits: the continuation (the remainder of the AsyncAwait_GetSomeDataAsync method) is run on a basic thread pool thread that doesn't have to enter the ASP.NET request context; and the controller itself is async (which doesn't block a request thread).

More information:

Update 2012-07-13: Incorporated this answer into a blog post.

Checkboxes in web pages – how to make them bigger?

Actually there is a way to make them bigger, checkboxes just like anything else (even an iframe like a facebook button).

Wrap them in a "zoomed" element:

_x000D_
_x000D_
.double {_x000D_
  zoom: 2;_x000D_
  transform: scale(2);_x000D_
  -ms-transform: scale(2);_x000D_
  -webkit-transform: scale(2);_x000D_
  -o-transform: scale(2);_x000D_
  -moz-transform: scale(2);_x000D_
  transform-origin: 0 0;_x000D_
  -ms-transform-origin: 0 0;_x000D_
  -webkit-transform-origin: 0 0;_x000D_
  -o-transform-origin: 0 0;_x000D_
  -moz-transform-origin: 0 0;_x000D_
}
_x000D_
<div class="double">_x000D_
  <input type="checkbox" name="hello" value="1">_x000D_
</div>
_x000D_
_x000D_
_x000D_

It might look a little bit "rescaled" but it works.

Of course you can make that div float:left and put your label besides it, float:left too.

Scrollview vertical and horizontal in android

since the Two Dimensional Scrollview link is dead I could not get it so I created my own component. It handles flinging and works properly for me. The only restriction is that wrap_content might not work properly for that component.

https://gist.github.com/androidseb/9902093

How to upload a file in Django?

Not sure if there any disadvantages to this approach but even more minimal, in views.py:

entry = form.save()

# save uploaded file
if request.FILES['myfile']:
    entry.myfile.save(request.FILES['myfile']._name, request.FILES['myfile'], True)

Setting dynamic scope variables in AngularJs - scope.<some_string>

If you were trying to do what I imagine you were trying to do, then you only have to treat scope like a regular JS object.

This is what I use for an API success response for JSON data array...

function(data){

    $scope.subjects = [];

    $.each(data, function(i,subject){
        //Store array of data types
        $scope.subjects.push(subject.name);

        //Split data in to arrays
        $scope[subject.name] = subject.data;
    });
}

Now {{subjects}} will return an array of data subject names, and in my example there would be a scope attribute for {{jobs}}, {{customers}}, {{staff}}, etc. from $scope.jobs, $scope.customers, $scope.staff

No more data to read from socket error

We were facing same problem, we resolved it by increasing initialSize and maxActive size of connection pool.

You can check this link

Maybe this helps someone.

How to check if an excel cell is empty using Apache POI?

Gagravarr's answer is quite good!


Check if an excel cell is empty

But if you assume that a cell is also empty if it contains an empty String (""), you need some additional code. This can happen, if a cell was edited and then not cleared properly (for how to clear a cell properly, see further below).

I wrote myself a helper to check if an XSSFCell is empty (including an empty String).

 /**
 * Checks if the value of a given {@link XSSFCell} is empty.
 * 
 * @param cell
 *            The {@link XSSFCell}.
 * @return {@code true} if the {@link XSSFCell} is empty. {@code false}
 *         otherwise.
 */
public static boolean isCellEmpty(final XSSFCell cell) {
    if (cell == null) { // use row.getCell(x, Row.CREATE_NULL_AS_BLANK) to avoid null cells
        return true;
    }

    if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
        return true;
    }

    if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().trim().isEmpty()) {
        return true;
    }

    return false;
}

Pay attention for newer POI Version

They first changed getCellType() to getCellTypeEnum() as of Version 3.15 Beta 3 and then moved back to getCellType() as of Version 4.0.

  • Version >= 3.15 Beta 3:

    • Use CellType.BLANK and CellType.STRING instead of Cell.CELL_TYPE_BLANK and Cell.CELL_TYPE_STRING
  • Version >= 3.15 Beta 3 && Version < 4.0

    • Use Cell.getCellTypeEnum() instead of Cell.getCellType()

But better double check yourself, because they planned to change it back in future releases.


Example

This JUnit test shows the case in which the additional empty check is needed.

Scenario: the content of a cell is changed within a Java program. Later on, in the same Java program, the cell is checked for emptiness. The test will fail if the isCellEmpty(XSSFCell cell) function doesn't check for empty Strings.

@Test
public void testIsCellEmpty_CellHasEmptyString_ReturnTrue() {
    // Arrange
    XSSFCell cell = new XSSFWorkbook().createSheet().createRow(0).createCell(0);

    boolean expectedValue = true;
    boolean actualValue;

    // Act
    cell.setCellValue("foo");
    cell.setCellValue("bar");
    cell.setCellValue(" ");
    actualValue = isCellEmpty(cell);

    // Assert
    Assert.assertEquals(expectedValue, actualValue);
}

In addition: Clear a cell properly

Just in case if someone wants to know, how to clear the content of a cell properly. There are two ways to archive that (I would recommend way 1).

// way 1
public static void clearCell(final XSSFCell cell) {
    cell.setCellType(Cell.CELL_TYPE_BLANK);
}

// way 2
public static void clearCell(final XSSFCell cell) {
    String nullString = null;
    cell.setCellValue(nullString); 
}

Why way 1? Explicit is better than implicit (thanks, Python)

Way 1: sets the cell type explicitly back to blank.
Way 2: sets the cell type implicitly back to blank due to a side effect when setting a cell value to a null String.


Useful sources

Regards winklerrr

MySQL joins and COUNT(*) from another table

Your groups_main table has a key column named id. I believe you can only use the USING syntax for the join if the groups_fans table has a key column with the same name, which it probably does not. So instead, try this:

LEFT JOIN groups_fans AS m ON m.group_id = g.id

Or replace group_id with whatever the appropriate column name is in the groups_fans table.

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

jQuery UI dialog positioning

above solutions are very true...but the UI dialog does not retain the position after window is resized. below code does this

            $(document).ready(function(){

                $(".test").click(function(){
                            var posX = $(".test").offset().left - $(document).scrollLeft() + $(".test").outerWidth();
                            var posY = $(".test").offset().top - $(document).scrollTop() + $(".test").outerHeight();
                            console.log("in click function");
                            $(".abc").dialog({
                                position:[posX,posY]
                            });

                        })

            })

            $(window).resize(function(){
                var posX=$(".test").offset().left - $(document).scrollLeft() + $(".test").outerWidth();
                var posY = $(".test").offset().top - $(document).scrollTop() + $(".test").outerHeight();

            $(".abc").dialog({
                                position:[posX,posY]
                            });
            })

Submit HTML form, perform javascript function (alert then redirect)

Looks like your form is submitting which is the default behaviour, you can stop it with this:

<form action="" method="post" onsubmit="completeAndRedirect();return false;">

Using client certificate in Curl command

This is how I did it:

curl -v \
  --key ./admin-key.pem \
  --cert ./admin.pem \
  https://xxxx/api/v1/

TSQL How do you output PRINT in a user defined function?

Use extended procedure xp_cmdshell to run a shell command. I used it to print output to a file:

exec xp_cmdshell 'echo "mytextoutput" >> c:\debuginfo.txt'

This creates the file debuginfo.txt if it does not exist. Then it adds the text "mytextoutput" (without quotation marks) to the file. Any call to the function will write an additional line.

You may need to enable this db-server property first (default = disabled), which I realize may not be to the liking of dba's for production environments though.

Read all files in a folder and apply a function to each data frame

Here is a tidyverse option that might not the most elegant, but offers some flexibility in terms of what is included in the summary:

library(tidyverse)
dir_path <- '~/path/to/data/directory/'
file_pattern <- 'Df\\.[0-9]\\.csv' # regex pattern to match the file name format

read_dir <- function(dir_path, file_name){
  read_csv(paste0(dir_path, file_name)) %>% 
    mutate(file_name = file_name) %>%                # add the file name as a column              
    gather(variable, value, A:B) %>%                 # convert the data from wide to long
    group_by(file_name, variable) %>% 
    summarize(sum = sum(value, na.rm = TRUE),
              min = min(value, na.rm = TRUE),
              mean = mean(value, na.rm = TRUE),
              median = median(value, na.rm = TRUE),
              max = max(value, na.rm = TRUE))
  }

df_summary <- 
  list.files(dir_path, pattern = file_pattern) %>% 
  map_df(~ read_dir(dir_path, .))

df_summary
# A tibble: 8 x 7
# Groups:   file_name [?]
  file_name variable   sum   min  mean median   max
  <chr>     <chr>    <int> <dbl> <dbl>  <dbl> <dbl>
1 Df.1.csv  A           34     4  5.67    5.5     8
2 Df.1.csv  B           22     1  3.67    3       9
3 Df.2.csv  A           21     1  3.5     3.5     6
4 Df.2.csv  B           16     1  2.67    2.5     5
5 Df.3.csv  A           30     0  5       5      11
6 Df.3.csv  B           43     1  7.17    6.5    15
7 Df.4.csv  A           21     0  3.5     3       8
8 Df.4.csv  B           42     1  7       6      16

symfony 2 twig limit the length of the text and put three dots

Bugginess* in the new Drupal 8 capabilities here inspired us to write our own:

<a href="{{ view_node }}">{% if title|length > 32 %}{% set title_array = title|split(' ') %}{% set title_word_count = 0 %}{% for ta in title_array %}{% set word_count = ta|length %}{% if title_word_count < 32 %}{% set title_word_count = title_word_count + word_count %}{{ ta }} {% endif %}{% endfor %}...{% else %}{{ title }}{% endif %}</a>

This takes into consideration both words and characters (*the "word boundary" setting in D8 was displaying nothing).

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

When calling a promise defined in a service or in a factory make sure to use service as I could not get response from a promise defined in a factory. This is how I call a promise defined in a service.

myApp.service('serverOperations', function($http) {
        this.get_data = function(user) {
          return $http.post('http://localhost/serverOperations.php?action=get_data', user);
        };
})


myApp.controller('loginCtrl', function($http, $q, serverOperations, user) {        
    serverOperations.get_data(user)
        .then( function(response) {
            console.log(response.data);
            }
        );
})

How do I hide certain files from the sidebar in Visual Studio Code?

For .meta files while using Unity3D, I found the best pattern for hiding is:

"files.exclude": {
  "*/**/**.meta": true
}

This captures all folders and subfolders, and will pick up foo.cs.meta in addition to foo.meta

How do I call an Angular 2 pipe with multiple arguments?

Since beta.16 the parameters are not passed as array to the transform() method anymore but instead as individual parameters:

{{ myData | date:'fullDate':'arg1':'arg2' }}


export class DatePipe implements PipeTransform {    
  transform(value:any, arg1:any, arg2:any):any {
        ...
}

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26

pipes now take a variable number of arguments, and not an array that contains all arguments.

Visual Studio breakpoints not being hit

If any of your components are Strong Named (signed), then all need to be. If you, as I did, add a project and reference it from a Strong Named project/component, neglecting to sign your new component, debugging will be as if your new component is an external one and you will not be able to step into it. So make sure all your components are signed, or none.

enter image description here

When should iteritems() be used instead of items()?

As the dictionary documentation for python 2 and python 3 would tell you, in python 2 items returns a list, while iteritems returns a iterator.

In python 3, items returns a view, which is pretty much the same as an iterator.

If you are using python 2, you may want to user iteritems if you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)

How to check if std::map contains a key without doing insert?

Your desideratum,map.contains(key), is scheduled for the draft standard C++2a. In 2017 it was implemented by gcc 9.2. It's also in the current clang.

How to get JSON response from http.Get

The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Tracks struct {
    Toptracks []Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  []Attr_info
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []Streamable_info
    Artist     []Artist_info
    Attr       []Track_attr_info
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "&limit=1" // limit data for testing
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var data interface{} // TopTracks
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Output:

Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]

How to get attribute of element from Selenium?

As the recent developed Web Applications are using JavaScript, jQuery, AngularJS, ReactJS etc there is a possibility that to retrieve an attribute of an element through Selenium you have to induce WebDriverWait to synchronize the WebDriver instance with the lagging Web Client i.e. the Web Browser before trying to retrieve any of the attributes.

Some examples:

  • Python:

    • To retrieve any attribute form a visible element (e.g. <h1> tag) you need to use the expected_conditions as visibility_of_element_located(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
      
    • To retrieve any attribute form an interactive element (e.g. <input> tag) you need to use the expected_conditions as element_to_be_clickable(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "org"))).get_attribute("attribute_name")
      

HTML Attributes

Below is a list of some attributes often used in HTML

HTML Attributes

Note: A complete list of all attributes for each HTML element, is listed in: HTML Attribute Reference

Is it possible to use raw SQL within a Spring Repository

The @Query annotation allows to execute native queries by setting the nativeQuery flag to true.

Quote from Spring Data JPA reference docs.

Also, see this section on how to do it with a named native query.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

Loop through a date range with JavaScript

I think I found an even simpler answer, if you allow yourself to use Moment.js:

_x000D_
_x000D_
// cycle through last five days, today included_x000D_
// you could also cycle through any dates you want, mostly for_x000D_
// making this snippet not time aware_x000D_
const currentMoment = moment().subtract(4, 'days');_x000D_
const endMoment = moment().add(1, 'days');_x000D_
while (currentMoment.isBefore(endMoment, 'day')) {_x000D_
  console.log(`Loop at ${currentMoment.format('YYYY-MM-DD')}`);_x000D_
  currentMoment.add(1, 'days');_x000D_
}
_x000D_
<script src="https://cdn.jsdelivr.net/npm/moment@2/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Duplicate symbols for architecture x86_64 under Xcode

I also have this fault today.That's because I defined a const value in a .m file.But I defined another .m file that also included this const value.That's means it has two same const values.So this error appears. And my solution is adding a keyword "static" before the const value.such as:

static CGFloat const btnConunt = 9;

And then I build the project it won't report this error.

How to remove unwanted space between rows and columns in table?

adding this line to the beginning of the file s worked for me:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

modifying the css to set the proper border properties did not work until i added the above line

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Selecting Folder Destination in Java?

I found a good example of what you need in this link.

import javax.swing.JFileChooser;

public class Main {
  public static void main(String s[]) {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
      System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {
      System.out.println("No Selection ");
    }
  }
}

Java Replace Character At Specific Position Of String?

Use StringBuilder:

StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();

Execute bash script from URL

source <(curl -s http://mywebsite.com/myscript.txt)

ought to do it. Alternately, leave off the initial redirection on yours, which is redirecting standard input; bash takes a filename to execute just fine without redirection, and <(command) syntax provides a path.

bash <(curl -s http://mywebsite.com/myscript.txt)

It may be clearer if you look at the output of echo <(cat /dev/null)

update query with join on two tables

this is Postgres UPDATE JOIN format:

UPDATE address 
SET cid = customers.id
FROM customers 
WHERE customers.id = address.id

Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html

Bootstrap: Open Another Modal in Modal

Modals in Modal:

_x000D_
_x000D_
$('.modal-child').on('show.bs.modal', function () {_x000D_
    var modalParent = $(this).attr('data-modal-parent');_x000D_
    $(modalParent).css('opacity', 0);_x000D_
});_x000D_
 _x000D_
$('.modal-child').on('hidden.bs.modal', function () {_x000D_
    var modalParent = $(this).attr('data-modal-parent');_x000D_
    $(modalParent).css('opacity', 1);_x000D_
});
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<a href="#myModal" role="button" class="btn btn-primary" data-toggle="modal">Modals in Modal</a>_x000D_
_x000D_
_x000D_
<div id="myModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
    <div class="modal-dialog">_x000D_
        <!-- Modal content-->_x000D_
        <div class="modal-content">_x000D_
            <div class="modal-header">_x000D_
             _x000D_
                <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
                <h4 class="modal-title">Modal Header</h4>_x000D_
            </div>_x000D_
            <div class="modal-body">_x000D_
                <a href="#myModal1" role="button" class="btn btn-primary" data-toggle="modal">Launch other modal 1</a>_x000D_
                <a href="#myModal2" role="button" class="btn btn-primary" data-toggle="modal">Launch other modal 2</a>_x000D_
            </div>_x000D_
_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
_x000D_
<div id="myModal1" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">_x000D_
    <div class="modal-dialog">_x000D_
        <!-- Modal content-->_x000D_
        <div class="modal-content">_x000D_
            <div class="modal-header">_x000D_
                <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
                <h4 class="modal-title">Modal Header 1</h4>_x000D_
            </div>_x000D_
            <div class="modal-body">_x000D_
                <p>Two modal body…1</p>_x000D_
            </div>_x000D_
            <div class="modal-footer">_x000D_
                <button class="btn btn-default" data-dismiss="modal" data-dismiss="modal" aria-hidden="true">Cancel</button>_x000D_
            </div>_x000D_
_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
_x000D_
<div id="myModal2" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">_x000D_
    <div class="modal-dialog">_x000D_
        <!-- Modal content-->_x000D_
        <div class="modal-content">_x000D_
            <div class="modal-header">_x000D_
                _x000D_
                <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
                <h4 class="modal-title">Modal Header 2</h4>_x000D_
            </div>_x000D_
            <div class="modal-body">_x000D_
                <p>Modal body…2</p>_x000D_
            </div>_x000D_
            <div class="modal-footer">_x000D_
                <button class="btn btn-default" data-dismiss="modal" data-dismiss="modal" aria-hidden="true">Cancel</button>_x000D_
            </div>_x000D_
_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SVG rounded corner

I found a solution but it is a bit hacky so it may not always work. I found that if you have an arc (A or a) with really small values it forces it to create a curve in one spot thus forming a rounded comer...

_x000D_
_x000D_
<svg viewBox="0 0 1 0.6" stroke="black" fill="grey" style="stroke-width:0.05px;">_x000D_
  <path d="M0.7 0.2 L0.1 0.1 A0.0001 0.0001 0 0 0 0.099 0.101 L0.5 0.5Z"></path>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Accessing attributes from an AngularJS directive

Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():

<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>

Directive:

myApp.directive('suLabel', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            title: '=tooltip'
        },
        template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
        link: function(scope, element, attrs) {
            if (scope.title) {
                element.addClass('tooltip-title');
            }
        },
    }
});

Fiddle.

With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.

Index of Currently Selected Row in DataGridView

Try the following:

int myIndex = MyDataGrid.SelectedIndex;

This will give the index of the row which is currently selected.

Hope this helps

How to loop an object in React?

const tifOptions = [];

for (const [key, value] of Object.entries(tifs)) {
    tifOptions.push(<option value={key} key={key}>{value}</option>);
}

return (
   <select id="tif" name="tif" onChange={this.handleChange}>  
      { tifOptions }          
   </select>
)

How to check if a String contains only ASCII?

commons-lang3 from Apache contains valuable utility/convenience methods for all kinds of 'problems', including this one.

System.out.println(StringUtils.isAsciiPrintable("!@£$%^&!@£$%^"));

How do I get the MAX row with a GROUP BY in LINQ query?

var q = from s in db.Serials
        group s by s.Serial_Number into g
        select new {Serial_Number = g.Key, MaxUid = g.Max(s => s.uid) }

Initializing a dictionary in python with a key value and no corresponding values

q = input("Apple")
w = input("Ball")
Definition = {'apple': q, 'ball': w}

In Perl, how do I create a hash whose keys come from a given array?

#!/usr/bin/perl -w

use strict;
use Data::Dumper;

my @a = qw(5 8 2 5 4 8 9);
my @b = qw(7 6 5 4 3 2 1);
my $h = {};

@{$h}{@a} = @b;

print Dumper($h);

gives (note repeated keys get the value at the greatest position in the array - ie 8->2 and not 6)

$VAR1 = {
          '8' => '2',
          '4' => '3',
          '9' => '1',
          '2' => '5',
          '5' => '4'
        };

How can I install Apache Ant on Mac OS X?

If you have MacPorts installed (https://www.macports.org/), do this:

sudo port install apache-ant

Android: how to parse URL String with spaces to URI object?

URL url = Test.class.getResource(args[0]);  // reading demo file path from                                                   
                                            // same location where class                                    
File input=null;
try {
    input = new File(url.toURI());
} catch (URISyntaxException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

How to hide a div element depending on Model value? MVC

The below code should apply different CSS classes based on your Model's CanEdit Property value .

<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>

But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.

@if(Model.CanEdit)
{
  <div>Edit/Delete link goes here</div>
}

Change drawable color programmatically

Try this:

Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, R.drawable.my_drawable); 
Drawable wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
DrawableCompat.setTint(wrappedDrawable, Color.RED);    

Using DrawableCompat is important because it provides backwards compatibility and bug fixes on API 22 devices and earlier.

Android emulator shows nothing except black screen and adb devices shows "device offline"

I changed it to always "cold boot" to fix my problem. Prior to this, when I ran adb devices it always showed as offline.

Cold boot screenshot

Java generics - why is "extends T" allowed but not "implements T"?

Probably because for both sides (B and C) only the type is relevant, not the implementation. In your example

public class A<B extends C>{}

B can be an interface as well. "extends" is used to define sub-interfaces as well as sub-classes.

interface IntfSub extends IntfSuper {}
class ClzSub extends ClzSuper {}

I usually think of 'Sub extends Super' as 'Sub is like Super, but with additional capabilities', and 'Clz implements Intf' as 'Clz is a realization of Intf'. In your example, this would match: B is like C, but with additional capabilities. The capabilities are relevant here, not the realization.

Override default Spring-Boot application.properties settings in Junit Test

Spring Boot automatically loads src/test/resources/application.properties, if following annotations are used

@RunWith(SpringRunner.class)
@SpringBootTest

So, rename test.properties to application.properties to utilize auto configuration.

If you only need to load the properties file (into the Environment) you can also use the following, as explained here

@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class) 

[Update: Overriding certain properties for testing]

  1. Add src/main/resources/application-test.properties.
  2. Annotate test class with @ActiveProfiles("test").

This loads application.properties and then application-test.properties properties into application context for the test case, as per rules defined here.

Demo - https://github.com/mohnish82/so-spring-boot-testprops

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

How to concatenate int values in java?

Others have pointed out that multiplying b by 1000 shouldn't cause a problem - but if a were zero, you'd end up losing it. (You'd get a 4 digit string instead of 5.)

Here's an alternative (general purpose) approach - which assumes that all the values are in the range 0-9. (You should quite possibly put in some code to throw an exception if that turns out not to be true, but I've left it out here for simplicity.)

public static String concatenateDigits(int... digits)
{
    char[] chars = new char[digits.length];
    for (int i = 0; i < digits.length; i++)
    {
        chars[i] = (char)(digits[i] + '0');
    }
    return new String(chars);
}

In this case you'd call it with:

String result = concatenateDigits(a, b, c, d, e);

jQuery: If this HREF contains

Along with the points made by others, the $= selector is the "ends with" selector. You will want the *= (contains) selector, like so:

$('a').each(function() {
    if ($(this).is('[href*="?"')) {
        alert("Contains questionmark");
    }
});

Here's a live demo ->

As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:

$('a[href*="?"]').each(function() {
    alert("Contains questionmark");
});

How do I recognize "#VALUE!" in Excel spreadsheets?

in EXCEL 2013 i had to use IF function 2 times: 1st to identify error with ISERROR and 2nd to identify the specific type of error by ERROR.TYPE=3 in order to address this type of error. This way you can differentiate between error you want and other types.

How can I do an asc and desc sort using underscore.js?

Descending order using underscore can be done by multiplying the return value by -1.

//Ascending Order:
_.sortBy([2, 3, 1], function(num){
    return num;
}); // [1, 2, 3]


//Descending Order:
_.sortBy([2, 3, 1], function(num){
    return num * -1;
}); // [3, 2, 1]

If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.

//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){ 
    return s.charCodeAt() * -1;
});

How to disable Google Chrome auto update?

For Windows users, you may follow the steps in Google Chrome Enterprise Help - Manage Chrome updates (Windows).

Just follow step 1: Install Google Update > Get the Google Update policy template & step 2: Configure auto-updates > Turn off Chrome Browser auto-updates.

If everything is configured correctly, you will see "Updates are disabled by your administrator." in Google Chrome settings About Chrome section after you reboot the pc. configured successful screenshot

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

I suggest creating an additional connection for the second command, would solve it. Try to combine both queries in one query. Create a subquery for the count.

while (dr3.Read())
{
    dados_historico[4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}

Why override the same value again and again?

if (dr3.Read())
{
    dados_historico[4] = dr3["QT"].ToString(); //quantidade de emails lidos naquela verificação
}

Would be enough.

How to convert string to integer in PowerShell

Use:

$filelist = @(11, 1, 2)
$filelist | sort @{expression={$_[0]}} | 
  % {$newName = [string]([int]$($_[0]) + 1)}
  New-Item $newName -ItemType Directory

Skip over a value in the range function in python

You can use any of these:

# Create a range that does not contain 50
for i in [x for x in xrange(100) if x != 50]:
    print i

# Create 2 ranges [0,49] and [51, 100] (Python 2)
for i in range(50) + range(51, 100):
    print i

# Create a iterator and skip 50
xr = iter(xrange(100))
for i in xr:
    print i
    if i == 49:
        next(xr)

# Simply continue in the loop if the number is 50
for i in range(100):
    if i == 50:
        continue
    print i

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

Disable Chrome strict MIME type checking

also had same problem once,

if you are unable to solve the problem you can run the following command on command line
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

Note: you have to navigate to the installation path of your chrome.
For example:cd C:\Program Files\Google\Chrome\Application

A developer session chrome browser will be opened, you can now launch your app on the new chrome browse.
I hope this should be helpful

How do I initialize an empty array in C#?

You could inititialize it with a size of 0, but you will have to reinitialize it, when you know what the size is, as you cannot append to the array.

string[] a = new string[0];

Disable submit button ONLY after submit

As a number of people have pointed out, disabling the submit button has some negative side effects (at least in Chrome it prevents the name/value of the button pressed from being submitted). My solution was to simply add an attribute to indicate that submit has been requested, and then check for the presence of this attribute on every submit. Because I'm using the submit function, this is only called after all HTML 5 validation is successful. Here is my code:

  $("form.myform").submit(function (e) {
    // Check if we have submitted before
    if ( $("#submit-btn").attr('attempted') == 'true' ) {
      //stop submitting the form because we have already clicked submit.
      e.preventDefault();
    }
    else {
      $("#submit-btn").attr("attempted", 'true');
    }
  });

What is a simple command line program or script to backup SQL server databases?

You can use the backup application by ApexSQL. Although it’s a GUI application, it has all its features supported in CLI. It is possible to either perform one-time backup operations, or to create a job that would back up specified databases on the regular basis. You can check the switch rules and exampled in the articles:

How to force a html5 form validation without submitting it via jQuery

This is a pretty straight forward way of having HTML5 perform validation for any form, while still having modern JS control over the form. The only caveat is the submit button must be inside the <form>.

html

<form id="newUserForm" name="create">
Email<input type="email" name="username" id="username" size="25" required>
Phone<input type="tel" id="phone" name="phone" pattern="(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}" size="12" maxlength="12" required>
<input id="submit" type="submit" value="Create Account" >
</form>

js

// bind in ready() function
jQuery( "#submit" ).click( newAcctSubmit );

function newAcctSubmit()
{
  var myForm = jQuery( "#newUserForm" );

  // html 5 is doing the form validation for us,
  // so no need here (but backend will need to still for security)
  if ( ! myForm[0].checkValidity() )
  {
    // bonk! failed to validate, so return true which lets the
    // browser show native validation messages to the user
    return true;
  }

  // post form with jQuery or whatever you want to do with a valid form!
  var formVars = myForm.serialize();
  etc...
}

How to find whether MySQL is installed in Red Hat?

to ckeck the status use the below command, which worked on debian....

/etc/init.d/mysql status

to start my sql server use the below command

/etc/init.d/mysql start

to stop the server use the below command

/etc/init.d/mysql stop

How to set value to variable using 'execute' in t-sql?

A slight change in the execute query will solve the problem:

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId int 
exec ('SELECT TOP 1 **''@siteId''** = Id FROM ' + @dbName + '..myTbl')  
select @siteId

Pass a local file in to URL in Java

You can also use

[AnyClass].class.getResource(filePath)

Changing nav-bar color after scrolling?

This can be done using jQuery.

Here is a link to a fiddle.

When the window scrolls, the distance between the top of the window and the height of the window is compared. When the if statement is true, the background color is set to transparent. And when you scroll back to the top the color comes back to white.

$(document).ready(function(){
    $(window).scroll(function(){
        if($(window).scrollTop() > $(window).height()){
            $(".menu").css({"background-color":"transparent"});   
        }
        else{
            $(".menu").css({"background-color":"white"});
        }

    })
})

How do I fix "The expression of type List needs unchecked conversion...'?

If you look at the javadoc for the class SyndFeed (I guess you are referring to the class com.sun.syndication.feed.synd.SyndFeed), the method getEntries() doesn't return java.util.List<SyndEntry>, but returns just java.util.List.

So you need an explicit cast for this.

How to assign bean's property an Enum value in Spring config file?

To be specific, set the value to be the name of a constant of the enum type, e.g., "TYPE1" or "TYPE2" in your case, as shown below. And it will work:

<bean name="someName" class="my.pkg.classes">
   <property name="type" value="TYPE1" />
</bean>

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

I usually use some #define and constants to make the calculation easy:

#define NANO_SECOND_MULTIPLIER  1000000  // 1 millisecond = 1,000,000 Nanoseconds
const long INTERVAL_MS = 500 * NANO_SECOND_MULTIPLIER;

Hence my code would look like this:

timespec sleepValue = {0};

sleepValue.tv_nsec = INTERVAL_MS;
nanosleep(&sleepValue, NULL);

How to verify if a file exists in a batch file?

Here is a good example on how to do a command if a file does or does not exist:

if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit

We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.

xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"

Use the XCOPY command:

xcopy "C:\myprogram\html\data.sql"  /c /d /h /e /i /y  "C:\myprogram\sync\"

I will explain what the /c /d /h /e /i /y means:

  /C           Continues copying even if errors occur.
  /D:m-d-y     Copies files changed on or after the specified date.
               If no date is given, copies only those files whose
               source time is newer than the destination time.
  /H           Copies hidden and system files also.
  /E           Copies directories and subdirectories, including empty ones.
               Same as /S /E. May be used to modify /T.
  /T           Creates directory structure, but does not copy files. Does not
               include empty directories or subdirectories. /T /E includes
  /I           If destination does not exist and copying more than one file,
               assumes that destination must be a directory.
  /Y           Suppresses prompting to confirm you want to overwrite an
               existing destination file.

`To see all the commands type`xcopy /? in cmd

Call other batch file with option sync.bat myprogram.ini.

I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like

Path/sync.bat
Path/myprogram.ini

If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.

You are using a batch file. You mentioned earlier you have to create a .bat file to use this:

I have to create a .BAT file that does this:

How to detect a USB drive has been plugged in?

Microsoft API Code Pack. ShellObjectWatcher class.

postgresql return 0 if returned value is null

use coalesce

COALESCE(value [, ...])
The COALESCE function returns the first of its arguments that is not null.  
Null is returned only if all arguments are null. It is often
used to substitute a default value for null values when data is
retrieved for display.

Edit

Here's an example of COALESCE with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

IMHO COALESCE should not be use with AVG because it modifies the value. NULL means unknown and nothing else. It's not like using it in SUM. In this example, if we replace AVG by SUM, the result is not distorted. Adding 0 to a sum doesn't hurt anyone but calculating an average with 0 for the unknown values, you don't get the real average.

In that case, I would add price IS NOT NULL in WHERE clause to avoid these unknown values.

Possible to view PHP code of a website?

Noone cand read the file except for those who have access to the file. You must make the code readable (but not writable) by the web server. If the php code handler is running properly you can't read it by requesting by name from the web server.

If someone compromises your server you are at risk. Ensure that the web server can only write to locations it absolutely needs to. There are a few locations under /var which should be properly configured by your distribution. They should not be accessible over the web. /var/www should not be writable, but may contain subdirectories written to by the web server for dynamic content. Code handlers should be disabled for these.

Ensure you don't do anything in your php code which can lead to code injection. The other risk is directory traversal using paths containing .. or begining with /. Apache should already be patched to prevent this when it is handling paths. However, when it runs code, including php, it does not control the paths. Avoid anything that allows the web client to pass a file path.

How to run Unix shell script from Java code?

You can use Apache Commons exec library also.

Example :

package testShellScript;

import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;

public class TestScript {
    int iExitValue;
    String sCommandString;

    public void runScript(String command){
        sCommandString = command;
        CommandLine oCmdLine = CommandLine.parse(sCommandString);
        DefaultExecutor oDefaultExecutor = new DefaultExecutor();
        oDefaultExecutor.setExitValue(0);
        try {
            iExitValue = oDefaultExecutor.execute(oCmdLine);
        } catch (ExecuteException e) {
            System.err.println("Execution failed.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("permission denied.");
            e.printStackTrace();
        }
    }

    public static void main(String args[]){
        TestScript testScript = new TestScript();
        testScript.runScript("sh /root/Desktop/testScript.sh");
    }
}

For further reference, An example is given on Apache Doc also.

How to convert array to a string using methods other than JSON?

Display array in beautiful way:

function arrayDisplay($input)
{
    return implode(
        ', ',
        array_map(
            function ($v, $k) {
                return sprintf("%s => '%s'", $k, $v);
            },
            $input,
            array_keys($input)
        )
    );
}

$arr = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo arrayDisplay($arr);

Displays:

foo => 'bar', baz => 'boom', cow => 'milk', php => 'hypertext processor'

How do I run git log to see changes only for a specific branch?

If you want only those commits which are done by you in a particular branch, use the below command.

git log branch_name --author='Dyaniyal'

Open button in new window?

If you strictly want to stick to using button,Then simply create an open window function as follows:

    <script>
function myfunction() {
    window.open("mynewpage.html");
}
</script>

Then in your html do the following with your button:

Join

So you would have something like this:

 <body>
    <script>
function joinfunction() {
    window.open("mynewpage.html");
}
</script>
<button  onclick="myfunction()" type="button" class="btn btn-default subs-btn">Join</button>