Programs & Examples On #Implicit

An implicit in Scala is a function applied or a parameter provided without explicitly appearing in the source code.

TypeError: Can't convert 'int' object to str implicitly

def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
    print("Your SP balance is now 0.")
    attributeConfirmation()
elif strength < 0:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif strength > balance:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
    print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
    print("That is an invalid input. Restarting attribute selection.")
    attributeSelection()

Android, How to read QR code in my application?

try {

    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
    intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes

    startActivityForResult(intent, 0);

} catch (Exception e) {

    Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
    Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
    startActivity(marketIntent);

}

and in onActivityResult():

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

        if (resultCode == RESULT_OK) {
            String contents = data.getStringExtra("SCAN_RESULT");
        }
        if(resultCode == RESULT_CANCELED){
            //handle cancel
        }
    }
}

Implicit type conversion rules in C++ operators

Arithmetic operations involving float results in float.

int + float = float
int * float = float
float * int = float
int / float = float
float / int = float
int / int = int

For more detail answer. Look at what the section §5/9 from the C++ Standard says

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result.

This pattern is called the usual arithmetic conversions, which are defined as follows:

— If either operand is of type long double, the other shall be converted to long double.

— Otherwise, if either operand is double, the other shall be converted to double.

— Otherwise, if either operand is float, the other shall be converted to float.

— Otherwise, the integral promotions (4.5) shall be performed on both operands.54)

— Then, if either operand is unsigned long the other shall be converted to unsigned long.

— Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.

— Otherwise, if either operand is long, the other shall be converted to long.

— Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

[Note: otherwise, the only remaining case is that both operands are int ]

Prepend line to beginning of a file

To put code to NPE's answer, I think the most efficient way to do this is:

def insert(originalfile,string):
    with open(originalfile,'r') as f:
        with open('newfile.txt','w') as f2: 
            f2.write(string)
            f2.write(f.read())
    os.rename('newfile.txt',originalfile)

How to loop through a checkboxlist and to find what's checked and not checked?

Use the CheckBoxList's GetItemChecked or GetItemCheckState method to find out whether an item is checked or not by its index.

Merge two (or more) lists into one, in C# .NET

I've already commented it but I still think is a valid option, just test if in your environment is better one solution or the other. In my particular case, using source.ForEach(p => dest.Add(p)) performs better than the classic AddRange but I've not investigated why at the low level.

You can see an example code here: https://gist.github.com/mcliment/4690433

So the option would be:

var allProducts = new List<Product>(productCollection1.Count +
                                    productCollection2.Count +
                                    productCollection3.Count);

productCollection1.ForEach(p => allProducts.Add(p));
productCollection2.ForEach(p => allProducts.Add(p));
productCollection3.ForEach(p => allProducts.Add(p));

Test it to see if it works for you.

Disclaimer: I'm not advocating for this solution, I find Concat the most clear one. I just stated -in my discussion with Jon- that in my machine this case performs better than AddRange, but he says, with far more knowledge than I, that this does not make sense. There's the gist if you want to compare.

How to use "Share image using" sharing Intent to share images in android?

Thanks all, I tried the few of the options given, but those seems not to work for the latest android releases, so adding the modified steps which work for the latest android releases. these are based on few of the answers above but with modifications & the solution is based on the use of File Provider :

Step:1

Add Following code in Manifest File:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_provider_paths" />
</provider>

step:2 Create an XML File in res > xml

Create file_provider_paths file inside xml.

Note that this is the file which we include in the android:resource in the previous step.

Write following codes inside the file_provider_paths:

<?xml version="1.0" encoding="utf-8"?>
<paths>
        <cache-path name="cache" path="/" />
        <files-path name="files" path="/" />
</paths>

Step:3

After that go to your button Click:

Button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

       Bitmap bit = BitmapFactory.decodeResource(context.getResources(),  R.drawable.filename);
        File filesDir = context.getApplicationContext().getFilesDir();
        File imageFile = new File(filesDir, "birds.png");
        OutputStream os;
        try {
            os = new FileOutputStream(imageFile);
            bit.compress(Bitmap.CompressFormat.PNG, 100, os); 
            os.flush();
            os.close();
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
        }

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        Uri imageUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, imageFile);

        intent.putExtra(Intent.EXTRA_STREAM, imageUri);
        intent.setType("image/*");
        context.startActivity(intent);
    }
});

For More detailed explanation Visit https://droidlytics.wordpress.com/2020/08/04/use-fileprovider-to-share-image-from-recyclerview/

Index all *except* one item in python

If you are using numpy, the closest, I can think of is using a mask

>>> import numpy as np
>>> arr = np.arange(1,10)
>>> mask = np.ones(arr.shape,dtype=bool)
>>> mask[5]=0
>>> arr[mask]
array([1, 2, 3, 4, 5, 7, 8, 9])

Something similar can be achieved using itertools without numpy

>>> from itertools import compress
>>> arr = range(1,10)
>>> mask = [1]*len(arr)
>>> mask[5]=0
>>> list(compress(arr,mask))
[1, 2, 3, 4, 5, 7, 8, 9]

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

How to get row index number in R?

If i understand your question, you just want to be able to access items in a data frame (or list) by row:

x = matrix( ceiling(9*runif(20)), nrow=5  )   
colnames(x) = c("col1", "col2", "col3", "col4")
df = data.frame(x)      # create a small data frame

df[1,]                  # get the first row
df[3,]                  # get the third row
df[nrow(df),]           # get the last row

lf = as.list(df)        

lf[[1]]                 # get first row
lf[[3]]                 # get third row

etc.

internal/modules/cjs/loader.js:582 throw err

When I was using the below command, I too was getting the same error:

node .function-hello.js

I changed my command to below command, it worked fine:

node .\function-hello.js

How to view log output using docker-compose run?

  1. use the command to start containers in detached mode: docker-compose up -d
  2. to view the containers use: docker ps
  3. to view logs for a container: docker logs <containerid>

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

Get DataKey values in GridView RowCommand

On the Button:

CommandArgument='<%# Eval("myKey")%>'

On the Server Event

e.CommandArgument

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

There's a difference between an empty string "" and an undefined variable. You should be checking whether or not theHref contains a defined string, rather than its lenght:

if(theHref){
   // ---
}

If you still want to check for the length, then do this:

if(theHref && theHref.length){
   // ...
}

Converting two lists into a matrix

You can use np.c_

np.c_[[1,2,3], [4,5,6]]

It will give you:

np.array([[1,4], [2,5], [3,6]])

How to pass command line arguments to a rake task

I couldn't figure out how to pass args and also the :environment until I worked this out:

namespace :db do
  desc 'Export product data'
  task :export, [:file_token, :file_path] => :environment do |t, args|
    args.with_defaults(:file_token => "products", :file_path => "./lib/data/")

       #do stuff [...]

  end
end

And then I call like this:

rake db:export['foo, /tmp/']

CSS Box Shadow Bottom Only

Do this:

box-shadow: 0 4px 2px -2px gray;

It's actually much simpler, whatever you set the blur to (3rd value), set the spread (4th value) to the negative of it.

C++ style cast from unsigned char * to const char *

Try reinterpret_cast

unsigned char *foo();
std::string str;
str.append(reinterpret_cast<const char*>(foo()));

Java - ignore exception and continue

You are already doing it in your code. Run this example below. The catch will "handle" the exception, and you can move forward, assuming whatever you caught and handled did not break code down the road which you did not anticipate.

 try{
      throw new Exception();
 }catch (Exception ex){
   ex.printStackTrace();
 }
 System.out.println("Made it!");

However, you should always handle an exception properly. You can get yourself into some pretty messy situations and write difficult to maintain code by "ignoring" exceptions. You should only do this if you are actually handling whatever went wrong with the exception to the point that it really does not affect the rest of the program.

Python: read all text file lines in loop

There's no need to check for EOF in python, simply do:

with open('t.ini') as f:
   for line in f:
       # For Python3, use print(line)
       print line
       if 'str' in line:
          break

Why the with statement:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.

Alternative for <blink>

The solution below is interesting because it can be applied across multiple elements concomitantly and does not trigger an error when the element no longer exists on the page. The secret is that it is called passing as a parameter a function in which you must return the elements you want to be affected by the blink. Then this function is called back with each blink. HTML file below:

<!doctype>
<html>
    <head>
        <style>
            .blink {color: red}
        </style>
    </head>
    <body>
        <h1>Blink test</h1>
        <p>
            Brazil elected President <span class="blink">Bolsonaro</span> because he 
            was the only candidate who did not promise <span class="blink">free things</span>
            to the population. Previous politicians created an image that would 
            bring many benefits, but in the end, the state has been getting more and 
            more <span class="blink">burdened</span>. Brazil voted for the 
            realistic idea that <span class="blink">there is no free lunch</span>.
        </p>
    </body>
    <script>
    var blink =
        {
            interval_in_miliseconds:
                400,
            on:
                true,
            function_wich_returns_the_elements: 
                [],
            activate:
                function(function_wich_returns_the_elements)
                {
                    this.function_wich_returns_the_elements = function_wich_returns_the_elements;
                    setInterval(blink.change, blink.interval_in_miliseconds);
                },
            change:
                function()
                {   
                    blink.on = !blink.on;
                    var i, elements = [];
                    for (i in blink.function_wich_returns_the_elements)
                    {
                        elements = elements.concat(blink.function_wich_returns_the_elements[i]());
                    }
                    for (i in elements)
                    {
                        if (elements[i])
                        {
                            elements[i].style.opacity = blink.on ? 1 : .2;
                        }
                    }
                }
        };
    blink.activate
    (
        [
            function()
            {
                var 
                    i,
                    node_collection = document.getElementsByClassName('blink'),
                    elements = [];
                for (i = 0; i < node_collection.length; i++)
                {
                    elements.push(node_collection[i]);
                }
                return elements;
            }
        ]
    );
    </script>
</html>

Service has zero application (non-infrastructure) endpoints

To prepare the configration for WCF is hard, and sometimes a service type definition go unnoticed.

I wrote only the namespace in the service tag, so I got the same error.

<service name="ServiceNameSpace">

Do not forget, the service tag needs a fully-qualified service class name.

<service name="ServiceNameSpace.ServiceClass">

For the other folks who are like me.

How to generate entire DDL of an Oracle schema (scriptable)?

There is a problem with objects such as PACKAGE_BODY:

SELECT DBMS_METADATA.get_ddl(object_Type, object_name, owner) FROM ALL_OBJECTS WHERE OWNER = 'WEBSERVICE';


ORA-31600 invalid input value PACKAGE BODY parameter OBJECT_TYPE in function GET_DDL
ORA-06512: ??  "SYS.DBMS_METADATA", line 4018
ORA-06512: ??  "SYS.DBMS_METADATA", line 5843
ORA-06512: ??  line 1
31600. 00000 -  "invalid input value %s for parameter %s in function %s"
*Cause:    A NULL or invalid value was supplied for the parameter.
*Action:   Correct the input value and try the call again.



SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type,' ','_'), object_name, owner)
  FROM all_OBJECTS 
  WHERE (OWNER = 'OWNER1');

UITableViewCell Selected Background Color on Multiple Selection

All the above answers are fine but a bit to complex to my liking. The simplest way to do it is to put some code in the cellForRowAtIndexPath. That way you never have to worry about changing the color when the cell is deselected.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

    /* this is where the magic happens, create a UIView and set its
       backgroundColor to what ever color you like then set the cell's
       selectedBackgroundView to your created View */

    let backgroundView = UIView()
    backgroundView.backgroundColor = YOUR_COLOR_HERE
    cell.selectedBackgroundView = backgroundView
    return cell
}

Missing MVC template in Visual Studio 2015

I had the same issue with the MVC template not appearing in VS2015.

I checked Web Developer Tools when originally installing. It was still checked when trying to Modify the install. I tried unchecking and updating the install but next time I went back to Modify, it was still checked. And still no MVC template.

I got it working by uninstalling: Microsoft ASP.NET Web Frameworks and Tools 2015 via the Programs and Features windows and re-installing. Here's the link for those who don't have it.

Moving x-axis to the top of a plot in matplotlib

tick_params is very useful for setting tick properties. Labels can be moved to the top with:

    ax.tick_params(labelbottom=False,labeltop=True)

Oracle SQL update based on subquery between two tables

As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.

However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.

Use images instead of radio buttons

Images can be placed in place of radio buttons by using label and span elements.

   <div class="customize-radio">
        <label>Favourite Smiley</label><br>
        <label for="hahaha">
        <input type="radio" name="smiley" id="hahaha">
        <span class="haha-img"></span>
        HAHAHA
        </label>
        <label for="kiss">
        <input type="radio" name="smiley" id="kiss">
        <span class="kiss-img"></span>
        Kiss
        </label>
        <label for="tongueOut">
        <input type="radio" name="smiley" id="tongueOut">
        <span class="tongueout-img"></span>
        TongueOut
        </label>
    </div>

Radio button should be hidden,

.customize-radio label > input[type = 'radio'] {
    visibility: hidden;
    position: absolute;
}

Image can be given in the span tag,

.customize-radio label > input[type = 'radio'] ~ span{
    cursor: pointer;
    width: 27px;
    height: 24px;
    display: inline-block;
    background-size: 27px 24px;
    background-repeat: no-repeat;
}
.haha-img {
    background-image: url('hahabefore.png');
}

.kiss-img{
    background-image: url('kissbefore.png');
}
.tongueout-img{
    background-image: url('tongueoutbefore.png');
}

To change the image on click of radio button, add checked state to the input tag,

