Programs & Examples On #Directcompute

Checking if output of a command contains a certain string in a shell script

A clean if/else conditional shell script:

if ./somecommand | grep -q 'some_string'; then
  echo "exists"
else
  echo "doesn't exist"
fi

C# Collection was modified; enumeration operation may not execute

The error tells you EXACTLY what the problem is (and running in the debugger or reading the stack trace will tell you exactly where the problem is):

C# Collection was modified; enumeration operation may not execute.

Your problem is the loop

foreach (KeyValuePair<int, int> kvp in rankings) {
    //
}

wherein you modify the collection rankings. In particular, the offensive line is

rankings[kvp.Key] = rankings[kvp.Key] + 4;

Before you enter the loop, add the following line:

var listOfRankingsToModify = new List<int>();

Replace the offending line with

listOfRankingsToModify.Add(kvp.Key);

and after you exit the loop

foreach(var key in listOfRankingsToModify) {
    rankings[key] = rankings[key] + 4;
}

That is, record what changes you need to make, and make them without iterating over the collection that you need to modify.

Can (domain name) subdomains have an underscore "_" in it?

I followed the link to RFC1034 and read most of it and was surprised to see this:

The labels must follow the rules for ARPANET host names. They must start with a letter, end with a letter or digit, and have as interior characters only letters, digits, and hyphen. There are also some restrictions on the length. Labels must be 63 characters or less.

For clarification, a domain names are made up of labels which are separated by dots ".". This spec must be outdated because it doesn't mention the use of underscores. I can understand the confusion if anybody stumbles over this spec without knowing it is obsolete. It is obsolete, isn't it?

I followed the link to RFC2181 and read some of it. Especially where it pertains to the issue of what is an authoritative, or canonical, name and the issue of what makes a valid DNS label.

As posted earlier it states there's only a length restriction then to sum it up it reads:

(about names and valid labels)

These are already adequately specified, however the specifications seem to be sometimes ignored. We seek to reinforce the existing specifications.

Kind of leaves me wondering if "a length only restriction" is "adequate". Are we going to start seeing domain names like @#$%!! soon? Isn't the internet screwed up enough?

push multiple elements to array

There are many answers recommend to use: Array.prototype.push(a, b). It's nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.

See What is the most efficient way to concatenate N arrays? for more details.

'Best' practice for restful POST response

Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.

There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API

It includes an answer to your question here: Updates & creation should return a resource representation

It says:

To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.

Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.

How should you diagnose the error SEHException - External component has thrown an exception

I got this error while running unit tests on inmemory caching I was setting up. It flooded the cache. After invalidating the cache and restarting the VM, it worked fine.

How do I exclude all instances of a transitive dependency when using Gradle?

I was using spring boot 1.5.10 and tries to exclude logback, the given solution above did not work well, I use configurations instead

configurations.all {
    exclude group: "org.springframework.boot", module:"spring-boot-starter-logging"
}

ImportError: No module named _ssl

I had exactly the same problem. I fixed it without rebuilding python, as follows:

  1. Find another server with the same architecture (i386 or x86_64) and the same python version (example: 2.7.5). Yes, this is the hard part. You can try installing python from sources into another server if you can't find any server with the same python version.

  2. In this another server, check if import ssl works. It should work.

  3. If it works, then try to find the _ssl lilbrary as follows:

    [root@myserver]# find / -iname _ssl.so
    /usr/local/python27/lib/python2.7/lib-dynload/_ssl.so
    
  4. Copy this file into the original server. Use the same destination folder: /usr/local/python27/lib/python2.7/lib-dynload/

  5. Double check owner and permissions:

    [root@myserver]# chown root:root _ssl.so
    [root@myserver]# chmod 755 _ssl.so
    
  6. Now you should be able to import ssl.

This worked for me in a CentOS 6.3 x86_64 environment with python 2.7.3. Also I had python 2.6.6 installed, but with ssl working fine.

typedef fixed length array

Arrays can't be passed as function parameters by value in C.

You can put the array in a struct:

typedef struct type24 {
    char byte[3];
} type24;

and then pass that by value, but of course then it's less convenient to use: x.byte[0] instead of x[0].

Your function type24_to_int32(char value[3]) actually passes by pointer, not by value. It's exactly equivalent to type24_to_int32(char *value), and the 3 is ignored.

If you're happy passing by pointer, you could stick with the array and do:

type24_to_int32(const type24 *value);

This will pass a pointer-to-array, not pointer-to-first-element, so you use it as:

(*value)[0]

I'm not sure that's really a gain, since if you accidentally write value[1] then something stupid happens.

Import pandas dataframe column as string not int

Just want to reiterate this will work in pandas >= 0.9.1:

In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]: 
                           ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

I'm creating an issue about detecting integer overflows also.

EDIT: See resolution here: https://github.com/pydata/pandas/issues/2247

Update as it helps others:

To have all columns as str, one can do this (from the comment):

pd.read_csv('sample.csv', dtype = str)

To have most or selective columns as str, one can do this:

# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str'  for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

How to export a mysql database using Command Prompt?

To export PROCEDUREs, FUNCTIONs & TRIGGERs too, add --routines parameter:

mysqldump -u YourUser -p YourDatabaseName --routines > wantedsqlfile.sql

replace String with another in java

Try this: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29

String a = "HelloBrother How are you!";
String r = a.replace("HelloBrother","Brother");

System.out.println(r);

This would print out "Brother How are you!"

Best way to track onchange as-you-type in input type="text"?

Below code works fine for me with Jquery 1.8.3

HTML : <input type="text" id="myId" />

Javascript/JQuery:

$("#myId").on('change keydown paste input', function(){
      doSomething();
});

fatal: early EOF fatal: index-pack failed

Network quality matters, try to switch to a different network. What helped me was changing my Internet connection from Virgin Media high speed land-based broadband to a hotspot on my phone.

Before that I tried the accepted answer to limit clone size, tried switching between 64 and 32 bit versions, tried disabling the git file cache, none of them helped.

Then I switched to the connection via my mobile, and the first step (git clone --depth 1 <repo_URI>) succeeded. Switched back to my broadband, but the next step (git fetch --unshallow) also failed. So I deleted the code cloned so far, switched to the mobile network tried again the default way (git clone <repo_URI>) and it succeeded without any issues.

Bash Shell Script - Check for a flag and grab its value

Here is a generalized simple command argument interface you can paste to the top of all your scripts.

#!/bin/bash

declare -A flags
declare -A booleans
args=()

while [ "$1" ];
do
    arg=$1
    if [ "${1:0:1}" == "-" ]
    then
      shift
      rev=$(echo "$arg" | rev)
      if [ -z "$1" ] || [ "${1:0:1}" == "-" ] || [ "${rev:0:1}" == ":" ]
      then
        bool=$(echo ${arg:1} | sed s/://g)
        booleans[$bool]=true
        echo \"$bool\" is boolean
      else
        value=$1
        flags[${arg:1}]=$value
        shift
        echo \"$arg\" is flag with value \"$value\"
      fi
    else
      args+=("$arg")
      shift
      echo \"$arg\" is an arg
    fi
done


echo -e "\n"
echo booleans: ${booleans[@]}
echo flags: ${flags[@]}
echo args: ${args[@]}

echo -e "\nBoolean types:\n\tPrecedes Flag(pf): ${booleans[pf]}\n\tFinal Arg(f): ${booleans[f]}\n\tColon Terminated(Ct): ${booleans[Ct]}\n\tNot Mentioned(nm): ${boolean[nm]}"
echo -e "\nFlag: myFlag => ${flags["myFlag"]}"
echo -e "\nArgs: one: ${args[0]}, two: ${args[1]}, three: ${args[2]}"

By running the command:

bashScript.sh firstArg -pf -myFlag "my flag value" secondArg -Ct: thirdArg -f

The output will be this:

"firstArg" is an arg
"pf" is boolean
"-myFlag" is flag with value "my flag value"
"secondArg" is an arg
"Ct" is boolean
"thirdArg" is an arg
"f" is boolean


booleans: true true true
flags: my flag value
args: firstArg secondArg thirdArg

Boolean types:
    Precedes Flag(pf): true
    Final Arg(f): true
    Colon Terminated(Ct): true
    Not Mentioned(nm): 

Flag: myFlag => my flag value

Args: one => firstArg, two => secondArg, three => thirdArg

Basically, the arguments are divided up into flags booleans and generic arguments. By doing it this way a user can put the flags and booleans anywhere as long as he/she keeps the generic arguments (if there are any) in the specified order.

Allowing me and now you to never deal with bash argument parsing again!

You can view an updated script here

This has been enormously useful over the last year. It can now simulate scope by prefixing the variables with a scope parameter.

Just call the script like

replace() (
  source $FUTIL_REL_DIR/commandParser.sh -scope ${FUNCNAME[0]} "$@"
  echo ${replaceFlags[f]}
  echo ${replaceBooleans[b]}
)

Doesn't look like I implemented argument scope, not sure why I guess I haven't needed it yet.

What's the difference between window.location and document.location in JavaScript?

document.location was originally a read-only property, although Gecko browsers allow you to assign to it as well. For cross-browser safety, use window.location instead.

Read more:

document.location

window.location

lvalue required as left operand of assignment

You need to compare, not assign:

if (strcmp("hello", "hello") == 0)
                             ^

Because you want to check if the result of strcmp("hello", "hello") equals to 0.

About the error:

lvalue required as left operand of assignment

lvalue means an assignable value (variable), and in assignment the left value to the = has to be lvalue (pretty clear).

Both function results and constants are not assignable (rvalues), so they are rvalues. so the order doesn't matter and if you forget to use == you will get this error. (edit:)I consider it a good practice in comparison to put the constant in the left side, so if you write = instead of ==, you will get a compilation error. for example:

int a = 5;
if (a = 0) // Always evaluated as false, no error.
{
    //...
}

vs.

int a = 5;
if (0 = a) // Generates compilation error, you cannot assign a to 0 (rvalue)
{
    //...
}

(see first answer to this question: https://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined)

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.

What are the advantages of Sublime Text over Notepad++ and vice-versa?

It's best if you judge on your own,

1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).

http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text

This Link is no more working so please watch this video for similar details Video

Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)

Some Variation: Some user find plugins useful for PHP coders on that

http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html

although, there are many plugins for Notepad Plus Plus ..

I am not sure of your requirements, nor I am promoter of either of these editors :)

So, judge on basis of your requirements, this should satisfy you query...

Yes we can add that both are evolving and changing fast..

Is recursion ever faster than looping?

Recursion may well be faster where the alternative is to explicitly manage a stack, like in the sorting or binary tree algorithms you mention.

I've had a case where rewriting a recursive algorithm in Java made it slower.

So the right approach is to first write it in the most natural way, only optimize if profiling shows it is critical, and then measure the supposed improvement.

How to temporarily disable a click handler in jQuery?

You can unbind your handler with .off, but there's a caveat; if you're doing this just prevent the handler from being triggered again while it's already running, you need to defer rebinding the handler.

For example, consider this code, which uses a 5-second hot sleep to simulate something synchronous and computationally expensive being done from within the handler (like heavy DOM manipulation, say):

<button id="foo">Click Me!</div>
<script>
    function waitForFiveSeconds() {
        var startTime = new Date();
        while (new Date() - startTime < 5000) {}
    }
    $('#foo').click(function handler() {
        // BAD CODE, DON'T COPY AND PASTE ME!
        $('#foo').off('click');
        console.log('Hello, World!');
        waitForFiveSeconds();
        $('#foo').click(handler);
    });
</script>

This won't work. As you can see if you try it out in this JSFiddle, if you click the button while the handler is already executing, the handler will execute a second time once the first execution finishes. What's more, at least in Chrome and Firefox, this would be true even if you didn't use jQuery and used addEventListener and removeEventListener to add and remove the handler instead. The browser executes the handler after the first click, unbinding and rebinding the handler, and then handles the second click and checks whether there's a click handler to execute.

To get around this, you need to defer rebinding of the handler using setTimeout, so that clicks that happen while the first handler is executing will be processed before you reattach the handler.

<button id="foo">Click Me!</div>
<script>
    function waitForFiveSeconds() {
        var startTime = new Date();
        while (new Date() - startTime < 5000) {}
    }
    $('#foo').click(function handler() {
        $('#foo').off('click');
        console.log('Hello, World!');
        waitForFiveSeconds();

        // Defer rebinding the handler, so that any clicks that happened while
        // it was unbound get processed first.
        setTimeout(function () {
            $('#foo').click(handler);
        }, 0);
    });
</script>

You can see this in action at this modified JSFiddle.

Naturally, this is unnecessary if what you're doing in your handler is already asynchronous, since then you're already yielding control to the browser and letting it flush all the click events before you rebind your handler. For instance, code like this will work fine without a setTimeout call:

<button id="foo">Save Stuff</div>
<script>
    $('#foo').click(function handler() {
        $('#foo').off('click');
        $.post( "/some_api/save_stuff", function() {
            $('#foo').click(handler);
        });
    });
</script>

How to programmatically round corners and set random background colors

Total programmatic approach to set rounded corners and add random background color to a View. I have not tested the code, but you get the idea.

 GradientDrawable shape =  new GradientDrawable();
 shape.setCornerRadius( 8 );

 // add some color
 // You can add your random color generator here
 // and set color
 if (i % 2 == 0) {
  shape.setColor(Color.RED);
 } else {
  shape.setColor(Color.BLUE);
 }

 // now find your view and add background to it
 View view = (LinearLayout) findViewById( R.id.my_view );
 view.setBackground(shape);

Here we are using gradient drawable so that we can make use of GradientDrawable#setCornerRadius because ShapeDrawable DOES NOT provide any such method.

How to resize an image with OpenCV2.0 and Python2.6

You could use the GetSize function to get those information, cv.GetSize(im) would return a tuple with the width and height of the image. You can also use im.depth and img.nChan to get some more information.

