Programs & Examples On #Testing strategies

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

How do I view / replay a chrome network debugger har file saved with content?

Chrome Dev Tool's "Network" tool now allows you to import HAR files by drag-and-dropping into the window.

How and when to use ‘async’ and ‘await’

Async / Await

Actually Async / Await are a pair of keywords which are just syntactic sugar for creating a callback of an asynchronous task.

Take by example this operation:

    public static void DoSomeWork()
    {
        var task = Task.Run(() =>
        {
            // [RUNS ON WORKER THREAD]

            // IS NOT bubbling up due to the different threads
            throw new Exception();
            Thread.Sleep(2000);

            return "Hello";
        });

        // This is the callback
        task.ContinueWith((t) => {
            // -> Exception is swallowed silently
            Console.WriteLine("Completed");

            // [RUNS ON WORKER THREAD]
        });
    }

The code above has several disadvantages. Errors are not passed on and it's hard to read. But Async and Await come in to help us out:

    public async static void DoSomeWork()
    {
        var result = await Task.Run(() =>
        {
            // [RUNS ON WORKER THREAD]

            // IS bubbling up
            throw new Exception();
            Thread.Sleep(2000);

            return "Hello";
        });

        // every thing below is a callback 
        // (including the calling methods)

        Console.WriteLine("Completed");

    }

Await calls have to be in Async methods. This has some advantages:

  • Returns the result of the Task
  • creates automatically a callback
  • checks for errors and lets them bubble up in callstack (only up to none-await calls in callstack)
  • waits for the result
  • frees up the main thread
  • runs the callback on the main thread
  • uses a worker thread from the threadpool for the task
  • makes the code easy to read
  • and a lot more

NOTE: Async and Await are used with asynchronous calls not to make these. You have to use Task Libary for this, like Task.Run() .

Here is a comparison between await and none await solutions

This is the none async solution:

    public static long DoTask()
    {
        stopWatch.Reset();
        stopWatch.Start();

        // [RUNS ON MAIN THREAD]
        var task = Task.Run(() => {
            Thread.Sleep(2000);
            // [RUNS ON WORKER THREAD]
        });
        // goes directly further
        // WITHOUT waiting until the task is finished

        // [RUNS ON MAIN THREAD]

        stopWatch.Stop();
        // 50 milliseconds
        return stopWatch.ElapsedMilliseconds;
    }

This is the async method:

    public async static Task<long> DoAwaitTask()
    {
        stopWatch.Reset();
        stopWatch.Start();

        // [RUNS ON MAIN THREAD]

        await Task.Run(() => {
            Thread.Sleep(2000);
            // [RUNS ON WORKER THREAD]
        });
        // Waits until task is finished

        // [RUNS ON MAIN THREAD]

        stopWatch.Stop();
        // 2050 milliseconds
        return stopWatch.ElapsedMilliseconds;
    }

You can actually call an async method without the await keyword but this means that any Exception here are swallowed in release mode:

    public static Stopwatch stopWatch { get; } = new Stopwatch();

    static void Main(string[] args)
    {
        Console.WriteLine("DoAwaitTask: " + DoAwaitTask().Result + " ms");
        // 2050 (2000 more because of the await)
        Console.WriteLine("DoTask: " + DoTask() + " ms");
        // 50
        Console.ReadKey();
    }

Async and Await are not meant for parallel computing. They are used to not block your main thread. When it's about asp.net or Windows applications, blocking your main thread due to a network call is a bad thing. If you do this, your app will get unresponsive or even crash.

Check out ms docs for more examples.

How can I stop python.exe from closing immediately after I get an output?

In windows, if Python is installed into the default directory (For me it is):

cd C:\Python27

You then proceed to type

"python.exe "[FULLPATH]\[name].py" 

to run your Python script in Command Prompt

z-index not working with fixed positioning

Add position: relative; to #over

_x000D_
_x000D_
    #over {_x000D_
      width: 600px;_x000D_
      z-index: 10;_x000D_
      position: relative;    _x000D_
    }_x000D_
    _x000D_
    #under {_x000D_
      position: fixed;_x000D_
      top: 5px;_x000D_
      width: 420px;_x000D_
      left: 20px;_x000D_
      border: 1px solid;_x000D_
      height: 10%;_x000D_
      background: #fff;_x000D_
      z-index: 1;_x000D_
    }
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    <body>_x000D_
     <div id="over">_x000D_
      Hello Hello HelloHelloHelloHelloHello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello_x000D_
     </div>  _x000D_
    _x000D_
     <div id="under"></div>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Fiddle

how to set the query timeout from SQL connection string

you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend

How do you execute an arbitrary native command from a string?

Invoke-Expression, also aliased as iex. The following will work on your examples #2 and #3:

iex $command

Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:

$command = 'C:\somepath\someexe.exe somearg'
iex $command

However, if the exe is in quotes, you need the help of & to get it running, as in this example, as run from the commandline:

>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"

And then in the script:

$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"

Likely, you could handle nearly all cases by detecting if the first character of the command string is ", like in this naive implementation:

function myeval($command) {
    if ($command[0] -eq '"') { iex "& $command" }
    else { iex $command }
}

But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}, perhaps for specific exception types/messages, or examine the command string.

If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.

Http Servlet request lose params from POST body after read it once

As an aside, an alternative way to solve this problem is to not use the filter chain and instead build your own interceptor component, perhaps using aspects, which can operate on the parsed request body. It will also likely be more efficient as you are only converting the request InputStream into your own model object once.

However, I still think it's reasonable to want to read the request body more than once particularly as the request moves through the filter chain. I would typically use filter chains for certain operations that I want to keep at the HTTP layer, decoupled from the service components.

As suggested by Will Hartung I achieved this by extending HttpServletRequestWrapper, consuming the request InputStream and essentially caching the bytes.

public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
  private ByteArrayOutputStream cachedBytes;

  public MultiReadHttpServletRequest(HttpServletRequest request) {
    super(request);
  }

  @Override
  public ServletInputStream getInputStream() throws IOException {
    if (cachedBytes == null)
      cacheInputStream();

      return new CachedServletInputStream();
  }

  @Override
  public BufferedReader getReader() throws IOException{
    return new BufferedReader(new InputStreamReader(getInputStream()));
  }

  private void cacheInputStream() throws IOException {
    /* Cache the inputstream in order to read it multiple times. For
     * convenience, I use apache.commons IOUtils
     */
    cachedBytes = new ByteArrayOutputStream();
    IOUtils.copy(super.getInputStream(), cachedBytes);
  }

  /* An inputstream which reads the cached request body */
  public class CachedServletInputStream extends ServletInputStream {
    private ByteArrayInputStream input;

    public CachedServletInputStream() {
      /* create a new input stream from the cached request body */
      input = new ByteArrayInputStream(cachedBytes.toByteArray());
    }

    @Override
    public int read() throws IOException {
      return input.read();
    }
  }
}

Now the request body can be read more than once by wrapping the original request before passing it through the filter chain:

public class MyFilter implements Filter {
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    /* wrap the request in order to read the inputstream multiple times */
    MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest((HttpServletRequest) request);

    /* here I read the inputstream and do my thing with it; when I pass the
     * wrapped request through the filter chain, the rest of the filters, and
     * request handlers may read the cached inputstream
     */
    doMyThing(multiReadRequest.getInputStream());
    //OR
    anotherUsage(multiReadRequest.getReader());
    chain.doFilter(multiReadRequest, response);
  }
}

This solution will also allow you to read the request body multiple times via the getParameterXXX methods because the underlying call is getInputStream(), which will of course read the cached request InputStream.

Edit

For newer version of ServletInputStream interface. You need to provide implementation of few more methods like isReady, setReadListener etc. Refer this question as provided in comment below.

Best way to restrict a text field to numbers only?

this will enable the numpad inputs also.

.keydown(function(event){                                     
    if(event.keyCode == 8 || event.keyCode == 46)             
        return true;                                         
    if(event.keyCode >= 96 && event.keyCode <= 105)           
        return true;                                          
    if(isNaN(parseInt(String.fromCharCode(event.keyCode),10)))
       return false;                                          
}); 

Python Variable Declaration

There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: mymagic = "Magic". Variables in Python can hold values of any type, and you can't restrict that.

Your question specifically asks about classes, objects and instance variables though. The idiomatic way to create instance variables is in the __init__ method and nowhere else — while you could create new instance variables in other methods, or even in unrelated code, it's just a bad idea. It'll make your code hard to reason about or to maintain.

So for example:

class Thing(object):

    def __init__(self, magic):
        self.magic = magic

Easy. Now instances of this class have a magic attribute:

thingo = Thing("More magic")
# thingo.magic is now "More magic"

Creating variables in the namespace of the class itself leads to different behaviour altogether. It is functionally different, and you should only do it if you have a specific reason to. For example:

class Thing(object):

    magic = "Magic"

    def __init__(self):
        pass

Now try:

thingo = Thing()
Thing.magic = 1
# thingo.magic is now 1

Or:

class Thing(object):

    magic = ["More", "magic"]

    def __init__(self):
        pass

thing1 = Thing()
thing2 = Thing()
thing1.magic.append("here")
# thing1.magic AND thing2.magic is now ["More", "magic", "here"]

This is because the namespace of the class itself is different to the namespace of the objects created from it. I'll leave it to you to research that a bit more.

The take-home message is that idiomatic Python is to (a) initialise object attributes in your __init__ method, and (b) document the behaviour of your class as needed. You don't need to go to the trouble of full-blown Sphinx-level documentation for everything you ever write, but at least some comments about whatever details you or someone else might need to pick it up.

Length of string in bash

Here is couple of ways to calculate length of variable :

echo ${#VAR}
echo -n $VAR | wc -m
echo -n $VAR | wc -c
printf $VAR | wc -m
expr length $VAR
expr $VAR : '.*'

and to set the result in another variable just assign above command with back quote into another variable as following:

otherVar=`echo -n $VAR | wc -m`   
echo $otherVar

http://techopsbook.blogspot.in/2017/09/how-to-find-length-of-string-variable.html

Java Loop every minute

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();

Fill remaining vertical space with CSS using display:flex

A more modern approach would be to use the grid property.

_x000D_
_x000D_
section {_x000D_
  display: grid;_x000D_
  align-items: stretch;_x000D_
  height: 300px;_x000D_
  grid-template-rows: min-content auto 60px;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  background: gold;_x000D_
  overflow: auto;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    _x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    _x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Enum "Inheritance"

Enums are not actual classes, even if they look like it. Internally, they are treated just like their underlying type (by default Int32). Therefore, you can only do this by "copying" single values from one enum to another and casting them to their integer number to compare them for equality.

bash: Bad Substitution

I have found that this issue is either caused by the marked answer or you have a line or space before the bash declaration

HTML5 phone number validation with pattern

How about

<input type="text" pattern="[789][0-9]{9}">

How to select a single column with Entity Framework?

You could use the LINQ select clause and reference the property that relates to your Name column.

check if directory exists and delete in one command unix

Here is another one liner:

[[ -d /tmp/test ]] && rm -r /tmp/test
  • && means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero)

What is the correct way to write HTML using Javascript?

Surely the best way is to avoid doing any heavy HTML creation in your JavaScript at all? The markup sent down from the server ought to contain the bulk of it, which you can then manipulate, using CSS rather than brute force removing/replacing elements, if at all possible.

This doesn't apply if you're doing something "clever" like emulating a widget system.

How to list the certificates stored in a PKCS12 keystore with keytool?

If the keystore is PKCS12 type (.pfx) you have to specify it with -storetype PKCS12 (line breaks added for readability):

keytool -list -v -keystore <path to keystore.pfx> \
    -storepass <password> \
    -storetype PKCS12

How to disable PHP Error reporting in CodeIgniter?

Here is the typical structure of new Codeigniter project:

- application/
- system/
- user_guide/
- index.php <- this is the file you need to change

I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.

With this code you can deploy your site to your production server without changing index.php each time.

// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;
        case 'testing':
        case 'production':
            error_reporting(0);
            ini_set('display_errors', 0);  
            break;
        default:
            exit('The application environment is not set correctly.');
    }
}

Convert SVG image to PNG with PHP

When converting SVG to transparent PNG, don't forget to put this BEFORE $imagick->readImageBlob():

$imagick->setBackgroundColor(new ImagickPixel('transparent'));

Getting Hour and Minute in PHP

Another way to address the timezone issue if you want to set the default timezone for the entire script to a certian timezone is to use date_default_timezone_set() then use one of the supported timezones.

Watching variables in SSIS during debug

Drag the variable from Variables pane to Watch pane and voila!

Find the greatest number in a list of numbers

Use max()

>>> l = [1, 2, 5]
>>> max(l)
5
>>> 

What's the purpose of git-mv?

git mv moves the file, updating the index to record the replaced file path, as well as updating any affected git submodules. Unlike a manual move, it also detects case-only renames that would not otherwise be detected as a change by git.

It is similar (though not identical) in behavior to moving the file externally to git, removing the old path from the index using git rm, and adding the new one to the index using git add.

Answer Motivation

This question has a lot of great partial answers. This answer is an attempt to combine them into a single cohesive answer. Additionally, one thing not called out by any of the other answers is the fact that the man page actually does mostly answer the question, but it's perhaps less obvious than it could be.

Detailed Explanation

