Programs & Examples On #Application pool

Application pools allow you to isolate your applications from one another, even if they are running on the same server.

What is an IIS application pool?

IIS-Internet information Service is a web server used to host one or more web application . Lets take any example here say Microsoft is maintaining web server and we are running our website abc.com (news content based)on this IIS. Since, Microsoft is a big shot company it might take or also ready to host another website say xyz.com(ecommerce based).

Now web server is hosting i.e providing memory to run both websites on its single web server.Thus , here application pools come into picture . abc.com has its own rules, business logic , data etc and same applies to xyz.com.

IIS provides two application pools (path) to run two websites in their own world (data) smoothly in a single webserver without affecting each ones matter (security, scalability).This is application pool in IIS.

So you can have any number of application pool depending upon on servers capacity

Byte Array to Image object

According to the Java docs, it looks like you need to use the MemoryImageSource Class to put your byte array into an object in memory, and then use Component.createImage(ImageProducer) next (passing in your MemoryImageSource, which implements ImageProducer).

Add row to query result using select

is it possible to extend query results with literals like this?

Yes.

Select Name
From Customers
UNION ALL
Select 'Jason'
  • Use UNION to add Jason if it isn't already in the result set.
  • Use UNION ALL to add Jason whether or not he's already in the result set.

What are alternatives to document.write?

As a recommended alternative to document.write you could use DOM manipulation to directly query and add node elements to the DOM.

Compilation error - missing zlib.h

In openSUSE 19.2 installing the patterns-hpc-development_node package fixed this issue for me.

IndentationError: unindent does not match any outer indentation level

The line: result = result * i should be indented (it is the body of the for-loop).

Or - you have mixed space and tab characters

How can I list all the deleted files in a Git repository?

This will get you a list of all files that were deleted in all branches, sorted by their path:

git log --diff-filter=D --summary | grep "delete mode 100" | cut -c 21- | sort > deleted.txt

Works in msysgit (2.6.1.windows.1). Note we need "delete mode 100" as git files may have been commited as mode 100644 or 100755.

What Scala web-frameworks are available?

Play is pretty sweet.

It is now production ready. It incorporates: a cool template framework,automatic reloading of source files upon safe, a composable action system, akka awesomeness, etc.

Its part of the Typesafe Stack.

Having used it for two projects, I can say that it works pretty smoothly and it should be something to consider next time you are looking to learn new web frameworks.

How to make "if not true condition"?

This one

if [[ !  $(cat /etc/passwd | grep "sysa") ]]
Then echo " something"
exit 2
fi

Android : difference between invisible and gone?

when you make it Gone every time of compilation of program the component gets initialized that means you are removing the component from layout and when you make it invisible the component it will take the same space in the layout but every time you dont need to initialize it.

if you set Visibility=Gone then you have to initialize the component..like

eg Button _mButton = new Button(this);

_mButton = (Button)findViewByid(R.id.mButton);

so it will take more time as compared to Visibility = invisible.

Python: How to get values of an array at certain index positions?

your code would be

a = [0,88,26,3,48,85,65,16,97,83,91]

ind_pos = [a[1],a[5],a[7]]

print(ind_pos)

you get [88, 85, 16]

Removing X-Powered-By

I think that is controlled by the expose_php setting in PHP.ini:

expose_php = off

Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.

There is no direct security risk, but as David C notes, exposing an outdated (and possibly vulnerable) version of PHP may be an invitation for people to try and attack it.

How to fix '.' is not an internal or external command error

Just leave out the "dot-slash" ./:

D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"

Though, if you wanted to, you could use .\ and it would work.

D:\Gesture Recognition\Gesture Recognition\Debug>.\"Gesture Recognition.exe"

how to use LIKE with column name

For SQLLite you will need to concat the strings

select * from list1 l, list2 ll 
WHERE l.name like "%"||ll.alias||"%";

How to extract this specific substring in SQL Server?

Assuming they always exist and are not part of your data, this will work:

declare @string varchar(8000) = '23;chair,red [$3]'
select substring(@string, charindex(';', @string) + 1, charindex(' [', @string) - charindex(';', @string) - 1)

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Clear and refresh jQuery Chosen dropdown list

If trigger("chosen:updated"); not working, use .trigger("liszt:updated"); of @Nhan Tran it is working fine.

The transaction log for the database is full

My problem solved with multiple execute of limited deletes like

Before

DELETE FROM TableName WHERE Condition

After

DELETE TOP(1000) FROM TableName WHERECondition

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

Converting XML to JSON using Python?

There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to do with the results.

That being said, Python's standard library has several modules for parsing XML (including DOM, SAX, and ElementTree). As of Python 2.6, support for converting Python data structures to and from JSON is included in the json module.

So the infrastructure is there.

Android layout replacing a view with another view on run time

private void replaceView(View oldV,View newV){
        ViewGroup par = (ViewGroup)oldV.getParent();
        if(par == null){return;}
        int i1 = par.indexOfChild(oldV);
        par.removeViewAt(i1);
        par.addView(newV,i1);
    }

How to set a default value in react-select

If you are not using redux-form and you are using local state for changes then your react-select component might look like this:

class MySelect extends Component {

constructor() {
    super()
}

state = {
     selectedValue: 'default' // your default value goes here
}

render() {
  <Select
       ...
       value={this.state.selectedValue}
       ...
  />
)}

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

Maybe it is too simplistic, but I used this solution and I find it very useful when I have a primary key that I can use to compare data sets. Hope it can help.

a1 <- data.frame(a = 1:5, b = letters[1:5])
a2 <- data.frame(a = 1:3, b = letters[1:3])
different.names <- (!a1$a %in% a2$a)
not.in.a2 <- a1[different.names,]

Is there a command to restart computer into safe mode?

In the command prompt, type the command below and press Enter.

bcdedit /enum

Under the Windows Boot Loader sections, make note of the identifier value.

To start in safe mode from command prompt :

bcdedit /set {identifier} safeboot minimal 

Then enter the command line to reboot your computer.

Cookie blocked/not saved in IFRAME in Internet Explorer

I was investigating this problem with regard to login-off via Azure Access Control Services, and wasn't able to connect head and tails of anything.

Then, stumbled over this post https://blogs.msdn.microsoft.com/ieinternals/2011/03/10/beware-cookie-sharing-in-cross-zone-scenarios/

In short, IE doesn't share cookies across zones (eg. Internet vs. Trusted sites).

So, if your IFrame target and html page are in different zone's P3P won't help with anything.

How to add an element to Array and shift indexes?

Have a look at commons. It uses arrayCopy(), but has nicer syntax. To those answering with the element-by-element code: if this isn't homework, that's trivial and the interesting answer is the one that promotes reuse. To those who propose lists: probably readers know about that too and performance issues should be mentioned.

How is a JavaScript hash map implemented?

every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:

var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;

javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode() function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)

2020 Update:

javascript today supports other datatypes as well: Map and WeakMap. They behave more closely as hash maps than traditional objects.

Get current controller in view

You are still in the context of your CategoryController even though you're loading a PartialView from your Views/News folder.

failed to load ad : 3

One new and update answer: Many apps that were removed this October(2018) for the lack of Privacy Policy are unable to receive ads after they get back in Play Store. You must use this form to request a "reset" for that app's ads. https://support.google.com/admob/contact/appeal_policy_violation

Took me a few days to realize and find the answer. Hope you get your ads back.

ProgressDialog is deprecated.What is the alternate one to use?

You can use this class I wrote. It offers only the basic functions. If you want a fully functional ProgressDialog, then use this lightweight library.

Gradle Setup

Add the following dependency to module/build.gradle:

compile 'com.lmntrx.android.library.livin.missme:missme:0.1.5'

How to use it?

Usage is similar to original ProgressDialog

ProgressDialog progressDialog = new 
progressDialog(YourActivity.this);
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.dismiss();

NB: You must override activity's onBackPressed()

Java8 Implementation:

@Override
public void onBackPressed() {
    progressDialog.onBackPressed(
            () -> {
                super.onBackPressed();
                return null;
            }
    );
}

Kotlin Implementation:

override fun onBackPressed() {
   progressDialog.onBackPressed { super.onBackPressed() }
}
  • Refer Sample App for the full implementation
  • Full documentation can be found here

how to open an URL in Swift3

Swift 3 version

import UIKit

protocol PhoneCalling {
    func call(phoneNumber: String)
}

extension PhoneCalling {
    func call(phoneNumber: String) {
        let cleanNumber = phoneNumber.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "-", with: "")
        guard let number = URL(string: "telprompt://" + cleanNumber) else { return }

        UIApplication.shared.open(number, options: [:], completionHandler: nil)
    }
}

Receive result from DialogFragment

I'm very surprised to see that no-one has suggested using local broadcasts for DialogFragment to Activity communication! I find it to be so much simpler and cleaner than other suggestions. Essentially, you register for your Activity to listen out for the broadcasts and you send the local broadcasts from your DialogFragment instances. Simple. For a step-by-step guide on how to set it all up, see here.

Overflow:hidden dots at the end

Hopefully it's helpful for you:

_x000D_
_x000D_
.text-with-dots {_x000D_
    display: block;_x000D_
    max-width: 98%;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden !important;_x000D_
    text-overflow: ellipsis;_x000D_
}
_x000D_
<div class='text-with-dots'>Some texts here Some texts here Some texts here Some texts here Some texts here Some texts here </div>
_x000D_
_x000D_
_x000D_

How to concatenate strings in a Windows batch file?

What about:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof

How can I detect the encoding/codepage of a text file

If you're looking to detect non-UTF encodings (i.e. no BOM), you're basically down to heuristics and statistical analysis of the text. You might want to take a look at the Mozilla paper on universal charset detection (same link, with better formatting via Wayback Machine).

Paused in debugger in chrome?

If you navigate to Sources you can see the pauseenter image description here button at the bottom of the DevTools. Basically there are 3 possible pause option in DevTools while debugging js file,

  • Don't pause on exceptions(enter image description here) :

    The pause button will be in grey colour as if "Don't pause on exceptions" is active. enter image description here

  • Pause on all exceptions(enter image description here) :

    The pause button will be in blue colour as if "Pause on all exceptions" is active. enter image description here

  • Pause on uncaught exceptions(enter image description here) :

    The pause button will be in purple colour as if "Pause on uncaught exceptions" is active. enter image description here

In your case, if you don't want to pause, select Don't pause on exceptions. To select, toggle the pause button till it become greyenter image description here.

How to scroll to an element in jQuery?

For the focus() function to work on the element the div needs to have a tabindex attribute. This is probably not done by default on this type of element as it is not an input field. You can add a tabindex for example at -1 to prevent users who use tab to focus on it. If you use a positive tabindex users will be able to use tab to focus on the div element.

Here an example: http://jsfiddle.net/klodder/gFPQL/

However tabindex is not supported in Safari.

Inserting image into IPython notebook markdown

If you want to display the image in a Markdown cell then use:

<img src="files/image.png" width="800" height="400">

If you want to display the image in a Code cell then use:

from IPython.display import Image
Image(filename='output1.png',width=800, height=400)

Remove all special characters from a string in R?

You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all from the stringr package, though gsub from base R works just as well.

The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.

x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")

(The base R equivalent is gsub("[[:punct:]]", " ", x).)

An alternative is to swap out all non-alphanumeric characters.

str_replace_all(x, "[^[:alnum:]]", " ")

Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.

Remove Primary Key in MySQL

ALTER TABLE `table_name` ADD PRIMARY KEY( `column_name`);

SyntaxError: cannot assign to operator

