Programs & Examples On #Copying

This tag refers to the process of making an exact duplicate of a file, database, etc.

Progress during large file copy (Copy-Item & Write-Progress?)

Hate to be the one to bump an old subject, but I found this post extremely useful. After running performance tests on the snippets by stej and it's refinement by Graham Gold, plus the BITS suggestion by Nacht, I have decuded that:

  1. I really liked Graham's command with time estimations and speed readings.
  2. I also really liked the significant speed increase of using BITS as my transfer method.

Faced with the decision between the two... I found that Start-BitsTransfer supported Asynchronous mode. So here is the result of my merging the two.

function Copy-File {
    # ref: https://stackoverflow.com/a/55527732/3626361
    param([string]$From, [string]$To)

    try {
        $job = Start-BitsTransfer -Source $From -Destination $To `
            -Description "Moving: $From => $To" `
            -DisplayName "Backup" -Asynchronous

        # Start stopwatch
        $sw = [System.Diagnostics.Stopwatch]::StartNew()
        Write-Progress -Activity "Connecting..."

        while ($job.JobState.ToString() -ne "Transferred") {
            switch ($job.JobState.ToString()) {
                "Connecting" {
                    break
                }
                "Transferring" {
                    $pctcomp = ($job.BytesTransferred / $job.BytesTotal) * 100
                    $elapsed = ($sw.elapsedmilliseconds.ToString()) / 1000

                    if ($elapsed -eq 0) {
                        $xferrate = 0.0
                    }
                    else {
                        $xferrate = (($job.BytesTransferred / $elapsed) / 1mb);
                    }

                    if ($job.BytesTransferred % 1mb -eq 0) {
                        if ($pctcomp -gt 0) {
                            $secsleft = ((($elapsed / $pctcomp) * 100) - $elapsed)
                        }
                        else {
                            $secsleft = 0
                        }

                        Write-Progress -Activity ("Copying file '" + ($From.Split("\") | Select-Object -last 1) + "' @ " + "{0:n2}" -f $xferrate + "MB/s") `
                            -PercentComplete $pctcomp `
                            -SecondsRemaining $secsleft
                    }
                    break
                }
                "Transferred" {
                    break
                }
                Default {
                    throw $job.JobState.ToString() + " unexpected BITS state."
                }
            }
        }

        $sw.Stop()
        $sw.Reset()
    }
    finally {
        Complete-BitsTransfer -BitsJob $job
        Write-Progress -Activity "Completed" -Completed
    }
}

How to copy a huge table data into another table in SQL Server

If your focus is Archiving (DW) and are dealing with VLDB with 100+ partitioned tables and you want to isolate most of these resource intensive work on a non production server (OLTP) here is a suggestion (OLTP -> DW) 1) Use backup / Restore to get the data onto the archive server (so now, on Archive or DW you will have Stage and Target database) 2) Stage database: Use partition switch to move data to corresponding stage table
3) Use SSIS to transfer data from staged database to target database for each staged table on both sides 4) Target database: Use partition switch on target database to move data from stage to base table Hope this helps.

How do I copy the contents of one stream to another?

There may be a way to do this more efficiently, depending on what kind of stream you're working with. If you can convert one or both of your streams to a MemoryStream, you can use the GetBuffer method to work directly with a byte array representing your data. This lets you use methods like Array.CopyTo, which abstract away all the issues raised by fryguybob. You can just trust .NET to know the optimal way to copy the data.

How to copy files across computers using SSH and MAC OS X Terminal

First zip or gzip the folders:
Use the following command:

zip -r NameYouWantForZipFile.zip foldertozip/

or

tar -pvczf BackUpDirectory.tar.gz /path/to/directory

for gzip compression use SCP:

scp [email protected]:~/serverpath/public_html ~/Desktop

Graphical user interface Tutorial in C

The two most usual choices are GTK+, which has documentation links here, and is mostly used with C; or Qt which has documentation here and is more used with C++.

I posted these two as you do not specify an operating system and these two are pretty cross-platform.

m2e lifecycle-mapping not found

this step works on me : 1. Remove your project on eclipse 2. Re import project 3. Delete target folder on your project 4. mvn or mvnw install

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

One can also receive this error if using the new (so far webkit only) notification feature before getting permission.

First run:

<!-- Get permission -->
<button onclick="webkitNotifications.requestPermission();">Enable Notifications</button>

Later run:

// Display Notification:
window.webkitNotifications.createNotification('image', 'Title', 'Body').show();

The request permission functions needs to be triggered from an event caused by the user, otherwise it won't be displayed.

TextView Marquee not working

I've encountered the same problem. Amith GC's answer(the first answer checked as accepted) is right, but sometimes textview.setSelected(true); doesn't work when the text view can't get the focus all the time. So, to ensure TextView Marquee working, I had to use a custom TextView.

public class CustomTextView extends TextView {
    public CustomTextView(Context context) {
        super(context);
    }
    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }


    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }


    @Override
    public boolean isFocused() {
        return true;
    }
}

And then, you can use the custom TextView as the scrolling text view in your layout .xml file like this:

<com.example.myapplication.CustomTextView
            android:id="@+id/tvScrollingMessage"
            android:text="@string/scrolling_message_main_wish_list"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit ="marquee_forever"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:scrollHorizontally="true"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/black"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="15dp"
            android:freezesText="true"/>

NOTE: in the above code snippet com.example.myapplication is an example package name and should be replaced by your own package name.

Hope this will help you. Cheers!

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

What is a good practice to check if an environmental variable exists or not?

Use the first; it directly tries to check if something is defined in environ. Though the second form works equally well, it's lacking semantically since you get a value back if it exists and only use it for a comparison.

You're trying to see if something is present in environ, why would you get just to compare it and then toss it away?

That's exactly what getenv does:

Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default.

(this also means your check could just be if getenv("FOO"))

you don't want to get it, you want to check for it's existence.

Either way, getenv is just a wrapper around environ.get but you don't see people checking for membership in mappings with:

from os import environ
if environ.get('Foo') is not None:

To summarize, use:

if "FOO" in os.environ:
    pass

if you just want to check for existence, while, use getenv("FOO") if you actually want to do something with the value you might get.

How do the post increment (i++) and pre increment (++i) operators work in Java?

++a increments and then uses the variable.
a++ uses and then increments the variable.

If you have

a = 1;

and you do

System.out.println(a++); //You will see 1

//Now a is 2

System.out.println(++a); //You will see 3

codaddict explains your particular snippet.

How can I unstage my files again after making a local commit?

git reset --soft is just for that: it is like git reset --hard, but doesn't touch the files.

How do you enable mod_rewrite on any OS?

Nope, mod_rewrite is an Apache module and has nothing to do with PHP.

To activate the module, the following line in httpd.conf needs to be active:

LoadModule rewrite_module modules/mod_rewrite.so

to see whether it is already active, try putting a .htaccess file into a web directory containing the line

RewriteEngine on

if this works without throwing a 500 internal server error, and the .htaccess file gets parsed, URL rewriting works.

How to force Chrome browser to reload .css file while debugging in Visual Studio?

If you are using SiteGround as your hosting company and none of the other solutions have worked, try this:

From the cPanel, go to "SITE IMPROVEMENT TOOLS" and click "SuperCacher." On the following page, click the "Flush Cache" button.

Set font-weight using Bootstrap classes

You should use bootstarp's variables to control your font-weight if you want a more customized value and/or you're following a scheme that needs to be repeated ; Variables are used throughout the entire project as a way to centralize and share commonly used values like colors, spacing, or font stacks;

you can find all the documentation at http://getbootstrap.com/css.

Creating a .p12 file

The openssl documentation says that file supplied as the -in argument must be in PEM format.

Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer is not PEM format rather it is PKCS7.

In order to create my .p12, I had to first convert the certificate to PEM:

openssl pkcs7 -in myCert.cer -print_certs -out certs.pem

and then execute

openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem

Evaluate expression given as a string

Alternatively, you can use evals from my pander package to capture output and all warnings, errors and other messages along with the raw results:

> pander::evals("5+5")
[[1]]
$src
[1] "5 + 5"

$result
[1] 10

$output
[1] "[1] 10"

$type
[1] "numeric"

$msg
$msg$messages
NULL

$msg$warnings
NULL

$msg$errors
NULL


$stdout
NULL

attr(,"class")
[1] "evals"

How can I count the rows with data in an Excel sheet?

With formulas, what you can do is:

  • in a new column (say col D - cell D2), add =COUNTA(A2:C2)
  • drag this formula till the end of your data (say cell D4 in our example)
  • add a last formula to sum it up (e.g in cell D5): =SUM(D2:D4)

Generate an integer that is not among four billion given ones

If they are 32-bit integers (likely from the choice of ~4 billion numbers close to 232), your list of 4 billion numbers will take up at most 93% of the possible integers (4 * 109 / (232) ). So if you create a bit-array of 232 bits with each bit initialized to zero (which will take up 229 bytes ~ 500 MB of RAM; remember a byte = 23 bits = 8 bits), read through your integer list and for each int set the corresponding bit-array element from 0 to 1; and then read through your bit-array and return the first bit that's still 0.

In the case where you have less RAM (~10 MB), this solution needs to be slightly modified. 10 MB ~ 83886080 bits is still enough to do a bit-array for all numbers between 0 and 83886079. So you could read through your list of ints; and only record #s that are between 0 and 83886079 in your bit array. If the numbers are randomly distributed; with overwhelming probability (it differs by 100% by about 10-2592069) you will find a missing int). In fact, if you only choose numbers 1 to 2048 (with only 256 bytes of RAM) you'd still find a missing number an overwhelming percentage (99.99999999999999999999999999999999999999999999999999999999999995%) of the time.

But let's say instead of having about 4 billion numbers; you had something like 232 - 1 numbers and less than 10 MB of RAM; so any small range of ints only has a small possibility of not containing the number.

If you were guaranteed that each int in the list was unique, you could sum the numbers and subtract the sum with one # missing to the full sum (½)(232)(232 - 1) = 9223372034707292160 to find the missing int. However, if an int occurred twice this method will fail.

However, you can always divide and conquer. A naive method, would be to read through the array and count the number of numbers that are in the first half (0 to 231-1) and second half (231, 232). Then pick the range with fewer numbers and repeat dividing that range in half. (Say if there were two less number in (231, 232) then your next search would count the numbers in the range (231, 3*230-1), (3*230, 232). Keep repeating until you find a range with zero numbers and you have your answer. Should take O(lg N) ~ 32 reads through the array.

That method was inefficient. We are only using two integers in each step (or about 8 bytes of RAM with a 4 byte (32-bit) integer). A better method would be to divide into sqrt(232) = 216 = 65536 bins, each with 65536 numbers in a bin. Each bin requires 4 bytes to store its count, so you need 218 bytes = 256 kB. So bin 0 is (0 to 65535=216-1), bin 1 is (216=65536 to 2*216-1=131071), bin 2 is (2*216=131072 to 3*216-1=196607). In python you'd have something like:

import numpy as np
nums_in_bin = np.zeros(65536, dtype=np.uint32)
for N in four_billion_int_array:
    nums_in_bin[N // 65536] += 1
for bin_num, bin_count in enumerate(nums_in_bin):
    if bin_count < 65536:
        break # we have found an incomplete bin with missing ints (bin_num)

Read through the ~4 billion integer list; and count how many ints fall in each of the 216 bins and find an incomplete_bin that doesn't have all 65536 numbers. Then you read through the 4 billion integer list again; but this time only notice when integers are in that range; flipping a bit when you find them.

del nums_in_bin # allow gc to free old 256kB array
from bitarray import bitarray
my_bit_array = bitarray(65536) # 32 kB
my_bit_array.setall(0)
for N in four_billion_int_array:
    if N // 65536 == bin_num:
        my_bit_array[N % 65536] = 1
for i, bit in enumerate(my_bit_array):
    if not bit:
        print bin_num*65536 + i
        break

How can I find all of the distinct file extensions in a folder hierarchy?

Find everythin with a dot and show only the suffix.

find . -type f -name "*.*" | awk -F. '{print $NF}' | sort -u

if you know all suffix have 3 characters then

find . -type f -name "*.???" | awk -F. '{print $NF}' | sort -u

or with sed shows all suffixes with one to four characters. Change {1,4} to the range of characters you are expecting in the suffix.

find . -type f | sed -n 's/.*\.\(.\{1,4\}\)$/\1/p'| sort -u

String vs. StringBuilder

I have seen significant performance gains from using the EnsureCapacity(int capacity) method call on an instance of StringBuilder before using it for any string storage. I usually call that on the line of code after instantiation. It has the same effect as if you instantiate the StringBuilder like this:

var sb = new StringBuilder(int capacity);

This call allocates needed memory ahead of time, which causes fewer memory allocations during multiple Append() operations. You have to make an educated guess on how much memory you will need, but for most applications this should not be too difficult. I usually err on the side of a little too much memory (we are talking 1k or so).

jquery data selector

$('a[data-category="music"]')

It works. See Attribute Equals Selector [name=”value”].

'python3' is not recognized as an internal or external command, operable program or batch file

Enter the command to start up the server in that directory: py -3.7 -m http.server

How to use Simple Ajax Beginform in Asp.net MVC 4?

Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

How do I divide in the Linux console?

I also had the same problem. It's easy to divide integer numbers but decimal numbers are not that easy. if you have 2 numbers like 3.14 and 2.35 and divide the numbers then, the code will be Division=echo 3.14 / 2.35 | bc echo "$Division" the quotes are different. Don't be confused, it's situated just under the esc button on your keyboard. THE ONLY DIFFERENCE IS THE | bc and also here echo works as an operator for the arithmetic calculations in stead of printing. So, I had added echo "$Division" for printing the value. Let me know if it works for you. Thank you.

What exactly does += do in python?

It is not mere a syntactic sugar. Try this:

x = []                 # empty list
x += "something"       # iterates over the string and appends to list
print(x)               # ['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']

versus

x = []                 # empty list
x = x + "something"    # TypeError: can only concatenate list (not "str") to list

The += operator invokes the __iadd__() list method, while + one invokes the __add__() one. They do different things with lists.

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

Best solution for me, detecting if a device is mobile or not:

@media (pointer:none), (pointer:coarse) {
}

Best ways to teach a beginner to program?

I would recommend in first teaching the very basics that are used in almost every language, but doing so without a language. Outline all the basic concepts If-Else If-Else, Loops, Classes, Variable Types, Structures, etc. Everything that is the foundation of most languages. Then move onto really understanding Boolean, comparisons and complex AND OR statements, to get the feeling on what the outcomes are for more complex statements.

By doing it this way he will understand the concepts of programming and have a much easier time stepping into languages, from there its just learning the intricate details of the languages, its functions, and syntax.

How do I find the data directory for a SQL Server instance?

From the GUI: open your server properties, go to Database Settings, and see Database default locations.

Note that you can drop your database files wherever you like, though it seems cleaner to keep them in the default directory.

It is more efficient to use if-return-return or if-else-return?

Since the return statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).

The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if condition is false anyway.

Note that Python supports a syntax that allows you to use only one return statement in your case:

return A+1 if A > B else A-1

How to replace comma with a dot in the number (or any replacement)

From the function's definition (http://www.w3schools.com/jsref/jsref_replace.asp):

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

This method does not change the original string.

Hence, the line: tt.replace(/,/g, '.') does not change the value of tt; it just returns the new value.

You need to replace this line with: tt = tt.replace(/,/g, '.')

How can I plot with 2 different y-axes?

One option is to make two plots side by side. ggplot2 provides a nice option for this with facet_wrap():

dat <- data.frame(x = c(rnorm(100), rnorm(100, 10, 2))
  , y = c(rnorm(100), rlnorm(100, 9, 2))
  , index = rep(1:2, each = 100)
  )

require(ggplot2)
ggplot(dat, aes(x,y)) + 
geom_point() + 
facet_wrap(~ index, scales = "free_y")

How to have Android Service communicate with Activity

Besides LocalBroadcastManager , Event Bus and Messenger already answered in this question,we can use Pending Intent to communicate from service.

As mentioned here in my blog post

Communication between service and Activity can be done using PendingIntent.For that we can use createPendingResult().createPendingResult() creates a new PendingIntent object which you can hand to service to use and to send result data back to your activity inside onActivityResult(int, int, Intent) callback.Since a PendingIntent is Parcelable , and can therefore be put into an Intent extra,your activity can pass this PendingIntent to the service.The service, in turn, can call send() method on the PendingIntent to notify the activity via onActivityResult of an event.

Activity

public class PendingIntentActivity extends AppCompatActivity
{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

PendingIntent pendingResult = createPendingResult(
100, new Intent(), 0);
Intent intent = new Intent(getApplicationContext(), PendingIntentService.class);
intent.putExtra("pendingIntent", pendingResult);
startService(intent);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode==200) {
Toast.makeText(this,data.getStringExtra("name"),Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
}

Service

public class PendingIntentService extends Service {

    private static final String[] items= { "lorem", "ipsum", "dolor",
            "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi",
            "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam",
            "vel", "erat", "placerat", "ante", "porttitor", "sodales",
            "pellentesque", "augue", "purus" };
    private PendingIntent data;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        data = intent.getParcelableExtra("pendingIntent");

        new LoadWordsThread().start();
        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    class LoadWordsThread extends Thread {
        @Override
        public void run() {
            for (String item : items) {
                if (!isInterrupted()) {

                    Intent result = new Intent();
                    result.putExtra("name", item);
                    try {
                        data.send(PendingIntentService.this,200,result);
                    } catch (PendingIntent.CanceledException e) {

                        e.printStackTrace();
                    }
                    SystemClock.sleep(400);

                }
            }
        }
    }
}

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

Android: how to make an activity return results to the activity which calls it?

UPDATE Feb. 2021

As in Activity v1.2.0 and Fragment v1.3.0, the new Activity Result APIs have been introduced.

The Activity Result APIs provide components for registering for a result, launching the result, and handling the result once it is dispatched by the system.

So there is no need of using startActivityForResult and onActivityResult anymore.

In order to use the new API, you need to create an ActivityResultLauncher in your origin Activity, specifying the callback that will be run when the destination Activity finishes and returns the desired data:

private val intentLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->

        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.getStringExtra("streetkey")
            result.data?.getStringExtra("citykey")
            result.data?.getStringExtra("homekey")
        }
    }

and then, launching your intent whenever you need to:

intentLauncher.launch(Intent(this, YourActivity::class.java))

And to return data from the destination Activity, you just have to add an intent with the values to return to the setResult() method:

val data = Intent()
data.putExtra("streetkey", "streetname")
data.putExtra("citykey", "cityname")
data.putExtra("homekey", "homename")

setResult(Activity.RESULT_OK, data)
finish()

For any additional information, please refer to Android Documentation

Centering the image in Bootstrap

Update 2018

Bootstrap 2.x

You could create a new CSS class such as:

.img-center {margin:0 auto;}

And then, add this to each IMG:

 <img src="images/2.png" class="img-responsive img-center">

OR, just override the .img-responsive if you're going to center all images..

 .img-responsive {margin:0 auto;}

Demo: http://bootply.com/86123

Bootstrap 3.x

EDIT - With the release of Bootstrap 3.0.1, the center-block class can now be used without any additional CSS..

 <img src="images/2.png" class="img-responsive center-block">

Bootstrap 4

In Bootstrap 4, the mx-auto class (auto x-axis margins) can be used to center images that are display:block. However, img is display:inline by default so text-center can be used on the parent.

<div class="container">
    <div class="row">
        <div class="col-12">
            <img class="mx-auto d-block" src="//placehold.it/200">  
        </div>
    </div>
    <div class="row">
        <div class="col-12 text-center">
            <img src="//placehold.it/200">  
        </div>
    </div>
</div>

Bootsrap 4 - center image demo

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

I had this same error in python 3.2.

I have script for email sending and:

csv.reader(open('work_dir\uslugi1.csv', newline='', encoding='utf-8'))

when I remove first char in file uslugi1.csv works fine.

Define an alias in fish shell

Just use alias. Here's a basic example:

# Define alias in shell
alias rmi "rm -i"

# Define alias in config file
alias rmi="rm -i"

# This is equivalent to entering the following function:
function rmi
    rm -i $argv
end

# Then, to save it across terminal sessions:
funcsave rmi

This last command creates the file ~/.config/fish/functions/rmi.fish.

Interested people might like to find out more about fish aliases in the official manual.

How to create a directory if it doesn't exist using Node.js?

    var filessystem = require('fs');
    var dir = './path/subpath/';

    if (!filessystem.existsSync(dir)){
        filessystem.mkdirSync(dir);
    }else
    {
        console.log("Directory already exist");
    }

This may help you :)

Is there a "standard" format for command line/shell help text?

I think there is no standard syntax for command line usage, but most use this convention:

Microsoft Command-Line Syntax, IBM has similar Command-Line Syntax


  • Text without brackets or braces

    Items you must type as shown

  • <Text inside angle brackets>

    Placeholder for which you must supply a value

  • [Text inside square brackets]

    Optional items

  • {Text inside braces}

    Set of required items; choose one

  • Vertical bar {a|b}

    Separator for mutually exclusive items; choose one

  • Ellipsis <file> …

    Items that can be repeated

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I'm using rescu with Kotlin and resolved it by using @ConstructorProperties

    data class MyResponse @ConstructorProperties("message", "count") constructor(
        val message: String,
        val count: Int
    )

Jackson uses @ConstructorProperties. This should fix Lombok @Data as well.

not:first-child selector

One of the versions you posted actually works for all modern browsers (where CSS selectors level 3 are supported):

div ul:not(:first-child) {
    background-color: #900;
}

If you need to support legacy browsers, or if you are hindered by the :not selector's limitation (it only accepts a simple selector as an argument) then you can use another technique:

Define a rule that has greater scope than what you intend and then "revoke" it conditionally, limiting its scope to what you do intend:

div ul {
    background-color: #900;  /* applies to every ul */
}

div ul:first-child {
    background-color: transparent; /* limits the scope of the previous rule */
}

When limiting the scope use the default value for each CSS attribute that you are setting.

Android - Spacing between CheckBox and text

If you want a clean design without codes, use:

<CheckBox
   android:id="@+id/checkBox1"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:drawableLeft="@android:color/transparent"
   android:drawablePadding="10dp"
   android:text="CheckBox"/>

The trick is to set colour to transparent for android:drawableLeft and assign a value for android:drawablePadding. Also, transparency allows you to use this technique on any background colour without the side effect - like colour mismatch.

Making HTML page zoom by default

Solved it as follows,

in CSS

#my{
zoom: 100%;
}

Now, it loads in 100% zoom by default. Tested it by giving 290% zoom and it loaded by that zoom percentage on default, it's upto the user if he wants to change zoom.

Though this is not the best way to do it, there is another effective solution

Check the page code of stack over flow, even they have buttons and they use un ordered lists to solve this problem.

How to insert close button in popover for Bootstrap

I was running into the problem of the tooltip doing some funky stuff when the close button became clicked. To work around this I used a span instead of using a button. Also, when the close button was clicked I would have to click the tooltip twice after it closed in order to get it to open again. To work around this I simply used the .click() method, as seen below.

<span tabindex='0' class='tooltip-close close'>×</span>

$('#myTooltip').tooltip({
    html: true,
    title: "Hello From Tooltip",
    trigger: 'click'
});    

$("body").on("click", ".tooltip-close", function (e) {
    else {
        $('.tooltip').remove();
        $('#postal-premium-tooltip').click();
    }
});

How to do INSERT into a table records extracted from another table

inserting data form one table to another table in different DATABASE

insert into DocTypeGroup 
    Select DocGrp_Id,DocGrp_SubId,DocGrp_GroupName,DocGrp_PM,DocGrp_DocType 
    from Opendatasource( 'SQLOLEDB','Data Source=10.132.20.19;UserID=sa;Password=gchaturthi').dbIPFMCI.dbo.DocTypeGroup

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

I would suggest:

def foo(element):
    do something
    if not check: return
    do more (because check was succesful)
    do much much more...

How to apply CSS page-break to print a table with lots of rows?

I eventually realised that my bulk content that was overflowing the table and not breaking properly simply didn't even need to be inside a table.

While it's not a technical solution, it solved my problem to simply end the table when I no longer needed a table; then started a new one for the footer.

Hope it helps someone... good luck!

Simple tool to 'accept theirs' or 'accept mine' on a whole file using git

The solution is very simple. git checkout <filename> tries to check out file from the index, and therefore fails on merge.

What you need to do is (i.e. checkout a commit):

To checkout your own version you can use one of:

git checkout HEAD -- <filename>

or

git checkout --ours -- <filename>

(Warning!: If you are rebasing --ours and --theirs are swapped.)

or

git show :2:<filename> > <filename> # (stage 2 is ours)

To checkout the other version you can use one of:

git checkout test-branch -- <filename>

or

git checkout --theirs -- <filename>

or

git show :3:<filename> > <filename> # (stage 3 is theirs)

You would also need to run 'add' to mark it as resolved:

git add <filename>

How to create an empty matrix in R?

The default for matrix is to have 1 column. To explicitly have 0 columns, you need to write

matrix(, nrow = 15, ncol = 0)

A better way would be to preallocate the entire matrix and then fill it in

mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- vector
}

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

I have done it this way (example):

String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"[email protected]"'";
int count=0;
try {
    ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
    while(rs.next())
        count=rs.getInt(1);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //...
}

Python For loop get index

Use the enumerate() function to generate the index along with the elements of the sequence you are looping over:

for index, w in enumerate(loopme):
    print "CURRENT WORD IS", w, "AT CHARACTER", index 

Calculate relative time in C#

You can reduce the server-side load by performing this logic client-side. View source on some Digg pages for reference. They have the server emit an epoch time value that gets processed by Javascript. This way you don't need to manage the end user's time zone. The new server-side code would be something like:

public string GetRelativeTime(DateTime timeStamp)
{
    return string.Format("<script>printdate({0});</script>", timeStamp.ToFileTimeUtc());
}

You could even add a NOSCRIPT block there and just perform a ToString().

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

So node got kicked out of path. you can do

       SET PATH=C:\Program Files\Nodejs;%PATH%

Or simply reinstall node to fix this. which ever you think is easiest for you

How to remove unused C/C++ symbols with GCC and ld?

If this thread is to be believed, you need to supply the -ffunction-sections and -fdata-sections to gcc, which will put each function and data object in its own section. Then you give and --gc-sections to GNU ld to remove the unused sections.

Notepad++ Regular expression find and delete a line

Provide the following in the search dialog:

Find What: ^$\r\n
Replace With: (Leave it empty)

Click Replace All

Detect home button press in android

An option for your application would be to write a replacement Home Screen using the android.intent.category.HOME Intent. I believe this type of Intent you can see the home button.

More details:

http://developer.android.com/guide/topics/intents/intents-filters.html#imatch

Passing variables through handlebars partial

This can also be done in later versions of handlebars using the key=value notation:

 {{> mypartial foo='bar' }}

Allowing you to pass specific values to your partial context.

Reference: Context different for partial #182

Hive query output to file

This command will redirect the output to a text file of your choice:

$hive -e "select * from table where id > 10" > ~/sample_output.txt

CSS full screen div with text in the middle

The standard approach is to give the centered element fixed dimensions, and place it absolutely:

<div class='fullscreenDiv'>
    <div class="center">Hello World</div>
</div>?

.center {
    position: absolute;
    width: 100px;
    height: 50px;
    top: 50%;
    left: 50%;
    margin-left: -50px; /* margin is -0.5 * dimension */
    margin-top: -25px; 
}?

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

...
import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

How do I get HTTP Request body content in Laravel?

You can pass data as the third argument to call(). Or, depending on your API, it's possible you may want to use the sixth parameter.

From the docs:

$this->call($method, $uri, $parameters, $files, $server, $content);

How to insert text in a td with id, using JavaScript

Use jQuery

Look how easy it would be if you did.

Example:

$('#td1').html('hello world');

What is the difference between SQL and MySQL?

SQL is the actual language that as defined by the ISO and ANSI. Here is a link to the Wikipedia article. MySQL is a specific implementation of this standard. I believe Oracle bought the company that originally developed MySQL. Other companies also have their own implementations of the SQL standard.

Create a rounded button / button with border-radius in Flutter

Different ways to create a Rounded button are as follows

FlatButton Button with Shape RoundedRectangleBorder

FlatButton(
minWidth: 260,
height: 60,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.red)),
color: Colors.white,
textColor: Colors.red,
padding: EdgeInsets.all(8.0),
onPressed: () {},
child: Text(
"Add to Cart".toUpperCase(),
style: TextStyle(
fontSize: 14.0,
),
),
),

RaisedButton Button with Shape RoundedRectangleBorder

RaisedButton(
padding:
EdgeInsets.only(left: 100, right: 100, top: 20, bottom: 20),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(28.0),
side: BorderSide(color: Colors.red)),
onPressed: () {},
color: Colors.red,
textColor: Colors.white,
child: Text("Buy now".toUpperCase(),
style: TextStyle(fontSize: 14)),
),
      

RaisedButton Button with Shape StadiumBorder()

RaisedButton(
padding:
EdgeInsets.only(left: 100, right: 100, top: 20, bottom: 20),
shape: StadiumBorder(),
onPressed: () {},
child: Text("Button"),
)

RaisedButton Button with ClipRRect

ClipRRect(
borderRadius: BorderRadius.circular(40),
child: RaisedButton(
padding: EdgeInsets.only(
left: 100, right: 100, top: 20, bottom: 20),
onPressed: () {},
child: Text("Button"),
),
)

RaisedButton Button with ClipOval

ClipOval(
child: RaisedButton(
onPressed: () {},
child: Text("Button"),
),
),

RaisedButton Button with ButtonTheme

ButtonTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: RaisedButton(
onPressed: () {},
child: Text("Button"),
),
)

practical demonstration of a round button can be found in below dartpad link

Rounded Button Demo Examples on DartPad

screenshot of dartpad

What are the different types of keys in RDBMS?

There is also a SURROGATE KEY: it occurs if one non prime attribute depends on another non prime attribute. that time you don't now to choose which key as primary key to split up your table. In that case use a surrogate key instead of a primary key. Usually this key is system defined and always have numeric values and its value often automatically incremented for new rows. Eg : ms acces = auto number & my SQL = identity column & oracle = sequence.

ps command doesn't work in docker container

If you're running a CentOS container, you can install ps using this command:

yum install -y procps

Running this command on Dockerfile:

RUN yum install -y procps

How can I replace non-printable Unicode characters in Java?

I have redesigned the code for phone numbers +9 (987) 124124 Extract digits from a string in Java

 public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );
    int i=0;
    while ( i< buffer.length()  ) { //buffer.hasRemaining()
        char chr = buffer.get(i);
        if (chr=='u'){
            i=i+5;
            chr=buffer.get(i);
        }

        if ( chr > 39 && chr < 58 )
            result[cursor++] = chr;
        i=i+1;
    }

    return new String( result, 0, cursor );
}

Location of my.cnf file on macOS

For Mac , what worked for me is creating a .my.cnf file in my ~ path. Hope this helps.

javascript how to create a validation error message without using alert

JavaScript

<script language="javascript">
        var flag=0;
        function username()
        {
            user=loginform.username.value;
            if(user=="")
            {
                document.getElementById("error0").innerHTML="Enter UserID";
                flag=1;
            }
        }   
        function password()
        {
            pass=loginform.password.value;
            if(pass=="")
            {
                document.getElementById("error1").innerHTML="Enter password";   
                flag=1;
            }
        }

        function check(form)
        {
            flag=0;
            username();
            password();
            if(flag==1)
                return false;
            else
                return true;
        }

    </script>

HTML

<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">



                    <div id="error0"></div>
                    <input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
               controls">
                    <div id="error1"></div>
                    <input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">

                    <button type="submit" class="btn">Sign in</button>
                </div>
            </div>
        </form>

Match two strings in one line with grep

To search for files containing all the words in any order anywhere:

grep -ril \'action\' | xargs grep -il \'model\' | xargs grep -il \'view_type\'

The first grep kicks off a recursive search (r), ignoring case (i) and listing (printing out) the name of the files that are matching (l) for one term ('action' with the single quotes) occurring anywhere in the file.

The subsequent greps search for the other terms, retaining case insensitivity and listing out the matching files.

The final list of files that you will get will the ones that contain these terms, in any order anywhere in the file.

java.lang.IllegalAccessError: tried to access method

In my case I was getting this error running my app in wildfly with the .ear deployed from eclipse. Because it was deployed from eclipse, the deployment folder did not contain an .ear file, but a folder representing it, and inside of it all the jars that would have been contained in the .ear file; like if the ear was unzipped.

So I had in on jar:

class MySuperClass {
  protected void mySuperMethod {}
}

And in another jar:

class MyExtendingClass extends MySuperClass {

  class MyChildrenClass {
    public void doSomething{
      mySuperMethod();
    }
  }
}

The solution for this was adding a new method to MyExtendingClass:

class MyExtendingClass extends MySuperClass {

  class MyChildrenClass {
    public void doSomething{
      mySuperMethod();
    }
  }

  @Override
  protected void mySuperMethod() {
    super.mySuperMethod();
  }
}

find without recursion

I believe you are looking for -maxdepth 1.

How to update/modify an XML file in python?

What you really want to do is use an XML parser and append the new elements with the API provided.

Then simply overwrite the file.

The easiest to use would probably be a DOM parser like the one below:

http://docs.python.org/library/xml.dom.minidom.html

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

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

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

In that case, you can use

jekyll serve --host 0.0.0.0

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

http://host's IP adress/4000 

How to convert a string to an integer in JavaScript?

There are many ways in JavaScript to convert a string to a number value... All simple and handy, choose the way which one works for you:

var num = Number("999.5"); //999.5
var num = parseInt("999.5", 10); //999
var num = parseFloat("999.5"); //999.5
var num = +"999.5"; //999.5

Also any Math operation converts them to number, for example...

var num = "999.5" / 1; //999.5
var num = "999.5" * 1; //999.5
var num = "999.5" - 1 + 1; //999.5
var num = "999.5" - 0; //999.5
var num = Math.floor("999.5"); //999
var num = ~~"999.5"; //999

My prefer way is using + sign, which is the elegant way to convert a string to number in JavaScript.

Nexus 5 USB driver

Nexus 5 with Win7 x64

-USB computer connection : Uncheck MTP and PTP

-Use a 2.0 USB port.

-Try to use the original USB cable.

Now device manager will detect nexus 5 as an androide device with ADB driver.

eclipse won't start - no java virtual machine was found

On Centos 7 I fixed this problem (after a big yum upgrade) by changing my setting for vm in:

~/eclipse/java-oxygen/eclipse/eclipse.ini

to:

-vm
/etc/alternatives/jre/bin

(which will always point to the latest installed java)

What is the main purpose of setTag() getTag() methods of View?

Setting of TAGs is really useful when you have a ListView and want to recycle/reuse the views. In that way the ListView is becoming very similar to the newer RecyclerView.

@Override
public View getView(int position, View convertView, ViewGroup parent)
  {
ViewHolder holder = null;

if ( convertView == null )
{
    /* There is no view at this position, we create a new one. 
       In this case by inflating an xml layout */
    convertView = mInflater.inflate(R.layout.listview_item, null);  
    holder = new ViewHolder();
    holder.toggleOk = (ToggleButton) convertView.findViewById( R.id.togOk );
    convertView.setTag (holder);
}
else
{
    /* We recycle a View that already exists */
    holder = (ViewHolder) convertView.getTag ();
}

// Once we have a reference to the View we are returning, we set its values.

// Here is where you should set the ToggleButton value for this item!!!

holder.toggleOk.setChecked( mToggles.get( position ) );

return convertView;
}

Refresh certain row of UITableView based on Int in Swift

I realize this question is for Swift, but here is the Xamarin equivalent code of the accepted answer if someone is interested.

var indexPath = NSIndexPath.FromRowSection(rowIndex, 0);
tableView.ReloadRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Top);

Embed image in a <button> element

Why don't you use an image with an onclick attribute?

For example:

<script>
function myfunction() {
}
</script>
<img src='Myimg.jpg' onclick='myfunction()'>

Change Spinner dropdown icon

Have you tried to define a custom background in xml? decreasing the Spinner background width which is doing your arrow look like that.

Define a layer-list with a rectangle background and your custom arrow icon:

    <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/color_white" />
            <corners android:radius="2.5dp" />
        </shape>
    </item>
    <item android:right="64dp">
         <bitmap android:gravity="right|center_vertical"  
             android:src="@drawable/custom_spinner_icon">
         </bitmap>
    </item>
</layer-list>

How can I format a decimal to always show 2 decimal places?

The Easiest way example to show you how to do that is :

Code :

>>> points = 19.5 >>> total = 22 >>>'Correct answers: {:.2%}'.format(points/total) `

Output : Correct answers: 88.64%

How to generate range of numbers from 0 to n in ES2015 only?

A lot of these solutions build on instantiating real Array objects, which can get the job done for a lot of cases but can't support cases like range(Infinity). You could use a simple generator to avoid these problems and support infinite sequences:

function* range( start, end, step = 1 ){
  if( end === undefined ) [end, start] = [start, 0];
  for( let n = start; n < end; n += step ) yield n;
}

Examples:

Array.from(range(10));     // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Array.from(range(10, 20)); // [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]

i = range(10, Infinity);
i.next(); // { value: 10, done: false }
i.next(); // { value: 11, done: false }
i.next(); // { value: 12, done: false }
i.next(); // { value: 13, done: false }
i.next(); // { value: 14, done: false }

Fast and simple String encrypt/decrypt in JAVA

Java - encrypt / decrypt user name and password from a configuration file

Code from above link

DESKeySpec keySpec = new DESKeySpec("Your secret Key phrase".getBytes("UTF8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();
sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
.........

// ENCODE plainTextPassword String
byte[] cleartext = plainTextPassword.getBytes("UTF8");      

Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
cipher.init(Cipher.ENCRYPT_MODE, key);
String encryptedPwd = base64encoder.encode(cipher.doFinal(cleartext));
// now you can store it 
......

// DECODE encryptedPwd String
byte[] encrypedPwdBytes = base64decoder.decodeBuffer(encryptedPwd);

Cipher cipher = Cipher.getInstance("DES");// cipher is not thread safe
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));

How to find Max Date in List<Object>?

LocalDate maxDate = dates.stream()
                            .max( Comparator.comparing( LocalDate::toEpochDay ) )
                            .get();

LocalDate minDate = dates.stream()
                            .min( Comparator.comparing( LocalDate::toEpochDay ) )
                            .get();

GitHub: How to make a fork of public repository private?

You have to duplicate the repo

You can see this doc (from github)

To create a duplicate of a repository without forking, you need to run a special clone command against the original repository and mirror-push to the new one.

In the following cases, the repository you're trying to push to--like exampleuser/new-repository or exampleuser/mirrored--should already exist on GitHub. See "Creating a new repository" for more information.

Mirroring a repository

To make an exact duplicate, you need to perform both a bare-clone and a mirror-push.

Open up the command line, and type these commands:

$ git clone --bare https://github.com/exampleuser/old-repository.git
# Make a bare clone of the repository

$ cd old-repository.git
$ git push --mirror https://github.com/exampleuser/new-repository.git
# Mirror-push to the new repository

$ cd ..
$ rm -rf old-repository.git
# Remove our temporary local repository

If you want to mirror a repository in another location, including getting updates from the original, you can clone a mirror and periodically push the changes.

$ git clone --mirror https://github.com/exampleuser/repository-to-mirror.git
# Make a bare mirrored clone of the repository

$ cd repository-to-mirror.git
$ git remote set-url --push origin https://github.com/exampleuser/mirrored
# Set the push location to your mirror

As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references will be overwritten each time you fetch, so it will always be the same as the original repository. Setting the URL for pushes simplifies pushing to your mirror. To update your mirror, fetch updates and push, which could be automated by running a cron job.

$ git fetch -p origin
$ git push --mirror

https://help.github.com/articles/duplicating-a-repository

What is the difference between --save and --save-dev?

I want to add some my ideas as

I think all differents will appear when someone use your codes instead of using by yourself

For example, you write a HTTP library called node's request

In your library,

you used lodash to handle string and object, without lodash, your codes cannot run

If someone use your HTTP library as a part of his codes. Your codes will be compiled with his.

your codes need lodash, So you need put in dependencies to compile


If you write a project like monaco-editor, which is a web editor,

you have bundle all your codes and your product env library using webpack, when build completed, only have a monaco-min.js

So someone don't case whether --save or --save-dependencies, only he need is monaco-min.js

Summary:

  1. If someone want to compile your codes (use as library), put lodash which used by your codes into dependencies

  2. If someone want add more feature to your codes, he need unit test and compiler, put these into dev-dependencies

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

If you have installed Visual Studio 2012 RC, then it installed .NET 4.5 RC.

Uninstall .NET 4.5 RC, and install the version you need (4.0 for VS 2010). This should clear up any problems you are having.

This solved the same problem. There is no need to uninstall Visual Studio.

RVM is not a function, selecting rubies with 'rvm use ...' will not work

The error is due to rvm is not running as in login shell. Hence try the below command:

/bin/bash --login

You will able run rvm commands instantly as login shell in terminal.

Thanks!

There are No resources that can be added or removed from the server

I encountered this error even though the Project Facets were set appropriately. The problem was that the "Runtime Environment" property was not set on the server:

Empty Runtime Environment for Eclipse Tomcat

It simply needed to be set to the appropriate Runtime:

Runtime Environment for Eclipse Tomcat

How do I create a batch file timer to execute / call another batch throughout the day

The AT command would do that but that's what the Scheduled Tasks gui is for. Enter "help at" in a cmd window for details.

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

i have created a php function which is used to upload multiple images, this function can upload multiple images in specific folder as well it can saves the records into the database in the following code $arrayimage is the array of images which is sent through form note that it will not allow upload to use multiple but you need to create different input field with same name as will you can set dynamic add field of file unput on button click.

$dir is the directory in which you want to save the image $fields is the name of the field which you want to store in the database

database field must be in array formate example if you have database imagestore and fields name like id,name,address then you need to post data like

$fields=array("id"=$_POST['idfieldname'], "name"=$_POST['namefield'],"address"=$_POST['addressfield']);

and then pass that field into function $fields

$table is the name of the table in which you want to store the data..

function multipleImageUpload($arrayimage,$dir,$fields,$table)
{
    //extracting extension of uploaded file
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $arrayimage["name"]);
    $extension = end($temp);

    //validating image
    if ((($arrayimage["type"] == "image/gif")
    || ($arrayimage["type"] == "image/jpeg")
    || ($arrayimage["type"] == "image/jpg")
    || ($arrayimage["type"] == "image/pjpeg")
    || ($arrayimage["type"] == "image/x-png")
    || ($arrayimage["type"] == "image/png"))

    //check image size

    && ($arrayimage["size"] < 20000000)

    //check iamge extension in above created extension array
    && in_array($extension, $allowedExts)) 
    {
        if ($arrayimage["error"] > 0) 
        {
            echo "Error: " . $arrayimage["error"] . "<br>";
        } 
        else 
        {
            echo "Upload: " . $arrayimage["name"] . "<br>";
            echo "Type: " . $arrayimage["type"] . "<br>";
            echo "Size: " . ($arrayimage["size"] / 1024) . " kB<br>";
            echo "Stored in: ".$arrayimage['tmp_name']."<br>";

            //check if file is exist in folder of not
            if (file_exists($dir."/".$arrayimage["name"])) 
            {
                echo $arrayimage['name'] . " already exists. ";
            } 
            else 
            {
                //extracting database fields and value
                foreach($fields as $key=>$val)
                {
                    $f[]=$key;
                    $v[]=$val;
                    $fi=implode(",",$f);
                    $value=implode("','",$v);
                }
                //dynamic sql for inserting data into any table
                $sql="INSERT INTO " . $table ."(".$fi.") VALUES ('".$value."')";
                //echo $sql;
                $imginsquery=mysql_query($sql);
                move_uploaded_file($arrayimage["tmp_name"],$dir."/".$arrayimage['name']);
                echo "<br> Stored in: " .$dir ."/ Folder <br>";

            }
        }
    } 
    //if file not match with extension
    else 
    {
        echo "Invalid file";
    }
}
//function imageUpload ends here
}

//imageFunctions class ends here

you can try this code for inserting multiple images with its extension this function is created for checking image files you can replace the extension list for perticular files in the code

Get source jar files attached to Eclipse for Maven-managed dependencies

overthink suggested using the setup in the pom:

<project>
...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <configuration>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
                ... other stuff ...
            </configuration>
        </plugin>
    </plgins>
</build>
...

First i thought this still won't attach the javadoc and sources (as i tried unsuccessfully with that -DdownloadSources option before).

But surprise - the .classpath file IS getting its sources and javadoc attached when using the POM variant!

Call a Javascript function every 5 seconds continuously

For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

setInterval(function() {
    // do stuff
}, duration);

Giving UIView rounded corners

Swift

Short answer:

myView.layer.cornerRadius = 8
myView.layer.masksToBounds = true  // optional

Supplemental Answer

If you have come to this answer, you have probably already seen enough to solve your problem. I'm adding this answer to give a bit more visual explanation for why things do what they do.

If you start with a regular UIView it has square corners.

let blueView = UIView()
blueView.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
blueView.backgroundColor = UIColor.blueColor()
view.addSubview(blueView)

enter image description here

You can give it round corners by changing the cornerRadius property of the view's layer.

blueView.layer.cornerRadius = 8

enter image description here

Larger radius values give more rounded corners

blueView.layer.cornerRadius = 25

enter image description here

and smaller values give less rounded corners.

blueView.layer.cornerRadius = 3

enter image description here

This might be enough to solve your problem right there. However, sometimes a view can have a subview or a sublayer that goes outside of the view's bounds. For example, if I were to add a subview like this

let mySubView = UIView()
mySubView.frame = CGRect(x: 20, y: 20, width: 100, height: 100)
mySubView.backgroundColor = UIColor.redColor()
blueView.addSubview(mySubView)

or if I were to add a sublayer like this

let mySubLayer = CALayer()
mySubLayer.frame = CGRect(x: 20, y: 20, width: 100, height: 100)
mySubLayer.backgroundColor = UIColor.redColor().CGColor
blueView.layer.addSublayer(mySubLayer)

Then I would end up with

enter image description here

Now, if I don't want things hanging outside of the bounds, I can do this

blueView.clipsToBounds = true

or this

blueView.layer.masksToBounds = true

which gives this result:

enter image description here

Both clipsToBounds and masksToBounds are equivalent. It is just that the first is used with UIView and the second is used with CALayer.

See also

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

I think maybe you installed redis by source code.If that you need locate to redis-source-code-path/utils and run sudo install_server.sh command. After that, make sure redis-server has been running as a service for your system sudo service redis-server status

PS: based on Debian/Ubuntu

How to use BigInteger?

sum = sum.add(BigInteger.valueOf(i))

The BigInteger class is immutable, hence you can't change its state. So calling "add" creates a new BigInteger, rather than modifying the current.

How to get all registered routes in Express?

Slightly updated and more functional approach to @prranay's answer:

const routes = app._router.stack
    .filter((middleware) => middleware.route)
    .map((middleware) => `${Object.keys(middleware.route.methods).join(', ')} -> ${middleware.route.path}`)

console.log(JSON.stringify(routes, null, 4));

Easy way to convert a unicode list to a list containing python strings?

Encode each value in the list to a string:

[x.encode('UTF8') for x in EmployeeList]

You need to pick a valid encoding; don't use str() as that'll use the system default (for Python 2 that's ASCII) which will not encode all possible codepoints in a Unicode value.

UTF-8 is capable of encoding all of the Unicode standard, but any codepoint outside the ASCII range will lead to multiple bytes per character.

However, if all you want to do is test for a specific string, test for a unicode string and Python won't have to auto-encode all values when testing for that:

u'1001' in EmployeeList.values()

Enabling error display in PHP via htaccess only

This works for me (reference):

# PHP error handling for production servers
# Disable display of startup errors
php_flag display_startup_errors off

# Disable display of all other errors
php_flag display_errors off

# Disable HTML markup of errors
php_flag html_errors off

# Enable logging of errors
php_flag log_errors on

# Disable ignoring of repeat errors
php_flag ignore_repeated_errors off

# Disable ignoring of unique source errors
php_flag ignore_repeated_source off

# Enable logging of PHP memory leaks
php_flag report_memleaks on

# Preserve most recent error via php_errormsg
php_flag track_errors on

# Disable formatting of error reference links
php_value docref_root 0

# Disable formatting of error reference links
php_value docref_ext 0

# Specify path to PHP error log
php_value error_log /home/path/public_html/domain/PHP_errors.log

# Specify recording of all PHP errors
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1

# Disable max error string length
php_value log_errors_max_len 0

# Protect error log by preventing public access
<Files PHP_errors.log>
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

AngularJS ng-click stopPropagation

In case that you're using a directive like me this is how it works when you need the two data way binding for example after updating an attribute in any model or collection:

angular.module('yourApp').directive('setSurveyInEditionMode', setSurveyInEditionMode)

function setSurveyInEditionMode() {
  return {
    restrict: 'A',
    link: function(scope, element, $attributes) {
      element.on('click', function(event){
        event.stopPropagation();
        // In order to work with stopPropagation and two data way binding
        // if you don't use scope.$apply in my case the model is not updated in the view when I click on the element that has my directive
        scope.$apply(function () {
          scope.mySurvey.inEditionMode = true;
          console.log('inside the directive')
        });
      });
    }
  }
}

Now, you can easily use it in any button, link, div, etc. like so:

<button set-survey-in-edition-mode >Edit survey</button>

Only mkdir if it does not exist

if [ ! -d directory ]; then
  mkdir directory
fi

or

mkdir -p directory

-p ensures creation if directory does not exist

Find the maximum value in a list of tuples in Python

In addition to max, you can also sort:

>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)

What is REST? Slightly confused

http://en.wikipedia.org/wiki/Representational_State_Transfer

The basic idea is that instead of having an ongoing connection to the server, you make a request, get some data, show that to a user, but maybe not all of it, and then when the user does something which calls for more data, or to pass some up to the server, the client initiates a change to a new state.

What are the differences between the urllib, urllib2, urllib3 and requests module?

I like the urllib.urlencode function, and it doesn't appear to exist in urllib2.

>>> urllib.urlencode({'abc':'d f', 'def': '-!2'})
'abc=d+f&def=-%212'

How do I conditionally add attributes to React components?

Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:

const InputComponent = function() {
    const required = true;
    const disabled = false;

    return (
        <input type="text" disabled={disabled} required={required} />
    );
}

will result in:

<input type="text" required>

Update: if anyone is curious as to how/why this happens, you can find details in ReactDOM's source code, specifically at lines 30 and 167 of the DOMProperty.js file.

Jquery - How to get the style display attribute "none / block"

If you're using jquery 1.6.2 you only need to code

$('#theid').css('display')

for example:

if($('#theid').css('display') == 'none'){ 
   $('#theid').show('slow'); 
} else { 
   $('#theid').hide('slow'); 
}

PHP get dropdown value and text

You will have to save the relationship on the server side. The value is the only part that is transmitted when the form is posted. You could do something nasty like...

<option value="2|Dog">Dog</option>

Then split the result apart if you really wanted to, but that is an ugly hack and a waste of bandwidth assuming the numbers are truly unique and have a one to one relationship with the text.

The best way would be to create an array, and loop over the array to create the HTML. Once the form is posted you can use the value to look up the text in that same array.

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

I use the AdWords API, and sometimes I have the same problem. My solution is to add ini_set('default_socket_timeout', 900); on the file vendor\googleads\googleads-php-lib\src\Google\AdsApi\AdsSoapClient.php line 65

and in the vendor\googleads-php-lib\src\Google\AdsApi\Adwords\Reporting\v201702\ReportDownloader.php line 126 ini_set('default_socket_timeout', 900); $requestOptions['stream_context']['http']['timeout'] = "900";

Google package overwrite the default php.ini parameter.

Sometimes, the page could connect to 'https://adwords.google.com/ap i/adwords/mcm/v201702/ManagedCustomerService?wsdl and sometimes no. If the page connects once, The WSDL cache will contain the same page, and the program will be ok until the code refreshes the cache...

How to check if an environment variable exists and get its value?

NEW_VAR=""
if [[ ${ENV_VAR} && ${ENV_VAR-x} ]]; then
  NEW_VAR=${ENV_VAR}
else
  NEW_VAR="new value"
fi

Listing only directories using ls in Bash?

In case you're wondering why output from 'ls -d */' gives you two trailing slashes, like:

[prompt]$ ls -d */
app//  cgi-bin//  lib//        pub//

it's probably because somewhere your shell or session configuration files alias the ls command to a version of ls that includes the -F flag. That flag appends a character to each output name (that's not a plain file) indicating the kind of thing it is. So one slash is from matching the pattern '*/', and the other slash is the appended type indicator.

To get rid of this issue, you could of course define a different alias for ls. However, to temporarily not invoke the alias, you can prepend the command with backslash:

\ls -d */

Python: How do I make a subclass from a superclass?

Subclassing in Python is done as follows:

class WindowElement:
    def print(self):
        pass

class Button(WindowElement):
    def print(self):
        pass

Here is a tutorial about Python that also contains classes and subclasses.

Bind failed: Address already in use

The error usually means that the port you are trying to open is being already used by another application. Try using netstat to see which ports are open and then use an available port.

Also check if you are binding to the right ip address (I am assuming it would be localhost)

Shared folder between MacOSX and Windows on Virtual Box

Edit

4+ years later after the original reply in 2015, virtualbox.org now offers an official user manual in both html and pdf formats, which effectively deprecates the previous version of this answer:

  • Step 3 (Guest Additions) mentioned in this response as well as several others, is discussed in great detail in manual sections 4.1 and 4.2
  • Step 1 (Shared Folders Setting in VirtualBox Manager) is discussed in section 4.3

Original Answer

Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:

  1. VirtualBox Manager: Open the Shared Folders setting and click the '+' icon to add a new folder. Then, populate the Folder Path (or use the drop-down to navigate) with the folder you want shared and make sure "Auto-Mount" and "Make Permanent" are checked.
  2. Boot Windows
  3. Once Windows is running, goto the Devices menu (at the top of the VirtualBox Manager window) and select "Insert Guest Additions CD Image...". Cycle through the prompts and once you finish installing, let it reboot.
  4. After Windows reboots, your new drive should show up as a Network Drive in Windows Explorer.

Hope that helps.

Scroll Automatically to the Bottom of the Page

If any one searching for Angular

you just need to scroll down add this to your div

 #scrollMe [scrollTop]="scrollMe.scrollHeight"

   <div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
   </div>

How to throw std::exceptions with variable messages?

Here is my solution:

#include <stdexcept>
#include <sstream>

class Formatter
{
public:
    Formatter() {}
    ~Formatter() {}

    template <typename Type>
    Formatter & operator << (const Type & value)
    {
        stream_ << value;
        return *this;
    }

    std::string str() const         { return stream_.str(); }
    operator std::string () const   { return stream_.str(); }

    enum ConvertToString 
    {
        to_str
    };
    std::string operator >> (ConvertToString) { return stream_.str(); }

private:
    std::stringstream stream_;

    Formatter(const Formatter &);
    Formatter & operator = (Formatter &);
};

Example:

throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData);   // implicitly cast to std::string
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData >> Formatter::to_str);    // explicitly cast to std::string

Laravel migration table field's type change

Not really an answer, but just a note about ->change():

Only the following column types can be "changed": bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger and unsignedSmallInteger.

https://laravel.com/docs/5.8/migrations#modifying-columns

If your column isn't one of these you will need to either drop the column or use the alter statement as mentioned in other answers.

Remove all line breaks from a long string of text

If anybody decides to use replace, you should try r'\n' instead '\n'

mystring = mystring.replace(r'\n', ' ').replace(r'\r', '')

What is a void pointer in C++?

Void is used as a keyword. The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type! A void pointer is declared like a normal pointer, using the void keyword as the pointer’s type:

General Syntax:

void* pointer_variable;

void *pVoid; // pVoid is a void pointer

A void pointer can point to objects of any data type:

int nValue;
float fValue;

struct Something
{
    int nValue;
    float fValue;
};

Something sValue;

void *pVoid;
pVoid = &nValue; // valid
pVoid = &fValue; // valid
pVoid = &sValue; // valid

However, because the void pointer does not know what type of object it is pointing to, it can not be dereferenced! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.

int nValue = 5;
void *pVoid = &nValue;

// can not dereference pVoid because it is a void pointer

int *pInt = static_cast<int*>(pVoid); // cast from void* to int*

cout << *pInt << endl; // can dereference pInt

Source: link

How do I round a double to two decimal places in Java?

Starting java 1.8 you can do more with lambda expressions & checks for null. Also, one below can handle Float or Double & variable number of decimal points (including 2 :-)).

public static Double round(Number src, int decimalPlaces) {

    return Optional.ofNullable(src)
            .map(Number::doubleValue)
            .map(BigDecimal::new)
            .map(dbl -> dbl.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP))
            .map(BigDecimal::doubleValue)
            .orElse(null);
}

How to disable HTML links

You can use this to disabled the Hyperlink of asp.net or link buttons in html.

$("td > a").attr("disabled", "disabled").on("click", function() {
    return false; 
});

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Try this:

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8,iso,utfBytes);
string msg = iso.GetString(isoBytes);

Build error: "The process cannot access the file because it is being used by another process"

VS2017 - Solved by closing all instances of MSBuild.exe in the windows task manager

Android customized button; changing text color

Changing text color of button

Because this method is now deprecated

button.setTextColor(getResources().getColor(R.color.your_color));

I use the following:

button.setTextColor(ContextCompat.getColor(mContext, R.color.your_color));

ORA-01843 not a valid month- Comparing Dates

Just in case this helps, I solved this by checking the server date format:

SELECT * FROM nls_session_parameters WHERE parameter = 'NLS_DATE_FORMAT';

then by using the following comparison (the left field is a date+time):

AND EV_DTTM >= ('01-DEC-16')

I was trying this with TO_DATE but kept getting an error. But when I matched my string with the NLS_DATE_FORMAT and removed TO_DATE, it worked...

Rails 4 - Strong Parameters - Nested Objects

If it is Rails 5, because of new hash notation: params.permit(:name, groundtruth: [:type, coordinates:[]]) will work fine.

How to convert string values from a dictionary, into int/float datatypes?

If you'd decide for a solution acting "in place" you could take a look at this one:

>>> d = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
>>> [dt.update({k: int(v)}) for dt in d for k, v in dt.iteritems()]
[None, None, None, None, None, None]
>>> d
[{'a': 1, 'c': 3, 'b': 2}, {'e': 5, 'd': 4, 'f': 6}]

Btw, key order is not preserved because that's the way standard dictionaries work, ie without the concept of order.

What are the differences between Deferred, Promise and Future in JavaScript?

These answers, including the selected answer, are good for introducing promises conceptually, but lacking in specifics of what exactly the differences are in the terminology that arises when using libraries implementing them (and there are important differences).

Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):

  • Deferred: Never described in popular references, 1 2 3 4 but commonly used by implementations as the arbiter of promise resolution (implementing resolve and reject). 5 6 7

    Sometimes deferreds are also promises (implementing then), 5 6 other times it's seen as more pure to have the Deferred only capable of resolution, and forcing the user to access the promise for using then. 7

  • Promise: The most all-encompasing word for the strategy under discussion.

    A proxy object storing the result of a target function whose synchronicity we would like to abstract, plus exposing a then function accepting another target function and returning a new promise. 2

    Example from CommonJS:

    > asyncComputeTheAnswerToEverything()
        .then(addTwo)
        .then(printResult);
    44
    

     

    Always described in popular references, although never specified as to whose responsibility resolution falls to. 1 2 3 4

    Always present in popular implementations, and never given resolution abilites. 5 6 7

  • Future: a seemingly deprecated term found in some popular references 1 and at least one popular implementation, 8 but seemingly being phased out of discussion in preference for the term 'promise' 3 and not always mentioned in popular introductions to the topic. 9

    However, at least one library uses the term generically for abstracting synchronicity and error handling, while not providing then functionality. 10 It's unclear if avoiding the term 'promise' was intentional, but probably a good choice since promises are built around 'thenables.' 2

