Programs & Examples On #Proxool

Proxool is a Java connection pool

How can I reference a dll in the GAC from Visual Studio?

In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go

EDIT:

That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

What does the 'static' keyword do in a class?

In Java, the static keyword can be simply regarded as indicating the following:

"without regard or relationship to any particular instance"

If you think of static in this way, it becomes easier to understand its use in the various contexts in which it is encountered:

  • A static field is a field that belongs to the class rather than to any particular instance

  • A static method is a method that has no notion of this; it is defined on the class and doesn't know about any particular instance of that class unless a reference is passed to it

  • A static member class is a nested class without any notion or knowledge of an instance of its enclosing class (unless a reference to an enclosing class instance is passed to it)

Circle-Rectangle collision detection (intersection)

To visualise, take your keyboard's numpad. If the key '5' represents your rectangle, then all the keys 1-9 represent the 9 quadrants of space divided by the lines that make up your rectangle (with 5 being the inside.)

1) If the circle's center is in quadrant 5 (i.e. inside the rectangle) then the two shapes intersect.

With that out of the way, there are two possible cases: a) The circle intersects with two or more neighboring edges of the rectangle. b) The circle intersects with one edge of the rectangle.

The first case is simple. If the circle intersects with two neighboring edges of the rectangle, it must contain the corner connecting those two edges. (That, or its center lies in quadrant 5, which we have already covered. Also note that the case where the circle intersects with only two opposing edges of the rectangle is covered as well.)

2) If any of the corners A, B, C, D of the rectangle lie inside the circle, then the two shapes intersect.

The second case is trickier. We should make note of that it may only happen when the circle's center lies in one of the quadrants 2, 4, 6 or 8. (In fact, if the center is on any of the quadrants 1, 3, 7, 8, the corresponding corner will be the closest point to it.)

Now we have the case that the circle's center is in one of the 'edge' quadrants, and it only intersects with the corresponding edge. Then, the point on the edge that is closest to the circle's center, must lie inside the circle.

3) For each line AB, BC, CD, DA, construct perpendicular lines p(AB,P), p(BC,P), p(CD,P), p(DA,P) through the circle's center P. For each perpendicular line, if the intersection with the original edge lies inside the circle, then the two shapes intersect.

There is a shortcut for this last step. If the circle's center is in quadrant 8 and the edge AB is the top edge, the point of intersection will have the y-coordinate of A and B, and the x-coordinate of center P.

You can construct the four line intersections and check if they lie on their corresponding edges, or find out which quadrant P is in and check the corresponding intersection. Both should simplify to the same boolean equation. Be wary of that the step 2 above did not rule out P being in one of the 'corner' quadrants; it just looked for an intersection.

Edit: As it turns out, I have overlooked the simple fact that #2 is a subcase of #3 above. After all, corners too are points on the edges. See @ShreevatsaR's answer below for a great explanation. And in the meanwhile, forget #2 above unless you want a quick but redundant check.

How do I set ANDROID_SDK_HOME environment variable?

Android SDK

Installing the Android SDK is also necessary. The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android.

Cordova requires the ANDROID_HOME environment variable to be set. This should point to the [ANDROID_SDK_DIR]\android-sdk directory (for example c:\android\android-sdk).

Next, update your PATH to include the tools/ and platform-tools/ folder in that folder. So, using ANDROID_HOME, you would add both %ANDROID_HOME%\tools and %ANDROID_HOME%\platform-tools.

Reference : http://ionicframework.com/docs/v1/guide/installation.html

Handler vs AsyncTask vs Thread

In my opinion threads aren't the most efficient way of doing socket connections but they do provide the most functionality in terms of running threads. I say that because from experience, running threads for a long time causes devices to be very hot and resource intensive. Even a simple while(true) will heat a phone in minutes. If you say that UI interaction is not important, perhaps an AsyncTask is good because they are designed for long-term processes. This is just my opinion on it.

UPDATE

Please disregard my above answer! I answered this question back in 2011 when I was far less experienced in Android than I am now. My answer above is misleading and is considered wrong. I'm leaving it there because many people commented on it below correcting me, and I've learned my lesson.

There are far better other answers on this thread, but I will at least give me more proper answer. There is nothing wrong with using a regular Java Thread; however, you should really be careful about how you implement it because doing it wrong can be very processor intensive (most notable symptom can be your device heating up). AsyncTasks are pretty ideal for most tasks that you want to run in the background (common examples are disk I/O, network calls, and database calls). However, AsyncTasks shouldn't be used for particularly long processes that may need to continue after the user has closed your app or put their device to standby. I would say for most cases, anything that doesn't belong in the UI thread, can be taken care of in an AsyncTask.

PHP - Redirect and send data via POST

Alternatively, setting a session variable before the redirect and test it in the destination url, can solve this problem for me.

Gunicorn worker timeout error

You need to used an other worker type class an async one like gevent or tornado see this for more explanation : First explantion :

You may also want to install Eventlet or Gevent if you expect that your application code may need to pause for extended periods of time during request processing

Second one :

The default synchronous workers assume that your application is resource bound in terms of CPU and network bandwidth. Generally this means that your application shouldn’t do anything that takes an undefined amount of time. For instance, a request to the internet meets this criteria. At some point the external network will fail in such a way that clients will pile up on your servers.

How do you normalize a file path in Bash?

As Adam Liss noted realpath is not bundled with every distribution. Which is a shame, because it is the best solution. The provided source code is great, and I will probably start using it now. Here is what I have been using until now, which I share here just for completeness:

get_abs_path() {
     local PARENT_DIR=$(dirname "$1")
     cd "$PARENT_DIR"
     local ABS_PATH="$(pwd)"/"$(basename "$1")"
     cd - >/dev/null
     echo "$ABS_PATH"
} 

If you want it to resolve symlinks, just replace pwd with pwd -P.

Why can't I center with margin: 0 auto?

You need to define the width of the element you are centering, not the parent element.

#header ul {
    margin: 0 auto;
    width: 90%;
}

Edit: Ok, I've seen the testpage now, and here is how I think you want it:

#header ul {
    list-style:none;
    margin:0 auto;
    width:90%;
}

/* Remove the float: left; property, it interferes with display: inline and 
 * causes problems. (float: left; makes the element implicitly a block-level
 * element. It is still good to use display: inline on it to overcome a bug
 * in IE6 and below that doubles horizontal margins for floated elements)
 * The styles below is the full style for the list-items. 
 */
#header ul li {
    color:#CCCCCC;
    display:inline;
    font-size:20px;
    padding-right:20px;
}

How to read a file and write into a text file?

It far easier to use the scripting runtime which is installed by default on Windows

Just go project Reference and check Microsoft Scripting Runtime and click OK.

Then you can use this code which is way better than the default file commands

Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("C:\Clients\Converter\Clockings.mis", ForReading)
'Use this for reading everything in one shot
Final = TS.ReadAll
'OR use this if you need to process each line
Do Until TS.AtEndOfStream
    TempS = TS.ReadLine
    Final = Final & TempS & vbCrLf
Loop
TS.Close

Set TS = FSO.OpenTextFile("C:\Clients\Converter\2.txt", ForWriting, True)
    TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing

As for what is wrong with your original code here you are reading each line of the text file.

Input #iFileNo, sFileText

Then here you write it out

Write #iFileNo, sFileText

sFileText is a string variable so what is happening is that each time you read, you just replace the content of sFileText with the content of the line you just read.

So when you go to write it out, all you are writing is the last line you read, which is probably a blank line.

Dim sFileText As String
Dim sFinal as String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
  Input #iFileNo, sFileText
sFinal = sFinal & sFileText & vbCRLF
Loop
Close #iFileNo

iFileNo = FreeFile 'Don't assume the last file number is free to use
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Write #iFileNo, sFinal
Close #iFileNo

Note you don't need to do a loop to write. sFinal contains the complete text of the File ready to be written at one shot. Note that input reads a LINE at a time so each line appended to sFinal needs to have a CR and LF appended at the end to be written out correctly on a MS Windows system. Other operating system may just need a LF (Chr$(10)).

If you need to process the incoming data then you need to do something like this.

Dim sFileText As String
Dim sFinal as String
Dim vTemp as Variant
Dim iFileNo As Integer
Dim C as Collection
Dim R as Collection
Dim I as Long
Set C = New Collection
Set R = New Collection

iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
  Input #iFileNo, sFileText
  C.Add sFileText
Loop
Close #iFileNo

For Each vTemp in C
     Process vTemp
Next sTemp

iFileNo = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
For Each vTemp in R
   Write #iFileNo, vTemp & vbCRLF
Next sTemp
Close #iFileNo

How to use 'cp' command to exclude a specific directory?

I use a "do while" loop to read the output of the find command. In this example, I am matching (rather than excluding) certain patterns since there are a more limited number of pattern matches that I want than that I don't want. You could reverse the logic with a -not in front of the -iname flags:

    find . -type f -iname "*.flac" -o -print0 -iname "*.mp3" -print0 -o -iname "*.wav" -print0 -o -iname "*.aac" -print0 -o -iname "*.wma" -print0 | while read -d $'\0' file; do cp -ruv "$file" "/media/wd/network_sync/music/$file"; done