Instead of ((t[1])/length) * t[1] += string, you should use string += ((t[1])/length) * t[1]. (The other syntax issue - int is not iterable - will be your exercise to figure out.)

Fully change package name including company domain

@Luch Filip's solution works well if you just want to rename the App package. In my case, I also want to rename the source package too, so as not to confuse things.

Only 2 steps are needed:

  1. Click on your source folder e.g. com.company.example > Shift + F6 (Refactor->Rename...) > Rename Package > enter your desired name.

  2. Go to your AndroidManifest.xml, click on your package name > Shift + F6 (Refactor->Rename...) > enter same name as above.

Step 1 will automatically rename your R.java folder, and you can build straight away.

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

How to import large sql file in phpmyadmin

I dont understand why nobody mention the easiest way....just split the large file with http://www.rusiczki.net/2007/01/24/sql-dump-file-splitter/ and after just execute vie mySQL admin the seperated generated files starting from the one with Structure

MySQL Workbench not displaying query results

I had the same problem after upgrading to Ubuntu 14.10. I found this link which describes the steps to be followed in order to apply the patch. It takes a while since you have to start all over again: downloading, building, installing... but it worked for me! Sorry I'm not an expert and I can't provide further details.

Here are the steps described in the link above:

If you want to patch and build mysql-workbench yourself, get the source from for 6.2.3. From the directory you downloaded it to, do:

wget 'http://dev.mysql.com/get/Downloads/MySQLGUITools/mysql-workbench-community-6.2.3-src.tar.gz'

tar xvf mysql-workbench-community-6.2.3-src.tar.gz && cd mysql-workbench-community-6.2.3-src

wget -O patch-glib.diff 'http://bugs.mysql.com/file.php?id=21874&bug_id=74147'

patch -p0 < patch-glib.diff

sudo apt-get build-dep mysql-workbench

sudo apt-get install libgdal-dev

cd build

cmake .. -DBUILD_CONFIG=mysql_release

make

sudo make install

Hope this can be helpful.

Jenkins Pipeline Wipe Out Workspace

If you have used custom workspace in Jenkins then deleteDir() will not delete @tmp folder.

So to delete @tmp along with workspace use following

pipeline {
    agent {
        node {
            customWorkspace "/home/jenkins/jenkins_workspace/${JOB_NAME}_${BUILD_NUMBER}"
        }
    }
    post {
        cleanup {
            /* clean up our workspace */
            deleteDir()
            /* clean up tmp directory */
            dir("${workspace}@tmp") {
                deleteDir()
            }
            /* clean up script directory */
            dir("${workspace}@script") {
                deleteDir()
            }
        }
    }
}

This snippet will work for default workspace also.

Pretty git branch graphs

Try ditaa. It can transform any ASCII diagram into an image. Although is was not designed with Git branches in mind, I was impressed by the results.

Source (txt file):

        +--------+
        | hotfix |
        +---+----+
            |
--*<---*<---*
       ^ 
       |
       \--*<---*
               |
           +---+----+
           | master |
           +--------+

Command:

java -jar ditaa0_9.jar ascii-graph.txt

Result:

enter image description here

It also supports background colors, dashed lines, different shapes and more. See the examples.

webpack: Module not found: Error: Can't resolve (with relative path)

changing templateUrl: '' to template: '' fixed it

Throw keyword in function's signature

To add a bit more value to all the other answer's to this question, one should invest a few minutes in the question: What is the output of the following code?

#include <iostream>
void throw_exception() throw(const char *)
{
    throw 10;
}
void my_unexpected(){
    std::cout << "well - this was unexpected" << std::endl;
}
int main(int argc, char **argv){
    std::set_unexpected(my_unexpected);
    try{
        throw_exception();
    }catch(int x){
        std::cout << "catch int: " << x << std::endl;
    }catch(...){
        std::cout << "catch ..." << std::endl;
    }
}

Answer: As noted here, the program calls std::terminate() and thus none of the exception handlers will get called.

Details: First my_unexpected() function is called, but since it doesn't re-throw a matching exception type for the throw_exception() function prototype, in the end, std::terminate() is called. So the full output looks like this:

user@user:~/tmp$ g++ -o except.test except.test.cpp
user@user:~/tmp$ ./except.test
well - this was unexpected
terminate called after throwing an instance of 'int'
Aborted (core dumped)

How do I get the height and width of the Android Navigation Bar programmatically?

I hope this helps you

public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

public int getNavigationBarHeight()
{
    boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
    int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId > 0 && !hasMenuKey)
    {
        return getResources().getDimensionPixelSize(resourceId);
    }
    return 0;
}

How to disable scrolling the document body?

I know this is an ancient question, but I just thought that I'd weigh in.

I'm using disableScroll. Simple and it works like in a dream.

I have had some trouble disabling scroll on body, but allowing it on child elements (like a modal or a sidebar). It looks like that something can be done using disableScroll.on([element], [options]);, but I haven't gotten that to work just yet.


The reason that this is prefered compared to overflow: hidden; on body is that the overflow-hidden can get nasty, since some things might add overflow: hidden; like this:

... This is good for preloaders and such, since that is rendered before the CSS is finished loading.

But it gives problems, when an open navigation should add a class to the body-tag (like <body class="body__nav-open">). And then it turns into one big tug-of-war with overflow: hidden; !important and all kinds of crap.

How do I URl encode something in Node.js?

You can use JavaScript's encodeURIComponent:

encodeURIComponent('select * from table where i()')

giving

'select%20*%20from%20table%20where%20i()'

How can I call a function using a function pointer?

Initially define a function pointer array which takes a void and returns a void.

Assuming that your function is taking a void and returning a void.

typedef void (*func_ptr)(void);

Now you can use this to create function pointer variables of such functions.

Like below:

func_ptr array_of_fun_ptr[3];

Now store the address of your functions in the three variables.

array_of_fun_ptr[0]= &A;
array_of_fun_ptr[1]= &B;
array_of_fun_ptr[2]= &C;

Now you can call these functions using function pointers as below:

some_a=(*(array_of_fun_ptr[0]))();
some_b=(*(array_of_fun_ptr[1]))();
some_c=(*(array_of_fun_ptr[2]))();

How do I detect "shift+enter" and generate a new line in Textarea?

Use the jQuery hotkeys plugin and this code

jQuery(document).bind('keydown', 'shift+enter', 
         function (evt){ 
             $('textarea').val($('#textarea').val() + "\n");// use the right id here
             return true;
         }
);

Retrieve the maximum length of a VARCHAR column in SQL Server

For Oracle, it is also LENGTH instead of LEN

SELECT MAX(LENGTH(Desc)) FROM table_name

Also, DESC is a reserved word. Although many reserved words will still work for column names in many circumstances it is bad practice to do so, and can cause issues in some circumstances. They are reserved for a reason.

If the word Desc was just being used as an example, it should be noted that not everyone will realize that, but many will realize that it is a reserved word for Descending. Personally, I started off by using this, and then trying to figure out where the column name went because all I had were reserved words. It didn't take long to figure it out, but keep that in mind when deciding on what to substitute for your actual column name.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

On CentOS Linux, Python3.6, I edited this file (make a backup copy first)

/usr/lib/python3.6/site-packages/certifi/cacert.pem

to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.

How to list containers in Docker

To display only running containers

docker ps

To show all containers (includes all states)

docker ps -a

To show the latest created container (includes all states)

docker ps -l

To show n last created containers (includes all states)

docker ps -n=-1

To display total file sizes

docker ps -s

In the new version of Docker, commands are updated, and some management commands are added:

docker container ls

List all the running containers.

docker container ls -a

How to convert Varchar to Double in sql?

use DECIMAL() or NUMERIC() as they are fixed precision and scale numbers.

SELECT fullName, 
       CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info 
ORDER BY _totalBal DESC

How to suppress scientific notation when printing float values?

If it is a string then use the built in float on it to do the conversion for instance: print( "%.5f" % float("1.43572e-03")) answer:0.00143572

Bootstrap Modal before form Submit

You can use browser default prompt window. Instead of basic <input type="submit" (...) > try:

<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>

Copying PostgreSQL database to another server

If you are more comfortable with a GUI, you can use the pgAdmin software.

  • Connect to your source and destination servers
  • Right-click on the source db > backup
  • Right-click on the destination server > create > database. Use the same properties as the source db (you can see the properties of the source db by right-click > properties)
  • Right-click on the created db > restore.

enter image description here

Query to get only numbers from a string

I did not have rights to create functions but had text like

["blahblah012345679"]

And needed to extract the numbers out of the middle

Note this assumes the numbers are grouped together and not at the start and end of the string.

select substring(column_name,patindex('%[0-9]%', column_name),patindex('%[0-9][^0-9]%', column_name)-patindex('%[0-9]%', column_name)+1)
from table name

Efficiently test if a port is open on Linux?

You can use netcat command as well

[location of netcat]/netcat -zv [ip] [port]

or

nc -zv [ip] [port]

-z – sets nc to simply scan for listening daemons, without actually sending any data to them.
-v – enables verbose mode.

Google Recaptcha v3 example demo

I process POST on PHP from an angular ajax call. I also like to see the SCORE from google.

This works well for me...

$postData = json_decode(file_get_contents('php://input'), true); //get data sent via post
$captcha = $postData['g-recaptcha-response'];

header('Content-Type: application/json');
if($captcha === ''){
    //Do something with error
    echo '{ "status" : "bad", "score" : "none"}';
} else {
    $secret   = 'your-secret-key';
    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
    );
    // use json_decode to extract json response
    $response = json_decode($response);

    if ($response->success === false) {
        //Do something with error
        echo '{ "status" : "bad", "score" : "none"}';
    }else if ($response->success==true && $response->score <= 0.5) {
        echo '{ "status" : "bad", "score" : "'.$response->score.'"}';
    }else {
        echo '{ "status" : "ok", "score" : "'.$response->score.'"}';
    }
}

On HTML

<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">

On js

$scope.grabCaptchaV3=function(){
    var params = {
                     method: 'POST',
                     url: 'api/recaptcha.php',
                     headers: {
                       'Content-Type': undefined
                     },
                     data:   {'g-recaptcha-response' : myCaptcha }
     }
     $http(params).then(function(result){ 
                console.log(result.data);
     }, function(response){
                console.log(response.statusText);
     }); 
}

Is there a date format to display the day of the week in java?

tl;dr

LocalDate.of( 2018 , Month.JANUARY , 23 )
         .format( DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US )  )

java.time

The modern approach uses the java.time classes.

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;

Note how we specify a Locale such as Locale.CANADA_FRENCH to determine the human language used to translate the name of the day.

DateTimeFormatter f = DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US ) ;
String output = ld.format( f ) ;

ISO 8601

By the way, you may be interested in the standard ISO 8601 week numbering scheme: yyyy-Www-d.

2018-W01-2

Week # 1 has the first Thursday of the calendar-year. Week starts on a Monday. A year has either 52 or 53 weeks. The last/first few days of a calendar-year may land in the next/previous week-based-year.

The single digit on the end is day-of-week, 1-7 for Monday-Sunday.

Add the ThreeTen-Extra library class to your project for the YearWeek class.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to change the font on the TextView?

First, the default is not Arial. The default is Droid Sans.

Second, to change to a different built-in font, use android:typeface in layout XML or setTypeface() in Java.

Third, there is no Helvetica font in Android. The built-in choices are Droid Sans (sans), Droid Sans Mono (monospace), and Droid Serif (serif). While you can bundle your own fonts with your application and use them via setTypeface(), bear in mind that font files are big and, in some cases, require licensing agreements (e.g., Helvetica, a Linotype font).

