Programs & Examples On #Aspose cells

Aspose.Cells is a spreadsheet component that allows .NET and Java developers to embed the ability to read, write, convert and manipulate Excel spreadsheets into their own applications without needing to rely on Microsoft Excel.

How to remove item from a JavaScript object

_x000D_
_x000D_
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

this deletes test.blue

How to check if a table contains an element in Lua?

Given your representation, your function is as efficient as can be done. Of course, as noted by others (and as practiced in languages older than Lua), the solution to your real problem is to change representation. When you have tables and you want sets, you turn tables into sets by using the set element as the key and true as the value. +1 to interjay.

python variable NameError

I would approach it like this:

sizes = [100, 250] print "How much space should the random song list occupy?" print '\n'.join("{0}. {1}Mb".format(n, s)                 for n, s in enumerate(sizes, 1)) # present choices choice = int(raw_input("Enter choice:")) # throws error if not int size = sizes[0] # safe starting choice if choice in range(2, len(sizes) + 1):     size = sizes[choice - 1] # note index offset from choice print "You  want to create a random song list that is {0}Mb.".format(size) 

You could also loop until you get an acceptable answer and cover yourself in case of error:

choice = 0 while choice not in range(1, len(sizes) + 1): # loop     try: # guard against error         choice = int(raw_input(...))     except ValueError: # couldn't make an int         print "Please enter a number"         choice = 0 size = sizes[choice - 1] # now definitely valid 

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

The simple answer is to set the Access-Control-Allow-Origin header to localhost or *. Here's how I usually do it:

Add the following code to bootstrap/app.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');

Iterating through struct fieldnames in MATLAB

Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.

fns{i}
teststruct.(fns{i})

Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.

name_as_char = 'a'
name_as_cellstr = {'a'}

how to include js file in php?

Pekka has the correct answer (hence my making this answer a Community Wiki): Use src, not href, to specify the file.

Regarding:

When i try it this way:

<script type="text/javascript">
    document.write('<script type="text/javascript" src="datetimepicker_css.js"></script>');
</script>

the first tag in the document.write function closes
what is the correct way to do this?

You don't want or need document.write for this, but just in case you ever do need to put the characters </script> inside a script tag for some other reason: You do that by ensuring that the HTML parser (which doesn't understand JavaScript) doesn't see a literal </script>. There are a couple of ways of doing that. One way is to escape the / even though you don't need to:

<script type='text/javascript'>
alert("<\/script>"); // Works, HTML parser doesn't see this as a closing script tag
//      ^--- note the seemingly-unnecessary backslash
</script>

Or if you're feeling more paranoid:

<script type='text/javascript'>
alert("</scr" + "ipt>"); // Works, HTML parser doesn't see this as a closing script tag
</script>

...since in each case, JavaScript sees the string as </script> but the HTML parser doesn't.

PHP exec() vs system() vs passthru()

The previous answers seem all to be a little confusing or incomplete, so here is a table of the differences...

+----------------+-----------------+----------------+----------------+
|    Command     | Displays Output | Can Get Output | Gets Exit Code |
+----------------+-----------------+----------------+----------------+
| system()       | Yes (as text)   | Last line only | Yes            |
| passthru()     | Yes (raw)       | No             | Yes            |
| exec()         | No              | Yes (array)    | Yes            |
| shell_exec()   | No              | Yes (string)   | No             |
| backticks (``) | No              | Yes (string)   | No             |
+----------------+-----------------+----------------+----------------+
  • "Displays Output" means it streams the output to the browser (or command line output if running from a command line).
  • "Can Get Output" means you can get the output of the command and assign it to a PHP variable.
  • The "exit code" is a special value returned by the command (also called the "return status"). Zero usually means it was successful, other values are usually error codes.

Other misc things to be aware of:

  • The shell_exec() and the backticks operator do the same thing.
  • There are also proc_open() and popen() which allow you to interactively read/write streams with an executing command.
  • Add "2>&1" to the command string if you also want to capture/display error messages.
  • Use escapeshellcmd() to escape command arguments that may contain problem characters.
  • If passing an $output variable to exec() to store the output, if $output isn't empty, it will append the new output to it. So you may need to unset($output) first.

How to remove the focus from a TextBox in WinForms?

You can also set the forms activecontrol property to null like

ActiveControl = null;

How to work with string fields in a C struct?

You could just use an even simpler typedef:

typedef char *string;

Then, your malloc would look like a usual malloc:

string s = malloc(maxStringLength);

How can I specify a [DllImport] path at runtime?