I use the above to copy all music type files that are newer on my server than the files on a Western Digital TV Live Hub that I have mounted at /media/wd. I use the above because I have a lot of DVD files, mpegs, etc. that I want to exclude AND because for some reason rsync looks like it is copying, but after I look at the wd device, the files are not there despite no errors during the rsync with this command:

    rsync -av --progress --exclude=*.VOB --exclude=*.avi --exclude=*.mkv --exclude=*.ts --exclude=*.mpg --exclude=*.iso --exclude=*ar --exclude=*.vob --exclude=*.BUP --exclude=*.cdi --exclude=*.ISO --exclude=*.shn --exclude=*.MPG --exclude=*.AVI --exclude=*.DAT --exclude=*.img --exclude=*.nrg --exclude=*.cdr --exclude=*.bin --exclude=*.MOV --exclude=*.goutputs* --exclude=*.flv --exclude=*.mov --exclude=*.m2ts --exclude=*.cdg --exclude=*.IFO --exclude=*.asf --exclude=*.ite /media/2TB\ Data/data/music/* /media/wd/network_sync/music/

$http get parameters does not work

The 2nd parameter in the get call is a config object. You want something like this:

$http
    .get('accept.php', {
        params: {
            source: link,
            category_id: category
        }
     })
     .success(function (data,status) {
          $scope.info_show = data
     });

See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail

Check Whether a User Exists

Actually I cannot reproduce the problem. The script as written in the question works fine, except for the case where $1 is empty.

However, there is a problem in the script related to redirection of stderr. Although the two forms &> and >& exist, in your case you want to use >&. You already redirected stdout, that's why the form &> does not work. You can easily verify it this way:

getent /etc/passwd username >/dev/null 2&>1
ls

You will see a file named 1 in the current directory. You want to use 2>&1 instead, or use this:

getent /etc/passwd username &>/dev/null

This also redirects stdout and stderr to /dev/null.

Warning Redirecting stderr to /dev/null might not be such a good idea. When things go wrong, you will have no clue why.

How to install Laravel's Artisan?

in laravel, artisan is a file under root/protected page

for example,

c:\xampp\htdocs\my_project\protected\artisan

you can view the content of "artisan" file with any text editor, it's a php command syntax

so when we type

php artisan

we tell php to run php script in "artisan" file

for example:

php artisan change

will show the change of current laravel version

to see the other option, just type

php artisan

Resource interpreted as Document but transferred with MIME type application/zip

You can specify the HTML5 download attribute in your <a> tag.

<a href="http://example.com/archive.zip" download>Export</a>

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download

Adding whitespace in Java

There's a few approaches for this:

  1. Create a char array then use Arrays.fill, and finally convert to a String
  2. Iterate through a loop adding a space each time
  3. Use String.format

Indirectly referenced from required .class file

Have you Googled for "weblogic ExpressionMap"? Do you know what it is and what it does?

Looks like you definitely need to be compiling alongside Weblogic and with Weblogic's jars included in your Eclipse classpath, if you're not already.

If you're not already working with Weblogic, then you need to find out what in the world is referencing it. You might need to do some heavy-duty grepping on your jars, classfiles, and/or source files looking for which ones include the string "weblogic".

If I had to include something that was relying on this Weblogic class, but couldn't use Weblogic, I'd be tempted to try to reverse-engineer a compatible class. Create your own weblogic.utils.expressions.ExpressionMap class; see if everything compiles; use any resultant errors or warnings at compile-time or runtime to give you clues as to what methods and other members need to be in this class. Make stub methods that do nothing or return null if possible.

How can I extract the folder path from file path in Python?

WITH PATHLIB MODULE (UPDATED ANSWER)

One should consider using pathlib for new development. It is in the stdlib for Python3.4, but available on PyPI for earlier versions. This library provides a more object-orented method to manipulate paths <opinion> and is much easier read and program with </opinion>.

>>> import pathlib
>>> existGDBPath = pathlib.Path(r'T:\Data\DBDesign\DBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:\Data\DBDesign')

WITH OS MODULE

Use the os.path module:

>>> import os
>>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr 
'T:\Data\DBDesign'

You can go ahead and assume that if you need to do some sort of filename manipulation it's already been implemented in os.path. If not, you'll still probably need to use this module as the building block.

How to loop backwards in python?

To reverse a string without using reversed or [::-1], try something like:

def reverse(text):
    # Container for reversed string
    txet=""

    # store the length of the string to be reversed
    # account for indexes starting at 0
    length = len(text)-1

    # loop through the string in reverse and append each character
    # deprecate the length index
    while length>=0:
        txet += "%s"%text[length]
        length-=1
    return txet

Iterate over each line in a string in PHP

Kyril's answer is best considering you need to be able to handle newlines on different machines.

"I'm mostly looking for useful PHP functions, not an algorithm for how to do it. Any suggestions?"

I use these a lot:

  • explode() can be used to split a string into an array, given a single delimiter.
  • implode() is explode's counterpart, to go from array back to string.

Java System.out.print formatting

Are you sure that you want "055" as opposed to "55"? Some programs interpret a leading zero as meaning octal, so that it would read 055 as (decimal) 45 instead of (decimal) 55.

That should just mean dropping the '0' (zero-fill) flag.

e.g., change System.out.printf("%03d ", x); to the simpler System.out.printf("%3d ", x);

Document Root PHP

Just / refers to the root of your website from the public html folder. DOCUMENT_ROOT refers to the local path to the folder on the server that contains your website.

For example, I have EasyPHP setup on a machine...

$_SERVER["DOCUMENT_ROOT"] gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www but any file I link to with just / will be relative to my www folder.

If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT. if you want to give the absolute path to a file from your website's root, use just /.

How can I do DNS lookups in Python, including referring to /etc/hosts?

I'm not really sure if you want to do DNS lookups yourself or if you just want a host's ip. In case you want the latter,

/!\ socket.gethostbyname is depricated, prefer socket.getaddrinfo

from man gethostbyname:

The gethostbyname*(), gethostbyaddr*(), [...] functions are obsolete. Applications should use getaddrinfo(3), getnameinfo(3),

import socket
print(socket.gethostbyname('localhost')) # result from hosts file
print(socket.gethostbyname('google.com')) # your os sends out a dns query

month name to month number and vice versa in python

form month name to number
d=['JAN','FEB','MAR','April','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
N=input()
for i in range(len(d)):
    if d[i] == N:
        month=(i+1)
print(month)

Search for all files in project containing the text 'querystring' in Eclipse

Just noticed that quick search has been included into eclipse 4.13 as a built-in function by typing Ctrl+Alt+Shift+L (or Cmd+Alt+Shift+L on Mac)

https://www.eclipse.org/eclipse/news/4.13/platform.php#quick-text-search

Jquery date picker z-index issue

That what solved my problem:

 $( document ).ready(function() {   
    $('#datepickerid').datepicker({
     zIndexOffset: 1040 #or any number you want
     });
});

Do you recommend using semicolons after every statement in JavaScript?

This is the very best explanation of automatic semicolon insertion that I've found anywhere. It will clear away all your uncertainty and doubt.

Python Brute Force algorithm

I found another very easy way to create dictionaries using itertools.

generator=itertools.combinations_with_replacement('abcd', 4 )

This will iterate through all combinations of 'a','b','c' and 'd' and create combinations with a total length of 1 to 4. ie. a,b,c,d,aa,ab.........,dddc,dddd. generator is an itertool object and you can loop through normally like this,

for password in generator:
        ''.join(password)

Each password is infact of type tuple and you can work on them as you normally do.

Aborting a stash pop in Git

I'm posting here hoping that others my find my answer helpful. I had a similar problem when I tried to do a stash pop on a different branch than the one I had stashed from. On my case I had no files that were uncommitted or in the index but still got into the merge conflicts case (same case as @pid). As others pointed out previously, the failed git stash pop did indeed retain my stash, then A quick git reset HEAD plus going back to my original branch and doing the stash from there did resolve my problem.

How can I suppress all output from a command using Bash?

An alternative that may fit in some situations is to assign the result of a command to a variable:

$ DUMMY=$( grep root /etc/passwd 2>&1 )
$ echo $?
0
$ DUMMY=$( grep r00t /etc/passwd 2>&1 )
$ echo $?
1

Since Bash and other POSIX commandline interpreters does not consider variable assignments as a command, the present command's return code is respected.

Note: assignement with the typeset or declare keyword is considered as a command, so the evaluated return code in case is the assignement itself and not the command executed in the sub-shell:

$ declare DUMMY=$( grep r00t /etc/passwd 2>&1 )
$ echo $?
0

How do I make a "div" button submit the form its sitting in?

onClick="javascript:this.form.submit();">

this in div onclick don't have attribute form, you may try this.parentNode.submit() or document.forms[0].submit() will do

Also, onClick, should be onclick, some browsers don't work with onClick

scrollTop jquery, scrolling to div with id?

My solution was the following:

document.getElementById("agent_details").scrollIntoView();

Loop through each cell in a range of cells when given a Range object

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Cells
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

Import SQL dump into PostgreSQL database

I'm not sure if this works for the OP's situation, but I found that running the following command in the interactive console was the most flexible solution for me:

\i 'path/to/file.sql'

Just make sure you're already connected to the correct database. This command executes all of the SQL commands in the specified file.

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

I had a similar issue some time ago. You must be careful with quotes and double quotes. It's recommended to reset the user password, using a admin credentials.

ALTER USER user_name IDENTIFIED BY new_password;

But don't use double quotes in both parameters.

Extract digits from a string in Java

Using Google Guava:

CharMatcher.DIGIT.retainFrom("123-456-789");

CharMatcher is plug-able and quite interesting to use, for instance you can do the following:

String input = "My phone number is 123-456-789!";
String output = CharMatcher.is('-').or(CharMatcher.DIGIT).retainFrom(input);

output == 123-456-789

How can you get the Manifest Version number from the App's (Layout) XML variables?

I solved this issue by extending the Preference class.

package com.example.android;

import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;

public class VersionPreference extends Preference {
    public VersionPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        String versionName;
        final PackageManager packageManager = context.getPackageManager();
        if (packageManager != null) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                versionName = null;
            }
            setSummary(versionName);
        }
    }
}

Then in my preferences XML:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <com.example.android.VersionPreference android:title="Version" />
</PreferenceScreen>

How to label scatterplot points by name?

Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.

In short it works ok for a small data set or just key points from a data set.

How many bytes in a JavaScript string?

A single element in a JavaScript String is considered to be a single UTF-16 code unit. That is to say, Strings characters are stored in 16-bit (1 code unit), and 16-bit is equal to 2 bytes (8-bit = 1 byte).

The charCodeAt() method can be used to return an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

The codePointAt() can be used to return the entire code point value for Unicode characters, e.g. UTF-32.

When a UTF-16 character can't be represented in a single 16-bit code unit, it will have a surrogate pair and therefore use two code units( 2 x 16-bit = 4 bytes)

See Unicode encodings for different encodings and their code ranges.

pip broke. how to fix DistributionNotFound error?

Try re-installing with the get-pip script:

wget https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py

This is sourced from the pip Github page, and worked for me.

Error using eclipse for Android - No resource found that matches the given name

For me the issue appeared because my string file could not be parsed. I wanted to have a value like '%s - %s'. However this appeared to be triggering a problem, it seems string will try to parse this value in a special way. Because two string values were provided in a single value an error was written in the console, but I had so many errors triggered from that, that the initial error was hidden, because of small console buffer. Adding formatted="false" attribute to this string value of mine fixed the problem in the string file (which btw was not reported as compilation error in the file itself) and I was able to build once more.

Clearing content of text file using php

//create a file handler by opening the file
$myTextFileHandler = @fopen("filelist.txt","r+");

//truncate the file to zero
//or you could have used the write method and written nothing to it
@ftruncate($myTextFileHandler, 0);

//use location header to go back to index.html
header("Location:index.html");

I don't exactly know where u want to show the result.

How to find the foreach index?

Jonathan is correct. PHP arrays act as a map table mapping keys to values. in some cases you can get an index if your array is defined, such as

$var = array(2,5);

for ($i = 0; $i < count($var); $i++) {
    echo $var[$i]."\n";
}

your output will be

2
5

in which case each element in the array has a knowable index, but if you then do something like the following

$var = array_push($var,10);

for ($i = 0; $i < count($var); $i++) {
    echo $var[$i]."\n";
}

you get no output. This happens because arrays in PHP are not linear structures like they are in most languages. They are more like hash tables that may or may not have keys for all stored values. Hence foreach doesn't use indexes to crawl over them because they only have an index if the array is defined. If you need to have an index, make sure your arrays are fully defined before crawling over them, and use a for loop.

Android: Test Push Notification online (Google Cloud Messaging)

POSTMAN : A google chrome extension

Use postman to send message instead of server. Postman settings are as follows :

Request Type: POST

URL: https://android.googleapis.com/gcm/send

Header
  Authorization  : key=your key //Google API KEY
  Content-Type : application/json

JSON (raw) :
{       
  "registration_ids":["yours"],
  "data": {
    "Hello" : "World"
  } 
}

on success you will get

Response :
{
  "multicast_id": 6506103988515583000,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    {
      "message_id": "0:1432811719975865%54f79db3f9fd7ecd"
    }
  ]
}

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

I wouldn't go with MSTest. Although it's probably the most future proof of the frameworks with Microsoft behind it's not the most flexible solution. It won't run stand alone without some hacks. So running it on a build server other than TFS without installing Visual Studio is hard. The visual studio test-runner is actually slower than Testdriven.Net + any of the other frameworks. And because the releases of this framework are tied to releases of Visual Studio there are less updates and if you have to work with an older VS you're tied to an older MSTest.

I don't think it matters a lot which of the other frameworks you use. It's really easy to switch from one to another.

I personally use XUnit.Net or NUnit depending on the preference of my coworkers. NUnit is the most standard. XUnit.Net is the leanest framework.

Number prime test in JavaScript

I think a better way to find a prime number is with this logic:

_x000D_
_x000D_
var p=prompt("input numeric value","10"); // input your number _x000D_
for(j=2;j<p;j++){ _x000D_
  if(isPrimes(j)){ _x000D_
    document.write(j+", "); // for output the value_x000D_
  } // end if_x000D_
}// end for loop_x000D_
function isPrimes(n) {_x000D_
  var primes = true;// let prime is true_x000D_
  for (i=2;i<n;i++) {_x000D_
    if(n%i==0) {_x000D_
      primes= false; // return prime is false_x000D_
      break; // break the loop_x000D_
    }// end if inner _x000D_
  }// end inner loop_x000D_
  return primes; // return the prime true or false_x000D_
}// end the function
_x000D_
_x000D_
_x000D_

Media query to detect if device is touchscreen

I was able to resolve this issue using this

@media (hover:none), (hover:on-demand) { 
Your class or ID{
attributes
}    
}

Replace all spaces in a string with '+'

You need to look for some replaceAll option

str = str.replace(/ /g, "+");

this is a regular expression way of doing a replaceAll.

function ReplaceAll(Source, stringToFind, stringToReplace) {
    var temp = Source;
    var index = temp.indexOf(stringToFind);

    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;
}

String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
    var temp = this;
    var index = temp.indexOf(stringToFind);

    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;

};

Determine number of pages in a PDF file

I have used pdflib for this.

    p = new pdflib();

    /* Open the input PDF */
    indoc = p.open_pdi_document("myTestFile.pdf", "");
    pageCount = (int) p.pcos_get_number(indoc, "length:pages");

Concatenate chars to form String in java

Use StringBuilder:

String str;
Char a, b, c;
a = 'i';
b = 'c';
c = 'e';

StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
sb.append(c);
str = sb.toString();

One-liner:

new StringBuilder().append(a).append(b).append(c).toString();

Doing ""+a+b+c gives:

new StringBuilder().append("").append(a).append(b).append(c).toString();

I asked some time ago related question.

I need to round a float to two decimal places in Java

If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat class. It's very simple:

double d = 2.3d;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(d);

Which will output (depending on locale):

$2.30

Also, if currency isn't required (just the exact two decimal places) you can use this instead:

NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String output = formatter.format(d);

Which will output 2.30

How can I open a link in a new window?

Be aware if you want to execute AJAX requests inside the event handler function for the click event. For some reason Chrome (and maybe other browsers) will not open a new tab/window.

Rails: How to reference images in CSS within Rails 4

Sprockets together with Sass has some nifty helpers you can use to get the job done. Sprockets will only process these helpers if your stylesheet file extensions are either .css.scss or .css.sass.


Image specific helper:

background-image: image-url("logo.png")

Agnostic helper:

background-image: asset-url("logo.png", image)
background-image: asset-url($asset, $asset-type)

Or if you want to embed the image data in the css file:

background-image: asset-data-url("logo.png")

How can I pass a parameter to a setTimeout() callback?

// These are three very simple and concise answers:

function fun() {
    console.log(this.prop1, this.prop2, this.prop3);
}

let obj = { prop1: 'one', prop2: 'two', prop3: 'three' };

let bound = fun.bind(obj);

setTimeout(bound, 3000);

 // or

function funOut(par1, par2, par3) {

  return function() { 

    console.log(par1, par2, par3);

  }
};

setTimeout(funOut('one', 'two', 'three'), 5000);

 // or

let funny = function(a, b, c) { console.log(a, b, c); };

setTimeout(funny, 2000, 'hello', 'worldly', 'people');

XMLHttpRequest status 0 (responseText is empty)

I just had this issue because I used 0.0.0.0 as my server, changed it to localhost and it works.

Nesting queries in SQL

If it has to be "nested", this would be one way, to get your job done:

SELECT o.name AS country, o.headofstate 
FROM   country o
WHERE  o.headofstate like 'A%'
AND   (
    SELECT i.population
    FROM   city i
    WHERE  i.id = o.capital
    ) > 100000

A JOIN would be more efficient than a correlated subquery, though. Can it be, that who ever gave you that task is not up to speed himself?

Set selected item in Android BottomNavigationView

For those, who still use SupportLibrary < 25.3.0

I'm not sure whether this is a complete answer to this question, but my problem was very similar - I had to process back button press and bring user to previous tab where he was. So, maybe my solution will be useful for somebody:

private void updateNavigationBarState(int actionId){
    Menu menu = bottomNavigationView.getMenu();

    for (int i = 0, size = menu.size(); i < size; i++) {
        MenuItem item = menu.getItem(i);
        item.setChecked(item.getItemId() == actionId);
    }
}

Please, keep in mind that if user press other navigation tab BottomNavigationView won't clear currently selected item, so you need to call this method in your onNavigationItemSelected after processing of navigation action:

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.some_id_1:
            // process action
            break;
        case R.id.some_id_2:
            // process action
            break;
        ...
        default:
            return false;
    }

    updateNavigationBarState(item.getItemId());

    return true;
}

Regarding the saving of instance state I think you could play with same action id of navigation view and find suitable solution.

Getting a count of objects in a queryset in django

Use related name to count votes for a specific contest

class Item(models.Model):
    name = models.CharField()

class Contest(models.Model);
    name = models.CharField()

class Votes(models.Model):
    user = models.ForeignKey(User)
    item = models.ForeignKey(Item)
    contest = models.ForeignKey(Contest, related_name="contest_votes")
    comment = models.TextField()

>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()

How do I clone a Django model instance object and save it to the database?

How to do this was added to the official Django docs in Django1.4

https://docs.djangoproject.com/en/1.10/topics/db/queries/#copying-model-instances

The official answer is similar to miah's answer, but the docs point out some difficulties with inheritance and related objects, so you should probably make sure you read the docs.

"VT-x is not available" when I start my Virtual machine

You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

$startTime = strtotime('2010-05-01'); 
$endTime = strtotime('2010-05-10'); 

// Loop between timestamps, 1 day at a time 
$i = 1;
do {
   $newTime = strtotime('+'.$i++.' days',$startTime); 
   echo $newTime;
} while ($newTime < $endTime);

or

$startTime = strtotime('2010-05-01'); 
$endTime = strtotime('2010-05-10'); 

// Loop between timestamps, 1 day at a time 
do {
   $startTime = strtotime('+1 day',$startTime); 
   echo $startTime;
} while ($startTime < $endTime);

Setting a property by reflection with a string value

Are you looking to play around with Reflection or are you looking to build a production piece of software? I would question why you're using reflection to set a property.

Double new_latitude;

Double.TryParse (value, out new_latitude);
ship.Latitude = new_latitude;

Make a table fill the entire window

You can use position like this to stretch an element across the parent container.

<table style="position: absolute; top: 0; bottom: 0; left: 0; right: 0;">
    <tr style="height: 25%; font-size: 180px;">
        <td>Region</td>
    </tr>
    <tr style="height: 75%; font-size: 540px;">
        <td>100.00%</td>
    </tr>
</table>

Java JTable getting the data of the selected row

http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html

You will find these methods in it:

getValueAt(int row, int column)
getSelectedRow()
getSelectedColumn()

Use a mix of these to achieve your result.

IntelliJ how to zoom in / out

Double click shift, type zoom and switch zoom to on

enter image description here

How to declare an array in Python?

A couple of contributions suggested that arrays in python are represented by lists. This is incorrect. Python has an independent implementation of array() in the standard library module array "array.array()" hence it is incorrect to confuse the two. Lists are lists in python so be careful with the nomenclature used.

list_01 = [4, 6.2, 7-2j, 'flo', 'cro']

list_01
Out[85]: [4, 6.2, (7-2j), 'flo', 'cro']

There is one very important difference between list and array.array(). While both of these objects are ordered sequences, array.array() is an ordered homogeneous sequences whereas a list is a non-homogeneous sequence.

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

As mentioned by @leocaseiro on github issue.

I found 3 solutions for those who are looking for easy fixes.

1) Moving from ngAfterViewInit to ngAfterContentInit

2) Moving to ngAfterViewChecked combined with ChangeDetectorRef as suggested on #14748 (comment)

3) Keep with ngOnInit() but call ChangeDetectorRef.detectChanges() after your changes.

Test class with a new() call in it with Mockito

I happened to be in a particular situation where my usecase resembled the one of Mureinik but I ended-up using the solution of Tomasz Nurkiewicz.

Here is how:

class TestedClass extends AARRGGHH {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
        return lc;
    }
}

Now, PowerMockRunner failed to initialize TestedClass because it extends AARRGGHH, which in turn does more contextual initialization... You see where this path was leading me: I would have needed to mock on several layers. Clearly a HUGE smell.

I found a nice hack with minimal refactoring of TestedClass: I created a small method

LoginContext initLoginContext(String login, CallbackHandler callbackHandler) {
    new lc = new LoginContext(login, callbackHandler);
}

The scope of this method is necessarily package.

Then your test stub will look like:

LoginContext lcMock = mock(LoginContext.class)
TestedClass testClass = spy(new TestedClass(withAllNeededArgs))
doReturn(lcMock)
    .when(testClass)
    .initLoginContext("login", callbackHandler)

and the trick is done...

How to check if a word is an English word with Python?

I find that there are 3 package-based solutions to solve the problem. They are pyenchant, wordnet and corpus(self-defined or from ntlk). Pyenchant couldn't installed easily in win64 with py3. Wordnet doesn't work very well because it's corpus isn't complete. So for me, I choose the solution answered by @Sadik, and use 'set(words.words())' to speed up.

First:

pip3 install nltk
python3

import nltk
nltk.download('words')

Then:

from nltk.corpus import words
setofwords = set(words.words())

print("hello" in setofwords)
>>True

Git merge without auto commit

I prefer this way so I don't need to remember any rare parameters.

git merge branch_name

It will then say your branch is ahead by "#" commits, you can now pop these commits off and put them into the working changes with the following:

git reset @~#

For example if after the merge it is 1 commit ahead, use:

git reset @~1

Note: On Windows, quotes are needed. (As Josh noted in comments) eg:

git reset "@~1"

Invalid column name sql error

You should never write code that concatenates SQL and parameters as string - this opens up your code to SQL injection which is a really serious security problem.

Use bind params - for a nice howto see here...

setContentView(R.layout.main); error

Step 1 : import android.*;

Step 2 : clean your project

Step 3 : Enjoy !!!

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

Vue-router redirect on page not found (404)

@mani's Original answer is all you want, but if you'd also like to read it in official way, here's

Reference to Vue's official page:

https://router.vuejs.org/guide/essentials/history-mode.html#caveat

How to compare two columns in Excel and if match, then copy the cell next to it

It might be easier with vlookup. Try this:

=IFERROR(VLOOKUP(D2,G:H,2,0),"")

The IFERROR() is for no matches, so that it throws "" in such cases.

VLOOKUP's first parameter is the value to 'look for' in the reference table, which is column G and H.