EDIT

The Android design language relies on traditional typographic tools such as scale, space, rhythm, and alignment with an underlying grid. Successful deployment of these tools is essential to help users quickly understand a screen of information. To support such use of typography, Ice Cream Sandwich introduced a new type family named Roboto, created specifically for the requirements of UI and high-resolution screens.

The current TextView framework offers Roboto in thin, light, regular and bold weights, along with an italic style for each weight. The framework also offers the Roboto Condensed variant in regular and bold weights, along with an italic style for each weight.

After ICS, android includes Roboto fonts style, Read more Roboto

EDIT 2

With the advent of Support Library 26, Android now supports custom fonts by default. You can insert new fonts in res/fonts which can be set to TextViews individually either in XML or programmatically. The default font for the whole application can also be changed by defining it styles.xml The android developer documentation has a clear guide on this here

Twitter Bootstrap Datepicker within modal window

try this

#ui-datepicker-div {
  z-index: 100000;
}

How to put spacing between floating divs?

You can do the following:

Assuming your container div has a class "yellow".

.yellow div {
    // Apply margin to every child in this container
    margin: 10px;
}

.yellow div:first-child, .yellow div:nth-child(3n+1) {
    // Remove the margin on the left side on the very first and then every fourth element (for example)
    margin-left: 0;
}

.yellow div:last-child {
    // Remove the right side margin on the last element
    margin-right: 0;
}

The number 3n+1 equals every fourth element outputted and will clearly only work if you know how many will be displayed in a row, but it should illustrate the example. More details regarding nth-child here.

Note: For :first-child to work in IE8 and earlier, a <!DOCTYPE> must be declared.

Note2: The :nth-child() selector is supported in all major browsers, except IE8 and earlier.

Cancel a vanilla ECMAScript 6 Promise chain

Try promise-abortable: https://www.npmjs.com/package/promise-abortable

$ npm install promise-abortable
import AbortablePromise from "promise-abortable";

const timeout = new AbortablePromise((resolve, reject, signal) => {
  setTimeout(reject, timeToLive, error);
  signal.onabort = resolve;
});

Promise.resolve(fn()).then(() => {
  timeout.abort();
});

Horizontal scroll on overflow of table

The solution for those who cannot or do not want to wrap the table in a div (e.g. if the HTML is generated from Markdown) but still want to have scrollbars:

_x000D_
_x000D_
table {_x000D_
  display: block;_x000D_
  max-width: -moz-fit-content;_x000D_
  max-width: fit-content;_x000D_
  margin: 0 auto;_x000D_
  overflow-x: auto;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Especially on mobile, a table can easily become wider than the viewport.</td>_x000D_
    <td>Using the right CSS, you can get scrollbars on the table without wrapping it.</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A centered table.</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Explanation: display: block; makes it possible to have scrollbars. By default (and unlike tables), blocks span the full width of the parent element. This can be prevented with max-width: fit-content;, which allows you to still horizontally center tables with less content using margin: 0 auto;. white-space: nowrap; is optional (but useful for this demonstration).

boto3 client NoRegionError: You must specify a region error only sometimes

One way or another you must tell boto3 in which region you wish the kms client to be created. This could be done explicitly using the region_name parameter as in:

kms = boto3.client('kms', region_name='us-west-2')

or you can have a default region associated with your profile in your ~/.aws/config file as in:

[default]
region=us-west-2

or you can use an environment variable as in:

export AWS_DEFAULT_REGION=us-west-2

but you do need to tell boto3 which region to use.

How do I test axios in Jest?

I could do that following the steps:

  1. Create a folder __mocks__/ (as pointed by @Januartha comment)
  2. Implement an axios.js mock file
  3. Use my implemented module on test

The mock will happen automatically

Example of the mock module:

module.exports = {
    get: jest.fn((url) => {
        if (url === '/something') {
            return Promise.resolve({
                data: 'data'
            });
        }
    }),
    post: jest.fn((url) => {
        if (url === '/something') {
            return Promise.resolve({
                data: 'data'
            });
        }
        if (url === '/something2') {
            return Promise.resolve({
                data: 'data2'
            });
        }
    }),
    create: jest.fn(function () {
        return this;
    })
};

Android - How to achieve setOnClickListener in Kotlin?

val saveButton:Button = findViewById(R.id.button_save)

saveButton.setOnClickListener{
// write code for click event
}

with view object
saveButton.setOnClickListener{
view -> // write code for click event
}

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

How to get the width and height of an android.widget.ImageView?

I think you can let the Android OS take care of this for you. Set the scale type on the ImageView to fitXY and the image it displays will be sized to fit the current size of the view.

<ImageView 
    android:layout_width="90px" 
    android:layout_height="60px"
    android:scaleType="fitXY" />

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

In my case, it was because of the proxy. A proxy was needed in the corporate network and TortoiseGit / Git does not seems to automatically get information from Windows internet settings. Setting up the proxy address solved the issue.

How to 'insert if not exists' in MySQL?

Something worth noting is that INSERT IGNORE will still increment the primary key whether the statement was a success or not just like a normal INSERT would.

This will cause gaps in your primary keys that might make a programmer mentally unstable. Or if your application is poorly designed and depends on perfect incremental primary keys, it might become a headache.

Look into innodb_autoinc_lock_mode = 0 (server setting, and comes with a slight performance hit), or use a SELECT first to make sure your query will not fail (which also comes with a performance hit and extra code).

Proper way to return JSON using node or Express

For the header half of the question, I'm gonna give a shout out to res.type here:

res.type('json')

is equivalent to

res.setHeader('Content-Type', 'application/json')

Source: express docs:

Sets the Content-Type HTTP header to the MIME type as determined by mime.lookup() for the specified type. If type contains the “/” character, then it sets the Content-Type to type.

How do I write a Windows batch script to copy the newest file from a directory?

The accepted answer gives an example of using the newest file in a command and then exiting. If you need to do this in a bat file with other complex operations you can use the following to store the file name of the newest file in a variable:

FOR /F "delims=|" %%I IN ('DIR "*.*" /B /O:D') DO SET NewestFile=%%I

Now you can reference %NewestFile% throughout the rest of your bat file.

For example here is what we use to get the latest version of a database .bak file from a directory, copy it to a server, and then restore the db:

:Variables
SET DatabaseBackupPath=\\virtualserver1\Database Backups

echo.
echo Restore WebServer Database
FOR /F "delims=|" %%I IN ('DIR "%DatabaseBackupPath%\WebServer\*.bak" /B /O:D') DO SET NewestFile=%%I
copy "%DatabaseBackupPath%\WebServer\%NewestFile%" "D:\"

sqlcmd -U <username> -P <password> -d master -Q ^
"RESTORE DATABASE [ExampleDatabaseName] ^
FROM  DISK = N'D:\%NewestFile%' ^
WITH  FILE = 1,  ^
MOVE N'Example_CS' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example.mdf',  ^
MOVE N'Example_CS_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example_1.LDF',  ^
NOUNLOAD,  STATS = 10"

CSS blur on background image but not on content

You could overlay one element above the blurred element like so

DEMO

div {
    position: absolute;
    left:0;
    top: 0;
}
p {
    position: absolute;
    left:0;
    top: 0;
}

Open-Source Examples of well-designed Android Applications?

All of the applications delivered with Android (Calendar, Contacts, Email, etc) are all open-source, but not part of the SDK. The source for those projects is here: https://android.googlesource.com/ (look at /platform/packages/apps). I've referred to those sources several times when I've used an application on my phone and wanted to see how a particular feature was implemented.

c++ parse int from string

You can use istringstream.

string s = "10";

// create an input stream with your string.
istringstream is(str);

int i;
// use is like an input stream
is >> i;

Difference between links and depends_on in docker_compose.yml

This answer is for docker-compose version 2 and it also works on version 3

You can still access the data when you use depends_on.

If you look at docker docs Docker Compose and Django, you still can access the database like this:

version: '2'
services:
  db:
    image: postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

What is the difference between links and depends_on?

links:

When you create a container for a database, for example:

docker run -d --name=test-mysql --env="MYSQL_ROOT_PASSWORD=mypassword" -P mysql

docker inspect d54cf8a0fb98 |grep HostPort

And you may find

"HostPort": "32777"

This means you can connect the database from your localhost port 32777 (3306 in container) but this port will change every time you restart or remove the container. So you can use links to make sure you will always connect to the database and don't have to know which port it is.

web:
  links:
   - db

depends_on:

I found a nice blog from Giorgio Ferraris Docker-compose.yml: from V1 to V2

When docker-compose executes V2 files, it will automatically build a network between all of the containers defined in the file, and every container will be immediately able to refer to the others just using the names defined in the docker-compose.yml file.

And

So we don’t need links anymore; links were used to start a network communication between our db container and our web-server container, but this is already done by docker-compose

Update

depends_on

Express dependency between services, which has two effects:

  • docker-compose up will start services in dependency order. In the following example, db and redis will be started before web.
  • docker-compose up SERVICE will automatically include SERVICE’s dependencies. In the following example, docker-compose up web will also create and start db and redis.

Simple example:

version: '2'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres

Note: depends_on will not wait for db and redis to be “ready” before starting web - only until they have been started. If you need to wait for a service to be ready, see Controlling startup order for more on this problem and strategies for solving it.

git pull error :error: remote ref is at but expected

Try this, it worked for me. In your terminal: git remote prune origin.

how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);

Mime type for WOFF fonts?

IIS automatically defined .ttf as application/octet-stream which seems to work fine and fontshop recommends .woff to be defined as application/octet-stream

How to flatten only some dimensions of a numpy array

Take a look at numpy.reshape .

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

How do I apply a perspective transform to a UIView?

As Ben said, you'll need to work with the UIView's layer, using a CATransform3D to perform the layer's rotation. The trick to get perspective working, as described here, is to directly access one of the matrix cells of the CATransform3D (m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:

Objective-C

UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;

Swift 5.0

if let myView = self.subviews.first {
    let layer = myView.layer
    var rotationAndPerspectiveTransform = CATransform3DIdentity
    rotationAndPerspectiveTransform.m34 = 1.0 / -500
    rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
    layer.transform = rotationAndPerspectiveTransform
}

which rebuilds the layer transform from scratch for each rotation.

A full example of this (with code) can be found here, where I've implemented touch-based rotation and scaling on a couple of CALayers, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.

The sublayerTransform you refer to in your response is a transform that is applied to the sublayers of your UIView's CALayer. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two CALayers contained within the one layer that I'm rotating.

upstream sent too big header while reading response header from upstream

upstream sent too big header while reading response header from upstream is nginx's generic way of saying "I don't like what I'm seeing"

  1. Your upstream server thread crashed
  2. The upstream server sent an invalid header back
  3. The Notice/Warnings sent back from STDERR overflowed their buffer and both it and STDOUT were closed

3: Look at the error logs above the message, is it streaming with logged lines preceding the message? PHP message: PHP Notice: Undefined index: Example snippet from a loop my log file:

2015/11/23 10:30:02 [error] 32451#0: *580927 FastCGI sent in stderr: "PHP message: PHP Notice:  Undefined index: Firstname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Lastname in /srv/www/classes/data_convert.php on line 1090
... // 20 lines of same
PHP message: PHP Notice:  Undefined index: Firstname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Lastname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undef
2015/11/23 10:30:02 [error] 32451#0: *580927 FastCGI sent in stderr: "ta_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Firstname

you can see in the 3rd line from the bottom that the buffer limit was hit, broke, and the next thread wrote in over it. Nginx then closed the connection and returned 502 to the client.