If all fails, simply put the DLL in the windows\system32 folder . The compiler will find it. Specify the DLL to load from with: DllImport("user32.dll"..., set EntryPoint = "my_unmanaged_function" to import your desired unmanaged function to your C# app:

 using System;
using System.Runtime.InteropServices;

class Example
{
   // Use DllImport to import the Win32 MessageBox function.

   [DllImport ("user32.dll", CharSet = CharSet.Auto)]
   public static extern int MessageBox 
      (IntPtr hWnd, String text, String caption, uint type);

   static void Main()
   {
      // Call the MessageBox function using platform invoke.
      MessageBox (new IntPtr(0), "Hello, World!", "Hello Dialog", 0);    
   }
}

Source and even more DllImport examples : http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx

What's the best way to iterate an Android Cursor?

import java.util.Iterator;
import android.database.Cursor;

public class IterableCursor implements Iterable<Cursor>, Iterator<Cursor> {
    Cursor cursor;
    int toVisit;
    public IterableCursor(Cursor cursor) {
        this.cursor = cursor;
        toVisit = cursor.getCount();
    }
    public Iterator<Cursor> iterator() {
        cursor.moveToPosition(-1);
        return this;
    }
    public boolean hasNext() {
        return toVisit>0;
    }
    public Cursor next() {
    //  if (!hasNext()) {
    //      throw new NoSuchElementException();
    //  }
        cursor.moveToNext();
        toVisit--;
        return cursor;
    }
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

Example code:

static void listAllPhones(Context context) {
    Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    for (Cursor phone : new IterableCursor(phones)) {
        String name = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        Log.d("name=" + name + " phoneNumber=" + phoneNumber);
    }
    phones.close();
}

What is the purpose of class methods?

Factory methods (alternative constructors) are indeed a classic example of class methods.

Basically, class methods are suitable anytime you would like to have a method which naturally fits into the namespace of the class, but is not associated with a particular instance of the class.

As an example, in the excellent unipath module:

Current directory

  • Path.cwd()
    • Return the actual current directory; e.g., Path("/tmp/my_temp_dir"). This is a class method.
  • .chdir()
    • Make self the current directory.

As the current directory is process wide, the cwd method has no particular instance with which it should be associated. However, changing the cwd to the directory of a given Path instance should indeed be an instance method.

Hmmm... as Path.cwd() does indeed return a Path instance, I guess it could be considered to be a factory method...

Difference between jQuery’s .hide() and setting CSS to display: none

.hide() stores the previous display property just before setting it to none, so if it wasn't the standard display property for the element you're a bit safer, .show() will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.

Url to a google maps page to show a pin given a latitude / longitude?

From my notes:

http://maps.google.com/maps?q=37.4185N+122.08774W+(label)&ll=37.419731,-122.088715&spn=0.004250,0.011579&t=h&iwloc=A&hl=en

Which parses like this:

    q=latN+lonW+(label)     location of teardrop

    t=k             keyhole (satelite map)
    t=h             hybrid

    ll=lat,-lon     center of map
    spn=w.w,h.h     span of map, degrees

iwloc has something to do with the info window. hl is obviously language.

See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

Creating an instance using the class name and calling constructor

You can use Class.forName() to get a Class object of the desired class.

Then use getConstructor() to find the desired Constructor object.

Finally, call newInstance() on that object to get your new instance.

Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("MyAttributeValue");

CAST DECIMAL to INT

There's also ROUND() if your numbers don't necessarily always end with .00. ROUND(20.6) will give 21, and ROUND(20.4) will give 20.

Laravel 5 Class 'form' not found

I have tried everything, but only this helped:

php artisan route:clear
php artisan cache:clear

How to remove Left property when position: absolute?

In the future one would use left: unset; for unsetting the value of left.

As of today 4 nov 2014 unset is only supported in Firefox.

Read more about unset in MDN.

My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.

Prevent line-break of span element

white-space: nowrap is the correct solution but it will prevent any break in a line. If you only want to prevent line breaks between two elements it gets a bit more complicated:

<p>
    <span class="text">Some text</span>
    <span class="icon"></span>
</p>

To prevent breaks between the spans but to allow breaks between "Some" and "text" can be done by:

p {
    white-space: nowrap;
}

.text {
    white-space: normal;
}

That's good enough for Firefox. In Chrome you additionally need to replace the whitespace between the spans with an &nbsp;. (Removing the whitespace doesn't work.)

How to get the number of characters in a string

If you need to take grapheme clusters into account, use regexp or unicode module. Counting the number of code points(runes) or bytes also is needed for validaiton since the length of grapheme cluster is unlimited. If you want to eliminate extremely long sequences, check if the sequences conform to stream-safe text format.

package main

import (
    "regexp"
    "unicode"
    "strings"
)

func main() {

    str := "\u0308" + "a\u0308" + "o\u0308" + "u\u0308"
    str2 := "a" + strings.Repeat("\u0308", 1000)

    println(4 == GraphemeCountInString(str))
    println(4 == GraphemeCountInString2(str))

    println(1 == GraphemeCountInString(str2))
    println(1 == GraphemeCountInString2(str2))

    println(true == IsStreamSafeString(str))
    println(false == IsStreamSafeString(str2))
}


func GraphemeCountInString(str string) int {
    re := regexp.MustCompile("\\PM\\pM*|.")
    return len(re.FindAllString(str, -1))
}

func GraphemeCountInString2(str string) int {

    length := 0
    checked := false
    index := 0

    for _, c := range str {

        if !unicode.Is(unicode.M, c) {
            length++

            if checked == false {
                checked = true
            }

        } else if checked == false {
            length++
        }

        index++
    }

    return length
}

func IsStreamSafeString(str string) bool {
    re := regexp.MustCompile("\\PM\\pM{30,}") 
    return !re.MatchString(str) 
}

How to style a checkbox using CSS

I prefer to use icon fonts (such as FontAwesome) since it's easy to modify their colours with CSS, and they scale really well on high pixel-density devices. So here's another pure CSS variant, using similar techniques to those above.

(Below is a static image so you can visualize the result; see the JSFiddle for an interactive version.)

Checkbox example

As with other solutions, it uses the label element. An adjacent span holds our checkbox character.

_x000D_
_x000D_
span.bigcheck-target {_x000D_
  font-family: FontAwesome; /* Use an icon font for the checkbox */_x000D_
}_x000D_
_x000D_
input[type='checkbox'].bigcheck {_x000D_
  position: relative;_x000D_
  left: -999em; /* Hide the real checkbox */_x000D_
}_x000D_
_x000D_
input[type='checkbox'].bigcheck + span.bigcheck-target:after {_x000D_
  content: "\f096"; /* In fontawesome, is an open square (fa-square-o) */_x000D_
}_x000D_
_x000D_
input[type='checkbox'].bigcheck:checked + span.bigcheck-target:after {_x000D_
  content: "\f046"; /* fontawesome checked box (fa-check-square-o) */_x000D_
}_x000D_
_x000D_
/* ==== Optional - colors and padding to make it look nice === */_x000D_
body {_x000D_
  background-color: #2C3E50;_x000D_
  color: #D35400;_x000D_
  font-family: sans-serif;_x000D_
  font-weight: 500;_x000D_
  font-size: 4em; /* Set this to whatever size you want */_x000D_
}_x000D_
_x000D_
span.bigcheck {_x000D_
  display: block;_x000D_
  padding: 0.5em;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />_x000D_
_x000D_
<span class="bigcheck">_x000D_
  <label class="bigcheck">_x000D_
    Cheese_x000D_
    <input type="checkbox" class="bigcheck" name="cheese" value="yes" />_x000D_
    <span class="bigcheck-target"></span>_x000D_
  </label>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Here's the JSFiddle for it.

Why is it bad style to `rescue Exception => e` in Ruby?

This blog post explains it perfectly: Ruby's Exception vs StandardError: What's the difference?

Why you shouldn't rescue Exception

The problem with rescuing Exception is that it actually rescues every exception that inherits from Exception. Which is....all of them!

That's a problem because there are some exceptions that are used internally by Ruby. They don't have anything to do with your app, and swallowing them will cause bad things to happen.

Here are a few of the big ones:

  • SignalException::Interrupt - If you rescue this, you can't exit your app by hitting control-c.

  • ScriptError::SyntaxError - Swallowing syntax errors means that things like puts("Forgot something) will fail silently.

  • NoMemoryError - Wanna know what happens when your program keeps running after it uses up all the RAM? Me neither.

begin
  do_something()
rescue Exception => e
  # Don't do this. This will swallow every single exception. Nothing gets past it. 
end

I'm guessing that you don't really want to swallow any of these system-level exceptions. You only want to catch all of your application level errors. The exceptions caused YOUR code.

Luckily, there's an easy way to to this.

Rescue StandardError Instead

All of the exceptions that you should care about inherit from StandardError. These are our old friends:

NoMethodError - raised when you try to invoke a method that doesn't exist

TypeError - caused by things like 1 + ""

RuntimeError - who could forget good old RuntimeError?

To rescue errors like these, you'll want to rescue StandardError. You COULD do it by writing something like this:

begin
  do_something()
rescue StandardError => e
  # Only your app's exceptions are swallowed. Things like SyntaxErrror are left alone. 
end

But Ruby has made it much easier for use.

When you don't specify an exception class at all, ruby assumes you mean StandardError. So the code below is identical to the above code:

begin
  do_something()
rescue => e
  # This is the same as rescuing StandardError
end

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

nginx: [emerg] "server" directive is not allowed here

Example valid nginx.conf for reverse proxy; In case someone is stuck like me. where 10.x.x.x is the server where you are running the nginx proxy server and to which you are connecting to with the browser, and 10.y.y.y is where your real web server is running

events {
  worker_connections  4096;  ## Default: 1024
}
http {
 server {
   listen 80;
   listen [::]:80;

   server_name 10.x.x.x;
 
   location / {
       proxy_pass http://10.y.y.y:80/;
       proxy_set_header Host $host;
   }
 }
}

Here is the snippet if you want to do SSL pass through. That is if 10.y.y.y is running a HTTPS webserver. Here 10.x.x.x, or where the nignx runs is listening to port 443, and all traffic to 443 is directed to your target web server

events {
  worker_connections  4096;  ## Default: 1024
}

stream {
  server {
    listen     443;
    proxy_pass 10.y.y.y:443;
  }
}

and you can serve it up in docker too

 docker run --name nginx-container --rm --net=host   -v /home/core/nginx/nginx.conf:/etc/nginx/nginx.conf nginx

Why does Git say my master branch is "already up to date" even though it is not?

Just a friendly reminder if you have files locally that aren't in github and yet your git status says

Your branch is up to date with 'origin/master'. nothing to commit, working tree clean

It can happen if the files are in .gitignore

Try running

cat .gitignore 

and seeing if these files show up there. That would explain why git doesn't want to move them to the remote.

How to close TCP and UDP ports via windows command line

If you're runnning on Windows 8,`Windows Server 2012 or above with PowerShell v4 of above installed, you can use the below script. This finds the processes associated with the port & terminates them.

Code

#which port do you want to kill
[int]$portOfInterest = 80

#fetch the process ids related to this port
[int[]]$processId = Get-NetTCPConnection -LocalPort $portOfInterest | 
    Select-Object -ExpandProperty OwningProcess -Unique | 
    Where-Object {$_ -gt 0} 

#kill those processes
Stop-Process -Id $processId 

Documentation:

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

Convert string with comma to integer

You may also want to make sure that your code localizes correctly, or make sure the users are used to the "international" notation. For example, "1,112" actually means different numbers across different countries. In Germany it means the number a little over one, instead of one thousand and something.

Corresponding Wikipedia article is at http://en.wikipedia.org/wiki/Decimal_mark. It seems to be poorly written at this time though. For example as a Chinese I'm not sure where does these description about thousand separator in China come from.

Is it possible to get a list of files under a directory of a website? How?

Yes, you can, but you need a few tools first. You need to know a little about basic coding, FTP clients, port scanners and brute force tools, if it has a .htaccess file.

If not just try tgp.linkurl.htm or html, ie default.html, www/home/siteurl/web/, or wap /index/ default /includes/ main/ files/ images/ pics/ vids/, could be possible file locations on the server, so try all of them so www/home/siteurl/web/includes/.htaccess or default.html. You'll hit a file after a few tries then work off that. Yahoo has a site file viewer too: you can try to scan sites file indexes.

Alternatively, try brutus aet, trin00, trinity.x, or whiteshark airtool to crack the site's FTP login (but it's illegal and I do not condone that).

Does Java read integers in little endian or big endian?

I would read the bytes one by one, and combine them into a long value. That way you control the endianness, and the communication process is transparent.

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

ES6 exporting/importing in index file

Simply:

// Default export (recommended)
export {default} from './MyClass' 

// Default export with alias
export {default as d1} from './MyClass' 

// In >ES7, it could be
export * from './MyClass'

// In >ES7, with alias
export * as d1 from './MyClass'

Or by functions names :

// export by function names
export { funcName1, funcName2, …} from './MyClass'

// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './MyClass'

More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

Batch not-equal (inequality) operator

Try

if NOT "asdf" == "fdas" echo asdf

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.

How to use if - else structure in a batch file?

Here's my code Example for if..else..if
which do the following

Prompt user for Process Name

If the process name is invalid
Then it's write to user

Error : The Processor above doesn't seem to be exist 

if the process name is services
Then it's write to user

Error : You can't kill the Processor above 

if the process name is valid and not services
Then it's write to user

the process has been killed via taskill

so i called it Process killer.bat
Here's my Code:

@echo off

:Start
Rem preparing the batch  
cls
Title Processor Killer
Color 0B
Echo Type Processor name to kill It (Without ".exe")
set /p ProcessorTokill=%=%  

:tasklist
tasklist|find /i "%ProcessorTokill%.exe">nul & if errorlevel 1 (
REM check if the process name is invalid 
Cls 
Title %ProcessorTokill% Not Found
Color 0A
echo %ProcessorTokill%
echo Error : The Processor above doesn't seem to be exist    

) else if %ProcessorTokill%==services (
REM check if the process name is services and doesn't kill it
Cls 
Color 0c
Title Permission denied 
echo "%ProcessorTokill%.exe"
echo Error : You can't kill the Processor above 

) else (
REM if the process name is valid and not services
Cls 
Title %ProcessorTokill% Found
Color 0e
echo %ProcessorTokill% Found
ping localhost -n 2 -w 1000>nul
echo Killing %ProcessorTokill% ...
taskkill /f /im %ProcessorTokill%.exe /t>nul
echo %ProcessorTokill% Killed...
)

pause>nul



REM If else if Template
REM if thing1 (
REM Command here 2 ! 
REM ) else if thing2 (
REM command here 2 !
REM ) else (
REM command here 3 !
REM )

AJAX reload page with POST

By using jquery ajax you can reload your page

$.ajax({
    type: "POST",
    url: "packtypeAdd.php",
    data: infoPO,
    success: function() {   
        location.reload();  
    }
});

binning data in python with scipy/numpy

It's probably faster and easier to use numpy.digitize():

import numpy
data = numpy.random.random(100)
bins = numpy.linspace(0, 1, 10)
digitized = numpy.digitize(data, bins)
bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]

An alternative to this is to use numpy.histogram():

bin_means = (numpy.histogram(data, bins, weights=data)[0] /
             numpy.histogram(data, bins)[0])

Try for yourself which one is faster... :)

What's the main difference between Java SE and Java EE?

Java SE (formerly J2SE) is the basic Java environment. In Java SE, you make all the "standards" programs with Java, using the API described here. You only need a JVM to use Java SE.

Java EE (formerly J2EE) is the enterprise edition of Java. With it, you make websites, Java Beans, and more powerful server applications. Besides the JVM, you need an application server Java EE-compatible, like Glassfish, JBoss, and others.

Minimum rights required to run a windows service as a domain account

I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.

How can I trigger the click event of another element in ng-click using angularjs?

for jqLite just use triggerHandler with event name, To simulate a "click" try:

_x000D_
_x000D_
angular.element("tr").triggerHandler("click");
_x000D_
_x000D_
_x000D_

Here's the list of jQLite commands

Take screenshots in the iOS simulator

In OSX Captain its a bug to take screenshot of simulator. You have to Update your OSX Sierra first then your are able to take. while taking in OSX Captain use terminal command which is xcrun simctl io booted screenshot.

before running this command u have to select desktop in terminal like:

"cd desktop" then run that command. Happy Coding!!!

Check date between two other dates spring data jpa

You should take a look the reference documentation. It's well explained.

In your case, I think you cannot use between because you need to pass two parameters

Between - findByStartDateBetween … where x.startDate between ?1 and ?2

In your case take a look to use a combination of LessThan or LessThanEqual with GreaterThan or GreaterThanEqual

  • LessThan/LessThanEqual

LessThan - findByEndLessThan … where x.start< ?1

LessThanEqual findByEndLessThanEqual … where x.start <= ?1

  • GreaterThan/GreaterThanEqual

GreaterThan - findByStartGreaterThan … where x.end> ?1

GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1

You can use the operator And and Or to combine both.

Matching strings with wildcard

Often, wild cards operate with two type of jokers:

  ? - any character  (one and only one)
  * - any characters (zero or more)

so you can easily convert these rules into appropriate regular expression:

  // If you want to implement both "*" and "?"
  private static String WildCardToRegular(String value) {
    return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$"; 
  }

  // If you want to implement "*" only
  private static String WildCardToRegular(String value) {
    return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$"; 
  }

And then you can use Regex as usual:

  String test = "Some Data X";

  Boolean endsWithEx = Regex.IsMatch(test, WildCardToRegular("*X"));
  Boolean startsWithS = Regex.IsMatch(test, WildCardToRegular("S*"));
  Boolean containsD = Regex.IsMatch(test, WildCardToRegular("*D*"));

  // Starts with S, ends with X, contains "me" and "a" (in that order) 
  Boolean complex = Regex.IsMatch(test, WildCardToRegular("S*me*a*X"));

How many characters can a Java String have?

Have you considered using BigDecimal instead of String to hold your numbers?

"Cloning" row or column vectors

Here's an elegant, Pythonic way to do it:

>>> array([[1,2,3],]*3)
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

>>> array([[1,2,3],]*3).transpose()
array([[1, 1, 1],
       [2, 2, 2],
       [3, 3, 3]])