References

  1. Wikipedia on Promises & Futures
  2. Promises/A+ spec
  3. DOM Standard on Promises
  4. DOM Standard Promises Spec WIP
  5. DOJO Toolkit Deferreds
  6. jQuery Deferreds
  7. Q
  8. FutureJS
  9. Functional Javascript section on Promises
  10. Futures in AngularJS Integration Testing

Misc potentially confusing things

XPath:: Get following Sibling

/html/body/table/tbody/tr[9]/td[1]

In Chrome (possible Safari too) you can inspect an element, then right click on the tag you want to get the xpath for, then you can copy the xpath to select that element.

A cycle was detected in the build path of project xxx - Build Path Problem

Sometimes marking as Warning

Windows -> Preferences -> Java-> Compiler -> Building -> Circular Dependencies

doesn't solve the problem because eclipse don't compile the projects that have another project in the dependencies that isn't compiled.

So to solve this problem you can try forcing Eclipse to compile every class that it be able to.

To make this just:

  1. Deselect

Windows -> Preferences -> Java-> Compiler -> Building -> Abort build when build path error occur

  1. Clean and rebuild all project

Project -> Clean...

  1. Reselect:

Windows -> Preferences -> Java-> Compiler -> Building -> Abort build when build path error occur

If you have the Automatic Build selected then you will not need to do this every time that you change the code