Three different effects are called out in the man page:

  1. The file, directory, or symlink is moved in the filesystem:

    git-mv - Move or rename a file, a directory, or a symlink

  2. The index is updated, adding the new path and removing the previous one:

    The index is updated after successful completion, but the change must still be committed.

  3. Moved submodules are updated to work at the new location:

    Moving a submodule using a gitfile (which means they were cloned with a Git version 1.7.8 or newer) will update the gitfile and core.worktree setting to make the submodule work in the new location. It also will attempt to update the submodule.<name>.path setting in the gitmodules(5) file and stage that file (unless -n is used).

As mentioned in this answer, git mv is very similar to moving the file, adding the new path to the index, and removing the previous path from the index:

mv oldname newname
git add newname
git rm oldname

However, as this answer points out, git mv is not strictly identical to this in behavior. Moving the file via git mv adds the new path to the index, but not any modified content in the file. Using the three individual commands, on the other hand, adds the entire file to the index, including any modified content. This could be relevant when using a workflow which patches the index, rather than adding all changes in the file.

Additionally, as mentioned in this answer and this comment, git mv has the added benefit of handling case-only renames on file systems that are case-insensitive but case-preserving, as is often the case in current macOS and Windows file systems. For example, in such systems, git would not detect that the file name has changed after moving a file via mv Mytest.txt MyTest.txt, whereas using git mv Mytest.txt MyTest.txt would successfully update its name.

mysql.h file can't be found

For CentOS/RHEL:

yum install mysql-devel -y

How to create json by JavaScript for loop?

If you want a single JavaScript object such as the following:

{ uniqueIDofSelect: "uniqueID", optionValue: "2" }

(where option 2, "Absent", is the current selection) then the following code should produce it:

  var jsObj = null;
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
        break;
     }
  }

If you want an array of all such objects (not just the selected one), use michael's code but swap out status.options[i].text for status.id.

If you want a string that contains a JSON representation of the selected object, use this instead:

  var jsonStr = "";
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsonStr = '{ '
                  + '"uniqueIDofSelect" : '
                  + '"' + status.id + '"'
                  + ", "
                  + '"optionValue" : '
                  + '"'+ options[i].value + '"'
                  + ' }';
        break;
     }
  }

How to move the cursor word by word in the OS X Terminal

Actually there is a much better approach. Hold option ( alt on some keyboards) and press the arrow keys left or right to move by word. Simple as that.

option
option

Also ctrle will take you to the end of the line and ctrla will take you to the start.

Twitter Bootstrap Button Text Word Wrap

You can simply add this class.

.btn {
    white-space:normal !important;
    word-wrap: break-word; 
}

python save image from url

import requests

img_data = requests.get(image_url).content
with open('image_name.jpg', 'wb') as handler:
    handler.write(img_data)

How to create an array for JSON using PHP?

$json_data = '{ "Languages:" : [ "English", "Spanish" ] }';
$lang_data = json_decode($json_data);
var_dump($lang_data);

Calling constructors in c++ without new

I assume with the second line you actually mean:

Thing *thing = new Thing("uiae");

which would be the standard way of creating new dynamic objects (necessary for dynamic binding and polymorphism) and storing their address to a pointer. Your code does what JaredPar described, namely creating two objects (one passed a const char*, the other passed a const Thing&), and then calling the destructor (~Thing()) on the first object (the const char* one).

By contrast, this:

Thing thing("uiae");

creates a static object which is destroyed automatically upon exiting the current scope.

How to pass in parameters when use resource service?

I suggest you to use provider. Provide is good when you want to configure it first before to use (against Service/Factory)

Something like:

.provider('Magazines', function() {

    this.url = '/';
    this.urlArray = '/';
    this.organId = 'Default';

    this.$get = function() {
        var url = this.url;
        var urlArray = this.urlArray;
        var organId = this.organId;

        return {
            invoke: function() {
                return ......
            }
        }
    };

    this.setUrl  = function(url) {
        this.url = url;
    };

   this.setUrlArray  = function(urlArray) {
        this.urlArray = urlArray;
    };

    this.setOrganId  = function(organId) {
        this.organId = organId;
    };
});

.config(function(MagazinesProvider){
    MagazinesProvider.setUrl('...');
    MagazinesProvider.setUrlArray('...');
    MagazinesProvider.setOrganId('...');
});

And now controller:

function MyCtrl($scope, Magazines) {        

        Magazines.invoke();

       ....

}

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

How do you run PowerShell built-in scripts inside of your scripts?

How do you use built-in scripts like

Get-Location
pwd
ls
dir
split-path
::etc...

Those are ran by your computer, automatically checking the path of the script.

Similarly, I can run my custom scripts by just putting the name of the script in the script-block

::sid.ps1 is a PS script I made to find the SID of any user
::it takes one argument, that argument would be the username
echo $(sid.ps1 jowers)


(returns something like)> S-X-X-XXXXXXXX-XXXXXXXXXX-XXX-XXXX


$(sid.ps1 jowers).Replace("S","X")

(returns same as above but with X instead of S)

Go on to the powershell command line and type

> $profile

This will return the path to a file that our PowerShell command line will execute every time you open the app.

It will look like this

C:\Users\jowers\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

Go to Documents and see if you already have a WindowsPowerShell directory. I didn't, so

> cd \Users\jowers\Documents
> mkdir WindowsPowerShell
> cd WindowsPowerShell
> type file > Microsoft.PowerShellISE_profile.ps1

We've now created the script that will launch every time we open the PowerShell App.

The reason we did that was so that we could add our own folder that holds all of our custom scripts. Let's create that folder and I'll name it "Bin" after the directories that Mac/Linux hold its scripts in.

> mkdir \Users\jowers\Bin

Now we want that directory to be added to our $env:path variable every time we open the app so go back to the WindowsPowerShell Directory and

> start Microsoft.PowerShellISE_profile.ps1

Then add this

$env:path += ";\Users\jowers\Bin"

Now the shell will automatically find your commands, as long as you save your scripts in that "Bin" directory.

Relaunch the powershell and it should be one of the first scripts that execute.

Run this on the command line after reloading to see your new directory in your path variable:

> $env:Path

Now we can call our scripts from the command line or from within another script as simply as this:

$(customScript.ps1 arg1 arg2 ...)

As you see we must call them with the .ps1 extension until we make aliases for them. If we want to get fancy.

php resize image on upload

A full example with Zebra_Image library, that I think is so easy and useful. There are a lot of code, but if you read it, there are a lot of comments too so you can make copy and paste to use it quickly.

This example validates image format, size and replace image size with custom resolution. There is Zebra library and documentation (download only Zebra_Image.php file).

Explanation:

  1. An image is uploaded to server by uploadFile function.
  2. If image has been uploaded correctly, we recover this image and its path by getUserFile function.
  3. Resize image to custom width and height and replace at same path.

Main function

private function uploadImage() {        
    $target_file = "../img/blog/";
    
//this function could be in the same PHP file or class. I use a Helper (see bellow)
    if(UsersUtils::uploadFile($target_file, $this->selectedBlog->getId())) {
//This function is at same Helper class.
//The image will be returned allways if there isn't errors uploading it, for this reason there aren't validations here.
        $blogPhotoPath = UsersUtils::getUserFile($target_file, $this->selectedBlog->getId());
        
        // create a new instance of the class
        $imageHelper = new Zebra_Image();
        // indicate a source image
        $imageHelper->source_path = $blogPhotoPath;
        // indicate a target image
        $imageHelper->target_path = $blogPhotoPath;
        // since in this example we're going to have a jpeg file, let's set the output
        // image's quality
        $imageHelper->jpeg_quality = 100;

        // some additional properties that can be set
        // read about them in the documentation
        $imageHelper->preserve_aspect_ratio = true;
        $imageHelper->enlarge_smaller_images = true;
        $imageHelper->preserve_time = true;
        $imageHelper->handle_exif_orientation_tag = true;
        // resize
        // and if there is an error, show the error message
        if (!$imageHelper->resize(450, 310, ZEBRA_IMAGE_CROP_CENTER)) {
            // if there was an error, let's see what the error is about
            switch ($imageHelper->error) {
                case 1:
                    echo 'Source file could not be found!';
                    break;
                case 2:
                    echo 'Source file is not readable!';
                    break;
                case 3:
                    echo 'Could not write target file!';
                    break;
                case 4:
                    echo 'Unsupported source file format!';
                    break;
                case 5:
                    echo 'Unsupported target file format!';
                    break;
                case 6:
                    echo 'GD library version does not support target file format!';
                    break;
                case 7:
                    echo 'GD library is not installed!';
                    break;
                case 8:
                    echo '"chmod" command is disabled via configuration!';
                    break;
                case 9:
                    echo '"exif_read_data" function is not available';
                    break;
            }
        } else {
            echo 'Image uploaded with new size without erros');
        }
    }
}

External functions or use at same PHP file removing public static qualifiers.

    public static function uploadFile($targetDir, $fileName) {        
    // File upload path
    $fileUploaded = $_FILES["input-file"];
    
    $fileType = pathinfo(basename($fileUploaded["name"]),PATHINFO_EXTENSION);
    $targetFilePath = $targetDir . $fileName .'.'.$fileType;
    
    if(empty($fileName)){
        echo 'Error: any file found inside this path';
        return false;
    }
    
    // Allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf');
    if(in_array($fileType, $allowTypes)){
        //Max buffer length 8M
        var_dump(ob_get_length());
        if(ob_get_length() > 8388608) {
            echo 'Error: Max size available 8MB';
            return false;
        }
        // Upload file to server
        if(move_uploaded_file($fileUploaded["tmp_name"], $targetFilePath)){
            return true;
        }else{
            echo 'Error: error_uploading_image.';
        }
    }else{
        echo 'Error: Only files JPG, JPEG, PNG, GIF y PDF types are allowed';
    }
    return false;
}

public static function getUserFile($targetDir, $userId) {
    $userImages = glob($targetDir.$userId.'.*');
    return !empty($userImages) ? $userImages[0] : null;
}

How to clone git repository with specific revision/changeset?

I use this snippet with GNU make to close any revision tag, branch or hash

it was tested on git version 2.17.1

${dir}:
    mkdir -p ${@D}
    git clone --recursive --depth 1 --branch ${revison} ${url} ${@} \
 || git clone --recursive --branch ${revison} ${url} ${@} \
 || git clone ${url} ${@}
    cd ${@} && git reset --hard ${revison}
    ls $@




Javascript : Send JSON Object with Ajax?