.customize-radio label > input[type = 'radio']:checked ~ span.haha-img{
     background-image: url('haha.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.kiss-img{
    background-image: url('kiss.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.tongueout-img{
        background-image: url('tongueout.png');
}

If you have any queries, Refer to the following link, As I have taken solution from the below blog, http://frontendsupport.blogspot.com/2018/06/cool-radio-buttons-with-images.html

How do I run a shell script without using "sh" or "bash" commands?

Here is my backup script that will give you the idea and the automation:

Server: Ubuntu 16.04 PHP: 7.0 Apache2, Mysql etc...

# Make Shell Backup Script - Bash Backup Script
    nano /home/user/bash/backupscript.sh
        #!/bin/bash
        # Backup All Start
        mkdir /home/user/backup/$(date +"%Y-%m-%d")
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_rest.zip /etc -x "*apache2*" -x "*php*" -x "*mysql*"
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_apache2.zip /etc/apache2
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_php.zip /etc/php
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_mysql.zip /etc/mysql
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_rest.zip /var/www -x "*html*"
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_html.zip /var/www/html
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/home_user.zip /home/user -x "*backup*"
        # Backup All End
        echo "Backup Completed Successfully!"
        echo "Location: /home/user/backup/$(date +"%Y-%m-%d")"

    chmod +x /home/user/bash/backupscript.sh
    sudo ln -s /home/user/bash/backupscript.sh /usr/bin/backupscript

change /home/user to your user directory and type: backupscript anywhere on terminal to run the script! (assuming that /usr/bin is in your path)

How to redirect to action from JavaScript method?

(This is more of a comment but I can't comment because of the low reputation, somebody might find these useful)

If you're in sth.com/product and you want to redirect to sth.com/product/index use

window.location.href = "index";

If you want to redirect to sth.com/home

window.location.href = "/home";

and if you want you want to redirect to sth.com/home/index

window.location.href = "/home/index";

node.js - how to write an array to file

A simple solution is to use writeFile :

require("fs").writeFile(
     somepath,
     arr.map(function(v){ return v.join(', ') }).join('\n'),
     function (err) { console.log(err ? 'Error :'+err : 'ok') }
);

Retrieve data from a ReadableStream object?

Some people may find an async example useful:

var response = await fetch("https://httpbin.org/ip");
var body = await response.json(); // .json() is asynchronous and therefore must be awaited

json() converts the response's body from a ReadableStream to a json object.

The await statements must be wrapped in an async function, however you can run await statements directly in the console of Chrome (as of version 62).

How to send a POST request from node.js Express?

you can try like this:

var request = require('request');
request.post({ headers: {'content-type' : 'application/json'}
               , url: <your URL>, body: <req_body in json> }
               , function(error, response, body){
   console.log(body); 
}); 

Displaying output of a remote command with Ansible

I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...

Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines attribute:

- name: Generate SSH keys for vagrant user
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
  register: vagrant
- debug: var=vagrant.stdout_lines

- name: Show SSH public key
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
- debug: var=cat.stdout_lines

- name: Wait for user to copy SSH public key
  pause: prompt="Please add the SSH public key above to your GitHub account"
  register: pause
- debug: var=pause.stdout_lines

How to get the range of occupied cells in excel sheet

You should try the currentRegion property, if you know from where you are to find the range. This will give you the boundaries of your used range.

Mockito : how to verify method was called on an object created within a method?

The classic response is, "You don't." You test the public API of Foo, not its internals.

Is there any behavior of the Foo object (or, less good, some other object in the environment) that is affected by foo()? If so, test that. And if not, what does the method do?

SQL Inner-join with 3 tables?

SELECT 
A.P_NAME AS [INDIVIDUAL NAME],B.F_DETAIL AS [INDIVIDUAL FEATURE],C.PL_PLACE AS [INDIVIDUAL LOCATION]
FROM 
[dbo].[PEOPLE] A
INNER JOIN 
[dbo].[FEATURE] B ON A.P_FEATURE = B.F_ID
INNER JOIN 
[dbo].[PEOPLE_LOCATION] C ON A.P_LOCATION = C.PL_ID

'dependencies.dependency.version' is missing error, but version is managed in parent

Make sure the value in the child's project/parent/version node matches its parent's project/version value

Fastest way to download a GitHub project

Another faster way of downloading a GitHub project would be to use the clone functionality with the --depth argument as:

git clone --depth=1 [email protected]:organization/your-repo.git

to perform a shallow clone.

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

Set ANDROID_HOME environment variable in mac

Open Terminal

nano ~/.bash_profile


export ANDROID_HOME=/Users/qss/Library/Android/sdk
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH

Control+S to save
Control+X to exit
Y to save changes
Update changes in terminal
source ~/.bash_profile

Validate Path:
echo $PATH

Confirm if all okay:
adb devices

Displaying better error message than "No JSON object could be decoded"

I had a similar problem and it was due to singlequotes. The JSON standard(http://json.org) talks only about using double quotes so it must be that the python json library supports only double quotes.

Set the value of an input field

Direct access

If you use ID then you have direct access to input in JS global scope

_x000D_
_x000D_
myInput.value = 'default_value'
_x000D_
<input id="myInput">
_x000D_
_x000D_
_x000D_

Python pandas: fill a dataframe row by row

This is a simpler version

import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
   df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`

Cookies on localhost with explicit domain

None of the suggested fixes worked for me - setting it to null, false, adding two dots, etc - didn't work.

In the end, I just removed the domain from the cookie if it is localhost and that now works for me in Chrome 38.

Previous code (did not work):

document.cookie = encodeURI(key) + '=' + encodeURI(value) + ';domain=.' + document.domain + ';path=/;';

New code (now working):

 if(document.domain === 'localhost') {
        document.cookie = encodeURI(key) + '=' + encodeURI(value) + ';path=/;' ;
    } else {
        document.cookie = encodeURI(key) + '=' + encodeURI(value) + ';domain=.' + document.domain + ';path=/;';
    }

HTML button opening link in new tab

If you're in pug:

html
    head
        title Pug
    body
        a(href="http://www.example.com" target="_blank") Example
        button(onclick="window.open('http://www.example.com')") Example

And if you're puggin' Semantic UI:

html
    head
        title Pug
        link(rel='stylesheet' href='https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css')
    body
        .ui.center.aligned.container
            a(href="http://www.example.com" target="_blank") Example
        .ui.center.aligned.container
           .ui.large.grey.button(onclick="window.open('http://www.example.com')") Example

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

"Missing return statement" within if / for / while

That is illegal syntax. It is not an optional thing for you to return a variable. You MUST return a variable of the type you specify in your method.

public String myMethod()
{
    if(condition)
    {
       return x;
    }
}

You are effectively saying, I promise any class can use this method(public) and I promise it will always return a String(String).

Then you are saying IF my condition is true I will return x. Well that is too bad, there is no IF in your promise. You promised that myMethod will ALWAYS return a String. Even if your condition is ALWAYS true the compiler has to assume that there is a possibility of it being false. Therefore you always need to put a return at the end of your non-void method outside of any conditions JUST IN CASE all of your conditions fail.

public String myMethod()
{
    if(condition)
    {
       return x;
    }
  return ""; //or whatever the default behavior will be if all of your conditions fail to return.
}

How to create a foreign key in phpmyadmin

The key must be indexed to apply foreign key constraint. To do that follow the steps.

  1. Open table structure. (2nd tab)
  2. See the last column action where multiples action options are there. Click on Index, this will make the column indexed.
  3. Open relation view and add foreign key constraint.

You will be able to assign DOCTOR_ID as foreign now.

Is there a TRY CATCH command in Bash

Below is an example of a script which implements try/catch/finally in bash.

Like other answers to this question, exceptions must be caught after exiting a subprocess.

The example scripts start by creating an anonymous fifo, which is used to pass string messages from a command exception or throw to end of the closest try block. Here the messages are removed from the fifo and placed in an array variable. The status is returned through return and exit commands and placed in a different variable. To enter a catch block, this status must not be zero. Other requirements to enter a catch block are passed as parameters. If the end of a catch block is reached, then the status is set to zero. If the end of the finally block is reached and the status is still nonzero, then an implicit throw containing the messages and status is executed. The script requires the calling of the function trycatchfinally which contains an unhandled exception handler.

The syntax for the trycatchfinally command is given below.

trycatchfinally [-cde] [-h ERR_handler] [-k] [-o debug_file] [-u unhandled_handler] [-v variable] fifo function

The -c option adds the call stack to the exception messages.
The -d option enables debug output.
The -e option enables command exceptions.
The -h option allows the user to substitute their own command exception handler.
The -k option adds the call stack to the debug output.
The -o option replaces the default output file which is /dev/fd/2.
The -u option allows the user to substitute their own unhandled exception handler.
The -v option allows the user the option to pass back values though the use of Command Substitution.
The fifo is the fifo filename.
The function function is called by trycatchfinally as a subprocess.

Note: The cdko options were removed to simplify the script.

The syntax for the catch command is given below.

catch [[-enoprt] list ...] ...

The options are defined below. The value for the first list is the status. Subsquent values are the messages. If the there are more messages than lists, then the remaining messages are ignored.

-e means [[ $value == "$string" ]] (the value has to match at least one string in the list)
-n means [[ $value != "$string" ]] (the value can not match any of the strings in the list)
-o means [[ $value != $pattern ]] (the value can not match any of the patterns in the list)
-p means [[ $value == $pattern ]] (the value has to match at least one pattern in the list)
-r means [[ $value =~ $regex ]] (the value has to match at least one extended regular expression in the list)
-t means [[ ! $value =~ $regex ]] (the value can not match any of the extended regular expressions in the list)

The try/catch/finally script is given below. To simplify the script for this answer, most of the error checking was removed. This reduced the size by 64%. A complete copy of this script can be found at my other answer.

shopt -s expand_aliases
alias try='{ common.Try'
alias yrt='EchoExitStatus; common.yrT; }'
alias catch='{ while common.Catch'
alias hctac='common.hctaC; done; }'
alias finally='{ common.Finally'
alias yllanif='common.yllaniF; }'

DefaultErrHandler() {
    echo "Orginal Status: $common_status"
    echo "Exception Type: ERR"
}

exception() {
    let "common_status = 10#$1"
    shift
    common_messages=()
    for message in "$@"; do
        common_messages+=("$message")
    done
}

throw() {
    local "message"
    if [[ $# -gt 0 ]]; then
        let "common_status = 10#$1"
        shift
        for message in "$@"; do
            echo "$message" >"$common_fifo"
        done
    elif [[ ${#common_messages[@]} -gt 0 ]]; then
        for message in "${common_messages[@]}"; do
            echo "$message" >"$common_fifo"
        done
    fi
    chmod "0400" "$common_fifo"
    exit "$common_status"
}

common.ErrHandler() {
    common_status=$?
    trap ERR
    if [[ -w "$common_fifo" ]]; then
        if [[ $common_options != *e* ]]; then
            common_status="0"
            return
        fi
        eval "${common_errHandler:-} \"${BASH_LINENO[0]}\" \"${BASH_SOURCE[1]}\" \"${FUNCNAME[1]}\" >$common_fifo <$common_fifo"
        chmod "0400" "$common_fifo"
    fi
    if [[ common_trySubshell -eq BASH_SUBSHELL ]]; then
        return   
    else
        exit "$common_status"
    fi
}

common.Try() {
    common_status="0"
    common_subshell="$common_trySubshell"
    common_trySubshell="$BASH_SUBSHELL"
    common_messages=()
}

common.yrT() {
    local "status=$?"
    if [[ common_status -ne 0 ]]; then    
        local "message=" "eof=TRY_CATCH_FINALLY_END_OF_MESSAGES_$RANDOM"
        chmod "0600" "$common_fifo"
        echo "$eof" >"$common_fifo"
        common_messages=()
        while read "message"; do
            [[ $message != *$eof ]] || break
            common_messages+=("$message")
        done <"$common_fifo"
    fi
    common_trySubshell="$common_subshell"
}

common.Catch() {
    [[ common_status -ne 0 ]] || return "1"
    local "parameter" "pattern" "value"
    local "toggle=true" "compare=p" "options=$-"
    local -i "i=-1" "status=0"
    set -f
    for parameter in "$@"; do
        if "$toggle"; then
            toggle="false"
            if [[ $parameter =~ ^-[notepr]$ ]]; then
                compare="${parameter#-}"
                continue 
            fi
        fi
        toggle="true"
        while "true"; do
            eval local "patterns=($parameter)"
            if [[ ${#patterns[@]} -gt 0 ]]; then
                for pattern in "${patterns[@]}"; do
                    [[ i -lt ${#common_messages[@]} ]] || break
                    if [[ i -lt 0 ]]; then
                        value="$common_status"
                    else
                        value="${common_messages[i]}"
                    fi
                    case $compare in
                    [ne]) [[ ! $value == "$pattern" ]] || break 2;;
                    [op]) [[ ! $value == $pattern ]] || break 2;;
                    [tr]) [[ ! $value =~ $pattern ]] || break 2;;
                    esac
                done
            fi
            if [[ $compare == [not] ]]; then
                let "++i,1"
                continue 2
            else
                status="1"
                break 2
            fi
        done
        if [[ $compare == [not] ]]; then
            status="1"
            break
        else
            let "++i,1"
        fi
    done
    [[ $options == *f* ]] || set +f
    return "$status"
} 

common.hctaC() {
    common_status="0"
}

common.Finally() {
    :
}

common.yllaniF() {
    [[ common_status -eq 0 ]] || throw
}

caught() {
    [[ common_status -eq 0 ]] || return 1
}

EchoExitStatus() {
    return "${1:-$?}"
}

EnableThrowOnError() {
    [[ $common_options == *e* ]] || common_options+="e"
}

DisableThrowOnError() {
    common_options="${common_options/e}"
}

GetStatus() {
    echo "$common_status"
}

SetStatus() {
    let "common_status = 10#$1"
}

GetMessage() {
    echo "${common_messages[$1]}"
}

MessageCount() {
    echo "${#common_messages[@]}"
}

CopyMessages() {
    if [[ ${#common_messages} -gt 0 ]]; then
        eval "$1=(\"\${common_messages[@]}\")"
    else
        eval "$1=()"
    fi
}

common.GetOptions() {
    local "opt"
    let "OPTIND = 1"
    let "OPTERR = 0"
    while getopts ":cdeh:ko:u:v:" opt "$@"; do
        case $opt in
        e)  [[ $common_options == *e* ]] || common_options+="e";;
        h)  common_errHandler="$OPTARG";;
        u)  common_unhandled="$OPTARG";;
        v)  common_command="$OPTARG";;
        esac
    done
    shift "$((OPTIND - 1))"
    common_fifo="$1"
    shift
    common_function="$1"
    chmod "0600" "$common_fifo"
}

DefaultUnhandled() {
    local -i "i"
    echo "-------------------------------------------------"
    echo "TryCatchFinally: Unhandeled exception occurred"
    echo "Status: $(GetStatus)"
    echo "Messages:"
    for ((i=0; i<$(MessageCount); i++)); do
        echo "$(GetMessage "$i")"
    done
    echo "-------------------------------------------------"
}

TryCatchFinally() {
    local "common_errHandler=DefaultErrHandler"
    local "common_unhandled=DefaultUnhandled"
    local "common_options="
    local "common_fifo="
    local "common_function="
    local "common_flags=$-"
    local "common_trySubshell=-1"
    local "common_subshell"
    local "common_status=0"
    local "common_command="
    local "common_messages=()"
    local "common_handler=$(trap -p ERR)"
    [[ -n $common_handler ]] || common_handler="trap ERR"
    common.GetOptions "$@"
    shift "$((OPTIND + 1))"
    [[ -z $common_command ]] || common_command+="=$"
    common_command+='("$common_function" "$@")'
    set -E
    set +e
    trap "common.ErrHandler" ERR
    try
        eval "$common_command"
    yrt
    catch; do
        "$common_unhandled" >&2
    hctac
    [[ $common_flags == *E* ]] || set +E
    [[ $common_flags != *e* ]] || set -e
    [[ $common_flags != *f* || $- == *f* ]] || set -f
    [[ $common_flags == *f* || $- != *f* ]] || set +f
    eval "$common_handler"
}

Below is an example, which assumes the above script is stored in the file named simple. The makefifo file contains the script described in this answer. The assumption is made that the file named 4444kkkkk does not exist, therefore causing an exception to occur. The error message output from the ls 4444kkkkk command is automatically suppressed until inside the appropriate catch block.

#!/bin/bash
#

if [[ $0 != ${BASH_SOURCE[0]} ]]; then
    bash "${BASH_SOURCE[0]}" "$@"
    return
fi

source simple
source makefifo

MyFunction3() {
    echo "entered MyFunction3" >&4
    echo "This is from MyFunction3"
    ls 4444kkkkk
    echo "leaving MyFunction3" >&4
}

MyFunction2() {
    echo "entered MyFunction2" >&4
    value="$(MyFunction3)"
    echo "leaving MyFunction2" >&4
}

MyFunction1() {
    echo "entered MyFunction1" >&4
    local "flag=false"
    try 
    (
        echo "start of try" >&4
        MyFunction2
        echo "end of try" >&4
    )
    yrt
    catch "[1-3]" "*" "Exception\ Type:\ ERR"; do
        echo 'start of catch "[1-3]" "*" "Exception\ Type:\ ERR"'
        local -i "i"
        echo "-------------------------------------------------"
        echo "Status: $(GetStatus)"
        echo "Messages:"
        for ((i=0; i<$(MessageCount); i++)); do
            echo "$(GetMessage "$i")"
        done
        echo "-------------------------------------------------"
        break
        echo 'end of catch "[1-3]" "*" "Exception\ Type:\ ERR"'
    hctac >&4
    catch "1 3 5" "*" -n "Exception\ Type:\ ERR"; do
        echo 'start of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"'
        echo "-------------------------------------------------"
        echo "Status: $(GetStatus)"
        [[ $(MessageCount) -le 1 ]] || echo "$(GetMessage "1")"
        echo "-------------------------------------------------"
        break
        echo 'end of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"'
    hctac >&4
    catch; do
        echo 'start of catch' >&4
        echo "failure"
        flag="true"
        echo 'end of catch' >&4
    hctac
    finally
        echo "in finally"
    yllanif >&4
    "$flag" || echo "success"
    echo "leaving MyFunction1" >&4
} 2>&6

ErrHandler() {
    echo "EOF"
    DefaultErrHandler "$@"
    echo "Function: $3"
    while read; do
        [[ $REPLY != *EOF ]] || break
        echo "$REPLY"
    done
}

set -u
echo "starting" >&2
MakeFIFO "6"
TryCatchFinally -e -h ErrHandler -o /dev/fd/4 -v result /dev/fd/6 MyFunction1 4>&2
echo "result=$result"
exec >&6-

The above script was tested using GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin17). The output, from running this script, is shown below.

starting
entered MyFunction1
start of try
entered MyFunction2
entered MyFunction3
start of catch "[1-3]" "*" "Exception\ Type:\ ERR"
-------------------------------------------------
Status: 1
Messages:
Orginal Status: 1
Exception Type: ERR
Function: MyFunction3
ls: 4444kkkkk: No such file or directory
-------------------------------------------------
start of catch
end of catch
in finally
leaving MyFunction1
result=failure

Another example which uses a throw can be created by replacing function MyFunction3 with the script shown below.

MyFunction3() {
    echo "entered MyFunction3" >&4
    echo "This is from MyFunction3"
    throw "3" "Orginal Status: 3" "Exception Type: throw"
    echo "leaving MyFunction3" >&4
}

The syntax for the throw command is given below. If no parameters are present, then status and messages stored in the variables are used instead.

throw [status] [message ...]

The output, from executing the modified script, is shown below.

starting
entered MyFunction1
start of try
entered MyFunction2
entered MyFunction3
start of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"
-------------------------------------------------
Status: 3
Exception Type: throw
-------------------------------------------------
start of catch
end of catch
in finally
leaving MyFunction1
result=failure

Add views below toolbar in CoordinatorLayout

Take the attribute

app:layout_behavior="@string/appbar_scrolling_view_behavior"

off the RecyclerView and put it on the FrameLayout that you are trying to show under the Toolbar.

I've found that one important thing the scrolling view behavior does is to layout the component below the toolbar. Because the FrameLayout has a descendant that will scroll (RecyclerView), the CoordinatorLayout will get those scrolling events for moving the Toolbar.


One other thing to be aware of: That layout behavior will cause the FrameLayout height to be sized as if the Toolbar is already scrolled, and with the Toolbar fully displayed the entire view is simply pushed down so that the bottom of the view is below the bottom of the CoordinatorLayout.

This was a surprise to me. I was expecting the view to be dynamically resized as the toolbar is scrolled up and down. So if you have a scrolling component with a fixed component at the bottom of your view, you won't see that bottom component until you have fully scrolled the Toolbar.

So when I wanted to anchor a button at the bottom of the UI, I worked around this by putting the button at the bottom of the CoordinatorLayout (android:layout_gravity="bottom") and adding a bottom margin equal to the button's height to the view beneath the toolbar.

CSS image overlay with color and transparency

If you want to make the reverse of what you showed consider doing this:

.tint:hover:before {
    background: rgba(0,0,250, 0.5);

  }

  .t2:before {
    background: none;
  }

and look at the effect on the 2nd picture.

Is it supposed to look like this?

Getting Lat/Lng from Google marker

Here is the JSFiddle Demo. In Google Maps API V3 it's pretty simple to track the lat and lng of a draggable marker. Let's start with the following HTML and CSS as our base.

<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>

#map_canvas{
    width: 400px;
    height: 300px;
}

#current{
     padding-top: 25px;
}

Here is our initial JavaScript initializing the google map. We create a marker that we want to drag and set it's draggable property to true. Of course keep in mind it should be attached to an onload event of your window for it to be loaded, but i'll skip to the code:

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 1,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(47.651968, 9.478485),
    draggable: true
});

Here we attach two events dragstart to track the start of dragging and dragend to drack when the marker stop getting dragged, and the way we attach it is to use google.maps.event.addListener. What we are doing here is setting the div current's content when marker is getting dragged and then set the marker's lat and lng when drag stops. Google mouse event has a property name 'latlng' that returns 'google.maps.LatLng' object when the event triggers. So, what we are doing here is basically using the identifier for this listener that gets returned by the google.maps.event.addListener and get the property latLng to extract the dragend's current position. Once we get that Lat Lng when the drag stops we'll display within your current div:

google.maps.event.addListener(myMarker, 'dragend', function(evt){
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function(evt){
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

Lastly, we'll center our marker and display it on the map:

map.setCenter(myMarker.position);
myMarker.setMap(map);

Let me know if you have any questions regarding my answer.

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

You can use regex.findall():

import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)

HTML radio buttons allowing multiple selections

They all need to have the same name attribute.

The radio buttons are grouped by the name attribute. Here's an example:

<fieldset>
    <legend>Please select one of the following</legend>
    <input type="radio" name="action" id="track" value="track" /><label for="track">Track Submission</label><br />
    <input type="radio" name="action" id="event" value="event"  /><label for="event">Events and Artist booking</label><br />
    <input type="radio" name="action" id="message" value="message" /><label for="message">Message us</label><br />
</fieldset>

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

gcc version 4.8.1, the error seems like:

/root/bllvm/build/Release+Asserts/bin/llvm-tblgen: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by /root/bllvm/build/Release+Asserts/bin/llvm-tblgen)

I found the libstdc++.so.6.0.18 at the place where I complied gcc 4.8.1

Then I do like this

cp ~/objdir/x86_64-unknown-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6.0.18 /usr/lib64/

rm /usr/lib64/libstdc++.so.6

ln -s libstdc++.so.6.0.18 libstdc++.so.6

problem solved.

Coarse-grained vs fine-grained

coarse grained and fine grained. Both of these modes define how the cores are shared between multiple Spark tasks. As the name suggests, fine-grained mode is responsible for sharing the cores at a more granular level. Fine-grained mode has been deprecated by Spark and will soon be removed.

Locking a file in Python

Coordinating access to a single file at the OS level is fraught with all kinds of issues that you probably don't want to solve.

Your best bet is have a separate process that coordinates read/write access to that file.

Mysql - delete from multiple tables with one query

You can use following query to delete rows from multiple tables,

DELETE table1, table2, table3 FROM table1 INNER JOIN table2 INNER JOIN table3 WHERE table1.userid = table2.userid AND table2.userid = table3.userid AND table1.userid=3

Scanning Java annotations at runtime

Google Reflection if you want to discover interfaces as well.

Spring ClassPathScanningCandidateComponentProvider is not discovering interfaces.

In jQuery, how do I select an element by its name attribute?

If you'd like to know the value of the default selected radio button before a click event, try this:

alert($("input:radio:checked").val());

Loading .sql files from within PHP

This may be helpful -->

More or less what it does is to first take the string given to the function (the file_get_contents() value of your file.sql) and remove all the line breaks. Then it splits the data by the ";" character. Next it goes into a while loop, looking at each line of the array that is created. If the line contains the " ` " character, it will know it is a query and execture the myquery() function for the given line data.

Code:

function myquery($query) {

mysql_connect(dbhost, dbuser, dbpass);

mysql_select_db(dbname);

$result = mysql_query($query);

if (!mysql_errno() && @mysql_num_rows($result) > 0) {
}

else {

$result="not";
}
mysql_close();

return $result;

}



function mybatchquery ($str) {

$sql = str_replace("\n","",$str)

$sql = explode(";",$str);

$x=0;

while (isset($str[$x])) {

if (preg_match("/(\w|\W)+`(\w|\W)+) {

myquery($str[$x]);

}

$x++

}

return TRUE;

}




function myrows($result) {

$rows = @mysql_num_rows($result);

return $rows;
}




function myarray($result) {

$array = mysql_fetch_array($result);

return $array;
}




function myescape($query) {

$escape = mysql_escape_string($query);

return $escape;
}



$str = file_get_contents("foo.sql");
mybatchquery($str);

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to set the credentials on the fly, have a look at this source:

http://spc3.codeplex.com/SourceControl/changeset/view/57957#1015709

private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype) {
    NetworkCredential cred;
    if (username.Contains(@"\")) {
        string domain = username.Substring(0, username.IndexOf(@"\"));
        username = username.Substring(username.IndexOf(@"\") + 1);
        cred = new System.Net.NetworkCredential(username, password, domain);
    } else {
        cred = new System.Net.NetworkCredential(username, password);
    }
    CredentialCache cache = new CredentialCache();
    if (authtype.Contains(":")) {
        authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
    }
    cache.Add(new Uri(siteurl), authtype, cred);
    return cache;
}

Sorting HashMap by values

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

public class CollectionsSort {

    /**
     * @param args
     */`enter code here`
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        CollectionsSort colleciotns = new CollectionsSort();

        List<combine> list = new ArrayList<combine>();
        HashMap<String, Integer> h = new HashMap<String, Integer>();
        h.put("nayanana", 10);
        h.put("lohith", 5);

        for (Entry<String, Integer> value : h.entrySet()) {
            combine a = colleciotns.new combine(value.getValue(),
                    value.getKey());
            list.add(a);
        }

        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }

    public class combine implements Comparable<combine> {

        public int value;
        public String key;

        public combine(int value, String key) {
            this.value = value;
            this.key = key;
        }

        @Override
        public int compareTo(combine arg0) {
            // TODO Auto-generated method stub
            return this.value > arg0.value ? 1 : this.value < arg0.value ? -1
                    : 0;
        }

        public String toString() {
            return this.value + " " + this.key;
        }
    }

}

Position absolute but relative to parent

Incase someone wants to postion a child div directly under a parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 100%;
}

Working demo Codepen

Best C++ IDE or Editor for Windows

With Intellisense, code folding, edit and continue, and a whole host of other features, Visual Studio is certainly the best IDE. However, for simple code editing, I often use UltraEdit. It has some great features not found in Visual Studio. One surprisingly useful feature is being able to select a column in the editor. You can find and replace within the column (useful for tabs vs. spaces wars...) delete the column, etc...

How do I best silence a warning about unused variables?

In GCC and Clang you can use the __attribute__((unused)) preprocessor directive to achieve your goal.
For example:

int foo (__attribute__((unused)) int bar) {
   return 0;
}

How do I insert an image in an activity with android studio?

copy the image that you want to show in android app and paste in drawable folder. given below code

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/image"
 />

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SSMS, "Query" menu item... "Results to"... "Results to File"

Shortcut = CTRL+shift+F

You can set it globally too

"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down

Edit: after comment

In SSMS, "Query" menu item... "SQLCMD" mode

This allows you to run "command line" like actions.

A quick test in my SSMS 2008

:OUT c:\foo.txt
SELECT * FROM sys.objects

Edit, Sep 2012

:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects

how to fire event on file select

This is an older question that needs a newer answer that will address @Christopher Thomas's concern above in the accept answer's comments. If you don't navigate away from the page and then select the file a second time, you need to clear the value when you click or do a touchstart(for mobile). The below will work even when you navigate away from the page and uses jquery:

//the HTML
<input type="file" id="file" name="file" />



//the JavaScript

/*resets the value to address navigating away from the page 
and choosing to upload the same file */ 

$('#file').on('click touchstart' , function(){
    $(this).val('');
});


//Trigger now when you have selected any file 
$("#file").change(function(e) {
    //do whatever you want here
});

node.js execute system command synchronously

Use ShellJS module.

exec function without providing callback.

Example:

var version = exec('node -v').output;

Tkinter understanding mainloop

tk.mainloop() blocks. It means that execution of your Python commands halts there. You can see that by writing:

while 1:
    ball.draw()
    tk.mainloop()
    print("hello")   #NEW CODE
    time.sleep(0.01)

You will never see the output from the print statement. Because there is no loop, the ball doesn't move.

On the other hand, the methods update_idletasks() and update() here:

while True:
    ball.draw()
    tk.update_idletasks()
    tk.update()

...do not block; after those methods finish, execution will continue, so the while loop will execute over and over, which makes the ball move.

An infinite loop containing the method calls update_idletasks() and update() can act as a substitute for calling tk.mainloop(). Note that the whole while loop can be said to block just like tk.mainloop() because nothing after the while loop will execute.

However, tk.mainloop() is not a substitute for just the lines:

tk.update_idletasks()
tk.update()

Rather, tk.mainloop() is a substitute for the whole while loop:

while True:
    tk.update_idletasks()
    tk.update()

Response to comment:

Here is what the tcl docs say:

Update idletasks

This subcommand of update flushes all currently-scheduled idle events from Tcl's event queue. Idle events are used to postpone processing until “there is nothing else to do”, with the typical use case for them being Tk's redrawing and geometry recalculations. By postponing these until Tk is idle, expensive redraw operations are not done until everything from a cluster of events (e.g., button release, change of current window, etc.) are processed at the script level. This makes Tk seem much faster, but if you're in the middle of doing some long running processing, it can also mean that no idle events are processed for a long time. By calling update idletasks, redraws due to internal changes of state are processed immediately. (Redraws due to system events, e.g., being deiconified by the user, need a full update to be processed.)

APN As described in Update considered harmful, use of update to handle redraws not handled by update idletasks has many issues. Joe English in a comp.lang.tcl posting describes an alternative:

So update_idletasks() causes some subset of events to be processed that update() causes to be processed.

From the update docs:

update ?idletasks?

The update command is used to bring the application “up to date” by entering the Tcl event loop repeatedly until all pending events (including idle callbacks) have been processed.

If the idletasks keyword is specified as an argument to the command, then no new events or errors are processed; only idle callbacks are invoked. This causes operations that are normally deferred, such as display updates and window layout calculations, to be performed immediately.

KBK (12 February 2000) -- My personal opinion is that the [update] command is not one of the best practices, and a programmer is well advised to avoid it. I have seldom if ever seen a use of [update] that could not be more effectively programmed by another means, generally appropriate use of event callbacks. By the way, this caution applies to all the Tcl commands (vwait and tkwait are the other common culprits) that enter the event loop recursively, with the exception of using a single [vwait] at global level to launch the event loop inside a shell that doesn't launch it automatically.

The commonest purposes for which I've seen [update] recommended are:

  1. Keeping the GUI alive while some long-running calculation is executing. See Countdown program for an alternative. 2) Waiting for a window to be configured before doing things like geometry management on it. The alternative is to bind on events such as that notify the process of a window's geometry. See Centering a window for an alternative.

What's wrong with update? There are several answers. First, it tends to complicate the code of the surrounding GUI. If you work the exercises in the Countdown program, you'll get a feel for how much easier it can be when each event is processed on its own callback. Second, it's a source of insidious bugs. The general problem is that executing [update] has nearly unconstrained side effects; on return from [update], a script can easily discover that the rug has been pulled out from under it. There's further discussion of this phenomenon over at Update considered harmful.

.....

Is there any chance I can make my program work without the while loop?

Yes, but things get a little tricky. You might think something like the following would work:

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        while True:
           self.canvas.move(self.id, 0, -1)

ball = Ball(canvas, "red")
ball.draw()
tk.mainloop()

The problem is that ball.draw() will cause execution to enter an infinite loop in the draw() method, so tk.mainloop() will never execute, and your widgets will never display. In gui programming, infinite loops have to be avoided at all costs in order to keep the widgets responsive to user input, e.g. mouse clicks.

So, the question is: how do you execute something over and over again without actually creating an infinite loop? Tkinter has an answer for that problem: a widget's after() method:

from Tkinter import *
import random
import time

tk = Tk()
tk.title = "Game"
tk.resizable(0,0)
tk.wm_attributes("-topmost", 1)

canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

    def draw(self):
        self.canvas.move(self.id, 0, -1)
        self.canvas.after(1, self.draw)  #(time_delay, method_to_execute)


       

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment
tk.mainloop()

The after() method doesn't block (it actually creates another thread of execution), so execution continues on in your python program after after() is called, which means tk.mainloop() executes next, so your widgets get configured and displayed. The after() method also allows your widgets to remain responsive to other user input. Try running the following program, and then click your mouse on different spots on the canvas:

from Tkinter import *
import random
import time

root = Tk()
root.title = "Game"
root.resizable(0,0)
root.wm_attributes("-topmost", 1)

canvas = Canvas(root, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

        self.canvas.bind("<Button-1>", self.canvas_onclick)
        self.text_id = self.canvas.create_text(300, 200, anchor='se')
        self.canvas.itemconfig(self.text_id, text='hello')

    def canvas_onclick(self, event):
        self.canvas.itemconfig(
            self.text_id, 
            text="You clicked at ({}, {})".format(event.x, event.y)
        )

    def draw(self):
        self.canvas.move(self.id, 0, -1)
        self.canvas.after(50, self.draw)


       

ball = Ball(canvas, "red")
ball.draw()  #Changed per Bryan Oakley's comment.
root.mainloop()

iFrame Height Auto (CSS)

 <div id="content" >
    <h1>Update Information</h1>
    <div id="support-box">
        <div id="wrapper">
            <iframe name="frame" id="frame" src="http://website.org/update.php" allowtransparency="true" frameborder="0"></iframe>
        </div>
    </div>
  </div>
 #support-box {
        width: 50%;
        float: left;
        display: block;
        height: 20rem; /* is support box height you can change as per your requirement*/
        background-color:#000;
    }
    #wrapper {
        width: 90%;
        display: block;
        position: relative;
        top: 50%;
        transform: translateY(-50%);
         background:#ddd;
       margin:auto;
       height:100px; /* here the height values are automatic you can leave this if you can*/

    }
    #wrapper iframe {
        width: 100%;
        display: block;
        padding:10px;
        margin:auto;
    }

https://jsfiddle.net/umd2ahce/1/

What is the use of "object sender" and "EventArgs e" parameters?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.

Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Example:

protected void btn_Click (object sender, EventArgs e){
   Button btn = sender as Button;
   btn.Text = "clicked!";
}

Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked

How to do an Integer.parseInt() for a decimal number?

use this one

int number = (int) Double.parseDouble(s);

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

Font-awesome provides a great solution out of the box:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />_x000D_
_x000D_
<ul class='fa-ul'>_x000D_
  <li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
  <li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Is there any way to set environment variables in Visual Studio Code?

For more advanced Go language scenarios, you can load an environment file, like this:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch",
      "type": "go",
      "request": "launch", 
      "mode": "debug",
      "remotePath": "",
      "port": 2345,
      "host": "127.0.0.1",
      "program": "${workspaceFolder}",
      "envFile": "${workspaceFolder}/.env",
      "args": [], 
      "showLog": true
    }
  ]
}

Place the .env file in your folder and add vars like this:

KEY1="TEXT_VAL1"
KEY2='{"key1":val1","key2":"val2"}'

Details: https://medium.com/@reuvenharrison/using-visual-studio-code-to-debug-a-go-program-with-environment-variables-523fea268271

Java dynamic array sizes?

Java Array sizes are fixed , You cannot make dynamic Arrays as that of in C++.

Initializing select with AngularJS and ng-repeat

Thanks to TheSharpieOne for pointing out the ng-selected option. If that had been posted as an answer rather than as a comment, I would have made that the correct answer.

Here's a working JSFiddle: http://jsfiddle.net/coverbeck/FxM3B/5/.

I also updated the fiddle to use the title attribute, which I had left out in my original post, since it wasn't the cause of the problem (but it is the reason I want to use ng-repeat instead of ng-options).

HTML:

<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator">
   <option ng-repeat="operator in operators" title="{{operator.title}}" ng-selected="{{operator.value == filterCondition.operator}}" value="{{operator.value}}">{{operator.displayName}}</option>
</select>
</body>

JS:

function AppCtrl($scope) {

    $scope.filterCondition={
        operator: 'eq'
    }

    $scope.operators = [
        {value: 'eq', displayName: 'equals', title: 'The equals operator does blah, blah'},
        {value: 'neq', displayName: 'not equal', title: 'The not equals operator does yada yada'}
     ]
}

How do I configure Apache 2 to run Perl CGI scripts?

As of Ubuntu 12.04 (Precise Pangolin) (and perhaps a release or two before) simply installing apache2 and mod-perl via Synaptic and placing your CGI scripts in /usr/lib/cgi-bin is really all you need to do.

How to get data out of a Node.js http get request

from learnyounode:

var http = require('http')  

http.get(options, function (response) {  
  response.setEncoding('utf8')  
  response.on('data', console.log)  
  response.on('error', console.error)  
})

'options' is the host/path variable

td widths, not working?

try this:

word-break: break-all;

How do I run Java .class files?

You have to put java in lower case and you have to add .class!

java HelloWorld2.class

Laravel view not found exception

In my case I had to run php artisan optimize:clear in order to make everything to work again.

Auto increment in phpmyadmin

Just run a simple MySQL query and set the auto increment number to whatever you want.

ALTER TABLE `table_name` AUTO_INCREMENT=10000

In terms of a maximum, as far as I am aware there is not one, nor is there any way to limit such number.

It is perfectly safe, and common practice to set an id number as a primiary key, auto incrementing int. There are alternatives such as using PHP to generate membership numbers for you in a specific format and then checking the number does not exist prior to inserting, however for me personally I'd go with the primary id auto_inc value.

Vertical align middle with Bootstrap responsive grid

.row {
    letter-spacing: -.31em;
    word-spacing: -.43em;
}
.col-md-4 {
    float: none;
    display: inline-block;
    vertical-align: middle;
}

Note: .col-md-4 could be any grid column, its just an example here.

How to override toString() properly in Java?

You can creating new object in the toString(). use

return "Name = " + this.name +" height= " + this.height;

instead of

return Kid(this.name, this.height, this.bDay);

You may change the return string as required. There are other ways to store date instead calander.

How to make a cross-module variable?

You can already do this with module-level variables. Modules are the same no matter what module they're being imported from. So you can make the variable a module-level variable in whatever module it makes sense to put it in, and access it or assign to it from other modules. It would be better to call a function to set the variable's value, or to make it a property of some singleton object. That way if you end up needing to run some code when the variable's changed, you can do so without breaking your module's external interface.

It's not usually a great way to do things — using globals seldom is — but I think this is the cleanest way to do it.

How to run html file on localhost?

On macOS:

Open Terminal (or iTerm) install Homebrew then run brew install live-server and run live-server.

You also can install Python 3 and run python3 -m http.server PORT.

On Windows:

If you have VS Code installed open it and install extension liveserver, then click Go Live in the bottom right corner.

Alternatively you can install WSL2 and follow the macOS steps via apt (sudo apt-get).

On Linux:

Open your favorite terminal emulator and follow the macOS steps via apt (sudo apt-get).

Integer value comparison

well i might be late on this but i would like to share something:

Given the input: System.out.println(isGreaterThanZero(-1));

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.compareTo(0) > 0;
}