the problem with [16] seems to be that the transpose has no effect for an array. you're probably wanting a matrix instead:

>>> x = array([1,2,3])
>>> x
array([1, 2, 3])
>>> x.transpose()
array([1, 2, 3])
>>> matrix([1,2,3])
matrix([[1, 2, 3]])
>>> matrix([1,2,3]).transpose()
matrix([[1],
        [2],
        [3]])

how to use XPath with XDocument?

you can use the example from Microsoft - for you without namespace:

using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");     

should do it

How to move a git repository into another directory and make that directory a git repository?

It's even simpler than that. Just did this (on Windows, but it should work on other OS):

  1. Create newrepo.
  2. Move gitrepo1 into newrepo.
  3. Move .git from gitrepo1 to newrepo (up one level).
  4. Commit changes (fix tracking as required).

Git just sees you added a directory and renamed a bunch of files. No biggie.

SQL Server 2005 Setting a variable to the result of a select query

You can use something like

SET @cnt = (SELECT COUNT(*) FROM User)

or

SELECT @cnt = (COUNT(*) FROM User)

For this to work the SELECT must return a single column and a single result and the SELECT statement must be in parenthesis.

Edit: Have you tried something like this?

DECLARE @OOdate DATETIME

SET @OOdate = Select OO.Date from OLAP.OutageHours as OO where OO.OutageID = 1

Select COUNT(FF.HALID) 
from Outages.FaultsInOutages as OFIO 
inner join Faults.Faults as FF 
    ON FF.HALID = OFIO.HALID 
WHERE @OODate = FF.FaultDate
    AND OFIO.OutageID = 1

Any tools to generate an XSD schema from an XML instance document?

If you have .Net installed, a tool to generate XSD schemas and classes is already included by default.
For me, the XSD tool is installed under the following structure. This may differ depending on your installation directory.

C:\Program Files\Microsoft Visual Studio 8\VC>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 2.0.50727.42]
Copyright (C) Microsoft Corporation. All rights reserved.

xsd.exe -
   Utility to generate schema or class files from given source.

xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/s] [/uri:]
xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]]
xsd.exe <instance>.xml [/outputdir:]
xsd.exe <schema>.xdr [/outputdir:]

Normally the classes and schemas that this tool generates work rather well, especially if you're going to be consuming them in a .Net language

I typically take the XML document that I'm after, push it through the XSD tool with the /o:<your path> flag to generate a schema (xsd) and then push the xsd file back through the tool using the /classes /L:VB (or CS) /o:<your path> flags to get classes that I can import and use in my day to day .Net projects

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT i.e 204 No Content as in place of HttpStatus.OK

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

Any value of T will be ignored for 204, but not for 404

  public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
            LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
            final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
            LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$

            if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
                LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
                 return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
            } else {
               LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
                return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
            }

    }

How to navigate through a vector using iterators? (C++)

Vector's iterators are random access iterators which means they look and feel like plain pointers.

You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [].

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

int sixth = *(it + 5);
int third = *(2 + it);
int second = it[1];

Alternatively you can use the advance function which works with all kinds of iterators. (You'd have to consider whether you really want to perform "random access" with non-random-access iterators, since that might be an expensive thing to do.)

std::vector<int> vec(10);
std::vector<int>::iterator it = vec.begin();

std::advance(it, 5);
int sixth = *it;

How to make/get a multi size .ico file?

This can be done for free using GIMP.

It uses the ability of GIMP to have each layer a different size.

I created the following layers sized correctly.

  • 256x256 will be saved as 32bpp 8bit alpha
  • 48x48 will be saved as 32bpp 8bit alpha
  • 48x48 will be saved as 8bpp 1bit alpha
  • 32x32 will be saved as 32bpp 8bit alpha
  • 32x32 will be saved as 8bpp 1bit alpha
  • 32x32 will be saved as 4bpp 1bit alpha
  • 16x16 will be saved as 32bpp 8bit alpha
  • 16x16 will be saved as 8bpp 1bit alpha
  • 16x16 will be saved as 4bpp 1bit alpha

Notes

  • You may need to check other resources to confirm to yourself that this is a sensible list of resolutions and colour depths.
  • Make sure you use transparency round the outside of your image, and anti-aliased edges. You should see the grey checkerboard effect round the outside of your layers to indicate they are transparent
  • The 16x16 icons will need to be heavily edited by hand using a 1 pixel wide pencil and the eyedropper tool to make them look any good.
  • Do not change colour depth / Mode in GIMP. Leave it as RGB
  • You change the colour depths when you save as an .ico - GIMP pops up a special dialog box for changing the colour settings for each layer

How can I send an email through the UNIX mailx command?

Here you are :

echo "Body" | mailx -r "FROM_EMAIL" -s "SUBJECT" "To_EMAIL"

PS. Body and subject should be kept within double quotes. Remove quotes from FROM_EMAIL and To_EMAIL while substituting email addresses.

Rounding a double to turn it into an int (java)

The Math.round function is overloaded When it receives a float value, it will give you an int. For example this would work.

int a=Math.round(1.7f);

When it receives a double value, it will give you a long, therefore you have to typecast it to int.

int a=(int)Math.round(1.7);

This is done to prevent loss of precision. Your double value is 64bit, but then your int variable can only store 32bit so it just converts it to long, which is 64bit but you can typecast it to 32bit as explained above.

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

String.split() will do most of what you want. You may then need to loop over the words to pull out any punctuation.

For example:

String s = "This is a sample sentence.";
String[] words = s.split("\\s+");
for (int i = 0; i < words.length; i++) {
    // You may want to check for a non-word character before blindly
    // performing a replacement
    // It may also be necessary to adjust the character class
    words[i] = words[i].replaceAll("[^\\w]", "");
}

How do you declare an object array in Java?

vehicle[] car = new vehicle[N];

How to change progress bar's progress color in Android

ProgressBar freeRamPb = findViewById(R.id.free_ram_progress_bar);

freeRamPb.getProgressDrawable().setColorFilter(
Color.BLUE, android.graphics.PorterDuff.Mode.SRC_IN);

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

Removing some unnecessary SQL and then COUNT(*) will be faster than SQL_CALC_FOUND_ROWS. Example:

SELECT Person.Id, Person.Name, Job.Description, Card.Number
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
LEFT JOIN Card ON Card.Person_Id = Person.Id
WHERE Job.Name = 'WEB Developer'
ORDER BY Person.Name

Then count without unnecessary part:

SELECT COUNT(*)
FROM Person
JOIN Job ON Job.Id = Person.Job_Id
WHERE Job.Name = 'WEB Developer'

QByteArray to QString

You can use QTextCodec to convert the bytearray to a string:

QString DataAsString = QTextCodec::codecForMib(1015)->toUnicode(Data);

(1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)

From your example we can see that the string "test" is encoded as "t\0 e\0 s\0 t\0 \0 \0" in your encoding, i.e. every ascii character is followed by a \0-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).

How to monitor Java memory usage?

There are tools that let you monitor the VM's memory usage. The VM can expose memory statistics using JMX. You can also print GC statistics to see how the memory is performing over time.

Invoking System.gc() can harm the GC's performance because objects will be prematurely moved from the new to old generations, and weak references will be cleared prematurely. This can result in decreased memory efficiency, longer GC times, and decreased cache hits (for caches that use weak refs). I agree with your consultant: System.gc() is bad. I'd go as far as to disable it using the command line switch.

TypeError: can't use a string pattern on a bytes-like object in re.findall()

You want to convert html (a byte-like object) into a string using .decode, e.g. html = response.read().decode('utf-8').

See Convert bytes to a Python String

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

The best option is to use the original LESS version of bootstrap (get it from github).

Open variables.less and look for // Media queries breakpoints

Find this code and change the breakpoint value:

// Large screen / wide desktop
@screen-lg:                  1200px; // change this
@screen-lg-desktop:          @screen-lg;

Change it to 9999px for example, and this will prevent the breakpoint to be reached, so your site will always load the previous media query which has 940px container

How to order by with union in SQL?

Add a column to the query which can sub identify the data to sort on that.

In the below example I use a Common Table Expression with the selects you showed which places them in specific groups in the CTE, and then do a union off of both of those groups into AllStudents.

The final select will then sort AllStudents by the SortIndex column first and then by the name such as:

WITH Juveniles as
(
      Select 1 as [SortIndex], id,name,age From Student
      Where age < 15
),

AStudents as
(
      Select 2 as [SortIndex], id,name,age From Student
      Where Name like "%a%" 
),

AllStudents as
(
      select * from Juveniles
      union 
      select * from AStudents
)

select * from AllStudents
sort by [SortIndex], name;

To summarize, it will get all the students which will be sorted by group first, and subsorted by the name within the group after that.

What's the canonical way to check for type in Python?

A simple way to check type is to compare it with something whose type you know.

>>> a  = 1
>>> type(a) == type(1)
True
>>> b = 'abc'
>>> type(b) == type('')
True

Validation for 10 digit mobile number and focus input field on invalid

for email validation, <input type="email"> is enough..

for mobile no use pattern attribute for input as follows:

<input type="number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" required>

you can check for more patterns on http://html5pattern.com.

for focusing on field, you can use onkeyup() event as:

function check()
{

    var mobile = document.getElementById('mobile');
   
    
    var message = document.getElementById('message');

   var goodColor = "#0C6";
    var badColor = "#FF9B37";
  
    if(mobile.value.length!=10){
       
        mobile.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "required 10 digits, match requested format!"
    }}

and your HTML code should be:

<input name="mobile"  id="mobile" type="number" required onkeyup="check(); return false;" ><span id="message"></span>

Converting String to Cstring in C++

.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.

Dependent DLL is not getting copied to the build output folder in Visual Studio

You may set both the main project and ProjectX's build output path to the same folder, then you can get all the dlls you need in that folder.

Meaning of delta or epsilon argument of assertEquals for double values

The thing is that two double may not be exactly equal due to precision issues inherent to floating point numbers. With this delta value you can control the evaluation of equality based on a error factor.

Also some floating-point values can have special values like NAN and -Infinity/+Infinity which can influence results.

If you really intend to compare that two doubles are exactly equal it is best compare them as an long representation

Assert.assertEquals(Double.doubleToLongBits(expected), Double.doubleToLongBits(result));

Or

Assert.assertEquals(0, Double.compareTo(expected, result));

Which can take these nuances into account.

I have not delved into the Assert method in question, but I can only assume the previous was deprecated for this kind of issues and the new one does take them into account.

What is the best way to get the count/length/size of an iterator?

Using Guava library:

int size = Iterators.size(iterator);

Internally it just iterates over all elements so its just for convenience.

How can I parse a JSON file with PHP?

Try it:

foreach ($json_a as $key => $value)
 {
   echo $key, ' : ';
   foreach($value as $v)
   {
       echo $v."  ";
   }
}

How to put more than 1000 values into an Oracle IN clause

Put the values in a temporary table and then do a select where id in (select id from temptable)

"Unable to acquire application service" error while launching Eclipse

The /configuration/config.ini file should contain org.eclipse.core.runtime@start in the commaseparated osgi.bundles property. Here is the default osgi.bundles property, maybe it was (accidently) changed during some upgrade:

osgi.bundles=org.eclipse.equinox.common@2:start,org.eclipse.update.configurator@3:start,org.eclipse.core.runtime@start

You can if necessary override it by setting it as VM argument in /eclipse.ini:

-Dosgi.bundles=org.eclipse.equinox.common@2:start,org.eclipse.update.configurator@3:start,org.eclipse.core.runtime@start