2: log all the headers sent per request, review them and make sure they conform to standards (nginx does not permit anything older than 24 hours to delete/expire a cookie, sending invalid content length because error messages were buffered before the content counted...). getallheaders function call can usually help out in abstracted code situations php get all headers

examples include:

<?php
//expire cookie
setcookie ( 'bookmark', '', strtotime('2012-01-01 00:00:00') );
// nginx will refuse this header response, too far past to accept
....
?>

and this:

<?php
header('Content-type: image/jpg');
?>

<?php   //a space was injected into the output above this line
header('Content-length: ' . filesize('image.jpg') );
echo file_get_contents('image.jpg');
// error! the response is now 1-byte longer than header!!
?>

1: verify, or make a script log, to ensure your thread is reaching the correct end point and not exiting before completion.

How to get option text value using AngularJS?

The best way is to use the ng-options directive on the select element.

Controller

function Ctrl($scope) {
  // sort options
  $scope.products = [{
    value: 'prod_1',
    label: 'Product 1'
  }, {
    value: 'prod_2',
    label: 'Product 2'
  }];   
}

HTML

<select ng-model="selected_product" 
        ng-options="product as product.label for product in products">           
</select>

This will bind the selected product object to the ng-model property - selected_product. After that you can use this:

<p>Ordered by: {{selected_product.label}}</p>

jsFiddle: http://jsfiddle.net/bmleite/2qfSB/

Dynamically load a JavaScript file

Here is a simple one with callback and IE support:

function loadScript(url, callback) {

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState) { //IE
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function () {
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {

     //jQuery loaded
     console.log('jquery loaded');

});

How do you run `apt-get` in a dockerfile behind a proxy?

As Tim Potter pointed out, setting proxy in dockerfile is horrible. When building the image, you add proxy for your corporate network but you may be deploying in cloud or a DMZ where there is no need for proxy or the proxy server is different.

Also, you cannot share your image with others outside your corporate n/w.

R Error in x$ed : $ operator is invalid for atomic vectors

You get this error, despite everything being in line, because of a conflict caused by one of the packages that are currently loaded in your R environment.

So, to solve this issue, detach all the packages that are not needed from the R environment. For example, when I had the same issue, I did the following:

detach(package:neuralnet)

bottom line: detach all the libraries no longer needed for execution... and the problem will be solved.

How to enable named/bind/DNS full logging?

Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

Also make sure you’re checking correct directory if your bind is chrooted.

How to fix "Headers already sent" error in PHP

Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session().

Example of Unpredictable Error:

 <?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();

//your page content

One more example:

<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();

//your page content

Conclusion: Do not output any character before calling session_start() or header() functions not even a white-space or new-line

When to use Common Table Expression (CTE)

Today we are going to learn about Common table expression that is a new feature which was introduced in SQL server 2005 and available in later versions as well.

Common table Expression :- Common table expression can be defined as a temporary result set or in other words its a substitute of views in SQL Server. Common table expression is only valid in the batch of statement where it was defined and cannot be used in other sessions.

Syntax of declaring CTE(Common table expression) :-

with [Name of CTE]
as
(
Body of common table expression
)

Lets take an example :-

CREATE TABLE Employee([EID] [int] IDENTITY(10,5) NOT NULL,[Name] [varchar](50) NULL)

insert into Employee(Name) values('Neeraj')
insert into Employee(Name) values('dheeraj')
insert into Employee(Name) values('shayam')
insert into Employee(Name) values('vikas')
insert into Employee(Name) values('raj')

CREATE TABLE DEPT(EID INT,DEPTNAME VARCHAR(100))
insert into dept values(10,'IT')
insert into dept values(15,'Finance')
insert into dept values(20,'Admin')
insert into dept values(25,'HR')
insert into dept values(10,'Payroll')

I have created two tables employee and Dept and inserted 5 rows in each table. Now I would like to join these tables and create a temporary result set to use it further.

With CTE_Example(EID,Name,DeptName)
as
(
select Employee.EID,Name,DeptName from Employee 
inner join DEPT on Employee.EID =DEPT.EID
)
select * from CTE_Example

Lets take each line of the statement one by one and understand.

To define CTE we write "with" clause, then we give a name to the table expression, here I have given name as "CTE_Example"

Then we write "As" and enclose our code in two brackets (---), we can join multiple tables in the enclosed brackets.

In the last line, I have used "Select * from CTE_Example" , we are referring the Common table expression in the last line of code, So we can say that Its like a view, where we are defining and using the view in a single batch and CTE is not stored in the database as an permanent object. But it behaves like a view. we can perform delete and update statement on CTE and that will have direct impact on the referenced table those are being used in CTE. Lets take an example to understand this fact.

With CTE_Example(EID,DeptName)
as
(
select EID,DeptName from DEPT 
)
delete from CTE_Example where EID=10 and DeptName ='Payroll'

In the above statement we are deleting a row from CTE_Example and it will delete the data from the referenced table "DEPT" that is being used in the CTE.

Catching multiple exception types in one catch block

As of PHP 8.0 you can use even cleaner way to catch your exceptions when you don't need to output the content of the error (from variable $e). However you must replace default Exception with Throwable.

try {
    /* something */
} catch (AError | BError) {
    handler1()
} catch (Throwable) {
    handler2()
}

Call to undefined function mysql_query() with Login

What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

jQuery bind to Paste Event, how to get the content of the paste

$(document).ready(function() {
    $("#editor").bind('paste', function (e){
        $(e.target).keyup(getInput);
    });

    function getInput(e){
        var inputText = $(e.target).html(); /*$(e.target).val();*/
        alert(inputText);
        $(e.target).unbind('keyup');
    }
});

Detect Android phone via Javascript / jQuery

How about this one-liner?

var isAndroid = /(android)/i.test(navigator.userAgent);

The i modifier is used to perform case-insensitive matching.


Technique taken from Cordova AdMob test project: https://github.com/floatinghotpot/cordova-admob-pro/wiki/00.-How-To-Use-with-PhoneGap-Build

Who sets response content-type in Spring MVC (@ResponseBody)

I'm using the CharacterEncodingFilter, configured in web.xml. Maybe that helps.

    <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

How to put sshpass command inside a bash script?

This worked for me:

#!/bin/bash

#Variables
FILELOCAL=/var/www/folder/$(date +'%Y%m%d_%H-%M-%S').csv    
SFTPHOSTNAME="myHost.com"
SFTPUSERNAME="myUser"
SFTPPASSWORD="myPass"
FOLDER="myFolderIfNeeded"
FILEREMOTE="fileNameRemote"

#SFTP CONNECTION
sshpass -p $SFTPPASSWORD sftp $SFTPUSERNAME@$SFTPHOSTNAME << !
    cd $FOLDER
    get $FILEREMOTE $FILELOCAL
    ls
   bye
!

Probably you have to install sshpass:

sudo apt-get install sshpass

What does EntityManager.flush do and why do I need to use it?

The EntityManager.flush() operation can be used the write all changes to the database before the transaction is committed. By default JPA does not normally write changes to the database until the transaction is committed. This is normally desirable as it avoids database access, resources and locks until required. It also allows database writes to be ordered, and batched for optimal database access, and to maintain integrity constraints and avoid deadlocks. This means that when you call persist, merge, or remove the database DML INSERT, UPDATE, DELETE is not executed, until commit, or until a flush is triggered.

Prompt for user input in PowerShell

Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)] above your mandatory parameters), but it's also the only option that you won't hate yourself for later.

More below:

[Console]::ReadLine is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.

Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.

You're trying to ask for parameters.

You should use the [Parameter(Mandatory=$true)] attribute, and correct typing, to ask for the parameters.

If you use this on a [SecureString], it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]) then it will become help text for the prompt.

How do I get my page title to have an icon?

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />

add this to your HTML Head. Of course the file "favicon.ico" has to exist. I think 16x16 or 32x32 pixel files are best.

python for increment inner loop

In python, for loops iterate over iterables, instead of incrementing a counter, so you have a couple choices. Using a skip flag like Artsiom recommended is one way to do it. Another option is to make a generator from your range and manually advance it by discarding an element using next().

iGen = (i for i in range(0, 6))
for i in iGen:
    print i
    if not i % 2:
        iGen.next()

But this isn't quite complete because next() might throw a StopIteration if it reaches the end of the range, so you have to add some logic to detect that and break out of the outer loop if that happens.

In the end, I'd probably go with aw4ully's solution with the while loops.

What should I do when 'svn cleanup' fails?

I've tried to do svn cleanup via the console and got an error like:

svn: E720002: Can't open file '..\.svn\pristine\40\40d53d69871f4ff622a3fbb939b6a79932dc7cd4.svn-base':
The system cannot find the file specified.

So I created this file manually (empty) and did svn cleanup again. This time it was done OK.

Parsing domain from a URL

I'm adding this answer late since this is the answer that pops up most on Google...

You can use PHP to...

$url = "www.google.co.uk";
$host = parse_url($url, PHP_URL_HOST);
// $host == "www.google.co.uk"

to grab the host but not the private domain to which the host refers. (Example www.google.co.uk is the host, but google.co.uk is the private domain)

To grab the private domain, you must need know the list of public suffixes to which one can register a private domain. This list happens to be curated by Mozilla at https://publicsuffix.org/

The below code works when an array of public suffixes has been created already. Simply call

$domain = get_private_domain("www.google.co.uk");

with the remaining code...

// find some way to parse the above list of public suffix
// then add them to a PHP array
$suffix = [... all valid public suffix ...];

function get_public_suffix($host) {
  $parts = split("\.", $host);
  while (count($parts) > 0) {
    if (is_public_suffix(join(".", $parts)))
      return join(".", $parts);

    array_shift($parts);
  }

  return false;
}

function is_public_suffix($host) {
  global $suffix;
  return isset($suffix[$host]);
}

function get_private_domain($host) {
  $public = get_public_suffix($host);
  $public_parts = split("\.", $public);
  $all_parts = split("\.", $host);

  $private = [];

  for ($x = 0; $x < count($public_parts); ++$x) 
    $private[] = array_pop($all_parts);

  if (count($all_parts) > 0)
    $private[] = array_pop($all_parts);

  return join(".", array_reverse($private));
}

How do I get this javascript to run every second?

You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.

var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);

//To abort the interval you can use this:
clearInterval(b);

Dynamic SQL results into temp table in SQL Stored procedure

INSERT INTO #TempTable
EXEC(@SelectStatement)

Round float to x decimals?

I feel compelled to provide a counterpoint to Ashwini Chaudhary's answer. Despite appearances, the two-argument form of the round function does not round a Python float to a given number of decimal places, and it's often not the solution you want, even when you think it is. Let me explain...

The ability to round a (Python) float to some number of decimal places is something that's frequently requested, but turns out to be rarely what's actually needed. The beguilingly simple answer round(x, number_of_places) is something of an attractive nuisance: it looks as though it does what you want, but thanks to the fact that Python floats are stored internally in binary, it's doing something rather subtler. Consider the following example:

>>> round(52.15, 1)
52.1

With a naive understanding of what round does, this looks wrong: surely it should be rounding up to 52.2 rather than down to 52.1? To understand why such behaviours can't be relied upon, you need to appreciate that while this looks like a simple decimal-to-decimal operation, it's far from simple.