And to resize an image, I would use a slightly different process, with another image instead of a matrix. It is better to try to work with the same type of data:

size = cv.GetSize(im)
thumbnail = cv.CreateImage( ( size[0] / 10, size[1] / 10), im.depth, im.nChannels)
cv.Resize(im, thumbnail)

Hope this helps ;)

Julien

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

Pad left or right with string.format (not padleft or padright) with arbitrary string

You could encapsulate the string in a struct that implements IFormattable

public struct PaddedString : IFormattable
{
   private string value;
   public PaddedString(string value) { this.value = value; }

   public string ToString(string format, IFormatProvider formatProvider)
   { 
      //... use the format to pad value
   }

   public static explicit operator PaddedString(string value)
   {
     return new PaddedString(value);
   }
}

Then use this like that :

 string.Format("->{0:x20}<-", (PaddedString)"Hello");

result:

"->xxxxxxxxxxxxxxxHello<-"

Collections.emptyList() vs. new instance

Be carefully though. If you return Collections.emptyList() and then try to do some changes with it like add() or smth like that, u will have an UnsupportedOperationException() because Collections.emptyList() returns an immutable object.

Joining two lists together

If some item(s) exist in both lists you may use

var all = list1.Concat(list2).Concat(list3) ... Concat(listN).Distinct().ToList();

Get Windows version in a batch file

Here is another variant : some other solutions doesn't work with XP, this one does and was inspired by RLH solution.

This script will continue only if it detects the Windows version you want, in this example I want my script to run only in win 7, so to support other windows just change the GOTO :NOTTESTEDWIN to GOTO :TESTEDWIN

ver | findstr /i "5\.0\."        && (echo Windows 2000 & GOTO :NOTTESTEDWIN)
ver | findstr /i "5\.1\."        && (echo Windows XP 32bit & GOTO :NOTTESTEDWIN) 
ver | findstr /i "5\.2\."        && (echo Windows XP x64 / Windows Server 2003 & GOTO :NOTTESTEDWIN)
ver | findstr /i "6\.0\." > nul  && (echo Windows Vista / Server 2008 & GOTO :NOTTESTEDWIN)
ver | findstr /i "6\.1\." > nul  && (echo Windows 7 / Server 2008R2 & GOTO :TESTEDWIN)
ver | findstr /i "6\.2\." > nul  && (echo Windows 8 / Server 2012 & GOTO :NOTTESTEDWIN)
ver | findstr /i "6\.3\." > nul  && (echo Windows 8.1 / Server 2012R2 & GOTO :NOTTESTEDWIN)
ver | findstr /i "10\.0\." > nul && (echo Windows 10 / Server 2016 & GOTO :NOTTESTEDWIN)

echo "Could not detect Windows version! exiting..."
color 4F & pause & exit /B 1

:NOTTESTEDWIN
echo "This is not a supported Windows version"
color 4F & pause & exit /B 1

:TESTEDWIN
REM put your code here

Why does NULL = NULL evaluate to false in SQL server

Because NULL means 'unknown value' and two unknown values cannot be equal.

So, if to our logic NULL N°1 is equal to NULL N°2, then we have to tell that somehow:

SELECT 1
WHERE ISNULL(nullParam1, -1) = ISNULL(nullParam2, -1)

where known value -1 N°1 is equal to -1 N°2

Reload a DIV without reloading the whole page

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" />

<div class="View"><?php include 'Small.php'; ?></div>

<script type="text/javascript">
$(document).ready(function() {
$('.View').load('Small.php');
var auto_refresh = setInterval(
    function ()
    {
        $('.View').load('Small.php').fadeIn("slow");
    }, 15000); // refresh every 15000 milliseconds
        $.ajaxSetup({ cache: true });
    });
</script>

Getting the source HTML of the current page from chrome extension

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
            alert(title)
        }
    });

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
        );
    });

How to enter command with password for git pull?

Below cmd will work if we dont have @ in password: git pull https://username:pass@[email protected]/my/repository If you have @ in password then replace it by %40 as shown below: git pull https://username:pass%[email protected]/my/repository

Casting variables in Java

Casting a reference will only work if it's an instanceof that type. You can't cast random references. Also, you need to read more on Casting Objects.

e.g.

String string = "String";

Object object = string; // Perfectly fine since String is an Object

String newString = (String)object; // This only works because the `reference` object is pointing to a valid String object.

Pycharm/Python OpenCV and CV2 install error

First step:

pip uninstall numpy
pip uninstall opencv-python

Second step:

pip install numpy
pip install opencv-python

Have bash script answer interactive prompts

In my situation I needed to answer some questions without Y or N but with text or blank. I found the best way to do this in my situation was to create a shellscript file. In my case I called it autocomplete.sh

I was needing to answer some questions for a doctrine schema exporter so my file looked like this.

-- This is an example only --

php vendor/bin/mysql-workbench-schema-export mysqlworkbenchfile.mwb ./doctrine << EOF
`#Export to Doctrine Annotation Format`                                     1
`#Would you like to change the setup configuration before exporting`        y
`#Log to console`                                                           y
`#Log file`                                                                 testing.log
`#Filename [%entity%.%extension%]`
`#Indentation [4]`
`#Use tabs [no]`
`#Eol delimeter (win, unix) [win]`
`#Backup existing file [yes]`
`#Add generator info as comment [yes]`
`#Skip plural name checking [no]`
`#Use logged storage [no]`
`#Sort tables and views [yes]`
`#Export only table categorized []`
`#Enhance many to many detection [yes]`
`#Skip many to many tables [yes]`
`#Bundle namespace []`
`#Entity namespace []`
`#Repository namespace []`
`#Use automatic repository [yes]`
`#Skip column with relation [no]`
`#Related var name format [%name%%related%]`
`#Nullable attribute (auto, always) [auto]`
`#Generated value strategy (auto, identity, sequence, table, none) [auto]`
`#Default cascade (persist, remove, detach, merge, all, refresh, ) [no]`
`#Use annotation prefix [ORM\]`
`#Skip getter and setter [no]`
`#Generate entity serialization [yes]`
`#Generate extendable entity [no]`                                          y
`#Quote identifier strategy (auto, always, none) [auto]`
`#Extends class []`
`#Property typehint [no]`
EOF

The thing I like about this strategy is you can comment what your answers are and using EOF a blank line is just that (the default answer). Turns out by the way this exporter tool has its own JSON counterpart for answering these questions, but I figured that out after I did this =).

to run the script simply be in the directory you want and run 'sh autocomplete.sh' in terminal.

In short by using << EOL & EOF in combination with Return Lines you can answer each question of the prompt as necessary. Each new line is a new answer.