VLOOKUP will thus look for D2 in column G and return the value in the column index 2 (column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.

The last parameter is 0 (or equivalently FALSE) to mean an exact match. That's what you need as opposed to approximate match.

In PHP, how do you change the key of an array element?

The answer from KernelM is nice, but in order to avoid the issue raised by Greg in the comment (conflicting keys), using a new array would be safer

$newarr[$newkey] = $oldarr[$oldkey];
$oldarr=$newarr;
unset($newarr);

Regular Expression For Duplicate Words

No. That is an irregular grammar. There may be engine-/language-specific regular expressions that you can use, but there is no universal regular expression that can do that.

How to create an installer for a .net Windows Service using Visual Studio

I follow Kelsey's first set of steps to add the installer classes to my service project, but instead of creating an MSI or setup.exe installer I make the service self installing/uninstalling. Here's a bit of sample code from one of my services you can use as a starting point.

public static int Main(string[] args)
{
    if (System.Environment.UserInteractive)
    {
        // we only care about the first two characters
        string arg = args[0].ToLowerInvariant().Substring(0, 2);

        switch (arg)
        {
            case "/i":  // install
                return InstallService();

            case "/u":  // uninstall
                return UninstallService();

            default:  // unknown option
                Console.WriteLine("Argument not recognized: {0}", args[0]);
                Console.WriteLine(string.Empty);
                DisplayUsage();
                return 1;
        }
    }
    else
    {
        // run as a standard service as we weren't started by a user
        ServiceBase.Run(new CSMessageQueueService());
    }

    return 0;
}

private static int InstallService()
{
    var service = new MyService();

    try
    {
        // perform specific install steps for our queue service.
        service.InstallService();

        // install the service with the Windows Service Control Manager (SCM)
        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
    }
    catch (Exception ex)
    {
        if (ex.InnerException != null && ex.InnerException.GetType() == typeof(Win32Exception))
        {
            Win32Exception wex = (Win32Exception)ex.InnerException;
            Console.WriteLine("Error(0x{0:X}): Service already installed!", wex.ErrorCode);
            return wex.ErrorCode;
        }
        else
        {
            Console.WriteLine(ex.ToString());
            return -1;
        }
    }

    return 0;
}

private static int UninstallService()
{
    var service = new MyQueueService();

    try
    {
        // perform specific uninstall steps for our queue service
        service.UninstallService();

        // uninstall the service from the Windows Service Control Manager (SCM)
        ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
    }
    catch (Exception ex)
    {
        if (ex.InnerException.GetType() == typeof(Win32Exception))
        {
            Win32Exception wex = (Win32Exception)ex.InnerException;
            Console.WriteLine("Error(0x{0:X}): Service not installed!", wex.ErrorCode);
            return wex.ErrorCode;
        }
        else
        {
            Console.WriteLine(ex.ToString());
            return -1;
        }
    }

    return 0;
}

How can I get a list of locally installed Python modules?

Now, these methods I tried myself, and I got exactly what was advertised: All the modules.

Alas, really you don't care much about the stdlib, you know what you get with a python install.

Really, I want the stuff that I installed.

What actually, surprisingly, worked just fine was:

pip freeze

Which returned:

Fabric==0.9.3
apache-libcloud==0.4.0
bzr==2.3b4
distribute==0.6.14
docutils==0.7
greenlet==0.3.1
ipython==0.10.1
iterpipes==0.4
libxml2-python==2.6.21

I say "surprisingly" because the package install tool is the exact place one would expect to find this functionality, although not under the name 'freeze' but python packaging is so weird, that I am flabbergasted that this tool makes sense. Pip 0.8.2, Python 2.7.

complex if statement in python

It is possible to write like this:

elif var1 in [80, 443] or 1024 < var1 < 65535

This way you check if var1 appears in that a list, then you make just 1 check, didn't repeat the "var1" one extra time, and looks clear:

if var1 in [80, 443] or 1024 < var1 < 65535: print 'good' else: print 'bad' ....:
good

Network tools that simulate slow network connection

You can also try WANem which is an open source Wide Area Network emulator. You can download the image (ISO, Knoppix live CD) or VMWare virtual appliances.

No such keg: /usr/local/Cellar/git

Had a similar issue while installing "Lua" in OS X using homebrew. I guess it could be useful for other users facing similar issue in homebrew.

On running the command:

$ brew install lua

The command returned an error:

Error: /usr/local/opt/lua is not a valid keg
(in general the error can be of /usr/local/opt/ is not a valid keg

FIXED it by deleting the file/directory it is referring to, i.e., deleting the "/usr/local/opt/lua" file.

root-user # rm -rf /usr/local/opt/lua

And then running the brew install command returned success.

Ruby on Rails: How do I add placeholder text to a f.text_field?

In Rails 4(Using HAML):

=f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'

Object cannot be cast from DBNull to other types

TryParse is usually the most elegant way to handle this type of thing:

long temp = 0;
if (Int64.TryParse(dataAccCom.GetParameterValue(IDbCmd, "op_Id").ToString(), out temp))
{
   DataTO.Id = temp;
}     

Import a custom class in Java

According Oracle and Sun doc, a class can use all classes from its own package and all public classes from other packages. You can access the public classes in another package in two ways.

  • The first is simply to add the full package name in front of every class name. For example:

    java.util.Date today = new java.util.Date();

  • The simpler, and more common, approach is to use the import statement. The point of the import statement is to give you a shorthand to refer to the classes in the package. Once you use import, you no longer have to give the classes their full names. You can import a specific class or the whole package. You place import statements at the top of your source files (but below any package statements). For example, you can import all classes in the java.util package with the statement Then you can use without a package prefix.

    import java.util.*;

    // Use class in your code with this manner

    Date today = new Date();

As you mentioned in your question that your classes are under the same package, you should not have any problem, it is better just to use class name.

Remove duplicated rows using dplyr

Most of the time, the best solution is using distinct() from dplyr, as has already been suggested.

However, here's another approach that uses the slice() function from dplyr.

# Generate fake data for the example
  library(dplyr)
  set.seed(123)
  df <- data.frame(
    x = sample(0:1, 10, replace = T),
    y = sample(0:1, 10, replace = T),
    z = 1:10
  )

# In each group of rows formed by combinations of x and y
# retain only the first row

    df %>%
      group_by(x, y) %>%
      slice(1)

Difference from using the distinct() function

The advantage of this solution is that it makes it explicit which rows are retained from the original dataframe, and it can pair nicely with the arrange() function.

Let's say you had customer sales data and you wanted to retain one record per customer, and you want that record to be the one from their latest purchase. Then you could write:

customer_purchase_data %>%
   arrange(desc(Purchase_Date)) %>%
   group_by(Customer_ID) %>%
   slice(1)

Python Script execute commands in Terminal

import os
os.system("echo 'hello world'")

This should work. I do not know how to print the output into the python Shell.

Django model "doesn't declare an explicit app_label"

Are you missing putting in your application name into the settings file? The myAppNameConfig is the default class generated at apps.py by the .manage.py createapp myAppName command. Where myAppName is the name of your app.

settings.py

INSTALLED_APPS = [
'myAppName.apps.myAppNameConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

This way, the settings file finds out what you want to call your application. You can change how it looks later in the apps.py file by adding the following code in

myAppName/apps.py

class myAppNameConfig(AppConfig):
    name = 'myAppName'
    verbose_name = 'A Much Better Name'

How can I return to a parent activity correctly?

Going into my manifest and adding android:launchMode="singleTop" to the activity did the trick for me.

This specifically solved my issue because I didn't want Android to create a new instance of the previous activity after hitting the Up button in the toolbar - I instead wanted to use the existing instance of the prior activity when I went up the navigation hierarchy.

Reference: android:launchMode

bootstrap 3 tabs not working properly

Use this for your code

<ul class="nav nav-tabs" style="margin-top:10em;">
  <li class="active" data-toggle="tab"><a href="#">Assign</a></li>
<li data-toggle="tab"><a href="#">Two</a></li>
<li data-toggle="tab"><a href="#">Three</a></li>

Submit HTML form on self page

If you are submitting a form using php be sure to use:

action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"

for security.

Convert an array to string

You probably want something like this overload of String.Join:

String.Join<T> Method (String, IEnumerable<T>)

Docs:

http://msdn.microsoft.com/en-us/library/dd992421.aspx

In your example, you'd use

String.Join("", Client);

Fixed height and width for bootstrap carousel

To have a consistent flow of the images on different devices, you'd have to specify the width and height value for each carousel image item, for instance here in my example the image would take the full width but with a height of "400px" (you can specify your personal value instead)

<div class="item">
        <img src="image.jpg" style="width:100%; height: 400px;">
      </div>

Unordered List (<ul>) default indent

As to why, no idea.

A reset will most certainly fix this:

ul { margin: 0; padding: 0; }

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

Give you something different, when you encounter this kind of error, cannot create bean datasource in a test case.

It might be caused by some reasons:

  1. No datasource, you will need to create your datasource, h2 in-memory datasource or whatever, or you can choose the way like exclude={datasource··}.
  2. You have your datasource, like MySQL, but it still not work. It was caused by class AutoConfigureTestDatabase, It will choose a datasource for you which may cause ambiguity.

Solution: add @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) to avoid replace the default datasource.

How to configure static content cache per folder and extension in IIS7?

I had the same issue.For me the problem was how to configure a cache limit to images.And i came across this site which gave some insights to the procedure on how the issue can be handled.Hope it will be helpful for you too Link:[https://varvy.com/pagespeed/cache-control.html]

node.js require all files in a folder?

One more option is require-dir-all combining features from most popular packages.

Most popular require-dir does not have options to filter the files/dirs and does not have map function (see below), but uses small trick to find module's current path.

Second by popularity require-all has regexp filtering and preprocessing, but lacks relative path, so you need to use __dirname (this has pros and contras) like:

var libs = require('require-all')(__dirname + '/lib');

Mentioned here require-index is quite minimalistic.

With map you may do some preprocessing, like create objects and pass config values (assuming modules below exports constructors):

// Store config for each module in config object properties 
// with property names corresponding to module names 
var config = {
  module1: { value: 'config1' },
  module2: { value: 'config2' }
};

// Require all files in modules subdirectory 
var modules = require('require-dir-all')(
  'modules', // Directory to require 
  { // Options 
    // function to be post-processed over exported object for each require'd module 
    map: function(reqModule) {
      // create new object with corresponding config passed to constructor 
      reqModule.exports = new reqModule.exports( config[reqModule.name] );
    }
  }
);

// Now `modules` object holds not exported constructors, 
// but objects constructed using values provided in `config`.

Edittext change border color with shape.xml

i use as following for over come this matter

edittext_style.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:thickness="0dp"
android:shape="rectangle">
<stroke android:width="1dp"
        android:color="#c8c8c8"/>
<corners android:radius="0dp" />

And applied as bellow

<EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/editTextName"
            android:background="@drawable/edit_text_style"/>

try like this..

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

How to toggle a boolean?

In a case where you may be storing true / false as strings, such as in localStorage where the protocol flipped to multi object storage in 2009 & then flipped back to string only in 2011 - you can use JSON.parse to interpret to boolean on the fly:

this.sidebar = !JSON.parse(this.sidebar);

Renaming part of a filename

Something like this will do it. The for loop may need to be modified depending on which filenames you wish to capture.

for fspec1 in DET01-ABC-5_50-*.dat ; do
    fspec2=$(echo ${fspec1} | sed 's/-ABC-/-XYZ-/')
    mv ${fspec1} ${fspec2}
done

You should always test these scripts on copies of your data, by the way, and in totally different directories.

Does Android support near real time push notification?

Firebase Cloud Messaging FCM FAQ is the new version of GCM. It inherits GCM’s core infrastructure to deliver messages reliably on Android, iOS and Chrome. However they'll continue to support GCM because lot of developers are using GCM SDKs today to handle notifications, and client app upgrade takes time.

As of June 26, 2012, Google Cloud Messaging is the preferred way of sending messages to applications running on devices.

Previously (and now deprecated), the service was called Cloud To Device Messaging.

How to round each item in a list of floats to 2 decimal places?

You can use the built-in map along with a lambda expression:

my_list = [0.2111111111, 0.5, 0.3777777777]
my_list_rounded = list(map(lambda x: round(x, ndigits=2), my_list))
my_list_rounded                                                                                                                                                                                                                 
Out[3]: [0.21, 0.5, 0.38]

Alternatively you could also create a named function for the rounding up to a specific digit using partial from the functools module for working with higher order functions:

from functools import partial

my_list = [0.2111111111, 0.5, 0.3777777777]
round_2digits = partial(round, ndigits=2)
my_list_rounded = list(map(round_2digits, my_list))
my_list_rounded                                                                                                                                                                                                                 
Out[6]: [0.21, 0.5, 0.38]

jQuery UI: Datepicker set year range dropdown to 100 years

I did this:

var dateToday = new Date();
var yrRange = dateToday.getFullYear() + ":" + (dateToday.getFullYear() + 50);
and then
yearRange : yrRange

where 50 is the range from current year.

What is the difference between 'git pull' and 'git fetch'?

I have struggled with this as well. In fact I got here with a google search of exactly the same question. Reading all these answers finally painted a picture in my head and I decided to try to get this down looking at the state of the 2 repositories and 1 sandbox and actions performed over time while watching the version of them. So here is what I came up with. Please correct me if I messed up anywhere.

The three repos with a fetch:

---------------------     -----------------------     -----------------------
- Remote Repo       -     - Remote Repo         -     - Remote Repo         -
-                   -     - gets pushed         -     -                     -
- @ R01             -     - @ R02               -     - @ R02               -
---------------------     -----------------------     -----------------------

---------------------     -----------------------     -----------------------
- Local Repo        -     - Local Repo          -     - Local Repo          -
- pull              -     -                     -     - fetch               -
- @ R01             -     - @ R01               -     - @ R02               -
---------------------     -----------------------     -----------------------

---------------------     -----------------------     -----------------------
- Local Sandbox     -     - Local Sandbox       -     - Local Sandbox       -
- Checkout          -     - new work done       -     -                     -
- @ R01             -     - @ R01+              -     - @R01+               -
---------------------     -----------------------     -----------------------

The three repos with a pull

---------------------     -----------------------     -----------------------
- Remote Repo       -     - Remote Repo         -     - Remote Repo         -
-                   -     - gets pushed         -     -                     -
- @ R01             -     - @ R02               -     - @ R02               -
---------------------     -----------------------     -----------------------

---------------------     -----------------------     -----------------------
- Local Repo        -     - Local Repo          -     - Local Repo          -
- pull              -     -                     -     - pull                -
- @ R01             -     - @ R01               -     - @ R02               -
---------------------     -----------------------     -----------------------

---------------------     -----------------------     -----------------------
- Local Sandbox     -     - Local Sandbox       -     - Local Sandbox       -
- Checkout          -     - new work done       -     - merged with R02     -
- @ R01             -     - @ R01+              -     - @R02+               -
---------------------     -----------------------     -----------------------

This helped me understand why a fetch is pretty important.

Maximize a window programmatically and prevent the user from changing the windows state

Change the property WindowState to System.Windows.Forms.FormWindowState.Maximized, in some cases if the older answers doesn't works.

So the window will be maximized, and the other parts are in the other answers.

MongoDB: How to query for records where field is null or not set?

db.employe.find({ $and:[ {"dept":{ $exists:false }, "empno": { $in:[101,102] } } ] }).count();

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?

Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.

tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.

Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.

hth! Regards, Remco

Get current time in hours and minutes

Provide a format string:

date +"%H:%M"

Running man date will give all the format options

%a     locale's abbreviated weekday name (e.g., Sun)
%A     locale's full weekday name (e.g., Sunday)
%b     locale's abbreviated month name (e.g., Jan)
%B     locale's full month name (e.g., January)
%c     locale's date and time (e.g., Thu Mar  3 23:05:25 2005)
%C     century; like %Y, except omit last two digits (e.g., 20)
%d     day of month (e.g., 01)
%D     date; same as %m/%d/%y
%e     day of month, space padded; same as %_d
%F     full date; same as %Y-%m-%d
%g     last two digits of year of ISO week number (see %G)
%G     year of ISO week number (see %V); normally useful only with %V
%h     same as %b
%H     hour (00..23)
%I     hour (01..12)
%j     day of year (001..366)
%k     hour, space padded ( 0..23); same as %_H
%l     hour, space padded ( 1..12); same as %_I
%m     month (01..12)
%M     minute (00..59)
%n     a newline
%N     nanoseconds (000000000..999999999)
%p     locale's equivalent of either AM or PM; blank if not known
%P     like %p, but lower case
%r     locale's 12-hour clock time (e.g., 11:11:04 PM)
%R     24-hour hour and minute; same as %H:%M
%s     seconds since 1970-01-01 00:00:00 UTC
%S     second (00..60)
%t     a tab
%T     time; same as %H:%M:%S
%u     day of week (1..7); 1 is Monday
%U     week number of year, with Sunday as first day of week (00..53)
%V     ISO week number, with Monday as first day of week (01..53)
%w     day of week (0..6); 0 is Sunday
%W     week number of year, with Monday as first day of week (00..53)
%x     locale's date representation (e.g., 12/31/99)
%X     locale's time representation (e.g., 23:13:48)
%y     last two digits of year (00..99)
%Y     year
%z     +hhmm numeric time zone (e.g., -0400)
%:z    +hh:mm numeric time zone (e.g., -04:00)
%::z   +hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::z  numeric time zone with : to necessary precision (e.g., -04, +05:30)
%Z     alphabetic time zone abbreviation (e.g., EDT)

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I'm not sure if I am correct, but from the request header that you post:

Request headers

Accept: Application/json

Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36

Content-Type: application/x-www-form-urlencoded

Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8

it seems like you didn't config your request body to JSON type.

warning: incompatible implicit declaration of built-in function ‘xyz’

I met these warnings on mempcpy function. Man page says this function is a GNU extension and synopsis shows:

#define _GNU_SOURCE
#include <string.h>

When #define is added to my source before the #include, declarations for the GNU extensions are made visible and warnings disappear.

Format price in the current locale and currency

By this code for formating price in product list

echo Mage::helper('core')->currency($_product->getPrice());

Is it safe to store a JWT in localStorage with ReactJS?

Localstorage is designed to be accessible by javascript, so it doesn't provide any XSS protection. As mentioned in other answers, there is a bunch of possible ways to do an XSS attack, from which localstorage is not protected by default.

However, cookies have security flags which protect from XSS and CSRF attacks. HttpOnly flag prevents client side javascript from accessing the cookie, Secure flag only allows the browser to transfer the cookie through ssl, and SameSite flag ensures that the cookie is sent only to the origin. Although I just checked and SameSite is currently supported only in Opera and Chrome, so to protect from CSRF it's better to use other strategies. For example, sending an encrypted token in another cookie with some public user data.

So cookies are a more secure choice for storing authentication data.

How to backup Sql Database Programmatically in C#

You can use the following queries to Backup and Restore, you must change the path for your backup

Database name=[data]

Backup:

BACKUP DATABASE [data] TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH NOFORMAT, NOINIT,  NAME = N'data-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

Restore:

RESTORE DATABASE [data] FROM  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10
GO

Check whether a value exists in JSON object

Why not JSON.stringify and .includes()?

You can easily check if a JSON object includes a value by turning it into a string and checking the string.

console.log(JSON.stringify(JSONObject).includes("dog"))
--> true

Edit: make sure to check browser compatibility for .includes()

How to uncheck a radio button?

Try

$(this).attr("checked" , false );

If statement in aspx page

<div>
    <% 
        if (true)
        {
    %>
    <div>
        Show true content
    </div>
    <%
        }
        else
        {
    %>
    <div>
        Show false content
    </div>
    <%
        }
    %>
</div>

How to create a temporary directory?

Here is a simple explanation about how to create a temp dir using templates.

  1. Creates a temporary file or directory, safely, and prints its name.
  2. TEMPLATE must contain at least 3 consecutive 'X's in last component.
  3. If TEMPLATE is not specified, it will use tmp.XXXXXXXXXX
  4. directories created are u+rwx, minus umask restrictions.

PARENT_DIR=./temp_dirs # (optional) specify a dir for your tempdirs
mkdir $PARENT_DIR

TEMPLATE_PREFIX='tmp' # prefix of your new tempdir template
TEMPLATE_RANDOM='XXXX' # Increase the Xs for more random characters
TEMPLATE=${PARENT_DIR}/${TEMPLATE_PREFIX}.${TEMPLATE_RANDOM}

# create the tempdir using your custom $TEMPLATE, which may include
# a path such as a parent dir, and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -d $TEMPLATE)
echo $NEW_TEMP_DIR_PATH

# create the tempdir in parent dir, using default template
# 'tmp.XXXXXXXXXX' and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -p $PARENT_DIR)
echo $NEW_TEMP_DIR_PATH

# create a tempdir in your systems default tmp path e.g. /tmp 
# using the default template 'tmp.XXXXXXXXXX' and assign path to var
NEW_TEMP_DIR_PATH=$(mktemp -d)
echo $NEW_TEMP_DIR_PATH

# Do whatever you want with your generated temp dir and var holding its path

Execute a shell script in current shell with sudo permission

I think you are confused about the difference between sourcing and executing a script.

Executing a script means creating a new process, and running the program. The program can be a shell script, or any other type of program. As it is a sub process, any environmental variables changed in the program will not affect the shell.

Sourcing a script can only be used with a bash script (if you are running bash). It effectively types the commands in as if you did them. This is useful as it lets a script change environmental variables in the shell.


Running a script is simple, you just type in the path to the script. . is the current directory. So ./script.sh will execute the file script.sh in the current directory. If the command is a single file (eg script.sh), it will check all the folders in the PATH variable to find the script. Note that the current directory isn't in PATH, so you can't execute a file script.sh in the current directory by running script.sh, you need to run ./script.sh (unless the current directory is in the PATH, eg you can run ls while in the /bin dir).

Sourcing a script doesn't use the PATH, and just searches for the path. Note that source isn't a program - otherwise it wouldn't be able to change environmental variables in the current shell. It is actually a bash built in command. Search /bin and /usr/bin - you won't find a source program there. So to source a file script.sh in the current directory, you just use source script.sh.


How does sudo interact with this? Well sudo takes a program, and executes it as root. Eg sudo ./script.sh executes script.sh in a sub process but running as root.

What does sudo source ./script.sh do however? Remember source isn't a program (rather a shell builtin)? Sudo expects a program name though, so it searches for a program named source. It doesn't find one, and so fails. It isn't possible to source a file running as root, without creating a new subprocess, as you cannot change the runner of a program (in this case, bash) after it has started.

I'm not sure what you actually wanted, but hopefully this will clear it up for you.


Here is a concrete example. Make the file script.sh in your current directory with the contents:

#!/bin/bash    
export NEW_VAR="hello"
whoami
echo "Some text"

Make it executable with chmod +x script.sh.

Now observe what happens with bash:

> ./script.sh
david
Some text
> echo $NEW_VAR

> sudo ./script.sh
root
Some text
> echo $NEW_VAR

> source script.sh
david
Some text
> echo $NEW_VAR
hello
> sudo source script.sh
sudo: source: command not found

Excel VBA - Range.Copy transpose paste

WorksheetFunction Transpose()

Instead of copying, pasting via PasteSpecial, and using the Transpose option you can simply type a formula

    =TRANSPOSE(Sheet1!A1:A5)

or if you prefer VBA:

    Dim v
    v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
    Sheet2.Range("A1").Resize(1, UBound(v)) = v

Note: alternatively you could use late-bound Application.Transpose instead.

MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.

Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365

Rolling back local and remote git repository by 1 commit

If you only want to remove the last commit from the remote repository without messing up with your local repository, here's a one-liner:

git push origin +origin/master~:master

This uses the following syntax:

git push <remote> <refspec>

Here, <remote> is origin, and <refspec> has the following structure:

+origin/master~:master

Details can be found in git-push(1). The preceding + means "force push this ref", and the other part means "from origin/master~ to master (of remote origin)". It isn't hard to know that origin/master~ is the last commit before origin/master, right?

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

On MySQL 8.0.15 (maybe earlier than this too): the PASSWORD() function does not work anymore, so you have to do:

Make sure you have stopped MySQL first (Go to: 'System Preferences' >> 'MySQL' and stop MySQL).

Run the server in safe mode with privilege bypass:

sudo mysqld_safe --skip-grant-tables
mysql -u root
UPDATE mysql.user SET authentication_string=null WHERE User='root';
FLUSH PRIVILEGES;
exit;

Then

mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';

Finally, start your MySQL again.

Enlighten by @OlatunjiYso in this GitHub issue.

How can I shrink the drawable on a button?

You can use different sized drawables that are used with different screen densities/sizes, etc. so that your image looks right on all devices.

See here: http://developer.android.com/guide/practices/screens_support.html#support

How to use hex color values

Swift 2.0:

In viewDidLoad()

 var viewColor:UIColor
    viewColor = UIColor()
    let colorInt:UInt
    colorInt = 0x000000
    viewColor = UIColorFromRGB(colorInt)
    self.View.backgroundColor=viewColor



func UIColorFromRGB(rgbValue: UInt) -> UIColor {
    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}

Merge Two Lists in R

In general one could,

merge_list <- function(...) by(v<-unlist(c(...)),names(v),base::c)

Note that the by() solution returns an attributed list, so it will print differently, but will still be a list. But you can get rid of the attributes with attr(x,"_attribute.name_")<-NULL. You can probably also use aggregate().

NoClassDefFoundError on Maven dependency

Choosing to Project -> Clean should resolve this

$_POST Array from html form

Change

$info=$_POST['id[]'];

to

$info=$_POST['id'];

by adding [] to the end of your form field names, PHP will automatically convert these variables into arrays.

SQL Server - boolean literal?

Most databases will accept this:

select * from SomeTable where true

However some databases (eg SQL Server, Oracle) do not have a boolean type. In these cases you may use:

select * from SomeTable where 1=1

BTW, if building up an sql where clause by hand, this is the basis for simplifying your code because you can avoid having to know if the condition you're about to add to a where clause is the first one (which should be preceded by "WHERE"), or a subsequent one (which should be preceded by "AND"). By always starting with "WHERE 1=1", all conditions (if any) added to the where clause are preceded by "AND".

How to run a PowerShell script from a batch file

Posted it also here: How to run powershell command in batch file

Following this thread:
https://community.idera.com/database-tools/powershell/powertips/b/tips/posts/converting-powershell-to-batch


you can convert any PowerShell script into a batch file easily using this PowerShell function:

function Convert-PowerShellToBatch
{
    param
    (
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [string]
        [Alias("FullName")]
        $Path
    )
 
    process
    {
        $encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content -Path $Path -Raw -Encoding UTF8)))
        $newPath = [Io.Path]::ChangeExtension($Path, ".bat")
        "@echo off`npowershell.exe -NoExit -encodedCommand $encoded" | Set-Content -Path $newPath -Encoding Ascii
    }
}