So here's what's really happening in the example above. (deep breath) We're displaying a decimal representation of the nearest binary floating-point number to the nearest n-digits-after-the-point decimal number to a binary floating-point approximation of a numeric literal written in decimal. So to get from the original numeric literal to the displayed output, the underlying machinery has made four separate conversions between binary and decimal formats, two in each direction. Breaking it down (and with the usual disclaimers about assuming IEEE 754 binary64 format, round-ties-to-even rounding, and IEEE 754 rules):

  1. First the numeric literal 52.15 gets parsed and converted to a Python float. The actual number stored is 7339460017730355 * 2**-47, or 52.14999999999999857891452847979962825775146484375.

  2. Internally as the first step of the round operation, Python computes the closest 1-digit-after-the-point decimal string to the stored number. Since that stored number is a touch under the original value of 52.15, we end up rounding down and getting a string 52.1. This explains why we're getting 52.1 as the final output instead of 52.2.

  3. Then in the second step of the round operation, Python turns that string back into a float, getting the closest binary floating-point number to 52.1, which is now 7332423143312589 * 2**-47, or 52.10000000000000142108547152020037174224853515625.

  4. Finally, as part of Python's read-eval-print loop (REPL), the floating-point value is displayed (in decimal). That involves converting the binary value back to a decimal string, getting 52.1 as the final output.

In Python 2.7 and later, we have the pleasant situation that the two conversions in step 3 and 4 cancel each other out. That's due to Python's choice of repr implementation, which produces the shortest decimal value guaranteed to round correctly to the actual float. One consequence of that choice is that if you start with any (not too large, not too small) decimal literal with 15 or fewer significant digits then the corresponding float will be displayed showing those exact same digits:

>>> x = 15.34509809234
>>> x
15.34509809234

Unfortunately, this furthers the illusion that Python is storing values in decimal. Not so in Python 2.6, though! Here's the original example executed in Python 2.6:

>>> round(52.15, 1)
52.200000000000003

Not only do we round in the opposite direction, getting 52.2 instead of 52.1, but the displayed value doesn't even print as 52.2! This behaviour has caused numerous reports to the Python bug tracker along the lines of "round is broken!". But it's not round that's broken, it's user expectations. (Okay, okay, round is a little bit broken in Python 2.6, in that it doesn't use correct rounding.)

Short version: if you're using two-argument round, and you're expecting predictable behaviour from a binary approximation to a decimal round of a binary approximation to a decimal halfway case, you're asking for trouble.

So enough with the "two-argument round is bad" argument. What should you be using instead? There are a few possibilities, depending on what you're trying to do.

  • If you're rounding for display purposes, then you don't want a float result at all; you want a string. In that case the answer is to use string formatting:

    >>> format(66.66666666666, '.4f')
    '66.6667'
    >>> format(1.29578293, '.6f')
    '1.295783'
    

    Even then, one has to be aware of the internal binary representation in order not to be surprised by the behaviour of apparent decimal halfway cases.

    >>> format(52.15, '.1f')
    '52.1'
    
  • If you're operating in a context where it matters which direction decimal halfway cases are rounded (for example, in some financial contexts), you might want to represent your numbers using the Decimal type. Doing a decimal round on the Decimal type makes a lot more sense than on a binary type (equally, rounding to a fixed number of binary places makes perfect sense on a binary type). Moreover, the decimal module gives you better control of the rounding mode. In Python 3, round does the job directly. In Python 2, you need the quantize method.

    >>> Decimal('66.66666666666').quantize(Decimal('1e-4'))
    Decimal('66.6667')
    >>> Decimal('1.29578293').quantize(Decimal('1e-6'))
    Decimal('1.295783')
    
  • In rare cases, the two-argument version of round really is what you want: perhaps you're binning floats into bins of size 0.01, and you don't particularly care which way border cases go. However, these cases are rare, and it's difficult to justify the existence of the two-argument version of the round builtin based on those cases alone.

ASP.NET MVC JsonResult Date Format

Override the controllers Json/JsonResult to return JSON.Net:

This works a treat

Get MAC address using shell script

$ ip route show default | awk '/default/ {print $5}'

return: eth0 (my online interface)

$ cat /sys/class/net/$(ip route show default | awk '/default/ {print $5}')/address

return: ec:a8:6b:bd:55:05 (macaddress of the eth0, my online interface)

Terminal image

How can I view an object with an alert()

Depending on which property you are interested in:

alert(product.ProductName);
alert(product.UnitPrice);
alert(product.Stock);

Something better than .NET Reflector?

I am not sure what you really want here. If you want to see the .NET framework source code, you may try Netmassdownloader. It's free.

If you want to see any assembly's code (not just .NET), you can use ReSharper. Although it's not free.

C# ASP.NET MVC Return to Previous Page

I am assuming (please correct me if I am wrong) that you want to re-display the edit page if the edit fails and to do this you are using a redirect.

You may have more luck by just returning the view again rather than trying to redirect the user, this way you will be able to use the ModelState to output any errors too.

Edit:

Updated based on feedback. You can place the previous URL in the viewModel, add it to a hidden field then use it again in the action that saves the edits.

For instance:

public ActionResult Index()
{
    return View();
}

[HttpGet] // This isn't required
public ActionResult Edit(int id)
{
   // load object and return in view
   ViewModel viewModel = Load(id);

   // get the previous url and store it with view model
   viewModel.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;

   return View(viewModel);
}

[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
   // Attempt to save the posted object if it works, return index if not return the Edit view again

   bool success = Save(viewModel);
   if (success)
   {
       return Redirect(viewModel.PreviousUrl);
   }
   else
   {
      ModelState.AddModelError("There was an error");
      return View(viewModel);
   }
}

The BeginForm method for your view doesn't need to use this return URL either, you should be able to get away with:

@model ViewModel

@using (Html.BeginForm())
{
    ...
    <input type="hidden" name="PreviousUrl" value="@Model.PreviousUrl" />
}

Going back to your form action posting to an incorrect URL, this is because you are passing a URL as the 'id' parameter, so the routing automatically formats your URL with the return path.

This won't work because your form will be posting to an controller action that won't know how to save the edits. You need to post to your save action first, then handle the redirect within it.

When to use window.opener / window.parent / window.top

I think you need to add some context to your question. However, basic information about these things can be found here:

window.opener https://developer.mozilla.org/en-US/docs/Web/API/Window.opener

I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.

window.parent https://developer.mozilla.org/en-US/docs/Web/API/Window.parent

I've used this mostly when working with IFrames that need to communicate with the window object that contains them.

window.top https://developer.mozilla.org/en-US/docs/Web/API/Window.top

This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.

If you add some more detail to your question, I can supply other more relevant examples.

UPDATE: There are a few ways you can handle your situation.
You have the following structure:

  • Main Window
    • Dialog 1
      • Dialog 2 Opened By Dialog 1

When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.

So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:

childwindow.appMainWindow = window.opener

After making the assignment above, close dialog 1. Then from the code running inside dialog2, you should be able to use window.appMainWindow to reference the main window, window object.

Hope this helps.

How does one create an InputStream from a String?

Java 7+

It's possible to take advantage of the StandardCharsets JDK class:

String str=...
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(str).array());

.jar error - could not find or load main class

You can always run this:

java -cp HelloWorld.jar HelloWorld

-cp HelloWorld.jar adds the jar to the classpath, then HelloWorld runs the class you wrote.

To create a runnable jar with a main class with no package, add Class-Path: . to the manifest:

Manifest-Version: 1.0
Class-Path: .
Main-Class: HelloWorld

I would advise using a package to give your class its own namespace. E.g.

package com.stackoverflow.user.blrp;

public class HelloWorld {
    ...
}

How does one use glide to download an image into a bitmap?

UPDATE FOR NEW VERSION

Glide.with(context.applicationContext)
    .load(url)
    .listener(object : RequestListener<Drawable> {
        override fun onLoadFailed(
            e: GlideException?,
            model: Any?,
            target: Target<Drawable>?,
            isFirstResource: Boolean
        ): Boolean {
            listener?.onLoadFailed(e)
            return false
        }

        override fun onResourceReady(
            resource: Drawable?,
            model: Any?,
            target: com.bumptech.glide.request.target.Target<Drawable>?,
            dataSource: DataSource?,
            isFirstResource: Boolean
        ): Boolean {
            listener?.onLoadSuccess(resource)
            return false
        }

    })
    .into(this)

OLD ANSWER

@outlyer's answer is correct, but there're some changes in new Glide version

My version: 4.7.1

Code:

 Glide.with(context.applicationContext)
                .asBitmap()
                .load(iconUrl)
                .into(object : SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                    override fun onResourceReady(resource: Bitmap, transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?) {
                        callback.onReady(createMarkerIcon(resource, iconId))
                    }
                })

Note: this code run in UI Thread, thus you can use AsyncTask, Executor or somethings else for concurrency (like @outlyer's code) If you want to get original size, put Target.SIZE_ORIGINA as my code. Don't use -1, -1

Plotting a fast Fourier transform in Python

Just as a complement to the answers already given, I would like to point out that often it is important to play with the size of the bins for the FFT. It would make sense to test a bunch of values and pick the one that makes more sense to your application. Often, it is in the same magnitude of the number of samples. This was as assumed by most of the answers given, and produces great and reasonable results. In case one wants to explore that, here is my code version:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

fig = plt.figure(figsize=[14,4])
N = 600           # Number of samplepoints
Fs = 800.0
T = 1.0 / Fs      # N_samps*T (#samples x sample period) is the sample spacing.
N_fft = 80        # Number of bins (chooses granularity)
x = np.linspace(0, N*T, N)     # the interval
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)   # the signal

# removing the mean of the signal
mean_removed = np.ones_like(y)*np.mean(y)
y = y - mean_removed

# Compute the fft.
yf = scipy.fftpack.fft(y,n=N_fft)
xf = np.arange(0,Fs,Fs/N_fft)

##### Plot the fft #####
ax = plt.subplot(121)
pt, = ax.plot(xf,np.abs(yf), lw=2.0, c='b')
p = plt.Rectangle((Fs/2, 0), Fs/2, ax.get_ylim()[1], facecolor="grey", fill=True, alpha=0.75, hatch="/", zorder=3)
ax.add_patch(p)
ax.set_xlim((ax.get_xlim()[0],Fs))
ax.set_title('FFT', fontsize= 16, fontweight="bold")
ax.set_ylabel('FFT magnitude (power)')
ax.set_xlabel('Frequency (Hz)')
plt.legend((p,), ('mirrowed',))
ax.grid()

##### Close up on the graph of fft#######
# This is the same histogram above, but truncated at the max frequence + an offset. 
offset = 1    # just to help the visualization. Nothing important.
ax2 = fig.add_subplot(122)
ax2.plot(xf,np.abs(yf), lw=2.0, c='b')
ax2.set_xticks(xf)
ax2.set_xlim(-1,int(Fs/6)+offset)
ax2.set_title('FFT close-up', fontsize= 16, fontweight="bold")
ax2.set_ylabel('FFT magnitude (power) - log')
ax2.set_xlabel('Frequency (Hz)')
ax2.hold(True)
ax2.grid()

plt.yscale('log')

the output plots: enter image description here

How do I remove blank elements from an array?

In my project I use delete:

cities.delete("")

How to iterate over a std::map full of strings in C++

iter->first and iter->second are variables, you are attempting to call them as methods.

Reading/Writing a MS Word file in PHP

Office 2007 .docx should be possible since it's an XML standard. Word 2003 most likely requires COM to read, even with the standards now published by MS, since those standards are huge. I haven't seen many libraries written to match them yet.

Python: download a file from an FTP server

As several folks have noted, requests doesn't support FTP but Python has other libraries that do. If you want to keep using the requests library, there is a requests-ftp package that adds FTP capability to requests. I've used this library a little and it does work. The docs are full of warnings about code quality though. As of 0.2.0 the docs say "This library was cowboyed together in about 4 hours of total work, has no tests, and relies on a few ugly hacks".