Select the first 10 rows - Laravel Eloquent

Another way to do it is using a limit method:

Listing::limit(10)->get();

This can be useful if you're not trying to implement pagination, but for example, return 10 random rows from a table:

Listing::inRandomOrder()->limit(10)->get();

How to do Base64 encoding in node.js?

Buffers can be used for taking a string or piece of data and doing base64 encoding of the result. For example:

> console.log(Buffer.from("Hello World").toString('base64'));
SGVsbG8gV29ybGQ=
> console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World

Buffers are a global object, so no require is needed. Buffers created with strings can take an optional encoding parameter to specify what encoding the string is in. The available toString and Buffer constructor encodings are as follows:

'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.

'utf8' - Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.

'ucs2' - 2-bytes, little endian encoded Unicode characters. It can encode only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).

'base64' - Base64 string encoding.

'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.

Why catch and rethrow an exception in C#?

You don't want to throw ex - as this will lose the call stack. See Exception Handling (MSDN).

And yes, the try...catch is doing nothing useful (apart from lose the call stack - so it's actually worse - unless for some reason you didn't want to expose this information).

WPF button click in C# code

You should place below line

btn.Click = btn.Click + btn1_Click;

How to get the data-id attribute?

using jQuery:

  $( ".myClass" ).load(function() {
    var myId = $(this).data("id");
    $('.myClass').attr('id', myId);
  });

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I was thinking the error is due to "s3:ListObjects" action but I had to add the action "s3:ListBucket" to solve the issue "AccessDenied for ListObjects for S3 bucket"