To convert all PowerShell scripts inside a directory, simply run the following command:

Get-ChildItem -Path <DIR-PATH> -Filter *.ps1 |
  Convert-PowerShellToBatch

Where is the path to the desired folder. For instance:

Get-ChildItem -Path "C:\path\to\powershell\scripts" -Filter *.ps1 |
  Convert-PowerShellToBatch


To convert a single PowerShell script, simply run this:

Get-ChildItem -Path <FILE-PATH> |
  Convert-PowerShellToBatch

Where is the path to the desired file.

The converted files are located in the source directory. i.e., <FILE-PATH> or <DIR-PATH>.

Putting it all together:
create a .ps1 file (PowerShell script) with the following code in it:

function Convert-PowerShellToBatch
{
    param
    (
        [Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
        [string]
        [Alias("FullName")]
        $Path
    )
 
    process
    {
        $encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content -Path $Path -Raw -Encoding UTF8)))
        $newPath = [Io.Path]::ChangeExtension($Path, ".bat")
        "@echo off`npowershell.exe -NoExit -encodedCommand $encoded" | Set-Content -Path $newPath -Encoding Ascii
    }
}

# change <DIR> to the path of the folder in which the desired powershell scripts are.
# the converted files will be created in the destination path location (in <DIR>).
Get-ChildItem -Path <DIR> -Filter *.ps1 |
  Convert-PowerShellToBatch