My example just shows how this can be done with comments also using the ` character so you remember what each step is.

Note the other advantage of this method is you can answer with more then just Y or N ... in fact you can answer with blanks!

Hope this helps someone out.

How can I tail a log file in Python?

Using the sh module (pip install sh):

from sh import tail
# runs forever
for line in tail("-f", "/var/log/some_log_file.log", _iter=True):
    print(line)

[update]

Since sh.tail with _iter=True is a generator, you can:

import sh
tail = sh.tail("-f", "/var/log/some_log_file.log", _iter=True)

Then you can "getNewData" with:

new_data = tail.next()

Note that if the tail buffer is empty, it will block until there is more data (from your question it is not clear what you want to do in this case).

[update]

This works if you replace -f with -F, but in Python it would be locking. I'd be more interested in having a function I could call to get new data when I want it, if that's possible. – Eli

A container generator placing the tail call inside a while True loop and catching eventual I/O exceptions will have almost the same effect of -F.

def tail_F(some_file):
    while True:
        try:
            for line in sh.tail("-f", some_file, _iter=True):
                yield line
        except sh.ErrorReturnCode_1:
            yield None

If the file becomes inaccessible, the generator will return None. However it still blocks until there is new data if the file is accessible. It remains unclear for me what you want to do in this case.

Raymond Hettinger approach seems pretty good:

def tail_F(some_file):
    first_call = True
    while True:
        try:
            with open(some_file) as input:
                if first_call:
                    input.seek(0, 2)
                    first_call = False
                latest_data = input.read()
                while True:
                    if '\n' not in latest_data:
                        latest_data += input.read()
                        if '\n' not in latest_data:
                            yield ''
                            if not os.path.isfile(some_file):
                                break
                            continue
                    latest_lines = latest_data.split('\n')
                    if latest_data[-1] != '\n':
                        latest_data = latest_lines[-1]
                    else:
                        latest_data = input.read()
                    for line in latest_lines[:-1]:
                        yield line + '\n'
        except IOError:
            yield ''

This generator will return '' if the file becomes inaccessible or if there is no new data.

[update]

The second to last answer circles around to the top of the file it seems whenever it runs out of data. – Eli

I think the second will output the last ten lines whenever the tail process ends, which with -f is whenever there is an I/O error. The tail --follow --retry behavior is not far from this for most cases I can think of in unix-like environments.

Perhaps if you update your question to explain what is your real goal (the reason why you want to mimic tail --retry), you will get a better answer.

The last answer does not actually follow the tail and merely reads what's available at run time. – Eli

Of course, tail will display the last 10 lines by default... You can position the file pointer at the end of the file using file.seek, I will left a proper implementation as an exercise to the reader.

IMHO the file.read() approach is far more elegant than a subprocess based solution.

Authenticate with GitHub using a token

Normally I do like this

 git push https://$(git_token)@github.com/user_name/repo_name.git

The git_token is reading from variable config in azure devops.

You can read my full blog here

Find element's index in pandas Series

you can use Series.idxmax()

>>> import pandas as pd
>>> myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
>>> myseries.idxmax()
3
>>> 

How to count TRUE values in a logical vector

There's also a package called bit that is specifically designed for fast boolean operations. It's especially useful if you have large vectors or need to do many boolean operations.

z <- sample(c(TRUE, FALSE), 1e8, rep = TRUE)

system.time({
  sum(z) # 0.170s
})

system.time({
  bit::sum.bit(z) # 0.021s, ~10x improvement in speed
})

How to Flatten a Multidimensional Array?

In PHP 5.6 and above you can flatten two dimensional arrays with array_merge after unpacking the outer array with ... operator. The code is simple and clear.

array_merge(...$a);

This works with collection of associative arrays too.

$a = [[10, 20], [30, 40]];
$b = [["x" => "X", "y" => "Y"], ["p" => "P", "q" => "Q"]];

print_r(array_merge(...$a));
print_r(array_merge(...$b));

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
)
Array
(
    [x] => X
    [y] => Y
    [p] => P
    [q] => Q
)

In PHP 8.0 and below, array unpacking does not work when the outer array has non numeric keys. Support for unpacking array with string keys is available from PHP 8.1. To support 8.0 and below, you should call array_values first.

$c = ["a" => ["x" => "X", "y" => "Y"], "b" => ["p" => "P", "q" => "Q"]];
print_r(array_merge(...array_values($c)));

Array
(
    [x] => X
    [y] => Y
    [p] => P
    [q] => Q
)

Update: Based on comment by @MohamedGharib

This will throw an error if the outer array is empty, since array_merge would be called with zero arguments. It can be be avoided by adding an empty array as the first argument.

array_merge([], ...$a);

Date / Timestamp to record when a record was added to the table?

You can make a default constraint on this column that will put a default getdate() as a value.

Example:

alter table dbo.TABLE 
add constraint df_TABLE_DATE default getdate() for DATE_COLUMN

vba error handling in loop

How about:

    For Each oSheet In ActiveWorkbook.Sheets
        If oSheet.ListObjects.Count > 0 Then
          oCmbBox.AddItem oSheet.Name
        End If
    Next oSheet

Android - java.lang.SecurityException: Permission Denial: starting Intent

If you are trying to test your app coded in android studio through your android phone, its generally the issue of your phone. Just uncheck all the USB debugging options and toggle the developer options to OFF. Then restart your phone and switch the developer and USB debugging on. You are ready to go!

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

  1. Open the xml in notepad
  2. Make sure you dont have extra space at the beginning and end of the document.
  3. Select File -> Save As
  4. select save as type -> All files
  5. Enter file name as abcd.xml
  6. select Encoding - UTF-8 -> Click Save

Difference between Groovy Binary and Source release?

Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.

What's the difference between select_related and prefetch_related in Django ORM?

Your understanding is mostly correct. You use select_related when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey. You use prefetch_related when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys. Just to clarify what I mean by "reverse ForeignKeys" here's an example:

class ModelA(models.Model):
    pass

class ModelB(models.Model):
    a = ForeignKey(ModelA)

ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship

The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA in the above example). You may use prefetch_related for anything that you can use select_related for.

The tradeoffs are that prefetch_related has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.

Everything discussed above is basically about the communications with the database. On the Python side however prefetch_related has the extra benefit that a single object is used to represent each object in the database. With select_related duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.

Find commit by hash SHA in Git

There are two ways to do this.

1. providing the SHA of the commit you want to see to git log

git log -p a2c25061

Where -p is short for patch

2. use git show

git show a2c25061

The output for both commands will be:

  • the commit
  • the author
  • the date
  • the commit message
  • the patch information

Creating stored procedure with declare and set variables

I assume you want to pass the Order ID in. So:

CREATE PROCEDURE [dbo].[Procedure_Name]
(
    @OrderID INT
) AS
BEGIN
    Declare @OrderItemID AS INT
    DECLARE @AppointmentID AS INT
    DECLARE @PurchaseOrderID AS INT
    DECLARE @PurchaseOrderItemID AS INT
    DECLARE @SalesOrderID AS INT
    DECLARE @SalesOrderItemID AS INT

    SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
    SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
    SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END

changing the owner of folder in linux

Use chown to change ownership and chmod to change rights.

use the -R option to apply the rights for all files inside of a directory too.

Note that both these commands just work for directories too. The -R option makes them also change the permissions for all files and directories inside of the directory.

For example

sudo chown -R username:group directory

will change ownership (both user and group) of all files and directories inside of directory and directory itself.

sudo chown username:group directory

will only change the permission of the folder directory but will leave the files and folders inside the directory alone.

you need to use sudo to change the ownership from root to yourself.

Edit:

Note that if you use chown user: file (Note the left-out group), it will use the default group for that user.

Also You can change the group ownership of a file or directory with the command:

chgrp group_name file/directory_name

You must be a member of the group to which you are changing ownership to.

You can find group of file as follows

# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file

# chown sujit:friends file

User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.

What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.

But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.

Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.

inherit from two classes in C#

Multitiple inheritance is not possible in C#, however it can be simulated using interfaces, see Simulated Multiple Inheritance Pattern for C#.

The basic idea is to define an interface for the members on class B that you wish to access (call it IB), and then have C inherit from A and implement IB by internally storing an instance of B, for example:

class C : A, IB
{
    private B _b = new B();

    // IB members
    public void SomeMethod()
    {
        _b.SomeMethod();
    }
}

There are also a couple of other alternaitve patterns explained on that page.

Logging in Scala

Quick and easy forms.

Scala 2.10 and older:

import com.typesafe.scalalogging.slf4j.Logger
import org.slf4j.LoggerFactory
val logger = Logger(LoggerFactory.getLogger("TheLoggerName"))
logger.debug("Useful message....")

And build.sbt:

libraryDependencies += "com.typesafe" %% "scalalogging-slf4j" % "1.1.0"

Scala 2.11+ and newer:

import import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory
val logger = Logger(LoggerFactory.getLogger("TheLoggerName"))
logger.debug("Useful message....")

And build.sbt:

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.1.0"

MongoDB: How to find out if an array field contains an element?

I am trying to explain by putting problem statement and solution to it. I hope it will help

Problem Statement:

Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-

Solution:

Below are the conditions that need to be taken care of

  1. Product price should be less than 15
  2. Product name should be either ABC Product or PQR Product
  3. Product should be in published state.

Below is the statement that applies above criterion to create query and fetch data.

$elements = $collection->find(
             Array(
                [price] => Array( [$lt] => 15 ),
                [$or] => Array(
                            [0]=>Array(
                                    [product_name]=>Array(
                                       [$in]=>Array(
                                            [0] => ABC Product,
                                            [1]=> PQR Product
                                            )
                                        )
                                    )
                                ),
                [state]=>Published
                )
            );

ORA-30926: unable to get a stable set of rows in the source tables

I was not able to resolve this after several hours. Eventually I just did a select with the two tables joined, created an extract and created individual SQL update statements for the 500 rows in the table. Ugly but beats spending hours trying to get a query to work.

T-SQL: Looping through an array of known values

Make a connection to your DB using a procedural programming language (here Python), and do the loop there. This way you can do complicated loops as well.

# make a connection to your db
import pyodbc
conn = pyodbc.connect('''
                        Driver={ODBC Driver 13 for SQL Server};
                        Server=serverName;
                        Database=DBname;
                        UID=userName;
                        PWD=password;
                      ''')
cursor = conn.cursor()

# run sql code
for id in [4, 7, 12, 22, 19]:
  cursor.execute('''
    exec p_MyInnerProcedure {}
  '''.format(id))

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

You can use following command if you uninstall globally

npm uninstall -g cordova ionic

option g for global

if you want to uninstall from he drive then you can use following command

npm uninstall cordova ionic

Change Activity's theme programmatically

I know that i am late but i would like to post a solution here:
Check the full source code here.
This is the code i used when changing theme using preferences..

SharedPreferences pref = PreferenceManager
        .getDefaultSharedPreferences(this);
String themeName = pref.getString("prefSyncFrequency3", "Theme1");
if (themeName.equals("Africa")) {
    setTheme(R.style.AppTheme);



} else if (themeName.equals("Colorful Beach")) {
    //Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
    setTheme(R.style.beach);


} else if (themeName.equals("Abstract")) {
    //Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();

    setTheme(R.style.abstract2);

} else if (themeName.equals("Default")) {

    setTheme(R.style.defaulttheme);

}

Please note that you have to put the code before setcontentview..

HAPPY CODING!

What's the best practice for putting multiple projects in a git repository?

While most people will tell you to just use multiple repositories, I feel it's worth mentioning there are other solutions.

Solution 1

A single repository can contain multiple independent branches, called orphan branches. Orphan branches are completely separate from each other; they do not share histories.

git checkout --orphan BRANCHNAME

This creates a new branch, unrelated to your current branch. Each project should be in its own orphaned branch.

Now for whatever reason, git needs a bit of cleanup after an orphan checkout.

rm .git/index
rm -r *

Make sure everything is committed before deleting

Once the orphan branch is clean, you can use it normally.

Solution 2

Avoid all the hassle of orphan branches. Create two independent repositories, and push them to the same remote. Just use different branch names for each repo.

# repo 1
git push origin master:master-1

# repo 2
git push origin master:master-2

Why am I getting a "401 Unauthorized" error in Maven?

In my case I removed the server logon credentials for central from my setting.

    <server> 
        <id>central</id>
        <username>admin</username> 
        <password>******</password> 
    </server>

   <mirror>
        <id>central</id>
        <mirrorOf>central</mirrorOf>
        <name>maven-central</name>
        <url>http://www.localhost:8081/repository/maven-central/</url>
   </mirror> 

I don't know why I did that, but its completely wrong since the central maven repo can be accessed anonymously. See my debug output that led to my error identification and resolution.

[DEBUG] Using connector BasicRepositoryConnector with priority 0.0 for http://www.localhost:8081/repository/maven-central/ with username=admin, password=***

python int( ) function

As the other answers have mentioned, the int operation will crash if the string input is not convertible to an int (such as a float or characters). What you can do is use a little helper method to try and interpret the string for you:

def interpret_string(s):
    if not isinstance(s, basestring):
        return str(s)
    if s.isdigit():
        return int(s)
    try:
        return float(s)
    except ValueError:
        return s

So it will take a string and try to convert it to int, then float, and otherwise return string. This is more just a general example of looking at the convertible types. It would be an error for your value to come back out of that function still being a string, which you would then want to report to the user and ask for new input.

Maybe a variation that returns None if its neither float nor int:

def interpret_string(s):
    if not isinstance(s, basestring):
        return None
    if s.isdigit():
        return int(s)
    try:
        return float(s)
    except ValueError:
        return None

val=raw_input("> ")
how_much=interpret_string(val)
if how_much is None:
    # ask for more input? Error?

Should Gemfile.lock be included in .gitignore?

A little late to the party, but answers still took me time and foreign reads to understand this problem. So I want to summarize what I have find out about the Gemfile.lock.

When you are building a Rails App, you are using certain versions of gems in your local machine. If you want to avoid errors in the production mode and other branches, you have to use that one Gemfile.lock file everywhere and tell bundler to bundle for rebuilding gems every time it changes.

If Gemfile.lock has changed on your production machine and Git doesn't let you git pull, you should write git reset --hard to avoid that file change and write git pull again.

REST API - file (ie images) processing - best practices

There are several decisions to make:

  1. The first about resource path:

    • Model the image as a resource on its own:

      • Nested in user (/user/:id/image): the relationship between the user and the image is made implicitly

      • In the root path (/image):

        • The client is held responsible for establishing the relationship between the image and the user, or;

        • If a security context is being provided with the POST request used to create an image, the server can implicitly establish a relationship between the authenticated user and the image.

    • Embed the image as part of the user

  2. The second decision is about how to represent the image resource:

    • As Base 64 encoded JSON payload
    • As a multipart payload

This would be my decision track:

  • I usually favor design over performance unless there is a strong case for it. It makes the system more maintainable and can be more easily understood by integrators.
  • So my first thought is to go for a Base64 representation of the image resource because it lets you keep everything JSON. If you chose this option you can model the resource path as you like.
    • If the relationship between user and image is 1 to 1 I'd favor to model the image as an attribute specially if both data sets are updated at the same time. In any other case you can freely choose to model the image either as an attribute, updating the it via PUT or PATCH, or as a separate resource.
  • If you choose multipart payload I'd feel compelled to model the image as a resource on is own, so that other resources, in our case, the user resource, is not impacted by the decision of using a binary representation for the image.

Then comes the question: Is there any performance impact about choosing base64 vs multipart?. We could think that exchanging data in multipart format should be more efficient. But this article shows how little do both representations differ in terms of size.

My choice Base64:

  • Consistent design decision
  • Negligible performance impact
  • As browsers understand data URIs (base64 encoded images), there is no need to transform these if the client is a browser
  • I won't cast a vote on whether to have it as an attribute or standalone resource, it depends on your problem domain (which I don't know) and your personal preference.

How to send post request to the below post method using postman rest client

I had same issue . I passed my data as key->value in "Body" section by choosing "form-data" option and it worked fine.

How can I get the timezone name in JavaScript?

You can use this script. http://pellepim.bitbucket.org/jstz/

Fork or clone repository here. https://bitbucket.org/pellepim/jstimezonedetect

Once you include the script, you can get the list of timezones in - jstz.olson.timezones variable.

And following code is used to determine client browser's timezone.

var tz = jstz.determine();
tz.name();

Enjoy jstz!

how do I give a div a responsive height

I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.

Hive cast string to date dd-MM-yyyy

If I have understood it correctly, you are trying to convert a String representing a given date, to another type.

Note: (As @Samson Scharfrichter has mentioned)

  • the default representation of a date is ISO8601
  • a date is stored in binary (not as a string)

There are a few ways to do it. And you are close to the solution. I would use the CAST (which converts to a DATE_TYPE):

SELECT cast('2018-06-05' as date); 

Result: 2018-06-05 DATE_TYPE

or (depending on your pattern)

select cast(to_date(from_unixtime(unix_timestamp('05-06-2018', 'dd-MM-yyyy'))) as date)

Result: 2018-06-05 DATE_TYPE

And if you decide to convert ISO8601 to a date type:

select cast(to_date(from_unixtime(unix_timestamp(regexp_replace('2018-06-05T08:02:59Z', 'T',' ')))) as date);

Result: 2018-06-05 DATE_TYPE

Hive has its own functions, I have written some examples for the sake of illustration of these date- and cast- functions:

Date and timestamp functions examples:

Convert String/Timestamp/Date to DATE

SELECT cast(date_format('2018-06-05 15:25:42.23','yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_date(),'yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_timestamp(),'yyyy-MM-dd') as date);  -- 2018-06-05 DATE_TYPE

Convert String/Timestamp/Date to BIGINT_TYPE

SELECT to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE
SELECT to_unix_timestamp(current_date(),'yyyy/MM/dd HH:mm:ss'); -- 1528205000 BIGINT_TYPE
SELECT to_unix_timestamp(current_timestamp(),'yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE

Convert String/Timestamp/Date to STRING

SELECT date_format('2018-06-05 15:25:42.23','yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_timestamp(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_date(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE

Convert BIGINT unixtime to STRING

SELECT to_date(from_unixtime(unixtime,'yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 STRING_TYPE

Convert String to BIGINT unixtime

SELECT unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP; -- 1528149600 BIGINT_TYPE

Convert String to TIMESTAMP

SELECT cast(unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP); -- 1528149600 TIMESTAMP_TYPE

Idempotent (String -> String)

SELECT from_unixtime(to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 15:25:42 STRING_TYPE

Idempotent (Date -> Date)

SELECT cast(current_date() as date); -- 2018-06-26 DATE_TYPE

Current date / timestamp

SELECT current_date(); -- 2018-06-26 DATE_TYPE
SELECT current_timestamp(); -- 2018-06-26 14:03:38.285 TIMESTAMP_TYPE

Adding the "Clear" Button to an iPhone UITextField

this don't work, do like me:

swift:

customTextField.clearButtonMode = UITextField.ViewMode.Always

customTextField.clearsOnBeginEditing = true;

func textFieldShouldClear(textField: UITextField) -> Bool {
    return true
}

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

Go to Windows Credentials Manager and update the credentials for GIT.

Javascript find json value

First convert this structure to a "dictionary" object:

dict = {}
json.forEach(function(x) {
    dict[x.code] = x.name
})

and then simply

countryName = dict[countryCode]

For a list of countries this doesn't matter much, but for larger lists this method guarantees the instant lookup, while the naive searching will depend on the list size.

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

In some cases, when you check your default encoding (print sys.getdefaultencoding()), it returns that you are using ASCII. If you change to UTF-8, it doesn't work, depending on the content of your variable. I found another way:

import sys
reload(sys)  
sys.setdefaultencoding('Cp1252')

Using env variable in Spring Boot's application.properties

This is in response to a number of comments as my reputation isn't high enough to comment directly.

You can specify the profile at runtime as long as the application context has not yet been loaded.

// Previous answers incorrectly used "spring.active.profiles" instead of
// "spring.profiles.active" (as noted in the comments).
// Use AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME to avoid this mistake.

System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, environment);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml");

How to debug an apache virtual host configuration?

Here's a command I think could be of some help :

apachectl -t -D DUMP_VHOSTS

You'll get a list of all the vhosts, you'll know which one is the default one and you'll make sure that your syntax is correct (same as apachectl configtest suggested by yojimbo87).

You'll also know where each vhost is declared. It can be handy if your config files are a mess. ;)

Using psql how do I list extensions installed in a database?

In psql that would be

\dx

See the manual for details: http://www.postgresql.org/docs/current/static/app-psql.html

Doing it in plain SQL it would be a select on pg_extension:

SELECT * 
FROM pg_extension

http://www.postgresql.org/docs/current/static/catalog-pg-extension.html

make div's height expand with its content

You need to force a clear:both before the #main_content div is closed. I would probably move the <br class="clear" />; into the #main_content div and set the CSS to be:

.clear { clear: both; }

Update: This question still gets a fair amount of traffic, so I wanted to update the answer with a modern alternative using a new layout mode in CSS3 called Flexible boxes or Flexbox:

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.flex-container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  min-height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
  background-color: #3F51B5;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
section.content {_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background-color: #FFC107;_x000D_
  color: #333;_x000D_
}
_x000D_
<div class="flex-container">_x000D_
  <header>_x000D_
    <h1>_x000D_
     Header   _x000D_
    </h1>_x000D_
  </header>_x000D_
_x000D_
  <section class="content">_x000D_
    Content_x000D_
  </section>_x000D_
_x000D_
  <footer>_x000D_
    <h4>_x000D_
      Footer_x000D_
    </h4>_x000D_
  </footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Most modern browsers currently support Flexbox and viewport units, but if you have to maintain support for older browsers, make sure to check compatibility for the specific browser version.

How to open remote files in sublime text 3

Base on this.

Step by step:

  • On your local workstation: On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub
  • On your local workstation: Add RemoteForward 52698 127.0.0.1:52698 to your .ssh/config file, or -R 52698:localhost:52698 if you prefer command line
  • On your remote server:

    sudo wget -O /usr/local/bin/rsub https://raw.github.com/aurora/rmate/master/rmate
    sudo chmod a+x /usr/local/bin/rsub
    

Just keep your ST3 editor open, and you can easily edit remote files with

rsub myfile.txt

EDIT: if you get "no such file or directory", it's because your /usr/local/bin is not in your PATH. Just add the directory to your path:

echo "export PATH=\"$PATH:/usr/local/bin\"" >> $HOME/.bashrc

Now just log off, log back in, and you'll be all set.

How to Get True Size of MySQL Database?

Basically there are two ways: query DB (data length + index length) or check files size. Index length is related to data stored in indexes.

Everything is described here:

http://www.mkyong.com/mysql/how-to-calculate-the-mysql-database-size/

How to write a basic swap function in Java

Use this one-liner for any primitive number class including double and float:

a += (b - (b = a));

For example:

double a = 1.41;
double b = 0;
a += (b - (b = a));
System.out.println("a = " + a + ", b = " + b);

Output is a = 0.0, b = 1.41

Auto-redirect to another HTML page

If you want to redirect your webpage to another HTML FILE, just use as followed:

<meta http-equiv="refresh" content"2;otherpage.html">

2 being the seconds you want the client to wait before redirecting. Use "url=" only when it's an URL, to redirect to an HTML file just write the name after the ';'

How to determine if a type implements an interface with C# reflection

IsAssignableFrom is now moved to TypeInfo:

typeof(ISMSRequest).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo());

Convert JSONObject to Map

The best way to convert it to HashMap<String, Object> is this:

HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, new TypeReference<Map<String, Object>>(){}));

Uncaught (in promise) TypeError: Failed to fetch and Cors error

you can use solutions without adding "Access-Control-Allow-Origin": "*", if your server is already using Proxy gateway this issue will not happen because the front and backend will be route in the same IP and port in client side but for development, you need one of this three solution if you don't need extra code 1- simulate the real environment by using a proxy server and configure the front and backend in the same port

2- if you using Chrome you can use the extension called Allow-Control-Allow-Origin: * it will help you to avoid this problem

3- you can use the code but some browsers versions may not support that so try to use one of the previous solutions

the best solution is using a proxy like ngnix its easy to configure and it will simulate the real situation of the production deployment

Check if a user has scrolled to the bottom

Nick Craver's answer needs to be slightly modified to work on iOS 6 Safari Mobile and should be:

$(window).scroll(function() {
   if($(window).scrollTop() + window.innerHeight == $(document).height()) {
       alert("bottom!");
   }
});

Changing $(window).height() to window.innerHeight should be done because when the address bar is hidden an additional 60px are added to the window's height but using $(window).height() does not reflect this change, while using window.innerHeight does.

Note: The window.innerHeight property also includes the horizontal scrollbar's height (if it is rendered), unlike $(window).height() which will not include the horizontal scrollbar's height. This is not a problem in Mobile Safari, but could cause unexpected behavior in other browsers or future versions of Mobile Safari. Changing == to >= could fix this for most common use cases.

Read more about the window.innerHeight property here

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

When you encounter exceptions like this, the most useful information is generally at the bottom of the stacktrace:

Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
  at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
  ...
  at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:246)

The problem is that Tomcat can't find com.mysql.jdbc.Driver. This is usually caused by the JAR containing the MySQL driver not being where Tomcat expects to find it (namely in the webapps/<yourwebapp>/WEB-INF/lib directory).

Inline <style> tags vs. inline css properties

There can be different reasons for choosing one way over the other.

  • If you need to specify css to elements that are generated programmatically (for example modifying css for images of different sizes), it can be more maintainable to use inline css.
  • If some css is valid only for the current page, you should rather use the script tag than a separate .css file. It is good if the browser doesn't have to do too many http requests.

Otherwise, as stated, it is better to use a separate css file.

Subtracting time.Duration from time in Go

In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    count := 10
    then := now.Add(time.Duration(-count) * time.Minute)
    // if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
    // then := now.Add(-10 * time.Minute)
    fmt.Println("10 minutes ago:", then)
}

Produces:

now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC

Not to mention, you can also use time.Hour or time.Second instead of time.Minute as per your needs.

Playground: https://play.golang.org/p/DzzH4SA3izp

Fatal error: Maximum execution time of 300 seconds exceeded

PHP's CLI's default execution time is infinite.

This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30. When running PHP from the command line the default setting is 0.

http://gr.php.net/manual/en/info.configuration.php#ini.max-execution-time

Check if you're running PHP in safe mode, because it ignores all time exec settings when on that.

Converts scss to css

Install Ruby-sass using below command
sudo apt-get -y update
sudo apt-get -y install ruby-full
sudo apt install ruby-sass
gem install bundler

Example
sass SCSS_FILE_PATH:CSS_FILE_PATH;

e.g sass mda/at-md-black.scss:css/at-md-black.css;

How can I get the length of text entered in a textbox using jQuery?

If your textbox has an id attribute of "mytextbox", then you can get the length like this:

var myLength = $("#mytextbox").val().length;
  • $("#mytextbox") finds the textbox by its id.
  • .val() gets the value of the input element entered by the user, which is a string.
  • .length gets the number of characters in the string.

How do I efficiently iterate over each entry in a Java Map?

In theory, the most efficient way will depend on which implementation of Map. The official way to do this is to call map.entrySet(), which returns a set of Map.Entry, each of which contains a key and a value (entry.getKey() and entry.getValue()).

In an idiosyncratic implementation, it might make some difference whether you use map.keySet(), map.entrySet() or something else. But I can't think of a reason why anyone would write it like that. Most likely it makes no difference to performance what you do.

And yes, the order will depend on the implementation - as well as (possibly) the order of insertion and other hard-to-control factors.

[edit] I wrote valueSet() originally but of course entrySet() is actually the answer.

How do you disable viewport zooming on Mobile Safari?

@mattis is correct that iOS 10 Safari won't allow you to disable pinch to zoom with the user-scalable attribute. However, I got it to disable using preventDefault on the 'gesturestart' event. I've only verified this on Safari in iOS 10.0.2.

document.addEventListener('gesturestart', function (e) {
    e.preventDefault();
});

What is the difference between single-quoted and double-quoted strings in PHP?

One thing:

It is very important to note that the line with the closing identifier of Heredoc must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon.

Example:

   $str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

Position a div container on the right side

Just wanna update this for beginners now you should definitly use flexbox to do that, it's more appropriate and work for responsive try this : http://jsfiddle.net/x5vyC/3957/

#wrapper{
  display:flex;
  justify-content:space-between;
  background:red;
}


#c1{
   background:blue;
}


#c2{
    background:green;
}

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

How to fix Python Numpy/Pandas installation?

I work with the guys that created Anaconda Python. You can install multiple versions of python and numpy without corrupting your system python. It's free and open source (OSX, linux, Windows). The paid packages are enhancements on top of the free version. Pandas is included.

conda create --name np17py27 anaconda=1.4 numpy=1.7 python=2.7
export PATH=~/anaconda/envs/np17py27/bin:$PATH

If you want numpy 1.6:

conda create --name np16py27 anaconda=1.4 numpy=1.6 python=2.7

Setting your PATH sets up where to find python and ipython. The environments (np17py27) can be named whatever you would like.

Creating java date object from year,month,day

Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.

Here is a quick example using LocalDate from the Joda Time library:

LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();

Here you can follow a quick start tutorial.

How to align form at the center of the page in html/css

This is my answer. I'm not a Pro. I hope this answer may help you :3

<div align="center">
<form>
.
.
Your elements
.
.
</form>
</div>

Logical operators ("and", "or") in DOS batch

An alternative is to look for a unix shell which does give you logical operators and a whole lot more. You can get a native win32 implementation of a Bourne shell here if you don't want to go the cygwin route. A native bash can be found here. I'm quite certain you could easily google other good alternatives such as zsh or tcsh.

K

The remote host closed the connection. The error code is 0x800704CD

I was getting this on an asp.net 2.0 iis7 Windows2008 site. Same code on iis6 worked fine. It was causing an issue for me because it was messing up the login process. User would login and get a 302 to default.asxp, which would get through page_load, but not as far as pre-render before iis7 would send a 302 back to login.aspx without the auth cookie. I started playing with app pool settings, and for some reason 'enable 32 bit applications' seems to have fixed it. No idea why, since this site isn't doing anything special that should require any 32 bit drivers. We have some sites that still use Access that require 32bit, but not our straight SQL sites like this one.

Replacing NULL with 0 in a SQL server query

If you are using Presto, AWS Athena etc, there is no ISNULL() function. Instead, use:

SELECT COALESCE(myColumn, 0 ) FROM myTable

How to get a property value based on the name

Simple sample (without write reflection hard code in the client)

class Customer
{
    public string CustomerName { get; set; }
    public string Address { get; set; }
    // approach here
    public string GetPropertyValue(string propertyName)
    {
        try
        {
            return this.GetType().GetProperty(propertyName).GetValue(this, null) as string;
        }
        catch { return null; }
    }
}
//use sample
static void Main(string[] args)
    {
        var customer = new Customer { CustomerName = "Harvey Triana", Address = "Something..." };
        Console.WriteLine(customer.GetPropertyValue("CustomerName"));
    }

How to uncommit my last commit in Git

Just a note - if you're using ZSH and see the error

zsh: no matches found: HEAD^

You need to escape the ^

git reset --soft HEAD\^

align images side by side in html

I suggest to use a container for each img p like this:

<div class="image123">
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif" height="200" width="200"  />
        <p style="text-align:center;">This is image 1</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img class="middle-img" src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 2</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 3</p>
    </div>
</div>

Then apply float:left to each container. I add and 5px margin right so there is a space between each image. Also alway close your elements. Maybe in html img tag is not important to close but in XHTML is.

fiddle

Also a friendly advice. Try to avoid inline styles as much as possible. Take a look here:

html

<div class="image123">
    <div>
        <img src="/images/tv.gif" />
        <p>This is image 1</p>
    </div>
    <div>
        <img class="middle-img" src="/images/tv.gif/" />
        <p>This is image 2</p>
    </div>
    <div>
        <img src="/images/tv.gif/" />
        <p>This is image 3</p>
    </div>
</div>

css

div{
    float:left;
    margin-right:5px;
}

div > img{
   height:200px;
    width:200px;
}

p{
    text-align:center;
}

It's generally recommended that you use linked style sheets because:

  • They can be cached by browsers for performance
  • Generally a lot easier to maintain for a development perspective

source

fiddle

Should we pass a shared_ptr by reference or by value?

Not knowing time cost of shared_copy copy operation where atomic increment and decrement is in, I suffered from much higher CPU usage problem. I never expected atomic increment and decrement may take so much cost.

Following my test result, int32 atomic increment and decrement takes 2 or 40 times than non-atomic increment and decrement. I got it on 3GHz Core i7 with Windows 8.1. The former result comes out when no contention occurs, the latter when high possibility of contention occurs. I keep in mind that atomic operations are at last hardware based lock. Lock is lock. Bad to performance when contention occurs.

Experiencing this, I always use byref(const shared_ptr&) than byval(shared_ptr).

Excel VBA, How to select rows based on data in a column?

The easiest way to do it is to use the End method, which is gives you the cell that you reach by pressing the end key and then a direction when you're on a cell (in this case B6). This won't give you what you expect if B6 or B7 is empty, though.

Dim start_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Range(start_cell, start_cell.End(xlDown)).Copy Range("[Workbook2.xlsx]Sheet1!A2")

If you can't use End, then you would have to use a loop.

Dim start_cell As Range, end_cell As Range

Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Set end_cell = start_cell

Do Until IsEmpty(end_cell.Offset(1, 0))
    Set end_cell = end_cell.Offset(1, 0)
Loop

Range(start_cell, end_cell).Copy Range("[Workbook2.xlsx]Sheet1!A2")

Count items in a folder with PowerShell

Only Files

Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}

Only Folders

Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}

Both

Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}

Update rows in one table with data from another table based on one column in each being equal

It's not an insert if the record already exists in t1 (the user_id matches) unless you are happy to create duplicate user_id's.

You might want an update?

UPDATE t1
   SET <t1.col_list> = (SELECT <t2.col_list>
                          FROM t2
                         WHERE t2.user_id = t1.user_id)
 WHERE EXISTS
      (SELECT 1
         FROM t2
        WHERE t1.user_id = t2.user_id);

Hope it helps...

How to check if a file exists from a url

I've just found this solution:

if(@getimagesize($remoteImageURL)){
    //image exists!
}else{
    //image does not exist.
}

Source: http://www.dreamincode.net/forums/topic/11197-checking-if-file-exists-on-remote-server/

Media Queries - In between two widths

_x000D_
_x000D_
.class {_x000D_
    display: none;_x000D_
}_x000D_
@media (min-width:400px) and (max-width:900px) {_x000D_
    .class {_x000D_
        display: block; /* just an example display property */_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How to Set Variables in a Laravel Blade Template

In laravel document https://laravel.com/docs/5.8/blade#php You can do this way:

@php
     $my_variable = 123;
@endphp

slashes in url variables

You need to escape the slashes as %2F.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

You can show whatever you want in list display by using a callable. It would look like this:


def book_author(object):
  return object.book.author

class PersonAdmin(admin.ModelAdmin):
  list_display = [book_author,]

How to implement reCaptcha for ASP.NET MVC?

An async version for MVC 5 (i.e. avoiding ActionFilterAttribute, which is not async until MVC 6) and reCAPTCHA 2

ExampleController.cs

public class HomeController : Controller
{
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ContactSubmit(
        [Bind(Include = "FromName, FromEmail, FromPhone, Message, ContactId")]
        ContactViewModel model)
    {
        if (!await RecaptchaServices.Validate(Request))
        {
            ModelState.AddModelError(string.Empty, "You have not confirmed that you are not a robot");
        }
        if (ModelState.IsValid)
        {
           ...

ExampleView.cshtml

@model MyMvcApp.Models.ContactViewModel

@*This is assuming the master layout places the styles section within the head tags*@
@section Styles {
    @Styles.Render("~/Content/ContactPage.css")
    <script src='https://www.google.com/recaptcha/api.js'></script>
}

@using (Html.BeginForm("ContactSubmit", "Home",FormMethod.Post, new { id = "contact-form" }))
{
    @Html.AntiForgeryToken()
    ...
    <div class="form-group">
      @Html.LabelFor(m => m.Message) 
      @Html.TextAreaFor(m => m.Message, new { @class = "form-control", @cols = "40", @rows = "3" })
      @Html.ValidationMessageFor(m => m.Message)
    </div>

    <div class="row">
      <div class="g-recaptcha" data-sitekey='@System.Configuration.ConfigurationManager.AppSettings["RecaptchaClientKey"]'></div>
    </div>

    <div class="row">
      <input type="submit" id="submit-button" class="btn btn-default" value="Send Your Message" />
    </div>
}

RecaptchaServices.cs

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web;
using System.Configuration;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Runtime.Serialization;

namespace MyMvcApp.Services
{
    public class RecaptchaServices
    {
        //ActionFilterAttribute has no async for MVC 5 therefore not using as an actionfilter attribute - needs revisiting in MVC 6
        internal static async Task<bool> Validate(HttpRequestBase request)
        {
            string recaptchaResponse = request.Form["g-recaptcha-response"];
            if (string.IsNullOrEmpty(recaptchaResponse))
            {
                return false;
            }
            using (var client = new HttpClient { BaseAddress = new Uri("https://www.google.com") })
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("secret", ConfigurationManager.AppSettings["RecaptchaSecret"]),
                    new KeyValuePair<string, string>("response", recaptchaResponse),
                    new KeyValuePair<string, string>("remoteip", request.UserHostAddress)
                });
                var result = await client.PostAsync("/recaptcha/api/siteverify", content);
                result.EnsureSuccessStatusCode();
                string jsonString = await result.Content.ReadAsStringAsync();
                var response = JsonConvert.DeserializeObject<RecaptchaResponse>(jsonString);
                return response.Success;
            }
        }

        [DataContract]
        internal class RecaptchaResponse
        {
            [DataMember(Name = "success")]
            public bool Success { get; set; }
            [DataMember(Name = "challenge_ts")]
            public DateTime ChallengeTimeStamp { get; set; }
            [DataMember(Name = "hostname")]
            public string Hostname { get; set; }
            [DataMember(Name = "error-codes")]
            public IEnumerable<string> ErrorCodes { get; set; }
        }

    }
}

web.config

<configuration>
  <appSettings>
    <!--recaptcha-->
    <add key="RecaptchaSecret" value="***secret key from https://developers.google.com/recaptcha***" />
    <add key="RecaptchaClientKey" value="***client key from https://developers.google.com/recaptcha***" />
  </appSettings>
</configuration>

Checking from shell script if a directory contains files

I would go for find:

if [ -z "$(find $dir -maxdepth 1 -type f)" ]; then
    echo "$dir has NO files"
else
    echo "$dir has files"

This checks the output of looking for just files in the directory, without going through the subdirectories. Then it checks the output using the -z option taken from man test:

   -z STRING
          the length of STRING is zero

See some outcomes:

$ mkdir aaa
$ dir="aaa"

Empty dir:

$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
empty

Just dirs in it:

$ mkdir aaa/bbb
$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
empty

A file in the directory:

$ touch aaa/myfile
$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
$ rm aaa/myfile 

A file in a subdirectory:

$ touch aaa/bbb/another_file
$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
empty

How can I remove the string "\n" from within a Ruby string?

use chomp or strip functions from Ruby:

"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"

Changing SVG image color with javascript

Given some SVG:

<div id="main">
  <svg id="octocat" xmlns="http://www.w3.org/2000/svg" width="400px" height="400px" viewBox="-60 0 420 330" style="fill:#fff;stroke: #000; stroke-opacity: 0.1">
    <path id="puddle" d="m296.94 295.43c0 20.533-47.56 37.176-106.22 37.176-58.67 0-106.23-16.643-106.23-37.176s47.558-37.18 106.23-37.18c58.66 0 106.22 16.65 106.22 37.18z"/>
    <path class="shadow-legs" d="m161.85 331.22v-26.5c0-3.422-.619-6.284-1.653-8.701 6.853 5.322 7.316 18.695 7.316 18.695v17.004c6.166.481 12.534.773 19.053.861l-.172-16.92c-.944-23.13-20.769-25.961-20.769-25.961-7.245-1.645-7.137 1.991-6.409 4.34-7.108-12.122-26.158-10.556-26.158-10.556-6.611 2.357-.475 6.607-.475 6.607 10.387 3.775 11.33 15.105 11.33 15.105v23.622c5.72.98 11.71 1.79 17.94 2.4z"/>
    <path class="shadow-legs" d="m245.4 283.48s-19.053-1.566-26.16 10.559c.728-2.35.839-5.989-6.408-4.343 0 0-19.824 2.832-20.768 25.961l-.174 16.946c6.509-.025 12.876-.254 19.054-.671v-17.219s.465-13.373 7.316-18.695c-1.034 2.417-1.653 5.278-1.653 8.701v26.775c6.214-.544 12.211-1.279 17.937-2.188v-24.113s.944-11.33 11.33-15.105c0-.01 6.13-4.26-.48-6.62z"/>
    <path id="cat" d="m378.18 141.32l.28-1.389c-31.162-6.231-63.141-6.294-82.487-5.49 3.178-11.451 4.134-24.627 4.134-39.32 0-21.073-7.917-37.931-20.77-50.759 2.246-7.25 5.246-23.351-2.996-43.963 0 0-14.541-4.617-47.431 17.396-12.884-3.22-26.596-4.81-40.328-4.81-15.109 0-30.376 1.924-44.615 5.83-33.94-23.154-48.923-18.411-48.923-18.411-9.78 24.457-3.733 42.566-1.896 47.063-11.495 12.406-18.513 28.243-18.513 47.659 0 14.658 1.669 27.808 5.745 39.237-19.511-.71-50.323-.437-80.373 5.572l.276 1.389c30.231-6.046 61.237-6.256 80.629-5.522.898 2.366 1.899 4.661 3.021 6.879-19.177.618-51.922 3.062-83.303 11.915l.387 1.36c31.629-8.918 64.658-11.301 83.649-11.882 11.458 21.358 34.048 35.152 74.236 39.484-5.704 3.833-11.523 10.349-13.881 21.374-7.773 3.718-32.379 12.793-47.142-12.599 0 0-8.264-15.109-24.082-16.292 0 0-15.344-.235-1.059 9.562 0 0 10.267 4.838 17.351 23.019 0 0 9.241 31.01 53.835 21.061v32.032s-.943 11.33-11.33 15.105c0 0-6.137 4.249.475 6.606 0 0 28.792 2.361 28.792-21.238v-34.929s-1.142-13.852 5.663-18.667v57.371s-.47 13.688-7.551 18.881c0 0-4.723 8.494 5.663 6.137 0 0 19.824-2.832 20.769-25.961l.449-58.06h4.765l.453 58.06c.943 23.129 20.768 25.961 20.768 25.961 10.383 2.357 5.663-6.137 5.663-6.137-7.08-5.193-7.551-18.881-7.551-18.881v-56.876c6.801 5.296 5.663 18.171 5.663 18.171v34.929c0 23.6 28.793 21.238 28.793 21.238 6.606-2.357.474-6.606.474-6.606-10.386-3.775-11.33-15.105-11.33-15.105v-45.786c0-17.854-7.518-27.309-14.87-32.3 42.859-4.25 63.426-18.089 72.903-39.591 18.773.516 52.557 2.803 84.873 11.919l.384-1.36c-32.131-9.063-65.692-11.408-84.655-11.96.898-2.172 1.682-4.431 2.378-6.755 19.25-.80 51.38-.79 82.66 5.46z"/>
    <path id="face" d="m258.19 94.132c9.231 8.363 14.631 18.462 14.631 29.343 0 50.804-37.872 52.181-84.585 52.181-46.721 0-84.589-7.035-84.589-52.181 0-10.809 5.324-20.845 14.441-29.174 15.208-13.881 40.946-6.531 70.147-6.531 29.07-.004 54.72-7.429 69.95 6.357z"/>
    <path id="eyes" d="m160.1 126.06 c0 13.994-7.88 25.336-17.6 25.336-9.72 0-17.6-11.342-17.6-25.336 0-13.992 7.88-25.33 17.6-25.33 9.72.01 17.6 11.34 17.6 25.33z m94.43 0 c0 13.994-7.88 25.336-17.6 25.336-9.72 0-17.6-11.342-17.6-25.336 0-13.992 7.88-25.33 17.6-25.33 9.72.01 17.6 11.34 17.6 25.33z"/>
    <path id="pupils" d="m154.46 126.38 c0 9.328-5.26 16.887-11.734 16.887s-11.733-7.559-11.733-16.887c0-9.331 5.255-16.894 11.733-16.894 6.47 0 11.73 7.56 11.73 16.89z m94.42 0 c0 9.328-5.26 16.887-11.734 16.887s-11.733-7.559-11.733-16.887c0-9.331 5.255-16.894 11.733-16.894 6.47 0 11.73 7.56 11.73 16.89z"/>
    <circle id="nose" cx="188.5" cy="148.56" r="4.401"/>
    <path id="mouth" d="m178.23 159.69c-.26-.738.128-1.545.861-1.805.737-.26 1.546.128 1.805.861 1.134 3.198 4.167 5.346 7.551 5.346s6.417-2.147 7.551-5.346c.26-.738 1.067-1.121 1.805-.861s1.121 1.067.862 1.805c-1.529 4.324-5.639 7.229-10.218 7.229s-8.68-2.89-10.21-7.22z"/>
    <path id="octo" d="m80.641 179.82 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m8.5 4.72 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m5.193 6.14 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m4.72 7.08 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m5.188 6.61 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m7.09 5.66 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m9.91 3.78 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m9.87 0 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m10.01 -1.64 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z"/>
    <path id="drop" d="m69.369 186.12l-3.066 10.683s-.8 3.861 2.84 4.546c3.8-.074 3.486-3.627 3.223-4.781z"/>
  </svg>
</div>

Using jQuery, for instance, you could do:

var _currentFill = "#f00"; // red
$svg = $("#octocat");
$("#face", $svg).attr('style', "fill:"+_currentFill); })

I provided a coloring book demo as an answer to another stackoverflow question: http://bl.ocks.org/4545199. Tested on Safari, Chrome, and Firefox.

Oracle date difference to get number of years

If you just want the difference in years, there's:

SELECT EXTRACT(YEAR FROM date1) - EXTRACT(YEAR FROM date2) FROM mytable

Or do you want fractional years as well?

SELECT (date1 - date2) / 365.242199 FROM mytable

365.242199 is 1 year in days, according to Google.

What Are The Best Width Ranges for Media Queries

Try this one with retina display

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Update

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width: 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
  /* Styles */
}

/* iPad 3 (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPad 3 (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen and (min-width: 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen and (min-width: 1824px) {
  /* Styles */
}

/* iPhone 4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (landscape) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (portrait) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (landscape) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (portrait) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (landscape) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (portrait) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

Add "Are you sure?" to my excel button, how can I?

Just make a custom userform that is shown when the "delete" button is pressed, then link the continue button to the actual code that does the deleting. Make the cancel button hide the userform.

Can you get a Windows (AD) username in PHP?

Check the AUTH_USER request variable. This will be empty if your web app allows anonymous access, but if your server's using basic or Windows integrated authentication, it will contain the username of the authenticated user.

In an Active Directory domain, if your clients are running Internet Explorer and your web server/filesystem permissions are configured properly, IE will silently submit their domain credentials to your server and AUTH_USER will be MYDOMAIN\user.name without the users having to explicitly log in to your web app.

Google Recaptcha v3 example demo

Simple code to implement ReCaptcha v3

The basic JS code

<script src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"></script>
<script>
    grecaptcha.ready(function() {
    // do request for recaptcha token
    // response is promise with passed token
        grecaptcha.execute('your reCAPTCHA site key here', {action:'validate_captcha'})
                  .then(function(token) {
            // add token value to form
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
</script>

The basic HTML code

<form id="form_id" method="post" action="your_action.php">
    <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
    <input type="hidden" name="action" value="validate_captcha">
    .... your fields
</form>

The basic PHP code

if (isset($_POST['g-recaptcha-response'])) {
    $captcha = $_POST['g-recaptcha-response'];
} else {
    $captcha = false;
}

if (!$captcha) {
    //Do something with error
} else {
    $secret   = 'Your secret key here';
    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
    );
    // use json_decode to extract json response
    $response = json_decode($response);

    if ($response->success === false) {
        //Do something with error
    }
}

//... The Captcha is valid you can continue with the rest of your code
//... Add code to filter access using $response . score
if ($response->success==true && $response->score <= 0.5) {
    //Do something to denied access
}

You have to filter access using the value of $response.score. It can takes values from 0.0 to 1.0, where 1.0 means the best user interaction with your site and 0.0 the worst interaction (like a bot). You can see some examples of use in ReCaptcha documentation.

How do I get the offset().top value of an element without using jQuery?

Here is a function that will do it without jQuery:

function getElementOffset(element)
{
    var de = document.documentElement;
    var box = element.getBoundingClientRect();
    var top = box.top + window.pageYOffset - de.clientTop;
    var left = box.left + window.pageXOffset - de.clientLeft;
    return { top: top, left: left };
}

Resize an Array while keeping current elements in Java?

It is not possible to resize an array. However, it is possible change the size of an array through copying the original array to the newly sized one and keep the current elements. The array can also be reduced in size by removing an element and resizing.

import java.util.Arrays 
public class ResizingArray {

    public static void main(String[] args) {

        String[] stringArray = new String[2] //A string array with 2 strings 
        stringArray[0] = "string1";
        stringArray[1] = "string2";

        // increase size and add string to array by copying to a temporary array
        String[] tempStringArray = Arrays.copyOf(stringArray, stringArray.length + 1);
        // Add in the new string 
        tempStringArray[2] = "string3";
        // Copy temp array to original array
        stringArray = tempStringArray;

       // decrease size by removing certain string from array (string1 for example)
       for(int i = 0; i < stringArray.length; i++) {
           if(stringArray[i] == string1) {
               stringArray[i] = stringArray[stringArray.length - 1];
               // This replaces the string to be removed with the last string in the array
               // When the array is resized by -1, The last string is removed 
               // Which is why we copied the last string to the position of the string we wanted to remove
               String[] tempStringArray2 = Arrays.copyOf(arrayString, arrayString.length - 1);
                // Set the original array to the new array
               stringArray = tempStringArray2;
           }
       }
    }    
}

Is it good practice to use the xor operator for boolean checks?

I personally prefer the "boolean1 ^ boolean2" expression due to its succinctness.

If I was in your situation (working in a team), I would strike a compromise by encapsulating the "boolean1 ^ boolean2" logic in a function with a descriptive name such as "isDifferent(boolean1, boolean2)".

For example, instead of using "boolean1 ^ boolean2", you would call "isDifferent(boolean1, boolean2)" like so:

if (isDifferent(boolean1, boolean2))
{
  //do it
}

Your "isDifferent(boolean1, boolean2)" function would look like:

private boolean isDifferent(boolean1, boolean2)
{
    return boolean1 ^ boolean2;
}

Of course, this solution entails the use of an ostensibly extraneous function call, which in itself is subject to Best Practices scrutiny, but it avoids the verbose (and ugly) expression "(boolean1 && !boolean2) || (boolean2 && !boolean1)"!

Adding three months to a date in PHP

Tchoupi's answer can be made a tad less verbose by concatenating the argument for strtotime() as follows:

$effectiveDate = date('Y-m-d', strtotime($effectiveDate . "+3 months") );

(This relies on magic implementation details, but you can always go have a look at them if you're rightly mistrustful.)

How to create a connection string in asp.net c#

Demo :

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

Based on your question:

<connectionStrings>
    <add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
    </connectionStrings>

Refer links:

http://www.connectionstrings.com/store-connection-string-in-webconfig/

Retrive connection string from web.config file:

write the below code in your file where you want;

string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;

SqlConnection con = new SqlConnection(connstring);

or you can go in your way like

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);

Note:

The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)

Export SQL query data to Excel

I see that you’re trying to export SQL data to Excel to avoid copy-pasting your very large data set into Excel.

You might be interested in learning how to export SQL data to Excel and update the export automatically (with any SQL database: MySQL, Microsoft SQL Server, PostgreSQL).

To export data from SQL to Excel, you need to follow 2 steps:

  • Step 1: Connect Excel to your SQL database? (Microsoft SQL Server, MySQL, PostgreSQL...)
  • Step 2: Import your SQL data into Excel

The result will be the list of tables you want to query data from your SQL database into Excel:

?

Step1: Connect Excel to an external data source: your SQL database

  1. Install An ODBC
  2. Install A Driver
  3. Avoid A Common Error
  4. Create a DSN

Step 2: Import your SQL data into Excel

  1. Click Where You Want Your Pivot Table
  2. Click Insert
  3. Click Pivot Table
  4. Click Use an external data source, then Choose Connection
  5. Click on the System DSN tab
  6. Select the DSN created in ODBC Manager
  7. Fill the requested username and password
  8. Avoid a Common Error
  9. Access The Microsoft Query Dialog Box
  10. Click on the arrow to see the list of tables in your database
  11. Select the table you want to query data from your SQL database into Excel
  12. Click on Return Data when you’re done with your selection

To update the export automatically, there are 2 additional steps:

  1. Create a Pivot Table with an external SQL data source
  2. Automate Your SQL Data Update In Excel With The GETPIVOTDATA Function

I’ve created a step-by-step tutorial about this whole process, from connecting Excel to SQL, up to having the whole thing automatically updated. You might find the detailed explanations and screenshots useful.

Should MySQL have its timezone set to UTC?

How about making your app agnostic of the server's timezone?

Owing to any of these possible scenarios:

  • You might not have control over the web/database server's timezone settings
  • You might mess up and set the settings incorrectly
  • There are so many settings as described in the other answers, and so many things to keep track of, that you might miss something
  • An update on the server, or a software reset, or another admin, might unknowing reset the servers' timezone to the default - thus breaking your application

All of the above scenarios give rise to breaking of your application's time calculations. Thus it appears that the better approach is to make your application work independent of the server's timezone.

The idea is simply to always create dates in UTC before storing them into the database, and always re-create them from the stored values in UTC as well. This way, the time calculations won't ever be incorrect, because they're always in UTC. This can be achieved by explicity stating the DateTimeZone parameter when creating a PHP DateTime object.

On the other hand, the client side functionality can be configured to convert all dates/times received from the server to the client's timezone. Libraries like moment.js make this super easy to do.

For example, when storing a date in the database, instead of using the NOW() function of MySQL, create the timestamp string in UTC as follows:

// Storing dates
$date = new DateTime('now', new DateTimeZone('UTC'));
$sql = 'insert into table_name (date_column) values ("' . $date . '")';

// Retreiving dates
$sql = 'select date_column from table_name where condition';
$dateInUTC = new DateTime($date_string_from_db, new DateTimeZone('UTC'));

You can set the default timezone in PHP for all dates created, thus eliminating the need to initialize the DateTimeZone class every time you want to create a date.

What's a good hex editor/viewer for the Mac?

There are probably better options, but I use and kind of like TextWrangler for basic hex editing. File -> hex Dump File

ArrayAdapter in android to create simple listview

public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)

Here, resource means the 'id' of the Layout you are using while instantiating the view.

Now, this layout has many child views with their own ids. So, textViewResourceId tells which child view we need to populate with the data.

Sending emails with Javascript

Send request to mandrillapp.com:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        console.log(xhttp.responseText);
    }
}
xhttp.open('GET', 'https://mandrillapp.com/api/1.0/messages/send.json?message[from_email][email protected]&message[to][0][email][email protected]&message[subject]=??????%20?%207995.by&message[html]=xxxxxx&key=oxddROOvCpKCp6InvVDqiGw', true);
xhttp.send();

CSS Pseudo-classes with inline styles

No, this is not possible. In documents that make use of CSS, an inline style attribute can only contain property declarations; the same set of statements that appears in each ruleset in a stylesheet. From the Style Attributes spec:

The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces), whose formal grammar is given below in the terms and conventions of the CSS core grammar:

declaration-list
  : S* declaration? [ ';' S* declaration? ]*
  ;

Neither selectors (including pseudo-elements), nor at-rules, nor any other CSS construct are allowed.

Think of inline styles as the styles applied to some anonymous super-specific ID selector: those styles only apply to that one very element with the style attribute. (They take precedence over an ID selector in a stylesheet too, if that element has that ID.) Technically it doesn't work like that; this is just to help you understand why the attribute doesn't support pseudo-class or pseudo-element styles (it has more to do with how pseudo-classes and pseudo-elements provide abstractions of the document tree that can't be expressed in the document language).

Note that inline styles participate in the same cascade as selectors in rule sets, and take highest precedence in the cascade (!important notwithstanding). So they take precedence even over pseudo-class states. Allowing pseudo-classes or any other selectors in inline styles would possibly introduce a new cascade level, and with it a new set of complications.

Note also that very old revisions of the Style Attributes spec did originally propose allowing this, however it was scrapped, presumably for the reason given above, or because implementing it was not a viable option.

In Perl, how can I read an entire file into a string?

These are all good answers. BUT if you're feeling lazy, and the file isn't that big, and security is not an issue (you know you don't have a tainted filename), then you can shell out:

$x=`cat /tmp/foo`;    # note backticks, qw"cat ..." also works

Can an AJAX response set a cookie?

Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

<?php

$lurl=get_fcontent("http://ip2.cc/?api=cname&ip=84.228.229.81");
echo"cid:".$lurl[0]."<BR>";


function get_fcontent( $url,  $javascript_loop = 0, $timeout = 5 ) {
    $url = str_replace( "&amp;", "&", urldecode(trim($url)) );

    $cookie = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $ch, CURLOPT_ENCODING, "" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    # required for https urls
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
    $content = curl_exec( $ch );
    $response = curl_getinfo( $ch );
    curl_close ( $ch );

    if ($response['http_code'] == 301 || $response['http_code'] == 302) {
        ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");

        if ( $headers = get_headers($response['url']) ) {
            foreach( $headers as $value ) {
                if ( substr( strtolower($value), 0, 9 ) == "location:" )
                    return get_url( trim( substr( $value, 9, strlen($value) ) ) );
            }
        }
    }

    if (    ( preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value) ) && $javascript_loop < 5) {
        return get_url( $value[1], $javascript_loop+1 );
    } else {
        return array( $content, $response );
    }
}


?>

I want to vertical-align text in select box

Try to set the "line-height" attribute

Like this:

select{
    height: 28px !important;
    line-height: 28px;
}

Here you are some documentation about this attribute:

http://www.w3.org/wiki/CSS/Properties/line-height

http://www.w3schools.com/cssref/pr_dim_line-height.asp

Tooltip with HTML content without JavaScript

I have made a little example using css

_x000D_
_x000D_
.hover {_x000D_
  position: relative;_x000D_
  top: 50px;_x000D_
  left: 50px;_x000D_
}_x000D_
_x000D_
.tooltip {_x000D_
  /* hide and position tooltip */_x000D_
  top: -10px;_x000D_
  background-color: black;_x000D_
  color: white;_x000D_
  border-radius: 5px;_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
  -webkit-transition: opacity 0.5s;_x000D_
  -moz-transition: opacity 0.5s;_x000D_
  -ms-transition: opacity 0.5s;_x000D_
  -o-transition: opacity 0.5s;_x000D_
  transition: opacity 0.5s;_x000D_
}_x000D_
_x000D_
.hover:hover .tooltip {_x000D_
  /* display tooltip on hover */_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div class="hover">hover_x000D_
  <div class="tooltip">asdadasd_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

FIDDLE

http://jsfiddle.net/8gC3D/471/

How to get current relative directory of your Makefile?

Here is one-liner to get absolute path to your Makefile file using shell syntax:

SHELL := /bin/bash
CWD := $(shell cd -P -- '$(shell dirname -- "$0")' && pwd -P)

And here is version without shell based on @0xff answer:

CWD := $(abspath $(patsubst %/,%,$(dir $(abspath $(lastword $(MAKEFILE_LIST))))))

Test it by printing it, like:

cwd:
        @echo $(CWD)

How to split a String by space

Very Simple Example below:

Hope it helps.

String str = "Hello I'm your String";
String[] splited = str.split(" ");
var splited = str.split(" ");
var splited1=splited[0]; //Hello
var splited2=splited[1]; //I'm
var splited3=splited[2]; //your
var splited4=splited[3]; //String

Get pixel color from canvas, on mousemove

calling getImageData every time will slow the process ... to speed up things i recommend store image data and then you can get pix value easily and quickly, so do something like this for better performance

// keep it global
let imgData = false;  // initially no image data we have

// create some function block 
if(imgData === false){   
  // fetch once canvas data     
  var ctx = canvas.getContext("2d");
  imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
}
    // Prepare your X Y coordinates which you will be fetching from your mouse loc
    let x = 100;   // 
    let y = 100;
    // locate index of current pixel
    let index = (y * imgData.width + x) * 4;

        let red = imgData.data[index];
        let green = imgData.data[index+1];
        let blue = imgData.data[index+2];
        let alpha = imgData.data[index+3];
   // Output
   console.log('pix x ' + x +' y '+y+ ' index '+index +' COLOR '+red+','+green+','+blue+','+alpha);

Search a text file and print related lines in Python?

Note the potential for an out-of-range index with "i+3". You could do something like:

with open("file.txt", "r") as f:
    searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        k=min(i+3,j)
        for l in searchlines[i:k]: print l,
        print

Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.

vertical-align image in div

you don't need define positioning when you need vertical align center for inline and block elements you can take mentioned below idea:-

inline-elements :- <img style="vertical-align:middle" ...>
                   <span style="display:inline-block; vertical-align:middle"> foo<br>bar </span>  

block-elements :- <td style="vertical-align:middle"> ... </td>
                  <div style="display:table-cell; vertical-align:middle"> ... </div>

see the demo:- http://jsfiddle.net/Ewfkk/2/

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.

If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.

SQL Server : export query as a .txt file

You can use windows Powershell to execute a query and output it to a text file

Invoke-Sqlcmd -Query "Select * from database" -ServerInstance "Servername\SQL2008" -Database "DbName" > c:\Users\outputFileName.txt

Find common substring between two strings

In case we have a list of words that we need to find all common substrings I check some of the codes above and the best was https://stackoverflow.com/a/42882629/8520109 but it has some bugs for example 'histhome' and 'homehist'. In this case, we should have 'hist' and 'home' as a result. Furthermore, it differs if the order of arguments is changed. So I change the code to find every block of substring and it results a set of common substrings:

main = input().split(" ")    #a string of words separated by space
def longestSubstringFinder(string1, string2):
    '''Find the longest matching word'''
    answer = ""
    len1, len2 = len(string1), len(string2)
    for i in range(len1):
        for j in range(len2):
            lcs_temp=0
            match=''
            while ((i+lcs_temp < len1) and (j+lcs_temp<len2) and string1[i+lcs_temp] == string2[j+lcs_temp]):
                match += string2[j+lcs_temp]
                lcs_temp+=1         
            if (len(match) > len(answer)):
                answer = match              
    return answer

def listCheck(main):
    '''control the input for finding substring in a list of words'''
    string1 = main[0]
    result = []
    for i in range(1, len(main)):
        string2 = main[i]
        res1 = longestSubstringFinder(string1, string2)
        res2 = longestSubstringFinder(string2, string1)
        result.append(res1)
        result.append(res2)
    result.sort()
    return result

first_answer = listCheck(main)

final_answer  = []


for item1 in first_answer:    #to remove some incorrect match
    string1 = item1
    double_check = True
    for item2 in main:
        string2 = item2
        if longestSubstringFinder(string1, string2) != string1:
            double_check = False
    if double_check:
        final_answer.append(string1)

print(set(final_answer))

main = 'ABACDAQ BACDAQA ACDAQAW XYZCDAQ' #>>> {'CDAQ'}
main = 'homehist histhome' #>>> {'hist', 'home'}

Failed to Connect to MySQL at localhost:3306 with user root

I had this exact problem after my last windows update and none of the above solutions worked. I know it's an old question, but if anyone has this problem in the future:

I managed to solve it by going to windows control panel > administrative tools > Component Services and finding "MySQL57" in the Services(local) list (I assume your server might have a slightly different name).

There I went to properties by right clicking and changed the Startup Type to Automatic under the General tab. Then I went on the Log On tab and checked "Allow Service to interact with Desktop".

If none of that works, you can try checking the "This account" box and filling both password fields with the root password you set up after installing the server (leave account blank).

I know it's a lot to do and most of these steps must be innefective, but I did it all at once and frankly have no clue which one solved the problem. Good luck I hope it helps.

Python memory usage of numpy arrays

You can use array.nbytes for numpy arrays, for example:

>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192

Javascript - User input through HTML input tag to set a Javascript variable?

When your script is running, it blocks the page from doing anything. You can work around this with one of two ways:

  • Use var foo = prompt("Give me input");, which will give you the string that the user enters into a popup box (or null if they cancel it)
  • Split your code into two function - run one function to set up the user interface, then provide the second function as a callback that gets run when the user clicks the button.

Find JavaScript function definition in Chrome

2016 Update: in Chrome Version 51.0.2704.103

There is a Go to member shortcut (listed in settings > shortcut > Text Editor). Open the file containing your function (in the sources panel of the DevTools) and press:

ctrl + shift + O

or in OS X:

? + shift + O

This enables to list and reach members of the current file.

Looping through JSON with node.js

You may also want to use hasOwnProperty in the loop.

for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        switch (prop) {
            // obj[prop] has the value
        }
    }
}

node.js is single-threaded which means your script will block whether you want it or not. Remember that V8 (Google's Javascript engine that node.js uses) compiles Javascript into machine code which means that most basic operations are really fast and looping through an object with 100 keys would probably take a couple of nanoseconds?

However, if you do a lot more inside the loop and you don't want it to block right now, you could do something like this

switch (prop) {
    case 'Timestamp':
        setTimeout(function() { ... }, 5);
        break;
    case 'Start_Value':
        setTimeout(function() { ... }, 10);
        break;
}

If your loop is doing some very CPU intensive work, you will need to spawn a child process to do that work or use web workers.

What is the purpose of global.asax in asp.net

MSDN has an outline of the purpose of the global.asax file.

Effectively, global.asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occuring, without having to try and shoe-horn that code into each and every page of your site.

You can use it by by choosing Add > New Item > Global Application Class in Visual Studio. Once you've added the file, you can add code under any of the events that are listed (and created by default, at least in Visual Studio 2008):

  • Application_Start
  • Application_End
  • Session_Start
  • Session_End
  • Application_BeginRequest
  • Application_AuthenticateRequest
  • Application_Error

There are other events that you can also hook into, such as "LogRequest".

How to get complete current url for Cakephp

for cakephp3+:

$url = $this->request->scheme().'://'.$this->request->domain().$this->request->here(false);

will get eg: http://bgq.dev/home/index?t44=333

How to calculate the sum of all columns of a 2D numpy array (efficiently)

a.sum(0)

should solve the problem. It is a 2d np.array and you will get the sum of all column. axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

How can I display an image from a file in Jupyter Notebook?

from IPython.display import Image

Image(filename =r'C:\user\path')

I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory. this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

What is SuppressWarnings ("unchecked") in Java?

In Java, generics are implemented by means of type erasure. For instance, the following code.

List<String> hello = List.of("a", "b");
String example = hello.get(0);

Is compiled to the following.

List hello = List.of("a", "b");
String example = (String) hello.get(0);

And List.of is defined as.

static <E> List<E> of(E e1, E e2);

Which after type erasure becomes.

static List of(Object e1, Object e2);

The compiler has no idea what are generic types at runtime, so if you write something like this.

Object list = List.of("a", "b");
List<Integer> actualList = (List<Integer>) list;

Java Virtual Machine has no idea what generic types are while running a program, so this compiles and runs, as for Java Virtual Machine, this is a cast to List type (this is the only thing it can verify, so it verifies only that).

But now add this line.

Integer hello = actualList.get(0);

And JVM will throw an unexpected ClassCastException, as Java compiler inserted an implicit cast.

java.lang.ClassCastException: java.base/java.lang.String cannot be cast to java.base/java.lang.Integer

An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.

Why would you want to do that? Java type system isn't good enough to represent all possible type usage patterns. Sometimes you may know that a cast is safe, but Java doesn't provide a way to say so - to hide warnings like this, @SupressWarnings("unchecked") can be used, so that a programmer can focus on real warnings. For instance, Optional.empty() returns a singleton to avoid allocation of empty optionals that don't store a value.

private static final Optional<?> EMPTY = new Optional<>();
public static<T> Optional<T> empty() {
    @SuppressWarnings("unchecked")
    Optional<T> t = (Optional<T>) EMPTY;
    return t;
}

This cast is safe, as the value stored in an empty optional cannot be retrieved so there is no risk of unexpected class cast exceptions.

Checking for multiple conditions using "when" on single task in ansible

You can use like this.

when: condition1 == "condition1" or condition2 == "condition2"

Link to official docs: The When Statement.

Also Please refer to this gist: https://gist.github.com/marcusphi/6791404

Setting custom UITableViewCells height

To set automatic dimension for row height & estimated row height, ensure following steps to make, auto dimension effective for cell/row height layout.

  • Assign and implement tableview dataSource and delegate
  • Assign UITableViewAutomaticDimension to rowHeight & estimatedRowHeight
  • Implement delegate/dataSource methods (i.e. heightForRowAt and return a value UITableViewAutomaticDimension to it)

-

Objective C:

// in ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

  @property IBOutlet UITableView * table;

@end

// in ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    self.table.dataSource = self;
    self.table.delegate = self;

    self.table.rowHeight = UITableViewAutomaticDimension;
    self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewAutomaticDimension;
}

Swift:

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Don't forget to set dataSource and delegate for table
    table.dataSource = self
    table.delegate = self

    // Set automatic dimensions for row height
    table.rowHeight = UITableViewAutomaticDimension
    table.estimatedRowHeight = UITableViewAutomaticDimension
}



// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

For label instance in UITableviewCell

  • Set number of lines = 0 (& line break mode = truncate tail)
  • Set all constraints (top, bottom, right left) with respect to its superview/ cell container.
  • Optional: Set minimum height for label, if you want minimum vertical area covered by label, even if there is no data.

enter image description here

Note: If you've more than one labels (UIElements) with dynamic length, which should be adjusted according to its content size: Adjust 'Content Hugging and Compression Resistance Priority` for labels which you want to expand/compress with higher priority.