Returns false

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.intValue() > 0;
}

Returns true So i think in yourcase 'compareTo' will be more accurate.

How to compare two lists in python?

for i in arr1:
    if i in arr2:
        return 1
    return  0
arr1=[1,2,5]
arr2=[2,4,15]
q=checkarrayequalornot(arr1,arr2)
print(q)
>>0

MySQL dump by query

You can dump a query as csv like this:

SELECT * from myTable
INTO OUTFILE '/tmp/querydump.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

Eclipse projects not showing up after placing project files in workspace/projects

Just because you have a project inside the workspace directory doesn't mean Eclipse opens it or even sees it automatically. You must use File - Import - General - Import existing project into workspace to have your project in Eclipse.

SQL Server SELECT into existing table

SELECT ... INTO ... only works if the table specified in the INTO clause does not exist - otherwise, you have to use:

INSERT INTO dbo.TABLETWO
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:

INSERT INTO dbo.TABLETWO
  (col1, col2)
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

How to query SOLR for empty fields?

One caveat! If you want to compose this via OR or AND you cannot use it in this form:

-myfield:*

but you must use

(*:* NOT myfield:*)

This form is perfectly composable. Apparently SOLR will expand the first form to the second, but only when it is a top node. Hope this saves you some time!

Adding an onclick event to a table row