Tooltips with Twitter Bootstrap

I included the JS and CSS file and was wondering why it is not working, what made it work was when I added the following in <head>:

<script>
jQuery(function ($) {
    $("a").tooltip()
});
</script>

How to call a method defined in an AngularJS directive?

Assuming that the action button uses the same controller $scope as the directive, just define function updateMap on $scope inside the link function. Your controller can then call that function when the action button is clicked.

<div ng-controller="MyCtrl">
    <map></map>
    <button ng-click="updateMap()">call updateMap()</button>
</div>
app.directive('map', function() {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function($scope, element, attrs) {
            $scope.updateMap = function() {
                alert('inside updateMap()');
            }
        }
    }
});

fiddle


As per @FlorianF's comment, if the directive uses an isolated scope, things are more complicated. Here's one way to make it work: add a set-fn attribute to the map directive which will register the directive function with the controller:

<map set-fn="setDirectiveFn(theDirFn)"></map>
<button ng-click="directiveFn()">call directive function</button>
scope: { setFn: '&' },
link: function(scope, element, attrs) {
    scope.updateMap = function() {
       alert('inside updateMap()');
    }
    scope.setFn({theDirFn: scope.updateMap});
}
function MyCtrl($scope) {
    $scope.setDirectiveFn = function(directiveFn) {
        $scope.directiveFn = directiveFn;
    };
}