import requests, requests_ftp
requests_ftp.monkeypatch_session()
response = requests.get('ftp://example.com/foo.txt')

How to compile C program on command line using MinGW?

First:

Add your minGW's bin folder directory ( ex: C\mingw64\bin ) in System variables => Path. visual example


Compile:

.c: gcc filename.c -o desire

.cpp: g++ filename.cpp -o desire


Run:

desire/ or ./desire

Use "ENTER" key on softkeyboard instead of clicking button

You do it by setting a OnKeyListener on your EditText.

Here is a sample from my own code. I have an EditText named addCourseText, which will call the function addCourseFromTextBox when either the enter key or the d-pad is clicked.

addCourseText = (EditText) findViewById(R.id.clEtAddCourse);
addCourseText.setOnKeyListener(new OnKeyListener()
{
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
        {
            switch (keyCode)
            {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    addCourseFromTextBox();
                    return true;
                default:
                    break;
            }
        }
        return false;
    }
});

Check if an array item is set in JS

This worked for me

if (assoc_pagine[var] != undefined) {

instead this

if (assoc_pagine[var] != "undefined") {

String to byte array in php

You could try this:

$in_str = 'this is a test';
$hex_ary = array();
foreach (str_split($in_str) as $chr) {
    $hex_ary[] = sprintf("%02X", ord($chr));
}
echo implode(' ',$hex_ary);

Check if passed argument is file or directory in Bash

At least write the code without the bushy tree:

#!/bin/bash

PASSED=$1

if   [ -d "${PASSED}" ]
then echo "${PASSED} is a directory";
elif [ -f "${PASSED}" ]
then echo "${PASSED} is a file";
else echo "${PASSED} is not valid";
     exit 1
fi

When I put that into a file "xx.sh" and create a file "xx sh", and run it, I get:

$ cp /dev/null "xx sh"
$ for file in . xx*; do sh "$file"; done
. is a directory
xx sh is a file
xx.sh is a file
$

Given that you are having problems, you should debug the script by adding:

ls -l "${PASSED}"

This will show you what ls thinks about the names you pass the script.

node.js http 'get' request with query string parameters

If you ever need to send GET request to an IP as well as a Domain (Other answers did not mention you can specify a port variable), you can make use of this function:

function getCode(host, port, path, queryString) {
    console.log("(" + host + ":" + port + path + ")" + "Running httpHelper.getCode()")

    // Construct url and query string
    const requestUrl = url.parse(url.format({
        protocol: 'http',
        hostname: host,
        pathname: path,
        port: port,
        query: queryString
    }));

    console.log("(" + host + path + ")" + "Sending GET request")
    // Send request
    console.log(url.format(requestUrl))
    http.get(url.format(requestUrl), (resp) => {
        let data = '';

        // A chunk of data has been received.
        resp.on('data', (chunk) => {
            console.log("GET chunk: " + chunk);
            data += chunk;
        });

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            console.log("GET end of response: " + data);
        });

    }).on("error", (err) => {
        console.log("GET Error: " + err);
    });
}

Don't miss requiring modules at the top of your file:

http = require("http");
url = require('url')

Also bare in mind that you may use https module for communicating over secured network.

How to prevent buttons from submitting forms

Here's a simple approach:

$('.mybutton').click(function(){

    /* Perform some button action ... */
    alert("I don't like it when you press my button!");

    /* Then, the most important part ... */
    return false;

});

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

What is the return type of the round() method in the snippet?

If this is the Math.round() method, it returns a Long when the input param is Double.

So, you will have to cast the return value:

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

Why XML-Serializable class need a parameterless constructor

First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?

I think there is a workaround to make constructor private.

conflicting types error when compiling c program using gcc

If you don't declare a function and it only appears after being called, it is automatically assumed to be int, so in your case, you didn't declare

void my_print (char *);
void my_print2 (char *);

before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *); and int my_print2 (char *); and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types.

As Brian suggested, declare those two methods before main.

Print string and variable contents on the same line in R

As other users said, cat() is probably the best option.

@krlmlr suggested using sprintf() and it's currently the third ranked answer. sprintf() is not a good idea. From R documentation:

The format string is passed down the OS's sprintf function, and incorrect formats can cause the latter to crash the R process.

There is no good reason to use sprintf() over cat or other options.

Find unique lines

uniq has the option you need:

   -u, --unique
          only print unique lines
$ cat file.txt
1
1
2
3
5
5
7
7
$ uniq -u file.txt
2
3

How to hide console window in python?

In linux, just run it, no problem. In Windows, you want to use the pythonw executable.

Update

Okay, if I understand the question in the comments, you're asking how to make the command window in which you've started the bot from the command line go away afterwards?

  • UNIX (Linux)

$ nohup mypythonprog &

  • Windows

C:/> start pythonw mypythonprog

I think that's right. In any case, now you can close the terminal.

How to send and receive JSON data from a restful webservice using Jersey API

The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.0</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>   


    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.25</version>
    </dependency>

How to find Google's IP address?

If all you are trying to do is find the IP address that corresponds to a domain name, like google.com, this is very easy on every machine connected to the Internet.

Simply run the ping command from any command prompt. Typing something like

ping google.com

will give you (among other things) that information.

What is the MySQL VARCHAR max size?

you can also use MEDIUMBLOB/LONGBLOB or MEDIUMTEXT/LONGTEXT

A BLOB type in MySQL can store up to 65,534 bytes, if you try to store more than this much data MySQL will truncate the data. MEDIUMBLOB can store up to 16,777,213 bytes, and LONGBLOB can store up to 4,294,967,292 bytes.

Android charting libraries

You can use MPAndroidChart.

It's native, free, easy to use, fast and reliable.

Core features, benefits:

  • LineChart, BarChart (vertical, horizontal, stacked, grouped), PieChart, ScatterChart, CandleStickChart (for financial data), RadarChart (spider web chart), BubbleChart
  • Combined Charts (e.g. lines and bars in one)
  • Scaling on both axes (with touch-gesture, axes separately or pinch-zoom)
  • Dragging / Panning (with touch-gesture)
  • Separate (dual) y-axes
  • Highlighting values (with customizeable popup-views)
  • Save chart to SD-Card (as image)
  • Predefined color templates
  • Legends (generated automatically, customizeable)
  • Customizeable Axes (both x- and y-axis)
  • Animations (build up animations, on both x- and y-axis)
  • Limit lines (providing additional information, maximums, ...)
  • Listeners for touch, gesture & selection callbacks
  • Fully customizeable (paints, typefaces, legends, colors, background, dashed lines, ...)
  • Realm.io mobile database support via MPAndroidChart-Realm library
  • Smooth rendering for up to 10.000 data points in Line- and BarChart
  • Lightweight (method count ~1.4K)
  • Available as .jar file (only 500kb in size)
  • Available as gradle dependency and via maven
  • Good documentation
  • Example Project (code for demo-application)
  • Google-PlayStore Demo Application
  • Widely used, great support on both GitHub and stackoverflow - mpandroidchart
  • Also available for iOS: Charts (API works the same way)
  • Also available for Xamarin: MPAndroidChart.Xamarin

Drawbacks:

Disclaimer: I am the developer of this library.

What's wrong with foreign keys?

I'll echo what Dmitriy said, but adding on a point.

I worked on a batch billing system that needed to insert large sets of rows on 30+ tables. We weren't allowed to do a data pump (Oracle) so we had to do bulk inserts. Those tables had foreign keys on them, but we had already ensured that they were not breaking any relationships.

Before insert, we disable the foreign key constraints so that Oracle doesn't take forever doing the inserts. After the insert is successful, we re-enable the constraints.

PS: In a large database with many foreign keys and child row data for a single record, sometimes foreign keys can be bad, and you may want to disallow cascading deletes. For us in the billing system, it would take too long and be too taxing on the database if we did cascading deletes, so we just mark the record as bad with a field on the main driver (parent) table.

Simple timeout in java

Use this line of code:

Thread.sleep(1000);

It will sleep for 1 second.

Text editor to open big (giant, huge, large) text files

Tips and tricks

less

Why are you using editors to just look at a (large) file?

Under *nix or Cygwin, just use less. (There is a famous saying – "less is more, more or less" – because "less" replaced the earlier Unix command "more", with the addition that you could scroll back up.) Searching and navigating under less is very similar to Vim, but there is no swap file and little RAM used.

There is a Win32 port of GNU less. See the "less" section of the answer above.

Perl

Perl is good for quick scripts, and its .. (range flip-flop) operator makes for a nice selection mechanism to limit the crud you have to wade through.

For example:

$ perl -n -e 'print if ( 1000000 .. 2000000)' humongo.txt | less

This will extract everything from line 1 million to line 2 million, and allow you to sift the output manually in less.

Another example:

$ perl -n -e 'print if ( /regex one/ .. /regex two/)' humongo.txt | less

This starts printing when the "regular expression one" finds something, and stops when the "regular expression two" find the end of an interesting block. It may find multiple blocks. Sift the output...

logparser

This is another useful tool you can use. To quote the Wikipedia article:

logparser is a flexible command line utility that was initially written by Gabriele Giuseppini, a Microsoft employee, to automate tests for IIS logging. It was intended for use with the Windows operating system, and was included with the IIS 6.0 Resource Kit Tools. The default behavior of logparser works like a "data processing pipeline", by taking an SQL expression on the command line, and outputting the lines containing matches for the SQL expression.

Microsoft describes Logparser as a powerful, versatile tool that provides universal query access to text-based data such as log files, XML files and CSV files, as well as key data sources on the Windows operating system such as the Event Log, the Registry, the file system, and Active Directory. The results of the input query can be custom-formatted in text based output, or they can be persisted to more specialty targets like SQL, SYSLOG, or a chart.

Example usage:

C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line > 1000 and line < 2000"
C:\>logparser.exe -i:textline -o:tsv "select Index, Text from 'c:\path\to\file.log' where line like '%pattern%'"

The relativity of sizes

100 MB isn't too big. 3 GB is getting kind of big. I used to work at a print & mail facility that created about 2% of U.S. first class mail. One of the systems for which I was the tech lead accounted for about 15+% of the pieces of mail. We had some big files to debug here and there.

And more...

Feel free to add more tools and information here. This answer is community wiki for a reason! We all need more advice on dealing with large amounts of data...

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

SQL Server equivalent to MySQL enum data type?

Found this interesting approach when I wanted to implement enums in SQL Server.

The approach mentioned below in the link is quite compelling, considering all your database enum needs could be satisfied with 2 central tables.

http://blog.sqlauthority.com/2010/03/22/sql-server-enumerations-in-relational-database-best-practice/

Reason: no suitable image found

I just cleaned the project and Clean Build Folder by alt Product menu

How to print strings with line breaks in java

private static final String mText = "SHOP MA" + "\n" +
        + "----------------------------" + "\n" +
        + "Pannampitiya" + newline +
        + "09-10-2012 harsha  no: 001" + "\n" +
        + "No  Item  Qty  Price  Amount" + "\n" +
        + "1 Bread 1 50.00  50.00" + "\n" +
        + "____________________________" + "\n";

This should work.

Rock, Paper, Scissors Game Java

You could insert something like this:

personPlay = "B";

while (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S")) {

    //Get player's play from input-- note that this is 
    // stored as a string 
    System.out.println("Enter your play: "); 
    personPlay = scan.next();

    //Make player's play uppercase for ease of comparison 
    personPlay = personPlay.toUpperCase();

    if (!personPlay.equals("R") && !personPlay.equals("P") && !personPlay.equals("S"))
        System.out.println("Invalid move. Try again.");

}