How to add items to a combobox in a form in excel VBA?

Here is another answer:

With DinnerComboBox
.AddItem "Italian"
.AddItem "Chinese"
.AddItem "Frites and Meat"
End With 

Source: Show the

Enabling/installing GD extension? --without-gd

I've PHP 7.3 and Nginx 1.14 on Ubuntu 18.

# it installs php7.3-gd for the moment
# and restarts PHP 7.3 FastCGI Process Manager: php-fpm7.3.
sudo apt-get install php-gd

# after I've restarted Nginx
sudo /etc/init.d/nginx restart

Works!

Python error "ImportError: No module named"

In my case, the problem was I was linking to debug python & boost::Python, which requires that the extension be FooLib_d.pyd, not just FooLib.pyd; renaming the file or updating CMakeLists.txt properties fixed the error.

How to read a list of files from a folder using PHP?

The simplest and most fun way (imo) is glob

foreach (glob("*.*") as $filename) {
    echo $filename."<br />";
}

But the standard way is to use the directory functions.

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: .".$file."<br />";
        }
        closedir($dh);
    }
}

There are also the SPL DirectoryIterator methods. If you are interested

How can I find matching values in two arrays?

You can use :

const intersection = array1.filter(element => array2.includes(element));

Distinct pair of values SQL

if you want to filter the tuples you can use on this way:

select distinct (case a > b then (a,b) else (b,a) end) from pairs

the good stuff is you don't have to use group by.

What is the difference between utf8mb4 and utf8 charsets in MySQL?

Taken from the MySQL 8.0 Reference Manual:

  • utf8mb4: A UTF-8 encoding of the Unicode character set using one to four bytes per character.

  • utf8mb3: A UTF-8 encoding of the Unicode character set using one to three bytes per character.

In MySQL utf8 is currently an alias for utf8mb3 which is deprecated and will be removed in a future MySQL release. At that point utf8 will become a reference to utf8mb4.

So regardless of this alias, you can consciously set yourself an utf8mb4 encoding.

To complete the answer, I'd like to add the @WilliamEntriken's comment below (also taken from the manual):

To avoid ambiguity about the meaning of utf8, consider specifying utf8mb4 explicitly for character set references instead of utf8.

find difference between two text files with one item per line

an awk answer:

awk 'NR == FNR {file1[$0]++; next} !($0 in file1)' file1 file2

Alternating Row Colors in Bootstrap 3 - No Table

There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type (or :nth-child -- either would work in this case.)

Smallest viewport:

@media (max-width:$smallest-breakpoint) {

  .row div {
     background: #eee;
   }

  .row div:nth-of-type(2n) {
     background: #fff;
   }

}

Medium viewport:

@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
    background: #fff;
  }

}

Largest viewport:

@media (min-width:$mid-breakpoint) and (max-width:9999px) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(6n+4), 
  .row div:nth-of-type(6n+5), 
  .row div:nth-of-type(6n+6) {
      background: #fff;
  }
}

Working fiddle here

Python: how can I check whether an object is of type datetime.date?

import datetime
d = datetime.date(2012, 9, 1)
print type(d) is datetime.date

> True

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

Left Join without duplicate rows from left table

Try an OUTER APPLY

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    OUTER APPLY
    (
        SELECT TOP 1 *
        FROM tbl_Media M 
        WHERE M.Content_Id = C.Content_Id 
    ) m
ORDER BY 
    C.Content_DatePublished ASC

Alternatively, you could GROUP BY the results

SELECT 
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
FROM 
    tbl_Contents C
    LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id 
GROUP BY
    C.Content_ID,
    C.Content_Title,
    C.Content_DatePublished,
    M.Media_Id
ORDER BY
    C.Content_DatePublished ASC

The OUTER APPLY selects a single row (or none) that matches each row from the left table.

The GROUP BY performs the entire join, but then collapses the final result rows on the provided columns.

Make the current commit the only (initial) commit in a Git repository?

I solved a similar issue by just deleting the .git folder from my project and reintegrating with version control through IntelliJ. Note: The .git folder is hidden. You can view it in the terminal with ls -a , and then remove it using rm -rf .git .

Combining the results of two SQL queries as separate columns

You could also use a CTE to grab groups of information you want and join them together, if you wanted them in the same row. Example, depending on which SQL syntax you use, here:

WITH group1 AS (
  SELECT testA
    FROM tableA
),
group2 AS (
  SELECT testB
    FROM tableB 
)
SELECT *
  FROM group1
  JOIN group2 ON group1.testA = group2.testB --your choice of join
;

You decide what kind of JOIN you want based on the data you are pulling, and make sure to have the same fields in the groups you are getting information from in order to put it all into a single row. If you have multiple columns, make sure to name them all properly so you know which is which. Also, for performance sake, CTE's are the way to go, instead of inline SELECT's and such. Hope this helps.

Javascript format date / time

I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.

function formatDate(date) {
    var year = date.getFullYear(),
        month = date.getMonth() + 1, // months are zero indexed
        day = date.getDate(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
        minuteFormatted = minute < 10 ? "0" + minute : minute,
        morning = hour < 12 ? "am" : "pm";

    return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
            minuteFormatted + morning;
}

How do you hide the Address bar in Google Chrome for Chrome Apps?

In the latest version of Chrome (Version 50.0.2661.94 m) you can accomplish this by going to the menu and then clicking -> More Tools -> Add to Desktop. You will then want to check off "Open as Window" in the popup that appears and then click "Add". Screen shots below:

enter image description here

enter image description here

What is the default boolean value in C#?

Try this (using default keyword)

 bool foo = default(bool); if (foo) { } 

Correct way to use get_or_create?

From the documentation get_or_create:

# get_or_create() a person with similar first names.

p, created = Person.objects.get_or_create(
    first_name='John',
    last_name='Lennon',
    defaults={'birthday': date(1940, 10, 9)},
)

# get_or_create() didn't have to create an object.
>>> created
False

Explanation: Fields to be evaluated for similarity, have to be mentioned outside defaults. Rest of the fields have to be included in defaults. In case CREATE event occurs, all the fields are taken into consideration.

It looks like you need to be returning into a tuple, instead of a single variable, do like this:

customer.source,created = Source.objects.get_or_create(name="Website")

What is the difference between Promises and Observables?

  1. Promises are focused only for single values or resolves, observables are stream of data.

  2. Observables can be canceled but promises can't be canceled.

The least known one, atleast to me is

  1. Promises are always of asynchronous nature, but observables can be both synchronous and asynchronous.

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

Perl: function to trim string leading and trailing whitespace

One option is Text::Trim:

use Text::Trim;
print trim("  example  ");

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

To track each try this example and before that completely reduce cursor blink rate to zero.

_x000D_
_x000D_
<body>_x000D_
//try onkeydown,onkeyup,onkeypress_x000D_
<input type="text" onkeypress="myFunction(this.value)">_x000D_
<span> </span>_x000D_
<script>_x000D_
function myFunction(val) {_x000D_
//alert(val);_x000D_
var mySpan = document.getElementsByTagName("span")[0].innerHTML;_x000D_
mySpan += val+"<br>";_x000D_
document.getElementsByTagName("span")[0].innerHTML = mySpan;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

onblur : event generates on exit

onchange : event generates on exit if any changes made in inputtext

onkeydown: event generates on any key press (for key holding long times also)

onkeyup : event generates on any key release

onkeypress: same as onkeydown (or onkeyup) but won't react for ctrl,backsace,alt other

What is the best way to search the Long datatype within an Oracle database?

You can't search LONGs directly. LONGs can't appear in the WHERE clause. They can appear in the SELECT list though so you can use that to narrow down the number of rows you'd have to examine.

Oracle has recommended converting LONGs to CLOBs for at least the past 2 releases. There are fewer restrictions on CLOBs.

How do you assert that a certain exception is thrown in JUnit 4 tests?

I recomend library assertj-core to handle exception in junit test

In java 8, like this:

//given

//when
Throwable throwable = catchThrowable(() -> anyService.anyMethod(object));

//then
AnyException anyException = (AnyException) throwable;
assertThat(anyException.getMessage()).isEqualTo("........");
assertThat(exception.getCode()).isEqualTo(".......);

Executable directory where application is running from?

I needed to know this and came here, before I remembered the Environment class.

In case anyone else had this issue, just use this: Environment.CurrentDirectory.

Example:

Dim dataDirectory As String = String.Format("{0}\Data\", Environment.CurrentDirectory)

When run from Visual Studio in debug mode yeilds:

C:\Development\solution folder\application folder\bin\debug

This is the exact behaviour I needed, and its simple and straightforward enough.

Ant error when trying to build file, can't find tools.jar?

Sometimes while installing JDK, you may get a dll is missing error. Because of this, it won't copy the tools.jar file to the java folder. So please reinstall the JDK in a different location and if it is successful then you will see the tools.jar file.

MS Access - execute a saved query by name in VBA

You can do it the following way:

DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit

OR

CurrentDb.OpenRecordset("yourQueryName")

Trying to detect browser close event

As Phoenix said, use jQuery .bind method, but for more browser compatibility you should return a String,

$(document).ready(function()
{
    $(window).bind("beforeunload", function() { 
        return "Do you really want to close?"; 
    });
});

more details can be found at : developer.mozilla.org

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,

CURLOPT_COOKIEFILE  => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',

/**
 * Or set header
 * CURLOPT_HTTPHEADER => [
       'Cookie: foo=bar;baz=foo',
   ]
 */
]);

$response = curl_exec($curlHandler);
curl_close($curlHandler);

echo $response;

How do I convert a double into a string in C++?

Heh, I just wrote this (unrelated to this question):

string temp = "";
stringstream outStream;
double ratio = (currentImage->width*1.0f)/currentImage->height;
outStream << " R: " << ratio;
temp = outStream.str();

/* rest of the code */

Converting a String to Object

String extends Object, which means an Object. Object o = a; If you really want to get as Object, you may do like below.

String s = "Hi";

Object a =s;

How to change text and background color?

There is no (standard) cross-platform way to do this. On windows, try using conio.h. It has the:

textcolor(); // and
textbackground();

functions.

For example:

textcolor(RED);
cprintf("H");
textcolor(BLUE);
cprintf("e");
// and so on.

Clang vs GCC - which produces faster binaries?

The fact that Clang compiles code faster may not be as important as the speed of the resulting binary. However, here is a series of benchmarks.

How to recursively list all the files in a directory in C#?

A very simple solution, returns a list of files.

    public static List<string> AllFilesInFolder(string folder)
    {
        var result = new List<string>();

        foreach (string f in Directory.GetFiles(folder))
        {
            result.Add(f);
        }

        foreach (string d in Directory.GetDirectories(folder))
        {
            result.AddRange(AllFilesInFolder(d));
        }

        return result;
    }

I need a Nodejs scheduler that allows for tasks at different intervals

I think the best ranking is

1.node-schedule

2.later

3.crontab

and the sample of node-schedule is below:

var schedule = require("node-schedule");
var rule = new schedule.RecurrenceRule();
//rule.minute = 40;
rule.second = 10;
var jj = schedule.scheduleJob(rule, function(){
    console.log("execute jj");
});

Maybe you can find the answer from node modules.

Parse json string using JSON.NET

You can use .NET 4's dynamic type and built-in JavaScriptSerializer to do that. Something like this, maybe:

string json = "{\"items\":[{\"Name\":\"AAA\",\"Age\":\"22\",\"Job\":\"PPP\"},{\"Name\":\"BBB\",\"Age\":\"25\",\"Job\":\"QQQ\"},{\"Name\":\"CCC\",\"Age\":\"38\",\"Job\":\"RRR\"}]}";

var jss = new JavaScriptSerializer();

dynamic data = jss.Deserialize<dynamic>(json);

StringBuilder sb = new StringBuilder();

sb.Append("<table>\n  <thead>\n    <tr>\n");

// Build the header based on the keys in the
//  first data item.
foreach (string key in data["items"][0].Keys) {
        sb.AppendFormat("      <th>{0}</th>\n", key);
}

sb.Append("    </tr>\n  </thead>\n  <tbody>\n");

foreach (Dictionary<string, object> item in data["items"]) {
    sb.Append("    <tr>\n");

    foreach (string val in item.Values) {
        sb.AppendFormat("      <td>{0}</td>\n", val);
    }
}

sb.Append("    </tr>\n  </tbody>\n</table>");

string myTable = sb.ToString();

At the end, myTable will hold a string that looks like this:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Job</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>AAA</td>
            <td>22</td>
            <td>PPP</td>
        <tr>
            <td>BBB</td>
            <td>25</td>
            <td>QQQ</td>
        <tr>
            <td>CCC</td>
            <td>38</td>
            <td>RRR</td>
        </tr>
    </tbody>
</table>

What Are Some Good .NET Profilers?

In the past, I’ve used the profiler that ships with Visual Studio Team System.

How to get Enum Value from index in Java?

I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.

The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:

public enum Example {

    UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");

    private static HashMap<Integer, Example> enumById = new HashMap<>();
    static {
        Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
    }

    public static Example getById(int id) {
        return enumById.getOrDefault(id, UNKNOWN);
    }

    private int id;
    private String description;

    private Example(int id, String description) {
        this.id = id;
        this.description= description;
    }

    public String getDescription() {
        return description;
    }

    public int getId() {
        return id;
    }
}

If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN like I did above you can of course also do:

public static Example getById(int id) {
        return enumById.get(id);
}

MySql export schema without data

Dumping without using output.

mysqldump --no-data <database name> --result-file=schema.sql

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

This particular commands worked for me. sudo apt-get remove --purge nginx nginx-full nginx-common

and sudo apt-get install nginx

credit to this answer on stackexchnage

Conda environments not showing up in Jupyter Notebook

We have struggle a lot with this issue, and here's what works for us. If you use the conda-forge channel, it's important to make sure you are using updated packages from conda-forge, even in your Miniconda root environment.

So install Miniconda, and then do:

conda config --add channels conda-forge --force
conda update --all  -y
conda install nb_conda_kernels -y
conda env create -f custom_env.yml -q --force
jupyter notebook

and your custom environment will show up in Jupyter as an available kernel, as long as ipykernel was listed for installation in your custom_env.yml file, like this example:

name: bqplot
channels:
- conda-forge
- defaults
dependencies:
- python>=3.6
- bqplot
- ipykernel

Just to prove it working with a bunch of custom environments, here's a screen grab from Windows:

enter image description here

How to pass a single object[] to a params object[]

You need to encapsulate it into another object[] array, like this:

Foo(new Object[] { new object[]{ (object)"1", (object)"2" }});

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

How to change the default encoding to UTF-8 for Apache?

Where all the HTML files are in UTF-8 and don't have meta tags for content type, I was only able to set the needed default for these files to be sent by Apache 2.4 by adding both directives:

AddLanguage ru .html
AddCharset UTF-8 .html

How can I get a list of all open named pipes in Windows?

The second pipe was interpreted by this web site when submitted... You need two backslashes at the beginning. So make sure to use System.IO.Directory.GetFiles(@"\\.\pipe\").

Note that I have seen this function call throw an 'illegal characters in path.' exception when one of the pipes on my machine had invalid characters. PipleList.exe worked ok though, so it seems like a bug in MS's .net code.

File Upload In Angular?

Angular 2 provides good support for uploading files. No third party library is required.

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        /** In Angular 5, including the header Content-Type can invalidate your request */
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        this.http.post(`${this.apiEndPoint}`, formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)
            )
    }
}