fiddle

Number of occurrences of a character in a string

You could do this:

int count = test.Split('&').Length - 1;

Or with LINQ:

test.Count(x => x == '&');

WCF named pipe minimal example

I just found this excellent little tutorial. broken link (Cached version)

I also followed Microsoft's tutorial which is nice, but I only needed pipes as well.

As you can see, you don't need configuration files and all that messy stuff.

By the way, he uses both HTTP and pipes. Just remove all code lines related to HTTP, and you'll get a pure pipe example.

Laravel Query Builder where max id

No need to use sub query, just Try this,Its working fine:

  DB::table('orders')->orderBy('id', 'desc')->first();

Open S3 object as a string with Boto3

Python3 + Using boto3 API approach.

By using S3.Client.download_fileobj API and Python file-like object, S3 Object content can be retrieved to memory.

Since the retrieved content is bytes, in order to convert to str, it need to be decoded.

import io
import boto3

client = boto3.client('s3')
bytes_buffer = io.BytesIO()
client.download_fileobj(Bucket=bucket_name, Key=object_key, Fileobj=bytes_buffer)
byte_value = bytes_buffer.getvalue()
str_value = byte_value.decode() #python3, default decoding is utf-8

Remove an item from an IEnumerable<T> collection

Try turning the IEnumerable into a List. From this point on you will be able to use List's Remove method to remove items.