If you`re not using jQuery then please make sure:

var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);

And for the php receiving end:

 $_POST['json_name'] 

How to merge 2 List<T> and removing duplicate values from it in C#

Have you had a look at Enumerable.Union

This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input sequences including duplicates.

List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();

// ulist output : 1, 12, 5, 7, 9

Wpf control size to content?

I had a user control which sat on page in a free form way, not constrained by another container, and the contents within the user control would not auto size but expand to the full size of what the user control was handed.

To get the user control to simply size to its content, for height only, I placed it into a grid with on row set to auto size such as this:

<Grid Margin="0,60,10,200">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <controls1:HelpPanel x:Name="HelpInfoPanel"
                         Visibility="Visible"
                         Width="570"
                         HorizontalAlignment="Right"
                         ItemsSource="{Binding HelpItems}"
                         Background="#FF313131" />
</Grid>

Save a file in json format using Notepad++

In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON.

Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as .JSON file, you have to just select the location of the file.

Thanks, -Sam

Please look at the pic, it will give you a better idea..

How to specify a port number in SQL Server connection string?

Use a comma to specify a port number with SQL Server:

mycomputer.test.xxx.com,1234

It's not necessary to specify an instance name when specifying the port.

Lots more examples at http://www.connectionstrings.com/. It's saved me a few times.

Regex: Remove lines containing "help", etc

If you're on Windows, try findstr. Third-party tools are not needed:

findstr /V /L "searchstring" inputfile.txt > outputfile.txt

It supports regex's too! Just read the tool's help findstr /?.

P.S. If you want to work with big, huge files (like 400 MB log files) a text editor is not very memory-efficient, so, as someone already pointed out, command-line tools are the way to go. But there's no grep on Windows, so...

I just ran this on a 1 GB log file, and it literally took 3 seconds.

what is the difference between const_iterator and iterator?

Performance wise there is no difference. The only purpose of having const_iterator over iterator is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

std::vector<int> integers{ 3, 4, 56, 6, 778 };

If we were to read & write the members of a container we will use iterator:

for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
       {*it = 4;  std::cout << *it << std::endl; }

If we were to only read the members of the container integers you might wanna use const_iterator which doesn't allow to write or modify members of container.

for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
       { cout << *it << endl; }

NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

Android: Changing Background-Color of the Activity (Main View)

Just add this below one line code in the XML file of that corresponding activity:

android:background="@android:color/black" 

it will help you for sure.

Override console.log(); for production

Put this at the top of the file:

var console = {};
console.log = function(){};

For some browsers and minifiers, you may need to apply this onto the window object.

window.console = console;

LINQ Group By and select collection

I think you want:

items.GroupBy(item => item.Order.Customer)
     .Select(group => new { Customer = group.Key, Items = group.ToList() })
     .ToList() 

If you want to continue use the overload of GroupBy you are currently using, you can do:

items.GroupBy(item => item.Order.Customer, 
              (key, group) =>  new { Customer = key, Items = group.ToList() })
     .ToList() 

...but I personally find that less clear.

Difference between single and double quotes in Bash

Since this is the de facto answer when dealing with quotes in bash, I'll add upon one more point missed in the answers above, when dealing with the arithmetic operators in the shell.

The bash shell supports two ways do arithmetic operation, one defined by the built-in let command and the $((..)) operator. The former evaluates an arithmetic expression while the latter is more of a compound statement.

It is important to understand that the arithmetic expression used with let undergoes word-splitting, pathname expansion just like any other shell commands. So proper quoting and escaping needs to be done.

See this example when using let

let 'foo = 2 + 1'
echo $foo
3

Using single quotes here is absolutely fine here, as there is no need for variable expansions here, consider a case of

bar=1
let 'foo = $bar + 1'

would fail miserably, as the $bar under single quotes would not expand and needs to be double-quoted as

let 'foo = '"$bar"' + 1'

This should be one of the reasons, the $((..)) should always be considered over using let. Because inside it, the contents aren't subject to word-splitting. The previous example using let can be simply written as

(( bar=1, foo = bar + 1 ))

Always remember to use $((..)) without single quotes

Though the $((..)) can be used with double-quotes, there is no purpose to it as the result of it cannot contain a content that would need the double-quote. Just ensure it is not single quoted.

printf '%d\n' '$((1+1))'
-bash: printf: $((1+1)): invalid number
printf '%d\n' $((1+1))
2
printf '%d\n' "$((1+1))"
2

May be in some special cases of using the $((..)) operator inside a single quoted string, you need to interpolate quotes in a way that the operator either is left unquoted or under double quotes. E.g. consider a case, when you are tying to use the operator inside a curl statement to pass a counter every time a request is made, do

curl http://myurl.com --data-binary '{"requestCounter":'"$((reqcnt++))"'}'

Notice the use of nested double-quotes inside, without which the literal string $((reqcnt++)) is passed to requestCounter field.

Can't connect to MySQL server on 'localhost' (10061) after Installation

In Windows 7

  1. press Windows+R it opens Run
  2. Enter services.msc
  3. Find out mysql right click and start
  4. if mysql was not found
    1. Run cmd as administrator
    2. goto C:\Program Files (x86)\MySQL\MySQL Server 5.6\bin directory(to go back use cd..) and type mysqld.exe --install
  5. follow step 3

That's all

ThreeJS: Remove object from scene

If your element is not directly on you scene go back to Parent to remove it

  function removeEntity(object) {
        var selectedObject = scene.getObjectByName(object.name);
        selectedObject.parent.remove( selectedObject );
    }

How to use the "required" attribute with a "radio" input field

TL;DR: Set the required attribute for at least one input of the radio group.


Setting required for all inputs is more clear, but not necessary (unless dynamically generating radio-buttons).

To group radio buttons they must all have the same name value. This allows only one to be selected at a time and applies required to the whole group.

_x000D_
_x000D_
<form>_x000D_
  Select Gender:<br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="male" required>_x000D_
    Male_x000D_
  </label><br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="female">_x000D_
    Female_x000D_
  </label><br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="other">_x000D_
    Other_x000D_
  </label><br>_x000D_
_x000D_
  <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Also take note of:

To avoid confusion as to whether a radio button group is required or not, authors are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general, authors are encouraged to avoid having radio button groups that do not have any initially checked controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.

Source

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

Generally speaking:

F5 may give you the same page even if the content is changed, because it may load the page from cache. But Ctrl-F5 forces a cache refresh, and will guarantee that if the content is changed, you will get the new content.

Configuring angularjs with eclipse IDE

Netbeans 8.0 (beta at the time of this post) has Angular support as well as HTML5 support.

Check out this Oracle article: https://blogs.oracle.com/geertjan/entry/integrated_angularjs_development

What is the syntax meaning of RAISERROR()

The answer posted to this question as an example taken from Microsoft's MSDN is nice however it doesn't directly demonstrate where the error comes from if it doesn't come from the TRY Block. I prefer this example with a very minor update to the RAISERROR Message within the CATCH Block stating that the error is from the CATCH Block. I demonstrate this in the gif as well.

BEGIN TRY
    /* RAISERROR with severity 11-19 will cause execution
     |  to jump to the CATCH block.
    */
    RAISERROR ('Error raised in TRY block.', -- Message text.
               5, -- Severity. /* Severity Levels Less Than 11 do not jump to the CATCH block */
               1 -- State.
               );
END TRY

BEGIN CATCH
    DECLARE @ErrorMessage  NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState    INT;

    SELECT 
        @ErrorMessage  = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState    = ERROR_STATE();

    /* Use RAISERROR inside the CATCH block to return error
     | information about the original error that caused
     | execution to jump to the CATCH block
    */
    RAISERROR ('Caught Error in Catch', --@ErrorMessage, /* Message text */
               @ErrorSeverity,                           /* Severity     */
               @ErrorState                               /* State        */
               );
END CATCH;

RAISERROR Demo Gif

C++ error 'Undefined reference to Class::Function()'

What are you using to compile this? If there's an undefined reference error, usually it's because the .o file (which gets created from the .cpp file) doesn't exist and your compiler/build system is not able to link it.

Also, in your card.cpp, the function should be Card::Card() instead of void Card. The Card:: is scoping; it means that your Card() function is a member of the Card class (which it obviously is, since it's the constructor for that class). Without this, void Card is just a free function. Similarly,

void Card(Card::Rank rank, Card::Suit suit)

should be

Card::Card(Card::Rank rank, Card::Suit suit)

Also, in deck.cpp, you are saying #include "Deck.h" even though you referred to it as deck.h. The includes are case sensitive.

How to install python developer package?

If you use yum search you can find the python dev package for your version of python.

For me I was using python 3.5. I ran the following

yum search python | grep devel

Which returned the following

enter image description here

I was then able to install the correct package for my version of python with the following cmd.

sudo yum install python35u-devel.x86_64

This works on centos for ubuntu or debian you would need to use apt-get

How to make parent wait for all child processes to finish?

Use waitpid() like this:

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
{   
   // Do something   
   exit(0); 
}

else if(childPid < 0)  // fork failed 
{    
   // log the error
}

else  // Main (parent) process after fork succeeds 
{    
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
    {
       printf("The child process terminated normally.");    
    }

    if (returnStatus == 1)      
    {
       printf("The child process terminated with an error!.");    
    }
}

IF Statement multiple conditions, same statement

var test = new char[] {a, b, c}.Contains(columnname));

if(test)
{
  "true statement"
}
else
{
   "false statement"
}

Line Break in HTML Select Option?

I know this is an older post, but I'm leaving this for whomever else comes looking in the future.

You can't format line breaks into an option; however, you can use the title attibute to give a mouse-over tooltip to give the full info. Use a short descriptor in the option text and give the full skinny in the title.

<option value="1" title="This is my lengthy explanation of what this selection really means, so since you only see 1 on the drop down list you really know that you're opting to elect me as King of Willywarts!  Always be sure to read the fine print!">1</option>

Laravel Eloquent compare date from datetime field

If you're still wondering how to solve it.

I use

$protected $dates = ['created_at','updated_at','aired'];

In my model and in my where i do

where('aired','>=',time())

So just use the unix to compaire in where.

In views on the otherhand you have to use the date object.

Hope it helps someone!

Bootstrap modal appearing under background

I got it to work by giving a high z-index value to the modal window AFTER opening it. E.g.:

$("#myModal").modal("show");
$("#myModal").css("z-index", "1500");

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

Android - How to regenerate R class?

To generate the R file again:

  1. Modify something in layout->activity_main.xml
  2. Save the file
  3. Project->Clean...

Just delete the R file located in gen directory, and then try Project->Clean. Then build your app again.

Open a Web Page in a Windows Batch FIle

Unfortunately, the best method to approach this is to use Internet Explorer as it's a browser that is guaranteed to be on Windows based machines. This will also bring compatibility of other users which might have alternative browsers such as Firefox, Chrome, Opera..etc,

start "iexplore.exe" http://www.website.com

Error: TypeError: $(...).dialog is not a function

I just experienced this with the line:

$('<div id="editor" />').dialogelfinder({

I got the error "dialogelfinder is not a function" because another component was inserting a call to load an older version of JQuery (1.7.2) after the newer version was loaded.

As soon as I commented out the second load, the error went away.

How can I use Guzzle to send a POST request in JSON?

I use the following code that works very reliably.

The JSON data is passed in the parameter $request, and the specific request type passed in the variable $searchType.

The code includes a trap to detect and report an unsuccessful or invalid call which will then return false.

If the call is sucessful then json_decode ($result->getBody(), $return=true) returns an array of the results.

    public function callAPI($request, $searchType) {
    $guzzleClient = new GuzzleHttp\Client(["base_uri" => "https://example.com"]);

    try {
        $result = $guzzleClient->post( $searchType, ["json" => $request]);
    } catch (Exception $e) {
        $error = $e->getMessage();
        $error .= '<pre>'.print_r($request, $return=true).'</pre>';
        $error .= 'No returnable data';
        Event::logError(__LINE__, __FILE__, $error);
        return false;
    }
    return json_decode($result->getBody(), $return=true);
}

Checking for empty or null JToken in a JObject

As of C# 7 you could also use this:

if (clientsParsed["objects"] is JArray clients) 
{
    foreach (JObject item in clients.Children())
    {
        if (item["thisParameter"] as JToken itemToken) 
        {
            command.Parameters["@MyParameter"].Value = JTokenToSql(itemToken);
        }
    }
}

The is Operator checks the Type and if its corrects the Value is inside the clients variable.

How to get just the parent directory name of a specific file

For Kotlin :

 fun getFolderName() {
            
            val uri: Uri
            val cursor: Cursor?
    
            uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
            val projection = arrayOf(MediaStore.Audio.AudioColumns.DATA)
            cursor = requireActivity().contentResolver.query(uri, projection, null, null, null)
            if (cursor != null) {
                column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA)
            }
            
            while (cursor!!.moveToNext()) {
    
                absolutePathOfImage = cursor.getString(column_index_data)
    
    
                val fileName: String = File(absolutePathOfImage).parentFile.name
    }
}

How to fix Cannot find module 'typescript' in Angular 4?

Run: npm link typescript if you installed globally

But if you have not installed typescript try this command: npm install typescript

Adding a library/JAR to an Eclipse Android project

Go to build path in eclipse, then click order and export, then check the library/jar, and then click the up button to move it to the top of the list to compile it first.

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

I've faced the same problem because of a cable. I changed my third party USB/lighting cable into original Apple cable, and it worked.

Which UUID version to use?

That's a very general question. One answer is: "it depends what kind of UUID you wish to generate". But a better one is this: "Well, before I answer, can you tell us why you need to code up your own UUID generation algorithm instead of calling the UUID generation functionality that most modern operating systems provide?"

Doing that is easier and safer, and since you probably don't need to generate your own, why bother coding up an implementation? In that case, the answer becomes use whatever your O/S, programming language or framework provides. For example, in Windows, there is CoCreateGuid or UuidCreate or one of the various wrappers available from the numerous frameworks in use. In Linux there is uuid_generate.

If you, for some reason, absolutely need to generate your own, then at least have the good sense to stay away from generating v1 and v2 UUIDs. It's tricky to get those right. Stick, instead, to v3, v4 or v5 UUIDs.

Update: In a comment, you mention that you are using Python and link to this. Looking through the interface provided, the easiest option for you would be to generate a v4 UUID (that is, one created from random data) by calling uuid.uuid4().

If you have some data that you need to (or can) hash to generate a UUID from, then you can use either v3 (which relies on MD5) or v5 (which relies on SHA1). Generating a v3 or v5 UUID is simple: first pick the UUID type you want to generate (you should probably choose v5) and then pick the appropriate namespace and call the function with the data you want to use to generate the UUID from. For example, if you are hashing a URL you would use NAMESPACE_URL:

uuid.uuid3(uuid.NAMESPACE_URL, 'https://ripple.com')

Please note that this UUID will be different than the v5 UUID for the same URL, which is generated like this:

uuid.uuid5(uuid.NAMESPACE_URL, 'https://ripple.com')

A nice property of v3 and v5 URLs is that they should be interoperable between implementations. In other words, if two different systems are using an implementation that complies with RFC4122, they will (or at least should) both generate the same UUID if all other things are equal (i.e. generating the same version UUID, with the same namespace and the same data). This property can be very helpful in some situations (especially in content-addressible storage scenarios), but perhaps not in your particular case.

Checking if a variable is an integer in PHP

Just for kicks, I tested out a few of the mentioned methods, plus one I've used as my go to solution for years when I know my input is a positive number or string equivalent.

I tested this with 125,000 iterations, with each iteration passing in the same set of variable types and values.

Method 1: is_int($value) || ctype_digit($value)
Method 2: (string)(int)$value == (string)$value
Method 3: strval(intval($value)) === strval($value)
Method 4: ctype_digit(strval($value))
Method 5: filter_var($value, FILTER_VALIDATE_INT) !== FALSE
Method 6: is_int($value) || ctype_digit($value) || (is_string($value) && $value[0] === '-' && filter_var($value, FILTER_VALIDATE_INT) !== FALSE)

Method 1: 0.0552167892456
Method 2: 0.126773834229
Method 3: 0.143012046814
Method 4: 0.0979189872742
Method 5: 0.112988948822
Method 6: 0.0858821868896

(I didn't even test the regex, I mean, seriously... regex for this?)

Things to note:
Method 4 always returns false for negative numbers (negative integer or string equivalent), so is a good method to consistently detect that a value is a positive integer.
Method 1 returns true for a negative integer, but false for a string equivalent of a negative integer, so don't use this method unless you are certain your input will never contain a negative number in string or integer form, and that if it does, your process won't break from this behavior.

Conclusions
So it seems that if you are certain that your input will not include a negative number, then it is almost twice as fast to use is_int and ctype_digit to validate that you have an integer. Using Method 1 with a fallback to method 5 when the variable is a string and the first character is a dash is the next fastest (especially when a majority of the input is actual integers or positive numbers in a string). All in all, if you need solid consistency, and you have no idea what the mix of data is coming in, and you must handle negatives in a consistent fashion, filter_var($value, FILTER_VALIDATE_INT) !== FALSE wins.

Code used to get the output above:

$u = "-10";
$v = "0";
$w = 0;
$x = "5";
$y = "5c";
$z = 1.44;

function is_int1($value){
    return (is_int($value) || ctype_digit($value));
}

function is_int2($value) {
    return ((string)(int)$value == (string)$value);
}

function is_int3($value) {
    return (strval(intval($value)) === strval($value));
}

function is_int4($value) {
    return (ctype_digit(strval($value)));
}

function is_int5($value) {
    return filter_var($value, FILTER_VALIDATE_INT) !== FALSE;
}

function is_int6($value){
    return (is_int($value) || ctype_digit($value) || (is_string($value) && $value[0] === '-' && filter_var($value, FILTER_VALIDATE_INT)) !== FALSE);
}

$start = microtime(TRUE);
for ($i=0; $i < 125000; $i++) {
  is_int1($u);
  is_int1($v);
  is_int1($w);
  is_int1($x);
  is_int1($y);
  is_int1($z);
}
$stop = microtime(TRUE);
$start2 = microtime(TRUE);
for ($j=0; $j < 125000; $j++) {
  is_int2($u);
  is_int2($v);
  is_int2($w);
  is_int2($x);
  is_int2($y);
  is_int2($z);
}
$stop2 = microtime(TRUE);
$start3 = microtime(TRUE);
for ($k=0; $k < 125000; $k++) {
  is_int3($u);
  is_int3($v);
  is_int3($w);
  is_int3($x);
  is_int3($y);
  is_int3($z);
}
$stop3 = microtime(TRUE);
$start4 = microtime(TRUE);
for ($l=0; $l < 125000; $l++) {
  is_int4($u);
  is_int4($v);
  is_int4($w);
  is_int4($x);
  is_int4($y);
  is_int4($z);
}
$stop4 = microtime(TRUE); 

$start5 = microtime(TRUE);
for ($m=0; $m < 125000; $m++) {
  is_int5($u);
  is_int5($v);
  is_int5($w);
  is_int5($x);
  is_int5($y);
  is_int5($z);
}
$stop5 = microtime(TRUE); 

$start6 = microtime(TRUE);
for ($n=0; $n < 125000; $n++) {
  is_int6($u);
  is_int6($v);
  is_int6($w);
  is_int6($x);
  is_int6($y);
  is_int6($z);
}
$stop6 = microtime(TRUE); 

$time = $stop - $start;  
$time2 = $stop2 - $start2;  
$time3 = $stop3 - $start3;  
$time4 = $stop4 - $start4;  
$time5 = $stop5 - $start5;  
$time6 = $stop6 - $start6;  
print "**Method 1:** $time <br>";
print "**Method 2:** $time2 <br>";
print "**Method 3:** $time3 <br>";
print "**Method 4:** $time4 <br>";  
print "**Method 5:** $time5 <br>";  
print "**Method 6:** $time6 <br>";  

Read a local text file using Javascript

Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!

<html>
<head>
  <meta charset="utf-8">
  <script type="text/javascript">

  var x;
  if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
  else { x = new XMLHttpRequest(); }

  function getdata() {
    x.open('get', 'data1.txt', true); 
    x.onreadystatechange= showdata;
    x.send(null);
  }

  function showdata() {
    if(x.readyState==4) {
      var el = document.getElementById('content');
      el.innerHTML = x.responseText;
    }
  }

  </script>
</head>
<body onload="getdata();showdata();">

  <div id="content"></div>

</body>
</html>

How to copy a file to another path?

File::Copy will copy the file to the destination folder and File::Move can both move and rename a file.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.

On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.

As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.

creating a table in ionic

the issue of too long content @beenotung can be resolved by this css class :

.col{
  max-width :20% !important;
}

example fork from @jpoveda

Installation failed with message Invalid File

My issue was with my Android Studio install.

I am building out a new CI server and although I installed Android Studio and hooked up the SDK, etc., I did not open the studio with the project -- instead just went to the command line to build. When I subsequently opened the project in the studio, it started prompting for all sorts of updates. Followed the bouncing-ball and then I was able to reach my USB tethered device.

Hopefully, this is helpful for Build Master and DevOps as a "got-cha" to avoid.

Import CSV to SQLite

Follow the steps:-

  1. 1] sqlite3 name 2] .mode csv tablename 3] .import Filename.csv tablename

How to deal with persistent storage (e.g. databases) in Docker

In case it is not clear from update 5 of the selected answer, as of Docker 1.9, you can create volumes that can exist without being associated with a specific container, thus making the "data-only container" pattern obsolete.

See Data-only containers obsolete with docker 1.9.0? #17798.

I think the Docker maintainers realized the data-only container pattern was a bit of a design smell and decided to make volumes a separate entity that can exist without an associated container.

Convert hex color value ( #ffffff ) to integer value

The real answer is this simplest and easiest ....

String white = "#ffffff";
int whiteInt = Color.parseColor(white);

How can I add an empty directory to a Git repository?

The solution of Jamie Flournoy works great. Here is a bit enhanced version to keep the .htaccess :

# Ignore everything in this directory
*
# Except this file
!.gitignore
!.htaccess

With this solution you are able to commit a empty folder, for example /log, /tmp or /cache and the folder will stay empty.

JQuery $.ajax() post - data in a java servlet

To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

I am using Visual Studio 2013 & SQL Server 2014. I got the below error Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0 not found by visual studio. I have tried all the things like installing

  • ENU\x64\SharedManagementObjects.msi for X64 OS or

  • ENU\x86\SharedManagementObjects.msi for X86 OS

  • ENU\x64\SQLSysClrTypes.msi

  • Reinstalling Sql Server 2014

What actually solved my problem is to repair the visual studio 2013(or any other version you are using) now the problem is removed . What i think it is problem of Visual Studio not Sql Server as i was able to access and use the Sql Server tool.

Easiest way to copy a single file from host to Vagrant guest?

Best way to copy file from local to vagrant, No need to write any code or any thing or any configuration changes. 1- First up the vagrant (vagrant up) 2- open cygwin 3- cygwin : go to your folder where is vagrantfile or from where you launch the vagrant 4- ssh vagrant 5- now it will work like a normal system.

changing source on html5 video tag

Yaur: Although what you have copied and pasted is good advice, this does not mean that it is impossible to change the source element of an HTML5 video element elegantly, even in IE9 (or IE8 for that matter).(This solution does NOT involve replacing the entire video element, as it is bad coding practice).

A complete solution to changing/switching videos in HTML5 video tags via javascript can be found here and is tested in all HTML5 browser (Firefox, Chrome, Safari, IE9, etc).

If this helps, or if you're having trouble, please let me know.

Stretch horizontal ul to fit width of div

I Hope that this helps you out... Because I tried all the answers but nothing worked perfectly. So, I had to come up with a solution on my own.

#horizontal-style {
  padding-inline-start: 0 !important; // Just in case if you find that there is an extra padding at the start of the line 
  justify-content: space-around;
  display: flex;
}

#horizontal-style a {
    text-align: center;
    color: white;
    text-decoration: none;
}

How to format numbers?

If you want to use built-in code, you can use toLocaleString() with minimumFractionDigits. Browser compatibility for the extended options on toLocaleString() was limited when I first wrote this answer, but the current status looks good.

_x000D_
_x000D_
var n = 100000;
var value = n.toLocaleString(
  undefined, // leave undefined to use the browser's locale,
             // or use a string like 'en-US' to override it.
  { minimumFractionDigits: 2 }
);
console.log(value);
// In en-US, logs '100,000.00'
// In de-DE, logs '100.000,00'
// In hi-IN, logs '1,00,000.00'
_x000D_
_x000D_
_x000D_

If you're using Node.js, you will need to npm install the intl package.

How to set up a Web API controller for multipart/form-data

You can use something like this

[HttpPost]
public async Task<HttpResponseMessage> AddFile()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
    var provider = new MultipartFormDataStreamProvider(root);
    var result = await Request.Content.ReadAsMultipartAsync(provider);

    foreach (var key in provider.FormData.AllKeys)
    {
        foreach (var val in provider.FormData.GetValues(key))
        {
            if (key == "companyName")
            {
                var companyName = val;
            }
        }
    }

    // On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
    // so this is how you can get the original file name
    var originalFileName = GetDeserializedFileName(result.FileData.First());

    var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
    string path = result.FileData.First().LocalFileName;

    //Do whatever you want to do with your file here

    return this.Request.CreateResponse(HttpStatusCode.OK, originalFileName );
}

private string GetDeserializedFileName(MultipartFileData fileData)
{
    var fileName = GetFileName(fileData);
    return JsonConvert.DeserializeObject(fileName).ToString();
}

public string GetFileName(MultipartFileData fileData)
{
    return fileData.Headers.ContentDisposition.FileName;
}

How do you access the value of an SQL count () query in a Java program

Statement stmt3 = con.createStatement();

ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");

count = rs3.getInt("count");

Why do I need to override the equals and hashCode methods in Java?

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.


   from Effective Java, by Joshua Bloch

By defining equals() and hashCode() consistently, you can improve the usability of your classes as keys in hash-based collections. As the API doc for hashCode explains: "This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable."

The best answer to your question about how to implement these methods efficiently is suggesting you to read Chapter 3 of Effective Java.

Android XML Percent Symbol

To allow the app using formatted strings from resources you should correct your xml. So, for example

<string name="app_name">Your App name, ver.%d</string>

should be replaced with

<string name="app_name">Your App name, ver.%1$d</string>

You can see this for details.

Is there a "theirs" version of "git merge -s ours"?

The equivalent(which keep parent order) to 'git merge -s theirs branchB'

Before merge:enter image description here

!!! Make sure you are in clean state !!!

Do the merge:

git commit-tree -m "take theirs" -p HEAD -p branchB 'branchB^{tree}'
git reset --hard 36daf519952 # is the output of the prev command

What we did ? We created a new commit which two parents ours and theirs and the contnet of the commit is branchB - theirs

After merge:enter image description here

More precisely:

git commit-tree -m "take theirs" -p HEAD -p 'SOURCE^{commit}' 'SOURCE^{tree}'

How to change port for jenkins window service when 8080 is being used

  1. Go to the directory where you installed Jenkins (by default, it's under Program Files/Jenkins)
  2. Open the Jenkins.xml configuration file
  3. Search --httpPort=8080 and replace the 8080 with the new port number that you wish
  4. Restart Jenkins for changes to take effect

How to make <div> fill <td> height

CSS height: 100% only works if the element's parent has an explicitly defined height. For example, this would work as expected:

td {
    height: 200px;
}

td div {
    /* div will now take up full 200px of parent's height */
    height: 100%;
}

Since it seems like your <td> is going to be variable height, what if you added the bottom right icon with an absolutely positioned image like so:

.thatSetsABackgroundWithAnIcon {
    /* Makes the <div> a coordinate map for the icon */
    position: relative;

    /* Takes the full height of its parent <td>.  For this to work, the <td>
       must have an explicit height set. */
    height: 100%;
}

.thatSetsABackgroundWithAnIcon .theIcon {        
    position: absolute;
    bottom: 0;
    right: 0;
}

With the table cell markup like so:

<td class="thatSetsABackground">  
  <div class="thatSetsABackgroundWithAnIcon">    
    <dl>
      <dt>yada
      </dt>
      <dd>yada
      </dd>
    </dl>
    <img class="theIcon" src="foo-icon.png" alt="foo!"/>
  </div>
</td>

Edit: using jQuery to set div's height

If you keep the <div> as a child of the <td>, this snippet of jQuery will properly set its height:

// Loop through all the div.thatSetsABackgroundWithAnIcon on your page
$('div.thatSetsABackgroundWithAnIcon').each(function(){
    var $div = $(this);

    // Set the div's height to its parent td's height
    $div.height($div.closest('td').height());
});

How to open a workbook specifying its path

Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")

Or, in a more structured way...

Sub openwb()
    Dim sPath As String, sFile As String
    Dim wb As Workbook

    sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
    sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"

    Set wb = Workbooks.Open(sFile)
End Sub

How to make a input field readonly with JavaScript?

Try This :

document.getElementById(<element_ID>).readOnly=true;

Android widget: How to change the text of a button

use the exchange using java. setText = "...", for class java there are many more methods for implementation.

    //button fechar
    btnclose.setEnabled(false);
    btnclose.setText("FECHADO");
    View.OnClickListener close = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (btnclose.isClickable()) {
                btnOpen.setEnabled(true);
                btnOpen.setText("ABRIR");
                btnclose.setEnabled(false);
                btnclose.setText("FECHADO");
            } else {
                btnOpen.setEnabled(false);
                btnOpen.setText("ABERTO");
                btnclose.setEnabled(true);
                btnclose.setText("FECHAR");
            }

            Toast.makeText(getActivity(), "FECHADO", Toast.LENGTH_SHORT).show();
        }
    };

    btnclose.setOnClickListener(close); 

Why ModelState.IsValid always return false in mvc

"ModelState.IsValid" tells you that the model is consumed by the view (i.e. PaymentAdviceEntity) is satisfy all types of validation or not specified in the model properties by DataAnotation.

In this code the view does not bind any model properties. So if you put any DataAnotations or validation in model (i.e. PaymentAdviceEntity). then the validations are not satisfy. say if any properties in model is Name which makes required in model.Then the value of the property remains blank after post.So the model is not valid (i.e. ModelState.IsValid returns false). You need to remove the model level validations.

What is the best (idiomatic) way to check the type of a Python variable?

I've been using a different approach:

from inspect import getmro
if (type([]) in getmro(obj.__class__)):
    # This is a list, or a subclass of...
elif (type{}) in getmro(obj.__class__)):
    # This one is a dict, or ...

I can't remember why I used this instead of isinstance, though...

Stopping a windows service when the stop option is grayed out

If you run the command:

sc queryex <service name>

where is the the name of the service, not the display name (spooler, not Print Spooler), at the cmd prompt it will return the PID of the process the service is running as. Take that PID and run

taskkill /F /PID <Service PID>

to force the PID to stop. Sometimes if the process hangs while stopping the GUI won't let you do anything with the service.

The create-react-app imports restriction outside of src directory

I have had to overcome this same issue in Truffle. The solution was as follows:

ince Create-React-App's default behavior disallows importing files from outside of the src folder, we need to bring the contracts in our build folder inside src. We can copy and paste them every time we compile our contracts, but a better way is to simply configure Truffle to put the files there.

In the truffle-config.js file, replace the contents with the following:

const path = require("path");

module.exports = {
  contracts_build_directory: path.join(__dirname, "client/src/contracts")
};

I don't know if this helps you, but I know I found your question when I had the same issue in Truffle, and this might help someone else.

Pythonic way to check if a file exists?

Instead of os.path.isfile, suggested by others, I suggest using os.path.exists, which checks for anything with that name, not just whether it is a regular file.

Thus:

if not os.path.exists(filename):
    file(filename, 'w').close()

Alternatively:

file(filename, 'w+').close()

The latter will create the file if it exists, but not otherwise. It will, however, fail if the file exists, but you don't have permission to write to it. That's why I prefer the first solution.

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

How can I check if an argument is defined when starting/calling a batch file?

The check for whether a commandline argument has been set can be [%1]==[], but, as Dave Costa points out, "%1"=="" will also work.

I also fixed a syntax error in the usage echo to escape the greater-than and less-than signs. In addition, the exit needs a /B argument otherwise CMD.exe will quit.

@echo off

if [%1]==[] goto usage
@echo This should not execute
@echo Done.
goto :eof
:usage
@echo Usage: %0 ^<EnvironmentName^>
exit /B 1

SQL Query to find the last day of the month

dateadd(month,1+datediff(month,0,getdate()),-1)

To check run:

print dateadd(month,1+datediff(month,0,@date),-1)

How to restrict UITextField to take only numbers in Swift?

An approach that solves both decimal and Int:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentText = textField.text
    let futureString = currentText.substring(toIndex: range.location) + string + currentText.substring(fromIndex: range.location + range.length)
    
    if futureString.count == 0 {
        return true
    }
    
    if isDecimal {
        if let numberAsDouble = Double(futureString), numberAsDouble.asPrice.count >= futureString.count {
            return true
        }
    } else if let numberAsInt = Int(futureString), "\(numberAsInt)".count == futureString.count {
        return true
    }
    
    return false
}

Turning multi-line string into single comma-separated

awk one liner

$ awk '{printf (NR>1?",":"") $2}' file

+12.0,+15.5,+9.0,+13.5

What is the difference between a static and const variable?

The short answer:

A const is a promise that you will not try to modify the value once set.

A static variable means that the object's lifetime is the entire execution of the program and it's value is initialized only once before the program startup. All statics are initialized if you do not explicitly set a value to them.The manner and timing of static initialization is unspecified.

C99 borrowed the use of const from C++. On the other hand, static has been the source of many debates (in both languages) because of its often confusing semantics.

Also, with C++0x until C++11 the use of the static keyword was deprecated for declaring objects in namespace scope. This deprecation was removed in C++11 for various reasons (see here).

The longer answer: More on the keywords than you wanted to know (right from the standards):

C99

#include <fenv.h>
#pragma STDC FENV_ACCESS ON

/* file scope, static storage, internal linkage */
static int i1; // tentative definition, internal linkage
extern int i1; // tentative definition, internal linkage

int i2; // external linkage, automatic duration (effectively lifetime of program)

int *p = (int []){2, 4}; // unnamed array has static storage

/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // static, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"}  // static, non-modifiable


void f(int m)
{
    static int vla[ m ]; // err

    float w[] = { 0.0/0.0 }; // raises an exception

    /* block scope, static storage, no-linkage */
    static float x = 0.0/0.0; // does not raise an exception
    /* ... */
     /* effect on string literals */
    char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
    char *p = (char []){"/tmp/fileXXXXXX"}; // automatic storage, modifiable
    const char *cp = (const char []){"/tmp/fileXXXXXX"}  // automatic storage, non-modifiable

}

inline void bar(void)
{
     const static int x = 42; // ok
     // Note: Since an inline definition is distinct from the 
     // corresponding external definition and from any other
     // corresponding inline definitions in other translation 
     // units, all corresponding objects with static storage
     // duration are also distinct in each of the definitions
     static int y = -42; // error, inline function definition
}

// the last declaration also specifies that the argument 
// corresponding to a in any call to f must be a non-null 
// pointer to the first of at least three arrays of 5 doubles
void f(double a[static 3][5]);

static void g(void); // internal linkage

C++

Has the same semantics mostly except as noted in the short answer. Also, there are no parameter qualifying statics.

extern "C" {
static void f4(); // the name of the function f4 has
                  // internal linkage (not C language
                  // linkage) and the function’s type
                  // has C language linkage.
}

class S {
   mutable static int i; // err
   mutable static int j; // err
   static int k; // ok, all instances share the same member
};

inline void bar(void)
{
     const static int x = 42; // ok
     static int y = -42; // ok
}

There are a few more nuances of C++'s static that I leave out here. Have a look at a book or the standard.

Select rows having 2 columns equal value

Actually this would go faster in most of cases:

SELECT *
FROM table ta1
JOIN table ta2 on ta1.id != ta2.id
WHERE ta1.c2 = ta2.c2 and ta1.c3 = ta2.c3 and ta1.c4 = ta2.c4

You join on different rows which have the same values. I think it should work. Correct me if I'm wrong.

Node Version Manager install - nvm command not found

For MacOS;

Run on Terminal >

open ~/.bash_profile

Paste all of this=

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm

Align button at the bottom of div using CSS

Parent container has to have this:

position: relative;

Button itself has to have this:

position: relative;
bottom: 20px;
right: 20px;

or whatever you like

How to access parent scope from within a custom directive *with own scope* in AngularJS?

Having tried everything, I finally came up with a solution.

Just place the following in your template:

{{currentDirective.attr = parentDirective.attr; ''}}

It just writes the parent scope attribute/variable you want to access to the current scope.

Also notice the ; '' at the end of the statement, it's to make sure there's no output in your template. (Angular evaluates every statement, but only outputs the last one).

It's a bit hacky, but after a few hours of trial and error, it does the job.

How do I turn a C# object into a JSON string in .NET?

Use these tools for generating a C# class, and then use this code to serialize your object:

 var json = new JavaScriptSerializer().Serialize(obj);

How to create an empty array in Swift?

Here are some common tasks in Swift 4 you can use as a reference until you get used to things.

    let emptyArray = [String]()
    let emptyDouble: [Double] = []

    let preLoadArray = Array(repeating: 0, count: 10) // initializes array with 10 default values of the number 0

    let arrayMix = [1, "two", 3] as [Any]
    var arrayNum = [1, 2, 3]
    var array = ["1", "two", "3"]
    array[1] = "2"
    array.append("4")
    array += ["5", "6"]
    array.insert("0", at: 0)
    array[0] = "Zero"
    array.insert(contentsOf: ["-3", "-2", "-1"], at: 0)
    array.remove(at: 0)
    array.removeLast()
    array = ["Replaces all indexes with this"]
    array.removeAll()

    for item in arrayMix {
        print(item)
    }

    for (index, element) in array.enumerated() {
        print(index)
        print(element)
    }

    for (index, _) in arrayNum.enumerated().reversed() {
        arrayNum.remove(at: index)
    }

    let words = "these words will be objects in an array".components(separatedBy: " ")
    print(words[1])

    var names = ["Jemima", "Peter", "David", "Kelly", "Isabella", "Adam"]
    names.sort() // sorts names in alphabetical order

    let nums = [1, 1234, 12, 123, 0, 999]
    print(nums.sorted()) // sorts numbers from lowest to highest

What does $1 [QSA,L] mean in my .htaccess file?

If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,

RewriteCond %{REQUEST_FILENAME} !-d

and if the requested filename is not a regular file that exists,

RewriteCond %{REQUEST_FILENAME} !-f

and if the requested filename is not a symbolic link,

RewriteCond %{REQUEST_FILENAME} !-l

then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Apache docs #flag_qsa

Another Example:

RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]

With the [QSA] flag, a request for

/pages/123?one=two

will be mapped to

/page.php?page=123&one=two

Enable vertical scrolling on textarea

Try this: http://jsfiddle.net/8fv6e/8/

It is another version of the answers.

HTML:

<label for="aboutDescription" id="aboutHeading">About</label>
<textarea rows="15" cols="50" id="aboutDescription"
    style="max-height:100px;min-height:100px; resize: none"></textarea>
<a  id="imageURLId" target="_blank">Go to
    HomePage</a>

CSS:

#imageURLId{
font-size: 14px;
font-weight: normal;
resize: none;
overflow-y: scroll;

}

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

Use .get(), which if the key is not found, returns None.

for i in keySet:
    temp = myDict.get(i)
    if temp is not None:
        print temp
        break

How to create a backup of a single table in a postgres database?

If you prefer a graphical user interface, you can use pgAdmin III (Linux/Windows/OS X). Simply right click on the table of your choice, then "backup". It will create a pg_dump command for you.

enter image description here

enter image description here

enter image description here

Filter output in logcat by tagname

In case someone stumbles in on this like I did, you can filter on multiple tags by adding a comma in between, like so:

adb logcat -s "browser","webkit"

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

If you need profile-specific control the in your application-{profile}.properties file

org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false

Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/

Java Serializable Object to Byte Array

Another interesting method is from com.fasterxml.jackson.databind.ObjectMapper

byte[] data = new ObjectMapper().writeValueAsBytes(JAVA_OBJECT_HERE)

Maven Dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

d3 add text to circle

Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:

enter image description here

The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same div in a page header.

The main code is:

var width = 960,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)

d3.json("data.json", function(json) {
    /* Define the data for the circles */
    var elem = svg.selectAll("g")
        .data(json.nodes)

    /*Create and place the "blocks" containing the circle and the text */  
    var elemEnter = elem.enter()
        .append("g")
        .attr("transform", function(d){return "translate("+d.x+",80)"})

    /*Create the circle for each block */
    var circle = elemEnter.append("circle")
        .attr("r", function(d){return d.r} )
        .attr("stroke","black")
        .attr("fill", "white")

    /* Create the text for each block */
    elemEnter.append("text")
        .attr("dx", function(d){return -20})
        .text(function(d){return d.label})
})

and the json file is:

{"nodes":[
  {"x":80, "r":40, "label":"Node 1"}, 
  {"x":200, "r":60, "label":"Node 2"}, 
  {"x":380, "r":80, "label":"Node 3"}
]}

The resulting html code shows the encapsulation you want:

<svg width="960" height="500">
    <g transform="translate(80,80)">
        <circle r="40" stroke="black" fill="white"></circle>
        <text dx="-20">Node 1</text>
    </g>
    <g transform="translate(200,80)">
        <circle r="60" stroke="black" fill="white"></circle>
        <text dx="-20">Node 2</text>
    </g>
    <g transform="translate(380,80)">
        <circle r="80" stroke="black" fill="white"></circle>
        <text dx="-20">Node 3</text>
    </g>
</svg>

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Your example code is wrong. This works:

import datetime

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.

Git: How to return from 'detached HEAD' state

If you remember which branch was checked out before (e.g. master) you could simply

git checkout master

to get out of detached HEAD state.

Generally speaking: git checkout <branchname> will get you out of that.

If you don't remember the last branch name, try

git checkout -

This also tries to check out your last checked out branch.

Callback functions in Java

If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well.

public class Main {

    public interface Visitor{
        int doJob(int a, int b);
    }


    public static void main(String[] args) {
        Visitor adder = new Visitor(){
            public int doJob(int a, int b) {
                return a + b;
            }
        };

        Visitor multiplier = new Visitor(){
            public int doJob(int a, int b) {
                return a*b;
            }
        };

        System.out.println(adder.doJob(10, 20));
        System.out.println(multiplier.doJob(10, 20));

    }
}

GIT vs. Perforce- Two VCS will enter... one will leave

I have no experience with Git, but I have with Mercurial which is also a distributed VCS. It depends on the project really, but in our case a distributed VCS suited the project as basically eliminated frequent broken builds.

I think it depends on the project really, as some are better suited towards a client-server VCS, and others towads a distributed one.

How can I use grep to find a word inside a folder?

  1. grep -r "yourstring" * Will find "yourstring" in any files and folders

Now if you want to look for two different strings at the same time you can always use option E and add words for the search. example after the break

  1. grep -rE "yourstring|yourotherstring|$" * will search for list locations where yourstring or yourotherstring matches

Easiest way to convert a List to a Set in Java

Let's not forget our relatively new friend, stream API. If you need to preprocess list before converting it to a set, it's better to have something like:

list.stream().<here goes some preprocessing>.collect(Collectors.toSet());

What exactly is an instance in Java?

When you use the keyword new for example JFrame j = new JFrame(); you are creating an instance of the class JFrame.

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

Take a look here
Creating Objects


The types of the Java programming language are divided into two categories: primitive types and reference types.
The reference types are class types, interface types, and array types.
There is also a special null type.
An object is a dynamically created instance of a class type or a dynamically created array.
The values of a reference type are references to objects.

Refer Types, Values, and Variables for more information

Dynamic button click event handler

Just to round out Reed's answer, you can either get the Button objects from the Form or other container and add the handler, or you could create the Button objects programmatically.
If you get the Button objects from the Form or other container, then you can iterate over the Controls collection of the Form or other container control, such as Panel or FlowLayoutPanel and so on. You can then just add the click handler with
AddHandler ctrl.Click, AddressOf Me.Button_Click (variables as in the code below),
but I prefer to check the type of the Control and cast to a Button so as I'm not adding click handlers for any other controls in the container (such as Labels). Remember that you can add handlers for any event of the Button at this point using AddHandler.
Alternatively, you can create the Button objects programmatically, as in the second block of code below.
Then, of course, you have to write the handler method, as in the third code block below.

Here is an example using Form as the container, but you're probably better off using a Panel or some other container control.

Dim btn as Button = Nothing
For Each ctrl As Control in myForm.Controls
    If TypeOf ctrl Is Button Then
        btn = DirectCast(ctrl, Button)
        AddHandler btn.Click, AddressOf Me.Button_Click   ' From answer by Reed.
    End If
 Next

Alternatively creating the Buttons programmatically, this time adding to a Panel container.

Dim Panel1 As new Panel()
For i As Integer = 1 to 100
    btn = New Button()
    ' Set Button properties or call a method to do so.
    Panel1.Controls.Add(btn)  ' Add Button to the container.
    AddHandler btn.Click, AddressOf Me.Button_Click   ' Again from the answer by Reed.
Next

Then your handler will look something like this

Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    ' Handle your Button clicks here
End Sub

excel delete row if column contains value from to-remove-list

Given sheet 2:

ColumnA
-------
apple
orange

You can flag the rows in sheet 1 where a value exists in sheet 2:

ColumnA  ColumnB
-------  --------------
pear     =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple    =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry   =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange   =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum     =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")

The resulting data looks like this:

ColumnA  ColumnB
-------  --------------
pear     Keep
apple    Delete
cherry   Keep
orange   Delete
plum     Keep

You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.

What is the difference between private and protected members of C++ classes?

private is preferred for member data. Members in C++ classes are private by default.

public is preferred for member functions, though it is a matter of opinion. At least some methods must be accessible. public is accessible to all. It is the most flexible option and least safe. Anybody can use them, and anybody can misuse them.

private is not accessible at all. Nobody can use them outside the class, and nobody can misuse them. Not even in derived classes.

protected is a compromise because it can be used in derived classes. When you derive from a class, you have a good understanding of the base class, and you are careful not to misuse these members.

MFC is a C++ wrapper for Windows API, it prefers public and protected. Classes generated by Visual Studio wizard have an ugly mix of protected, public, and private members. But there is some logic to MFC classes themselves.

Members such as SetWindowText are public because you often need to access these members.

Members such as OnLButtonDown, handle notifications received by the window. They should not be accessed, therefore they are protected. You can still access them in the derived class to override these functions.

Some members have to do threads and message loops, they should not be accessed or override, so they are declared as private

In C++ structures, members are public by default. Structures are usually used for data only, not methods, therefore public declaration is considered safe.

Using a bitmask in C#

To combine bitmasks you want to use bitwise-or. In the trivial case where every value you combine has exactly 1 bit on (like your example), it's equivalent to adding them. If you have overlapping bits however, or'ing them handles the case gracefully.

To decode the bitmasks you and your value with a mask, like so:

if(val & (1<<1)) SusanIsOn();
if(val & (1<<2)) BobIsOn();
if(val & (1<<3)) KarenIsOn();

What are these ^M's that keep showing up in my files in emacs?

See also:

Hiding ^M in emacs

Be careful if you choose to remove the ^M characters and resubmit to your team. They may see a file without carriage returns afterward.

How can I get the value of a registry key from within a batch script?

This works if the value contains a space:

FOR /F "skip=2 tokens=1,2*" %%A IN ('REG QUERY "%KEY_NAME%" /v "%VALUE_NAME%" 2^>nul') DO (
    set ValueName=%%A
    set ValueType=%%B
    set ValueValue=%%C
)

if defined ValueName (
    echo Value Name = %ValueName%
    echo Value Type = %ValueType%
    echo Value Value = %ValueValue%
) else (
    @echo "%KEY_NAME%"\"%VALUE_NAME%" not found.
)

Recyclerview and handling different type of row inflation

It is quite tricky but that much hard, just copy the below code and you are done

package com.yuvi.sample.main;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import com.yuvi.sample.R;

import java.util.List;

/**
 * Created by yubraj on 6/17/15.
 */

public class NavDrawerAdapter extends RecyclerView.Adapter<NavDrawerAdapter.MainViewHolder> {
    List<MainOption> mainOptionlist;
    Context context;
    private static final int TYPE_PROFILE = 1;
    private static final int TYPE_OPTION_MENU = 2;
    private int selectedPos = 0;
    public NavDrawerAdapter(Context context){
        this.mainOptionlist = MainOption.getDrawableDataList();
        this.context = context;
    }

    @Override
    public int getItemViewType(int position) {
        return (position == 0? TYPE_PROFILE : TYPE_OPTION_MENU);
    }

    @Override
    public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType){
            case TYPE_PROFILE:
                return new ProfileViewHolder(LayoutInflater.from(context).inflate(R.layout.row_profile, parent, false));
            case TYPE_OPTION_MENU:
                return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.row_nav_drawer, parent, false));
        }
        return null;
    }

    @Override
    public void onBindViewHolder(MainViewHolder holder, int position) {
        if(holder.getItemViewType() == TYPE_PROFILE){
            ProfileViewHolder mholder = (ProfileViewHolder) holder;
            setUpProfileView(mholder);
        }
        else {
            MyViewHolder mHolder = (MyViewHolder) holder;
            MainOption mo = mainOptionlist.get(position);
            mHolder.tv_title.setText(mo.title);
            mHolder.iv_icon.setImageResource(mo.icon);
            mHolder.itemView.setSelected(selectedPos == position);
        }
    }

    private void setUpProfileView(ProfileViewHolder mholder) {

    }

    @Override
    public int getItemCount() {
        return mainOptionlist.size();
    }




public class MyViewHolder extends MainViewHolder{
    TextView tv_title;
    ImageView iv_icon;

    public MyViewHolder(View v){
        super(v);
        this.tv_title = (TextView) v.findViewById(R.id.tv_title);
        this.iv_icon = (ImageView) v.findViewById(R.id.iv_icon);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Redraw the old selection and the new
                notifyItemChanged(selectedPos);
                selectedPos = getLayoutPosition();
                notifyItemChanged(selectedPos);
            }
        });
    }
}
    public class ProfileViewHolder extends MainViewHolder{
        TextView tv_name, login;
        ImageView iv_profile;

        public ProfileViewHolder(View v){
            super(v);
            this.tv_name = (TextView) v.findViewById(R.id.tv_profile);
            this.iv_profile = (ImageView) v.findViewById(R.id.iv_profile);
            this.login = (TextView) v.findViewById(R.id.tv_login);
        }
    }

    public void trace(String tag, String message){
        Log.d(tag , message);
    }
    public class MainViewHolder extends  RecyclerView.ViewHolder {
        public MainViewHolder(View v) {
            super(v);
        }
    }


}

enjoy !!!!

Resize a picture to fit a JLabel

public static void main(String s[]) 
  {

    BufferedImage image = null;
    try 
    {
        image = ImageIO.read(new File("your image path"));

    } catch (Exception e) 
    {
        e.printStackTrace();
    }

    ImageIcon imageIcon = new ImageIcon(fitimage(image, label.getWidth(), label.getHeight()));
    jLabel1.setIcon(imageIcon);
}


private Image fitimage(Image img , int w , int h)
{
    BufferedImage resizedimage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedimage.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(img, 0, 0,w,h,null);
    g2.dispose();
    return resizedimage;
}

how to overwrite css style

You can create one more class naming

.flex-control-thumbs-without-width li {
width: auto;
float: initial; or none
}

Add this class whenever you need to override like below,

<li class="flex-control-thumbs flex-control-thumbs-without-width"> </li>

And do remove whenever you don't need for other <li>

How do I make a request using HTTP basic authentication with PHP curl?

You want this:

curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  

Zend has a REST client and zend_http_client and I'm sure PEAR has some sort of wrapper. But its easy enough to do on your own.

So the entire request might look something like this:

$ch = curl_init($host);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($ch);
curl_close($ch);

How can I align text directly beneath an image?

I am not an expert in HTML but here is what worked for me:

<div class="img-with-text-below">
    <img src="your-image.jpg" alt="alt-text" />
    <p><center>Your text</center></p>
</div>

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

check your application.properties

changing

spring.datasource.driverClassName=com.mysql.jdbc.Driver

to

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

worked for me. Full config:

spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=
spring.datasource.password=   
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update

Import PEM into Java Key Store

In my case I had a pem file which contained two certificates and an encrypted private key to be used in mutual SSL authentication. So my pem file looked like this:

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

-----BEGIN RSA PRIVATE KEY-----

Proc-Type: 4,ENCRYPTED

DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9

...

-----END RSA PRIVATE KEY-----

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

Here is what I did

Split the file into three separate files, so that each one contains just one entry, starting with ---BEGIN.. and ending with ---END.. lines. Lets assume we now have three files: cert1.pem, cert2.pem, and pkey.pem.

Convert pkey.pem into DER format using openssl and the following syntax:

openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER

Note, that if the private key is encrypted you need to supply a password( obtain it from the supplier of the original pem file ) to convert to DER format, openssl will ask you for the password like this: "enter a passphrase for pkey.pem: ".

If conversion is successful, you will get a new file called pkey.der.

Create a new java keystore and import the private key and the certificates:

String keypass = "password";  // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");

// this section does not make much sense to me, 
// but I will leave it intact as this is how it was in the original example I found on internet:   
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore"  ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ),    keypass.toCharArray());
// end of section..


// read the key file from disk and create a PrivateKey

FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();

PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);


// read the certificates from the files and load them into the key store:

Collection  col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection  col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));

Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };

String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();

ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);

// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );

// save the key store to a file         
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());

(optional) Verify the content of your new key store:

$ keytool -list -keystore mykeystore -storepass password

Keystore type: JKS Keystore provider: SUN

Your keystore contains 3 entries:

  • cn=...,ou=...,o=.., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 2C:B8: ...

  • importkey, Sep 2, 2014, PrivateKeyEntry, Certificate fingerprint (SHA1): 9C:B0: ...

  • cn=...,o=...., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 83:63: ...

(optional) Test your certificates and private key from your new key store against your SSL server: ( You may want to enable debugging as an VM option: -Djavax.net.debug=all )

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        SSLSocketFactory factory = sclx.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
        socket.startHandshake();

        //if no exceptions are thrown in the startHandshake method, then everything is fine..

Finally register your certificates with HttpsURLConnection if plan to use it:

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        HostnameVerifier hv = new HostnameVerifier()
        {
            public boolean verify(String urlHostName, SSLSession session)
            {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
                {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

How to change the icon of an Android app in Eclipse?

In your AndroidManifest.xml file

<application
        android:name="ApplicationClass"
        android:icon="@drawable/ic_launcher"  <--------
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

Good Linux (Ubuntu) SVN client

You could also look at git-svn, which is essentially a git front-end to subversion.

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.

Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/

Since I need to post code here is what each collapsible "section" should look like ->

<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
    <td>1</td>
    <td>05 May 2013</td>
    <td>Credit Account</td>
    <td class="text-success">$150.00</td>
    <td class="text-error"></td>
    <td class="text-success">$150.00</td>
</tr>

<tr>
    <td colspan="6" class="hiddenRow">
        <div class="accordion-body collapse" id="demo1">Demo1</div>
    </td>
</tr>

How do I programmatically set the value of a select box element using JavaScript?

Should be something along these lines:

function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
  if (dl.options[i].value == inVal){
    el=i;
    break;
  }
}
dl.selectedIndex = el;
}

How to clear all inputs, selects and also hidden fields in a form using jQuery?

I had a slightly more specialised case, a search form which had an input which had autocomplete for a person name. The Javascript code set a hidden input which from.reset() does not clear.

However I didn't want to reset all hidden inputs. There I added a class, search-value, to the hidden inputs which where to be cleared.

$('form#search-form').reset();
$('form#search-form input[type=hidden].search-value').val('');

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

I had to do rake clean --force. Then did gem install rake and so forth.

Parse JSON in TSQL

I developed my own SQL Server 2016+ JSON parser a while ago. I use this in all my projects - very good performance. I hope it can help someone else too.

Full code of the function:

ALTER FUNCTION [dbo].[SmartParseJSON] (@json NVARCHAR(MAX))
RETURNS @Parsed TABLE (Parent NVARCHAR(MAX),Path NVARCHAR(MAX),Level INT,Param NVARCHAR(4000),Type NVARCHAR(255),Value NVARCHAR(MAX),GenericPath NVARCHAR(MAX))
AS
BEGIN
    -- Author: Vitaly Borisov
    -- Create date: 2018-03-23
    ;WITH crData AS (
        SELECT CAST(NULL AS NVARCHAR(4000)) COLLATE DATABASE_DEFAULT AS [Parent]
            ,j.[Key] AS [Param],j.Value,j.Type
            ,j.[Key] AS [Path],0 AS [Level]
            ,j.[Key] AS [GenericPath]
        FROM OPENJSON(@json) j
        UNION ALL
        SELECT CAST(d.Path AS NVARCHAR(4000)) COLLATE DATABASE_DEFAULT AS [Parent]
            ,j.[Key] AS [Param],j.Value,j.Type 
            ,d.Path + CASE d.Type WHEN 5 THEN '.' WHEN 4 THEN '[' ELSE '' END + j.[Key] + CASE d.Type WHEN 4 THEN ']' ELSE '' END AS [Path]
            ,d.Level+1
            ,d.GenericPath + CASE d.Type WHEN 5 THEN '.' + j.[Key] ELSE '' END AS [GenericPath]
        FROM crData d 
        CROSS APPLY OPENJSON(d.Value) j
        WHERE ISJSON(d.Value) = 1
    )
    INSERT INTO @Parsed(Parent, Path, Level, Param, Type, Value, GenericPath)
    SELECT d.Parent,d.Path,d.Level,d.Param
        ,CASE d.Type 
            WHEN 1 THEN CASE WHEN TRY_CONVERT(UNIQUEIDENTIFIER,d.Value) IS NOT NULL THEN 'UNIQUEIDENTIFIER' ELSE 'NVARCHAR(MAX)' END 
            WHEN 2 THEN 'INT' 
            WHEN 3 THEN 'BIT' 
            WHEN 4 THEN 'Array' 
            WHEN 5 THEN 'Object' 
                ELSE 'NVARCHAR(MAX)'
         END AS [Type]
        ,CASE 
            WHEN d.Type = 3 AND d.Value = 'true' THEN '1'
            WHEN d.Type = 3 AND d.Value = 'false' THEN '0'
                ELSE d.Value
         END AS [Value]
        ,d.GenericPath
    FROM crData d
    OPTION(MAXRECURSION 1000) /*Limit to 1000 levels deep*/
    ;
    RETURN;
END
GO

Example of use:

DECLARE @json NVARCHAR(MAX) = '{"Objects":[{"SomeKeyID":1,"Value":3}],"SomeParam":"Lalala"}';
SELECT j.Parent, j.Path, j.Level, j.Param, j.Type, j.Value, j.GenericPath 
FROM dbo.SmartParseJSON(@json) j;

Example of multilevel use:

DECLARE @json NVARCHAR(MAX) = '{"Objects":[{"SomeKeyID":1,"Value":3}],"SomeParam":"Lalala"}';
DROP TABLE IF EXISTS #ParsedData;
SELECT j.Parent, j.Path, j.Level, j.Param, j.Type, j.Value, j.GenericPath 
INTO #ParsedData
FROM dbo.SmartParseJSON(@json) j;

SELECT COALESCE(p2.GenericPath,p.GenericPath) AS [GenericPath]
    ,COALESCE(p2.Param,p.Param) AS [Param]
    ,COALESCE(p2.Value,p.Value) AS [Value]
FROM #ParsedData p
LEFT JOIN #ParsedData p1 ON p1.Parent = p.Path AND p1.Level = 1
LEFT JOIN #ParsedData p2 ON p2.Parent = p1.Path AND p2.Level = 2
WHERE p.Level = 0
;
DROP TABLE IF EXISTS #ParsedData;

JavaFX Application Icon

What do you think about creating new package i.e image.icons in your src directory and moving there you .png images? Than you just need to write:

Image image = new Image("/image/icons/nameOfImage.png");
primaryStage.getIcons().add(image);

This solution works for me perfectly, but still I'm not sure if it's correct (beginner here).

How do I launch the Android emulator from the command line?

The android create avd command is deprecated. It's now recommended to use avdmanager instead to launch emulators from the command line.

First, create a new emulator if one doesn't already exist:

avdmanager create avd --name "MyEmulator" -k "system-images;android-
26;google_apis;x86"

This assumes that you already have an X86 system image installed that matches API 26, and has the Google APIs installed.

You can then launch the emulator with emulator @MyEmulator.

SQL Server: Maximum character length of object names

128 characters. This is the max length of the sysname datatype (nvarchar(128)).

How to force Docker for a clean build of an image

You can manage the builder cache with docker builder

To clean all the cache with no prompt: docker builder prune -af

how to make a cell of table hyperlink

Why not combine the onclick method with the <a> element inside the <td> for backup for non-JS? Seems to work great.

<td onclick="location.href='yourpage.html'"><a href="yourpage.html">Link</a></td>

How to set a ripple effect on textview or imageview on Android?

for circle ripple : android:background="?attr/selectableItemBackgroundBorderless"

for rectangle ripple : android:background="?attr/selectableItemBackground"

JQuery datepicker not working

You did not include the datepicker library

so add

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>

to your <head> tag

live demo

Is there a link to the "latest" jQuery library on Google APIs?

What about this one?

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

I think this is always the latest version - Correct me, if I'm wrong.

jQuery autocomplete with callback ajax json

If you are returning a complex json object you need to modify you success function of your auto-complete as follows.

$.ajax({
    url: "/Employees/SearchEmployees",
    dataType: "json",
    data: {
        searchText: request.term
    },
    success: function (data) {
        response($.map(data.employees, function (item) {
            return {
                label: item.name,
                value: item.id
            };
        }));
    }
});

Find first element by predicate

return dataSource.getParkingLots()
                 .stream()
                 .filter(parkingLot -> Objects.equals(parkingLot.getId(), id))
                 .findFirst()
                 .orElse(null);

I had to filter out only one object from a list of objects. So i used this, hope it helps.

Using DataContractSerializer to serialize, but can't deserialize back

Here is how I've always done it:

    public static string Serialize(object obj) {
        using(MemoryStream memoryStream = new MemoryStream())
        using(StreamReader reader = new StreamReader(memoryStream)) {
            DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
            serializer.WriteObject(memoryStream, obj);
            memoryStream.Position = 0;
            return reader.ReadToEnd();
        }
    }

    public static object Deserialize(string xml, Type toType) {
        using(Stream stream = new MemoryStream()) {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
            stream.Write(data, 0, data.Length);
            stream.Position = 0;
            DataContractSerializer deserializer = new DataContractSerializer(toType);
            return deserializer.ReadObject(stream);
        }
    }

Android emulator-5554 offline

Did you try deleting and recreating your AVD? You can manually delete the AVD files by going to the directory they're stored in (in your user's /.android/avd subdirectory).

Removing elements by class name?

I prefer using forEach over for/while looping. In order to use it's necessary to convert HTMLCollection to Array first:

Array.from(document.getElementsByClassName("post-text"))
    .forEach(element => element.remove());

Pay attention, it's not necessary the most efficient way. Just much more elegant for me.

How can I change IIS Express port for a site

I'm using VS 2019.

if your solution has more than one project / class libraries etc, then you may not see the Web tab when clicking on Solution explorer properties.

Clicking on the MVC project and then checking properties will reveal the web tab where you can change the port.

How to find all trigger associated with a table with SQL Server?

select so.name, text
from sysobjects so, syscomments sc
where type = 'TR'
and so.id = sc.id
and text like '%YourTableName%'

This way you can list out all the triggers associated with the given table.

fcntl substitute on Windows

Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker

It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.

The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker

Forms authentication timeout vs sessionState timeout

The slidingExpiration=true value is basically saying that after every request made, the timer is reset and as long as the user makes a request within the timeout value, he will continue to be authenticated.

This is not correct. The authentication cookie timeout will only be reset if half the time of the timeout has passed.

See for example https://support.microsoft.com/de-ch/kb/910439/en-us or https://itworksonmymachine.wordpress.com/2008/07/17/forms-authentication-timeout-vs-session-timeout/

jQuery How to Get Element's Margin and Padding?

According to the jQuery documentation, shorthand CSS properties are not supported.

Depending on what you mean by "total padding", you may be able to do something like this:

var $img = $('img');
var paddT = $img.css('padding-top') + ' ' + $img.css('padding-right') + ' ' + $img.css('padding-bottom') + ' ' + $img.css('padding-left');

Is Visual Studio Community a 30 day trial?

Sign in and the 30 day trial will go away!

"And if you're already signed in, sign out then sign in again." –b1nary.atr0phy

Lollipop : draw behind statusBar with its color set to transparent

Instead of

<item name="android:statusBarColor">@android:color/transparent</item>

Use the following:

<item name="android:windowTranslucentStatus">true</item>

And make sure to remove the top padding (which is added by default) on your 'MainActivity' layout.

Note that this does not make the status bar fully transparent, and there will still be a "faded black" overlay over your status bar.

Call static methods from regular ES6 class methods

I stumbled over this thread searching for answer to similar case. Basically all answers are found, but it's still hard to extract the essentials from them.

Kinds of Access

Assume a class Foo probably derived from some other class(es) with probably more classes derived from it.

Then accessing

  • from static method/getter of Foo
    • some probably overridden static method/getter:
      • this.method()
      • this.property
    • some probably overridden instance method/getter:
      • impossible by design
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • impossible by design
  • from instance method/getter of Foo
    • some probably overridden static method/getter:
      • this.constructor.method()
      • this.constructor.property
    • some probably overridden instance method/getter:
      • this.method()
      • this.property
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • not possible by intention unless using some workaround:
        • Foo.prototype.method.call( this )
        • Object.getOwnPropertyDescriptor( Foo.prototype,"property" ).get.call(this);

Keep in mind that using this isn't working this way when using arrow functions or invoking methods/getters explicitly bound to custom value.

Background

  • When in context of an instance's method or getter
    • this is referring to current instance.
    • super is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo's prototype).
    • definition of instance's class used on creating it is available per this.constructor.
  • When in context of a static method or getter there is no "current instance" by intention and so
    • this is available to refer to the definition of current class directly.
    • super is not referring to some instance either, but to static methods and getters written in context of some class current one is extending.

Conclusion

Try this code:

_x000D_
_x000D_
class A {_x000D_
  constructor( input ) {_x000D_
    this.loose = this.constructor.getResult( input );_x000D_
    this.tight = A.getResult( input );_x000D_
    console.log( this.scaledProperty, Object.getOwnPropertyDescriptor( A.prototype, "scaledProperty" ).get.call( this ) );_x000D_
  }_x000D_
_x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 100;_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return input * this.scale;_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 2;_x000D_
  }_x000D_
}_x000D_
_x000D_
class B extends A {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
    this.tight = B.getResult( input ) + " (of B)";_x000D_
  }_x000D_
  _x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 10000;_x000D_
  }_x000D_
_x000D_
  static get scale() {_x000D_
    return 4;_x000D_
  }_x000D_
}_x000D_
_x000D_
class C extends B {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 5;_x000D_
  }_x000D_
}_x000D_
_x000D_
class D extends C {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return super.getResult( input ) + " (overridden)";_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 10;_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
let instanceA = new A( 4 );_x000D_
console.log( "A.loose", instanceA.loose );_x000D_
console.log( "A.tight", instanceA.tight );_x000D_
_x000D_
let instanceB = new B( 4 );_x000D_
console.log( "B.loose", instanceB.loose );_x000D_
console.log( "B.tight", instanceB.tight );_x000D_
_x000D_
let instanceC = new C( 4 );_x000D_
console.log( "C.loose", instanceC.loose );_x000D_
console.log( "C.tight", instanceC.tight );_x000D_
_x000D_
let instanceD = new D( 4 );_x000D_
console.log( "D.loose", instanceD.loose );_x000D_
console.log( "D.tight", instanceD.tight );
_x000D_
_x000D_
_x000D_

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

It would be more helpful if you posed a more complete working (or in this case non-working) example.

I tried the following:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(1000)

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, density=True)
fig.canvas.draw()
plt.show()

This will indeed produce a bar-chart histogram with a y-axis that goes from [0,1].

Further, as per the hist documentation (i.e. ax.hist? from ipython), I think the sum is fine too:

*normed*:
If *True*, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)*dbin)``.  In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::

    pdf, bins, patches = ax.hist(...)
    print np.sum(pdf * np.diff(bins))

Giving this a try after the commands above:

np.sum(n * np.diff(bins))

I get a return value of 1.0 as expected. Remember that normed=True doesn't mean that the sum of the value at each bar will be unity, but rather than the integral over the bars is unity. In my case np.sum(n) returned approx 7.2767.

Plotting multiple lines, in different colors, with pandas dataframe

If you have seaborn installed, an easier method that does not require you to perform pivot:

import seaborn as sns

sns.lineplot(data=df, x='x', y='y', hue='color')

When to use RSpec let()?

Note to Joseph -- if you are creating database objects in a before(:all) they won't be captured in a transaction and you're much more likely to leave cruft in your test database. Use before(:each) instead.

The other reason to use let and its lazy evaluation is so you can take a complicated object and test individual pieces by overriding lets in contexts, as in this very contrived example:

context "foo" do
  let(:params) do
     { :foo => foo,  :bar => "bar" }
  end
  let(:foo) { "foo" }
  it "is set to foo" do
    params[:foo].should eq("foo")
  end
  context "when foo is bar" do
    let(:foo) { "bar" }
    # NOTE we didn't have to redefine params entirely!
    it "is set to bar" do
      params[:foo].should eq("bar")
    end
  end
end

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Integer.toString calls the static method in the class Integer. It does not need an instance of Integer.

If you call new Integer(i) you create an instance of type Integer, which is a full Java object encapsulating the value of your int. Then you call the toString method on it to ask it to return a string representation of itself.

If all you want is to print an int, you'd use the first one because it's lighter, faster and doesn't use extra memory (aside from the returned string).

If you want an object representing an integer value—to put it inside a collection for example—you'd use the second one, since it gives you a full-fledged object to do all sort of things that you cannot do with a bare int.

OPTION (RECOMPILE) is Always Faster; Why?

There are times that using OPTION(RECOMPILE) makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:

EXEC sp_updatestats

And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.

Adding OPTION(RECOMPILE) rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy but maybe we are just using different terms for the same thing.

When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.

In summary - I don't see any reason that OPTION(RECOMPILE) would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.

And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

How to delete parent element using jQuery

$('#' + catId).parent().remove('.subcatBtns');

How to align td elements in center

The best way to center content in a table (for example <video> or <img>) is to do the following:

_x000D_
_x000D_
<table width="100%" border="0" cellspacing="0" cellpadding="100%">
<tr>
<td>Video Tag 1 Here</td>
<td>Video Tag 2 Here</td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

Floating divs in Bootstrap layout

I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding

style="position: relative; bottom: 0px"

to your Widget2 tag. Also try:

style="position: absolute; bottom: 0px"

if you want to snap your widget to the bottom of the screen.

I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.

Detecting endianness programmatically in a C++ program

untested, but in my mind, this should work? cause it'll be 0x01 on little endian, and 0x00 on big endian?

bool runtimeIsLittleEndian(void)
{
 volatile uint16_t i=1;
 return  ((uint8_t*)&i)[0]==0x01;//0x01=little, 0x00=big
}

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

In your example, the compiler has no way of knowing what type should TModel be. You could do something close to what you are probably trying to do with an extension method.

static class ModelExtensions
{
   public static IDictionary<string, object> GetHtmlAttributes<TModel, TProperty>
      (this TModel model, Expression<Func<TModel, TProperty>> propertyExpression)
   {
       return new Dictionary<string, object>();
   }
}

But you wouldn't be able to have anything similar to virtual, I think.

EDIT:

Actually, you can do virtual, using self-referential generics:

class ModelBase<TModel>
{
    public virtual IDictionary<string, object> GetHtmlAttributes<TProperty>
        (Expression<Func<TModel, TProperty>> propertyExpression)
    {
        return new Dictionary<string, object>();
    }
}

class FooModel : ModelBase<FooModel>
{
    public override IDictionary<string, object> GetHtmlAttributes<TProperty>
        (Expression<Func<FooModel, TProperty>> propertyExpression)
    {
        return new Dictionary<string, object> { { "foo", "bar" } };
    }
}

How to change href attribute using JavaScript after opening the link in a new window?

You can change this in the page load.

My intention is that when the page comes to the load function, switch the links (the current link in the required one)

Pandas: Subtracting two date columns and the result being an integer

You can divide column of dtype timedelta by np.timedelta64(1, 'D'), but output is not int, but float, because NaN values:

df_test['Difference'] = df_test['Difference'] / np.timedelta64(1, 'D')
print (df_test)
  First_Date Second Date  Difference
0 2016-02-09  2015-11-19        82.0
1 2016-01-06  2015-11-30        37.0
2        NaT  2015-12-04         NaN
3 2016-01-06  2015-12-08        29.0
4        NaT  2015-12-09         NaN
5 2016-01-07  2015-12-11        27.0
6        NaT  2015-12-12         NaN
7        NaT  2015-12-14         NaN
8 2016-01-06  2015-12-14        23.0
9        NaT  2015-12-15         NaN

Frequency conversion.

Make HTML5 video poster be same size as video itself

Depending on what browsers you're targeting, you could go for the object-fit property to solve this:

object-fit: cover;

or maybe fill is what you're looking for. Still under consideration for IE.

Creating a JavaScript cookie on a domain and reading it across sub domains

You want:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

Xcode 6.1 - How to uninstall command line tools?

An excerpt from an apple technical note (Thanks to matthias-bauch)

Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.

If your tools were downloaded separately from Xcode, then they are located at /Library/Developer/CommandLineTools on your system. Delete the CommandLineTools folder to uninstall them.

you could easily delete using terminal:

Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

Swift 3 - Comparing Date objects

Swift 5:

1) If you use Date type:

let firstDate  = Date()
let secondDate = Date()

print(firstDate > secondDate)  
print(firstDate < secondDate)
print(firstDate == secondDate)

2) If you use String type:

let firstStringDate  = "2019-05-22T09:56:00.1111111"
let secondStringDate = "2019-05-22T09:56:00.2222222"

print(firstStringDate > secondStringDate)  // false
print(firstStringDate < secondStringDate)  // true
print(firstStringDate == secondStringDate) // false 

I'm not sure or the second option works at 100%. But how much would I not change the values of firstStringDate and secondStringDate the result was correct.

Error: request entity too large

I too faced that issue, I was making a silly mistake by repeating the app.use(bodyParser.json()) like below:

app.use(bodyParser.json())
app.use(bodyParser.json({ limit: '50mb' }))

by removing app.use(bodyParser.json()), solved the problem.

What is Common Gateway Interface (CGI)?

CGI is an interface which tells the webserver how to pass data to and from an application. More specifically, it describes how request information is passed in environment variables (such as request type, remote IP address), how the request body is passed in via standard input, and how the response is passed out via standard output. You can refer to the CGI specification for details.

To use your image:

user (client) request for page ---> webserver ---[CGI]----> Server side Program ---> MySQL Server.

Most if not all, webservers can be configured to execute a program as a 'CGI'. This means that the webserver, upon receiving a request, will forward the data to a specific program, setting some environment variables and marshalling the parameters via standard input and standard output so the program can know where and what to look for.

The main benefit is that you can run ANY executable code from the web, given that both the webserver and the program know how CGI works. That's why you could write web programs in C or Bash with a regular CGI-enabled webserver. That, and that most programming environments can easily use standard input, standard output and environment variables.

In your case you most likely used another, specific for PHP, means of communication between your scripts and the webserver, this, as you well mention in your question, is an embedded interpreter called mod_php.

So, answering your questions:

What exactly is CGI?

See above.

Whats the big deal with /cgi-bin/*.cgi? Whats up with this? I don't know what is this cgi-bin directory on the server for. I don't know why they have *.cgi extensions.

That's the traditional place for cgi programs, many webservers come with this directory pre configured to execute all binaries there as CGI programs. The .cgi extension denotes an executable that is expected to work through the CGI.

Why does Perl always comes in the way. CGI & Perl (language). I also don't know whats up with these two. Almost all the time I keep hearing these two in combination "CGI & Perl". This book is another great example CGI Programming with Perl Why not "CGI Programming with PHP/JSP/ASP". I never saw such things.

Because Perl is ancient (older than PHP, JSP and ASP which all came to being when CGI was already old, Perl existed when CGI was new) and became fairly famous for being a very good language to serve dynamic webpages via the CGI. Nowadays there are other alternatives to run Perl in a webserver, mainly mod_perl.

CGI Programming in C this confuses me a lot. in C?? Seriously?? I don't know what to say. I"m just confused. "in C"?? This changes everything. Program needs to be compiled and executed. This entirely changes my view of web programming. When do I compile? How does the program gets executed (because it will be a machine code, so it must execute as a independent process). How does it communicate with the web server? IPC? and interfacing with all the servers (in my example MATLAB & MySQL) using socket programming? I'm lost!!

You compile the executable once, the webserver executes the program and passes the data in the request to the program and outputs the received response. CGI specifies that one program instance will be launched per each request. This is why CGI is inefficient and kind of obsolete nowadays.

They say that CGI is deprecated. Its no more in use. Is it so? What is its latest update?

CGI is still used when performance is not paramount and a simple means of executing code is required. It is inefficient for the previously stated reasons and there are more modern means of executing any program in a web enviroment. Currently the most famous is FastCGI.

How to change the URL from "localhost" to something else, on a local system using wampserver?

They are probably using a virtual host (http://www.keanei.com/2011/07/14/creating-virtual-hosts-with-wamp/)

You can go into your Apache configuration file (httpd.conf) or your virtual host configuration file (recommended) and add something like:

<VirtualHost *:80>
    DocumentRoot /www/ap-mispro
    ServerName ap-mispro

    # Other directives here
</VirtualHost>

And when you call up http://ap-mispro/ you would see whatever is in C:/wamp/www/ap-mispro (assuming default directory structure). The ServerName and DocumentRoot do no have to have the same name at all. Other factors needed to make this work:

  1. You have to make sure httpd-vhosts.conf is included by httpd.conf for your changes in that file to take effect.
  2. When you make changes to either file, you have to restart Apache to see your changes.
  3. You have to change your hosts file http://en.wikipedia.org/wiki/Hosts_(file) for your computer to know where to go when you type http://ap-mispro into your browser. This change to your hosts file will only apply to your computer - not that it sounds like you are trying from anyone else's.

There are plenty more things to know about virtual hosts but this should get you started.

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

Following is a simple code to read from SQL database. Database names is "database1". Table name is "table1". It contain two columns "uname" and "pass". Dont forget to add "sqljdbc4.jar" to your project. Download sqljdbc4.jar

public class NewClass {

    public static void main(String[] args) {

        Connection conn = null;
        String dbName = "database1";
        String serverip="192.168.100.100";
        String serverport="1433";
        String url = "jdbc:sqlserver://"+serverip+"\\SQLEXPRESS:"+serverport+";databaseName="+dbName+"";
        Statement stmt = null;
        ResultSet result = null;
        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        String databaseUserName = "admin";
        String databasePassword = "root";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, databaseUserName, databasePassword);
            stmt = conn.createStatement();
            result = null;
            String pa,us;
            result = stmt.executeQuery("select * from table1 ");

            while (result.next()) {
                us=result.getString("uname");
                pa = result.getString("pass");              
                System.out.println(us+"  "+pa);
            }

            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How to remove listview all items

You can do this:

listView.setAdapter(null);

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

Here is a generalized solution to this kind of problem:

General procedure

The taken approach is as follows. The algorithm operates on a single buffer of 32-bit words. It performs the following procedure in a loop:

  • We start with a buffer filled with compressed data from the last iteration. The buffer looks like this

    |compressed sorted|empty|

  • Calculate the maximum amount of numbers that can be stored in this buffer, both compressed and uncompressed. Split the buffer into these two sections, beginning with the space for compressed data, ending with the uncompressed data. The buffer looks like

    |compressed sorted|empty|empty|

  • Fill the uncompressed section with numbers to be sorted. The buffer looks like

    |compressed sorted|empty|uncompressed unsorted|

  • Sort the new numbers with an in-place sort. The buffer looks like

    |compressed sorted|empty|uncompressed sorted|

  • Right-align any already compressed data from the previous iteration in the compressed section. At this point the buffer is partitioned

    |empty|compressed sorted|uncompressed sorted|

  • Perform a streaming decompression-recompression on the compressed section, merging in the sorted data in the uncompressed section. The old compressed section is consumed as the new compressed section grows. The buffer looks like

    |compressed sorted|empty|

This procedure is performed until all numbers have been sorted.

Compression

This algorithm of course only works when it's possible to calculate the final compressed size of the new sorting buffer before actually knowing what will actually be compressed. Next to that, the compression algorithm needs to be good enough to solve the actual problem.

The used approach uses three steps. First, the algorithm will always store sorted sequences, therefore we can instead store purely the differences between consecutive entries. Each difference is in the range [0, 99999999].

These differences are then encoded as a unary bitstream. A 1 in this stream means "Add 1 to the accumulator, A 0 means "Emit the accumulator as an entry, and reset". So difference N will be represented by N 1's and one 0.

The sum of all differences will approach the maximum value that the algorithm supports, and the count of all differences will approach the amount of values inserted in the algorithm. This means we expect the stream to, at the end, contain max value 1's and count 0's. This allows us to calculate the expected probability of a 0 and 1 in the stream. Namely, the probability of a 0 is count/(count+maxval) and the probability of a 1 is maxval/(count+maxval).

We use these probabilities to define an arithmetic coding model over this bitstream. This arithmetic code will encode exactly this amounts of 1's and 0's in optimal space. We can calculate the space used by this model for any intermediate bitstream as: bits = encoded * log2(1 + amount / maxval) + maxval * log2(1 + maxval / amount). To calculate the total required space for the algorithm, set encoded equal to amount.

To not require a ridiculous amount of iterations, a small overhead can be added to the buffer. This will ensure that the algorithm will at least operate on the amount of numbers that fit in this overhead, as by far the largest time cost of the algorithm is the arithmetic coding compression and decompression each cycle.

Next to that, some overhead is necessary to store bookkeeping data and to handle slight inaccuracies in the fixed-point approximation of the arithmetic coding algorithm, but in total the algorithm is able to fit in 1MiB of space even with an extra buffer that can contain 8000 numbers, for a total of 1043916 bytes of space.

Optimality

Outside of reducing the (small) overhead of the algorithm it should be theoretically impossible to get a smaller result. To just contain the entropy of the final result, 1011717 bytes would be necessary. If we subtract the extra buffer added for efficiency this algorithm used 1011916 bytes to store the final result + overhead.