Here in this example I set low hugging and high compression resistance priority, that leads to set more priority/importance for contents of second (yellow) label.

enter image description here

socket programming multiple client to one server

This is the echo server handling multiple clients... Runs fine and good using Threads

// echo server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class Server_X_Client {
public static void main(String args[]){


    Socket s=null;
    ServerSocket ss2=null;
    System.out.println("Server Listening......");
    try{
        ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined

    }
    catch(IOException e){
    e.printStackTrace();
    System.out.println("Server error");

    }

    while(true){
        try{
            s= ss2.accept();
            System.out.println("connection Established");
            ServerThread st=new ServerThread(s);
            st.start();

        }

    catch(Exception e){
        e.printStackTrace();
        System.out.println("Connection Error");

    }
    }

}

}

class ServerThread extends Thread{  

    String line=null;
    BufferedReader  is = null;
    PrintWriter os=null;
    Socket s=null;

    public ServerThread(Socket s){
        this.s=s;
    }

    public void run() {
    try{
        is= new BufferedReader(new InputStreamReader(s.getInputStream()));
        os=new PrintWriter(s.getOutputStream());

    }catch(IOException e){
        System.out.println("IO error in server thread");
    }

    try {
        line=is.readLine();
        while(line.compareTo("QUIT")!=0){

            os.println(line);
            os.flush();
            System.out.println("Response to Client  :  "+line);
            line=is.readLine();
        }   
    } catch (IOException e) {

        line=this.getName(); //reused String line for getting thread name
        System.out.println("IO Error/ Client "+line+" terminated abruptly");
    }
    catch(NullPointerException e){
        line=this.getName(); //reused String line for getting thread name
        System.out.println("Client "+line+" Closed");
    }

    finally{    
    try{
        System.out.println("Connection Closing..");
        if (is!=null){
            is.close(); 
            System.out.println(" Socket Input Stream Closed");
        }

        if(os!=null){
            os.close();
            System.out.println("Socket Out Closed");
        }
        if (s!=null){
        s.close();
        System.out.println("Socket Closed");
        }

        }
    catch(IOException ie){
        System.out.println("Socket Close Error");
    }
    }//end finally
    }
}

Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..