Something like this.

function addRowHandlers() {
  var table = document.getElementById("tableId");
  var rows = table.getElementsByTagName("tr");
  for (i = 0; i < rows.length; i++) {
    var currentRow = table.rows[i];
    var createClickHandler = function(row) {
      return function() {
        var cell = row.getElementsByTagName("td")[0];
        var id = cell.innerHTML;
        alert("id:" + id);
      };
    };
    currentRow.onclick = createClickHandler(currentRow);
  }
}

EDIT

Working demo.

ModuleNotFoundError: What does it mean __main__ is not a package?

I have the same issue as you did. I think the problem is that you used relative import in in-package import. There is no __init__.py in your directory. So just import as Moses answered above.

The core issue I think is when you import with a dot:

from .p_02_paying_debt_off_in_a_year import compute_balance_after

It is equivalent to:

from __main__.p_02_paying_debt_off_in_a_year import compute_balance_after

where __main__ refers to your current module p_03_using_bisection_search.py.


Briefly, the interpreter does not know your directory architecture.

When the interpreter get in p_03.py, the script equals:

from p_03_using_bisection_search.p_02_paying_debt_off_in_a_year import compute_balance_after

and p_03_using_bisection_search does not contain any modules or instances called p_02_paying_debt_off_in_a_year.


So I came up with a cleaner solution without changing python environment valuables (after looking up how requests do in relative import):

The main architecture of the directory is:

main.py
setup.py
problem_set_02/
   __init__.py
   p01.py
   p02.py
   p03.py

Then write in __init__.py:

from .p_02_paying_debt_off_in_a_year import compute_balance_after

Here __main__ is __init__ , it exactly refers to the module problem_set_02.

Then go to main.py:

import problem_set_02

You can also write a setup.py to add specific module to the environment.

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

How to insert a blob into a database using sql server management studio

There are two ways to SELECT a BLOB with TSQL:

SELECT * FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a

As well as:

SELECT BulkColumn FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a

Note the correlation name after the FROM clause, which is mandatory.

You can then this to INSERT by doing an INSERT SELECT.

You can also use the second version to do an UPDATE as I described in How To Update A BLOB In SQL SERVER Using TSQL .

What's the difference between returning value or Promise.resolve from then()

You already got a good formal answer. I figured I should add a short one.

The following things are identical with Promises/A+ promises:

  • Calling Promise.resolve (In your Angular case that's $q.when)
  • Calling the promise constructor and resolving in its resolver. In your case that's new $q.
  • Returning a value from a then callback.
  • Calling Promise.all on an array with a value and then extract that value.

So the following are all identical for a promise or plain value X:

Promise.resolve(x);
new Promise(function(resolve, reject){ resolve(x); });
Promise.resolve().then(function(){ return x; });
Promise.all([x]).then(function(arr){ return arr[0]; });

And it's no surprise, the promises specification is based on the Promise Resolution Procedure which enables easy interoperation between libraries (like $q and native promises) and makes your life overall easier. Whenever a promise resolution might occur a resolution occurs creating overall consistency.

Why use @Scripts.Render("~/bundles/jquery")

Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.

As example you could create your own bundle:

bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
            "~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
            "~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))

And render it like this:

@Scripts.Render("~/bundles/mybundle")

One more advantage of @Scripts.Render("~/bundles/mybundle") over the native <script src="~/bundles/mybundle" /> is that @Scripts.Render() will respect the web.config debug setting:

  <system.web>
    <compilation debug="true|false" />

If debug="true" then it will instead render individual script tags for each source script, without any minification.

For stylesheets you will have to use a StyleBundle and @Styles.Render().

Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.

Decoding a Base64 string in Java

The following should work with the latest version of Apache common codec

byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));