To pass it as a param to the Remove method using Linq you can get the item by the following methods:

  • users.Single(x => x.userId == 1123)
  • users.First(x => x.userId == 1123)

The code is as follows:

users = users.ToList(); // Get IEnumerable as List

users.Remove(users.First(x => x.userId == 1123)); // Remove item

// Finished

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

Simple:



    dim input as string = "SPQR"
    dim format as string =""
    dim result as string = ""

    'pad left:
    format = "{0,-8}"
    result = String.Format(format,input)
    'result = "SPQR    "

    'pad right
    format = "{0,8}"
    result = String.Format(format,input)
    'result = "    SPQR"


How to clear radio button in Javascript?

Simple, no jQuery required:

<a href="javascript:clearChecks('group1')">clear</a>

<script type="text/javascript">
function clearChecks(radioName) {
    var radio = document.form1[radioName]
    for(x=0;x<radio.length;x++) {
        document.form1[radioName][x].checked = false
    }
}

</script>

Download and save PDF file with Python requests module

Please note I'm a beginner. If My solution is wrong, please feel free to correct and/or let me know. I may learn something new too.

My solution:

Change the downloadPath accordingly to where you want your file to be saved. Feel free to use the absolute path too for your usage.

Save the below as downloadFile.py.

Usage: python downloadFile.py url-of-the-file-to-download new-file-name.extension