// A simple Client Server Protocol .. Client for Echo Server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class NetworkClient {

public static void main(String args[]) throws IOException{


    InetAddress address=InetAddress.getLocalHost();
    Socket s1=null;
    String line=null;
    BufferedReader br=null;
    BufferedReader is=null;
    PrintWriter os=null;

    try {
        s1=new Socket(address, 4445); // You can use static final constant PORT_NUM
        br= new BufferedReader(new InputStreamReader(System.in));
        is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
        os= new PrintWriter(s1.getOutputStream());
    }
    catch (IOException e){
        e.printStackTrace();
        System.err.print("IO Exception");
    }

    System.out.println("Client Address : "+address);
    System.out.println("Enter Data to echo Server ( Enter QUIT to end):");

    String response=null;
    try{
        line=br.readLine(); 
        while(line.compareTo("QUIT")!=0){
                os.println(line);
                os.flush();
                response=is.readLine();
                System.out.println("Server Response : "+response);
                line=br.readLine();

            }



    }
    catch(IOException e){
        e.printStackTrace();
    System.out.println("Socket read Error");
    }
    finally{

        is.close();os.close();br.close();s1.close();
                System.out.println("Connection Closed");

    }

}
}

python pandas remove duplicate columns

Note that Gene Burinsky's answer (at the time of writing the selected answer) keeps the first of each duplicated column. To keep the last:

df=df.loc[:, ~df.columns[::-1].duplicated()[::-1]]

How do I convert a file path to a URL in ASP.NET

this is what i use:

private string MapURL(string path)
{
    string appPath = Server.MapPath("/").ToLower();
    return string.Format("/{0}", path.ToLower().Replace(appPath, "").Replace(@"\", "/"));
 }

Media Queries: How to target desktop, tablet, and mobile?

It's not a matter of pixels count, it's a matter of actual size (in mm or inches) of characters on the screen, which depends on pixels density. Hence "min-width:" and "max-width:" are useless. A full explanation of this issue is here: what exactly is device pixel ratio?

"@media" queries take into account the pixels count and the device pixel ratio, resulting in a "virtual resolution" which is what you have to actually take into account while designing your page: if your font is 10px fixed-width and the "virtual horizontal resolution" is 300 px, 30 characters will be needed to fill a line.

Converting a sentence string to a string array of words in Java

Following is a code snippet which splits a sentense to word and give its count too.

 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;

 public class StringToword {
public static void main(String[] args) {
    String s="a a a A A";
    String[] splitedString=s.split(" ");
    Map m=new HashMap();
    int count=1;
    for(String s1 :splitedString){
         count=m.containsKey(s1)?count+1:1;
          m.put(s1, count);
        }
    Iterator<StringToword> itr=m.entrySet().iterator();
    while(itr.hasNext()){
        System.out.println(itr.next());         
    }
    }

}

How to get the last value of an ArrayList

A one liner that takes into account empty lists would be:

T lastItem = list.size() == 0 ? null : list.get(list.size() - 1);

Or if you don't like null values (and performance isn't an issue):

Optional<T> lastItem = list.stream().reduce((first, second) -> second);

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

Windows- Pyinstaller Error "failed to execute script " When App Clicked

That error is due to missing of modules in pyinstaller. You can find the missing modules by running script in executable command line, i.e., by removing '-w' from the command. Once you created the command line executable file then in command line it will show the missing modules. By finding those missing modules you can add this to your command : " --hidden-import = missingmodule "

I solved my problem through this.

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

Your use of it isn't a hack, though like many things in C++, mutable can be hack for a lazy programmer who doesn't want to go all the way back and mark something that shouldn't be const as non-const.

ALTER TABLE to add a composite primary key

ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);