Split Strings into words with multiple word boundary delimiters

Heres my take on it....

def split_string(source,splitlist):
    splits = frozenset(splitlist)
    l = []
    s1 = ""
    for c in source:
        if c in splits:
            if s1:
                l.append(s1)
                s1 = ""
        else:
            print s1
            s1 = s1 + c
    if s1:
        l.append(s1)
    return l

>>>out = split_string("First Name,Last Name,Street Address,City,State,Zip Code",",")
>>>print out
>>>['First Name', 'Last Name', 'Street Address', 'City', 'State', 'Zip Code']

How do I add a auto_increment primary key in SQL Server database?

In SQL Server 2008:

  • Right click on table
  • Go to design
  • Select numeric datatype
  • Add Name to the new column
  • Make Identity Specification to 'YES'

How do I check if a number is positive or negative in C#?

For a 32-bit signed integer, such as System.Int32, aka int in C#:

bool isNegative = (num & (1 << 31)) != 0;

Enable CORS in Web API 2

 var cors = new EnableCorsAttribute("*","*","*");
 config.EnableCors(cors);

 var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);

VB.NET: how to prevent user input in a ComboBox

Using 'DropDownList' for the 'DropDownStyle' property of the combo box doesn't work as it changes the look and feel of the combo box. I am using Visual Studio 2019 Community Edition.

Using 'e.Handled = True' also doesn't work either as it still allows user input. Using 'False' for the 'Enabled' property of the combo box also doesn't work too because it stops the user from being able to use the combo box.

All of the "solutions" that have been proposed above are complete rubbish. What really works is this following code which restricts user input to certain keys such as up / down (for navigating through the list of all available choices in the combo box), suppressing all other key inputs:-

Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles 
  ComboBox1.KeyDown
    REM The following code is executed whenever the user has pressed
    REM a key.  Added on Wednesday 1st January 2020.

    REM Determine what key the user has pressed.  Added on Wednesday
    REM 1st January 2020.
    Select Case e.KeyCode
        Case Keys.Down, Keys.Up
            REM This section is for whenever the user has pressed either
            REM the arrow down key or arrow up key.  Added on Wednesday
            REM 1st January 2020.

        Case Else
            REM This section is for whenever the user has pressed any
            REM other key.  Added on Wednesday 1st January 2020.

            REM Cancelling the key that the user has pressed.  Added on
            REM Wednesday 1st January 2020.
            e.SuppressKeyPress = True

    End Select

End Sub

Append data to a POST NSURLRequest

If you don't wish to use 3rd party classes then the following is how you set the post body...

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                             delegate:self];

Simply append your key/value pair to the post string

Select random lines from a file

seq 1 100 | python3 -c 'print(__import__("random").choice(__import__("sys").stdin.readlines()))'

AngularJS - Any way for $http.post to send request parameters instead of JSON?

You can also solve this problem without changing code in server, changing header in $http.post call and use $_POST the regular way. Explained here: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/

Difference between e.target and e.currentTarget

  • e.target is element, which you f.e. click
  • e.currentTarget is element with added event listener.

If you click on child element of button, its better to use currentTarget to detect buttons attributes, in CH its sometimes problem to use e.target.

Better way of getting time in milliseconds in javascript?

This is a very old question - but still for reference if others are looking at it - requestAnimationFrame() is the right way to handle animation in modern browsers:

UPDATE: The mozilla link shows how to do this - I didn't feel like repeating the text behind the link ;)

openpyxl - adjust column width size

Since in openpyxl 2.6.1, it requires the column letter, not the column number, when setting the width.

 for column in sheet.columns:
    length = max(len(str(cell.value)) for cell in column)
    length = length if length <= 16 else 16
    sheet.column_dimensions[column[0].column_letter].width = length

Datatables: Cannot read property 'mData' of undefined

One more reason why this happens is because of the columns parameter in the DataTable initialization.

The number of columns has to match with headers

"columns" : [ {
                "width" : "30%"
            }, {
                "width" : "15%"
            }, {
                "width" : "15%"
            }, {
                "width" : "30%"
            } ]

I had 7 columns

<th>Full Name</th>
<th>Phone Number</th>
<th>Vehicle</th>
<th>Home Location</th>
<th>Tags</th>
<th>Current Location</th>
<th>Serving Route</th>

What does %5B and %5D in POST requests stand for?

The data would probably have been posted originally from a web form looking a bit like this (but probably much more complicated):

<form action="http://example.com" method="post">

  User login    <input name="user[login]"    /><br />
  User password <input name="user[password]" /><br />

  <input type="submit" />
</form>

If the method were "get" instead of "post", clicking the submit button would take you to a URL looking a bit like this:

http://example.com/?user%5Blogin%5D=username&user%5Bpassword%5D=123456

or:

http://example.com/?user[login]=username&user[password]=123456

The web server on the other end will likely take the user[login] and user[password] parameters, and make them into a user object with login and password fields containing those values.

How to _really_ programmatically change primary and accent color in Android Lollipop?

You can use Theme.applyStyle to modify your theme at runtime by applying another style to it.

Let's say you have these style definitions:

<style name="DefaultTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/md_lime_500</item>
    <item name="colorPrimaryDark">@color/md_lime_700</item>
    <item name="colorAccent">@color/md_amber_A400</item>
</style>

<style name="OverlayPrimaryColorRed">
    <item name="colorPrimary">@color/md_red_500</item>
    <item name="colorPrimaryDark">@color/md_red_700</item>
</style>

<style name="OverlayPrimaryColorGreen">
    <item name="colorPrimary">@color/md_green_500</item>
    <item name="colorPrimaryDark">@color/md_green_700</item>
</style>

<style name="OverlayPrimaryColorBlue">
    <item name="colorPrimary">@color/md_blue_500</item>
    <item name="colorPrimaryDark">@color/md_blue_700</item>
</style>

Now you can patch your theme at runtime like so:

getTheme().applyStyle(R.style.OverlayPrimaryColorGreen, true);

The method applyStylehas to be called before the layout gets inflated! So unless you load the view manually you should apply styles to the theme before calling setContentView in your activity.

Of course this cannot be used to specify an arbitrary color, i.e. one out of 16 million (2563) colors. But if you write a small program that generates the style definitions and the Java code for you then something like one out of 512 (83) should be possible.

What makes this interesting is that you can use different style overlays for different aspects of your theme. Just add a few overlay definitions for colorAccent for example. Now you can combine different values for primary color and accent color almost arbitrarily.

You should make sure that your overlay theme definitions don't accidentally inherit a bunch of style definitions from a parent style definition. For example a style called AppTheme.OverlayRed implicitly inherits all styles defined in AppTheme and all these definitions will also be applied when you patch the master theme. So either avoid dots in the overlay theme names or use something like Overlay.Red and define Overlay as an empty style.

How do you append to a file?

I always do this,

f = open('filename.txt', 'a')
f.write("stuff")
f.close()

It's simple, but very useful.

Elegant way to report missing values in a data.frame

ExPanDaR’s package function prepare_missing_values_graph can be used to explore panel data:

enter image description here

The system cannot find the file specified in java

In your IDE right click on the file you want to read and choose "copy path" then paste it into your code.

Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"

Javascript parse float is ignoring the decimals after my comma

This is "By Design". The parseFloat function will only consider the parts of the string up until in reaches a non +, -, number, exponent or decimal point. Once it sees the comma it stops looking and only considers the "75" portion.

To fix this convert the commas to decimal points.

var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));

Add custom buttons on Slick Carousel

$('.slider').slick({
  slidesToShow: 3,
  slidesToScroll: 1,
  speed: 500,
  dots: true,
  arrows: true,
  centerMode: false,
  focusOnSelect: false,
  autoplay: false,
  autoplaySpeed: 2000,
  slide: 'div',  
    nextArrow: '<button id="next">Next >',
        prevArrow: '<button id="previous">previous >',  
    
  
});

Result : enter image description here

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

It can be resolved as follows:

  1. Go to Project properties.

  2. Then 'Java Compiler' -> Check the box ('Enable project specific settings')

  3. Change the compiler compliance level to '5.0' & click ok.

Do rebuild. It will be resolved.

Also, click the checkbox for "Use default compliance settings".

Case Function Equivalent in Excel

Try this;

=IF(B1>=0, B1, OFFSET($X$1, MATCH(B1, $X:$X, Z) - 1, Y)

WHERE
X = The columns you are indexing into
Y = The number of columns to the left (-Y) or right (Y) of the indexed column to get the value you are looking for
Z = 0 if exact-match (if you want to handle errors)

Change UITextField and UITextView Cursor / Caret Color

With iOS7 you can simply change tintColor of the textField

How to compare two JSON objects with the same elements in a different order equal?

You can write your own equals function:

  • dicts are equal if: 1) all keys are equal, 2) all values are equal
  • lists are equal if: all items are equal and in the same order
  • primitives are equal if a == b

Because you're dealing with json, you'll have standard python types: dict, list, etc., so you can do hard type checking if type(obj) == 'dict':, etc.

Rough example (not tested):

def json_equals(jsonA, jsonB):
    if type(jsonA) != type(jsonB):
        # not equal
        return False
    if type(jsonA) == dict:
        if len(jsonA) != len(jsonB):
            return False
        for keyA in jsonA:
            if keyA not in jsonB or not json_equal(jsonA[keyA], jsonB[keyA]):
                return False
    elif type(jsonA) == list:
        if len(jsonA) != len(jsonB):
            return False
        for itemA, itemB in zip(jsonA, jsonB):
            if not json_equal(itemA, itemB):
                return False
    else:
        return jsonA == jsonB

How to advance to the next form input when the current input has a value?

Needed to emulate the tab functionality a while ago, and now I've released it as a library that uses .

EmulateTab: A jQuery plugin to emulate tabbing between elements on a page.

You can see how it works in the demo.

if (myTextHasBeenFilledWithText) {
  // Tab to the next input after #my-text-input
  $("#my-text-input").emulateTab();
}

Matplotlib-Animation "No MovieWriters Available"

If you are using Ubuntu 14.04 ffmpeg is not available. You can install it by using the instructions directly from https://www.ffmpeg.org/download.html.

In short you will have to:

sudo add-apt-repository ppa:mc3man/trusty-media
sudo apt-get update
sudo apt-get install ffmpeg gstreamer0.10-ffmpeg

If this does not work maybe try using sudo apt-get dist-upgrade but this may broke things in your system.

HTML5 phone number validation with pattern

How about this? /(7|8|9)\d{9}/

It starts by either looking for 7 or 8 or 9, and then followed by 9 digits.

How can I format a String number to have commas and round?

I've created my own formatting utility. Which is extremely fast at processing the formatting along with giving you many features :)

It supports:

  • Comma Formatting E.g. 1234567 becomes 1,234,567.
  • Prefixing with "Thousand(K),Million(M),Billion(B),Trillion(T)".
  • Precision of 0 through 15.
  • Precision re-sizing (Means if you want 6 digit precision, but only have 3 available digits it forces it to 3).
  • Prefix lowering (Means if the prefix you choose is too large it lowers it to a more suitable prefix).

The code can be found here. You call it like this:

public static void main(String[])
{
   int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
   String formatted = ValueFormat.format(1234567, settings);
}

I should also point out this doesn't handle decimal support, but is very useful for integer values. The above example would show "1.23M" as the output. I could probably add decimal support maybe, but didn't see too much use for it since then I might as well merge this into a BigInteger type of class that handles compressed char[] arrays for math computations.

Cursor adapter and sqlite example

Really simple example.