And don't forget, if you wanna convert only one file instead of many, you can replace the following

Get-ChildItem -Path <DIR> -Filter *.ps1 |
  Convert-PowerShellToBatch

with this:

Get-ChildItem -Path <FILE-PATH> |
  Convert-PowerShellToBatch

as I explained before.

Open a new tab in the background?

THX for this question! Works good for me on all popular browsers:

function openNewBackgroundTab(){
    var a = document.createElement("a");
    a.href = window.location.pathname;
    var evt = document.createEvent("MouseEvents");
    //the tenth parameter of initMouseEvent sets ctrl key
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                                true, false, false, false, 0, null);
    a.dispatchEvent(evt);
}

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
    var url = window.location.pathname;
    var win = window.open(url, '_blank');
} else {
    openNewBackgroundTab();
}

How to add a title to a html select tag

The first option's text will always display as default title.

   <select>
        <option value ="">What is the name of your city?</option>
        <option value ="sydney">Sydney</option>
        <option value ="melbourne">Melbourne</option>
        <option value ="cromwell">Cromwell</option>
        <option value ="queenstown">Queenstown</option>
   </select>

how to change attribute "hidden" in jquery

$(':checkbox').change(function(){
    $('#delete').removeAttr('hidden');
});

Note, thanks to tip by A.Wolff, you should use removeAttr instead of setting to false. When set to false, the element will still be hidden. Therefore, removing is more effective.

Store text file content line by line into array

JAVA 8 :

Files.lines(new File("/home/abdennour/path/to/file.txt").toPath()).collect(Collectors.toList());

How to set enum to null

I'm assuming c++ here. If you're using c#, the answer is probably the same, but the syntax will be a bit different. The enum is a set of int values. It's not an object, so you shouldn't be setting it to null. Setting something to null means you are pointing a pointer to an object to address zero. You can't really do that with an int. What you want to do with an int is to set it to a value you wouldn't normally have it at so that you can tel if it's a good value or not. So, set your colour to -1

Color color = -1;

Or, you can start your enum at 1 and set it to zero. If you set the colour to zero as it is right now, you will be setting it to "red" because red is zero in your enum.

So,

enum Color {
red =1
blue,
green
}
//red is 1, blue is 2, green is 3
Color mycolour = 0;

Getting Serial Port Information

None of the answers here satisfies my needs.

The answer from Muno is wrong because it lists ONLY the USB ports.

The answer from code4life is wrong because it lists all EXCEPT the USB ports. (Nevertheless it has 44 up-votes!!!)

I have an EPSON printer simulation port on my computer which is not listed by any of the answers here. So I had to write my own solution. Additionally I want to display more information than just the caption string. I also need to separate the port name from the description.

My code has been tested on Windows XP, Windows 7 and Windows 10.

The Port Name (like "COM1") must be read from the registry because WMI does not give this information for all COM ports (EPSON).

If you use my code you do not need SerialPort.GetPortNames() anymore. My function returns the same ports, but with additional details. Why did Microsoft not implement such a function into the framework??

using System.Management;
using Microsoft.Win32;

using (ManagementClass i_Entity = new ManagementClass("Win32_PnPEntity"))
{
    foreach (ManagementObject i_Inst in i_Entity.GetInstances())
    {
        Object o_Guid = i_Inst.GetPropertyValue("ClassGuid");
        if (o_Guid == null || o_Guid.ToString().ToUpper() != "{4D36E978-E325-11CE-BFC1-08002BE10318}")
            continue; // Skip all devices except device class "PORTS"

        String s_Caption  = i_Inst.GetPropertyValue("Caption")     .ToString();
        String s_Manufact = i_Inst.GetPropertyValue("Manufacturer").ToString();
        String s_DeviceID = i_Inst.GetPropertyValue("PnpDeviceID") .ToString();
        String s_RegPath  = "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\" + s_DeviceID + "\\Device Parameters";
        String s_PortName = Registry.GetValue(s_RegPath, "PortName", "").ToString();

        int s32_Pos = s_Caption.IndexOf(" (COM");
        if (s32_Pos > 0) // remove COM port from description
            s_Caption = s_Caption.Substring(0, s32_Pos);

        Console.WriteLine("Port Name:    " + s_PortName);
        Console.WriteLine("Description:  " + s_Caption);
        Console.WriteLine("Manufacturer: " + s_Manufact);
        Console.WriteLine("Device ID:    " + s_DeviceID);
        Console.WriteLine("-----------------------------------");
    }
}

I tested the code with a lot of COM ports. This is the Console output:

Port Name:    COM29
Description:  CDC Interface (Virtual COM Port) for USB Debug
Manufacturer: GHI Electronics, LLC
Device ID:    USB\VID_1B9F&PID_F003&MI_01\6&3009671A&0&0001
-----------------------------------
Port Name:    COM28
Description:  Teensy USB Serial
Manufacturer: PJRC.COM, LLC.
Device ID:    USB\VID_16C0&PID_0483\1256310
-----------------------------------
Port Name:    COM25
Description:  USB-SERIAL CH340
Manufacturer: wch.cn
Device ID:    USB\VID_1A86&PID_7523\5&2499667D&0&3
-----------------------------------
Port Name:    COM26
Description:  Prolific USB-to-Serial Comm Port
Manufacturer: Prolific
Device ID:    USB\VID_067B&PID_2303\5&2499667D&0&4
-----------------------------------
Port Name:    COM1
Description:  Comunications Port
Manufacturer: (Standard port types)
Device ID:    ACPI\PNP0501\1
-----------------------------------
Port Name:    COM999
Description:  EPSON TM Virtual Port Driver
Manufacturer: EPSON
Device ID:    ROOT\PORTS\0000
-----------------------------------
Port Name:    COM20
Description:  EPSON COM Emulation USB Port
Manufacturer: EPSON
Device ID:    ROOT\PORTS\0001
-----------------------------------
Port Name:    COM8
Description:  Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID:    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&000F\8&3ADBDF90&0&001DA568988B_C00000000
-----------------------------------
Port Name:    COM9
Description:  Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID:    BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\8&3ADBDF90&0&000000000000_00000002
-----------------------------------
Port Name:    COM30
Description:  Arduino Uno
Manufacturer: Arduino LLC (www.arduino.cc)
Device ID:    USB\VID_2341&PID_0001\74132343530351F03132
-----------------------------------

COM1 is a COM port on the mainboard.

COM 8 and 9 are Buetooth COM ports.

COM 25 and 26 are USB to RS232 adapters.

COM 28 and 29 and 30 are Arduino-like boards.

COM 20 and 999 are EPSON ports.

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

Freely convert between List<T> and IEnumerable<T>

Aside: Note that the standard LINQ operators (as per the earlier example) don't change the existing list - list.OrderBy(...).ToList() will create a new list based on the re-ordered sequence. It is pretty easy, however, to create an extension method that allows you to use lambdas with List<T>.Sort:

static void Sort<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
}

static void SortDescending<TSource, TValue>(this List<TSource> list,
    Func<TSource, TValue> selector)
{
    var comparer = Comparer<TValue>.Default;
    list.Sort((x,y) => comparer.Compare(selector(y), selector(x)));
}

Then you can use:

list.Sort(x=>x.SomeProp); // etc

This updates the existing list in the same way that List<T>.Sort usually does.

Using :focus to style outer div?

Some people, like me, will benefit from using the :focus-within pseudo-class.

Using it will apply the css you want to a div, for instance.

You can read more here https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within

How to use a RELATIVE path with AuthUserFile in htaccess?

If you are trying to use XAMPP with Windows and want to use an .htaccess file on a live server and also develop on a XAMPP development machine the following works great!


1) After a fresh install of XAMPP make sure that Apache is installed as a service.

  • This is done by opening up the XAMPP Control Panel and clicking on the little red "X" to the left of the Apache module.
  • It will then ask you if you want to install Apache as a service.
  • Then it should turn to a green check mark.

2) When Apache is installed as a service add a new environment variable as a flag.

  • First stop the Apache service from the XAMPP Control Panel.
  • Next open a command prompt. (You know the little black window the simulates DOS)
  • Type "C:\Program Files (x86)\xampp\apache\bin\httpd.exe" -D "DEV" -k config.
  • This will append a new DEV flag to the environment variables that you can use later.

3) Start Apache

  • Open back up the XAMPP Control Panel and start the Apache service.

4) Create your .htaccess file with the following information...

<IfDefine DEV>
  AuthType Basic
  AuthName "Authorized access only!"
  AuthUserFile "/sandbox/web/scripts/.htpasswd"
  require valid-user
</IfDefine>

<IfDefine !DEV>
  AuthType Basic
  AuthName "Authorized access only!"
  AuthUserFile "/home/arvo/public_html/scripts/.htpasswd"
  require valid-user
</IfDefine>

To explain the above script here are a few notes...

  • My AuthUserFile is based on my setup and personal preferences.
  • I have a local test dev box that has my webpage located at c:\sandbox\web\. Inside that folder I have a folder called scripts that contains the password file .htpasswd.
  • The first entry IfDefine DEV is used for that instance. If DEV is set (which is what we did above, only on the dev machine of coarse) then it will use that entry.
  • And in turn if using the live server IfDefine !DEV will be used.

5) Create your password file (in this case named .htpasswd) with the following information...

user:$apr1$EPuSBcwO$/KtqDUttQMNUa5lGXSOzk.

A few things to note...

CSS disable hover effect

You can achieve this using :not selector:

HTML code:

<a class="button">Click me</a>
<a class="button disable">Click me</a>

CSS code (using scss):

.button {
  background-color: red;
  &:not(.disable):hover {
    /* apply hover effect here */
  }   
}

In this way you apply the hover effect style when a specified class (.disable) is not applied.

C++ template constructor

You could do this:

class C 
{
public:
    template <typename T> C(T*);
};
template <typename T> T* UseType() 
{
    static_cast<T*>(nullptr);
}

Then to create an object of type C using int as the template parameter to the constructor:

C obj(UseType<int>());

Since you can't pass template parameters to a constructor, this solution essentially converts the template parameter to a regular parameter. Using the UseType<T>() function when calling the constructor makes it clear to someone looking at the code that the purpose of that parameter is to tell the constructor what type to use.

One use case for this would be if the constructor creates a derived class object and assigns it to a member variable that is a base class pointer. (The constructor needs to know which derived class to use, but the class itself doesn't need to be templated since the same base class pointer type is always used.)

How to change the size of the radio button using CSS?

This works fine for me in all browsers:

(inline style for simplicity...)

<label style="font-size:16px;">
    <input style="height:1em; width:1em;" type="radio">
    <span>Button One</span>
</label>

The size of both the radio button and text will change with the label's font-size.

How can I use console logging in Internet Explorer?

Since version 8, Internet Explorer has its own console, like other browsers. However, if the console is not enabled, the console object does not exist and a call to console.log will throw an error.

Another option is to use log4javascript (full disclosure: written by me), which has its own logging console that works in all mainstream browsers, including IE >= 5, plus a wrapper for the browser's own console that avoids the issue of an undefined console.

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I recently get across the same issue. I was using IntelliJx64 with Tomcat7.0.32 with jdk.8.0.102. There was no issue then. I was able to directly access my deployment localhost:[port] without adding [mywebapp] or /ROOT.

When I tried to migrate to eclipse neon, I came across the same bug that is discussed when I tried to set the path as empty string. When I enforced execution environment to Java7 and set modules to empty it did not solve toe issue. However, when I changed my tomcat installation to 7.072 and manually changed context path configuration to path="" the problem was solved in eclipse. (You can manipulate the path via double click server and switching to module tab too.)

My wonder is how come IntelliJ was not giving any issues with the same bug which was supposed to be related to tomcat installation version?

There also seems to be a relation with the IDE in use.

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

How to redirect 'print' output to a file using python?

Something to extend print function for loops

x = 0
while x <=5:
    x = x + 1
    with open('outputEis.txt', 'a') as f:
        print(x, file=f)
    f.close()

How to check if a user is logged in (how to properly use user.is_authenticated)?

Following block should work:

    {% if user.is_authenticated %}
        <p>Welcome {{ user.username }} !!!</p>       
    {% endif %}

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64 macro and other printf issues altogether:

#include <fmt/core.h>

int main() {
  uint64_t ui64 = 90;
  fmt::print("test uint64_t : {}\n", ui64);
}

The formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

SSH to Vagrant box in Windows?

Windows 7 ( not tested on other versions )

  1. Right Click on "My Computer" and click properties
  2. Click Advanced System Settings
  3. Click Environment Variables
  4. In second box under "System Variables" scroll down and click on variable "Path" and click EDIT
  5. Make sure the path is included in the Variable Value by appending (a semicolon if it's not there and) C:\Program Files (x86)\Git\bin; ( or whatever is the path to your ssh.exe )
  6. OK > OK > OK and RESTART WINDOWS
  7. You'll have to run vagrant up but after that vagrant ssh should work permanently

More Info which might help with other versions ... http://www.computerhope.com/issues/ch000549.htm

Creating a Jenkins environment variable using Groovy

My environment was prior tooling such as Jenkins and was running with batch files (I know, I'm old). So those batch files (and their sub-batch files) are using environment variables. This was my piece of groovy script which injects environment variables. The names and parameters used are dummy ones.

// The process/batch which uses environment variables
def buildLabel = "SomeVersionNr"
def script = "startBuild.bat"
def processBuilder = new ProcessBuilder(script, buildLabel)

//Inject our environment variables
Map<String, String> env = processBuilder.environment()
env.put("ProjectRoot", "someLocation")
env.put("SomeVar", "Some")

Process p = processBuilder.start()
p.waitFor()

Of course if you set Jenkins up from scratch you would probably do it differently and share the variables in another way, or pass parameters around but this might come handy.

Get index of element as child relative to parent

Take a look at this example.

$("#wizard li").click(function () {
    alert($(this).index()); // alert index of li relative to ul parent
});

ERROR 1064 (42000): You have an error in your SQL syntax;

Use varchar instead of VAR_CHAR and omit the comma in the last line i.e.phone INT NOT NULL );. The last line during creating table is kept "comma free". Ex:- CREATE TABLE COMPUTER ( Model varchar(50) ); Here, since we have only one column ,that's why there is no comma used during entire code.

How to check if current thread is not main thread

Summarizing the solutions, I think that's the best one:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M 
    ? Looper.getMainLooper().isCurrentThread()
    : Thread.currentThread() == Looper.getMainLooper().getThread();

And, if you wish to run something on the UI thread, you can use this:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
       //this runs on the UI thread
    }
});