How to Create a circular progressbar in Android which rotates on it?

Good news is that now material design library supports determinate circular progress bars too:

<com.google.android.material.progressindicator.CircularProgressIndicator
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

For more info about this refer here.

REST / SOAP endpoints for a WCF service

We must define the behavior configuration to REST endpoint

<endpointBehaviors>
  <behavior name="restfulBehavior">
   <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
  </behavior>
</endpointBehaviors>

and also to a service

<serviceBehaviors>
   <behavior>
     <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
   </behavior>
</serviceBehaviors>

After the behaviors, next step is the bindings. For example basicHttpBinding to SOAP endpoint and webHttpBinding to REST.

<bindings>
   <basicHttpBinding>
     <binding name="soapService" />
   </basicHttpBinding>
   <webHttpBinding>
     <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
   </webHttpBinding>
</bindings>

Finally we must define the 2 endpoint in the service definition. Attention for the address="" of endpoint, where to REST service is not necessary nothing.

<services>
  <service name="ComposerWcf.ComposerService">
    <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
  </service>
</services>

In Interface of the service we define the operation with its attributes.

namespace ComposerWcf.Interface
{
    [ServiceContract]
    public interface IComposerService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "/autenticationInfo/{app_id}/{access_token}", ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        Task<UserCacheComplexType_RootObject> autenticationInfo(string app_id, string access_token);
    }
}