Here is a really simple, but very effective, example. Once you have the basics down you can easily build off of it.

There are two main parts to using a Cursor Adapter with SQLite:

  1. Create a proper Cursor from the Database.

  2. Create a custom Cursor Adapter that takes the Cursor data from the database and pairs it with the View you intend to represent the data with.

1. Create a proper Cursor from the Database.

In your Activity:

SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper( 
        context, DATABASE_NAME, null, DATABASE_VERSION);

SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase();

String query = "SELECT * FROM clients ORDER BY company_name ASC"; // No trailing ';'

Cursor cursor = sqLiteDatabase.rawQuery(query, null); 

ClientCursorAdapter adapter = new ClientCursorAdapter(
        this, R.layout.clients_listview_row, cursor, 0 );

this.setListAdapter(adapter);

2. Create a Custom Cursor Adapter.

Note: Extending from ResourceCursorAdapter assumes you use XML to create your views.

public class ClientCursorAdapter extends ResourceCursorAdapter {

    public ClientCursorAdapter(Context context, int layout, Cursor cursor, int flags) {
        super(context, layout, cursor, flags);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView name = (TextView) view.findViewById(R.id.name);
        name.setText(cursor.getString(cursor.getColumnIndex("name")));

        TextView phone = (TextView) view.findViewById(R.id.phone);
        phone.setText(cursor.getString(cursor.getColumnIndex("phone")));
    }
}

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

From gsitgithub/find-currupt-jars.txt, the following command lists all the corrupted jar files in the repository:

find  /home/me/.m2/repository/ -name "*jar" | xargs -L 1 zip -T | grep error | grep invalid

You can delete the corrupted jar files, and recompile the project.

Example output:

warning [/cygdrive/J/repo/net/java/dev/jna/jna/4.1.0/jna-4.1.0.jar]:  98304 extra bytes at beginning or within zipfile
  (attempting to process anyway)
file #1:  bad zipfile offset (local header sig):  98304
  (attempting to re-compensate)
zip error: Zip file invalid, could not spawn unzip, or wrong unzip (original files unmodified)

How to convert Java String to JSON Object

You are passing into the JSONObject constructor an instance of a StringBuilder class.

This is using the JSONObject(Object) constructor, not the JSONObject(String) one.

Your code should be:

JSONObject jsonObj = new JSONObject(jsonString.toString());

How can I use a search engine to search for special characters?

duckduckgo.com doesn't ignore special characters, at least if the whole string is between ""

https://duckduckgo.com/?q=%22*222%23%22

Pass a variable to a PHP script running from the command line

Just pass it as parameters as follows:

php test.php one two three

And inside file test.php:

<?php
    if(isset($argv))
    {
        foreach ($argv as $arg)
        {
            echo $arg;
            echo "\r\n";
        }
    }
?>

Do you (really) write exception safe code?

Your question makes an assertion, that "Writing exception-safe code is very hard". I will answer your questions first, and then, answer the hidden question behind them.

Answering questions

Do you really write exception safe code?

Of course, I do.

This is the reason Java lost a lot of its appeal to me as a C++ programmer (lack of RAII semantics), but I am digressing: This is a C++ question.

It is, in fact, necessary when you need to work with STL or Boost code. For example, C++ threads (boost::thread or std::thread) will throw an exception to exit gracefully.

Are you sure your last "production ready" code is exception safe?

Can you even be sure, that it is?

Writing exception-safe code is like writing bug-free code.

You can't be 100% sure your code is exception safe. But then, you strive for it, using well-known patterns, and avoiding well-known anti-patterns.

Do you know and/or actually use alternatives that work?

There are no viable alternatives in C++ (i.e. you'll need to revert back to C and avoid C++ libraries, as well as external surprises like Windows SEH).

Writing exception safe code

To write exception safe code, you must know first what level of exception safety each instruction you write is.

For example, a new can throw an exception, but assigning a built-in (e.g. an int, or a pointer) won't fail. A swap will never fail (don't ever write a throwing swap), a std::list::push_back can throw...

Exception guarantee

The first thing to understand is that you must be able to evaluate the exception guarantee offered by all of your functions:

  1. none: Your code should never offer that. This code will leak everything, and break down at the very first exception thrown.
  2. basic: This is the guarantee you must at the very least offer, that is, if an exception is thrown, no resources are leaked, and all objects are still whole
  3. strong: The processing will either succeed, or throw an exception, but if it throws, then the data will be in the same state as if the processing had not started at all (this gives a transactional power to C++)
  4. nothrow/nofail: The processing will succeed.

Example of code

The following code seems like correct C++, but in truth, offers the "none" guarantee, and thus, it is not correct:

void doSomething(T & t)
{
   if(std::numeric_limits<int>::max() > t.integer)  // 1.   nothrow/nofail
      t.integer += 1 ;                              // 1'.  nothrow/nofail
   X * x = new X() ;                // 2. basic : can throw with new and X constructor
   t.list.push_back(x) ;            // 3. strong : can throw
   x->doSomethingThatCanThrow() ;   // 4. basic : can throw
}

I write all my code with this kind of analysis in mind.

The lowest guarantee offered is basic, but then, the ordering of each instruction makes the whole function "none", because if 3. throws, x will leak.

The first thing to do would be to make the function "basic", that is putting x in a smart pointer until it is safely owned by the list:

void doSomething(T & t)
{
   if(std::numeric_limits<int>::max() > t.integer)  // 1.   nothrow/nofail
      t.integer += 1 ;                              // 1'.  nothrow/nofail
   std::auto_ptr<X> x(new X()) ;    // 2.  basic : can throw with new and X constructor
   X * px = x.get() ;               // 2'. nothrow/nofail
   t.list.push_back(px) ;           // 3.  strong : can throw
   x.release() ;                    // 3'. nothrow/nofail
   px->doSomethingThatCanThrow() ;  // 4.  basic : can throw
}

Now, our code offers a "basic" guarantee. Nothing will leak, and all objects will be in a correct state. But we could offer more, that is, the strong guarantee. This is where it can become costly, and this is why not all C++ code is strong. Let's try it:

void doSomething(T & t)
{
   // we create "x"
   std::auto_ptr<X> x(new X()) ;    // 1. basic : can throw with new and X constructor
   X * px = x.get() ;               // 2. nothrow/nofail
   px->doSomethingThatCanThrow() ;  // 3. basic : can throw

   // we copy the original container to avoid changing it
   T t2(t) ;                        // 4. strong : can throw with T copy-constructor

   // we put "x" in the copied container
   t2.list.push_back(px) ;          // 5. strong : can throw
   x.release() ;                    // 6. nothrow/nofail
   if(std::numeric_limits<int>::max() > t2.integer)  // 7.   nothrow/nofail
      t2.integer += 1 ;                              // 7'.  nothrow/nofail

   // we swap both containers
   t.swap(t2) ;                     // 8. nothrow/nofail
}

We re-ordered the operations, first creating and setting X to its right value. If any operation fails, then t is not modified, so, operation 1 to 3 can be considered "strong": If something throws, t is not modified, and X will not leak because it's owned by the smart pointer.

Then, we create a copy t2 of t, and work on this copy from operation 4 to 7. If something throws, t2 is modified, but then, t is still the original. We still offer the strong guarantee.

Then, we swap t and t2. Swap operations should be nothrow in C++, so let's hope the swap you wrote for T is nothrow (if it isn't, rewrite it so it is nothrow).

So, if we reach the end of the function, everything succeeded (No need of a return type) and t has its excepted value. If it fails, then t has still its original value.

Now, offering the strong guarantee could be quite costly, so don't strive to offer the strong guarantee to all your code, but if you can do it without a cost (and C++ inlining and other optimization could make all the code above costless), then do it. The function user will thank you for it.

Conclusion

It takes some habit to write exception-safe code. You'll need to evaluate the guarantee offered by each instruction you'll use, and then, you'll need to evaluate the guarantee offered by a list of instructions.

Of course, the C++ compiler won't back up the guarantee (in my code, I offer the guarantee as a @warning doxygen tag), which is kinda sad, but it should not stop you from trying to write exception-safe code.

Normal failure vs. bug

How can a programmer guarantee that a no-fail function will always succeed? After all, the function could have a bug.

This is true. The exception guarantees are supposed to be offered by bug-free code. But then, in any language, calling a function supposes the function is bug-free. No sane code protects itself against the possibility of it having a bug. Write code the best you can, and then, offer the guarantee with the supposition it is bug-free. And if there is a bug, correct it.

Exceptions are for exceptional processing failure, not for code bugs.

Last words

Now, the question is "Is this worth it ?".

Of course, it is. Having a "nothrow/no-fail" function knowing that the function won't fail is a great boon. The same can be said for a "strong" function, which enables you to write code with transactional semantics, like databases, with commit/rollback features, the commit being the normal execution of the code, throwing exceptions being the rollback.

Then, the "basic" is the very least guarantee you should offer. C++ is a very strong language there, with its scopes, enabling you to avoid any resource leaks (something a garbage collector would find it difficult to offer for the database, connection or file handles).

So, as far as I see it, it is worth it.

Edit 2010-01-29: About non-throwing swap

nobar made a comment that I believe, is quite relevant, because it is part of "how do you write exception safe code":

  • [me] A swap will never fail (don't even write a throwing swap)
  • [nobar] This is a good recommendation for custom-written swap() functions. It should be noted, however, that std::swap() can fail based on the operations that it uses internally

the default std::swap will make copies and assignments, which, for some objects, can throw. Thus, the default swap could throw, either used for your classes or even for STL classes. As far as the C++ standard is concerned, the swap operation for vector, deque, and list won't throw, whereas it could for map if the comparison functor can throw on copy construction (See The C++ Programming Language, Special Edition, appendix E, E.4.3.Swap).

Looking at Visual C++ 2008 implementation of the vector's swap, the vector's swap won't throw if the two vectors have the same allocator (i.e., the normal case), but will make copies if they have different allocators. And thus, I assume it could throw in this last case.

So, the original text still holds: Don't ever write a throwing swap, but nobar's comment must be remembered: Be sure the objects you're swapping have a non-throwing swap.

Edit 2011-11-06: Interesting article

Dave Abrahams, who gave us the basic/strong/nothrow guarantees, described in an article his experience about making the STL exception safe:

http://www.boost.org/community/exception_safety.html

Look at the 7th point (Automated testing for exception-safety), where he relies on automated unit testing to make sure every case is tested. I guess this part is an excellent answer to the question author's "Can you even be sure, that it is?".

Edit 2013-05-31: Comment from dionadar

t.integer += 1; is without the guarantee that overflow will not happen NOT exception safe, and in fact may technically invoke UB! (Signed overflow is UB: C++11 5/4 "If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.") Note that unsigned integer do not overflow, but do their computations in an equivalence class modulo 2^#bits.

Dionadar is referring to the following line, which indeed has undefined behaviour.

   t.integer += 1 ;                 // 1. nothrow/nofail

The solution here is to verify if the integer is already at its max value (using std::numeric_limits<T>::max()) before doing the addition.

My error would go in the "Normal failure vs. bug" section, that is, a bug. It doesn't invalidate the reasoning, and it does not mean the exception-safe code is useless because impossible to attain. You can't protect yourself against the computer switching off, or compiler bugs, or even your bugs, or other errors. You can't attain perfection, but you can try to get as near as possible.

I corrected the code with Dionadar's comment in mind.

How to make the web page height to fit screen height

Don't give exact heights, but relative ones, adding up to 100%. For example:

  #content {height: 80%;}
  #footer {height: 20%;}

Add in

 html, body {height: 100%;}