Git error on git pull (unable to update local ref)

This happened to me on OSX where I use a case insensitive file system. Somehow another developer pushed a branch with the same name but different case: My-Branch vs my-branch.

I already had My-Branch checked out and got the error "unable to update local ref" when I did a pull probably because the file system thinks My-Branch == my-branch.

Since we use Github I could solve the problem by deleting one of the branches via Github's GUI.

How to open new browser window on button click event?

You can use some code like this, you can adjust a height and width as per your need

    protected void button_Click(object sender, EventArgs e)
    {
        // open a pop up window at the center of the page.
        ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
    }

Angular HTML binding

Short answer was provided here already: use <div [innerHTML]="yourHtml"> binding.

However the rest of the advices mentioned here might be misleading. Angular has a built-in sanitizing mechanism when you bind to properties like that. Since Angular is not a dedicated sanitizing library, it is overzealous towards suspicious content to not take any risks. For example, it sanitizes all SVG content into empty string.

You might hear advices to "sanitize" your content by using DomSanitizer to mark content as safe with bypassSecurityTrustXXX methods. There are also suggestions to use pipe to do that and that pipe is often called safeHtml.

All of this is misleading because it actually bypasses sanitizing, not sanitizing your content. This could be a security concern because if you ever do this on user provided content or on anything that you are not sure about — you open yourself up for a malicious code attacks.

If Angular removes something that you need by its built-in sanitization — what you can do instead of disabling it is delegate actual sanitization to a dedicated library that is good at that task. For example — DOMPurify.

I've made a wrapper library for it so it could be easily used with Angular: https://github.com/TinkoffCreditSystems/ng-dompurify

It also has a pipe to declaratively sanitize HTML:

<div [innerHtml]="value | dompurify"></div>

The difference to pipes suggested here is that it actually does do the sanitization through DOMPurify and therefore work for SVG.

One thing to keep in mind is DOMPurify is great for sanitizing HTML/SVG, but not CSS. So you can provider Angular's CSS sanitizer to handle CSS:

import {NgModule, ?_sanitizeStyle} from '@angular/core';
import {SANITIZE_STYLE} from '@tinkoff/ng-dompurify';

@NgModule({
    // ...
    providers: [
        {
            provide: SANITIZE_STYLE,
            useValue: ?_sanitizeStyle,
        },
    ],
    // ...
})
export class AppModule {}

It's internal — hense ? prefix, but this is how Angular team use it across their own packages as well anyway. That library also works for Angular Universal and server side renedring environment.

How do I delete an exported environment variable?

As mentioned in the above answers, unset GNUPLOT_DRIVER_DIR should work if you have used export to set the variable. If you have set it permanently in ~/.bashrc or ~/.zshrc then simply removing it from there will work.

How do you change the datatype of a column in SQL Server?

The syntax to modify a column in an existing table in SQL Server (Transact-SQL) is:

ALTER TABLE table_name
    ALTER COLUMN column_name column_type;

For example:

ALTER TABLE employees
    ALTER COLUMN last_name VARCHAR(75) NOT NULL;

This SQL Server ALTER TABLE example will modify the column called last_name to be a data type of VARCHAR(75) and force the column to not allow null values.

see here

I can't find my git.exe file in my Github folder

The path for the latest version of Git is changed, In my laptop, I found it in

C:\Users\Anum Sheraz\AppData\Local\Programs\Git\bin\git.exe

This resolved my issue of path. Hope that helps to someone :)

How to export a CSV to Excel using Powershell

Why would you bother? Load your CSV into Excel like this:

$csv = Join-Path $env:TEMP "process.csv"
$xls = Join-Path $env:TEMP "process.xlsx"

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.OpenText($csv)

$wb.SaveAs($xls, 51)

You just need to make sure that the CSV export uses the delimiter defined in your regional settings. Override with -Delimiter if need be.


Edit: A more general solution that should preserve the values from the CSV as plain text. Code for iterating over the CSV columns taken from here.

$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.Add()
$ws = $wb.Sheets.Item(1)

$ws.Cells.NumberFormat = "@"

$i = 1
Import-Csv $csv | ForEach-Object {
  $j = 1
  foreach ($prop in $_.PSObject.Properties) {
    if ($i -eq 1) {
      $ws.Cells.Item($i, $j++).Value = $prop.Name
    } else {
      $ws.Cells.Item($i, $j++).Value = $prop.Value
    }
  }
  $i++
}

$wb.SaveAs($xls, 51)
$wb.Close()

$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)

Obviously this second approach won't perform too well, because it's processing each cell individually.

Tree implementation in Java (root, parents and children)

Accepted answer throws a java.lang.StackOverflowError when calling the setParent or addChild methods.

Here's a slightly simpler implementation without those bugs:

public class MyTreeNode<T>{
    private T data = null;
    private List<MyTreeNode> children = new ArrayList<>();
    private MyTreeNode parent = null;

    public MyTreeNode(T data) {
        this.data = data;
    }

    public void addChild(MyTreeNode child) {
        child.setParent(this);
        this.children.add(child);
    }

    public void addChild(T data) {
        MyTreeNode<T> newChild = new MyTreeNode<>(data);
        this.addChild(newChild);
    }

    public void addChildren(List<MyTreeNode> children) {
        for(MyTreeNode t : children) {
            t.setParent(this);
        }
        this.children.addAll(children);
    }

    public List<MyTreeNode> getChildren() {
        return children;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    private void setParent(MyTreeNode parent) {
        this.parent = parent;
    }

    public MyTreeNode getParent() {
        return parent;
    }
}

Some examples:

MyTreeNode<String> root = new MyTreeNode<>("Root");

MyTreeNode<String> child1 = new MyTreeNode<>("Child1");
child1.addChild("Grandchild1");
child1.addChild("Grandchild2");

MyTreeNode<String> child2 = new MyTreeNode<>("Child2");
child2.addChild("Grandchild3");

root.addChild(child1);
root.addChild(child2);
root.addChild("Child3");

root.addChildren(Arrays.asList(
        new MyTreeNode<>("Child4"),
        new MyTreeNode<>("Child5"),
        new MyTreeNode<>("Child6")
));

for(MyTreeNode node : root.getChildren()) {
    System.out.println(node.getData());
}

How to get whole and decimal part of a number?

This code will split it up for you:

list($whole, $decimal) = explode('.', $your_number);

where $whole is the whole number and $decimal will have the digits after the decimal point.

QED symbol in latex

I think you are looking for this:

\newcommand*{\QEDA}{\hfill\ensuremath{\blacksquare}}

Usage:

\begin{example}
  blah blah blah \QEDA
\end{example}

How to get HttpClient returning status code and response body?

Don't provide the handler to execute.

Get the HttpResponse object, use the handler to get the body and get the status code from it directly

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    final HttpGet httpGet = new HttpGet(GET_URL);

    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        System.out.println("Response body: " + responseBody);
    }
}

For quick single calls, the fluent API is useful:

Response response = Request.Get(uri)
        .connectTimeout(MILLIS_ONE_SECOND)
        .socketTimeout(MILLIS_ONE_SECOND)
        .execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();

For older versions of java or httpcomponents, the code might look different.

Is there a way to represent a directory tree in a Github README.md?

I wrote a small script that does the trick:

#!/bin/bash

#File: tree-md

tree=$(tree -tf --noreport -I '*~' --charset ascii $1 |
       sed -e 's/| \+/  /g' -e 's/[|`]-\+/ */g' -e 's:\(* \)\(\(.*/\)\([^/]\+\)\):\1[\4](\2):g')

printf "# Project tree\n\n${tree}"

Example:

Original tree command:

$ tree
.
+-- dir1
¦   +-- file11.ext
¦   +-- file12.ext
+-- dir2
¦   +-- file21.ext
¦   +-- file22.ext
¦   +-- file23.ext
+-- dir3
+-- file_in_root.ext
+-- README.md

3 directories, 7 files

Markdown tree command:

$ ./tree-md .
# Project tree

.
 * [tree-md](./tree-md)
 * [dir2](./dir2)
   * [file21.ext](./dir2/file21.ext)
   * [file22.ext](./dir2/file22.ext)
   * [file23.ext](./dir2/file23.ext)
 * [dir1](./dir1)
   * [file11.ext](./dir1/file11.ext)
   * [file12.ext](./dir1/file12.ext)
 * [file_in_root.ext](./file_in_root.ext)
 * [README.md](./README.md)
 * [dir3](./dir3)

Rendered result:

(Links are not visible in Stackoverflow...)

Project tree
  • tree-md
  • dir2
    • file21.ext
    • file22.ext
    • file23.ext
  • dir1
    • file11.ext
    • file12.ext
  • file_in_root.ext
  • README.md
  • dir3

How to Configure SSL for Amazon S3 bucket

I found you can do this easily via the Cloud Flare service.

Set up a bucket, enable webhosting on the bucket and point the desired CNAME to that endpoint via Cloudflare... and pay for the service of course... but $5-$20 VS $600 is much easier to stomach.

Full detail here: https://www.engaging.io/easy-way-to-configure-ssl-for-amazon-s3-bucket-via-cloudflare/

Are there best practices for (Java) package organization?

Are there best practices with regards to the organisation of packages in Java and what goes in them?

Not really no. There are lots of ideas, and lots opinions, but real "best practice" is to use your common sense!

(Please read No best Practices for a perspective on "best practices" and the people who promote them.)

However, there is one principal that probably has broad acceptance. Your package structure should reflect your application's (informal) module structure, and you should aim to minimize (or ideally entirely avoid) any cyclic dependencies between modules.