and for encoding

byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));

Postgresql 9.2 pg_dump version mismatch

Try that:

export PATH=/usr/local/bin:$PATH

Convert bytes to a string

def toString(string):    
    try:
        return v.decode("utf-8")
    except ValueError:
        return string

b = b'97.080.500'
s = '97.080.500'
print(toString(b))
print(toString(s))

Session TimeOut in web.xml

To set a session-timeout that never expires is not desirable because you would be reliable on the user to push the logout-button every time he's finished to prevent your server of too much load (depending on the amount of users and the hardware). Additionaly there are some security issues you might run into you would rather avoid.

The reason why the session gets invalidated while the server is still working on a task is because there is no communication between client-side (users browser) and server-side through e.g. a http-request. Therefore the server can't know about the users state, thinks he's idling and invalidates the session after the time set in your web.xml.

To get around this you have several possibilities:

  • You could ping your backend while the task is running to touch the session and prevent it from being expired
  • increase the <session-timeout> inside the server but I wouldn't recommend this
  • run your task in a dedicated thread which touches (extends) the session while working or notifies the user when the thread has finished

There was a similar question asked, maybe you can adapt parts of this solution in your project. Have a look at this.

Hope this helps, have Fun!

Convert list to array in Java

You can use toArray() api as follows,

ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);

Values from the array are,

for(String value : stringList)
{
    System.out.println(value);
}

showing that a date is greater than current date

Select * from table where date > 'Today's date(mm/dd/yyyy)'

You can also add time in the single quotes(00:00:00AM)

For example:

Select * from Receipts where Sales_date > '08/28/2014 11:59:59PM'

PHP - Move a file into a different folder on the server

use copy() and unlink() function

$moveFile="path/filename";
if (copy($csvFile,$moveFile)) 
{
  unlink($csvFile);
}

How to have multiple CSS transitions on an element?

Transition properties are comma delimited in all browsers that support transitions:

.nav a {
  transition: color .2s, text-shadow .2s;
}

ease is the default timing function, so you don't have to specify it. If you really want linear, you will need to specify it:

transition: color .2s linear, text-shadow .2s linear;

This starts to get repetitive, so if you're going to be using the same times and timing functions across multiple properties it's best to go ahead and use the various transition-* properties instead of the shorthand:

transition-property: color, text-shadow;
transition-duration: .2s;
transition-timing-function: linear;

milliseconds to days

public static final long SECOND_IN_MILLIS = 1000;
public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
public static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
public static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
public static final long WEEK_IN_MILLIS = DAY_IN_MILLIS * 7;

You could cast int but I would recommend using long.

How to check if an element of a list is a list (in Python)?

  1. Work out what specific properties of a list you want the items to have. Do they need to be indexable? Sliceable? Do they need an .append() method?

  2. Look up the abstract base class which describes that particular type in the collections module.

  3. Use isinstance:

    isinstance(x, collections.MutableSequence)
    

You might ask "why not just use type(x) == list?" You shouldn't do that, because then you won't support things that look like lists. And part of the Python mentality is duck typing:

I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck

In other words, you shouldn't require that the objects are lists, just that they have the methods you will need. The collections module provides a bunch of abstract base classes, which are a bit like Java interfaces. Any type that is an instance of collections.Sequence, for example, will support indexing.

Remove by _id in MongoDB console

The answer is that the web console/shell at mongodb.org behaves differently and not as I expected it to. An installed version at home worked perfectly without problem ie; the auto generated _id on the web shell was saved like this :

"_id" : { "$oid" : "4d512b45cc9374271b02ec4f" },

The same document setup at home and the auto generated _id was saved like this :

"_id" : ObjectId("4d5192665777000000005490")

Queries worked against the latter without problem.

How to multiply all integers inside list

Try a list comprehension:

l = [x * 2 for x in l]

This goes through l, multiplying each element by two.

Of course, there's more than one way to do it. If you're into lambda functions and map, you can even do

l = map(lambda x: x * 2, l)

to apply the function lambda x: x * 2 to each element in l. This is equivalent to:

def timesTwo(x):
    return x * 2

l = map(timesTwo, l)

Note that map() returns a map object, not a list, so if you really need a list afterwards you can use the list() function afterwards, for instance:

l = list(map(timesTwo, l))

Thanks to Minyc510 in the comments for this clarification.

jQuery: Adding two attributes via the .attr(); method

Something like this:

$(myObj).attr({"data-test-1": num1, "data-test-2": num2});

Android: show/hide status bar/power bar

with this method, using SYSTEM_UI_FLAG_IMMERSIVE_STICKY the full screen come back with one tap without any implementation. Just copy past this method below and call it where you want in your activity. More details here

private void hideSystemUI() {
    getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
                    // Set the content to appear under the system bars so that the
                    // content doesn't resize when the system bars hide and show.
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    // Hide the nav bar and status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

Button inside of anchor link works in Firefox but not in Internet Explorer?

Why not just convert all <button> to <span> with type="button" and then style with your normal css button classes? Just confirmed that this works in IE11.

How to auto adjust the <div> height according to content in it?

Most of these are great answers, but I feel that they are leaving out one inevitable aspect of web-development which is the on-going page update. What if you want to come and add content to this div? Should you always come to adjust the div min-height? Well, whilst trying to answer these two questions, I tried out the following code instead:

.box-centerside {
  background: url("../images/greybox-center-bg1.jpg") repeat-x scroll center top transparent;
  float: left;
  height: auto; /* adjusts height container element according to content */
  width: 260px;
}

furthermore, just for a sort of bonus , if you have elements around this div with properties like position: relative; , they would consequently stack on top of this div, because it has property float: left; To avoid such stacking, I tried the following code:

.parent {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* number depends on how many columns you want for a particular screen width. */
  height: auto; /* adjusts height container element according to content */
}

.box-centerside {
  background: url("../images/greybox-center-bg1.jpg") repeat-x scroll center top transparent;
  height: auto; /* adjusts height container element according to content */
  width: 100%;
}

.sibling 1 {
  /* Code here */
}

.sibling 2 {
  /* Code here */
}

My opinion is that, I find this grid method of displaying more fitting for a responsive website. Otherwise, there are many ways of achieving the same goals; But some of the important goals of programming are to make coding simpler and more readable as well as easier to understand.

How to decode JWT Token?

I found the solution, I just forgot to Cast the result:

var stream ="[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = handler.ReadToken(stream) as JwtSecurityToken;

I can get Claims using:

var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value;

How to get C# Enum description from value?

int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);

The default underlying data type for an enum in C# is an int, you can just cast it.

Get output parameter value in ADO.NET

For anyone looking to do something similar using a reader with the stored procedure, note that the reader must be closed to retrieve the output value.

using (SqlConnection conn = new SqlConnection())
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add parameters
    SqlParameter outputParam = cmd.Parameters.Add("@ID", SqlDbType.Int);
    outputParam.Direction = ParameterDirection.Output;

    conn.Open();

    using(IDataReader reader = cmd.ExecuteReader())
    {
        while(reader.Read())
        {
            //read in data
        }
    }
    // reader is closed/disposed after exiting the using statement
    int id = outputParam.Value;
}

Regex - Does not contain certain Characters

Here you go:

^[^<>]*$

This will test for string that has no < and no >

If you want to test for a string that may have < and >, but must also have something other you should use just

[^<>] (or ^.*[^<>].*$)

Where [<>] means any of < or > and [^<>] means any that is not of < or >.

And of course the mandatory link.

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

fatal error: iostream.h no such file or directory

That header doesn't exist in standard C++. It was part of some pre-1990s compilers, but it is certainly not part of C++.

Use #include <iostream> instead. And all the library classes are in the std:: namespace, for ex­am­ple std::cout.

Also, throw away any book or notes that mention the thing you said.

Else clause on Python while statement

The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won't be executed.

One way to think about it is as an if/else construct with respect to the condition:

if condition:
    handle_true()
else:
    handle_false()

is analogous to the looping construct:

while condition:
    handle_true()
else:
    # condition is false now, handle and go on with the rest of the program
    handle_false()

An example might be along the lines of:

while value < threshold:
    if not process_acceptable_value(value):
        # something went wrong, exit the loop; don't pass go, don't collect 200
        break
    value = update(value)
else:
    # value >= threshold; pass go, collect 200
    handle_threshold_reached()

Android: failed to convert @drawable/picture into a drawable

Also check if the resource-name contains any illegal characters (for me it was a "-" in my-image)

iText - add content to existing PDF file

Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, 
        new FileOutputStream("E:/TextFieldForm.pdf"));
    document.open();

    PdfPTable table = new PdfPTable(2);
    table.getDefaultCell().setPadding(5f); // Code 1
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    PdfPCell cell;      

    // Code 2, add name TextField       
    table.addCell("Name"); 
    TextField nameField = new TextField(writer, 
        new Rectangle(0,0,200,10), "nameField");
    nameField.setBackgroundColor(Color.WHITE);
    nameField.setBorderColor(Color.BLACK);
    nameField.setBorderWidth(1);
    nameField.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    nameField.setText("");
    nameField.setAlignment(Element.ALIGN_LEFT);
    nameField.setOptions(TextField.REQUIRED);               
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(nameField.getTextField(), 
        200, writer));
    table.addCell(cell);

    // force upper case javascript
    writer.addJavaScript(
        "var nameField = this.getField('nameField');" +
        "nameField.setAction('Keystroke'," +
        "'forceUpperCase()');" +
        "" +
        "function forceUpperCase(){" +
        "if(!event.willCommit)event.change = " +
        "event.change.toUpperCase();" +
        "}");


    // Code 3, add empty row
    table.addCell("");
    table.addCell("");


    // Code 4, add age TextField
    table.addCell("Age");
    TextField ageComb = new TextField(writer, new Rectangle(0,
         0, 30, 10), "ageField");
    ageComb.setBorderColor(Color.BLACK);
    ageComb.setBorderWidth(1);
    ageComb.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    ageComb.setText("12");
    ageComb.setAlignment(Element.ALIGN_RIGHT);
    ageComb.setMaxCharacterLength(2);
    ageComb.setOptions(TextField.COMB | 
        TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(10);
    cell.setCellEvent(new FieldCell(ageComb.getTextField(), 
        30, writer));
    table.addCell(cell);

    // validate age javascript
    writer.addJavaScript(
        "var ageField = this.getField('ageField');" +
        "ageField.setAction('Validate','checkAge()');" +
        "function checkAge(){" +
        "if(event.value < 12){" +
        "app.alert('Warning! Applicant\\'s age can not" +
        " be younger than 12.');" +
        "event.value = 12;" +
        "}}");      



    // add empty row
    table.addCell("");
    table.addCell("");


    // Code 5, add age TextField
    table.addCell("Comment");
    TextField comment = new TextField(writer, 
        new Rectangle(0, 0,200, 100), "commentField");
    comment.setBorderColor(Color.BLACK);
    comment.setBorderWidth(1);
    comment.setBorderStyle(PdfBorderDictionary.STYLE_SOLID);
    comment.setText("");
    comment.setOptions(TextField.MULTILINE | 
        TextField.DO_NOT_SCROLL);
    cell = new PdfPCell();
    cell.setMinimumHeight(100);
    cell.setCellEvent(new FieldCell(comment.getTextField(), 
        200, writer));
    table.addCell(cell);


    // check comment characters length javascript
    writer.addJavaScript(
        "var commentField = " +
        "this.getField('commentField');" +
        "commentField" +
        ".setAction('Keystroke','checkLength()');" +
        "function checkLength(){" +
        "if(!event.willCommit && " +
        "event.value.length > 100){" +
        "app.alert('Warning! Comment can not " +
        "be more than 100 characters.');" +
        "event.change = '';" +
        "}}");          

    // add empty row
    table.addCell("");
    table.addCell("");


    // Code 6, add submit button    
    PushbuttonField submitBtn = new PushbuttonField(writer,
            new Rectangle(0, 0, 35, 15),"submitPOST");
    submitBtn.setBackgroundColor(Color.GRAY);
    submitBtn.
        setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
    submitBtn.setText("POST");
    submitBtn.setOptions(PushbuttonField.
        VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField submitField = submitBtn.getField();
    submitField.setAction(PdfAction
    .createSubmitForm("",null, PdfAction.SUBMIT_HTML_FORMAT));

    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(submitField, 35, writer));
    table.addCell(cell);



    // Code 7, add reset button
    PushbuttonField resetBtn = new PushbuttonField(writer,
            new Rectangle(0, 0, 35, 15), "reset");
    resetBtn.setBackgroundColor(Color.GRAY);
    resetBtn.setBorderStyle(
        PdfBorderDictionary.STYLE_BEVELED);
    resetBtn.setText("RESET");
    resetBtn
    .setOptions(
        PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField resetField = resetBtn.getField();
    resetField.setAction(PdfAction.createResetForm(null, 0));
    cell = new PdfPCell();
    cell.setMinimumHeight(15);
    cell.setCellEvent(new FieldCell(resetField, 35, writer));
    table.addCell(cell);        

    document.add(table);
    document.close();
}


class FieldCell implements PdfPCellEvent{

    PdfFormField formField;
    PdfWriter writer;
    int width;

    public FieldCell(PdfFormField formField, int width, 
        PdfWriter writer){
        this.formField = formField;
        this.width = width;
        this.writer = writer;
    }

    public void cellLayout(PdfPCell cell, Rectangle rect, 
        PdfContentByte[] canvas){
        try{
            // delete cell border
            PdfContentByte cb = canvas[PdfPTable
                .LINECANVAS];
            cb.reset();

            formField.setWidget(
                new Rectangle(rect.left(), 
                    rect.bottom(), 
                    rect.left()+width, 
                    rect.top()), 
                    PdfAnnotation
                    .HIGHLIGHT_NONE);

            writer.addAnnotation(formField);
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

I had the same issue, and solved it by adding 'mavenCentral()' to build.gradle(Project)

allprojects {
    repositories {
        ...
        mavenCentral()
    }
}

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

When I used the code mysqld_safe --skip-grant-tables & but I get the error:

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.

$ systemctl stop  mysql.service
$ ps -eaf|grep mysql
$ mysqld_safe --skip-grant-tables &

I solved:

$ mkdir -p /var/run/mysqld
$ chown mysql:mysql /var/run/mysqld

Now I use the same code mysqld_safe --skip-grant-tables & and get

mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

If I use $ mysql -u root I'll get :

Server version: 5.7.18-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Now time to change password:

mysql> use mysql
mysql> describe user;

Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

Database changed

mysql> FLUSH PRIVILEGES;
mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('newpwd');

or If you have a mysql root account that can connect from everywhere, you should also do:

UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

Alternate Method:

   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')
   WHERE Host = 'localhost' AND User = 'root';

And if you have a root account that can access from everywhere:

 USE mysql
 UPDATE user SET Password = PASSWORD('newpwd')
 WHERE Host = '%' AND User = 'root';`enter code here

now need to quit from mysql and stop/start

FLUSH PRIVILEGES;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

now again ` mysql -u root -p' and use the new password to get

mysql>

Connecting to TCP Socket from browser using javascript

This will be possible via the navigator interface as shown below:

navigator.tcpPermission.requestPermission({remoteAddress:"127.0.0.1", remotePort:6789}).then(
  () => {
    // Permission was granted
    // Create a new TCP client socket and connect to remote host
    var mySocket = new TCPSocket("127.0.0.1", 6789);

    // Send data to server
    mySocket.writeable.write("Hello World").then(
        () => {

            // Data sent sucessfully, wait for response
            console.log("Data has been sent to server");
            mySocket.readable.getReader().read().then(
                ({ value, done }) => {
                    if (!done) {
                        // Response received, log it:
                        console.log("Data received from server:" + value);
                    }

                    // Close the TCP connection
                    mySocket.close();
                }
            );
        },
        e => console.error("Sending error: ", e)
    );
  }
);

More details are outlined in the w3.org tcp-udp-sockets documentation.

http://raw-sockets.sysapps.org/#interface-tcpsocket

https://www.w3.org/TR/tcp-udp-sockets/

Another alternative is to use Chrome Sockets

Creating connections

chrome.sockets.tcp.create({}, function(createInfo) {
  chrome.sockets.tcp.connect(createInfo.socketId,
    IP, PORT, onConnectedCallback);
});

Sending data

chrome.sockets.tcp.send(socketId, arrayBuffer, onSentCallback);

Receiving data

chrome.sockets.tcp.onReceive.addListener(function(info) {
  if (info.socketId != socketId)
    return;
  // info.data is an arrayBuffer.
});

You can use also attempt to use HTML5 Web Sockets (Although this is not direct TCP communication):

var connection = new WebSocket('ws://IPAddress:Port');

connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server
};

http://www.html5rocks.com/en/tutorials/websockets/basics/

Your server must also be listening with a WebSocket server such as pywebsocket, alternatively you can write your own as outlined at Mozilla

Attach to a processes output for viewing

You can use reptyr:

sudo apt install reptyr
reptyr pid

Generate an HTML Response in a Java Servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}

First Heroku deploy failed `error code=H10`

The H10 error code could mean many different things. In my case, the first time was because I didn't know that Heroku isn't compatible with Sqlite3, the second time was because I accidentally pushed an update with Google analytics working in development as well as production.

How to load external webpage in WebView

Add below method in your activity class.Here browser is nothing but your webview object.

Now you can view web contain page wise easily.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && browser.canGoBack()) {
        browser.goBack();
        return true;
    }
    return false;
}