using @angular/core": "~2.0.0" and @angular/http: "~2.0.0"

How can I print variable and string on same line in Python?

Two more

The First one

>>> births = str(5)
>>> print("there are " + births + " births.")
there are 5 births.

When adding strings, they concatenate.

The Second One

Also the format (Python 2.6 and newer) method of strings is probably the standard way:

>>> births = str(5)
>>>
>>> print("there are {} births.".format(births))
there are 5 births.

This format method can be used with lists as well

>>> format_list = ['five', 'three']
>>> # * unpacks the list:
>>> print("there are {} births and {} deaths".format(*format_list))  
there are five births and three deaths

or dictionaries

>>> format_dictionary = {'births': 'five', 'deaths': 'three'}
>>> # ** unpacks the dictionary
>>> print("there are {births} births, and {deaths} deaths".format(**format_dictionary))
there are five births, and three deaths

What is an Intent in Android?

In a broad view, we can define Intent as

When one Activity wants to start another activity it creates an Object called Intent that specifies which Activity it wants to start.

Unresolved external symbol in object files

In my case, I needed add the function name to the DEF file.

LIBRARY   DEMO
EXPORTS
   ExistingFunction   @1
   MyNewFunction      @2

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

Unfortunately, the methods you are using are unsupported in those browsers. To support my answer (this unsupportive behaviour) I have given links below.

onbeforeunload and onunload not working in opera... to support this

onbeforeunload in Opera
http://www.zachleat.com/web/dont-let-the-door-hit-you-onunload-and-onbeforeunload/

Though the onunload event doesn't work completely, you can use onunload to show a warning if a user clicks a link to navigate away from a page with an unsaved form.

onunload not working in safari... to support this

https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/

You could rather try using the pagehide event in the safari browser in lieu of onunload.

onunload not working in firefox... to support this

https://bugzilla.mozilla.org/show_bug.cgi?id=681636

They are yet to come up with a solution in FF too

Wish you good luck cheers.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

Debug assertion failed. C++ vector subscript out of range

v has 10 element, the index starts from 0 to 9.

for(int j=10;j>0;--j)
{
    cout<<v[j];   // v[10] out of range
}

you should update for loop to

for(int j=9; j>=0; --j)
//      ^^^^^^^^^^
{
    cout<<v[j];   // out of range
}

Or use reverse iterator to print element in reverse order

for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
  std::cout << *ri << std::endl;
}

Ubuntu: OpenJDK 8 - Unable to locate package

As you can see I only have java 1.7 installed (on a Ubuntu 14.04 machine).

update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64

To install Java 8, I did,

sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt-get install openjdk-8-jdk

Afterwards, now I have java 7 and 8,

update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1069 /usr/lib/jvm/java-1.8.0-openjdk-amd64

BONUS ADDED (how to switch between different versions)

  • run the follwing command from the terminal:

sudo update-alternatives --config java

There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1071      auto mode
  1            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1071      manual mode
* 2            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1069      manual mode

Press enter to keep the current choice[*], or type selection number:

As you can see I'm running open jdk 8. To switch to to jdk 7, press 1 and hit the Enter key. Do the same for javac as well with, sudo update-alternatives --config javac.

Check versions to confirm the change: java -version and javac -version.

Left Outer Join using + sign in Oracle 11g

There is some incorrect information in this thread. I copied and pasted the incorrect information:

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

The above is WRONG!!!!! It's reversed. How I determined it's incorrect is from the following book:

Oracle OCP Introduction to Oracle 9i: SQL Exam Guide. Page 115 Table 3-1 has a good summary on this. I could not figure why my converted SQL was not working properly until I went old school and looked in a printed book!

Here is the summary from this book, copied line by line:

Oracle outer Join Syntax:

from tab_a a, tab_b b,                                       
where a.col_1 + = b.col_1                                     

ANSI/ISO Equivalent:

from tab_a a left outer join  
tab_b b on a.col_1 = b.col_1

Notice here that it's the reverse of what is posted above. I suppose it's possible for this book to have errata, however I trust this book more so than what is in this thread. It's an exam guide for crying out loud...

How do I use Comparator to define a custom sort order?

In Java 8 you can do something like this:

You first need an Enum:

public enum Color {
    BLUE, YELLOW, RED
}

Car class:

public class Car {

    Color color;

    ....

    public Color getColor() {
        return color;
    }

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

And then, using your car list, you can simply do:

Collections.sort(carList, Comparator:comparing(CarSort::getColor));

simple custom event

Events are pretty easy in C#, but the MSDN docs in my opinion make them pretty confusing. Normally, most documentation you see discusses making a class inherit from the EventArgs base class and there's a reason for that. However, it's not the simplest way to make events, and for someone wanting something quick and easy, and in a time crunch, using the Action type is your ticket.

Creating Events & Subscribing To Them

1. Create your event on your class right after your class declaration.

public event Action<string,string,string,string>MyEvent;

2. Create your event handler class method in your class.

private void MyEventHandler(string s1,string s2,string s3,string s4)
{
  Console.WriteLine("{0} {1} {2} {3}",s1,s2,s3,s4);
}

3. Now when your class is invoked, tell it to connect the event to your new event handler. The reason the += operator is used is because you are appending your particular event handler to the event. You can actually do this with multiple separate event handlers, and when an event is raised, each event handler will operate in the sequence in which you added them.

class Example
{
  public Example() // I'm a C# style class constructor
  {
    MyEvent += new Action<string,string,string,string>(MyEventHandler);
  }
}

4. Now, when you're ready, trigger (aka raise) the event somewhere in your class code like so:

MyEvent("wow","this","is","cool");

The end result when you run this is that the console will emit "wow this is cool". And if you changed "cool" with a date or a sequence, and ran this event trigger multiple times, you'd see the result come out in a FIFO sequence like events should normally operate.

In this example, I passed 4 strings. But you could change those to any kind of acceptable type, or used more or less types, or even remove the <...> out and pass nothing to your event handler.

And, again, if you had multiple custom event handlers, and subscribed them all to your event with the += operator, then your event trigger would have called them all in sequence.

Identifying Event Callers

But what if you want to identify the caller to this event in your event handler? This is useful if you want an event handler that reacts with conditions based on who's raised/triggered the event. There are a few ways to do this. Below are examples that are shown in order by how fast they operate:

Option 1. (Fastest) If you already know it, then pass the name as a literal string to the event handler when you trigger it.

Option 2. (Somewhat Fast) Add this into your class and call it from the calling method, and then pass that string to the event handler when you trigger it:

private static string GetCaller([System.Runtime.CompilerServices.CallerMemberName] string s = null) => s;

Option 3. (Least Fast But Still Fast) In your event handler when you trigger it, get the calling method name string with this:

string callingMethod = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().ReflectedType.Name.Split('<', '>')[1];

Unsubscribing From Events

You may have a scenario where your custom event has multiple event handlers, but you want to remove one special one out of the list of event handlers. To do so, use the -= operator like so:

MyEvent -= MyEventHandler;

A word of minor caution with this, however. If you do this and that event no longer has any event handlers, and you trigger that event again, it will throw an exception. (Exceptions, of course, you can trap with try/catch blocks.)

Clearing All Events

Okay, let's say you're through with events and you don't want to process any more. Just set it to null like so:

MyEvent = null;

The same caution for Unsubscribing events is here, as well. If your custom event handler no longer has any events, and you trigger it again, your program will throw an exception.

When does Java's Thread.sleep throw InterruptedException?

You should generally NOT ignore the exception. Take a look at the following paper:

Don't swallow interrupts

Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can't rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt() to "reinterrupt" the current thread, as shown in Listing 3. At the very least, whenever you catch InterruptedException and don't rethrow it, reinterrupt the current thread before returning.

public class TaskRunner implements Runnable {
    private BlockingQueue<Task> queue;