(Cyclic dependencies between classes in a package / module are just fine, but inter-package cycles tend to make it hard understand your application's architecture, and can be a barrier to code reuse. In particular, if you use Maven you will find that cyclic inter-package / inter-module dependencies mean that the whole interconnected mess has to be one Maven artifact.)

I should also add that there is one widely accepted best practice for package names. And that is that your package names should start with your organization's domain name in reverse order. If you follow this rule, you reduce the likelihood of problems caused by your (full) class names clashing with other peoples'.

Will using 'var' affect performance?

If the compiler can do automatic type inferencing, then there wont be any issue with performance. Both of these will generate same code

var    x = new ClassA();
ClassA x = new ClassA();

however, if you are constructing the type dynamically (LINQ ...) then var is your only question and there is other mechanism to compare to in order to say what is the penalty.

Select values from XML field in SQL Server 2008

If you are able to wrap your XML in a root element - say then the following is your solution:

DECLARE @PersonsXml XML = '<persons><person><firstName>Jon</firstName><lastName>Johnson</lastName></person>
<person><firstName>Kathy</firstName><lastName>Carter</lastName></person>
<person><firstName>Bob</firstName><lastName>Burns</lastName></person></persons>'

SELECT  b.value('(./firstName/text())[1]','nvarchar(max)') as FirstName, b.value('(./lastName/text())[1]','nvarchar(max)') as LastName
FROM @PersonsXml.nodes('/persons/person') AS a(b)

enter image description here

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

You probably want to use something like jQuery, which makes JS programming easier.

Something like:

$(document).ready(function(){
   // Your code here
});

Would seem to do what you are after.

Operator overloading on class templates

// In MyClass.h
MyClass<T>& operator+=(const MyClass<T>& classObj);


// In MyClass.cpp
template <class T>
MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) {
  // ...
  return *this;
}

This is invalid for templates. The full source code of the operator must be in all translation units that it is used in. This typically means that the code is inline in the header.

Edit: Technically, according to the Standard, it is possible to export templates, however very few compilers support it. In addition, you CAN also do the above if the template is explicitly instantiated in MyClass.cpp for all types that are T- but in reality, that normally defies the point of a template.

More edit: I read through your code, and it needs some work, for example overloading operator[]. In addition, typically, I would make the dimensions part of the template parameters, allowing for the failure of + or += to be caught at compile-time, and allowing the type to be meaningfully stack allocated. Your exception class also needs to derive from std::exception. However, none of those involve compile-time errors, they're just not great code.

matrix multiplication algorithm time complexity

In matrix multiplication there are 3 for loop, we are using since execution of each for loop requires time complexity O(n). So for three loops it becomes O(n^3)

Remove trailing comma from comma-separated string

Use Guava to normalize all your commas. Split the string up around the commas, throw out the empties, and connect it all back together. Two calls. No loops. Works the first time:

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;

public class TestClass {

    Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();
    Joiner joiner = Joiner.on(',').skipNulls();

    public String cleanUpCommas(String string) {
        return joiner.join(splitter.split(string));
    }

}



public class TestMain {

    public static void main(String[] args) {
        TestClass testClass = new TestClass();

        System.out.println(testClass.cleanUpCommas("a,b,c,d,e"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,,, ,c,d,  ,,e,,,,,"));
        System.out.println(testClass.cleanUpCommas("a,b,c,d,  e,,,,,"));
        System.out.println(testClass.cleanUpCommas(",,, ,,,,a,b,c,d,  e,,,,,"));
    }

}

Output:

a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e

Personally, I hate futzing around with counting limits of substrings and all that nonsense.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

I don't know about javax.media.j3d, so I might be mistaken, but you usually want to investigate whether there is a memory leak. Well, as others note, if it was 64MB and you are doing something with 3d, maybe it's obviously too small...

But if I were you, I'll set up a profiler or visualvm, and let your application run for extended time (days, weeks...). Then look at the heap allocation history, and make sure it's not a memory leak.

If you use a profiler, like JProfiler or the one that comes with NetBeans IDE etc., you can see what object is being accumulating, and then track down what's going on.. Well, almost always something is incorrectly not removed from a collection...

how to get vlc logs?

Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...

Passing by reference in C

What you are doing is pass by value not pass by reference. Because you are sending the value of a variable 'p' to the function 'f' (in main as f(p);)

The same program in C with pass by reference will look like,(!!!this program gives 2 errors as pass by reference is not supported in C)

#include <stdio.h>

void f(int &j) {    //j is reference variable to i same as int &j = i
  j++;
}

int main() {
  int i = 20;
  f(i);
  printf("i = %d\n", i);

  return 0;
}

Output:-

3:12: error: expected ';', ',' or ')' before '&' token
             void f(int &j);
                        ^
9:3:  warning: implicit declaration of function 'f'
               f(a);
               ^

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

I live in uk was keep on trying for 'us-west-2'region. So redirected to 'eu-west-2'. The correct region for S3 is 'eu-west-2'

Changing iframe src with Javascript

Here is my updated code. It works fine and it can help you.

<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
  <title>Untitled 1</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
  <script type="text/javascript">
  function go(loc) {
    document.getElementById('calendar').src = loc;
  }
  </script>
</head>

<body>
  <iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>

  <form method="post">
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week
    <input name="calendarSelection" type="radio" onclick="go('http://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month
  </form>

</body>

</html>

Clear data in MySQL table with PHP?

TRUNCATE TABLE table;

is the SQL command. In PHP, you'd use:

mysql_query('TRUNCATE TABLE table;');

Typescript: How to extend two classes?

A very hacky solution would be to loop through the class you want to inherit from adding the functions one by one to the new parent class

class ChildA {
    public static x = 5
}

class ChildB {
    public static y = 6
}

class Parent {}

for (const property in ChildA) {
    Parent[property] = ChildA[property]
}
for (const property in ChildB) {
    Parent[property] = ChildB[property]
}


Parent.x
// 5
Parent.y
// 6

All properties of ChildA and ChildB can now be accessed from the Parent class, however they will not be recognised meaning that you will receive warnings such as Property 'x' does not exist on 'typeof Parent'

How to center an image horizontally and align it to the bottom of the container?

have you tried:

.image_block{
text-align: center;
vertical-align: bottom;
}

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

If you are using the JPA annotations to create the entities and then make sure that the table name is mapped along with @Table annotation instead of @Entity.

Incorrectly mapped :

@Entity(name="DB_TABLE_NAME")
public class DbTableName implements Serializable {
   ....
   ....
}

Correctly mapped entity :

@Entity
@Table(name="DB_TABLE_NAME")
public class DbTableName implements Serializable {
   ....
   ....
}

Post-increment and Pre-increment concept?

The pre increment is before increment value ++ e.g.:

(++v) or 1 + v

The post increment is after increment the value ++ e.g.:

(rmv++) or rmv + 1

Program:

int rmv = 10, vivek = 10;
cout << "rmv++ = " << rmv++ << endl; // the value is 10
cout << "++vivek = " << ++vivek; // the value is 11

..The underlying connection was closed: An unexpected error occurred on a receive

None of the solutions out there worked for me. What I eventually discovered was the following combination:

  • Client system: Windows XP Pro SP3
  • Client system has .NET Framework 2 SP1, 3, 3.5 installed
  • Software targeting .NET 2 using classic web services (.asmx)
  • Server: IIS6
  • Web site "Secure Communications" set to:
    • Require Secure Channel
    • Accept client certificates

enter image description here

Apparently, it was this last option that was causing the issue. I discovered this by trying to open the web service URL directly in Internet Explorer. It just hung indefinitely trying to load the page. Disabling "Accept client certificates" allowed the page to load normally. I am not sure if it was a problem with this specific system (maybe a glitched client certificate?) Since I wasn't using client certificates this option worked for me.

How to install and use "make" in Windows?

Another alternative is if you already installed minGW and added the bin folder the to Path environment variable, you can use "mingw32-make" instead of "make".

You can also create a symlink from "make" to "mingw32-make", or copying and changing the name of the file. I would not recommend the options before, they will work until you do changes on the minGW.

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Convert string with commas to array

How to Convert Comma Separated String into an Array in JavaScript?

var string = 'hello, world, test, test2, rummy, words';
var arr = string.split(', '); // split string on comma space
console.log( arr );
 
//Output
["hello", "world", "test", "test2", "rummy", "words"]

For More Examples of convert string to array in javascript using the below ways:

  1. Split() – No Separator:

  2. Split() – Empty String Separator:

  3. Split() – Separator at Beginning/End:

  4. Regular Expression Separator:

  5. Capturing Parentheses:

  6. Split() with Limit Argument

    check out this link ==> https://www.tutsmake.com/javascript-convert-string-to-array-javascript/

Syntax of for-loop in SQL Server

For loop is not officially supported yet by SQL server. Already there is answer on achieving FOR Loop's different ways. I am detailing answer on ways to achieve different types of loops in SQL server.

FOR Loop

DECLARE @cnt INT = 0;

WHILE @cnt < 10
BEGIN
   PRINT 'Inside FOR LOOP';
   SET @cnt = @cnt + 1;
END;

PRINT 'Done FOR LOOP';

If you know, you need to complete first iteration of loop anyway, then you can try DO..WHILE or REPEAT..UNTIL version of SQL server.

DO..WHILE Loop

DECLARE @X INT=1;

WAY:  --> Here the  DO statement

  PRINT @X;

  SET @X += 1;

IF @X<=10 GOTO WAY;

REPEAT..UNTIL Loop

DECLARE @X INT = 1;

WAY:  -- Here the REPEAT statement

  PRINT @X;

  SET @X += 1;

IFNOT(@X > 10) GOTO WAY;

Reference

difference between @size(max = value ) and @min(value) @max(value)

@Min and @Max are used for validating numeric fields which could be String(representing number), int, short, byte etc and their respective primitive wrappers.

@Size is used to check the length constraints on the fields.

As per documentation @Size supports String, Collection, Map and arrays while @Min and @Max supports primitives and their wrappers. See the documentation.

What does the clearfix class do in css?

When an element, such as a div is floated, its parent container no longer considers its height, i.e.

<div id="main">
  <div id="child" style="float:left;height:40px;"> Hi</div>
</div>

The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.

So the clearfix class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.

Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.

Can read more here

http://www.webtoolkit.info/css-clearfix.html

What is the difference between docker-compose ports vs expose

I totally agree with the answers before. I just like to mention that the difference between expose and ports is part of the security concept in docker. It goes hand in hand with the networking of docker. For example:

Imagine an application with a web front-end and a database back-end. The outside world needs access to the web front-end (perhaps on port 80), but only the back-end itself needs access to the database host and port. Using a user-defined bridge, only the web port needs to be opened, and the database application doesn’t need any ports open, since the web front-end can reach it over the user-defined bridge.

This is a common use case when setting up a network architecture in docker. So for example in a default bridge network, not ports are accessible from the outer world. Therefor you can open an ingresspoint with "ports". With using "expose" you define communication within the network. If you want to expose the default ports you don't need to define "expose" in your docker-compose file.

How to enter special characters like "&" in oracle database?

We can use another way as well for example to insert the value with special characters 'Java_22 & Oracle_14' into db we can use the following format..

'Java_22 '||'&'||' Oracle_14'

Though it consider as 3 different tokens we dont have any option as the handling of escape sequence provided in the oracle documentation is incorrect.

Firefox 'Cross-Origin Request Blocked' despite headers

The files are self explanatory. Make a file, call it anything. In my case jq2.php.

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
    // document is made ready so that the program starts when we load this page       
    $(document).ready(function(){

        // it tells that any key activity in the "subcat_search" filed will execute the query.
        $("#subcat_search").keyup(function(){

            // we assemble the get link for the direction to our engine "gs.php". 
            var link1 = "http://127.0.0.1/jqm/gs.php?needle=" + $("#subcat_search").val();

            $.ajax({
                url: link1,
                // ajax function is called sending the input string to "gs.php".
                success: function(result){
                    // result is stuffed in the label.
                    $("#search_val").html(result);
                }
            });
        })   

    });
</script>
</head>

<body>

<!-- the input field for search string -->
<input type="text" id="subcat_search">
<br>
<!-- the output field for stuffing the output. -->
<label id="search_val"></label>

</body>
</html>

Now we will include an engine, make a file, call it anything you like. In my case it is gs.php.

$head = "https://maps.googleapis.com/maps/api/place/textsearch/json?query="; //our head
$key = "your key here"; //your key
$hay = $_GET['needle'];

$hay = str_replace(" ", "+", $hay); //replacing the " " with "+" to design it as per the google's requirement 
$kill = $head . $hay . "&key=" . $key; //assembling the string in proper way . 
print file_get_contents($kill);

I have tried to keep the example as simple as possible. And because it executes the link on every keypress, the quota of your API will be consumed pretty fast.

Of course there is no end to things we can do, like putting the data into a table, sending to database and so on.

SQL: ... WHERE X IN (SELECT Y FROM ...)

SELECT Customers.* 
  FROM Customers 
 WHERE NOT EXISTS (
       SELECT *
         FROM SUBSCRIBERS AS s
         JOIN s.Cust_ID = Customers.Customer_ID) 

When using “NOT IN”, the query performs nested full table scans, whereas for “NOT EXISTS”, the query can use an index within the sub-query.