Remember to add an extension!

Example usage: python downloadFile.py http://www.google.co.uk google.html

import requests
import sys
import os

def downloadFile(url, fileName):
    with open(fileName, "wb") as file:
        response = requests.get(url)
        file.write(response.content)


scriptPath = sys.path[0]
downloadPath = os.path.join(scriptPath, '../Downloads/')
url = sys.argv[1]
fileName = sys.argv[2]      
print('path of the script: ' + scriptPath)
print('downloading file to: ' + downloadPath)
downloadFile(url, downloadPath + fileName)
print('file downloaded...')
print('exiting program...')

Casting int to bool in C/C++

There some kind of old school 'Marxismic' way to the cast int -> bool without C4800 warnings of Microsoft's cl compiler - is to use negation of negation.

int  i  = 0;
bool bi = !!i;

int  j  = 1;
bool bj = !!j;

Get current scroll position of ScrollView in React Native

I believe contentOffset will give you an object containing the top-left scroll offset:

http://facebook.github.io/react-native/docs/scrollview.html#contentoffset

exception.getMessage() output with class name

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

public static void main(String[] args) {
    try {
        throw new RuntimeException("Cannot move file");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
    }
}

...you will see a popup that says exactly what you want.


However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:

public static void main(String[] args) {
    try {
        throw new Exception(new RuntimeException("Cannot move file"));
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                                      "Error: " + getRootCause(ex).getMessage());
    }
}

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

Laravel redirect back to original destination after login

Larvel 5.3 this actually worked for me by just updating LoginController.php

 use Illuminate\Support\Facades\Session;
 use Illuminate\Support\Facades\URL;


public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
    Session::set('backUrl', URL::previous());
}


public function redirectTo()
{
    return Session::get('backUrl') ? Session::get('backUrl') :   $this->redirectTo;
}

ref: https://laracasts.com/discuss/channels/laravel/redirect-to-previous-page-after-login

Command not found error in Bash variable assignment

I know this has been answered with a very high-quality answer. But, in short, you cant have spaces.

#!/bin/bash
STR = "Hello World"
echo $STR

Didn't work because of the spaces around the equal sign. If you were to run...

#!/bin/bash
STR="Hello World"
echo $STR

It would work

How do I drop a function if it already exists?

I usually shy away from queries from sys* type tables, vendors tend to change these between releases, major or otherwise. What I have always done is to issue the DROP FUNCTION <name> statement and not worry about any SQL error that might come back. I consider that standard procedure in the DBA realm.

How to add new item to hash

Create the hash:

hash = {:item1 => 1}

Add a new item to it:

hash[:item2] = 2

Using Mockito, how do I verify a method was a called with a certain argument?

Building off of Mamboking's answer:

ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(anyString())).thenReturn("Some result");

m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work(); 

Addressing your request to verify whether the argument contains a certain value, I could assume you mean that the argument is a String and you want to test whether the String argument contains a substring. For this you could do:

ArgumentCaptor<String> savedCaptor = ArgumentCaptor.forClass(String.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains("substring I want to find");

If that assumption was wrong, and the argument to save() is a collection of some kind, it would be only slightly different:

ArgumentCaptor<Collection<MyType>> savedCaptor = ArgumentCaptor.forClass(Collection.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains(someMyTypeElementToFindInCollection);

You might also check into ArgumentMatchers, if you know how to use Hamcrest matchers.

android.widget.Switch - on/off event listener?

For those using Kotlin, you can set a listener for a switch (in this case having the ID mySwitch) as follows:

    mySwitch.setOnCheckedChangeListener { _, isChecked ->
         // do whatever you need to do when the switch is toggled here
    }

isChecked is true if the switch is currently checked (ON), and false otherwise.

How to call a function, PostgreSQL

you declare your function as returning boolean, but it never returns anything.

pypi UserWarning: Unknown distribution option: 'install_requires'

I've now seen this in legacy tools using Python2.7, where a build (like a Dockerfile) installs an unpinned dependancy, for example pytest. PyTest has dropped Python 2.7 support, so you may need to specify version < the new package release.

Or bite the bullet and convert that app to Python 3 if that is viable.

Repeat string to certain length

def repeat_to_length(string_to_expand, length):
   return (string_to_expand * ((length/len(string_to_expand))+1))[:length]

For python3:

def repeat_to_length(string_to_expand, length):
    return (string_to_expand * (int(length/len(string_to_expand))+1))[:length]

How to list all tags along with the full message in git?

Try this it will list all the tags along with annotations & 9 lines of message for every tag:

git tag -n9

can also use

git tag -l -n9

if specific tags are to list:

git tag -l -n9 v3.*

(e.g, above command will only display tags starting with "v3.")

-l , --list List tags with names that match the given pattern (or all if no pattern is given). Running "git tag" without arguments also lists all tags. The pattern is a shell wildcard (i.e., matched using fnmatch(3)). Multiple patterns may be given; if any of them matches, the tag is shown.

Multiline editing in Visual Studio Code

For me Alt + Middle Click (scroll wheel) worked fine You have to click on Alt then long click on Middle Click then scroll Up or down

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

Something like this could be it?

HTML

 <div class="random">
        SOMETHING
 </div>

CSS

body{

    text-align: center;
}

.random{

    width: 60%;
    margin: auto;
    background-color: yellow;
    display:block;

}

DEMO: http://jsfiddle.net/t5Pp2/2/

Edit: adding display:block doesn't ruin the thing, so...

You can also set the margin to: margin: 0 auto 0 auto; just to be sure it centers only this way not from the top too.

String, StringBuffer, and StringBuilder

  • You use String when an immutable structure is appropriate; obtaining a new character sequence from a String may carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated).
  • You use StringBuilder when you need to create a mutable character sequence, usually to concatenate several character sequences together.
  • You use StringBuffer in the same circumstances you would use StringBuilder, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).

See an example here.

Force "portrait" orientation mode

I think you want to add android:configChanges="orientation|keyboardHidden" to your activity? Otherwise the activity is restarted on config-change. The onConfigurationChanged would not be called then, only the onCreate

Set value to an entire column of a pandas dataframe

Assuming your Data frame is like 'Data' you have to consider if your data is a string or an integer. Both are treated differently. So in this case you need be specific about that.

import pandas as pd

data = [('001','xxx'), ('002','xxx'), ('003','xxx'), ('004','xxx'), ('005','xxx')]

df = pd.DataFrame(data,columns=['issueid', 'industry'])

print("Old DataFrame")
print(df)

df.loc[:,'industry'] = str('yyy')

print("New DataFrame")
print(df)

Now if want to put numbers instead of letters you must create and array

list_of_ones = [1,1,1,1,1]
df.loc[:,'industry'] = list_of_ones
print(df)

Or if you are using Numpy

import numpy as np
n = len(df)
df.loc[:,'industry'] = np.ones(n)
print(df)

Call Python function from MATLAB