Joining all parties, this will be our WCF system.serviceModel definition.

<system.serviceModel>

  <behaviors>
    <endpointBehaviors>
      <behavior name="restfulBehavior">
        <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
  </behaviors>

  <bindings>
    <basicHttpBinding>
      <binding name="soapService" />
    </basicHttpBinding>
    <webHttpBinding>
      <binding name="jsonp" crossDomainScriptAccessEnabled="true" />
    </webHttpBinding>
  </bindings>

  <protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
  </protocolMapping>

  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

  <services>
    <service name="ComposerWcf.ComposerService">
      <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
    </service>
  </services>

</system.serviceModel>

To test the both endpoint, we can use WCFClient to SOAP and PostMan to REST.

how to get the first and last days of a given month

You might want to look at the strtotime and date functions.

<?php

$query_date = '2010-02-04';

// First day of the month.
echo date('Y-m-01', strtotime($query_date));

// Last day of the month.
echo date('Y-m-t', strtotime($query_date));

Effective method to hide email from spam bots

First I would make sure the email address only shows when you have javascript enabled. This way, there is no plain text that can be read without javascript.

Secondly, A way of implementing a safe feature is by staying away from the <button> tag. This tag needs a text insert between the tags, which makes it computer-readable. Instead try the <input type="button"> with a javascript handler for an onClick. Then use all of the techniques mentioned by otherse to implement a safe email notation.

One other option is to have a button with "Click to see emailaddress". Once clicked this changes into a coded email (the characters in HTML codes). On another click this redirects to the 'mailto:email' function

An uncoded version of the last idea, with selectable and non-selectable email addresses:

<html>
<body>
<script type="text/javascript">
      e1="@domain";
      e2="me";
      e3=".extension";
email_link="mailto:"+e2+e1+e3;
</script>
<input type="text" onClick="this.onClick=window.open(email_link);" value="Click for mail"/>
<input type="text" onClick="this.value=email;" value="Click for mail-address"/>
<input type="button" onClick="this.onClick=window.open(email_link);" value="Click for mail"/>
<input type="button" onClick="this.value=email;" value="Click for mail-address"/>
</body></html>

See if this is something you would want and combine it with others' ideas. You can never be too sure.

Convert 4 bytes to int

The following code reads 4 bytes from array (a byte[]) at position index and returns a int. I tried out most of the code from the other answers on Java 10 and some other variants I dreamed up.

This code used the least amount of CPU time but allocates a ByteBuffer until Java 10's JIT gets rid of the allocation.

int result;

result = ByteBuffer.
   wrap(array).
   getInt(index);

This code is the best performing code that does not allocate anything. Unfortunately, it consumes 56% more CPU time compared to the above code.

int result;
short data0, data1, data2, data3;

data0  = (short) (array[index++] & 0x00FF);
data1  = (short) (array[index++] & 0x00FF);
data2  = (short) (array[index++] & 0x00FF);
data3  = (short) (array[index++] & 0x00FF);
result = (data0 << 24) | (data1 << 16) | (data2 << 8) | data3;

Convert date to day name e.g. Mon, Tue, Wed

Your code works for me

$date = '15-12-2016';
$nameOfDay = date('D', strtotime($date));
echo $nameOfDay;

Use l instead of D, if you prefer the full textual representation of the name

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

In Kotlin, you can do:

ContextCompat.getColor(requireContext(), R.color.stage_hls_fallback_snackbar)

if requireContext() is accessible from where you are calling the function. I was getting an error when trying

ContextCompat.getColor(context, R.color.stage_hls_fallback_snackbar)

How to get first character of string?

You can even use slice to cut-off all other characters:

x.slice(0, 1);

Meaning of delta or epsilon argument of assertEquals for double values

Epsilon is the value that the 2 numbers can be off by. So it will assert to true as long as Math.abs(expected - actual) < epsilon

How to update a claim in ASP.NET Identity?

You can create a new ClaimsIdentity and then do the claims update with such.

set {
    // get context of the authentication manager
    var authenticationManager = HttpContext.GetOwinContext().Authentication;

    // create a new identity from the old one
    var identity = new ClaimsIdentity(User.Identity);

    // update claim value
    identity.RemoveClaim(identity.FindFirst("AccountNo"));
    identity.AddClaim(new Claim("AccountNo", value));

    // tell the authentication manager to use this new identity
    authenticationManager.AuthenticationResponseGrant = 
        new AuthenticationResponseGrant(
            new ClaimsPrincipal(identity),
            new AuthenticationProperties { IsPersistent = true }
        );
}

Copy Image from Remote Server Over HTTP

make folder and name it foe example download open note pad and insert this code

only change http://www.google.com/aa.zip to your file and save it to m.php for example

chamod the php file to 666 and the folder download to 777

<?php
define('BUFSIZ', 4095);
$url = 'http://www.google.com/aa.zip';
$rfile = fopen($url, 'r');
$lfile = fopen(basename($url), 'w');
while(!feof($rfile))
fwrite($lfile, fread($rfile, BUFSIZ), BUFSIZ);
fclose($rfile);
fclose($lfile);
?>

finally from your browser enter to these URL http://www.example.com/download/m.php

you will see in download folder the file download from other server

thanks

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

Changing every value in a hash in Ruby

A bit more readable one, map it to an array of single-element hashes and reduce that with merge

the_hash.map{ |key,value| {key => "%#{value}%"} }.reduce(:merge)

Failed to load ApplicationContext from Unit Test: FileNotFound

Give the below

@ContextConfiguration(locations =  {"classpath*:/spring/test-context.xml"})

And in pom.xml give the following plugin:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-surefire-plugin</artifactId>
   <version>2.20.1</version>
<configuration>
    <additionalClasspathElements>
       <additionalClasspathElement>${basedir}/src/test/resources</additionalClasspathElement>
    </additionalClasspathElements>
</configuration>

Pointer to class data member "::*"

I think you'd only want to do this if the member data was pretty large (e.g., an object of another pretty hefty class), and you have some external routine which only works on references to objects of that class. You don't want to copy the member object, so this lets you pass it around.

For Loop on Lua

Your problem is simple:

names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
  print (names)
end

This code first declares a global variable called names. Then, you start a for loop. The for loop declares a local variable that just happens to be called names too; the fact that a variable had previously been defined with names is entirely irrelevant. Any use of names inside the for loop will refer to the local one, not the global one.

The for loop says that the inner part of the loop will be called with names = 1, then names = 2, and finally names = 3. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.

What you actually wanted was something like this:

names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
  print (names[nameCount])
end

The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).

Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.

However, this has a flaw. What happens if you remove one of the elements from the list?

names = {'John', 'Joe'}
for nameCount = 1, 3 do
  print (names[nameCount])
end

Now, we get John Joe nil, because attempting to access values from a table that don't exist results in nil. To prevent this, we need to count from 1 to the length of the table:

names = {'John', 'Joe'}
for nameCount = 1, #names do
  print (names[nameCount])
end

The # is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names gets, this will always work.

However, there is a more convenient way to iterate through an array of items:

names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
  print (name)
end

ipairs is a Lua standard function that iterates over a list. This style of for loop, the iterator for loop, uses this kind of iterator function. The i value is the index of the entry in the array. The name value is the value at that index. So it basically does a lot of grunt work for you.

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

I have tried so many approches! the only useful thing is:

if var topController = UIApplication.shared.keyWindow?.rootViewController
{
  while (topController.presentedViewController != nil)
  {
    topController = topController.presentedViewController!
  }
}

Debug JavaScript in Eclipse

I tried to get aptana running on my ubuntu 10.4. Unfortunately I didn't succeed. Chrome on the other hand, has an eclipse plugin that lets you debug javascript that's running in a chrome instance. Works very well. YOu'll have to install the eclipse plugin you'll find here:

http://code.google.com/p/chromedevtools/

Set Breakpoints in the javascript sources you edit in eclipse and browser your page in chrome. As soon as a javascript breakpoint is hit, the eclipse debugger halts and lets you step into, step over, browse the variables etc. Very nice!

input type="submit" Vs button tag are they interchangeable?

http://www.w3.org/TR/html4/interact/forms.html#h-17.5

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.

So for functionality only they're interchangeable!

(Don't forget, type="submit" is the default with button, so leave it off!)

javax.persistence.NoResultException: No entity found for query

String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
DrawUnusedBalance drawUnusedBalance = em.unwrap(Session.class)
    .createQuery(hql, DrawUnusedBalance.class)
    .setParameter("today",new LocalDate())
    .uniqueResultOptional()
    .orElseThrow(NotFoundException::new);

Search text in fields in every table of a MySQL database

I am use HeidiSQL is a useful and reliable tool designed for web developers using the popular MySQL server.

In HeidiSQL you can push shift + ctrl + f and you can find text on the server in all tables. This option is very usefully.

LINQ Using Max() to select a single row

You can also do:

(from u in table
orderby u.Status descending
select u).Take(1);

replace anchor text with jquery

$('#link1').text("Replacement text");

The .text() method drops the text you pass it into the element content. Unlike using .html(), .text() implicitly ignores any embedded HTML markup, so if you need to embed some inline <span>, <i>, or whatever other similar elements, use .html() instead.

Redirect on select option in select box

Because the first option is already selected, the change event is never fired. Add an empty value as the first one and check for empty in the location assignment.

Here's an example:

https://jsfiddle.net/bL5sq/

_x000D_
_x000D_
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">_x000D_
  <option value="">Select...</option>_x000D_
  <option value="https://google.com">Google</option>_x000D_
  <option value="https://yahoo.com">Yahoo</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to copy Docker images from one host to another without using a repository

First save the Docker image to a zip file:

docker save <docker image name> | gzip > <docker image name>.tar.gz

Then load the exported image to Docker using the below command:

zcat <docker image name>.tar.gz | docker load

Mocking python function based on input arguments

Just to show another way of doing it:

def mock_isdir(path):
    return path in ['/var/log', '/var/log/apache2', '/var/log/tomcat']

with mock.patch('os.path.isdir') as os_path_isdir:
    os_path_isdir.side_effect = mock_isdir

How do I make an http request using cookies on Android?

A cookie is just another HTTP header. You can always set it while making a HTTP call with the apache library or with HTTPUrlConnection. Either way you should be able to read and set HTTP cookies in this fashion.

You can read this article for more information.

I can share my peace of code to demonstrate how easy you can make it.

public static String getServerResponseByHttpGet(String url, String token) {

        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            get.setHeader("Cookie", "PHPSESSID=" + token + ";");
            Log.d(TAG, "Try to open => " + url);

            HttpResponse httpResponse = client.execute(get);
            int connectionStatusCode = httpResponse.getStatusLine().getStatusCode();
            Log.d(TAG, "Connection code: " + connectionStatusCode + " for request: " + url);

            HttpEntity entity = httpResponse.getEntity();
            String serverResponse = EntityUtils.toString(entity);
            Log.d(TAG, "Server response for request " + url + " => " + serverResponse);

            if(!isStatusOk(connectionStatusCode))
                return null;

            return serverResponse;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

Best way to convert list to comma separated string in java

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here

Import PEM into Java Key Store

I used Keystore Explorer

  1. Open JKS with a private key
  2. Examine signed PEM from CA
  3. Import key
  4. Save JKS

Similarity String Comparison in Java

This is typically done using an edit distance measure. Searching for "edit distance java" turns up a number of libraries, like this one.

Jquery insert new row into table at a certain index

Adding on to Nick Craver's answer and also considering the point raised by rossisdead, if scenario exists like one has to append to an empty table, or before a certain row, I have done like this:

var arr = []; //array
if (your condition) {
  arr.push(row.id); //push row's id for eg: to the array
  idx = arr.sort().indexOf(row.id);

  if (idx === 0) {   
    if (arr.length === 1) {  //if array size is only 1 (currently pushed item)
        $("#tableID").append(row);
    }
    else {       //if array size more than 1, but index still 0, meaning inserted row must be the first row
       $("#tableID tr").eq(idx + 1).before(row);
    }   
  }          
  else {     //if index is greater than 0, meaning inserted row to be after specified index row
      $("#tableID tr").eq(idx).after(row);
  }    
}

Hope it helps someone.