Plot logarithmic axes with matplotlib in python

You can use the Axes.set_yscale method. That allows you to change the scale after the Axes object is created. That would also allow you to build a control to let the user pick the scale if you needed to.

The relevant line to add is:

ax.set_yscale('log')

You can use 'linear' to switch back to a linear scale. Here's what your code would look like:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)

ax.set_yscale('log')

pylab.show()

result chart

Easy way to password-protect php page

I would simply look for a $_GET variable and redirect the user if it's not correct.

<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
  header('Location: http://www.staggeringbeauty.com/');
}
?>

Now, if this page is located at say: http://example.com/secrets/files.php

You can now access it with: http://example.com/secrets/files.php?pass=my-secret-password Keep in mind that this isn't the most efficient or secure way, but nonetheless it is a easy and fast way. (Also, I know my answer is outdated but someone else looking at this question may find it valuable)

parseInt with jQuery

Two issues:

  1. You're passing the jQuery wrapper of the element into parseInt, which isn't what you want, as parseInt will call toString on it and get back "[object Object]". You need to use val or text or something (depending on what the element is) to get the string you want.

  2. You're not telling parseInt what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt guesses which radix to use.

Fix if the element is a form field:

//                               vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
//                                    ^^^^-- tell parseInt to use decimal (base 10)

Fix if the element is something else and you want to use the text within it:

//                               vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
//                                     ^^^^-- tell parseInt to use decimal (base 10)

How to scroll up or down the page to an anchor using jQuery?

I stumbled upon this example on https://css-tricks.com/snippets/jquery/smooth-scrolling/ explaining every line of code. I found this to be the best option.

https://css-tricks.com/snippets/jquery/smooth-scrolling/

You can go native:

window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth' 
});

window.scrollBy({ 
  top: 100, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});

or with jquery:

$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function(event) {

    if (
        location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
        && location.hostname == this.hostname
       ) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');

      if (target.length) {
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
      }
    }
  });

Selecting only first-level elements in jquery

Once you have the initial ul, you can use the children() method, which will only consider the immediate children of the element. As @activa points out, one way to easily select the root element is to give it a class or an id. The following assumes you have a root ul with id root.

$('ul#root').children('li');

How to connect to a remote Git repository?