I've adapted the perl.m to python.m and attached this for reference for others, but I can't seem to get any output from the Python scripts to be returned to the MATLAB variable :(

Here is my M-file; note I point directly to the Python folder, C:\python27_64, in my code, and this would change on your system.

function [result status] = python(varargin)
cmdString = '';
for i = 1:nargin
    thisArg = varargin{i};
    if isempty(thisArg) || ~ischar(thisArg)
        error('MATLAB:python:InputsMustBeStrings', 'All input arguments must be valid strings.');
    end
    if i==1
        if exist(thisArg, 'file')==2
            if isempty(dir(thisArg))
                thisArg = which(thisArg);
            end
        else
            error('MATLAB:python:FileNotFound', 'Unable to find Python file: %s', thisArg);
        end
    end
  if any(thisArg == ' ')
    thisArg = ['"', thisArg, '"'];
  end
  cmdString = [cmdString, ' ', thisArg];
end
errTxtNoPython = 'Unable to find Python executable.';
if isempty(cmdString)
  error('MATLAB:python:NoPythonCommand', 'No python command specified');
elseif ispc
  pythonCmd = 'C:\python27_64';
  cmdString = ['python' cmdString];  
  pythonCmd = ['set PATH=',pythonCmd, ';%PATH%&' cmdString];
  [status, result] = dos(pythonCmd)
else
  [status ignore] = unix('which python'); %#ok
  if (status == 0)
    cmdString = ['python', cmdString];
    [status, result] = unix(cmdString);
  else
    error('MATLAB:python:NoExecutable', errTxtNoPython);
  end
end
if nargout < 2 && status~=0
  error('MATLAB:python:ExecutionError', ...
        'System error: %sCommand executed: %s', result, cmdString);
end

EDIT :

Worked out my problem the original perl.m points to a Perl installation in the MATLAB folder by updating PATH then calling Perl. The function above points to my Python install. When I called my function.py file, it was in a different directory and called other files in that directory. These where not reflected in the PATH, and I had to easy_install my Python files into my Python distribution.

How to empty a list in C#?

you can do that

var list = new List<string>();
list.Clear();

CSS3 selector to find the 2nd div of the same class

UPDATE: This answer was originally written in 2008 when nth-of-type support was unreliable at best. Today I'd say you could safely use something like .bar:nth-of-type(2), unless you have to support IE8 and older.


Original answer from 2008 follows (Note that I would not recommend this anymore!):

If you can use Prototype JS you can use this code to set some style values, or add another classname:

// set style:
$$('div.theclassname')[1].setStyle({ backgroundColor: '#900', fontSize: '1.2em' });
// OR add class name:
$$('div.theclassname')[1].addClassName('secondclass'); // pun intentded...

(I didn't test this code, and it doesn't check if there actually is a second div present, but something like this should work.)

But if you're generating the html serverside you might just as well add an extra class on the second item...

How do you build a Singleton in Dart?

Here's a concise example that combines the other solutions. Accessing the singleton can be done by:

  • Using a singleton global variable that points to the instance.
  • The common Singleton.instance pattern.
  • Using the default constructor, which is a factory that returns the instance.

Note: You should implement only one of the three options so that code using the singleton is consistent.

Singleton get singleton => Singleton.instance;
ComplexSingleton get complexSingleton => ComplexSingleton._instance;

class Singleton {
  static final Singleton instance = Singleton._private();
  Singleton._private();
  factory Singleton() => instance;
}

class ComplexSingleton {
  static ComplexSingleton _instance;
  static ComplexSingleton get instance => _instance;
  static void init(arg) => _instance ??= ComplexSingleton._init(arg);

  final property;
  ComplexSingleton._init(this.property);
  factory ComplexSingleton() => _instance;
}

If you need to do complex initialization, you'll just have to do so before using the instance later in the program.

Example

void main() {
  print(identical(singleton, Singleton.instance));        // true
  print(identical(singleton, Singleton()));               // true
  print(complexSingleton == null);                        // true
  ComplexSingleton.init(0); 
  print(complexSingleton == null);                        // false
  print(identical(complexSingleton, ComplexSingleton())); // true
}

Null & empty string comparison in Bash

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';
fi

Or to verify that a variable is empty

#!/bin/bash      
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi

tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

How to serialize a JObject without the formatting?

Call JObject's ToString(Formatting.None) method.

Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.

Documentation: Write JSON text with JToken.ToString

How to make an embedded Youtube video automatically start playing?

You have to use

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI?autoplay=1" frameborder="0" allowfullscreen></iframe>

?autoplay=1

and not

&autoplay=1

its the first URL param so its added with a ?

How can I set a custom baud rate on Linux?

You can just use the normal termios header and normal termios structure (it's the same as the termios2 when using header asm/termios).

So, you open the device using open() and get a file descriptor, then use it in tcgetattr() to fill your termios structure.

Then clear CBAUD and set CBAUDEX on c_cflag. CBAUDEX has the same value as BOTHER.

After setting this, you can set a custom baud rate using normal functions, like cfsetspeed(), specifying the desired baud rate as an integer.

How Connect to remote host from Aptana Studio 3

Window -> Show View -> Other -> Studio/Remote

(Drag this tabbed window wherever)

Click the add FTP button (see below); #profit

Add New FTP Site...

Remove end of line characters from Java string

Hey we can also use this regex solution.

String chomp = StringUtils.normalizeSpace(sentence.replaceAll("[\\r\\n]"," "));

Add the loading screen in starting of the android application

Write the code:

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        Thread welcomeThread = new Thread() {

            @Override
            public void run() {
                try {
                    super.run();
                    sleep(10000)  //Delay of 10 seconds
                } catch (Exception e) {

                } finally {

                    Intent i = new Intent(SplashActivity.this,
                            MainActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        };
        welcomeThread.start();
    }

AngularJS: How to make angular load script inside ng-include?

The accepted answer won't work from 1.2.0-rc1+ (Github issue).

Here's a quick fix created by endorama:

/*global angular */
(function (ng) {
  'use strict';

  var app = ng.module('ngLoadScript', []);

  app.directive('script', function() {
    return {
      restrict: 'E',
      scope: false,
      link: function(scope, elem, attr) {
        if (attr.type === 'text/javascript-lazy') {
          var code = elem.text();
          var f = new Function(code);
          f();
        }
      }
    };
  });

}(angular));

Simply add this file, load ngLoadScript module as application dependency and use type="text/javascript-lazy" as type for script you which to load lazily in partials:

<script type="text/javascript-lazy">
  console.log("It works!");
</script>

Java - JPA - @Version annotation

Version used to ensure that only one update in a time. JPA provider will check the version, if the expected version already increase then someone else already update the entity so an exception will be thrown.

So updating entity value would be more secure, more optimist.

If the value changes frequent, then you might consider not to use version field. For an example "an entity that has counter field, that will increased everytime a web page accessed"

Run a command over SSH with JSch

This is a shameless plug, but I'm just now writing some extensive Javadoc for JSch.

Also, there is now a Manual in the JSch Wiki (written mainly by me).


About the original question, there is not really an example for handling the streams. Reading/writing a stream is done as always.

But there simply can't be a sure way to know when one command in a shell has finished just from reading the shell's output (this is independent of the SSH protocol).

If the shell is interactive, i.e. it has a terminal attached, it will usually print a prompt, which you could try to recognize. But at least theoretically this prompt string could also occur in normal output from a command. If you want to be sure, open individual exec channels for each command instead of using a shell channel. The shell channel is mainly used for interactive use by a human user, I think.

What is the difference between SQL Server 2012 Express versions?

This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.

Summary compiled from the above document:

    * = contains the feature
                                           SQLEXPR    SQLEXPRWT   SQLEXPRADV
 ----------------------------------------------------------------------------
    > SQL Server Core                         *           *           *
    > SQL Server Management Studio            -           *           *
    > Distributed Replay – Admin Tool         -           *           *
    > LocalDB                                 -           *           *
    > SQL Server Data Tools (SSDT)            -           -           *
    > Full-text and semantic search           -           -           *
    > Specification of language in query      -           -           *
    > some of Reporting services features     -           -           *

Are PDO prepared statements sufficient to prevent SQL injection?

No, they are not always.

It depends on whether you allow user input to be placed within the query itself. For example:

$dbh = new PDO("blahblah");

$tableToUse = $_GET['userTable'];

$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );

would be vulnerable to SQL injections and using prepared statements in this example won't work, because the user input is used as an identifier, not as data. The right answer here would be to use some sort of filtering/validation like:

$dbh = new PDO("blahblah");

$tableToUse = $_GET['userTable'];
$allowedTables = array('users','admins','moderators');
if (!in_array($tableToUse,$allowedTables))    
 $tableToUse = 'users';

$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );

Note: you can't use PDO to bind data that goes outside of DDL (Data Definition Language), i.e. this does not work:

$stmt = $dbh->prepare('SELECT * FROM foo ORDER BY :userSuppliedData');

The reason why the above does not work is because DESC and ASC are not data. PDO can only escape for data. Secondly, you can't even put ' quotes around it. The only way to allow user chosen sorting is to manually filter and check that it's either DESC or ASC.

How to change Vagrant 'default' machine name?

You can change vagrant default machine name by changing value of config.vm.define.

Here is the simple Vagrantfile which uses getopts and allows you to change the name dynamically:

# -*- mode: ruby -*-
require 'getoptlong'

opts = GetoptLong.new(
  [ '--vm-name',        GetoptLong::OPTIONAL_ARGUMENT ],
)
vm_name        = ENV['VM_NAME'] || 'default'

begin
  opts.each do |opt, arg|
    case opt
      when '--vm-name'
        vm_name = arg
    end
  end
  rescue
end

Vagrant.configure(2) do |config|
  config.vm.define vm_name
  config.vm.provider "virtualbox" do |vbox, override|
    override.vm.box = "ubuntu/wily64"
    # ...
  end
  # ...
end

So to use different name, you can run for example:

vagrant --vm-name=my_name up --no-provision

Note: The --vm-name parameter needs to be specified before up command.

or:

VM_NAME=my_name vagrant up --no-provision

optional parameters in SQL Server stored proc?

You can declare like this

CREATE PROCEDURE MyProcName
    @Parameter1 INT = 1,
    @Parameter2 VARCHAR (100) = 'StringValue',
    @Parameter3 VARCHAR (100) = NULL
AS

/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
    /* whatever code you desire for a missing parameter*/
    INSERT INTO ........
END

/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter

importing external ".txt" file in python

As you can't import a .txt file, I would suggest to read words this way.

list_ = open("world.txt").read().split()

Check if one list contains element from the other

Loius answer is correct, I just want to add an example:

listOne.add("A");
listOne.add("B");
listOne.add("C");

listTwo.add("D");
listTwo.add("E");
listTwo.add("F");      

boolean noElementsInCommon = Collections.disjoint(listOne, listTwo); // true

Iterating a JavaScript object's properties using jQuery

$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

each

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

The FailedPreconditionError comes because the session is trying to read a variable that hasn"t been initialized.

As of Tensorflow version 1.11.0, you need to take this :

init_op = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init_op)

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

$month = 10; // october

$firstday = date('01-' . $month . '-Y');
$lastday = date(date('t', strtotime($firstday)) .'-' . $month . '-Y');

What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

  • RESTful services use REST architectural style,
  • RESTless services use SOAP protocol.

2. Business logic / Functionality

  • RESTful services use URL to expose business logic,
  • RESTless services use the service interface to expose business logic.

3. Security

  • RESTful inherits security from the underlying transport protocols,
  • RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

  • RESTful supports various data formats such as HTML, JSON, text, etc,
  • RESTless supports XML format.

5. Flexibility

  • RESTful is easier and flexible,
  • RESTless is not as easy and flexible.

6. Bandwidth

  • RESTful services consume less bandwidth and resource,
  • RESTless services consume more bandwidth and resources.

How to automatically reload a page after a given period of inactivity

I would consider activity to be whether or not the user is focused on the window. For example, when you click from one window to another (e.g. Google Chrome to iTunes, or Tab 1 to Tab 2 within an internet browser), the webpage can send a callback saying "Im out of focus!" or "Im in focus!". One could use jQuery to harness this possible lack of activity to do whatever they wanted. If I were in your position, I would use the following code to check for focus every 5 seconds, etc and reload if no focus.

var window_focus;
$(window).focus(function() {
    window_focus = true;
}).blur(function() {
    window_focus = false;
});
function checkReload(){
    if(!window_focus){
        location.reload();  // if not focused, reload
    }
}
setInterval(checkReload, 5000);  // check if not focused, every 5 seconds

Format number as percent in MS SQL Server

SELECT cast( cast(round(37.0/38.0,2) AS DECIMAL(18,2)) as varchar(100)) + ' %'

RESULT:  0.97 %

List files recursively in Linux CLI with path relative to the current directory

DIR=your_path
find $DIR | sed 's:""$DIR""::'

'sed' will erase 'your_path' from all 'find' results. And you recieve relative to 'DIR' path.

Connect to SQL Server Database from PowerShell

I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn [email protected] ... basic username.

Toad for Oracle..How to execute multiple statements?

If you have Multiple Insert Statements then Toad has a simple Way to execute all the Insert Statements.

Right Click On the Highlighted Insert Statements --> Select Execute Menu --> Execute Script

This will automatically start running the Insert Statements

Should I use encodeURI or encodeURIComponent for encoding URLs?

xkr.us has a great discussion, with examples. To quote their summary:

The escape() method does not encode the + character which is interpreted as a space on the server side as well as generated by forms with spaces in their fields. Due to this shortcoming and the fact that this function fails to handle non-ASCII characters correctly, you should avoid use of escape() whenever possible. The best alternative is usually encodeURIComponent().

escape() will not encode: @*/+

Use of the encodeURI() method is a bit more specialized than escape() in that it encodes for URIs as opposed to the querystring, which is part of a URL. Use this method when you need to encode a string to be used for any resource that uses URIs and needs certain characters to remain un-encoded. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURI() will not encode: ~!@#$&*()=:/,;?+'

Lastly, the encodeURIComponent() method should be used in most cases when encoding a single component of a URI. This method will encode certain chars that would normally be recognized as special chars for URIs so that many components may be included. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURIComponent() will not encode: ~!*()'

Find a class somewhere inside dozens of JAR files?

user1207523's script works fine for me. Here is a variant that searches for jar files recusively using find instead of simple expansion;

#!/bin/bash
for i in `find . -name '*.jar'`; do jar -tf "$i" | grep $1 | xargs -I{} echo -e "$i : {}" ; done

Calculate RSA key fingerprint

On Windows, if you're running PuTTY/Pageant, the fingerprint is listed when you load your PuTTY (.ppk) key into Pageant. It is pretty useful in case you forget which one you're using.

Enter image description here

Timeout on a function call

The stopit package, found on pypi, seems to handle timeouts well.

I like the @stopit.threading_timeoutable decorator, which adds a timeout parameter to the decorated function, which does what you expect, it stops the function.

Check it out on pypi: https://pypi.python.org/pypi/stopit

Multi-line strings in PHP

Well,

$xml = "l
vv";

Works.

You can also use the following:

$xml = "l\nvv";

or

$xml = <<<XML
l
vv
XML;

Edit based on comment:

You can concatenate strings using the .= operator.

$str = "Hello";
$str .= " World";
echo $str; //Will echo out "Hello World";