    public TaskRunner(BlockingQueue<Task> queue) { 
        this.queue = queue; 
    }

    public void run() { 
        try {
             while (true) {
                 Task task = queue.take(10, TimeUnit.SECONDS);
                 task.execute();
             }
         }
         catch (InterruptedException e) { 
             // Restore the interrupted status
             Thread.currentThread().interrupt();
         }
    }
}

See the entire paper here:

http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-

Getting "TypeError: failed to fetch" when the request hasn't actually failed

The issue could be with the response you are receiving from back-end. If it was working fine on the server then the problem could be with the response headers. Check the Access-Control-Allow-Origin (ACAO) in the response headers. Usually react's fetch API will throw fail to fetch even after receiving response when the response headers' ACAO and the origin of request won't match.

How to remove all ListBox items?

  • VB ListBox2.DataSource = Nothing
  • C# ListBox2.DataSource = null;

SQL Server 2008 - Case / If statements in SELECT Clause

The most obvious solutions are already listed. Depending on where the query is sat (i.e. in application code) you can't always use IF statements and the inline CASE statements can get painful where lots of columns become conditional. Assuming Col1 + Col3 + Col7 are the same type, and likewise Col2, Col4 + Col8 you can do this:

SELECT Col1, Col2 FROM tbl WHERE @Var LIKE 'xyz'
UNION ALL
SELECT Col3, Col4 FROM tbl WHERE @Var LIKE 'zyx'
UNION ALL
SELECT Col7, Col8 FROM tbl WHERE @Var NOT LIKE 'xyz' AND @Var NOT LIKE 'zyx'

As this is a single command there are several performance benefits with regard to plan caching. Also the Query Optimiser will quickly eliminate those statements where @Var doesn't match the appropriate value without touching the storage engine.

Capture Image from Camera and Display in Activity

Here is code I have used for Capturing and Saving Camera Image then display it to imageview. You can use according to your need.

You have to save Camera image to specific location then fetch from that location then convert it to byte-array.

Here is method for opening capturing camera image activity.

private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;

private void captureCameraImage() {
        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        imageToUploadUri = Uri.fromFile(f);
        startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }

then your onActivityResult() method should be like this.

@Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                if(imageToUploadUri != null){
                    Uri selectedImage = imageToUploadUri;
                    getContentResolver().notifyChange(selectedImage, null);
                    Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                    if(reducedSizeBitmap != null){
                        ImgPhoto.setImageBitmap(reducedSizeBitmap);
                        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                          uploadImageButton.setVisibility(View.VISIBLE);                
                    }else{
                        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                }
            } 
        }

Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.

private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;

                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                    b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

Hope it helps!

How to save an image locally using Python whose URL address I already know?

Something fresh for Python 3 using Requests:

Comments in the code. Ready to use function.


import requests
from os import path

def get_image(image_url):
    """
    Get image based on url.
    :return: Image name if everything OK, False otherwise
    """
    image_name = path.split(image_url)[1]
    try:
        image = requests.get(image_url)
    except OSError:  # Little too wide, but work OK, no additional imports needed. Catch all conection problems
        return False
    if image.status_code == 200:  # we could have retrieved error page
        base_dir = path.join(path.dirname(path.realpath(__file__)), "images") # Use your own path or "" to use current working directory. Folder must exist.
        with open(path.join(base_dir, image_name), "wb") as f:
            f.write(image.content)
        return image_name

get_image("https://apod.nasddfda.gov/apod/image/2003/S106_Mishra_1947.jpg")

What is the difference between Cloud Computing and Grid Computing?

Cloud Computing is For Service Oriented where as Grid Computing is for Application Oriented. Grid computing is used to build Virtual supercomputer using a middler ware to achieve a common task that can be shared among several resources. most probably this task will be kind of computing or data storage.

Cloud computing is providing services over the internet through several servers uses Virtualization.In cloud computing either you can provide service in three types Iaas , Paas, Saas . This will give you solution when you don't have any resources for a short time Business service over the Internet.

is there a require for json in node.js

You even can use require of your JSON without specifying the extension .json. It will let you change the file extension to .js without any changes in your imports.

assuming we have ./myJsonFile.json in the same directory.

const data = require('./myJsonFile')

If in the future you'll change ./myJsonFile.json to ./myJsonFile.js nothing should be changed in the import.

Oracle query execution time

select LAST_LOAD_TIME, ELAPSED_TIME, MODULE, SQL_TEXT elapsed from v$sql
  order by LAST_LOAD_TIME desc

