Programs & Examples On #Third normal form

How to send objects through bundle

One More way to send objects through bundle is by using bundle.putByteArray
Sample code

public class DataBean implements Serializable {
private Date currentTime;

public setDate() {
    currentTime = Calendar.getInstance().getTime();
 }

public Date getCurrentTime() {
    return currentTime;
 }
}

put Object of DataBean in to Bundle:

class FirstClass{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code...

//When you want to start new Activity...
Intent dataIntent =new Intent(FirstClass.this, SecondClass.class);
            Bundle dataBundle=new Bundle();
            DataBean dataObj=new DataBean();
            dataObj.setDate();
            try {
                dataBundle.putByteArray("Obj_byte_array", object2Bytes(dataObj));

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }

            dataIntent.putExtras(dataBundle);

            startActivity(dataIntent);
}

Converting objects to byte arrays

/**
 * Converting objects to byte arrays
 */
static public byte[] object2Bytes( Object o ) throws IOException {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream( baos );
      oos.writeObject( o );
      return baos.toByteArray();
    }

Get Object back from Bundle:

class SecondClass{
DataBean dataBean;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code...

//Get Info from Bundle...
    Bundle infoBundle=getIntent().getExtras();
    try {
        dataBean = (DataBean)bytes2Object(infoBundle.getByteArray("Obj_byte_array"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Method to get objects from byte arrays:

/**
 * Converting byte arrays to objects
 */
static public Object bytes2Object( byte raw[] )
        throws IOException, ClassNotFoundException {
      ByteArrayInputStream bais = new ByteArrayInputStream( raw );
      ObjectInputStream ois = new ObjectInputStream( bais );
      Object o = ois.readObject();
      return o;
    }

Hope this will help to other buddies.

How do I add BundleConfig.cs to my project?

BundleConfig is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)

To add this file, first you need to add the Microsoft.AspNet.Web.Optimization nuget package to your web project:

Install-Package Microsoft.AspNet.Web.Optimization

Then under the App_Start folder create a new cs file called BundleConfig.cs. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):

using System.Web;
using System.Web.Optimization;

namespace CodeRepository.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

Then modify your Global.asax and add a call to RegisterBundles() in Application_Start():

using System.Web.Optimization;

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

Creating multiline strings in JavaScript

Just tried the Anonymous answer and found there's a little trick here, it doesn't work if there's a space after backslash \
So the following solution doesn't work -

var x = { test:'<?xml version="1.0"?>\ <-- One space here
            <?mso-application progid="Excel.Sheet"?>' 
};

But when space is removed it works -

var x = { test:'<?xml version="1.0"?>\<-- No space here now
          <?mso-application progid="Excel.Sheet"?>' 
};

alert(x.test);?

Hope it helps !!

print spaces with String.format()

int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");

How to set the part of the text view is clickable

Created elegant Kotlin way with extension:

fun TextView.setClickableText(text: Spanned,
                              clickableText: String,
                              @ColorInt clickableColor: Int,
                              clickListener: () -> Unit) {
    val spannableString = SpannableString(text)

    val startingPosition: Int = text.indexOf(clickableText)

    if (startingPosition > -1) {
        val clickableSpan: ClickableSpan = object : ClickableSpan() {
            override fun onClick(textView: View) {
                clickListener()
            }

            override fun updateDrawState(textPaint: TextPaint) {
                super.updateDrawState(textPaint)
                textPaint.isUnderlineText = false
            }
        }

        val endingPosition: Int = startingPosition + clickableText.length
        spannableString.setSpan(clickableSpan, startingPosition,
                endingPosition, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.setSpan(ForegroundColorSpan(clickableColor), startingPosition,
                endingPosition, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        movementMethod = LinkMovementMethod.getInstance()
        highlightColor = Color.TRANSPARENT
    }

    setText(spannableString)
}

Are table names in MySQL case sensitive?

In general:

Database and table names are not case sensitive in Windows, and case sensitive in most varieties of Unix.

In MySQL, databases correspond to directories within the data directory. Each table within a database corresponds to at least one file within the database directory. Consequently, the case sensitivity of the underlying operating system plays a part in the case sensitivity of database and table names.

One can configure how tables names are stored on the disk using the system variable lower_case_table_names (in the my.cnf configuration file under [mysqld]).

Read the section: 10.2.2 Identifier Case Sensitivity for more information.

undefined reference to `WinMain@16'

Try saving your .c file before building. I believe your computer is referencing a path to a file with no information inside of it.

--Had similar issue when building C projects

PHP Unset Array value effect on other indexes

The Key Disappears, whether it is numeric or not. Try out the test script below.

<?php
    $t = array( 'a', 'b', 'c', 'd' );
    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 1: b, 2: c, 3: d

    unset($t[1]);

    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 2: c, 3: d
?>

How to create nonexistent subdirectories recursively using Bash?

mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8

How to get Real IP from Visitor?

This is my function.

benefits :

  • Work if $_SERVER was not available.
  • Filter private and/or reserved IPs;
  • Process all forwarded IPs in X_FORWARDED_FOR
  • Compatible with CloudFlare
  • Can set a default if no valid IP found!
  • Short & Simple !

/**
 * Get real user ip
 *
 * Usage sample:
 * GetRealUserIp();
 * GetRealUserIp('ERROR',FILTER_FLAG_NO_RES_RANGE);
 * 
 * @param string $default default return value if no valid ip found
 * @param int    $filter_options filter options. default is FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
 *
 * @return string real user ip
 */

function GetRealUserIp($default = NULL, $filter_options = 12582912) {
    $HTTP_X_FORWARDED_FOR = isset($_SERVER)? $_SERVER["HTTP_X_FORWARDED_FOR"]:getenv('HTTP_X_FORWARDED_FOR');
    $HTTP_CLIENT_IP = isset($_SERVER)?$_SERVER["HTTP_CLIENT_IP"]:getenv('HTTP_CLIENT_IP');
    $HTTP_CF_CONNECTING_IP = isset($_SERVER)?$_SERVER["HTTP_CF_CONNECTING_IP"]:getenv('HTTP_CF_CONNECTING_IP');
    $REMOTE_ADDR = isset($_SERVER)?$_SERVER["REMOTE_ADDR"]:getenv('REMOTE_ADDR');

    $all_ips = explode(",", "$HTTP_X_FORWARDED_FOR,$HTTP_CLIENT_IP,$HTTP_CF_CONNECTING_IP,$REMOTE_ADDR");
    foreach ($all_ips as $ip) {
        if ($ip = filter_var($ip, FILTER_VALIDATE_IP, $filter_options))
            break;
    }
    return $ip?$ip:$default;
}

Get all files and directories in specific path fast

Maybe it will be helpfull for you. You could use "DirectoryInfo.EnumerateFiles" method and handle UnauthorizedAccessException as you need.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        DirectoryInfo diTop = new DirectoryInfo(@"d:\");
        try
        {
            foreach (var fi in diTop.EnumerateFiles())
            {
                try
                {
                    // Display each file over 10 MB; 
                    if (fi.Length > 10000000)
                    {
                        Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
                    }
                }
                catch (UnauthorizedAccessException UnAuthTop)
                {
                    Console.WriteLine("{0}", UnAuthTop.Message);
                }
            }

            foreach (var di in diTop.EnumerateDirectories("*"))
            {
                try
                {
                    foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
                    {
                        try
                        {
                            // Display each file over 10 MB; 
                            if (fi.Length > 10000000)
                            {
                                Console.WriteLine("{0}\t\t{1}",  fi.FullName, fi.Length.ToString("N0"));
                            }
                        }
                        catch (UnauthorizedAccessException UnAuthFile)
                        {
                            Console.WriteLine("UnAuthFile: {0}", UnAuthFile.Message);
                        }
                    }
                }
                catch (UnauthorizedAccessException UnAuthSubDir)
                {
                    Console.WriteLine("UnAuthSubDir: {0}", UnAuthSubDir.Message);
                }
            }
        }
        catch (DirectoryNotFoundException DirNotFound)
        {
            Console.WriteLine("{0}", DirNotFound.Message);
        }
        catch (UnauthorizedAccessException UnAuthDir)
        {
            Console.WriteLine("UnAuthDir: {0}", UnAuthDir.Message);
        }
        catch (PathTooLongException LongPath)
        {
            Console.WriteLine("{0}", LongPath.Message);
        }
    }
}

How to enable TLS 1.2 in Java 7

To force enable TLSv1.2 in JRE7u_80 I had to use following code snippet before creating JDBC connection.

import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import javax.net.ssl.SSLContextSpi;
import sun.security.jca.GetInstance;
import sun.security.jca.ProviderList;
import sun.security.jca.Providers;

public static void enableTLSv12ForMssqlJdbc() throws NoSuchAlgorithmException
{
    ProviderList providerList = Providers.getProviderList();
    GetInstance.Instance instance = GetInstance.getInstance("SSLContext", SSLContextSpi.class, "TLS");
    for (Provider provider : providerList.providers())
    {
        if (provider == instance.provider)
        {
            provider.put("Alg.Alias.SSLContext.TLS", "TLSv1.2");
        }
    }
}

Able to connect to Windows 10 with SQL server 2017 & TLSv1.2 enabled OS.

Can I override and overload static methods in Java?

The very purpose of using the static method is to access the method of a class without creating an instance for it.It will make no sense if we override that method since they will be accessed by classname.method()

Declare an array in TypeScript

Here are the different ways in which you can create an array of booleans in typescript:

let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();

let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();

let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];

let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();

let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();

You can access them using the index:

console.log(arr[5]);

and you add elements using push:

arr.push(true);

When creating the array you can supply the initial values:

let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

Loose coupling is and answer to to old style hardcoded dependencies and related issues issues like frequent recompilation when anything changes and code reuse. It stresses on implementing the worker logic in components and avoiding solution specific wire up code there.

Loose Coupling = IoC See this for easier explanation.

How to get DataGridView cell value in messagebox?

You can use the DataGridViewCell.Value Property to retrieve the value stored in a particular cell.

So to retrieve the value of the 'first' selected Cell and display in a MessageBox, you can:

MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());

The above probably isn't exactly what you need to do. If you provide more details we can provide better help.

How do I copy a hash in Ruby?

The clone method is Ruby's standard, built-in way to do a shallow-copy:

irb(main):003:0> h0 = {"John" => "Adams", "Thomas" => "Jefferson"}
=> {"John"=>"Adams", "Thomas"=>"Jefferson"}
irb(main):004:0> h1 = h0.clone
=> {"John"=>"Adams", "Thomas"=>"Jefferson"}
irb(main):005:0> h1["John"] = "Smith"
=> "Smith"
irb(main):006:0> h1
=> {"John"=>"Smith", "Thomas"=>"Jefferson"}
irb(main):007:0> h0
=> {"John"=>"Adams", "Thomas"=>"Jefferson"}

Note that the behavior may be overridden:

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

How to use log levels in java

Here is a good introduction to logging in Java: http://www.javapractices.com/topic/TopicAction.do?Id=143

Java comes with a logging API since it's 1.4.2 version: http://download.oracle.com/javase/1.4.2/docs/guide/util/logging/overview.html

You can also use other logging frameworks like Apache Log4j which is the most popular one: http://logging.apache.org/log4j

I suggest you to use a logging abstraction framework which allows you to change your logging framework without re-factoring you code. So you can starts by using Jul (Java Util Logging) then swith to Log4j without changing you code. The most popular logging facade is slf4j: http://www.slf4j.org/

Regards,

Android - Handle "Enter" in an EditText

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId != 0 || event.getAction() == KeyEvent.ACTION_DOWN) {
                // Action
                return true;
            } else {
                return false;
            }
        }
    });

Xml

<EditText
        android:id="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/password"
        android:imeOptions="actionGo|flagNoFullscreen"
        android:inputType="textPassword"
        android:maxLines="1" />

How to reduce the image size without losing quality in PHP

well I think I have something interesting for you... https://github.com/whizzzkid/phpimageresize. I wrote it for the exact same purpose. Highly customizable, and does it in a great way.

How do I get the type of a variable?

For static assertions, C++11 introduced decltype which is quite useful in certain scenarios.

Passing arguments to an interactive program non-interactively

You can also use printf to pipe the input to your script.

var=val
printf "yes\nno\nmaybe\n$var\n" | ./your_script.sh

Git error when trying to push -- pre-receive hook declined

For me everything was working fine until Bitbucket automatically changed their policy today (April 21, 2020). This happens to align with a new feature recently introduced today called Workspaces, so I suspect it has something to do with that.

Workaround: I (as an Admin) followed the instructions to add the email address to Users in the UI (the email you are using can be found git config --list

enter image description here

What are the advantages of NumPy over regular Python lists?

NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.

Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware!

The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!

window.open(url, '_blank'); not working on iMac/Safari

window.location.assign(url) this fixs the window.open(url) issue in ios devices

How to get config parameters in Symfony2 Twig Templates

In confing.yml

# app/config/config.yml
twig:
  globals:
    version: '%app.version%'

In Twig view

# twig view
{{ version }}

Add row to query result using select

You use it like this:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

Use UNION ALL to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION.

How can I exit from a javascript function?

Use return statement anywhere you want to exit from function.

if(somecondtion)
   return;

if(somecondtion)
   return false;

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):

C:\xampp\php\PEAR\initcontrols\header_myworks.php

providing the path you pasted in the subject is correct. Make sure your file is located there.

For more info you can get and set the include path programmatically.

Disabling right click on images using jquery

For modern browsers all you need is this CSS:

img {
    pointer-events: none;
}

Older browsers will still allow pointer events on the images, but the CSS above will take care of the vast majority of visitors to your site, and used in conjunction with the contextmenu methods should give you a very solid solution.

jQuery Cross Domain Ajax

If you are planning to use JSONP you can use getJSON which made for that. jQuery has helper methods for JSONP.

$.getJSON( 'http://someotherdomain.com/service.svc&callback=?', function( result ) {
       console.log(result);
});

Read the below links

http://api.jquery.com/jQuery.getJSON/

Basic example of using .ajax() with JSONP?

Basic how-to for cross domain jsonp

How to create multiple class objects with a loop in python?

I hope this is what you are looking for.

class Try:
    def do_somthing(self):
        print 'Hello'

if __name__ == '__main__':
    obj_list = []
    for obj in range(10):
        obj = Try()
        obj_list.append(obj)

    obj_list[0].do_somthing()

Output:

Hello

Unsuccessful append to an empty NumPy array

SO thread 'Multiply two arrays element wise, where one of the arrays has arrays as elements' has an example of constructing an array from arrays. If the subarrays are the same size, numpy makes a 2d array. But if they differ in length, it makes an array with dtype=object, and the subarrays retain their identity.

Following that, you could do something like this:

In [5]: result=np.array([np.zeros((1)),np.zeros((2))])

In [6]: result
Out[6]: array([array([ 0.]), array([ 0.,  0.])], dtype=object)

In [7]: np.append([result[0]],[1,2])
Out[7]: array([ 0.,  1.,  2.])

In [8]: result[0]
Out[8]: array([ 0.])

In [9]: result[0]=np.append([result[0]],[1,2])

In [10]: result
Out[10]: array([array([ 0.,  1.,  2.]), array([ 0.,  0.])], dtype=object)

However, I don't offhand see what advantages this has over a pure Python list or lists. It does not work like a 2d array. For example I have to use result[0][1], not result[0,1]. If the subarrays are all the same length, I have to use np.array(result.tolist()) to produce a 2d array.

Efficiently finding the last line in a text file

with open('output.txt', 'r') as f:
    lines = f.read().splitlines()
    last_line = lines[-1]
    print last_line

How can I create 2 separate log files with one log4j config file?

Modify your log4j.properties file accordingly:

log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog

Change the log levels for each logger depending to your needs.

Batch script loop

And to iterate on the files of a directory:

@echo off 
setlocal enableDelayedExpansion 

set MYDIR=C:\something
for /F %%x in ('dir /B/D %MYDIR%') do (
  set FILENAME=%MYDIR%\%%x\log\IL_ERROR.log
  echo ===========================  Search in !FILENAME! ===========================
  c:\utils\grep motiv !FILENAME!
)

You must use "enableDelayedExpansion" and !FILENAME! instead of $FILENAME$. In the second case, DOS will interpret the variable only once (before it enters the loop) and not each time the program loops.

Resetting MySQL Root Password with XAMPP on Localhost

For me much better way is to do it using terminal rather then PhpMyAdmin UI.

The answer is copied from "https://gist.github.com/susanBuck/39d1a384779f3d596afb19fcad6b598c" which I have tried and it works always, try it out..

  • Open C:\xampp\mysql\bin\my.ini (MySQL config file)
  • Find the line [mysqld] and right below it add skip-grant-tables. Example:

    [mysqld] skip-grant-tables port= 3306 socket = "C:/xampp/mysql/mysql.sock" basedir = "C:/xampp/mysql" tmpdir = "C:/xampp/tmp" [...etc...]

  • This should allow you to access MySQL if you don't know your password.

  • Stop and start MySQL from XAMPP to make this change take effect.
  • Next, in command line, connect to MySQL:

C:\xampp\mysql\bin\mysql.exe --user=root

  • Once in MySQL command line "select" the mysql database:

USE mysql;

  • Then, the following command will list all your MySQL users:

SELECT * FROM user \G;

  • You can scan through the rows to see what the root user's password is set to. There will be a few root users listed, with different hosts.
  • To set root user's to have a password of your choice, run this command:

UPDATE user SET password = PASSWORD('secret_pass') WHERE user = 'root';

  • -OR- To set all root user's to have a blank password, run this command:

UPDATE user SET password = '' WHERE user = 'root';

When you're done, run exit; to exit the MySQL command line.

Next, re-enable password checking by removing skip-grant-tables from C:\xampp\mysql\bin\my.ini.

Save changes, restart MySQL from XAMPP.

The imported project "C:\Microsoft.CSharp.targets" was not found

In my case I could not load one out of 5 projects in my solution.

It helped to close Visual Studio and I had to delete Microsoft.Net.Compilers.1.3.2 nuget folder under packages folder.

Afterwards, open your solution again and the project loaded as expected

Just to be sure, close all instances of VS before you delete the folder.

CORS with spring-boot and angularjs not working

This works for me:

@Configuration
public class MyConfig extends WebSecurityConfigurerAdapter  {
   //...
   @Override
   protected void configure(HttpSecurity http) throws Exception {

       //...         

       http.cors().configurationSource(new CorsConfigurationSource() {

        @Override
        public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowedHeaders(Collections.singletonList("*"));
            config.setAllowedMethods(Collections.singletonList("*"));
            config.addAllowedOrigin("*");
            config.setAllowCredentials(true);
            return config;
        }
      });

      //...

   }

   //...

}

How to calculate age (in years) based on Date of Birth and getDate()

EDIT: THIS ANSWER IS INCORRECT. I leave it in here as a warning to anyone tempted to use dayofyear, with a further edit at the end.


If, like me, you do not want to divide by fractional days or risk rounding/leap year errors, I applaud @Bacon Bits comment in a post above https://stackoverflow.com/a/1572257/489865 where he says:

If we're talking about human ages, you should calculate it the way humans calculate age. It has nothing to do with how fast the earth moves and everything to do with the calendar. Every time the same month and day elapses as the date of birth, you increment age by 1. This means the following is the most accurate because it mirrors what humans mean when they say "age".

He then offers:

DATEDIFF(yy, @date, GETDATE()) -
CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE()))
THEN 1 ELSE 0 END

There are several suggestions here involving comparing the month & day (and some get it wrong, failing to allow for the OR as correctly here!). But nobody has offered dayofyear, which seems so simple and much shorter. I offer:

DATEDIFF(year, @date, GETDATE()) -
CASE WHEN DATEPART(dayofyear, @date) > DATEPART(dayofyear, GETDATE()) THEN 1 ELSE 0 END

[Note: Nowhere in SQL BOL/MSDN is what DATEPART(dayofyear, ...) returns actually documented! I understand it to be a number in the range 1--366; most importantly, it does not change by locale as per DATEPART(weekday, ...) & SET DATEFIRST.]


EDIT: Why dayofyear goes wrong: As user @AeroX has commented, if the birth/start date is after February in a non leap year, the age is incremented one day early when the current/end date is a leap year, e.g. '2015-05-26', '2016-05-25' gives an age of 1 when it should still be 0. Comparing the dayofyear in different years is clearly dangerous. So using MONTH() and DAY() is necessary after all.

Understanding implicit in Scala

Also, in the above case there should be only one implicit function whose type is double => Int. Otherwise, the compiler gets confused and won't compile properly.

//this won't compile

implicit def doubleToInt(d: Double) = d.toInt
implicit def doubleToIntSecond(d: Double) = d.toInt
val x: Int = 42.0

Get screenshot on Windows with Python?

A simple way to take a screenshot is through Pygame.

 pygame.image.save(Surface, filename)

Where 'Surface' is the surface you are taking a screenshot of, and 'filename' is the file path, name, and type where you save thew image.

You can export as BMP, TGA, PNG, or JPEG. As of Pygame 1.8, PNG, and JPEG also work.

If no file extension is specified it will default to a .TGA file.

You can even use the 'os' library for saving to specific file directories.

An example:

import os
import pygame
surface = pygame.display.set_mode((100, 100), 0, 32)
surface.fill((255, 255, 255))
pygame.draw.circle(surface, (0, 0, 0), (10, 10), 15, 0)
pygame.display.update()
pygame.image.save(surface, os.path.expanduser("~/Desktop/pic.png"))

This saves anything on the 'surface' Surface to the user's desktop as pic.png

Time in milliseconds in C

The standard C library provides timespec_get. It can tell time up to nanosecond precision, if the system supports. Calling it, however, takes a bit more effort because it involves a struct. Here's a function that just converts the struct to a simple 64-bit integer so you can get time in milliseconds.

#include <stdio.h>
#include <inttypes.h>
#include <time.h>

int64_t millis()
{
    struct timespec now;
    timespec_get(&now, TIME_UTC);
    return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}

int main(void)
{
    printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}

Unlike clock, this function returns a Unix timestamp so it will correctly account for the time spent in blocking functions, such as sleep.

Looking for a short & simple example of getters/setters in C#

This would be a get/set in C# using the smallest amount of code possible. You get auto-implemented properties in C# 3.0+.

public class Contact
{
   public string Name { get; set; }
}

Java serialization - java.io.InvalidClassException local class incompatible

The short answer here is the serial ID is computed via a hash if you don't specify it. (Static members are not inherited--they are static, there's only (1) and it belongs to the class).

http://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html

The getSerialVersionUID method returns the serialVersionUID of this class. Refer to Section 4.6, "Stream Unique Identifiers." If not specified by the class, the value returned is a hash computed from the class's name, interfaces, methods, and fields using the Secure Hash Algorithm (SHA) as defined by the National Institute of Standards.

If you alter a class or its hierarchy your hash will be different. This is a good thing. Your objects are different now that they have different members. As such, if you read it back in from its serialized form it is in fact a different object--thus the exception.

The long answer is the serialization is extremely useful, but probably shouldn't be used for persistence unless there's no other way to do it. Its a dangerous path specifically because of what you're experiencing. You should consider a database, XML, a file format and probably a JPA or other persistence structure for a pure Java project.

What's the difference between django OneToOneField and ForeignKey?

The easiest way to draw a relationship between items is by understanding them in plain languages. Example

A user can have many cars but then a car can have just one owner. After establishing this, the foreign key should be used on the item with the many relationship. In this case the car. Meaning you'll include user as a foreign key in cars

And a one on one relationship is quite simple. Say a man and a heart. A man has only one heart and a heart can belong to just one man

Regex to accept alphanumeric and some special character in Javascript?

use:

/^[ A-Za-z0-9_@./#&+-]*$/

You can also use the character class \w to replace A-Za-z0-9_

PHPDoc type hinting for array of objects?

As DanielaWaranie mentioned in her answer - there is a way to specify the type of $item when you iterating over $items in $collectionObject: Add @return MyEntitiesClassName to current() and rest of the Iterator and ArrayAccess-methods which return values.

Boom! No need in /** @var SomeObj[] $collectionObj */ over foreach, and works right with collection object, no need to return collection with specific method described as @return SomeObj[].

I suspect not all IDE support it but it works perfectly fine in PhpStorm, which makes me happier.

Example:

class MyCollection implements Countable, Iterator, ArrayAccess {

    /**
     * @return User
     */
    public function current() {
        return $this->items[$this->cursor];
    }

    //... implement rest of the required `interface` methods and your custom
}

What useful i was going to add posting this answer

In my case current() and rest of interface-methods are implemented in Abstract-collection class and I do not know what kind of entities will eventually be stored in collection.

So here is the trick: Do not specify return type in abstract class, instead use PhpDoc instuction @method in description of specific collection class.

Example:

class User {

    function printLogin() {
        echo $this->login;
    }

}

abstract class MyCollection implements Countable, Iterator, ArrayAccess {

    protected $items = [];

    public function current() {
        return $this->items[$this->cursor];
    }

    //... implement rest of the required `interface` methods and your custom
    //... abstract methods which will be shared among child-classes
}

/**
 * @method User current()
 * ...rest of methods (for ArrayAccess) if needed
 */
class UserCollection extends MyCollection {

    function add(User $user) {
        $this->items[] = $user;
    }

    // User collection specific methods...

}

Now, usage of classes:

$collection = new UserCollection();
$collection->add(new User(1));
$collection->add(new User(2));
$collection->add(new User(3));

foreach ($collection as $user) {
    // IDE should `recognize` method `printLogin()` here!
    $user->printLogin();
}

Once again: I suspect not all IDE support it, but PhpStorm does. Try yours, post in comment the results!

How to run .APK file on emulator

Steps (These apply for Linux. For other OS, visit here) -

  1. Copy the apk file to platform-tools in android-sdk linux folder.
  2. Open Terminal and navigate to platform-tools folder in android-sdk.
  3. Then Execute this command -

    ./adb install FileName.apk

  4. If the operation is successful (the result is displayed on the screen), then you will find your file in the launcher of your emulator.

For more info can check this link : android videos

How to remove list elements in a for loop in Python?

Iterate through a copy of the list:

>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
    print item
    if item == "b":
        a.remove(item)

a
b
c
d
e
>>> print a
['a', 'c', 'd', 'e']

Why is January month 0 in Java Calendar?

Personally, I took the strangeness of the Java calendar API as an indication that I needed to divorce myself from the Gregorian-centric mindset and try to program more agnostically in that respect. Specifically, I learned once again to avoid hardcoded constants for things like months.

Which of the following is more likely to be correct?

if (date.getMonth() == 3) out.print("March");

if (date.getMonth() == Calendar.MARCH) out.print("March");

This illustrates one thing that irks me a little about Joda Time - it may encourage programmers to think in terms of hardcoded constants. (Only a little, though. It's not as if Joda is forcing programmers to program badly.)

Inputting a default image in case the src attribute of an html <img> is not valid?

The above solution is incomplete, it missed the attribute src.

this.src and this.attribute('src') are NOT the same, the first one contains the full reference to the image, for example http://my.host/error.jpg, but the attribute just keeps the original value, error.jpg

Correct solution

<img src="foo.jpg" onerror="if (this.src != 'error.jpg' && this.attribute('src') != 'error.jpg') this.src = 'error.jpg';" />

Default optional parameter in Swift function

Swift is not like languages like JavaScript, where you can call a function without passing the parameters and it will still be called. So to call a function in Swift, you need to assign a value to its parameters.

Default values for parameters allow you to assign a value without specifying it when calling the function. That's why test() works when you specify a default value on test's declaration.

If you don't include that default value, you need to provide the value on the call: test(nil).

Also, and not directly related to this question, but probably worth to note, you are using the "C++" way of dealing with possibly null pointers, for dealing with possible nil optionals in Swift. The following code is safer (specially in multithreading software), and it allows you to avoid the forced unwrapping of the optional:

func test(firstThing: Int? = nil) {
    if let firstThing = firstThing {
        print(firstThing)
    }
    print("done")
}
test()

IIS w3svc error

Run cmd as administrator. Type iisreset. That's it.

How do you setLayoutParams() for an ImageView?

You need to set the LayoutParams of the ViewGroup the ImageView is sitting in. For example if your ImageView is inside a LinearLayout, then you create a

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

This is because it's the parent of the View that needs to know what size to allocate to the View.

Insert default value when parameter is null

The best option by far is to create an INSTEAD OF INSERT trigger for your table, removing the default values from your table, and moving them into the trigger.

This will look like the following:

create trigger dbo.OnInsertIntoT
ON TablenameT
INSTEAD OF INSERT
AS
insert into TablenameT
select
   IsNull(column1 ,<default_value>)
  ,IsNull(column2 ,<default_value>)
  ...
from inserted

This makes it work NO MATTER what code tries to insert NULLs into your table, avoids stored procedures, is completely transparent, and you only need to maintain your default values in one place, namely this trigger.

How to 'insert if not exists' in MySQL?

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

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

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

Count unique values using pandas groupby

I think you can use SeriesGroupBy.nunique:

print (df.groupby('param')['group'].nunique())
param
a    2
b    1
Name: group, dtype: int64

Another solution with unique, then create new df by DataFrame.from_records, reshape to Series by stack and last value_counts:

a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a    2
b    1
dtype: int64

Creating a constant Dictionary in C#

Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.

There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:

switch (myString)
{
   case "cat": return 0;
   case "dog": return 1;
   case "elephant": return 3;
}

This is exactly what you want. And yes, I know, it's ugly.

Hive Alter table change Column Name

Change Column Name/Type/Position/Comment:

ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]

Example:

CREATE TABLE test_change (a int, b int, c int);

// will change column a's name to a1
ALTER TABLE test_change CHANGE a a1 INT;

How to add subject alernative name to ssl certs?

Although this question was more specifically about IP addresses in Subject Alt. Names, the commands are similar (using DNS entries for a host name and IP entries for IP addresses).

To quote myself:

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1

Note that you only need Java 7's keytool to use this command. Once you've prepared your keystore, it should work with previous versions of Java.

(The rest of this answer also mentions how to do this with OpenSSL, but it doesn't seem to be what you're using.)

What is the difference between ( for... in ) and ( for... of ) statements?

A see a lot of good answers, but I decide to put my 5 cents just to have good example:

For in loop

iterates over all enumerable props

_x000D_
_x000D_
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var key in nodes) {_x000D_
  console.log( key );_x000D_
}
_x000D_
_x000D_
_x000D_

For of loop

iterates over all iterable values

_x000D_
_x000D_
let nodes = document.documentElement.childNodes;_x000D_
_x000D_
for (var node of nodes) {_x000D_
  console.log( node.toString() );_x000D_
}
_x000D_
_x000D_
_x000D_

Is this the proper way to do boolean test in SQL?

PostgreSQL supports boolean types, so your SQL query would work perfectly in PostgreSQL.

What is the difference between an interface and abstract class?

Interfaces

An interface is a contract: The person writing the interface says, "hey, I accept things looking that way", and the person using the interface says "OK, the class I write looks that way".

An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern.

For example (pseudo code):

// I say all motor vehicles should look like this:
interface MotorVehicle
{
    void run();

    int getFuel();
}

// My team mate complies and writes vehicle looking that way
class Car implements MotorVehicle
{

    int fuel;

    void run()
    {
        print("Wrroooooooom");
    }


    int getFuel()
    {
        return this.fuel;
    }
}

Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there isn't any expensive look-up to do. It's great when it matters, such as in embedded devices.


Abstract classes

Abstract classes, unlike interfaces, are classes. They are more expensive to use, because there is a look-up to do when you inherit from them.

Abstract classes look a lot like interfaces, but they have something more: You can define a behavior for them. It's more about a person saying, "these classes should look like that, and they have that in common, so fill in the blanks!".

For example:

// I say all motor vehicles should look like this:
abstract class MotorVehicle
{

    int fuel;

    // They ALL have fuel, so lets implement this for everybody.
    int getFuel()
    {
         return this.fuel;
    }

    // That can be very different, force them to provide their
    // own implementation.
    abstract void run();
}

// My teammate complies and writes vehicle looking that way
class Car extends MotorVehicle
{
    void run()
    {
        print("Wrroooooooom");
    }
}

Implementation

While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are.

In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared.

In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods).

As usual with programming, there is theory, practice, and practice in another language :-)

<hr> tag in Twitter Bootstrap not functioning correctly?

You may want one of these, so to correspond to the Bootstrap layout:

<div class="col-xs-12">
    <hr >
</div>

<!-- or -->

<div class="col-xs-12">
    <hr style="border-style: dashed; border-top-width: 2px;">
</div>

<!-- or -->

<div class="col-xs-12">
    <hr class="col-xs-1" style="border-style: dashed; border-top-width: 2px;">
</div>

Without a DIV grid element included, layout may brake on different devices.

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Some basic differences can be written in short:

MVC:

Traditional MVC is where there is a

  1. Model: Acts as the model for data
  2. View : Deals with the view to the user which can be the UI
  3. Controller: Controls the interaction between Model and View, where view calls the controller to update model. View can call multiple controllers if needed.

MVP:

Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.

MVVM

The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.

change values in array when doing foreach

Javascript is pass by value, and which essentially means part is a copy of the value in the array.

To change the value, access the array itself in your loop.

arr[index] = 'new value';

restart mysql server on windows 7

First try:

net stop MySQL   
net start MySQL

If that does not work, try using the windows interface:

Start > Control Panel > System and Security > Administrative Tools > Services

Look for your version of MySQL (In my case - MySQL55), highlight and click the green start arrow. The status should change to "Started"

jQuery fade out then fade in

After jQuery 1.6, using promise seems like a better option.

var $div1 = $('#div1');
var fadeOutDone = $div1.fadeOut().promise();
// do your logic here, e.g.fetch your 2nd image url
$.get('secondimageinfo.json').done(function(data){
  fadeoOutDone.then(function(){
    $div1.html('<img src="' + data.secondImgUrl + '" alt="'data.secondImgAlt'">');
    $div1.fadeIn();
  });
});

Onclick on bootstrap button

Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:

$('#myButton').on('click', function(event) {
  event.preventDefault(); // To prevent following the link (optional)
  ...
});

You can also use inline javascript in the onclick attribute:

<a ... onclick="myFunc();">..</a>

Do I cast the result of malloc?

I prefer to do the cast, but not manually. My favorite is using g_new and g_new0 macros from glib. If glib is not used, I would add similar macros. Those macros reduce code duplication without compromising type safety. If you get the type wrong, you would get an implicit cast between non-void pointers, which would cause a warning (error in C++). If you forget to include the header that defines g_new and g_new0, you would get an error. g_new and g_new0 both take the same arguments, unlike malloc that takes fewer arguments than calloc. Just add 0 to get zero-initialized memory. The code can be compiled with a C++ compiler without changes.

Check if a string is palindrome

bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

What do two question marks together mean in C#?

It's the null coalescing operator.

http://msdn.microsoft.com/en-us/library/ms173224.aspx

Yes, nearly impossible to search for unless you know what it's called! :-)

EDIT: And this is a cool feature from another question. You can chain them.

Hidden Features of C#?

How to end C++ code

People are saying "call exit(return code)," but this is bad form. In small programs it is fine, but there are a number of issues with this:

  1. You will end up having multiple exit points from the program
  2. It makes code more convoluted (like using goto)
  3. It cannot release memory allocated at runtime

Really, the only time you should exit the problem is with this line in main.cpp:

return 0;

If you are using exit() to handle errors, you should learn about exceptions (and nesting exceptions), as a much more elegant and safe method.

Check cell for a specific letter or set of letters

You can use the following formula,

=IF(ISTEXT(REGEXEXTRACT(A1; "Bla")); "Yes";"No")

How to convert string to string[]?

You can create a string[] (string array) that contains your string like :

string someString = "something";
string[] stringArray = new string[]{ someString };

The variable stringArray will now have a length of 1 and contain someString.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

org.glassfish.jersey.servlet.ServletContainer.class

here remove .class

org.glassfish.jersey.servlet.ServletContainer now you wont get

What is the OR operator in an IF statement

See C# Operators for C# operators including OR which is ||

Marker content (infoWindow) Google Maps

Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:

Each marker gets an "infowindow" entry :

function createMarker(lat, lon, html) {
    var newmarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        map: map,
        title: html
    });

    newmarker['infowindow'] = new google.maps.InfoWindow({
            content: html
        });

    google.maps.event.addListener(newmarker, 'mouseover', function() {
        this['infowindow'].open(map, this);
    });
}

How to add a single item to a Pandas Series

  • ser1 = pd.Sereis(np.linspace(1, 10, 2))
  • element = np.nan
  • ser1 = ser1.append(pd.Series(element))

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

For MAVEN,

I tried all of the above methods, but couldn't find the solution,

So below are the steps I tried(A mix of some solutions),

  1. mvn clean

  2. mvn idea:clean

  3. Invalidate cache and restart
  4. Remove all the extra .iml files you see in the project structure.
  5. At the root directory of your project, run mvn idea:idea and mvn clean install, to reimport all the dependencies of your maven project.

(Make sure you don't have extra .iml files other than the project/subprojects .iml files)

android pinch zoom

I have created a project for basic pinch-zoom that supports Android 2.1+

Available here

How to get row data by clicking a button in a row in an ASP.NET gridview

You can also use button click event like this:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Button ID="Button1" runat="server" Text="Button" 
                    OnClick="MyButtonClick" />
    </ItemTemplate>
</asp:TemplateField>
protected void MyButtonClick(object sender, System.EventArgs e)
{
    //Get the button that raised the event
    Button btn = (Button)sender;

    //Get the row that contains this button
    GridViewRow gvr = (GridViewRow)btn.NamingContainer;
} 

OR

You can do like this to get data:

 void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
 {

    // If multiple ButtonField column fields are used, use the
    // CommandName property to determine which button was clicked.
    if(e.CommandName=="Select")
    {
      // Convert the row index stored in the CommandArgument
      // property to an Integer.
      int index = Convert.ToInt32(e.CommandArgument);    

      // Get the last name of the selected author from the appropriate
      // cell in the GridView control.
      GridViewRow selectedRow = CustomersGridView.Rows[index];
    }
}

and Button in gridview should have command like this and handle rowcommand event:

<asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="false"
        onrowcommand="CustomersGridView_RowCommand"
        runat="server">

        <columns>
          <asp:buttonfield buttontype="Button" 
            commandname="Select"
            headertext="Select Customer" 
            text="Select"/>
        </columns>
  </asp:gridview>

Check full example on MSDN

Example use of "continue" statement in Python?

Here is very good visual representation about continue and break statements

Chart

source

How to read a .xlsx file using the pandas Library in iPython?

The following worked for me:

from pandas import read_excel
my_sheet = 'Sheet1' # change it to your sheet name, you can find your sheet name at the bottom left of your excel file
file_name = 'products_and_categories.xlsx' # change it to the name of your excel file
df = read_excel(file_name, sheet_name = my_sheet)
print(df.head()) # shows headers with top 5 rows

Get file content from URL?

Use file_get_contents in combination with json_decode and echo.

How to set the height of table header in UITableView?

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
}

or you can use like this also

tableView.estimatedSectionHeaderHeight 

Body set to overflow-y:hidden but page is still scrollable in Chrome

What works for me on /FF and /Chrome:

body {

    position: fixed;
    width: 100%;
    height: 100%;

}

overflow: hidden just disables display of the scrollbars. (But you can put it in there if you like to).

There is one drawback I found: If you use this method on a page which you want only temporarily to stop scrolling, setting position: fixed will scroll it to the top. This is because position: fixed uses absolute positions which are currently set to 0/0.

This can be repaired e.g. with jQuery:

var lastTop;

function stopScrolling() {
    lastTop = $(window).scrollTop();      
    $('body').addClass( 'noscroll' )          
         .css( { top: -lastTop } )        
         ;            
}

function continueScrolling() {                    

    $('body').removeClass( 'noscroll' );      
    $(window).scrollTop( lastTop );       
}                                         

git cherry-pick says "...38c74d is a merge but no -m option was given"

Simplify. Cherry-pick the commits. Don't cherry-pick the merge.

Here's a rewrite of the accepted answer that ideally clarifies the advantages/risks of possible approaches:

You're trying to cherry pick fd9f578, which was a merge with two parents.

Instead of cherry-picking a merge, the simplest thing is to cherry pick the commit(s) you actually want from each branch in the merge.

Since you've already merged, it's likely all your desired commits are in your list. Cherry-pick them directly and you don't need to mess with the merge commit.

explanation

The way a cherry-pick works is by taking the diff that a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying the changeset to your current branch.

If a commit has two or more parents, as is the case with a merge, that commit also represents two or more diffs. The error occurs because of the uncertainty over which diff should apply.

alternatives

If you determine you need to include the merge vs cherry-picking the related commits, you have two options:

  1. (More complicated and obscure; also discards history) you can indicate which parent should apply.

    • Use the -m option to do so. For example, git cherry-pick -m 1 fd9f578 will use the first parent listed in the merge as the base.

    • Also consider that when you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m into that one commit. You lose all their history, and glom together all their diffs. Your call.

  2. (Simpler and more familiar; preserves history) you can use git merge instead of git cherry-pick.

    • As is usual with git merge, it will attempt to apply all commits that exist on the branch you are merging, and list them individually in your git log.

How to get a list of column names

Use a recursive query. Given

create table t (a int, b int, c int);

Run:

with recursive
  a (cid, name) as (select cid, name from pragma_table_info('t')),
  b (cid, name) as (
    select cid, '|' || name || '|' from a where cid = 0
    union all
    select a.cid, b.name || a.name || '|' from a join b on a.cid = b.cid + 1
  )
select name
from b
order by cid desc
limit 1;

Alternatively, just use group_concat:

select '|' || group_concat(name, '|') || '|' from pragma_table_info('t')

Both yield:

|a|b|c|

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

IOCTL Linux device driver

An ioctl, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.

An alternative is the sysfs interface, where you set up a file under /sys/ and read/write that to get information from and to the driver. An example of how to set this up:

static ssize_t mydrvr_version_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
    return sprintf(buf, "%s\n", DRIVER_RELEASE);
}

static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);

And during driver setup:

device_create_file(dev, &dev_attr_version);

You would then have a file for your device in /sys/, for example, /sys/block/myblk/version for a block driver.

Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl or libnl3 libraries.

Procedure or function !!! has too many arguments specified

For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.

Just put use [DBName] on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.

How do you convert Html to plain text?

To add to vfilby's answer, you can just perform a RegEx replace within your code; no new classes are necessary. In case other newbies like myself stumple upon this question.

using System.Text.RegularExpressions;

Then...

private string StripHtml(string source)
{
        string output;

        //get rid of HTML tags
        output = Regex.Replace(source, "<[^>]*>", string.Empty);

        //get rid of multiple blank lines
        output = Regex.Replace(output, @"^\s*$\n", string.Empty, RegexOptions.Multiline);

        return output;
}

How do I define the name of image built with docker-compose

As per docker-compose 1.6.0:

You can now specify both a build and an image key if you're using the new file format. docker-compose build will build the image and tag it with the name you've specified, while docker-compose pull will attempt to pull it.

So your docker-compose.yml would be

version: '2'
services:
  wildfly:
      build: /path/to/dir/Dockerfile
      image: wildfly_server
      ports:
       - 9990:9990
       - 80:8080

To update docker-compose

sudo pip install -U docker-compose==1.6.0

Property [title] does not exist on this collection instance

With get() method you get a collection (all data that match the query), try to use first() instead, it return only one element, like this:

$about = Page::where('page', 'about-me')->first();

gcc error: wrong ELF class: ELFCLASS64

sudo apt-get install ia32-libs 

DIV table colspan: how?

you just use the :nth-child(num) in css for add the colspan like

 <style>
 div.table
  {
  display:table;
  width:100%;
  }
 div.table-row
  {
   display:table-row;
  }
 div.table-td
 {
  display:table-cell;
 }
 div.table-row:nth-child(1)
 {
  display:block;
 }
</style>
<div class="table>
    <div class="table-row">test</div>
    <div class="table-row">
      <div class="table-td">data1</div>
      <div class="table-td">data2</div>
    </div>
</div>

Batch File: ( was unexpected at this time

You are getting that error because when the param1 if statements are evaluated, param is always null due to being scoped variables without delayed expansion.

When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.

Also I recommend using if not defined command to determine if a variable is set.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.

set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if not defined a goto :aPrompt
echo %a%

IF "%a%"=="2" (
    title USB WRITE LOCK
    echo What do you want to do?
    echo 1.Apply USB Write Protection
    echo 2.Remove USB Write Protection

    ::param1
    set "param1=%globalparam2%"
    goto :param1Check
    :param1Prompt
    set /p "param1=Enter Choice: "
    :param1Check
    if not defined param1 goto :param1Prompt
    echo !param1!

    if "!param1!"=="1" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001 
        echo USB Write is Locked!
    )
    if "!param1!"=="2" (
        REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
        echo USB Write is Unlocked! 
    )
)
pause
endlocal

What's the difference between '$(this)' and 'this'?

Yes you only need $() when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.

$(this)[0] === this

Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.

$("#myDiv")[0] === document.getElementById("myDiv");

And so on...

FileNotFoundException while getting the InputStream object from HttpURLConnection

I don't know about your Spring/JAXB combination, but the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.

Replace

InputStream response = con.getInputStream();

by

int status = con.getResponseCode();

All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.

If the status starts with 4nn or 5nn, you'd like to use getErrorStream() instead to read the response body which may contain the error details.

InputStream error = con.getErrorStream();

Array copy values to keys in PHP

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}

Which is a better way to check if an array has more than one element?

isset() only checks if a variable is set.. Has got nothing to do with size or what the array contains

Image.open() cannot identify image file - Python?

For anyone who make it in bigger scale, you might have also check how many file descriptors you have. It will throw this error if you ran out at bad moment.

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

CSS: How can I set image size relative to parent height?

Use max-width property of CSS, like this :

img{
  max-width:100%;
}

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

The easiest and the most effective way would be to allow eclipse to generate and override the equals and hashcode method. Just select the attributes to be checked for duplicates when prompted and you should be all set.

Also once the list is ready, put it into a Set and you have the duplicates gone.

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

For camera access use:

<key>NSCameraUsageDescription</key>
<string>Camera Access Warning</string>

Regular expression to match URLs in Java

This works too:

String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

Note:

String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>

String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>

So probably the first one is more useful for general use.

Unable to create Android Virtual Device

I had to move the folders inside a folder named "default" to the android-## folder so Eclipse could see the images.

Can't load AMD 64-bit .dll on a IA 32-bit platform

Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.

mongodb how to get max value from collections

For max value, we can write sql query as

select age from table_name order by age desc limit 1

same way we can write in mongodb too.

db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age

How to send data with angularjs $http.delete() request?

$http.delete method doesn't accept request body. You can try this workaround :

$http( angular.merge({}, config || {}, {
    method  : 'delete',
    url     : _url,
    data    : _data
}));

where in config you can pass config data like headers etc.

How to convert color code into media.brush?

What version of WPF are you using? I tried in both 3.5 and 4.0, and Fill="#FF000000" should work fine in a in the XAML. There is another syntax, however, if it doesn't. Here's a 3.5 XAML that I tested with two different ways. Better yet would be to use a resource.

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,12,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FF00AE00" />
    <Rectangle Height="100" HorizontalAlignment="Left" Margin="100,132,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" >
        <Rectangle.Fill>
            <SolidColorBrush Color="#FF00AE00" />
        </Rectangle.Fill>
    </Rectangle>
</Grid>

Stored Procedure error ORA-06550

create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS)  from PLAYERREGULARSEASON  where TEAM    = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)

LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;

END;
/

How to run a cronjob every X minutes?

2 steps to check if a cronjob is working :

  1. Login on the server with the user that execute the cronjob
  2. Manually run php command :

    /usr/bin/php /mydomain.in/cromail.php

And check if any error is displayed

Copy existing project with a new name in Android Studio

This is a combination nt.bas's answer and step 9 of Civic's answer with visual examples because it took me a while to find out what was intended since I am new to Android Studio. It has been tested in Android Studio 3.2.1.

  1. Open the project you want to clone in Android Studio. (In this example, the old project name was test5 and the new project name was test6)

  2. In the left file-overview pane, click: Project (where it might currently say android).

fig0

  1. Right mouse button click on the project within the file explorer pane and click refactor>clone.

fig1

  1. Change the "New name" to your new project name and click ok.

fig2

  1. File>open>New window>Select your new project>Open in new project window. In the new window, wait until the bottom line of Android studio is finished/says:"Gradle Sync Finished".

16

17

14

  1. In the file overview pane and right mouse button click (RMB) on: app.java/< your old project name (not the test one, not the androidTest one, just the blank one)>

fig8

  1. Enter the new name of your package and select both checkmarks, click refactor.

fig9 fig10

  1. In the bottom left bar click "Do refactor".

fig12

  1. Open app/res/values/strings.xml and change name of the old project (e.g. test5) to the new name of the project in line:

    <string name="app_name">test5</string>
    

fig3

  1. Open Gradle scripts/build.gradle (Module:app) and change the line to the same line with your new project name:%fig4

    applicationId "com.example.a.test5"    
    

fig4

  1. A yellow line will appear at the top of your code pane, requesting gradle sync. Press "sync now".

fig5

  1. in top bar, press build>Clean project.

fig13

  1. If it says "Gradle build finished" in the bottom left, you click "Build>Rebuild project".

fig14

fig15

  1. Now you should be able to compile and run your project again (if it worked in the first place).

How to get city name from latitude and longitude coordinates in Google Maps?

Just Use this method and pass your lat, long.

public static void getAddress(Context context, double LATITUDE, double LONGITUDE) {

//Set Address
try {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
    if (addresses != null && addresses.size() > 0) {



        String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = addresses.get(0).getLocality();
        String state = addresses.get(0).getAdminArea();
        String country = addresses.get(0).getCountryName();
        String postalCode = addresses.get(0).getPostalCode();
        String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

        Log.d(TAG, "getAddress:  address" + address);
        Log.d(TAG, "getAddress:  city" + city);
        Log.d(TAG, "getAddress:  state" + state);
        Log.d(TAG, "getAddress:  postalCode" + postalCode);
        Log.d(TAG, "getAddress:  knownName" + knownName);

    }
} catch (IOException e) {
    e.printStackTrace();
}
    return;
}

Java generics - ArrayList initialization

ArrayList<Integer> a = new ArrayList<Number>(); 

Does not work because the fact that Number is a super class of Integer does not mean that List<Number> is a super class of List<Integer>. Generics are removed during compilation and do not exist on runtime, so parent-child relationship of collections cannot be be implemented: the information about element type is simply removed.

ArrayList<? extends Object> a1 = new ArrayList<Object>();
a1.add(3);

I cannot explain why it does not work. It is really strange but it is a fact. Really syntax <? extends Object> is mostly used for return values of methods. Even in this example Object o = a1.get(0) is valid.

ArrayList<?> a = new ArrayList<?>()

This does not work because you cannot instantiate list of unknown type...

Edit Crystal report file without Crystal Report software

This may be a long shot, but Crystal Reports for Eclipse is free. I'm not sure if it will work, but if all you need is to edit some static text, you could get that version of CR and get the job done.

What does /p mean in set /p?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Two ways I've used it... first:

SET /P variable=

When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

And second:

SET /P variable=<%temp%\filename.txt

Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

:before and background-image... should it work?

 color: transparent; 

make the tricks for me

#videos-part:before{
    font-size: 35px;
    line-height: 33px;
    width: 16px;
    color: transparent;
    content: 'AS YOU LIKE';
    background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUwIDUwIiBoZWlnaHQ9IjUwcHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MCA1MCIgd2lkdGg9IjUwcHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik04LDE0TDQsNDloNDJsLTQtMzVIOHoiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzAwMDAwMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbWl0ZXJsaW1pdD0iMTAiIHN0cm9rZS13aWR0aD0iMiIvPjxyZWN0IGZpbGw9Im5vbmUiIGhlaWdodD0iNTAiIHdpZHRoPSI1MCIvPjxwYXRoIGQ9Ik0zNCwxOWMwLTEuMjQxLDAtNi43NTksMC04ICBjMC00Ljk3MS00LjAyOS05LTktOXMtOSw0LjAyOS05LDljMCwxLjI0MSwwLDYuNzU5LDAsOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1taXRlcmxpbWl0PSIxMCIgc3Ryb2tlLXdpZHRoPSIyIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIxOSIgcj0iMiIvPjxjaXJjbGUgY3g9IjE2IiBjeT0iMTkiIHI9IjIiLz48L3N2Zz4=');
    background-size: 25px;
    background-repeat: no-repeat;
    }

Why does an image captured using camera intent gets rotated on some devices on Android?

Got an answer for this problem without using ExifInterface. We can get the rotation of the camera either front camera or back camera whichever you are using then while creating the Bitmap we can rotate the bitmap using Matrix.postRotate(degree)

public int getRotationDegree() {
    int degree = 0;

    for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(i, info);
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
            degree = info.orientation;

            return degree;
        }
    }

    return degree;
}

After calculating the rotation you can rotate you bitmap like below:

 Matrix matrix = new Matrix();

 matrix.postRotate(getRotationDegree());

 Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

Herare bm should be your bitmap.

If you want to know the rotation of your front camera just change Camera.CameraInfo.CAMERA_FACING_BACK to Camera.CameraInfo.CAMERA_FACING_FRONT above.

I hope this helps.

How to achieve pagination/table layout with Angular.js?

The best simple plug and play solution for pagination.

https://ciphertrick.com/2015/06/01/search-sort-and-pagination-ngrepeat-angularjs/#comment-1002

you would jus need to replace ng-repeat with custom directive.

<tr dir-paginate="user in userList|filter:search |itemsPerPage:7">
<td>{{user.name}}</td></tr>

Within the page u just need to add

<div align="center">
       <dir-pagination-controls
            max-size="100"
            direction-links="true"
            boundary-links="true" >
       </dir-pagination-controls>
</div>

In your index.html load

<script src="./js/dirPagination.js"></script>

In your module just add dependencies

angular.module('userApp',['angularUtils.directives.dirPagination']);

and thats all needed for pagination.

Might be helpful for someone.

Is it possible to change the radio button icon in an android radio button group

You can put custom image in radiobutton like normal button. for that create one XML file in drawable folder e.g

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sub_screens_aus_hl" 
    android:state_pressed="true"/>  
<item android:drawable="@drawable/sub_screens_aus" 
    android:state_checked="true"/>  
<item android:drawable="@drawable/sub_screens_aus" 
    android:state_focused="true" />
<item android:drawable="@drawable/sub_screens_aus_dis" />  
</selector> 

Here you can use 3 different images for radiobutton

and use this file to RadioButton like:

android:button="@drawable/aus"
android:layout_height="120dp"
android:layout_width="wrap_content" 

Vue JS mounted()

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

BEGIN - END block atomic transactions in PL/SQL

BEGIN-END blocks are the building blocks of PL/SQL, and each PL/SQL unit is contained within at least one such block. Nesting BEGIN-END blocks within PL/SQL blocks is usually done to trap certain exceptions and handle that special exception and then raise unrelated exceptions. Nevertheless, in PL/SQL you (the client) must always issue a commit or rollback for the transaction.

If you wish to have atomic transactions within a PL/SQL containing transaction, you need to declare a PRAGMA AUTONOMOUS_TRANSACTION in the declaration block. This will ensure that any DML within that block can be committed or rolledback independently of the containing transaction.

However, you cannot declare this pragma for nested blocks. You can only declare this for:

  • Top-level (not nested) anonymous PL/SQL blocks
  • List item
  • Local, standalone, and packaged functions and procedures
  • Methods of a SQL object type
  • Database triggers

Reference: Oracle

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

Any good boolean expression simplifiers out there?

I found that The Boolean Expression Reducer is much easier to use than Logic Friday. Plus it doesn't require installation and is multi-platform (Java).

Also in Logic Friday the expression A | B just returns 3 entries in truth table; I expected 4.

How to create a directory and give permission in single command

IMO, it's better to use the install command in such situations. I was trying to make systemd-journald persistent across reboots.

install -d  -g systemd-journal -m 2755 -v /var/log/journal

How to set width of mat-table column in angular?

If you're using scss for your styles you can use a mixin to help generate the code. Your styles will quickly get out of hand if you put all the properties every time.

This is a very simple example - really nothing more than a proof of concept, you can extend this with multiple properties and rules as needed.

@mixin mat-table-columns($columns)
{
    .mat-column-
    {
        @each $colName, $props in $columns {

            $width: map-get($props, 'width');

            &#{$colName} 
            {
                flex: $width;
                min-width: $width;

                @if map-has-key($props, 'color') 
                {
                    color: map-get($props, 'color');
                }
            }  
        }
    }
}

Then in your component where your table is defined you just do this:

@include mat-table-columns((

    orderid: (width: 6rem, color: gray),
    date: (width: 9rem),
    items: (width: 20rem)

));

This generates something like this:

.mat-column-orderid[_ngcontent-c15] {
  flex: 6rem;
  min-width: 6rem;
  color: gray; }

.mat-column-date[_ngcontent-c15] {
  flex: 9rem;
  min-width: 9rem; }

In this version width becomes flex: value; min-width: value.

For your specific example you could add wrap: true or something like that as a new parameter.

How to change button background image on mouseOver?

In the case of winforms:

If you include the images to your resources you can do it like this, very simple and straight forward:

public Form1()
          {
               InitializeComponent();
               button1.MouseEnter += new EventHandler(button1_MouseEnter);
               button1.MouseLeave += new EventHandler(button1_MouseLeave);
          }

          void button1_MouseLeave(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
          }


          void button1_MouseEnter(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

I would not recommend hardcoding image paths.

As you have altered your question ...

There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or Move :

in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover); 
button1.MouseMove += new MouseEventHandler(button1_MouseMove);

void button1_MouseMove(object sender, MouseEventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

          void button1_MouseHover(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

To add images to your resources: Projectproperties/resources/add/existing file

Android Image View Pinch Zooming

I made code for imageview with pinch to zoom using zoomageview. so user can drag the image off the screen and zoom-In , zoom-out the image.

You can follow this link to get the Step By Step Code and also given Output Screenshot.

https://stackoverflow.com/a/58074642/11613683

No signing certificate "iOS Distribution" found

I got the "No signing certificate" error when running Xcode 11.3 on macOS 10.14.x Mojave. (but after Xcode 12 was released.)

I was also using Fastlane. My fix was to set generate_apple_certs to false when running Match. This seemed to generate signing certificates that were backwards-compatible with Xcode 11.3

Match documentation - https://docs.fastlane.tools/actions/match/

This is the relevant section of my Fastfile:

platform :ios do
  lane :certs do
    force = false
    match(type: "development", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.dev")
    match(type: "adhoc",       generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.beta")
    match(type: "appstore",    generate_apple_certs: false, force: force, app_identifier: "your.app.identifier")
  end

  ...

Where do I find the current C or C++ standard documents?

ISO standards cost money, from a moderate amount (for a PDF version), to a bit more (for a book version).

While they aren't finalised however, they can usually be found online, as drafts. Most of the times the final version doesn't differ significantly from the last draft, so while not perfect, they'll suit just fine.

Angular.js How to change an elements css class on click and to remove all others

I only change/remove the class:

   function removeClass() {
                    var element = angular.element('#nameInput');
          element.removeClass('nameClass');
   };

Get an object attribute

To access field or method of an object use dot .:

user = User()
print user.fullName

If a name of the field will be defined at run time, use buildin getattr function:

field_name = "fullName"
print getattr(user, field_name) # prints content of user.fullName

Set HTML element's style property in javascript

The DOM element style "property" is a readonly collection of all the style attributes defined on the element. (The collection property is readonly, not necessarily the items within the collection.)

You would be better off using the className "property" on the elements.

How to remove all namespaces from XML with C#?

This worked for me.

       FileStream fs = new FileStream(filePath, FileMode.Open);

       StreamReader sr = new StreamReader(fs);

        DataSet ds = new DataSet();
        ds.ReadXml(sr);
        ds.Namespace = "";

        string outXML = ds.GetXml();
        ds.Dispose();
        sr.Dispose();
        fs.Dispose();

Go install fails with error: no install location for directory xxx outside GOPATH

For what it's worth, here's my .bash_profile, that works well for me on a mac with Atom, after installing go with Homebrew:

export GOROOT=`go env GOROOT`
export GOPATH=/Users/yy/Projects/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOBIN

What's the difference between git reset --mixed, --soft, and --hard?

In the simplest terms:

  • --soft: uncommit changes, changes are left staged (index).
  • --mixed (default): uncommit + unstage changes, changes are left in working tree.
  • --hard: uncommit + unstage + delete changes, nothing left.

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

when you are in El Capitan, will get error: ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted need to close the "System Integrity Protection".

first, reboot and hold on cmd + R to enter the Recovery mode, then launch the terminal and type the command: csrutil disable, now you can reboot and try again.

How to open .mov format video in HTML video Tag?

Instead of using <source> tag, use <src> attribute of <video> as below and you will see the action.

<video width="320" height="240" src="mov1.mov"></video>

or

you can give multiple tags within the tag, each with a different video source. The browser will automatically go through the list and pick the first one it’s able to play. For example:

<video id="sampleMovie" width="640" height="360" preload controls>
    <source src="HTML5Sample_H264.mov" />
    <source src="HTML5Sample_Ogg.ogv" />
    <source src="HTML5Sample_WebM.webm" />
</video>

If you test that code in Chrome, you’ll get the H.264 video. Run it in Firefox, though, and you’ll see the Ogg video in the same place.

How to POST a FORM from HTML to ASPX page

Are you sure your HTML form is correct, and does, in fact, do an HTTP POST? I would suggest running Fiddler2, and then trying to log in via your Login.aspx, then the remote HTML site, and then comparing the requests that are sent to the server. For me, ASP.Net always worked fine -- if HTTP request contains a valid POST, I can get to values using Request.Form...

How to obtain a Thread id in Python?

Similarly to @brucexin I needed to get OS-level thread identifier (which != thread.get_ident()) and use something like below not to depend on particular numbers and being amd64-only:

---- 8< ---- (xos.pyx)
"""module xos complements standard module os""" 

cdef extern from "<sys/syscall.h>":                                                             
    long syscall(long number, ...)                                                              
    const int SYS_gettid                                                                        

# gettid returns current OS thread identifier.                                                  
def gettid():                                                                                   
    return syscall(SYS_gettid)                                                                  

and

---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos

...

print 'my tid: %d' % xos.gettid()

this depends on Cython though.

Check whether a variable is a string in Ruby

foo.instance_of? String

or

foo.kind_of? String 

if you you only care if it is derrived from String somewhere up its inheritance chain

Bootstrap css hides portion of container below navbar navbar-fixed-top

Just define an empty navbar prior to the fixed one, it will create the space needed.

<nav class="navbar navbar-default ">
</nav>
<nav class="navbar  navbar-default navbar-fixed-top ">
     <div class="container-fluid">
// Your menu code 
     </div>
</nav>

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

You can use the approach below, it works fine:

getActivity().getSupportFragmentManager().popBackStack();

MySQL timezone change?

The easiest way to do this, as noted by Umar is, for example

mysql> SET GLOBAL time_zone = 'America/New_York';

Using the named timezone is important for timezone that has a daylights saving adjustment. However, for some linux builds you may get the following response:

#1298 - Unknown or incorrect time zone

If you're seeing this, you may need to run a tzinfo_to_sql translation... it's easy to do, but not obvious. From the linux command line type in:

mysql_tzinfo_to_sql /usr/share/zoneinfo/|mysql -u root mysql -p

Provide your root password (MySQL root, not Linux root) and it will load any definitions in your zoneinfo into mysql. You can then go back and run your

mysql> SET GLOBAL time_zone = timezone;

SQL Query to add a new column after an existing column in SQL Server 2005

According to my research there is no way to do this exactly the way you want. You can manually re-create the table and copy the data, or SSMS can (and will) do this for you (when you drag and drop a column to a different order, it does this). In fact it souldn't matter what order the columns are... As an alternative solution you can select the data you want in the order you desired. For example, instead of using asterisk (*) in select, specify the column names in some order... Lets say MyTable has col1, col2, col3, colNew columns.

Instead of:

SELECT * FROM MyTable

You can use:

SELECT col1, colNew, col2, col3 FROM MyTable

What is the purpose of nameof?

One of the usage of nameof keyword is for setting Binding in wpf programmatically.

to set Binding you have to set Path with string, and with nameof keyword, it's possible to use Refactor option.

For example, if you have IsEnable dependency property in your UserControl and you want to bind it to IsEnable of some CheckBox in your UserControl, you can use these two codes:

CheckBox chk = new CheckBox();
Binding bnd = new Binding ("IsEnable") { Source = this };
chk.SetBinding(IsEnabledProperty, bnd);

and

CheckBox chk = new CheckBox();
Binding bnd = new Binding (nameof (IsEnable)) { Source = this };
chk.SetBinding(IsEnabledProperty, bnd);

It's obvious the first code can't refactor but the secend one...

How to select Python version in PyCharm?

Quick Answer:

  • File --> Setting
  • In left side in project section --> Project interpreter
  • Select desired Project interpreter
  • Apply + OK

[NOTE]:

Tested on Pycharm 2018 and 2017.


How do you handle a "cannot instantiate abstract class" error in C++?

Visual Studio's Error List pane only shows you the first line of the error. Invoke View>Output and I bet you'll see something like:

c:\path\to\your\code.cpp(42): error C2259: 'AmbientOccluder' : cannot instantiate abstract class
          due to following members:
          'ULONG MysteryUnimplementedMethod(void)' : is abstract
          c:\path\to\some\include.h(8) : see declaration of 'MysteryUnimplementedMethod'

How to go back (ctrl+z) in vi/vim

You can use the u button to undo the last modification. (And Ctrl+R to redo it).

Read more about it at: http://vim.wikia.com/wiki/Undo_and_Redo

Chrome Extension: Make it run every page load

If it needs to run on the onload event of the page, meaning that the document and all its assets have loaded, this needs to be in a content script embedded in each page for which you wish to track onload.

How does Access-Control-Allow-Origin header work?

If you want just to test a cross domain application in which the browser blocks your request, then you can just open your browser in unsafe mode and test your application without changing your code and without making your code unsafe. From MAC OS you can do this from the terminal line:

open -a Google\ Chrome --args --disable-web-security --user-data-dir

CSV API for Java

Reading CSV format description makes me feel that using 3rd party library would be less headache than writing it myself:

Wikipedia lists 10 or something known libraries:

I compared libs listed using some kind of check list. OpenCSV turned out a winner to me (YMMV) with the following results:

+ maven

+ maven - release version   // had some cryptic issues at _Hudson_ with snapshot references => prefer to be on a safe side

+ code examples

+ open source   // as in "can hack myself if needed"

+ understandable javadoc   // as opposed to eg javadocs of _genjava gj-csv_

+ compact API   // YAGNI (note *flatpack* seems to have much richer API than OpenCSV)

- reference to specification used   // I really like it when people can explain what they're doing

- reference to _RFC 4180_ support   // would qualify as simplest form of specification to me

- releases changelog   // absence is quite a pity, given how simple it'd be to get with maven-changes-plugin   // _flatpack_, for comparison, has quite helpful changelog

+ bug tracking

+ active   // as in "can submit a bug and expect a fixed release soon"

+ positive feedback   // Recommended By 51 users at sourceforge (as of now)

Windows error 2 occured while loading the Java VM

I got the same problem after upgrading java from 1.8.0_202 to 1.8.0_211

Problem:

Here are directories where new version of 1.8.0_211 of Java installed:

Directory of c:\Program Files\Java\jre1.8.0_211\bin Directory of c:\Program Files (x86)\Common Files\Oracle\Java\javapath

So one is located in 32 bit and second is in 64 bit Program files folder. The one that is specified in the PATH is 32 bit version (c:\Program Files (x86)\Common Files\Oracle\Java\javapath), even though it was 64 bit version of the Java that was installed.

Solution:

Change system environments variable PATH from c:\Program Files (x86)\Common Files\Oracle\Java\javapath to c:\Program Files\Java\jre1.8.0_211\bin

List vs tuple, when to use each?

The first thing you need to decide is whether the data structure needs to be mutable or not. As has been mentioned, lists are mutable, tuples are not. This also means that tuples can be used for dictionary keys, wheres lists cannot.

In my experience, tuples are generally used where order and position is meaningful and consistant. For example, in creating a data structure for a choose your own adventure game, I chose to use tuples instead of lists because the position in the tuple was meaningful. Here is one example from that data structure:

pages = {'foyer': {'text' : "some text", 
          'choices' : [('open the door', 'rainbow'),
                     ('go left into the kitchen', 'bottomless pit'),
                     ('stay put','foyer2')]},}

The first position in the tuple is the choice displayed to the user when they play the game and the second position is the key of the page that choice goes to and this is consistent for all pages.

Tuples are also more memory efficient than lists, though I'm not sure when that benefit becomes apparent.

Also check out the chapters on lists and tuples in Think Python.

How to get Client location using Google Maps API v3?

No need to do your own implementation. I can recommend using geolocationmarker from google-maps-utility-library-v3.

Where can I set path to make.exe on Windows?

The path is in the registry but usually you edit through this interface:

  1. Go to Control Panel -> System -> System settings -> Environment Variables.
  2. Scroll down in system variables until you find PATH.
  3. Click edit and change accordingly.
  4. BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. c:\path;c:\path2
  5. Launch a new console for the settings to take effect.

Ruby on Rails form_for select field with class

This work for me

<%= f.select :status, [["Single", "single"], ["Married", "married"], ["Engaged", "engaged"], ["In a Relationship", "relationship"]], {}, {class: "form-control"} %>

clearing a char array c

Try the following:

strcpy(my_custom_data,"");

Overlapping elements in CSS

the easiest way is to use position:absolute on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative

<div id="container" style="position:relative;">
    <div id="div1" style="position:absolute; top:0; left:0;"></div>
    <div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>

How to delete all records from table in sqlite with Android?

Here is simple way to delete:

public void deleteItem(Item item) {
SQLiteDatabase db = getWritableDatabase();
String whereClause = "id=?";
String whereArgs[] = {item.id.toString()};
db.delete("Items", whereClause, whereArgs);
}

Here whereClause is optional, passing null will delete all rows in table. delete function will return number of affected row if whereClause passed otherwise will return 0.

Important Note: If you want to remove all rows and require count of deleted ones also then pass 1 as whereClause.

Regular expression field validation in jQuery

I believe this does it:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

It's got built-in patterns for stuff like URLs and e-mail addresses, and I think you can have it use your own as well.

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

Android 'Unable to add window -- token null is not for an application' exception

I'm guessing - are you trying to create Dialog using.

 getApplicationContext()
 mContext which is passed by activity.

if You displaying dialog non activity class then you have to pass activity as a parameter.

Activity activity=YourActivity.this;

Now it will be work great.

If you find any trouble then let me know.

Days between two dates?

Do you mean full calendar days, or groups of 24 hours?

For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:

days = (a - b).days

For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:

roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days

Change the Arrow buttons in Slick slider

You can easily create your own style of arrow with the .slick-next:before and the .slick-prev:after pseudo-classes.

Here's an example:

.slick-prev:before {
  content: "<";
  color: red;
  font-size: 30px;
}

.slick-next:before {
  content: ">";
  color: red;
  font-size: 30px;
}

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

In these two lines:

mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)

frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)

try instead:

cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)

cv2.circle(frame,(a, b),5,color[i].tolist(),-1)

I had the same problem and the variables were being returned empty

What are the differences between using the terminal on a mac vs linux?

If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.

Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.

If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.

There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd on Mac and ifconfig works differently.

The following table is useful for knowing the various unix shells.

sh      The original Bourne shell   Present on every unix system 
ksh     Original Korn shell         Richer shell programming environment than sh 
csh     Original C-shell            C-like syntax; early versions buggy 
tcsh    Enhanced C-shell            User-friendly and less buggy csh implementation 
bash    GNU Bourne-again shell      Enhanced and free sh implementation 
zsh     Z shell                     Enhanced, user-friendly ksh-like shell

You may also find these guides helpful:

http://homepage.mac.com/rgriff/files/TerminalBasics.pdf

http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html

On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile on OSX) file with aliases, some examples below. I now placed all my aliases in a separate .bash_aliases file and include it with:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

in the .bashrc or .bash_profile file.

Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto. The first time I did this (without knowing) I redefined ls to be invalid which was a bit alarming until I removed --auto-color !

You may also find https://unix.stackexchange.com/q/127799/10043 useful

# ~/.bash_aliases
# ls variants
#alias l='ls -CF' 
alias la='ls -A' 
alias l='ls -alFtr' 
alias lsd='ls -d .*' 
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i' 
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed' 
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status' 
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'

Create a .txt file if doesn't exist, and if it does append a new line

 else if (File.Exists(path)) 
{ 
  using (StreamWriter w = File.AppendText(path))
        {
            w.WriteLine("The next line!"); 
            w.Close();
        }
 } 

When should I use Lazy<T>?

You typically use it when you want to instantiate something the first time its actually used. This delays the cost of creating it till if/when it's needed instead of always incurring the cost.

Usually this is preferable when the object may or may not be used and the cost of constructing it is non-trivial.

Select first occurring element after another element

Simplyfing for the begginers:

If you want to select an element immediatly after another element you use the + selector.

For example:

div + p The "+" element selects all <p> elements that are placed immediately after <div> elements


If you want to learn more about selectors use this table

Byte Array and Int conversion in Java

That's a lot of work for:

public static int byteArrayToLeInt(byte[] b) {
    final ByteBuffer bb = ByteBuffer.wrap(b);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    return bb.getInt();
}

public static byte[] leIntToByteArray(int i) {
    final ByteBuffer bb = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    bb.putInt(i);
    return bb.array();
}

This method uses the Java ByteBuffer and ByteOrder functionality in the java.nio package. This code should be preferred where readability is required. It should also be very easy to remember.

I've shown Little Endian byte order here. To create a Big Endian version you can simply leave out the call to order(ByteOrder).


In code where performance is higher priority than readability (about 10x as fast):

public static int byteArrayToLeInt(byte[] encodedValue) {
    int value = (encodedValue[3] << (Byte.SIZE * 3));
    value |= (encodedValue[2] & 0xFF) << (Byte.SIZE * 2);
    value |= (encodedValue[1] & 0xFF) << (Byte.SIZE * 1);
    value |= (encodedValue[0] & 0xFF);
    return value;
}

public static byte[] leIntToByteArray(int value) {
    byte[] encodedValue = new byte[Integer.SIZE / Byte.SIZE];
    encodedValue[3] = (byte) (value >> Byte.SIZE * 3);
    encodedValue[2] = (byte) (value >> Byte.SIZE * 2);   
    encodedValue[1] = (byte) (value >> Byte.SIZE);   
    encodedValue[0] = (byte) value;
    return encodedValue;
}

Just reverse the byte array index to count from zero to three to create a Big Endian version of this code.


Notes:

  • In Java 8 you can also make use of the Integer.BYTES constant, which is more succinct than Integer.SIZE / Byte.SIZE.

What is the difference between the float and integer data type when the size is the same?

Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point

Select DataFrame rows between two dates

Inspired by unutbu

print(df.dtypes)                                 #Make sure the format is 'object'. Rerunning this after index will not show values.
columnName = 'YourColumnName'
df[columnName+'index'] = df[columnName]          #Create a new column for index
df.set_index(columnName+'index', inplace=True)   #To build index on the timestamp/dates
df.loc['2020-09-03 01:00':'2020-09-06']          #Select range from the index. This is your new Dataframe.

Auto-click button element on page load using jQuery

Use the following code

$("#modal").trigger('click');

Define: What is a HashSet?

    1. A HashSet holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object. Take a look here

    2. HashSet is an unordered collection containing unique elements. It has the standard collection operations Add, Remove, Contains, but since it uses a hash-based implementation, these operations are O(1). (As opposed to List for example, which is O(n) for Contains and Remove.) HashSet also provides standard set operations such as union, intersection, and symmetric difference. Take a look here

  1. There are different implementations of Sets. Some make insertion and lookup operations super fast by hashing elements. However, that means that the order in which the elements were added is lost. Other implementations preserve the added order at the cost of slower running times.

The HashSet class in C# goes for the first approach, thus not preserving the order of elements. It is much faster than a regular List. Some basic benchmarks showed that HashSet is decently faster when dealing with primary types (int, double, bool, etc.). It is a lot faster when working with class objects. So that point is that HashSet is fast.

The only catch of HashSet is that there is no access by indices. To access elements you can either use an enumerator or use the built-in function to convert the HashSet into a List and iterate through that. Take a look here

What characters are forbidden in Windows and Linux directory names?

In Unix shells, you can quote almost every character in single quotes '. Except the single quote itself, and you can't express control characters, because \ is not expanded. Accessing the single quote itself from within a quoted string is possible, because you can concatenate strings with single and double quotes, like 'I'"'"'m' which can be used to access a file called "I'm" (double quote also possible here).

So you should avoid all control characters, because they are too difficult to enter in the shell. The rest still is funny, especially files starting with a dash, because most commands read those as options unless you have two dashes -- before, or you specify them with ./, which also hides the starting -.

If you want to be nice, don't use any of the characters the shell and typical commands use as syntactical elements, sometimes position dependent, so e.g. you can still use -, but not as first character; same with ., you can use it as first character only when you mean it ("hidden file"). When you are mean, your file names are VT100 escape sequences ;-), so that an ls garbles the output.

How to measure time taken between lines of code in python?

You can try this as well:

from time import perf_counter

t0 = perf_counter()

...

t1 = perf_counter()
time_taken = t1 - t0

How to reset index in a pandas dataframe?

DataFrame.reset_index is what you're looking for. If you don't want it saved as a column, then do:

df = df.reset_index(drop=True)

If you don't want to reassign:

df.reset_index(drop=True, inplace=True)

Apply formula to the entire column

Found another solution:

  • Apply the formula to the first 3 or 4 cells of the column
  • Ctrl + C the formula in one of the last rows (if you copy the first line it won't work)
  • Click on the column header to select the whole column
  • Press Ctrl + V to paste it in all cells bellow

Java Command line arguments

Command-line arguments are passed in the first String[] parameter to main(), e.g.

public static void main( String[] args ) {
}

In the example above, args contains all the command-line arguments.

The short, sweet answer to the question posed is:

public static void main( String[] args ) {
    if( args.length > 0 && args[0].equals( "a" ) ) {
        // first argument is "a"
    } else {
        // oh noes!?
    }
}

Professional jQuery based Combobox control?

If you don't need multi-column, chosen is another good choice. MIT Licensed

Git: Find the most recent common ancestor of two branches

As noted in a prior answer, although git merge-base works,

$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

If myfeature is the current branch, as is common, you can use --fork-point:

$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.


For full commit info, consider:

$ git log -1 $(git merge-base --fork-point develop) 

How do I automatically scroll to the bottom of a multiline text box?

This will scroll to the end of the textbox when the text is changed, but still allows the user to scroll up

outbox.SelectionStart = outbox.Text.Length;
outbox.ScrollToEnd();

tested on Visual Studio Enterprise 2017

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

Determine the line of code that causes a segmentation fault?

All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.

If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.

It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)

How do I compile C++ with Clang?

I've had a similar problem when building Clang from source (but not with sudo apt-get install. This might depend on the version of Ubuntu which you're running).

It might be worth checking if clang++ can find the correct locations of your C++ libraries:

Compare the results of g++ -v <filename.cpp> and clang++ -v <filename.cpp>, under "#include < ... > search starts here:".

Use of contains in Java ArrayList<String>

You are right. ArrayList.contains() tests equals(), not object identity:

returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))

If you got a NullPointerException, verify that you initialized your list, either in a constructor or the declaration. For example:

private List<String> rssFeedURLs = new ArrayList<String>();

Make a div into a link

My smarty pants answer:

"Evasive answer to: "How to make block level element a hyperlink and validate in XHTML 1.1"

Just use HTML5 DOCTYPE DTD."

Didn't actually hold true for ie7

onclick="location.href='page.html';"

Works IE7-9, Chrome, Safari, Firefox,