It's simple and follow the small Steps to proceed:

  • Install git on the remote server say some ec2 instance
  • Now create a project folder `$mkdir project.git
  • $cd project and execute $git init --bare

Let's say this project.git folder is present at your ip with address inside home_folder/workspace/project.git, forex- ec2 - /home/ubuntu/workspace/project.git

Now in your local machine, $cd into the project folder which you want to push to git execute the below commands:

  • git init .

  • git remote add origin [email protected]:/home/ubuntu/workspace/project.git

  • git add .
  • git commit -m "Initial commit"

Below is an optional command but found it has been suggested as i was working to setup the same thing

git config --global remote.origin.receivepack "git receive-pack"

  • git pull origin master
  • git push origin master

This should work fine and will push the local code to the remote git repository.

To check the remote fetch url, cd project_folder/.git and cat config, this will give the remote url being used for pull and push operations.

You can also use an alternative way, after creating the project.git folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.

Ruby: How to convert a string to boolean

A gem like https://rubygems.org/gems/to_bool can be used, but it can easily be written in one line using a regex or ternary.

regex example:

boolean = (var.to_s =~ /^true$/i) == 0

ternary example:

boolean = var.to_s.eql?('true') ? true : false

The advantage to the regex method is that regular expressions are flexible and can match a wide variety of patterns. For example, if you suspect that var could be any of "True", "False", 'T', 'F', 't', or 'f', then you can modify the regex:

boolean = (var.to_s =~ /^[Tt].*$/i) == 0

Java better way to delete file if exists

  File xx = new File("filename.txt");
    if (xx.exists()) {
       System.gc();//Added this part
       Thread.sleep(2000);////This part gives the Bufferedreaders and the InputStreams time to close Completely
       xx.delete();     
    }

HTML Table different number of columns in different rows

On the realisation that you're unfamiliar with colspan, I presumed you're also unfamiliar with rowspan, so I thought I'd throw that in for free.

One important point to note, when using rowspan: the following tr elements must contain fewer td elements, because of the cells using rowspan in the previous row (or previous rows).

_x000D_
_x000D_
table {_x000D_
  border: 1px solid #000;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th colspan="2">Column one and two</th>_x000D_
      <th>Column three</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td rowspan="2" colspan="2">A large cell</td>_x000D_
      <td>a smaller cell</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <!-- note that this row only has _one_ td, since the preceding row_x000D_
                     takes up some of this row -->_x000D_
      <td>Another small cell</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

When correctly use Task.Run and when just async-await

Note the guidelines for performing work on a UI thread, collected on my blog:

  • Don't block the UI thread for more than 50ms at a time.
  • You can schedule ~100 continuations on the UI thread per second; 1000 is too much.

There are two techniques you should use:

1) Use ConfigureAwait(false) when you can.

E.g., await MyAsync().ConfigureAwait(false); instead of await MyAsync();.

ConfigureAwait(false) tells the await that you do not need to resume on the current context (in this case, "on the current context" means "on the UI thread"). However, for the rest of that async method (after the ConfigureAwait), you cannot do anything that assumes you're in the current context (e.g., update UI elements).

For more information, see my MSDN article Best Practices in Asynchronous Programming.

2) Use Task.Run to call CPU-bound methods.

You should use Task.Run, but not within any code you want to be reusable (i.e., library code). So you use Task.Run to call the method, not as part of the implementation of the method.

So purely CPU-bound work would look like this:

// Documentation: This method is CPU-bound.
void DoWork();

Which you would call using Task.Run:

await Task.Run(() => DoWork());

Methods that are a mixture of CPU-bound and I/O-bound should have an Async signature with documentation pointing out their CPU-bound nature:

// Documentation: This method is CPU-bound.
Task DoWorkAsync();

Which you would also call using Task.Run (since it is partially CPU-bound):

await Task.Run(() => DoWorkAsync());

Display PNG image as response to jQuery AJAX request

You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php

Then in your ajax call change the success function to this:

$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');

Visual Studio 2010 always thinks project is out of date, but nothing has changed

I had this problem and found this:

http://curlybrace.blogspot.com/2005/11/visual-c-project-continually-out-of.html

Visual C++ Project continually out-of-date (winwlm.h macwin32.h rpcerr.h macname1.h missing)

Problem:

In Visual C++ .Net 2003, one of my projects always claimed to be out of date, even though nothing had changed and no errors had been reported in the last build.

Opening the BuildLog.htm file for the corresponding project showed a list of PRJ0041 errors for these files, none of which appear on my system anywhere: winwlm.h macwin32.h rpcerr.h macname1.h

Each error looks something like this:

  MyApplication : warning PRJ0041 : Cannot find missing dependency 'macwin32.h' for file 'MyApplication.rc'.  

Your project may still build, but may continue to appear out of date until this file is found.

Solution:

Include afxres.h instead of resource.h inside the project's .rc file.

The project's .rc file contained "#include resource.h". Since the resource compiler does not honor preprocessor #ifdef blocks, it will tear through and try to find include files it should be ignoring. Windows.h contains many such blocks. Including afxres.h instead fixed the PRJ0041 warnings and eliminated the "Project is out-of-date" error dialog.

Check if my SSL Certificate is SHA1 or SHA2

I had to modify this slightly to be used on a Windows System. Here's the one-liner version for a windows box.

openssl.exe s_client -connect yoursitename.com:443 > CertInfo.txt && openssl x509 -text -in CertInfo.txt | find "Signature Algorithm" && del CertInfo.txt /F

Tested on Server 2012 R2 using http://iweb.dl.sourceforge.net/project/gnuwin32/openssl/0.9.8h-1/openssl-0.9.8h-1-bin.zip

convert php date to mysql format

$date = mysql_real_escape_string($_POST['intake_date']);

1. If your MySQL column is DATE type:

$date = date('Y-m-d', strtotime(str_replace('-', '/', $date)));

2. If your MySQL column is DATETIME type:

$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));

You haven't got to work strototime(), because it will not work with dash - separators, it will try to do a subtraction.


Update, the way your date is formatted you can't use strtotime(), use this code instead:

$date = '02/07/2009 00:07:00';
$date = preg_replace('#(\d{2})/(\d{2})/(\d{4})\s(.*)#', '$3-$2-$1 $4', $date);
echo $date;

Output:

2009-07-02 00:07:00

PHP check if date between two dates

function get_format($df) {

    $str = '';
    $str .= ($df->invert == 1) ? ' - ' : '';
    if ($df->y > 0) {
        // years
        $str .= ($df->y > 1) ? $df->y . ' Years ' : $df->y . ' Year ';
    } if ($df->m > 0) {
        // month
        $str .= ($df->m > 1) ? $df->m . ' Months ' : $df->m . ' Month ';
    } if ($df->d > 0) {
        // days
        $str .= ($df->d > 1) ? $df->d . ' Days ' : $df->d . ' Day ';
    } 

    echo $str;
}

$yr=$year;
$dates=$dor;
$myyear='+'.$yr.' years';
$new_date = date('Y-m-d', strtotime($myyear, strtotime($dates)));
$date1 = new DateTime("$new_date");
$date2 = new DateTime("now");
$diff = $date2->diff($date1);

"The Controls collection cannot be modified because the control contains code blocks"

I also faced the same issue. I found the solutions like following.

Solution 1: I kept my script tag in the body.

<body>
   <form> . . . .  </form>
    <script type="text/javascript" src="<%= My.Working.Common.Util.GetSiteLocation()%>Scripts/Common.js"></script> </body>

Now conflicts regarding the tags will resolve.

Solution 2:

We can also solve this one of the above solutions like Replace the code block with <%# instead of <%= But the problem is it will give only relative path. If you want really absolute path it won't work.

Solution 1 works for me. Next is your choice.

Python convert csv to xlsx

There is a simple way

import os
import csv
import sys

from openpyxl import Workbook

reload(sys)
sys.setdefaultencoding('utf8')

if __name__ == '__main__':
    workbook = Workbook()
    worksheet = workbook.active
    with open('input.csv', 'r') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                for idx, val in enumerate(col.split(',')):
                    cell = worksheet.cell(row=r+1, column=c+1)
                    cell.value = val
    workbook.save('output.xlsx')

How do I preserve line breaks when getting text from a textarea?

The easiest solution is to simply style the element you're inserting the text into with the following CSS property:

white-space: pre-wrap;

This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).

Given that several of the answers posted here so far have been vulnerable to HTML injection (e.g. because they assign unescaped user input to innerHTML) or otherwise buggy, let me give an example of how to do this safely and correctly, based on your original code:

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.append(postText);_x000D_
  var card = document.createElement('div');_x000D_
  card.append(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.prepend(card);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_


Note that, like your original code, the snippet above uses append() and prepend(). As of this writing, those functions are still considered experimental and not fully supported by all browsers. If you want to be safe and remain compatible with older browsers, you can substitute them pretty easily as follows:

  • element.append(otherElement) can be replaced with element.appendChild(otherElement);
  • element.prepend(otherElement) can be replaced with element.insertBefore(otherElement, element.firstChild);
  • element.append(stringOfText) can be replaced with element.appendChild(document.createTextNode(stringOfText));
  • element.prepend(stringOfText) can be replaced with element.insertBefore(document.createTextNode(stringOfText), element.firstChild);
  • as a special case, if element is empty, both element.append(stringOfText) and element.prepend(stringOfText) can simply be replaced with element.textContent = stringOfText.

Here's the same snippet as above, but without using append() or prepend():

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.textContent = postText;_x000D_
  var card = document.createElement('div');_x000D_
  card.appendChild(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_


Ps. If you really want to do this without using the CSS white-space property, an alternative solution would be to explicitly replace any newline characters in the text with <br> HTML tags. The tricky part is that, to avoid introducing subtle bugs and potential security holes, you have to first escape any HTML metacharacters (at a minimum, & and <) in the text before you do this replacement.

Probably the simplest and safest way to do that is to let the browser handle the HTML-escaping for you, like this:

var post = document.createElement('p');
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.textContent = postText;_x000D_
  post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');  // <-- THIS FIXES THE LINE BREAKS_x000D_
  var card = document.createElement('div');_x000D_
  card.appendChild(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_

Note that, while this will fix the line breaks, it won't prevent consecutive whitespace from being collapsed by the HTML renderer. It's possible to (sort of) emulate that by replacing some of the whitespace in the text with non-breaking spaces, but honestly, that's getting rather complicated for something that can be trivially solved with a single line of CSS.

How to merge a list of lists with same type of items to a single list of items?

Use the SelectMany extension method

list = listOfList.SelectMany(x => x).ToList();

How to get only the date value from a Windows Forms DateTimePicker control?

@Shoban It looks like the question is tagged c# so here is the appropriate snipped http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx

public MyClass()
{
    // Create a new DateTimePicker
    DateTimePicker dateTimePicker1 = new DateTimePicker();
    Controls.Add(dateTimePicker1);
    MessageBox.Show(dateTimePicker1.Value.ToString());

    dateTimePicker1.Value = DateTime.Now.AddDays(1);
    MessageBox.Show(dateTimePicker1.Value.ToString());
 } 

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

Ran into the same problem and at first defragmenting seemed to work. But it was for just a short while. Turns out the server the customer was using, was running the Express version and that has a licensing limit of about 10gb.

So even though the size was set to "unlimited", it wasn't.

Read only the first line of a file?

This should do it:

f = open('myfile.txt')
first = f.readline()

Using Html.ActionLink to call action on different controller

With that parameters you're triggering the wrong overloaded function/method.

What worked for me:

<%= Html.ActionLink("Details", "Details", "Product", new { id=item.ID }, null) %>

It fires HtmlHelper.ActionLink(string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)

I'm using MVC 4.

Cheerio!

Visualizing decision tree in scikit-learn

I copy and change a part of your code as the below:

from pandas import read_csv, DataFrame
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from os import system

data = read_csv('D:/training.csv')
Y = data.Y
X = data.ix[:,"X0":"X33"]

dtree = tree.DecisionTreeClassifier(criterion = "entropy")
dtree = dtree.fit(X, Y)

After making sure you have dtree, which means that the above code runs well, you add the below code to visualize decision tree:

Remember to install graphviz first: pip install graphviz

import graphviz 
from graphviz import Source
dot_data = tree.export_graphviz(dtree, out_file=None, feature_names=X.columns)
graph = graphviz.Source(dot_data) 
graph.render("name of file",view = True)

I tried with my data, visualization worked well and I got a pdf file viewed immediately.

Python - Locating the position of a regex match in a string?

You could use .find("is"), it would return position of "is" in the string

or use .start() from re

>>> re.search("is", String).start()
2

Actually its match "is" from "This"

If you need to match per word, you should use \b before and after "is", \b is the word boundary.

>>> re.search(r"\bis\b", String).start()
5
>>>

for more info about python regular expressions, docs here

adb not finding my device / phone (MacOS X)

Tried all the above, the last piece missing was to enable USB Debugging within Developer Options which was hidden on my 4.4 Galaxy Note 10.1.

See item 5.2 from this link.

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))

PHP: date function to get month of the current date

As it's not specified if you mean the system's current date or the date held in a variable, I'll answer for latter with an example.

<?php
$dateAsString = "Wed, 11 Apr 2018 19:00:00 -0500";

// This converts it to a unix timestamp so that the date() function can work with it.
$dateAsUnixTimestamp = strtotime($dateAsString);

// Output it month is various formats according to http://php.net/date

echo date('M',$dateAsUnixTimestamp);
// Will output Apr

echo date('n',$dateAsUnixTimestamp);
// Will output 4

echo date('m',$dateAsUnixTimestamp);
// Will output 04
?>

Java ArrayList Index

In order to store Strings in an dynamic array (add-method) you can't define it as an array of integers ( int[3] ). You should declare it like this:

ArrayList<String> alist = new ArrayList<String>();
alist.add("apple"); 
alist.add("banana"); 
alist.add("orange"); 

System.out.println( alist.get(1) );

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

Rails 4.0.0 will look image defined with image-url in same directory structure with your css file.

For example, if your css in assets/stylesheets/main.css.scss, image-url('logo.png') becomes url(/assets/logo.png).

If you move your css file to assets/stylesheets/cpanel/main.css.scss, image-url('logo.png') becomes /assets/cpanel/logo.png.

If you want to use image directly under assets/images directory, you can use asset-url('logo.png')

Selenium using Python - Geckodriver executable needs to be in PATH

I've actually discovered you can use the latest geckodriver without putting it in the system path. Currently I'm using

https://github.com/mozilla/geckodriver/releases/download/v0.12.0/geckodriver-v0.12.0-win64.zip

Firefox 50.1.0

Python 3.5.2

Selenium 3.0.2

Windows 10

I'm running a VirtualEnv (which I manage using PyCharm, and I assume it uses Pip to install everything).

In the following code I can use a specific path for the geckodriver using the executable_path parameter (I discovered this by having a look in Lib\site-packages\selenium\webdriver\firefox\webdriver.py ). Note I have a suspicion that the order of parameter arguments when calling the webdriver is important, which is why the executable_path is last in my code (the second to last line off to the far right).

You may also notice I use a custom Firefox profile to get around the sec_error_unknown_issuer problem that you will run into if the site you're testing has an untrusted certificate. See How to disable Firefox's untrusted connection warning using Selenium?

After investigation it was found that the Marionette driver is incomplete and still in progress, and no amount of setting various capabilities or profile options for dismissing or setting certificates was going to work. So it was just easier to use a custom profile.

Anyway, here's the code on how I got the geckodriver to work without being in the path:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

firefox_capabilities = DesiredCapabilities.FIREFOX
firefox_capabilities['marionette'] = True

#you probably don't need the next 3 lines they don't seem to work anyway
firefox_capabilities['handleAlerts'] = True
firefox_capabilities['acceptSslCerts'] = True
firefox_capabilities['acceptInsecureCerts'] = True

# In the next line I'm using a specific Firefox profile because
# I wanted to get around the sec_error_unknown_issuer problems with the new Firefox and Marionette driver
# I create a Firefox profile where I had already made an exception for the site I'm testing
# see https://support.mozilla.org/en-US/kb/profile-manager-create-and-remove-firefox-profiles#w_starting-the-profile-manager

ffProfilePath = 'D:\Work\PyTestFramework\FirefoxSeleniumProfile'
profile = webdriver.FirefoxProfile(profile_directory=ffProfilePath)
geckoPath = 'D:\Work\PyTestFramework\geckodriver.exe'
browser = webdriver.Firefox(firefox_profile=profile, capabilities=firefox_capabilities, executable_path=geckoPath)
browser.get('http://stackoverflow.com')

"And" and "Or" troubles within an IF statement

I like assylias' answer, however I would refactor it as follows:

Sub test()

Dim origNum As String
Dim creditOrDebit As String

origNum = "30062600006"
creditOrDebit = "D"

If creditOrDebit = "D" Then
  If origNum = "006260006" Then
    MsgBox "OK"
  ElseIf origNum = "30062600006" Then
    MsgBox "OK"
  End If
End If

End Sub

This might save you some CPU cycles since if creditOrDebit is <> "D" there is no point in checking the value of origNum.

Update:

I used the following procedure to test my theory that my procedure is faster:

Public Declare Function timeGetTime Lib "winmm.dll" () As Long

Sub DoTests2()

  Dim startTime1 As Long
  Dim endTime1 As Long
  Dim startTime2 As Long
  Dim endTime2 As Long
  Dim i As Long
  Dim msg As String

  Const numberOfLoops As Long = 10000
  Const origNum As String = "006260006"
  Const creditOrDebit As String = "D"

  startTime1 = timeGetTime
  For i = 1 To numberOfLoops
    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        ' do something here
        Debug.Print "OK"
      ElseIf origNum = "30062600006" Then
        ' do something here
        Debug.Print "OK"
      End If
    End If
  Next i
  endTime1 = timeGetTime

  startTime2 = timeGetTime
  For i = 1 To numberOfLoops
    If (origNum = "006260006" Or origNum = "30062600006") And _
      creditOrDebit = "D" Then
      ' do something here
      Debug.Print "OK"
    End If
  Next i
  endTime2 = timeGetTime

  msg = "number of iterations: " & numberOfLoops & vbNewLine
  msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
       " ms" & vbNewLine
  msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
       " ms"

  MsgBox msg

End Sub

I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>"D", my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it - to short-circuit the logic so that origNum doesn't need to be evaluated when creditOrDebit <> "D".

At this point, the rest depends on the OP's spreadsheet. If creditOrDebit is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

How to provide animation when calling another activity in Android?

Wrote a tutorial so that you can animate your activity's in and out,

Enjoy:

http://blog.blundellapps.com/animate-an-activity/

Difference between javacore, thread dump and heap dump in Websphere

Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores

Is it better to use "is" or "==" for number comparison in Python?

Others have answered your question, but I'll go into a little bit more detail:

Python's is compares identity - it asks the question "is this one thing actually the same object as this other thing" (similar to == in Java). So, there are some times when using is makes sense - the most common one being checking for None. Eg, foo is None. But, in general, it isn't what you want.

==, on the other hand, asks the question "is this one thing logically equivalent to this other thing". For example:

>>> [1, 2, 3] == [1, 2, 3]
True
>>> [1, 2, 3] is [1, 2, 3]
False

And this is true because classes can define the method they use to test for equality:

>>> class AlwaysEqual(object):
...     def __eq__(self, other):
...         return True
...
>>> always_equal = AlwaysEqual()
>>> always_equal == 42
True
>>> always_equal == None
True

But they cannot define the method used for testing identity (ie, they can't override is).

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I don't think that x[[1,3]][:,[1,3]] is hardly readable. If you want to be more clear on your intent, you can do:

a[[1,3],:][:,[1,3]]

I am not an expert in slicing but typically, if you try to slice into an array and the values are continuous, you get back a view where the stride value is changed.

e.g. In your inputs 33 and 34, although you get a 2x2 array, the stride is 4. Thus, when you index the next row, the pointer moves to the correct position in memory.

Clearly, this mechanism doesn't carry well into the case of an array of indices. Hence, numpy will have to make the copy. After all, many other matrix math function relies on size, stride and continuous memory allocation.

C# guid and SQL uniqueidentifier

You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier.

Your method may look like this (provided that your only parameter is the Guid):

public static void StoreGuid(Guid guid)
{
    using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
    using (var cmd = new SqlCommand {
        Connection = cnx,
        CommandType = CommandType.StoredProcedure,
        CommandText = "StoreGuid",
        Parameters = {
            new SqlParameter {
                ParameterName = "@guid",
                SqlDbType = SqlDbType.UniqueIdentifier, // right here
                Value = guid
            }
        }
    })
    {
        cnx.Open();
        cmd.ExecuteNonQuery();
    }
}

See also: SQL Server's uniqueidentifier

syntaxerror: unexpected character after line continuation character in python

The filename should be a string. In other names it should be within quotes.

f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
    thisline = i.split(" ");

You can also open the file using with

with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
    lines = f.readlines()
    for i in lines:
        thisline = i.split(" ");

There is no need to add the semicolon(;) in python. It's ugly.

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

Whether or not the "date" '0000-00-00" is a valid "date" is irrelevant to the question. "Just change the database" is seldom a viable solution.

Facts:

  • MySQL allows a date with the value of zeros.
  • This "feature" enjoys widespread use with other languages.

So, if I "just change the database", thousands of lines of PHP code will break.

Java programmers need to accept the MySQL zero-date and they need to put a zero date back into the database, when other languages rely on this "feature".

A programmer connecting to MySQL needs to handle null and 0000-00-00 as well as valid dates. Changing 0000-00-00 to null is not a viable option, because then you can no longer determine if the date was expected to be 0000-00-00 for writing back to the database.

For 0000-00-00, I suggest checking the date value as a string, then changing it to ("y",1), or ("yyyy-MM-dd",0001-01-01), or into any invalid MySQL date (less than year 1000, iirc). MySQL has another "feature": low dates are automatically converted to 0000-00-00.

I realize my suggestion is a kludge. But so is MySQL's date handling. And two kludges don't make it right. The fact of the matter is, many programmers will have to handle MySQL zero-dates forever.

Get the latest record with filter in Django

obj= Model.objects.filter(testfield=12).order_by('-id')[0]

Simplest way to detect keypresses in javascript

KEYPRESS (enter key)
Click inside the snippet and press Enter key.

Vanilla

_x000D_
_x000D_
document.addEventListener("keypress", function(event) {
  if (event.keyCode == 13) {
    alert('hi.');
  }
});
_x000D_
_x000D_
_x000D_

Vanilla shorthand (ES6)

_x000D_
_x000D_
this.addEventListener('keypress', event => {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
$(this).on('keypress', function(event) {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery classic

_x000D_
_x000D_
$(this).keypress(function(event) {
  if (event.keyCode == 13) {
    alert('hi.')
  }
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery shorthand (ES6)

_x000D_
_x000D_
$(this).keypress((e) => {
  if (e.keyCode == 13)
    alert('hi.')
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Even shorter (ES6)

_x000D_
_x000D_
$(this).keypress(e=>
  e.which==13?
  alert`hi.`:null
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Due some requests, here an explanation:

I rewrote this answer as things have become deprecated over time so I updated it.

I used this to focus on the window scope inside the results when document is ready and for the sake of brevity but it's not necessary.

Deprecated:
The .which and .keyCode methods are actually considered deprecated so I would recommend .code but I personally still use keyCode as the performance is much faster and only that counts for me. The jQuery classic version .keypress() is not officially deprecated as some people say but they are no more preferred like .on('keypress') as it has a lot more functionality(live state, multiple handlers, etc.). The 'keypress' event in the Vanilla version is also deprecated. People should prefer beforeinput or keydown today. (Note: It has nothing to do with jQuery's events, they are called the same but execute differently.)

All examples above are no biggies regarding deprecated or not. Consoles or any browser should be able to notify you with that if this happens. And if this ever does in future, just fix it.

Readablity:
Despite the ease making it too short and snippy isn't always good either. If you work in a team, your code must be readable and detailed. I recommend the jQuery version .on('keypress'), this is the way to go and understandable by most people.

Performance:
I always follow my phrase Performance over Effectiveness as anything can be more effective if there is the option but it just should function and execute only what I want, the faster the better. This is why I prefer .keyCode even if it's considered deprecated(in most cases). It's all up to you though.

Performance Test

npm install hangs

I had the same problem. The reason - wrong proxy was configured and because of that npm was unable to download packages.

So your best bet is to the see the output of

$ npm install --verbose

and identify the problem. If you have never configured proxy, then possible causes can be

  • Very outdated npm version.
  • Some problem with your internet connection.
  • Permissions are not sufficient for npm to modify files.

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

Determine if Android app is being used for the first time

Hi guys I am doing something like this. And its works for me

create a Boolean field in shared preference.Default value is true {isFirstTime:true} after first time set it to false. Nothing can be simple and relaiable than this in android system.

New og:image size for Facebook share?

Tried to get the 1200x630 image working. Facebook kept complaining that it couldn't read the image, or that it was too small (it was a jpeg image ~150Kb).

Switched to a 200x200 size image, worked perfectly.

https://developers.facebook.com/tools/debug/og/object?q=drift.team

How to reduce the image size without losing quality in PHP

I'd go for jpeg. Read this post regarding image size reduction and after deciding on the technique, use ImageMagick

Hope this helps

Convert Iterator to ArrayList

Here in this case if you want the fastest way possible then for loop is better.

The iterator over a sample size of 10,000 runs takes 40 ms where as for loop takes 2 ms

        ArrayList<String> alist = new ArrayList<String>();  
        long start, end;  

        for (int i = 0; i < 1000000; i++) {  
            alist.add(String.valueOf(i));  
        }  

        ListIterator<String> it = alist.listIterator();      

        start = System.currentTimeMillis();  
        while (it.hasNext()) {  
            String s = it.next();  
        }  
        end = System.currentTimeMillis();  

        System.out.println("Iterator start: " + start + ", end: " + end + ", delta: "  
            + (end - start));  
        start = System.currentTimeMillis();  
        int ixx = 0;  
        for (int i = 0; i < 100000; i++) {  
            String s = alist.get(i);  
        }  

        System.out.println(ixx);  
        end = System.currentTimeMillis();  
        System.out.println("for loop start: " + start + ", end: " + end + ", delta: "  
            + (end - start));  

That's assuming that the list contains strings.

Default passwords of Oracle 11g?

Login into the machine as oracle login user id( where oracle is installed)..

  1. Add ORACLE_HOME = <Oracle installation Directory> in Environment variable

  2. Open a command prompt

  3. Change the directory to %ORACLE_HOME%\bin

  4. type the command sqlplus /nolog

  5. SQL> connect /as sysdba

  6. SQL> alter user SYS identified by "newpassword";

One more check, while oracle installation and database confiuration assistant setup, if you configure any database then you might have given password and checked the same password for all other accounts.. If so, then you try with the password which you have given in your database configuration assistant setup.

Hope this will work for you..

How to keep a git branch in sync with master

The accepted answer via git merge will get the job done but leaves a messy commit hisotry, correct way should be 'rebase' via the following steps(assuming you want to keep your feature branch in sycn with develop before you do the final push before PR).

1 git fetch from your feature branch (make sure the feature branch you are working on is update to date)

2 git rebase origin/develop

3 if any conflict shall arise, resolve them one by one

4 use git rebase --continue once all conflicts are dealt with

5 git push --force

How to check if a service is running via batch file and start it, if it is not running?

I just found this thread and wanted to add to the discussion if the person doesn't want to use a batch file to restart services. In Windows there is an option if you go to Services, service properties, then recovery. Here you can set parameters for the service. Like to restart the service if the service stops. Also, you can even have a second fail attempt do something different as in restart the computer.

Getting or changing CSS class property with Javascript using DOM style

As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.

This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...

function changeBGColor() {
  var cols = document.getElementsByClassName('col1');
  for(i = 0; i < cols.length; i++) {
    cols[i].style.backgroundColor = 'blue';
  }
}

How to send a correct authorization header for basic authentication

If you are in a browser environment you can also use btoa.

btoa is a function which takes a string as argument and produces a Base64 encoded ASCII string. Its supported by 97% of browsers.

Example:

> "Basic " + btoa("billy"+":"+"secretpassword")
< "Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ="

You can then add Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ= to the authorization header.

Note that the usual caveats about HTTP BASIC auth apply, most importantly if you do not send your traffic over https an eavesdropped can simply decode the Base64 encoded string thus obtaining your password.

This security.stackexchange.com answer gives a good overview of some of the downsides.

Run script with rc.local: script works, but not at boot

This is most probably caused by a missing or incomplete PATH environment variable.

If you provide full absolute paths to your executables (su and node) it will work.

How do I verify/check/test/validate my SSH passphrase?

You can verify your SSH key passphrase by attempting to load it into your SSH agent. With OpenSSH this is done via ssh-add.

Once you're done, remember to unload your SSH passphrase from the terminal by running ssh-add -d.

Simultaneously merge multiple data.frames in a list

Another question asked specifically how to perform multiple left joins using dplyr in R . The question was marked as a duplicate of this one so I answer here, using the 3 sample data frames below:

x <- data.frame(i = c("a","b","c"), j = 1:3, stringsAsFactors=FALSE)
y <- data.frame(i = c("b","c","d"), k = 4:6, stringsAsFactors=FALSE)
z <- data.frame(i = c("c","d","a"), l = 7:9, stringsAsFactors=FALSE)

Update June 2018: I divided the answer in three sections representing three different ways to perform the merge. You probably want to use the purrr way if you are already using the tidyverse packages. For comparison purposes below, you'll find a base R version using the same sample dataset.


1) Join them with reduce from the purrr package:

The purrr package provides a reduce function which has a concise syntax:

library(tidyverse)
list(x, y, z) %>% reduce(left_join, by = "i")
#  A tibble: 3 x 4
#  i       j     k     l
#  <chr> <int> <int> <int>
# 1 a      1    NA     9
# 2 b      2     4    NA
# 3 c      3     5     7

You can also perform other joins, such as a full_join or inner_join:

list(x, y, z) %>% reduce(full_join, by = "i")
# A tibble: 4 x 4
# i       j     k     l
# <chr> <int> <int> <int>
# 1 a     1     NA     9
# 2 b     2     4      NA
# 3 c     3     5      7
# 4 d     NA    6      8

list(x, y, z) %>% reduce(inner_join, by = "i")
# A tibble: 1 x 4
# i       j     k     l
# <chr> <int> <int> <int>
# 1 c     3     5     7

2) dplyr::left_join() with base R Reduce():

list(x,y,z) %>%
    Reduce(function(dtf1,dtf2) left_join(dtf1,dtf2,by="i"), .)

#   i j  k  l
# 1 a 1 NA  9
# 2 b 2  4 NA
# 3 c 3  5  7

3) Base R merge() with base R Reduce():

And for comparison purposes, here is a base R version of the left join based on Charles's answer.

 Reduce(function(dtf1, dtf2) merge(dtf1, dtf2, by = "i", all.x = TRUE),
        list(x,y,z))
#   i j  k  l
# 1 a 1 NA  9
# 2 b 2  4 NA
# 3 c 3  5  7

What is the most efficient way to deep clone an object in JavaScript?

Native deep cloning

It's called "structured cloning", works experimentally in Node 11 and later, and hopefully will land in browsers. See this answer for more details.

Fast cloning with data loss - JSON.parse/stringify

If you do not use Dates, functions, undefined, Infinity, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is:

JSON.parse(JSON.stringify(object))

_x000D_
_x000D_
const a = {
  string: 'string',
  number: 123,
  bool: false,
  nul: null,
  date: new Date(),  // stringified
  undef: undefined,  // lost
  inf: Infinity,  // forced to 'null'
  re: /.*/,  // lost
}
console.log(a);
console.log(typeof a.date);  // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);
console.log(typeof clone.date);  // result of .toISOString()
_x000D_
_x000D_
_x000D_

See Corban's answer for benchmarks.

Reliable cloning using a library

Since cloning objects is not trivial (complex types, circular references, function etc.), most major libraries provide function to clone objects. Don't reinvent the wheel - if you're already using a library, check if it has an object cloning function. For example,

ES6 (shallow copy)

For completeness, note that ES6 offers two shallow copy mechanisms: Object.assign() and the spread syntax. which copies values of all enumerable own properties from one object to another. For example:

var A1 = {a: "2"};
var A2 = Object.assign({}, A1);
var A3 = {...A1};  // Spread Syntax

What REALLY happens when you don't free after malloc?

You are correct, memory is automatically freed when the process exits. Some people strive not to do extensive cleanup when the process is terminated, since it will all be relinquished to the operating system. However, while your program is running you should free unused memory. If you don't, you may eventually run out or cause excessive paging if your working set gets too big.

Revert a jQuery draggable object back to its original container on out event of droppable

If you want to revert the element to the source position if it's not dropped inside a #droppable element, just save the original parent element of the draggable at the start of the script (instead of the position), and if you verify that it's not dropped into #droppable, then just restore the parent of #draggable to this original element.

So, replace this:

}).each(function() {
    var top = $(this).position().top;
    var left = $(this).position().left;
    $(this).data('orgTop', top);
    $(this).data('orgLeft', left);
});

with this:

}).each(function() {
    $(this).data('originalParent', $(this).parent())
});

Here, you'll have the original parent element of the draggable. Now, you have to restore it's parent in a precise moment.

drop is called every time the element is dragged out from the droppable, not at the stop. So, you're adding a lot of event callbacks. This is wrong, because you never clean the mouseup event. A good place where you can hook a callback and check if the element was dropped inside or outside the #droppable element, is revert, and you're doing it right now, so, just delete the drop callback.

When the element is dropped, and needs to know if it should be reverted or not, you know for sure that you'll not have any other interaction from the user until the new drag start. So, using the same condition you're using to know if it should revert or know, let's replace this alert with a fragment of code that: restores the parent element to the original div, and resets the originalPosition from the draggable internals. The originalPosition proeprty is setted at the time of _mouseStart, so, if you change the owner of the element, you should reset it, in order to make the animation of revert go to the proper place. So, let's set this to {top: 0, left: 0}, making the animation go to the origin point of the element:

revert: function(dropped) {
    var dropped = dropped && dropped[0].id == "droppable";
    if(!dropped) {
        $(this).data("draggable").originalPosition = {top:0, left:0}
        $(this).appendTo($(this).data('originalParent'))
    }
    return !dropped;
}

And that's it! You can check this working here: http://jsfiddle.net/eUs3e/1/

Take into consideration that, if in any jQuery's UI update, the behavior of revert or originalPosition changes, you'll need to update your code in order to make it work. Keep in mind that.

If you need a solution which doesn't make use of calls to the internals of ui.draggable, you can make your body an droppable element with greedy option defined as false. You'll have to make sure that your body elements take the full screen.

Good luck!

How can I convert a zero-terminated byte array to string?

For example,

package main

import "fmt"

func CToGoString(c []byte) string {
    n := -1
    for i, b := range c {
        if b == 0 {
            break
        }
        n = i
    }
    return string(c[:n+1])
}

func main() {
    c := [100]byte{'a', 'b', 'c'}
    fmt.Println("C: ", len(c), c[:4])
    g := CToGoString(c[:])
    fmt.Println("Go:", len(g), g)
}

Output:

C:  100 [97 98 99 0]
Go: 3 abc

Hiding table data using <div style="display:none">

<style type="text/css">
.hidden { display:none; }
</style>

<table>
<tr><th>Test Table</th><tr>
<tr class="hidden"><td>123456789</td></tr>
<tr class="hidden"><td>123456789</td></tr>
<tr class="hidden"><td>123456789</td></tr>
</table>

And instead of:

<div style="display:none;">
<table>...</table>
</div>

you had better use: ...

json_encode() escaping forward slashes

is there a way to disable it?

Yes, you only need to use the JSON_UNESCAPED_SLASHES flag.

!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy)

json_encode($str, JSON_UNESCAPED_SLASHES);

If you don't have PHP 5.4 at hand, pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).

Example Demo

<?php
/*
 * Escaping the reverse-solidus character ("/", slash) is optional in JSON.
 *
 * This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
 *
 * @link http://stackoverflow.com/a/10210433/367456
 */    

$url = 'http://www.example.com/';

echo json_encode($url), "\n";

echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";

Example Output:

"http:\/\/www.example.com\/"
"http://www.example.com/"

Get top n records for each group of grouped results

I wanted to share this because I spent a long time searching for an easy way to implement this in a java program I'm working on. This doesn't quite give the output you're looking for but its close. The function in mysql called GROUP_CONCAT() worked really well for specifying how many results to return in each group. Using LIMIT or any of the other fancy ways of trying to do this with COUNT didn't work for me. So if you're willing to accept a modified output, its a great solution. Lets say I have a table called 'student' with student ids, their gender, and gpa. Lets say I want to top 5 gpas for each gender. Then I can write the query like this

SELECT sex, SUBSTRING_INDEX(GROUP_CONCAT(cast(gpa AS char ) ORDER BY gpa desc), ',',5) 
AS subcategories FROM student GROUP BY sex;

Note that the parameter '5' tells it how many entries to concatenate into each row

And the output would look something like

+--------+----------------+
| Male   | 4,4,4,4,3.9    |
| Female | 4,4,3.9,3.9,3.8|
+--------+----------------+

You can also change the ORDER BY variable and order them a different way. So if I had the student's age I could replace the 'gpa desc' with 'age desc' and it will work! You can also add variables to the group by statement to get more columns in the output. So this is just a way I found that is pretty flexible and works good if you are ok with just listing results.

Internet Access in Ubuntu on VirtualBox

I had the same problem.

Solved by sharing internet connection (on the hosting OS).

Network Connection Properties -> advanced -> Allow other users to connect...

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

As mentioned by @CommonsWare, you will want to try android sqlite asset helper. It made opening a pre-existing db a piece of cake for me.

I literally had it working in about a half hour after spending 3 hours trying to do it all manually. Funny thing is, I thought I was doing the same thing the library did for me, but something was missing!

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

first you have to give echo to display base url. Then change below value in your autoload.php which will be inside your application/config/ folder. $autoload['helper'] = array('url'); then your issue will be resolved.

What do two question marks together mean in C#?

Thanks everybody, here is the most succinct explanation I found on the MSDN site:

// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:

<location path="YourWebservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>

Save file to specific folder with curl command

I don't think you can give a path to curl, but you can CD to the location, download and CD back.

cd target/path && { curl -O URL ; cd -; }

Or using subshell.

(cd target/path && curl -O URL)

Both ways will only download if path exists. -O keeps remote file name. After download it will return to original location.

If you need to set filename explicitly, you can use small -o option:

curl -o target/path/filename URL