More complicated example (don't forget to delete or to substitute PATTERN):

select * from (
  select LAST_LOAD_TIME, to_char(ELAPSED_TIME/1000, '999,999,999.000') || ' ms' as TIME,
         MODULE, SQL_TEXT from SYS."V_\$SQL"
    where SQL_TEXT like '%PATTERN%'
    order by LAST_LOAD_TIME desc
  ) where ROWNUM <= 5;

How to output in CLI during execution of PHP Unit tests?

It is possible to use Symfony\Component\Console\Output\TrimmedBufferOutput and then test the buffered output string like this:

use Symfony\Component\Console\Output\TrimmedBufferOutput;

//...
public function testSomething()
{
   $output = new TrimmedBufferOutput(999);
   $output->writeln('Do something in your code with the output class...');
   
   //test the output:
   $this->assertStringContainsString('expected string...', $output->fetch());   
}

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

Find the below code in xampp/phpmyadmin/config.inc.php

$cfg['Servers'][$i]['controluser']  = 'user_name/root';   
$cfg['Servers'][$i]['controlpass']  = 'passwaord';
$cfg['Servers'][$i]['auth_type']    = 'config';
$cfg['Servers'][$i]['user']         = 'user_name/root';
$cfg['Servers'][$i]['password']     = 'password';

Replace each statement above with the corresponding entry below:

$cfg['Servers'][$i]['controluser']  = 'root';   
$cfg['Servers'][$i]['controlpass']  = 'xxxx';
$cfg['Servers'][$i]['auth_type']    = 'config';
$cfg['Servers'][$i]['user']         = 'root';
$cfg['Servers'][$i]['password']     = 'xxxx';

Doing this caused localhost/phpmyadmin in the browser and the MySQL command prompt to work properly.

JQuery: detect change in input field

Use jquery change event

Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

An example

$("input[type='text']").change( function() {
  // your code
});

The advantage that .change has over .keypress , .focus , .blur is that .change event will fire only when input has changed

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

getting the error: expected identifier or ‘(’ before ‘{’ token

{
int main(void);

should be

int main(void)
{

Then I let you fix the next compilation errors of your program...

Bootstrap datepicker disabling past dates without current date

The following worked for me

$('.input-group.date').datepicker({
     format: 'dd/mm/yyyy',
     startDate: new Date()
});

Get current value when change select option - Angular2

In angular 4, this worked for me

template.html

<select (change)="filterChanged($event.target.value)">
  <option *ngFor="let type of filterTypes" [value]="type.value">{{type.display}}
  </option>
</select>

component.ts

export class FilterComponent implements OnInit {

selectedFilter:string;
   public filterTypes = [
     { value: 'percentage', display: 'percentage' },
     { value: 'amount', display: 'amount' }
  ];

   constructor() { 
     this.selectedFilter = 'percentage';
   }

   filterChanged(selectedValue:string){
     console.log('value is ', selectedValue);
   }

  ngOnInit() {
  }
}

What does ^M character mean in Vim?

If it breaks your configuration, and the ^M characters are required in mappings, you can simply replace the ^M characters by <Enter> or even <C-m> (both typed as simple character sequences, so 7 and 5 characters, respectively).

This is the single recommended, portable way of storing special keycodes in mappings

How to get JSON from webpage into Python script

Late answer, but for python>=3.6 you can use:

import dload
j = dload.json(url)

Install dload with:

pip3 install dload

WPF Check box: Check changed handling

Im putting this in an answer because it's too long for a comment:

If you need the VM to be aware when the CheckBox is changed, you should really bind the CheckBox to the VM, and not a static value:

public class ViewModel
{
    private bool _caseSensitive;
    public bool CaseSensitive
    {
        get { return _caseSensitive; }
        set
        {
            _caseSensitive = value;
            NotifyPropertyChange(() => CaseSensitive);

            Settings.Default.bSearchCaseSensitive = value;
        }
    }
}

XAML:

<CheckBox Content="Case Sensitive" IsChecked="{Binding CaseSensitive}"/>

Convert Json String to C# Object List

You can use json2csharp.com to Convert your json to object model

  • Go to json2csharp.com
  • Past your JSON in the Box.
  • Clik on Generate.
  • You will get C# Code for your object model
  • Deserialize by var model = JsonConvert.DeserializeObject<RootObject>(json); using NewtonJson

Here, It will generate something like this:

public class MatrixModel
{
    public class Option
    {
        public string text { get; set; }
        public string selectedMarks { get; set; }
    }

    public class Model
    {
        public List<Option> options { get; set; }
        public int maxOptions { get; set; }
        public int minOptions { get; set; }
        public bool isAnswerRequired { get; set; }
        public string selectedOption { get; set; }
        public string answerText { get; set; }
        public bool isRangeType { get; set; }
        public string from { get; set; }
        public string to { get; set; }
        public string mins { get; set; }
        public string secs { get; set; }
    }

    public class Question
    {
        public int QuestionId { get; set; }
        public string QuestionText { get; set; }
        public int TypeId { get; set; }
        public string TypeName { get; set; }
        public Model Model { get; set; }
    }

    public class RootObject
    {
        public Question Question { get; set; }
        public string CheckType { get; set; }
        public string S1 { get; set; }
        public string S2 { get; set; }
        public string S3 { get; set; }
        public string S4 { get; set; }
        public string S5 { get; set; }
        public string S6 { get; set; }
        public string S7 { get; set; }
        public string S8 { get; set; }
        public string S9 { get; set; }
        public string S10 { get; set; }
        public string ScoreIfNoMatch { get; set; }
    }
}

Then you can deserialize as:

var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);

Are complex expressions possible in ng-hide / ng-show?

Some of these above answers didn't work for me but this did. Just in case someone else has the same issue.

ng-show="column != 'vendorid' && column !='billingMonth'"

How do I save a String to a text file using Java?

If you wish to keep the carriage return characters from the string into a file here is an code example:

    jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
    orderButton = new JButton("Execute");
    textArea = new JTextArea();
    ...


    // String captured from JTextArea()
    orderButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            // When Execute button is pressed
            String tempQuery = textArea.getText();
            tempQuery = tempQuery.replaceAll("\n", "\r\n");
            try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
                out.print(tempQuery);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(tempQuery);
        }

    });

How to use a jQuery plugin inside Vue

There's a much, much easier way. Do this:

MyComponent.vue

<template>
  stuff here
</template>
<script>
  import $ from 'jquery';
  import 'selectize';

  $(function() {
      // use jquery
      $('body').css('background-color', 'orange');

      // use selectize, s jquery plugin
      $('#myselect').selectize( options go here );
  });

</script>

Make sure JQuery is installed first with npm install jquery. Do the same with your plugin.

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

Byte Array to Image object

Since it sounds like you already know what format the byte[] array is in (e.g. RGB, ARGB, BGR etc.) you might be able to use BufferedImage.setRGB(...), or a combination of BufferedImage.getRaster() and WritableRaster.setPixels(...) or WritableRaster.setSamples(...). Unforunately both of these methods require you transform your byte[] into one of int[], float[] or double[] depending on the image format.

How do I deal with certificates using cURL while trying to access an HTTPS url?

This error is related to a missing package: ca-certificates. Install it.

In Ubuntu Linux (and similar distro):

# apt-get install ca-certificates

In CygWin via Apt-Cyg

# apt-cyg install ca-certificates

In Arch Linux (Raspberry Pi)

# pacman -S ca-certificates

The documentation tells:

This package includes PEM files of CA certificates to allow SSL-based applications to check for the authenticity of SSL connections.

As seen at: Debian -- Details of package ca-certificates in squeeze

Setting Short Value Java

There is no such thing as a byte or short literal. You need to cast to short using (short)100

Convert DateTime to String PHP

Its worked for me

$start_time   = date_create_from_format('Y-m-d H:i:s', $start_time);
$current_date = new DateTime();
$diff         = $start_time->diff($current_date);
$aa           = (string)$diff->format('%R%a');
echo gettype($aa);

How to do tag wrapping in VS code?

  1. Open Keyboard Shortcuts by typing ? Command+k ? Command+s or Code > Preferences > Keyboard Shortcuts
  2. Type emmet wrap
  3. Click the plus sign to the left of "Emmet: Wrap with Abbreviation"
  4. Type ? Option+w
  5. Press Enter

Save a list to a .txt file

If you have more then 1 dimension array

with open("file.txt", 'w') as output:
    for row in values:
        output.write(str(row) + '\n')

Code to write without '[' and ']'

with open("file.txt", 'w') as file:
        for row in values:
            s = " ".join(map(str, row))
            file.write(s+'\n')

Send POST data via raw json with postman

Unlike jQuery in order to read raw JSON you will need to decode it in PHP.

print_r(json_decode(file_get_contents("php://input"), true));

php://input is a read-only stream that allows you to read raw data from the request body.

$_POST is form variables, you will need to switch to form radiobutton in postman then use:

foo=bar&foo2=bar2

To post raw json with jquery:

$.ajax({
    "url": "/rest/index.php",
    'data': JSON.stringify({foo:'bar'}),
    'type': 'POST',
    'contentType': 'application/json'
});

Windows service on Local Computer started and then stopped error

Use Timer and tick event to copy your files.

On start the service, start the time and specify the interval in the time.

So the service is keep running and copy the files ontick.

Hope it help.

Finishing current activity from a fragment

In Fragment use getActivity.finishAffinity()

getActivity().finishAffinity();

It will remove all the fragment which pushed by the current activity from the Stack with the Activity too...

How to make an autocomplete TextBox in ASP.NET?

Try this: .aspx page

<td>  
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"OnTextChanged="TextBox1_TextChanged"></asp:TextBox>  
<asp:AutoCompleteExtender ServiceMethod="GetCompletionList" MinimumPrefixLength="1"  
   CompletionInterval="10" EnableCaching="false" CompletionSetCount="1" TargetControlID="TextBox1"  
   ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">  
      </asp:AutoCompleteExtender>  

Now To auto populate from database :

public static List<string> GetCompletionList(string prefixText, int count)  
    {  
        return AutoFillProducts(prefixText);  

    }  

    private static List<string> AutoFillProducts(string prefixText)  
    {  
        using (SqlConnection con = new SqlConnection())  
        {  
            con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;  
            using (SqlCommand com = new SqlCommand())  
            {  
                com.CommandText = "select ProductName from ProdcutMaster where " + "ProductName like @Search + '%'";  
                com.Parameters.AddWithValue("@Search", prefixText);  
                com.Connection = con;  
                con.Open();  
                List<string> countryNames = new List<string>();  
                using (SqlDataReader sdr = com.ExecuteReader())  
                {  
                    while (sdr.Read())  
                    {  
                        countryNames.Add(sdr["ProductName"].ToString());  
                    }  
                }  
                con.Close();  
                return countryNames;  
            }  
        }  
    }  

Now:create a stored Procedure that fetches the Product details depending on the selected product from the Auto Complete Text Box.

Create Procedure GetProductDet  
(  
@ProductName varchar(50)    
)  
as  
begin  
Select BrandName,warranty,Price from ProdcutMaster where ProductName=@ProductName  
End   

Create a function name to get product details ::

private void GetProductMasterDet(string ProductName)  
    {  
        connection();  
        com = new SqlCommand("GetProductDet", con);  
        com.CommandType = CommandType.StoredProcedure;  
        com.Parameters.AddWithValue("@ProductName", ProductName);  
        SqlDataAdapter da = new SqlDataAdapter(com);  
        DataSet ds=new DataSet();  
        da.Fill(ds);  
        DataTable dt = ds.Tables[0];  
        con.Close();  
        //Binding TextBox From dataTable  
        txtbrandName.Text =dt.Rows[0]["BrandName"].ToString();  
        txtwarranty.Text = dt.Rows[0]["warranty"].ToString();  
        txtPrice.Text = dt.Rows[0]["Price"].ToString();   
    }

Auto post back should be true

<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

Now, Just call this function

protected void TextBox1_TextChanged(object sender, EventArgs e)  
  {  
      //calling method and Passing Values  
      GetProductMasterDet(TextBox1.Text);  
  } 

JavaScript: What are .extend and .prototype used for?

Javascript inheritance seems to be like an open debate everywhere. It can be called "The curious case of Javascript language".

The idea is that there is a base class and then you extend the base class to get an inheritance-like feature (not completely, but still).

The whole idea is to get what prototype really means. I did not get it until I saw John Resig's code (close to what jQuery.extend does) wrote a code chunk that does it and he claims that base2 and prototype libraries were the source of inspiration.

Here is the code.

    /* Simple JavaScript Inheritance
     * By John Resig http://ejohn.org/
     * MIT Licensed.
     */  
     // Inspired by base2 and Prototype
    (function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

There are three parts which are doing the job. First, you loop through the properties and add them to the instance. After that, you create a constructor for later to be added to the object.Now, the key lines are:

// Populate our constructed prototype object
Class.prototype = prototype;

// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;

You first point the Class.prototype to the desired prototype. Now, the whole object has changed meaning that you need to force the layout back to its own one.

And the usage example:

var Car = Class.Extend({
  setColor: function(clr){
    color = clr;
  }
});

var volvo = Car.Extend({
   getColor: function () {
      return color;
   }
});

Read more about it here at Javascript Inheritance by John Resig 's post.

How to create a multi line body in C# System.Net.Mail.MailMessage

Sometimes you don't want to create a html e-mail. I solved the problem this way :

Replace \n by \t\n

The tab will not be shown, but the newline will work.

How to iterate over a JavaScript object?

<script type="text/javascript">
// method 1
var images = {};
images['name'] = {};
images['family'] = {};
images[1] = {};
images['name'][5] = "Mehdi";
images['family'][8] = "Mohammadpour";
images['family']['ok'] = 123456;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][22] = 2602;
images[1][23] = 2602;

for (const [key1, value1] of Object.entries(images)){
    for (const [key2, value2] of Object.entries(value1)){
        console.log(`${key1} => ${key2}: ${value2}`);
    }
}


console.log("=============================");

// method 2
var arr = [];
for(var x = 0; x < 5; x++){
     arr[x] = [];    
     for(var y = 0; y < 5; y++){ 
         arr[x][y] = x*y;    
     }    
 }

for(var i = 0; i < arr.length; i++) {
    var cube = arr[i];
    for(var j = 0; j < cube.length; j++) {
        console.log("cube[" + i + "][" + j + "] = " + cube[j]);
    }
}

</script>

LAST_INSERT_ID() MySQL

It would be possible to save the last_id_in_table1 variable into a php variable to use it later?

With this last_id I need to attach some records in another table with this last_id, so I need:

1) Do an INSERT and get the last_id_in_table1

INSERT into Table1(name) values ("AAA"); 
SET @last_id_in_table1 = LAST_INSERT_ID();

2) For any indeterminated rows in another table, UPDATING these rows with the last_id_insert generated in the insert.

$element = array(some ids)    
foreach ($element as $e){ 
         UPDATE Table2 SET column1 = @last_id_in_table1 WHERE id = $e 
    }

Short IF - ELSE statement

The ternary operator can only be the right side of an assignment and not a statement of its own.

http://www.devdaily.com/java/edu/pj/pj010018/

Best way to call a JSON WebService from a .NET Console

I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON string
string GET(string url) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            return reader.ReadToEnd();
        }
    }
    catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText
        }
        throw;
    }
}

I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/

POST looks like this:

// POST a JSON string
void POST(string url, string jsonContent) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType = @"application/json";

    using (Stream dataStream = request.GetRequestStream()) {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }
    long length = 0;
    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            length = response.ContentLength;
        }
    }
    catch (WebException ex) {
        // Log exception and throw as for GET example above
    }
}

I use code like this in automated tests of our web service.

In a Bash script, how can I exit the entire script if a certain condition occurs?

Try this statement:

exit 1

Replace 1 with appropriate error codes. See also Exit Codes With Special Meanings.

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

  1. First of all, there is no difference between View.OnClickListener and OnClickListener. If you just use View.OnClickListener directly, then you don't need to write-

    import android.view.View.OnClickListener

  2. You set an OnClickListener instance (e.g. myListener named object)as the listener to a view via setOnclickListener(). When a click event is fired, that myListener gets notified and it's onClick(View view) method is called. Thats where we do our own task. Hope this helps you.

Quick way to list all files in Amazon S3 bucket?

Be carefull, amazon list only returns 1000 files. If you want to iterate over all files you have to paginate the results using markers :

In ruby using aws-s3

bucket_name = 'yourBucket'
marker = ""

AWS::S3::Base.establish_connection!(
  :access_key_id => 'your_access_key_id',
  :secret_access_key => 'your_secret_access_key'
)

loop do
  objects = Bucket.objects(bucket_name, :marker=>marker, :max_keys=>1000)
  break if objects.size == 0
  marker = objects.last.key

  objects.each do |obj|
      puts "#{obj.key}"
  end
end

end

Hope this helps, vincent

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

As additional possibility for future googlers

I find it more useful to have null in the updated_at column when the record is been created but has never been modified. It reduces the db size (ok, just a little) and its possible to see it at the first sight that the data has never been modified.

As of this I use:

$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('NULL ON UPDATE CURRENT_TIMESTAMP'))->nullable();

(In Laravel 7 with mysql 8).

Best C/C++ Network Library

Aggregated List of Libraries

Capture characters from standard input without waiting for enter to be pressed

Assuming Windows, take a look at the ReadConsoleInput function.

angular-cli server - how to proxy API requests to another server?

EDIT: THIS NO LONGER WORKS IN CURRENT ANGULAR-CLI

See answer from @imal hasaranga perera for up-to-date solution


The server in angular-cli comes from the ember-cli project. To configure the server, create an .ember-cli file in the project root. Add your JSON config in there:

{
   "proxy": "https://api.example.com"
}

Restart the server and it will proxy all requests there.

For example, I'm making relative requests in my code to /v1/foo/123, which is being picked up at https://api.example.com/v1/foo/123.

You can also use a flag when you start the server: ng serve --proxy https://api.example.com

Current for angular-cli version: 1.0.0-beta.0

Get name of property as a string

Based on the answer which is already in the question and on this article: https://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/ I am presenting my solution to this problem:

public static class PropertyNameHelper
{
    /// <summary>
    /// A static method to get the Propertyname String of a Property
    /// It eliminates the need for "Magic Strings" and assures type safety when renaming properties.
    /// See: http://stackoverflow.com/questions/2820660/get-name-of-property-as-a-string
    /// </summary>
    /// <example>
    /// // Static Property
    /// string name = PropertyNameHelper.GetPropertyName(() => SomeClass.SomeProperty);
    /// // Instance Property
    /// string name = PropertyNameHelper.GetPropertyName(() => someObject.SomeProperty);
    /// </example>
    /// <typeparam name="T"></typeparam>
    /// <param name="propertyLambda"></param>
    /// <returns></returns>
    public static string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
    {
        var me = propertyLambda.Body as MemberExpression;

        if (me == null)
        {
            throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
        }

        return me.Member.Name;
    }
    /// <summary>
    /// Another way to get Instance Property names as strings.
    /// With this method you don't need to create a instance first.
    /// See the example.
    /// See: https://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/
    /// </summary>
    /// <example>
    /// string name = PropertyNameHelper((Firma f) => f.Firmenumsatz_Waehrung);
    /// </example>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="TReturn"></typeparam>
    /// <param name="expression"></param>
    /// <returns></returns>
    public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
    {
        MemberExpression body = (MemberExpression)expression.Body;
        return body.Member.Name;
    }
}

And a Test which also shows the usage for instance and static properties:

[TestClass]
public class PropertyNameHelperTest
{
    private class TestClass
    {
        public static string StaticString { get; set; }
        public string InstanceString { get; set; }
    }

    [TestMethod]
    public void TestGetPropertyName()
    {
        Assert.AreEqual("StaticString", PropertyNameHelper.GetPropertyName(() => TestClass.StaticString));

        Assert.AreEqual("InstanceString", PropertyNameHelper.GetPropertyName((TestClass t) => t.InstanceString));
    }
}

Cancel a UIView animation?

To cancel an animation you simply need to set the property that is currently being animated, outside of the UIView animation. That will stop the animation wherever it is, and the UIView will jump to the setting you just defined.

Best way to check if a drop down list contains a value?

You could try checking to see if this method returns a null:

if (ddlCustomerNumber.Items.FindByText(GetCustomerNumberCookie().ToString()) != null)
    ddlCustomerNumber.SelectedIndex = 0;

What is the Eclipse shortcut for "public static void main(String args[])"?

In Eclipse, select preferences.

In preferences, look for Java/Editor/Templates.

Here you will see a list of all of them. And you can even add your own.

How to download file from database/folder using php

You can use html5 tag to download the image directly

<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."' download>donload</a> ";
?>

For more information, check this link http://www.w3schools.com/tags/att_a_download.asp

Stopping Excel Macro executution when pressing Esc won't work

ESC and CTRL-BREAK did not work for me just now. But CTRL-ESC worked!? No idea why, but I thought I would throw it out there in case it helps someone else. (I had forgotten i = i + 1 in my loop...)

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

For 'Bad' red:

  • The Font Is: (156,0,6)
  • The Background Is: (255,199,206)

For 'Good' green:

  • The Font Is: (0,97,0)
  • The Background Is: (198,239,206)

For 'Neutral' yellow:

  • The Font Is: (156,101,0)
  • The Background Is: (255,235,156)

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">

The above links need to be included

    <context:property-placeholder location="classpath:sport.properties" />


    <bean id="myFortune" class="com.kiran.springdemo.HappyFortuneService"></bean>

    <bean id="myCoach" class="com.kiran.springdemo.setterinjection.MyCricketCoach">
        <property name="fortuner" ref="myFortune" />

        <property name="emailAddress" value="${ipl.email}" />
        <property name="team" value="${ipl.team}" />

    </bean>


</beans>

What's the best way to dedupe a table?

Using analytic function row_number:

WITH CTE (col1, col2, dupcnt)
AS
(
SELECT col1, col2,
ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col1) AS dupcnt
FROM Youtable
)
DELETE
FROM CTE
WHERE dupcnt > 1
GO                                                                 

calling javascript function on OnClientClick event of a Submit button

<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="btnGet_Click" OnClientClick="retun callMethod();" />
<script type="text/javascript">
    function callMethod() {
        //your logic should be here and make sure your logic code note returing function
        return false;
}
</script>

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

Well, people usually ask this question: Heroku or AWS when starting to deploy something.

My experiment of using both of Heroku & AWS, here is my quick review and comparison:

Heroku

  • One command to deploy whatever your project types: Ruby on Rails, Nodejs
  • So many 1-click to integrate plugins & third parties: It is super easy to start with something.
  • Don't have auto-scaling; that means you need to scale up/down manually
  • Cost is expensive, especially, when system needs more resources
  • Free instance available
  • The free instance goes to sleep if it is inactive.
  • Data center: US & EU only
  • CAN dive into/access to machine level by using Heroku run bash (Thanks, MJafar Mash for the advice) but it is kind of limited! You don't have full access!
  • Don't need to know too much about DevOps

AWS - EC2

  • This just like a machine with pre-config OS (or not), so you need to install software, library to make your website/service go online.
  • Plugin & Library need to be integrated manually, or automation script (public script & written by you)
  • Auto scaling & load balancer are the supported services, just learn how to config & integrate to your system
  • Cost is quite cheap, depends on which services and number of hours you use it
  • There are several free hours for T2.micro instances, but usually, you will pay few dollars every month (if still using T2.micro)
  • Your free instance won't go to sleep, available 24/7 (because you may pay for it :) )
  • Data center: around the world. Pick the region which is the best fit for you.
  • Dive into machine level. So you can enjoy it
  • Some knowledge about DevOps, but it is okay, Stackoverflow is helpful there!

AWS Elastic Beanstalk an alternative of Heroku, but cheaper

  • Elastic Beanstalk was announced as a public beta from 2010; it helps we easier to work with deployment. For detail please go here

  • Beanstalk is free, the cost you will pay will be for the services you use & number of hours of usage.

  • I use Elastic Beanstalk for a long time, and I think it can be the replacement of Heroku and cheaper!

Summary

  • Heroku: Easy at beginning, FREE instance, but expensive later
  • AWS: Not easy, free hours available, kind of cheaper, Beanstalk should be concerned to use

So in my current system, I use Heroku for staging and Beanstalk for production!

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

jQuery: count number of rows in a table

Well, I get the attr rows from the table and get the length for that collection:

$("#myTable").attr('rows').length;

I think that jQuery works less.

How do I create a round cornered UILabel on the iPhone?

iOS 3.0 and later

iPhone OS 3.0 and later supports the cornerRadius property on the CALayer class. Every view has a CALayer instance that you can manipulate. This means you can get rounded corners in one line:

view.layer.cornerRadius = 8;

You will need to #import <QuartzCore/QuartzCore.h> and link to the QuartzCore framework to get access to CALayer's headers and properties.

Before iOS 3.0

One way to do it, which I used recently, is to create a UIView subclass which simply draws a rounded rectangle, and then make the UILabel or, in my case, UITextView, a subview inside of it. Specifically:

  1. Create a UIView subclass and name it something like RoundRectView.
  2. In RoundRectView's drawRect: method, draw a path around the bounds of the view using Core Graphics calls like CGContextAddLineToPoint() for the edges and and CGContextAddArcToPoint() for the rounded corners.
  3. Create a UILabel instance and make it a subview of the RoundRectView.
  4. Set the frame of the label to be a few pixels inset of the RoundRectView's bounds. (For example, label.frame = CGRectInset(roundRectView.bounds, 8, 8);)

You can place the RoundRectView on a view using Interface Builder if you create a generic UIView and then change its class using the inspector. You won't see the rectangle until you compile and run your app, but at least you'll be able to place the subview and connect it to outlets or actions if needed.

How to import a csv file using python with headers intact, where first column is a non-numerical

For Python 3

Remove the rb argument and use either r or don't pass argument (default read mode).

with open( <path-to-file>, 'r' ) as theFile:
    reader = csv.DictReader(theFile)
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'
        print(line)

For Python 2

import csv
with open( <path-to-file>, "rb" ) as theFile:
    reader = csv.DictReader( theFile )
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'

Python has a powerful built-in CSV handler. In fact, most things are already built in to the standard library.

File size exceeds configured limit (2560000), code insight features not available

Windows default install location for Webstorm:

C:\Program Files\JetBrains\WebStorm 2019.1.3\bin\idea.properties

I went x4 default for intellisense and x5 for file size

(my business workstation is a beast though: 8th gen i7, 32Gb RAM, NVMe PCIE3.0x4 SDD, gloat, etc, gloat, etc)

#---------------------------------------------------------------------
# Maximum file size (kilobytes) IDE should provide code assistance for.
# The larger file is the slower its editor works and higher overall system memory requirements are
# if code assistance is enabled. Remove this property or set to very large number if you need
# code assistance for any files available regardless their size.
#--------------------------------------------------------------------- 
idea.max.intellisense.filesize=10000

    #---------------------------------------------------------------------
    # Maximum file size (kilobytes) IDE is able to open.
    #--------------------------------------------------------------------- 

idea.max.content.load.filesize=100000

How can I find out if an .EXE has Command-Line Options?

The easiest way would be to use use ProcessExplorer but it would still require some searching.

Make sure your exe is running and open ProcessExplorer. In ProcessExplorer find the name of your binary file and double click it to show properties. Click the Strings tab. Search down the list of string found in the binary file. Most strings will be garbage so they can be ignored. Search for anything that might possibly resemble a command line switch. Test this switch from the command line and see if it does anything.

Note that it might be your binary simply has no command line switches.

For reference here is the above steps applied to the Chrome executable. The command line switches accepted by Chrome can be seen in the list:

Process explorer analyzing Chrome.exe

How to clear the interpreter console?

The perfect cls:

cls = lambda: print("\033c\033[3J", end='')
cls()

Or directly:

print("\033c\033[3J", end='')

Performing a Stress Test on Web Application?

For a web based service, check out loader.io.

Summary:

loader.io is a free load testing service that allows you to stress test your web-apps/apis with thousands of concurrent connections.

They also have an API.

What is the main difference between PATCH and PUT request?

According to HTTP terms, The PUT request is just-like a database update statement. PUT - is used for modifying existing resource (Previously POSTED). On the other hand the PATCH request is used to update some portion of existing resource.

For Example:

Customer Details:

// This is just a example.

firstName = "James";
lastName = "Anderson";
email = "[email protected]";
phoneNumber = "+92 1234567890";
//..

When we want to update to entire record ? we have to use Http PUT verb for that.

such as:

// Customer Details Updated.

firstName = "James++++";
lastName = "Anderson++++";
email = "[email protected]";
phoneNumber = "+92 0987654321";
//..

On the other hand if we want to update only the portion of the record not the entire record then go for Http PATCH verb. such as:

   // Only Customer firstName and lastName is Updated.

    firstName = "Updated FirstName";
    lastName = "Updated LastName";
   //..

PUT VS POST:

When using PUT request we have to send all parameter such as firstName, lastName, email, phoneNumber Where as In patch request only send the parameters which one we want to update and it won't effecting or changing other data.

For more details please visit : https://fullstack-developer.academy/restful-api-design-post-vs-put-vs-patch/

Bash script - variable content as a command to run

Your are probably looking for eval $var.