Programs & Examples On #Aidl

Android Interface Definition Language is a special language that allows a server and a client to establish interface for Inter Process Communication (IPC).

Execution failed for task ':app:compileDebugAidl': aidl is missing

I am working with sdk 23.1.0 and gradle 1.3.1. I created a new project edited nothing and got the aidl error. I went into my project gradle file and changed tool to 22.0.1 instead of 23.1.0 and it worked:

   compileSdkVersion 23
   buildToolsVersion "22.0.1" //"23.1.0"

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

To resolve this issue:

  1. The jstl jar should be in your classpath. If you are using maven, add a dependency to jstl in your pom.xml using the snippet provided here. If you are not using maven, download the jstl jar from here and deploy it into your WEB-INF/lib.

  2. Make sure you have the following taglib directive at the top of your jsp:

     <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    

Overwriting txt file in java

This simplifies it a bit and it behaves as you want it.

FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");

try {
 f.write(source);
 ...
} catch(...) {
} finally {
 //close it here
}

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

Connection timeouts (assuming a local network and several client machines) typically result from

a) some kind of firewall on the way that simply eats the packets without telling the sender things like "No Route to host"

b) packet loss due to wrong network configuration or line overload

c) too many requests overloading the server

d) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c).

Hope this helps.

1114 (HY000): The table is full

In my case, this was because the partition hosting the ibdata1 file was full.

HighCharts Hide Series Name from the Legend

Set showInLegend to false.

series: [{
            showInLegend: false,
            name: 'Series',
            data: value                
        }]

How to float a div over Google Maps?

Just set the position of the div and you may have to set the z-index.

ex.

div#map-div {
    position: absolute;
    left: 10px;
    top: 10px;
}
div#cover-div {
    position:absolute;
    left:10px;
    top: 10px;
    z-index:3;
}

Implementing multiple interfaces with Java - is there a way to delegate?

There is one way to implement multiple interface.

Just extend one interface from another or create interface that extends predefined interface Ex:

public interface PlnRow_CallBack extends OnDateSetListener {
    public void Plan_Removed();
    public BaseDB getDB();
}

now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces

public class Calculator extends FragmentActivity implements PlnRow_CallBack {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }

    @Override
    public void Plan_Removed() {

    }

    @Override
    public BaseDB getDB() {

    }
}

hope this helps

How to show the Project Explorer window in Eclipse

Using the latest Luna upgrade. The only solution that worked was Window >> New Window. It's very easy to lose that critical bar.

How can I edit a .jar file?

Here's what I did:

  • Extracted the files using WinRAR
  • Made my changes to the extracted files
  • Opened the original JAR file with WinRAR
  • Used the ADD button to replace the files that I modified

That's it. I have tested it with my Nokia and it's working for me.

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

NoClassDefFoundError for code in an Java library on Android

I met NoClassDefFoundError for a class that exists in my project (not a library class). The class exists but i got NoClassDefFoundError. In my case, the problem was multidex support. The problem and solution is here: Android Multidex and support libraries

You get this error for Android versions lower than 5.0.

How do I add a Maven dependency in Eclipse?

In fact when you open the pom.xml, you should see 5 tabs in the bottom. Click the pom.xml, and you can type whatever dependencies you want.

enter image description here

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

Why do we use volatile keyword?

In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia

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

Set order of columns in pandas dataframe

I find this to be the most straightforward and working:

df = pd.DataFrame({
        'one thing':[1,2,3,4],
        'second thing':[0.1,0.2,1,2],
        'other thing':['a','e','i','o']})

df = df[['one thing','second thing', 'other thing']]

How to change color of the back arrow in the new material theme?

Need to add a single attribute to your toolbar theme -

<style name="toolbar_theme" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="colorControlNormal">@color/arrow_color</item>
</style>

Apply this toolbar_theme to your toolbar.

OR

you can directly apply to your theme -

<style name="CustomTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorControlNormal">@color/arrow_color</item> 
  //your code ....
</style>

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

A better solution is explained in the official explanation. I left the answer I have given before under the horizontal line.

According to the solution there:

Use an external tag and write down the following code below in the top-level build.gradle file. You're going to change the version to a variable rather than a static version number.

ext {
    compileSdkVersion = 26
    supportLibVersion = "27.1.1"
}

Change the static version numbers in your app-level build.gradle file, the one has (Module: app) near.

android {
    compileSdkVersion rootProject.ext.compileSdkVersion // It was 26 for example
    // the below lines will stay
}

// here there are some other stuff maybe

dependencies {
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    // the below lines will stay
}

Sync your project and you'll get no errors.


You don't need to add anything to Gradle scripts. Install the necessary SDKs and the problem will be solved.

In your case, install the libraries below from Preferences > Android SDK or Tools > Android > SDK Manager

enter image description here

How to get html to print return value of javascript function?

you could change the innerHtml on an element

function produceMessage(){
    var msg= 'Hello<br />';
     document.getElementById('someElement').innerHTML = msg;
}

jQuery: Load Modal Dialog Contents via Ajax

Check out this blog post from Nemikor, which should do what you want.

http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/

Basically, before calling 'open', you 'load' the content from the other page first.

jQuery('#dialog').load('path to my page').dialog('open'); 

gcloud command not found - while installing Google Cloud SDK

If you are on MAC OS and using .zsh shell then do the following:

  1. Edit your .zshrc and add the following

    # The next line updates PATH for the Google Cloud SDK.
    source /Users/USER_NAME/google-cloud-sdk/path.zsh.inc
    
    # The next line enables zsh completion for gcloud.
    source /Users/USER_NAME/google-cloud-sdk/completion.zsh.inc
    
  2. Create new file named path.zsh.inc under your home directory(/Users/USER_NAME/):

    script_link="$( readlink "$0" )" || script_link="$0"
    apparent_sdk_dir="${script_link%/*}"
    if [ "$apparent_sdk_dir" == "$script_link" ]; then
     apparent_sdk_dir=.
    fi
    sdk_dir="$( cd -P "$apparent_sdk_dir" && pwd -P )"
    bin_path="$sdk_dir/bin"
    export PATH=$bin_path:$PATH
    

Checkout more @ Official Docs

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

'nuget' is not recognized but other nuget commands working

In [Package Manager Console] try the below

Install-Package NuGet.CommandLine

How to get annotations of a member variable?

for(Field field : cls.getDeclaredFields()){
  Class type = field.getType();
  String name = field.getName();
  Annotation[] annotations = field.getDeclaredAnnotations();
}

See also: http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html

Android EditText Hint

et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            et.setHint(temp +" Characters");
        }
    });

How can I use pointers in Java?

As Java has no pointer data types, it is impossible to use pointers in Java. Even the few experts will not be able to use pointers in java.

See also the last point in: The Java Language Environment

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

VBA subs are no macros. A VBA sub can be a macro, but it is not a must.

The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.

The more elegant way is, to design and write your own VBA code without using the macro features!

VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.

If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".

In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.

It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.

In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.

Cannot delete or update a parent row: a foreign key constraint fails

The simple way would be to disable the foreign key check; make the changes then re-enable foreign key check.

SET FOREIGN_KEY_CHECKS=0; -- to disable them
SET FOREIGN_KEY_CHECKS=1; -- to re-enable them

How to store phone numbers on MySQL databases?

I suggest storing the numbers in a varchar without formatting. Then you can just reformat the numbers on the client side appropriately. Some cultures prefer to have phone numbers written differently; in France, they write phone numbers like 01-22-33-44-55.

You might also consider storing another field for the country that the phone number is for, because this can be difficult to figure out based on the number you are looking at. The UK uses 11 digit long numbers, some African countries use 7 digit long numbers.

That said, I used to work for a UK phone company, and we stored phone numbers in our database based on if they were UK or international. So, a UK phone number would be 02081234123 and an international one would be 001800300300.

Highlight all occurrence of a selected word?

For example this plugIns:

Just search for under cursor in vimawesome.com

The key, as clagccs mentioned, is that the highlight does NOT conflict with your search: https://vim.fandom.com/wiki/Auto_highlight_current_word_when_idle

Screen-shot of how it does NOT conflict with search: enter image description here Notes:

  • vim-illuminate highlights by default, in my screen-shot I switched to underline
  • vim-illuminate highlights/underlines word under cursor by default, in my screen-shot I unset it
  • my colorschemes are very grey-ish. Check yours to customize it too.

jquery change style of a div on click

you can use .css method of jquery..

reference css method

Rendering HTML inside textarea

An addendum to this. You can use character entities (such as changing <div> to &lt;div&gt;) and it will render in the textarea. But when it is saved, the value of the textarea is the text as rendered. So you don't need to de-encode. I just tested this across browsers (ie back to 11).

How to search if dictionary value contains certain string with Python

import re
for i in range(len(myDict.values())):
     for j in range(len(myDict.values()[i])):
             match=re.search(r'Mary', myDict.values()[i][j])
             if match:
                     print match.group() #Mary
                     print myDict.keys()[i] #firstName
                     print myDict.values()[i][j] #Mary-Ann

How can I read large text files in Python, line by line, without loading it into memory?

An old school approach:

fh = open(file_name, 'rt')
line = fh.readline()
while line:
    # do stuff with line
    line = fh.readline()
fh.close()

Get class list for element with jQuery

$('div').attr('class').split(' ').each(function(cls){ console.log(cls);})

Write / add data in JSON file using Node.js

try

var fs = require("fs");
var sampleObject = { your data };

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {  console.error(err);  return; };
    console.log("File has been created");
});

failed to push some refs to [email protected]

I was facing this issue while deploying a django app on heroku.

In my case the requirements.txt, Procfile and runtime.txt files were present in a subdirectory. Moving them to the root directory of the repository solved the problem.

Heroku is specifically looking for requirements.txt in the root directory to setup the python environment.


P.S :

If heroku is unable to reach till the wsgi file residing in the subdirectory, solve it by referring below thread -

How can I modify Procfile to run Gunicorn process in a non-standard folder on Heroku?

JavaScript function to add X months to a date

addDateMonate : function( pDatum, pAnzahlMonate )
{
    if ( pDatum === undefined )
    {
        return undefined;
    }

    if ( pAnzahlMonate === undefined )
    {
        return pDatum;
    }

    var vv = new Date();

    var jahr = pDatum.getFullYear();
    var monat = pDatum.getMonth() + 1;
    var tag = pDatum.getDate();

    var add_monate_total = Math.abs( Number( pAnzahlMonate ) );

    var add_jahre = Number( Math.floor( add_monate_total / 12.0 ) );
    var add_monate_rest = Number( add_monate_total - ( add_jahre * 12.0 ) );

    if ( Number( pAnzahlMonate ) > 0 )
    {
        jahr += add_jahre;
        monat += add_monate_rest;

        if ( monat > 12 )
        {
            jahr += 1;
            monat -= 12;
        }
    }
    else if ( Number( pAnzahlMonate ) < 0 )
    {
        jahr -= add_jahre;
        monat -= add_monate_rest;

        if ( monat <= 0 )
        {
            jahr = jahr - 1;
            monat = 12 + monat;
        }
    }

    if ( ( Number( monat ) === 2 ) && ( Number( tag ) === 29 ) )
    {
        if ( ( ( Number( jahr ) % 400 ) === 0 ) || ( ( Number( jahr ) % 100 ) > 0 ) && ( ( Number( jahr ) % 4 ) === 0 ) )
        {
            tag = 29;
        }
        else
        {
            tag = 28;
        }
    }

    return new Date( jahr, monat - 1, tag );
}


testAddMonate : function( pDatum , pAnzahlMonate )
{
    var datum_js = fkDatum.getDateAusTTMMJJJJ( pDatum );
    var ergebnis = fkDatum.addDateMonate( datum_js, pAnzahlMonate );

    app.log( "addDateMonate( \"" + pDatum + "\", " + pAnzahlMonate + " ) = \"" + fkDatum.getStringAusDate( ergebnis ) + "\"" );
},


test1 : function()
{
    app.testAddMonate( "15.06.2010",    10 );
    app.testAddMonate( "15.06.2010",   -10 );
    app.testAddMonate( "15.06.2010",    37 );
    app.testAddMonate( "15.06.2010",   -37 );
    app.testAddMonate( "15.06.2010",  1234 );
    app.testAddMonate( "15.06.2010", -1234 );
    app.testAddMonate( "15.06.2010",  5620 );
    app.testAddMonate( "15.06.2010", -5120 );

}

Iterating each character in a string using Python

You can also do the following:

txt = "Hello World!"
print (*txt, sep='\n')

This does not use loops but internally print statement takes care of it.

* unpacks the string into a list and sends it to the print statement

sep='\n' will ensure that the next char is printed on a new line

The output will be:

H
e
l
l
o
 
W
o
r
l
d
!

If you do need a loop statement, then as others have mentioned, you can use a for loop like this:

for x in txt: print (x)

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

Javascript ajax call on page onload

Or with Prototype:

Event.observe(this, 'load', function() { new Ajax.Request(... ) );

Or better, define the function elsewhere rather than inline, then:

Event.observe(this, 'load', functionName );

You don't have to use jQuery or Prototype specifically, but I hope you're using some kind of library. Either library is going to handle the event handling in a more consistent manner than onload, and of course is going to make it much easier to process the Ajax call. If you must use the body onload attribute, then you should just be able to call the same function as referenced in these examples (onload="javascript:functionName();").

However, if your database update doesn't depend on the rendering on the page, why wait until it's fully loaded? You could just include a call to the Ajax-calling function at the end of the JavaScript on the page, which should give nearly the same effect.

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

SQL: ... WHERE X IN (SELECT Y FROM ...)

Any mature enough SQL database should be able to execute that just as effectively as the equivalent JOIN. Use whatever is more readable to you.

Inheriting constructors

You have to explicitly define the constructor in B and explicitly call the constructor for the parent.

B(int x) : A(x) { }

or

B() : A(5) { }

What is the meaning of {...this.props} in Reactjs

You will use props in your child component

for example

if your now component props is

{
   booking: 4,
   isDisable: false
}

you can use this props in your child compoenet

 <div {...this.props}> ... </div>

in you child component, you will receive all your parent props.

Detect whether a Python string is a number or a letter

Check if string is positive digit (integer) and alphabet

You may use str.isdigit() and str.isalpha() to check whether given string is positive integer and alphabet respectively.

Sample Results:

# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True

# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False

Check for strings as positive/negative - integer/float

str.isdigit() returns False if the string is a negative number or a float number. For example:

# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False

If you want to also check for the negative integers and float, then you may write a custom function to check for it as:

def is_number(n):
    try:
        float(n)   # Type-casting the string to `float`.
                   # If string is not a valid `float`, 
                   # it'll raise `ValueError` exception
    except ValueError:
        return False
    return True

Sample Run:

>>> is_number('123')    # positive integer number
True

>>> is_number('123.4')  # positive float number
True
 
>>> is_number('-123')   # negative integer number
True

>>> is_number('-123.4') # negative `float` number
True

>>> is_number('abc')    # `False` for "some random" string
False

Discard "NaN" (not a number) strings while checking for number

The above functions will return True for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:

>>> is_number('NaN')
True

In order to check whether the number is "NaN", you may use math.isnan() as:

>>> import math
>>> nan_num = float('nan')

>>> math.isnan(nan_num)
True

Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==. Python returns False when nan float is compared with itself. For example:

# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False

Hence, above function is_number can be updated to return False for "NaN" as:

def is_number(n):
    is_number = True
    try:
        num = float(n)
        # check for "nan" floats
        is_number = num == num   # or use `math.isnan(num)`
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('Nan')   # not a number "Nan" string
False

>>> is_number('nan')   # not a number string "nan" with all lower cased
False

>>> is_number('123')   # positive integer
True

>>> is_number('-123')  # negative integer
True

>>> is_number('-1.12') # negative `float`
True

>>> is_number('abc')   # "some random" string
False

Allow Complex Number like "1+2j" to be treated as valid number

The above function will still return you False for the complex numbers. If you want your is_number function to treat complex numbers as valid number, then you need to type cast your passed string to complex() instead of float(). Then your is_number function will look like:

def is_number(n):
    is_number = True
    try:
        #      v type-casting the number here as `complex`, instead of `float`
        num = complex(n)
        is_number = num == num
    except ValueError:
        is_number = False
    return is_number

Sample Run:

>>> is_number('1+2j')    # Valid 
True                     #      : complex number 

>>> is_number('1+ 2j')   # Invalid 
False                    #      : string with space in complex number represetantion
                         #        is treated as invalid complex number

>>> is_number('123')     # Valid
True                     #      : positive integer

>>> is_number('-123')    # Valid 
True                     #      : negative integer

>>> is_number('abc')     # Invalid 
False                    #      : some random string, not a valid number

>>> is_number('nan')     # Invalid
False                    #      : not a number "nan" string

PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number function which fits your requirement.

How to add an image to the "drawable" folder in Android Studio?

Copy the image then paste it to drawables in the resource folder of you project in android studio.Make sure the name of your image is not too long and does not have any spacial characters.Then click SRC(source) under properties and look for your image click on it then it will automatically get imported to you image view on you emulator.

Set default time in bootstrap-datetimepicker

Hello developers,

Please try this code

var default_date=  new Date(); // or your date
$('#datetimepicker').datetimepicker({
    format: 'DD/MM/YYYY HH:mm', // format you want to show on datetimepicker
    useCurrent:false, // default this is set to true
    defaultDate: default_date
});

if you want to set default date then please set useCurrent to false otherwise setDate or defaultDate like methods will not work.

Gridview get Checkbox.Checked value

You want an independent for loop for all the rows in grid view, then refer the below link

http://nikhilsreeni.wordpress.com/asp-net/checkbox/

Select all checkbox in Gridview

CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
    cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);

    cb.Checked = ((CheckBox)sender).Checked;
}

Select checked rows to a dataset; For gridview multiple edit

CheckBox cb = default(CheckBox);

foreach (GridViewRow row in grdforumcomments.Rows)
{
    cb = (CheckBox)row.FindControl("cbsel");
    if (cb.Checked)
    {
        drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
        drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
        drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
    }
}

Syntax for a for loop in ruby

['foo', 'bar', 'baz'].each_with_index {|j, i| puts "#{i} #{j}"}

How to use bitmask?

Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45

unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));

The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

You're probably passing null value if you're loading the coordinates dynamically, set a check before you call the map loader ie: if(mapCords){loadMap}

How to scroll to top of a div using jQuery?

Special thanks to Stoic for

   $("#miscCategory").animate({scrollTop: $("#miscCategory").offset().top});

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

I have personally witnessed "" resulting in (minor) problems twice. Once was due to a mistake of a junior developer new to team-based programming, and the other was a simple typo, but the fact is using string.Empty would have avoided both issues.

Yes, this is very much a judgement call, but when a language gives you multiple ways to do things, I tend to lean toward the one that has the most compiler oversight and strongest compile-time enforcement. That is not "". It's all about expressing specific intent.

If you type string.EMpty or Strng.Empty, the compiler lets you know you did it wrong. Immediately. It simply will not compile. As a developer you are citing specific intent that the compiler (or another developer) cannot in any way misinterpret, and when you do it wrong, you can't create a bug.

If you type " " when you mean "" or vice-versa, the compiler happily does what you told it to do. Another developer may or may not be able to glean your specific intent. Bug created.

Long before string.Empty was a thing I've used a standard library that defined the EMPTY_STRING constant. We still use that constant in case statements where string.Empty is not allowed.

Whenever possible, put the compiler to work for you, and eliminate the possibility of human error, no matter how small. IMO, this trumps "readability" as others have cited.

Specificity and compile time enforcement. It's what's for dinner.

Delete the 'first' record from a table in SQL Server, without a WHERE condition

SQL-92:

DELETE Field FROM Table WHERE Field IN (SELECT TOP 1 Field FROM Table ORDER BY Field DESC)

How do I make a dotted/dashed line in Android?

The only thing that worked for me and I think it is the simplest way is using a Path with a paint object like this:

    Paint paintDash = new Paint();
    paintDash.setARGB(255, 0, 0, 0);
    paintDash.setStyle(Paint.Style.STROKE);
    paintDash.setPathEffect(new DashPathEffect(new float[]{10f,10f}, 0));
    paintDash.setStrokeWidth(2);
    Path pathDashLine = new Path();

Then onDraw(): (important call reset if you change those points between ondraw calls, cause Path save all the movements)

    pathDashLine.reset();
    pathDashLine.moveTo(porigenX, porigenY);
    pathDashLine.lineTo(cursorX,cursorY);
    c.drawPath(pathDashLine, paintDash);

Why am I getting this error Premature end of file?

I resolved the issue by converting the source feed from http://www.news18.com/rss/politics.xml to https://www.news18.com/rss/politics.xml

with http below code was creating an empty file which was causing the issue down the line

    String feedUrl = "https://www.news18.com/rss/politics.xml"; 
    File feedXmlFile = null;

    try {
    feedXmlFile =new File("C://opinionpoll/newsFeed.xml");
    FileUtils.copyURLToFile(new URL(feedUrl),feedXmlFile);


          DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
          DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
          Document doc = dBuilder.parse(feedXmlFile);

iPhone - Grand Central Dispatch main thread

Hopefully I'm understanding your question correctly in that you are wondering about the differences between dispatch_async and dispatch_sync?

dispatch_async

will dispatch the block to a queue asynchronously. Meaning it will send the block to the queue and not wait for it to return before continuing on the execution of the remaining code in your method.

dispatch_sync

will dispatch the block to a queue synchronously. This will prevent any more execution of remaining code in the method until the block has finished executing.

I've mostly used a dispatch_async to a background queue to get work off the main queue and take advantage of any extra cores that the device may have. Then dispatch_async to the main thread if I need to update the UI.

Good luck

Math operations from string

A simple way but dangerous way to do this would be to use eval(). eval() executes the string passed to it as code. The dangerous thing about this is that if this string is gained from user input, they could maliciously execute code that could break the computer. I would get the input, check it with a regex, and then execute it if you determine if it's OK. If it's only going to be in the format "number operation number", then you could use a simple regex:

import re
s = raw_input('What is your math problem? ')
if re.findall('\d+? *?\+ *?\d+?', s):
  print eval(s)
else:
  print "Try entering a math problem"

Otherwise, you would have to come up with something a bit stricter than this. You could also do it conversely, using a regex to find if certain things are not in it, such as numbers and operations. Also you could check to see if the input contains certain commands.

Get current directory name (without full path) in a Bash script

Use:

basename "$PWD"

OR

IFS=/ 
var=($PWD)
echo ${var[-1]} 

Turn the Internal Filename Separator (IFS) back to space.

IFS= 

There is one space after the IFS.

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

It's looking for the file in the current directory.

First, go to that directory

cd /users/gcameron/Desktop/map

And then try to run it

python colorize_svg.py

Spring Boot Multiple Datasource

Update 2018-01-07 with Spring Boot 1.5.8.RELEASE

If you want to know how to config it, how to use it, and how to control transaction. I may have answers for you.

You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/

I copied some code here.

First you have to set application.properties like this

#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver

Then define them as providers (@Bean) like this:

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
    return DataSourceBuilder.create().build();
}

Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example

@Qualifier("datasource1")
@Autowired
private DataSource dataSource;

If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:

@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

Then you can use it like

@Transactional //this will use the first datasource because it is @primary

or

@Transactional("tm2")

This should be enough. See example and detail in the link above.

CRON job to run on the last day of the month

Some cron implementations support the "L" flag to represent the last day of the month.

If you're lucky to be using one of those implementations, it's as simple as:

0 55 23 L * ?

That will run at 11:55 pm on the last day of every month.

http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger

Git log out user from command line

Try this on Windows:

cmdkey /delete:LegacyGeneric:target=git:https://github.com

Javascript Array.sort implementation?

As of V8 v7.0 / Chrome 70, V8 uses TimSort, Python's sorting algorithm. Chrome 70 was released on September 13, 2018.

See the the post on the V8 dev blog for details about this change. You can also read the source code or patch 1186801.

Converting JSON String to Dictionary Not List

I am working with a Python code for a REST API, so this is for those who are working on similar projects.

I extract data from an URL using a POST request and the raw output is JSON. For some reason the output is already a dictionary, not a list, and I'm able to refer to the nested dictionary keys right away, like this:

datapoint_1 = json1_data['datapoints']['datapoint_1']

where datapoint_1 is inside the datapoints dictionary.

How to set HttpResponse timeout for Android in Java

you can creat HttpClient instance by the way with Httpclient-android-4.3.5,it can work well.

 SSLContext sslContext = SSLContexts.createSystemDefault();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
                RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCircularRedirectsAllowed(false).setConnectionRequestTimeout(30*1000).setConnectTimeout(30 * 1000).setMaxRedirects(10).setSocketTimeout(60 * 1000);
        CloseableHttpClient hc = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(requestConfigBuilder.build()).build();

CURRENT_DATE/CURDATE() not working as default DATE value

Currently from MySQL 8 you can set the following to a DATE column:

In MySQL Workbench, in the Default field next to the column, write: (curdate())

If you put just curdate() it will fail. You need the extra ( and ) at the beginning and end.

Selecting only numeric columns from a data frame

iris %>% dplyr::select(where(is.numeric)) #as per most recent updates

Another option with purrr would be to negate discard function:

iris %>% purrr::discard(~!is.numeric(.))

If you want the names of the numeric columns, you can add names or colnames:

iris %>% purrr::discard(~!is.numeric(.)) %>% names

How to write a comment in a Razor view?

Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.

Server side Comments:

Razor .cshtml

Like so:

@* Comment goes here *@

.aspx
For those looking for the older .aspx view (and Asp.Net WebForms) server side comment syntax:

<%-- Comment goes here --%>

Client Side Comments

HTML Comment

<!-- Comment goes here -->

Javascript Comment

// One line Comment goes Here
/* Multiline comment
   goes here */

As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

On your remote machine, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:

  • Install Oracle Client , and add bin location to Path environment varaible of windows OR
  • Copy oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version), oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll

On your local machine most probably path to Oracle Client is already added in Path environment variable to there required dll are available to application but not on remote machine

How do I hide an element on a click event anywhere outside of the element?

This following code example seems to work best for me. While you can use 'return false' that stops all handling of that event for the div or any of it's children. If you want to have controls on the pop-up div (a pop-up login form for example) you need to use event.stopPropogation().

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <a id="link" href="#">show box</a>
    <div id="box" style="background: #eee; display: none">
        <p>a paragraph of text</p>
        <input type="file"  />
    </div>

    <script src="jquery.js" type="text/javascript"></script>

    <script type="text/javascript">
        var box = $('#box');
        var link = $('#link');

        link.click(function() {
            box.show(); return false;
        });

        $(document).click(function() {
            box.hide();
        });

        box.click(function(e) {
            e.stopPropagation();
        });

    </script>
</body>
</html>

How to change default JRE for all Eclipse workspaces?

I navigated to:

Eclipse>Pref>Java>Installed JRE>Search...

2 of them popped up and I checked the latest one. Before I did this I also went to About>Check for Updates and updated it. I didn't have to reinstall any JRE or JDK either. I might have done it a while back, except it was with 1.6 not 1.4. Hope that helps!

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

If your <td> is not empty, one popular trick is to insert a non breaking space &nbsp; in it, such that:

 <td id="td1">&nbsp;</td>

Then you will be able to use:

 document.getElementById('td1').firstChild.data = 'New Value';

Otherwise, if you do not fancy adding the meaningless &nbsp you can use the solution that Jonathan Fingland described in the other answer.

How to remove/delete a large file from commit history in Git repository?

I ran into this with a bitbucket account, where I had accidentally stored ginormous *.jpa backups of my site.

git filter-branch --prune-empty --index-filter 'git rm -rf --cached --ignore-unmatch MY-BIG-DIRECTORY-OR-FILE' --tag-name-filter cat -- --all

Relpace MY-BIG-DIRECTORY with the folder in question to completely rewrite your history (including tags).

source: https://web.archive.org/web/20170727144429/http://naleid.com:80/blog/2012/01/17/finding-and-purging-big-files-from-git-history/

Checking if a SQL Server login already exists

This works on SQL Server 2000.

use master
select count(*) From sysxlogins WHERE NAME = 'myUsername'

on SQL 2005, change the 2nd line to

select count(*) From syslogins WHERE NAME = 'myUsername'

I'm not sure about SQL 2008, but I'm guessing that it will be the same as SQL 2005 and if not, this should give you an idea of where t start looking.

How to resolve git status "Unmerged paths:"?

Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:

git reset

This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run

git add -p

which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached), you can commit, and then

git reset --hard

to destroy all the unwanted changes in your working directory.

Convert seconds into days, hours, minutes and seconds

This is a function i used in the past for substracting a date from another one related with your question, my principe was to get how many days, hours minutes and seconds has left until a product has expired :

$expirationDate = strtotime("2015-01-12 20:08:23");
$toDay = strtotime(date('Y-m-d H:i:s'));
$difference = abs($toDay - $expirationDate);
$days = floor($difference / 86400);
$hours = floor(($difference - $days * 86400) / 3600);
$minutes = floor(($difference - $days * 86400 - $hours * 3600) / 60);
$seconds = floor($difference - $days * 86400 - $hours * 3600 - $minutes * 60);

echo "{$days} days {$hours} hours {$minutes} minutes {$seconds} seconds";

Send form data with jquery ajax json

The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.

To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.

$.ajax({
    url: 'test.php',
    type: "POST",
    dataType: 'json',
    data: formToJson($("form")),
    contentType: 'application/json;charset=UTF-8',
    ...
})

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

I prefer to use Daniel X. Moore's {SUPER: SYSTEM}. This is a discipline that provides benefits such as true instance variables, trait based inheritance, class hierarchies and configuration options. The example below illustrates the use of true instance variables, which I believe is the biggest advantage. If you don't need instance variables and are happy with only public or private variables then there are probably simpler systems.

function Person(I) {
  I = I || {};

  Object.reverseMerge(I, {
    name: "McLovin",
    age: 25,
    homeState: "Hawaii"
  });

  return {
    introduce: function() {
      return "Hi I'm " + I.name + " and I'm " + I.age;
    }
  };
}

var fogel = Person({
  age: "old enough"
});
fogel.introduce(); // "Hi I'm McLovin and I'm old enough"

Wow, that's not really very useful on it's own, but take a look at adding a subclass:

function Ninja(I) {
  I = I || {};

  Object.reverseMerge(I, {
    belt: "black"
  });

  // Ninja is a subclass of person
  return Object.extend(Person(I), {
    greetChallenger: function() {
      return "In all my " + I.age + " years as a ninja, I've never met a challenger as worthy as you...";
    }
  });
}

var resig = Ninja({name: "John Resig"});

resig.introduce(); // "Hi I'm John Resig and I'm 25"

Another advantage is the ability to have modules and trait based inheritance.

// The Bindable module
function Bindable() {

  var eventCallbacks = {};

  return {
    bind: function(event, callback) {
      eventCallbacks[event] = eventCallbacks[event] || [];

      eventCallbacks[event].push(callback);
    },

    trigger: function(event) {
      var callbacks = eventCallbacks[event];

      if(callbacks && callbacks.length) {
        var self = this;
        callbacks.forEach(function(callback) {
          callback(self);
        });
      }
    },
  };
}

An example of having the person class include the bindable module.

function Person(I) {
  I = I || {};

  Object.reverseMerge(I, {
    name: "McLovin",
    age: 25,
    homeState: "Hawaii"
  });

  var self = {
    introduce: function() {
      return "Hi I'm " + I.name + " and I'm " + I.age;
    }
  };

  // Including the Bindable module
  Object.extend(self, Bindable());

  return self;
}

var person = Person();
person.bind("eat", function() {
  alert(person.introduce() + " and I'm eating!");
});

person.trigger("eat"); // Blasts the alert!

Disclosure: I am Daniel X. Moore and this is my {SUPER: SYSTEM}. It is the best way to define a class in JavaScript.

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

One thing you might consider is something like Robocode, in which a lot of coding is abstracted away and you basically just tell a robot what to do. A simple 10-line function can make the robot do a great deal, and has a very visual and easy-to-follow result.

Perhaps Robocode itself isn't suited to the task, but this kind of thing is a good way to relate written code to visual actions on the computer, plus it's fun to watch for when you need to give examples.

public class MyFirstJuniorRobot extends JuniorRobot {
 public void run() {
  setColors(green, black, blue);
  // Seesaw forever
  while (true) {
   ahead(100); // Move ahead 100
   turnGunRight(360); // Spin gun around
   back(100); // Move back 100
   turnGunRight(360); // Spin gun around
  }
 }
 public void onScannedRobot() {
  turnGunTo(scannedAngle);
  fire(1);
 }
 public void onHitByBullet() {
  turnAheadLeft(100, 90 - hitByBulletBearing);
 }
}

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

SQL how to check that two tables has exactly the same data?

    SELECT unnest(ARRAY[1,2,2,3,3]) 
    EXCEPT
    SELECT unnest(ARRAY[1,1,2,3,3])
UNION
    SELECT unnest(ARRAY[1,1,2,3,3])
    EXCEPT
    SELECT unnest(ARRAY[1,2,2,3,3])

Result is null, but sources are different!

But:

(
    SELECT unnest(ARRAY[1,2,2,3])
    EXCEPT ALL
    SELECT unnest(ARRAY[2,1,2,3])
)
UNION
(
    SELECT unnest(ARRAY[2,1,2,3])
    EXCEPT ALL
    SELECT unnest(ARRAY[1,2,2,3])
)

works.

Bootstrap modal not displaying

I had the same issue and I realized that my <button>had a type="submit"when Bootstrap states that it needs to be type="button"

Escaping HTML strings with jQuery

If you're escaping for HTML, there are only three that I can think of that would be really necessary:

html.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");

Depending on your use case, you might also need to do things like " to &quot;. If the list got big enough, I'd just use an array:

var escaped = html;
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/"/g, "&quot;"]]
for(var item in findReplace)
    escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);

encodeURIComponent() will only escape it for URLs, not for HTML.

Parse rfc3339 date strings in Python?

You should have a look at moment which is a python port of the excellent js lib momentjs.

One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

import moment
time_string='2012-10-09T19:00:55Z'

m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday

Result:

2012-10-09 19:10
2

How can I use threading in Python?

Most documentation and tutorials use Python's Threading and Queue module, and they could seem overwhelming for beginners.

Perhaps consider the concurrent.futures.ThreadPoolExecutor module of Python 3.

Combined with with clause and list comprehension it could be a real charm.

from concurrent.futures import ThreadPoolExecutor, as_completed

def get_url(url):
    # Your actual program here. Using threading.Lock() if necessary
    return ""

# List of URLs to fetch
urls = ["url1", "url2"]

with ThreadPoolExecutor(max_workers = 5) as executor:

    # Create threads
    futures = {executor.submit(get_url, url) for url in urls}

    # as_completed() gives you the threads once finished
    for f in as_completed(futures):
        # Get the results
        rs = f.result()

How do I use FileSystemObject in VBA?

In excel 2013 the object creation string is:

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

instead of the code in the answer above:

Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")

Angular 2 ngfor first, last, index loop

Here is how its done in Angular 6

<li *ngFor="let user of userObservable ; first as isFirst">
   <span *ngIf="isFirst">default</span>
</li>

Note the change from let first = first to first as isFirst

Javascript loop through object array?

To loop through an object array or just array in javascript, you can do the following:

var cars = [{name: 'Audi'}, {name: 'BMW'}, {name: 'Ferrari'}, {name: 'Mercedes'}, {name: 'Maserati'}];

for(var i = 0; i < cars.length; i++) {
    console.log(cars[i].name);
}

There is also the forEach() function, which is more "javascript-ish" and also less code but more complicated for its syntax:

cars.forEach(function (car) {
    console.log(car.name);
});

And both of them are outputting the following:

// Audi
// BMW
// Ferrari
// Mercedes
// Maserati

How do I delete an entity from symfony2

From what I understand, you struggle with what to put into your template.

I'll show an example:

<ul>
    {% for guest in guests %}
    <li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
    {% endfor %}
</ul>

Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.

How do I read a string entered by the user in C?

Using scanf removing any blank spaces before the string is typed and limiting the amount of characters to be read:

#define SIZE 100

....

char str[SIZE];

scanf(" %99[^\n]", str);

/* Or even you can do it like this */

scanf(" %99[a-zA-Z0-9 ]", str);

If you do not limit the amount of characters to be read with scanf it can be as dangerous as gets

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

The Problem might be from the driver name for example instead of DRIVER={MySQL ODBC 5.3 Driver} try DRIVER={MySQL ODBC 5.3 Unicode Driver} you can see the name of the driver from administration tool

How can I move a tag on a git branch to a different commit?

I try to avoid a few things when using Git.

  1. Using knowledge of the internals, e.g. refs/tags. I try to use solely the documented Git commands and avoid using things which require knowledge of the internal contents of the .git directory. (That is to say, I treat Git as a Git user and not a Git developer.)

  2. The use of force when not required.

  3. Overdoing things. (Pushing a branch and/or lots of tags, to get one tag where I want it.)

So here is my non-violent solution for changing a tag, both locally and remotely, without knowledge of the Git internals.

I use it when a software fix ultimately has a problem and needs to be updated/re-released.

git tag -d fix123                # delete the old local tag
git push github :fix123          # delete the old remote tag (use for each affected remote)
git tag fix123 790a621265        # create a new local tag
git push github fix123           # push new tag to remote    (use for each affected remote)

github is a sample remote name, fix123 is a sample tag name, and 790a621265 a sample commit.

jQuery & CSS - Remove/Add display:none

i'd suggest adding a class to display/hide elements:

.hide { display:none; }

and then use jquery's .toggleClass() to show/hide the element:

$(".news").toggleClass("hide");

HashMap: One Key, multiple Values

For example:

Map<Object,Pair<Integer,String>> multiMap = new HashMap<Object,Pair<Integer,String>>();

where the Pair is a parametric class

public class Pair<A, B> {
    A first = null;
    B second = null;

    Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    public A getFirst() {
        return first;
    }

    public void setFirst(A first) {
        this.first = first;
    }

    public B getSecond() {
        return second;
    }

    public void setSecond(B second) {
        this.second = second;
    }

}

Handling onchange event in HTML.DropDownList Razor MVC

The way of dknaack does not work for me, I found this solution as well:

@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList, 
                    "Select chapter", new { @onchange = "location = this.value;" })

where

@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)

In the controller you can add:

DbModel db = new DbModel();    //entity model of Entity Framework

ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");

How can I mock the JavaScript window object using Jest?

Instead of window use global

it('correct url is called', () => {
  global.open = jest.fn();
  statementService.openStatementsReport(111);
  expect(global.open).toBeCalled();
});

you could also try

const open = jest.fn()
Object.defineProperty(window, 'open', open);

INSERT INTO @TABLE EXEC @query with SQL Server 2000

The documentation is misleading.
I have the following code running in production

DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
   SET @sql = 'SELECT UserID FROM UserTable'
*/

INSERT INTO @table
EXEC(@sql)

SELECT * FROM @table

How to extract string following a pattern with grep, regex or perl

The regular expression would be:

.+name="([^"]+)"

Then the grouping would be in the \1

How to get ° character in a string in python?

You can also use chr(176) to print the degree sign. Here is an example using python 3.6.5 interactive shell:

https://i.stack.imgur.com/spoWL.png

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

You could unregister the control with

regsvr32 /u badboy.ocx

at the command line. Though i would suggest testing these things in a vmware.

How can I convert a zero-terminated byte array to string?

Though not extremely performant, the only readable solution is:

  // Split by separator and pick the first one.
  // This has all the characters till null, excluding null itself.
  retByteArray := bytes.Split(byteArray[:], []byte{0}) [0]

  // OR

  // If you want a true C-like string, including the null character
  retByteArray := bytes.SplitAfter(byteArray[:], []byte{0}) [0]

A full example to have a C-style byte array:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var byteArray = [6]byte{97,98,0,100,0,99}

    cStyleString := bytes.SplitAfter(byteArray[:], []byte{0}) [0]
    fmt.Println(cStyleString)
}

A full example to have a Go style string excluding the nulls:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var byteArray = [6]byte{97, 98, 0, 100, 0, 99}

    goStyleString := string(bytes.Split(byteArray[:], []byte{0}) [0])
    fmt.Println(goStyleString)
}

This allocates a slice of slice of bytes. So keep an eye on performance if it is used heavily or repeatedly.

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Hardware

If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).

Software

threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).

Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).

Now a simple case: processing a 512x512 image

Suppose we want one thread to process one pixel (i,j).

We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)

It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.

dim3 threadsPerBlock(8, 8);  // 64 threads

and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.

dim3 numBlocks(imageWidth/threadsPerBlock.x,  /* for instance 512/8 = 64*/
              imageHeight/threadsPerBlock.y); 

The kernel is launched like this:

myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );       

Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.

In the kernel the pixel (i,j) to be processed by a thread is calculated this way:

uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;

module.exports vs exports in Node.js

module.exports and exports both point to the same object before the module is evaluated.

Any property you add to the module.exports object will be available when your module is used in another module using require statement. exports is a shortcut made available for the same thing. For instance:

module.exports.add = (a, b) => a+b

is equivalent to writing:

exports.add = (a, b) => a+b

So it is okay as long as you do not assign a new value to exports variable. When you do something like this:

exports = (a, b) => a+b 

as you are assigning a new value to exports it no longer has reference to the exported object and thus will remain local to your module.

If you are planning to assign a new value to module.exports rather than adding new properties to the initial object made available, you should probably consider doing as given below:

module.exports = exports = (a, b) => a+b

Node.js website has a very good explanation of this.

How to vertically center a container in Bootstrap?

My prefered technique :

body {
  display: table;
  position: absolute;
  height: 100%;
  width: 100%;
}

.jumbotron {
   display: table-cell;
   vertical-align: middle;
}

Demo

_x000D_
_x000D_
body {_x000D_
  display: table;_x000D_
  position: absolute;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.jumbotron {_x000D_
   display: table-cell;_x000D_
   vertical-align: middle;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">_x000D_
<div class="jumbotron vertical-center">_x000D_
  <div class="container text-center">_x000D_
    <h1>The easiest and powerful way</h1>_x000D_
    <div class="row">_x000D_
      <div class="col-md-7">_x000D_
        <div class="top-bg">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>_x000D_
      </div>_x000D_
_x000D_
      <div class="col-md-5 iPhone-features">_x000D_
        <ul class="top-features">_x000D_
          <li>_x000D_
            <span><i class="fa fa-random simple_bg top-features-bg"></i></span>_x000D_
            <p><strong>Redirect</strong><br>Visitors where they converts more.</p>_x000D_
          </li>_x000D_
          <li>_x000D_
            <span><i class="fa fa-cogs simple_bg top-features-bg"></i></span>_x000D_
            <p><strong>Track</strong><br>Views, Clicks and Conversions.</p>_x000D_
          </li>_x000D_
          <li>_x000D_
            <span><i class="fa fa-check simple_bg top-features-bg"></i></span>_x000D_
            <p><strong>Check</strong><br>Constantly the status of your links.</p>_x000D_
          </li>_x000D_
          <li>_x000D_
            <span><i class="fa fa-users simple_bg top-features-bg"></i></span>_x000D_
            <p><strong>Collaborate</strong><br>With Customers, Partners and Co-Workers.</p>_x000D_
          </li>_x000D_
          <a href="pricing-and-signup.html" class="btn-primary btn h2 lightBlue get-Started-btn">GET STARTED</a>_x000D_
          <h6 class="get-Started-sub-btn">FREE VERSION AVAILABLE!</h6>_x000D_
        </ul>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

iOS: set font size of UILabel Programmatically

In Swift 3.0, you could use this code below:

let textLabel = UILabel(frame: CGRect(x:containerView.frame.width/2 - 35, y: 
    containerView.frame.height/2 + 10, width: 70, height: 20))
    textLabel.text = "Add Text"
    textLabel.font = UIFont(name: "Helvetica", size: 15.0) // set fontName and Size
    textLabel.textAlignment = .center
    containerView.addSubview(textLabel) // containerView is a UIView

React Hooks useState() with Object

Thanks Philip this helped me - my use case was I had a form with lot of input fields so I maintained initial state as object and I was not able to update the object state.The above post helped me :)

const [projectGroupDetails, setProjectGroupDetails] = useState({
    "projectGroupId": "",
    "projectGroup": "DDD",
    "project-id": "",
    "appd-ui": "",
    "appd-node": ""    
});

const inputGroupChangeHandler = (event) => {
    setProjectGroupDetails((prevState) => ({
       ...prevState,
       [event.target.id]: event.target.value
    }));
}

<Input 
    id="projectGroupId" 
    labelText="Project Group Id" 
    value={projectGroupDetails.projectGroupId} 
    onChange={inputGroupChangeHandler} 
/>


How to get htaccess to work on MAMP

Go to httpd.conf on /Applications/MAMP/conf/apache and see if the LoadModule rewrite_module modules/mod_rewrite.so line is un-commented (without the # at the beginning)

and change these from ...

<VirtualHost *:80>
    ServerName ...
    DocumentRoot /....
</VirtualHost>

To this:

<VirtualHost *:80>
    ServerAdmin ...
    ServerName ...

    DocumentRoot ...
    <Directory ...>
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory ...>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
</VirtualHost>

Update OpenSSL on OS X with Homebrew

I had problems installing some Wordpress plugins on my local server running php56 on OSX10.11. They failed connection on the external API over SSL.

Installing openSSL didn't solved my problem. But then I figured out that CURL also needed to be reinstalled.

This solved my problem using Homebrew.

brew rm curl && brew install curl --with-openssl

brew uninstall php56 && brew install php56 --with-homebrew-curl --with-openssl

How to remove spaces from a string using JavaScript?

_x000D_
_x000D_
var str = '/var/www/site/Brand new document.docx';

document.write( str.replace(/\s\/g, '') );


----------
_x000D_
_x000D_
_x000D_

Very simple C# CSV reader

You can try the some thing like the below LINQ snippet.

string[] allLines = File.ReadAllLines(@"E:\Temp\data.csv");

    var query = from line in allLines
                let data = line.Split(',')
                select new
                {
                    Device = data[0],
                    SignalStrength = data[1],
                    Location = data[2], 
                    Time = data[3],
                    Age = Convert.ToInt16(data[4])
                };

UPDATE: Over a period of time, things evolved. As of now, I would prefer to use this library http://www.aspnetperformance.com/post/LINQ-to-CSV-library.aspx

How to handle a lost KeyStore password in Android?

In terminal go to which might be different in your PC :

C:\Program Files\Java\jre1.8.0_241\bin

Then:

For Windows:

keytool -list -v -keystore C:\Users\YOURUSERPROFILENAME\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

For Mac:

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

What are alternatives to document.write?

I fail to see the problem with document.write. If you are using it before the onload event fires, as you presumably are, to build elements from structured data for instance, it is the appropriate tool to use. There is no performance advantage to using insertAdjacentHTML or explicitly adding nodes to the DOM after it has been built. I just tested it three different ways with an old script I once used to schedule incoming modem calls for a 24/7 service on a bank of 4 modems.

By the time it is finished this script creates over 3000 DOM nodes, mostly table cells. On a 7 year old PC running Firefox on Vista, this little exercise takes less than 2 seconds using document.write from a local 12kb source file and three 1px GIFs which are re-used about 2000 times. The page just pops into existence fully formed, ready to handle events.

Using insertAdjacentHTML is not a direct substitute as the browser closes tags which the script requires remain open, and takes twice as long to ultimately create a mangled page. Writing all the pieces to a string and then passing it to insertAdjacentHTML takes even longer, but at least you get the page as designed. Other options (like manually re-building the DOM one node at a time) are so ridiculous that I'm not even going there.

Sometimes document.write is the thing to use. The fact that it is one of the oldest methods in JavaScript is not a point against it, but a point in its favor - it is highly optimized code which does exactly what it was intended to do and has been doing since its inception.

It's nice to know that there are alternative post-load methods available, but it must be understood that these are intended for a different purpose entirely; namely modifying the DOM after it has been created and memory allocated to it. It is inherently more resource-intensive to use these methods if your script is intended to write the HTML from which the browser creates the DOM in the first place.

Just write it and let the browser and interpreter do the work. That's what they are there for.

PS: I just tested using an onload param in the body tag and even at this point the document is still open and document.write() functions as intended. Also, there is no perceivable performance difference between the various methods in the latest version of Firefox. Of course there is a ton of caching probably going on somewhere in the hardware/software stack, but that's the point really - let the machine do the work. It may make a difference on a cheap smartphone though. Cheers!

How to copy directories in OS X 10.7.3?

tl;dr

cp -R "/src/project 1/App" "/src/project 2"

Explanation:

Using quotes will cater for spaces in the directory names

cp -R "/src/project 1/App" "/src/project 2"

If the App directory is specified in the destination directory:

cp -R "/src/project 1/App" "/src/project 2/App"

and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"

Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.

Inside a bash script:

cp -R "${1}/App" "${2}"

How to update a value in a json file and save it through node.js

//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));

Case vs If Else If: Which is more efficient?

i think it's just the debugger making it simple. Note that a case and "if list" are not ultimately the same. There is is a reason why case blocks normally end with "break". The case stmt actually looks something like this when broken down in assembly.

if myObject.GetType() == type of Car
    GOTO START_CAR
else if myObject.GetType() == type of Bike
    GOTO START_BIKE

LABEL START_CAR
//do something car     
GOTO END

LABEL START_BIKE
//do something bike  
GOTO END

LABEL END

If you don't have the break, then the case blocks would be missing the "GOTO END" stmts, and in fact if you landed in the "car" case you'd actually run both sections

//do something car     
//do something bike  
GOTO END

Angular 2: Passing Data to Routes?

It changes in angular 2.1.0

In something.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
const routes = [
  {
    path: '',
    component: BlogComponent
  },
  {
    path: 'add',
    component: AddComponent
  },
  {
    path: 'edit/:id',
    component: EditComponent,
    data: {
      type: 'edit'
    }
  }

];
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
    MaterialModule.forRoot(),
    FormsModule
  ],
  declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }

To get the data or params in edit component

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {

    this.route.snapshot.params['id'];
    this.route.snapshot.data['type'];

  }
}

.mp4 file not playing in chrome

I too had the same issue. I changed the codec to H264-MPEG-4 AVC and the videos started working in HTML5/Chrome.

Option selected in converter: H264-MPEG-4 AVC, Codec visible in VLC player: H264-MPEG-4 AVC (part 10) (avc1)

Hope it helps...

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

This should be able to set to whatever keybindings you want for indent/outdent here:

Menu FilePreferencesKeyboard Shortcuts

editor.action.indentLines

editor.action.outdentLines

Message 'src refspec master does not match any' when pushing commits in Git

I ran into the same snag..and the solution was to push the code to the repo as though it were an existing project and not a brand new one being initialised.

git remote add origin https://github.com/Name/reponame.git
git branch -M main
git push -u origin main

Convert string to decimal, keeping fractions

Hmm... I can't reproduce this:

using System;

class Test
{
    static void Main()        
    {
        decimal d = decimal.Parse("1200.00");
        Console.WriteLine(d); // Prints 1200.00
    }
}

Are you sure it's not some other part of your code normalizing the decimal value later?

Just in case it's cultural issues, try this version which shouldn't depend on your locale at all:

using System;
using System.Globalization;

class Test
{
    static void Main()        
    {
        decimal d = decimal.Parse("1200.00", CultureInfo.InvariantCulture);
        Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));
    }
}

What charset does Microsoft Excel use when saving files?

From memory, Excel uses the machine-specific ANSI encoding. So this would be Windows-1252 for a EN-US installation, 1251 for Russian, etc.

How to have an automatic timestamp in SQLite?

you can use the custom datetime by using...

 create table noteTable3 
 (created_at DATETIME DEFAULT (STRFTIME('%d-%m-%Y   %H:%M', 'NOW','localtime')),
 title text not null, myNotes text not null);

use 'NOW','localtime' to get the current system date else it will show some past or other time in your Database after insertion time in your db.

Thanks You...

Using HTTPS with REST in Java

Something to keep in mind is that this error isn't only due to self signed certs. The new Entrust CA certs fail with the same error, and the right thing to do is to update the server with the appropriate root certs, not to disable this important security feature.

python: restarting a loop

You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.

perhaps a:

i=2
while i < n:
    if something:
       do something
       i += 1
    else: 
       do something else  
       i = 2 #restart the loop  

How can I capitalize the first letter of each word in a string?

A quick function worked for Python 3

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> capitalizeFirtChar = lambda s: s[:1].upper() + s[1:]
>>> print(capitalizeFirtChar('??????? ????? ????????. ???????? ?? ?????? ? ??????????????!'))
??????? ????? ????????. ???????? ?? ?????? ? ??????????????!
>>> print(capitalizeFirtChar('??? ???? ?????? ???????! ??? ???? ?????? ????? ???.'))
??? ???? ?????? ???????! ??? ???? ?????? ????? ???.
>>> print(capitalizeFirtChar('faith and Labour make Dreams come true.'))
Faith and Labour make Dreams come true.

MySql sum elements of a column

select
  sum(a) as atotal,
  sum(b) as btotal,
  sum(c) as ctotal
from
  yourtable t
where
  t.id in (1, 2, 3)

jQuery Combobox/select autocomplete?

This works great for me and I'm doing more, writing less with jQuery's example modified.

I defined the select object on my page, just like the jQuery ex. I took the text and pushed it to an array. Then I use the array as my source to my input autocomplete. tadaa.

$(function() {
   var mySource = [];
   $("#mySelect").children("option").map(function() {
      mySource.push($(this).text());
   });

   $("#myInput").autocomplete({
      source: mySource,
      minLength: 3
   });
}

'gulp' is not recognized as an internal or external command

The best solution, you can manage the multiple node versions using nvm installer. then, install the required node's version using below command

nvm install version

Use below command as a working node with mentioned version alone

nvm use version

now, you can use any version node without uninstalling previous installed node.

What properties does @Column columnDefinition make redundant?

My Answer: All of the following should be overridden (i.e. describe them all within columndefinition, if appropriate):

  • length
  • precision
  • scale
  • nullable
  • unique

i.e. the column DDL will consist of: name + columndefinition and nothing else.

Rationale follows.


  1. Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.

  2. Other annotation purely logical - properties used in-memory in java to control JPA processing.

  3. That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true) and once via @Column(...,nullable=true). Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.

In your example, length and nullable properties are overridden and redundant.


So, when specifying columnDefinition, what other properties of @Column are made redundant?

  1. In JPA Spec & javadoc:

    • columnDefinition definition: The SQL fragment that is used when generating the DDL for the column.

    • columnDefinition default: Generated SQL to create a column of the inferred type.

    • The following examples are provided:

      @Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
      @Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
      
    • And, err..., that's it really. :-$ ?!

    Does columnDefinition override other properties provided in the same annotation?

    The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.

  2. The following can be safely implied from examples provided in the JPA spec

    • name & table can be used in conjunction with columnDefinition, neither are overridden
    • nullable is overridden/made redundant by columnDefinition
  3. The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):

    • length, precision, scale are overridden/made redundant by the columnDefinition - they are integral to the type
    • insertable and updateable are provided separately and never included in columnDefinition, because they control SQL generation in-memory, before it is emmitted to the database.
  4. That leaves just the "unique" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.


Test My Answer For columns "A" & "B", respectively:

  @Column(name="...", table="...", insertable=true, updateable=false,
          columndefinition="NUMBER(5,2) NOT NULL UNIQUE"

  @Column(name="...", table="...", insertable=false, updateable=true,
          columndefinition="NVARCHAR2(100) NULL"
  • confirm generated table has correct type/nullability/uniqueness
  • optionally, do JPA insert & update: former should include column A, latter column B

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

In SQL Server Import and Export Wizard you can adjust the source data types in the Advanced tab (these become the data types of the output if creating a new table, but otherwise are just used for handling the source data).

The data types are annoyingly different than those in MS SQL, instead of VARCHAR(255) it's DT_STR and the output column width can be set to 255. For VARCHAR(MAX) it's DT_TEXT.

So, on the Data Source selection, in the Advanced tab, change the data type of any offending columns from DT_STR to DT_TEXT (You can select multiple columns and change them all at once).

Import and Export Wizard - Data Source - Advanced

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

The ThreadPoolExecutor class is the base implementation for the executors that are returned from many of the Executors factory methods. So let's approach Fixed and Cached thread pools from ThreadPoolExecutor's perspective.

ThreadPoolExecutor

The main constructor of this class looks like this:

public ThreadPoolExecutor(
                  int corePoolSize,
                  int maximumPoolSize,
                  long keepAliveTime,
                  TimeUnit unit,
                  BlockingQueue<Runnable> workQueue,
                  ThreadFactory threadFactory,
                  RejectedExecutionHandler handler
)

Core Pool Size

The corePoolSize determines the minimum size of the target thread pool. The implementation would maintain a pool of that size even if there are no tasks to execute.

Maximum Pool Size

The maximumPoolSize is the maximum number of threads that can be active at once.

After the thread pool grows and becomes bigger than the corePoolSize threshold, the executor can terminate idle threads and reach to the corePoolSize again. If allowCoreThreadTimeOut is true, then the executor can even terminate core pool threads if they were idle more than keepAliveTime threshold.

So the bottom line is if threads remain idle more than keepAliveTime threshold, they may get terminated since there is no demand for them.

Queuing

What happens when a new task comes in and all core threads are occupied? The new tasks will be queued inside that BlockingQueue<Runnable> instance. When a thread becomes free, one of those queued tasks can be processed.

There are different implementations of the BlockingQueue interface in Java, so we can implement different queuing approaches like:

  1. Bounded Queue: New tasks would be queued inside a bounded task queue.

  2. Unbounded Queue: New tasks would be queued inside an unbounded task queue. So this queue can grow as much as the heap size allows.

  3. Synchronous Handoff: We can also use the SynchronousQueue to queue the new tasks. In that case, when queuing a new task, another thread must already be waiting for that task.

Work Submission

Here's how the ThreadPoolExecutor executes a new task:

  1. If fewer than corePoolSize threads are running, tries to start a new thread with the given task as its first job.
  2. Otherwise, it tries to enqueue the new task using the BlockingQueue#offer method. The offer method won't block if the queue is full and immediately returns false.
  3. If it fails to queue the new task (i.e. offer returns false), then it tries to add a new thread to the thread pool with this task as its first job.
  4. If it fails to add the new thread, then the executor is either shut down or saturated. Either way, the new task would be rejected using the provided RejectedExecutionHandler.

The main difference between the fixed and cached thread pools boils down to these three factors:

  1. Core Pool Size
  2. Maximum Pool Size
  3. Queuing

+-----------+-----------+-------------------+---------------------------------+
| Pool Type | Core Size |    Maximum Size   |         Queuing Strategy        |
+-----------+-----------+-------------------+---------------------------------+
|   Fixed   | n (fixed) |     n (fixed)     | Unbounded `LinkedBlockingQueue` |
+-----------+-----------+-------------------+---------------------------------+
|   Cached  |     0     | Integer.MAX_VALUE |        `SynchronousQueue`       |
+-----------+-----------+-------------------+---------------------------------+


Fixed Thread Pool


Here's how the Excutors.newFixedThreadPool(n) works:

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

As you can see:

  • The thread pool size is fixed.
  • If there is high demand, it won't grow.
  • If threads are idle for quite some time, it won't shrink.
  • Suppose all those threads are occupied with some long-running tasks and the arrival rate is still pretty high. Since the executor is using an unbounded queue, it may consume a huge part of the heap. Being unfortunate enough, we may experience an OutOfMemoryError.

When should I use one or the other? Which strategy is better in terms of resource utilization?

A fixed-size thread pool seems to be a good candidate when we're going to limit the number of concurrent tasks for resource management purposes.

For example, if we're going to use an executor to handle web server requests, a fixed executor can handle the request bursts more reasonably.

For even better resource management, it's highly recommended to create a custom ThreadPoolExecutor with a bounded BlockingQueue<T> implementation coupled with reasonable RejectedExecutionHandler.


Cached Thread Pool


Here's how the Executors.newCachedThreadPool() works:

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

As you can see:

  • The thread pool can grow from zero threads to Integer.MAX_VALUE. Practically, the thread pool is unbounded.
  • If any thread is idle for more than 1 minute, it may get terminated. So the pool can shrink if threads remain too much idle.
  • If all allocated threads are occupied while a new task comes in, then it creates a new thread, as offering a new task to a SynchronousQueue always fails when there is no one on the other end to accept it!

When should I use one or the other? Which strategy is better in terms of resource utilization?

Use it when you have a lot of predictable short-running tasks.

How to print / echo environment variables?

These need to go as different commands e.g.:

NAME=sam; echo "$NAME"
NAME=sam && echo "$NAME"

The expansion $NAME to empty string is done by the shell earlier, before running echo, so at the time the NAME variable is passed to the echo command's environment, the expansion is already done (to null string).

To get the same result in one command:

NAME=sam printenv NAME

Handling errors in Promise.all

NEW ANSWER

const results = await Promise.all(promises.map(p => p.catch(e => e)));
const validResults = results.filter(result => !(result instanceof Error));

FUTURE Promise API

Pythonic way to create a long multi-line string

This approach uses:

  • almost no internal punctuation by using a triple quoted string
  • strips away local indentation using the inspect module
  • uses Python 3.6 formatted string interpolation ('f') for the account_id and def_id variables.

This way looks the most Pythonic to me.

import inspect

query = inspect.cleandoc(f'''
    SELECT action.descr as "action",
    role.id as role_id,
    role.descr as role
    FROM
    public.role_action_def,
    public.role,
    public.record_def,
    public.action
    WHERE role.id = role_action_def.role_id AND
    record_def.id = role_action_def.def_id AND
    action.id = role_action_def.action_id AND
    role_action_def.account_id = {account_id} AND
    record_def.account_id={account_id} AND
    def_id={def_id}'''
)

How to hide the keyboard when I press return key in a UITextField?

If you want to hide the keyboard for a particular keyboard use [self.view resignFirstResponder]; If you want to hide any keyboard from view use [self.view endEditing:true];

Visual Studio 2017: Display method references

In Visual Studio Professional or Enterprise you can enable CodeLens by doing this:

Tools ? Options ? Text Editor ? All Languages ? CodeLens

This is not available in the Community Edition

When should we implement Serializable interface?

The answer to this question is, perhaps surprisingly, never, or more realistically, only when you are forced to for interoperability with legacy code. This is the recommendation in Effective Java, 3rd Edition by Joshua Bloch:

There is no reason to use Java serialization in any new system you write

Oracle's chief architect, Mark Reinhold, is on record as saying removing the current Java serialization mechanism is a long-term goal.


Why Java serialization is flawed

Java provides as part of the language a serialization scheme you can opt in to, by using the Serializable interface. This scheme however has several intractable flaws and should be treated as a failed experiment by the Java language designers.

  • It fundamentally pretends that one can talk about the serialized form of an object. But there are infinitely many serialization schemes, resulting in infinitely many serialized forms. By imposing one scheme, without any way of changing the scheme, applications can not use a scheme most appropriate for them.
  • It is implemented as an additional means of constructing objects, which bypasses any precondition checks your constructors or factory methods perform. Unless tricky, error prone, and difficult to test extra deserialization code is written, your code probably has a gaping security weakness.
  • Testing interoperability of different versions of the serialized form is very difficult.
  • Handling of immutable objects is troublesome.

What to do instead

Instead, use a serialization scheme that you can explicitly control. Such as Protocol Buffers, JSON, XML, or your own custom scheme.

How to clear the logs properly for a Docker container?

Use:

truncate -s 0 /var/lib/docker/containers/*/*-json.log

You may need sudo

sudo sh -c "truncate -s 0 /var/lib/docker/containers/*/*-json.log"

ref. Jeff S. How to clear the logs properly for a Docker container?

Reference: Truncating a file while it's being used (Linux)

restart mysql server on windows 7

open task manager, click in Service button and search MySql service, now you can stop and restart

enter image description here

enter image description here

case statement in SQL, how to return multiple variables?

Depending on your use case, instead of using a case statement, you can use the union of multiple select statements, one for each condition.

My goal when I found this question was to select multiple columns conditionally. I didn't necessarily need the case statement, so this is what I did.

For example:

  SELECT
    a1,
    a2,
    a3,
    ...
  WHERE <condition 1>
    AND (<other conditions>)
  UNION
  SELECT
    b1,
    b2,
    b3,
    ...
  WHERE <condition 2>
    AND (<other conditions>)
  UNION
  SELECT
  ...
-- and so on

Be sure that exactly one condition evaluates to true at a time.

I'm using Postgresql, and the query planner was smart enough to not run a select statement at all if the condition in the where clause evaluated to false (i.e. only one of the select statement actually runs), so this was also performant for me.

What is the format specifier for unsigned short int?

Here is a good table for printf specifiers. So it should be %hu for unsigned short int.

And link to Wikipedia "C data types" too.

Replacing last character in a String with java

you can use regular expressions to identify the last comma (,) and replace it with " " as follow:

if(fieldName.endsWith(","))
{                           
fieldName = fieldName.replace(/,([^,]*)$/," ");
}

What is the difference between concurrent programming and parallel programming?

Classic scheduling of tasks can be serial, parallel or concurrent.

  • Serial: tasks must be executed one after the other in a known tricked order or it will not work. Easy enough.

  • Parallel: tasks must be executed at the same time or it will not work.

    • Any failure of any of the tasks - functionally or in time - will result in total system failure.
    • All tasks must have a common reliable sense of time.

    Try to avoid this or we will have tears by tea time.

  • Concurrent: we do not care. We are not careless, though: we have analysed it and it doesn't matter; we can therefore execute any task using any available facility at any time. Happy days.

Often, the available scheduling changes at known events which we call a state change.

People often think this is about software, but it is in fact a systems design concept that pre-dates computers; software systems were a little slow in the uptake, very few software languages even attempt to address the problem. You might try looking up the transputer language occam if you are interested.

Succinctly, systems design addresses the following:

  • the verb - what you are doing (operation or algorithm)
  • the noun - what you are doing it to (data or interface)
  • when - initiation, schedule, state changes
  • how - serial, parallel, concurrent
  • where - once you know when things happen, you can say where they can happen and not before.
  • why - is this the way to do it? Are there other ways, and more importantly, a better way? What happens if you don't do it?

Good luck.

Convert SVG image to PNG with PHP

You can use Raphaël—JavaScript Library and achieve it easily. It will work in IE also.

Android: Rotate image in imageview by an angle

Rather than convert image to bitmap and then rotate it try to rotate direct image view like below code.

ImageView myImageView = (ImageView)findViewById(R.id.my_imageview);

AnimationSet animSet = new AnimationSet(true);
animSet.setInterpolator(new DecelerateInterpolator());
animSet.setFillAfter(true);
animSet.setFillEnabled(true);

final RotateAnimation animRotate = new RotateAnimation(0.0f, -90.0f,
    RotateAnimation.RELATIVE_TO_SELF, 0.5f, 
    RotateAnimation.RELATIVE_TO_SELF, 0.5f);

animRotate.setDuration(1500);
animRotate.setFillAfter(true);
animSet.addAnimation(animRotate);

myImageView.startAnimation(animSet);

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

Yes, that is supported.

Check the documentation provided here for the supported keywords inside method names.

You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:

List<Inventory> findByIdIn(List<Long> ids);

I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:

The Entity

@Entity
public class Inventory implements Serializable {

  private static final long serialVersionUID = 1L;

  private Long id;

  // other fields
  // getters/setters

}

The Repository

@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {

  List<Inventory> findByIdIn(List<Long> ids);

}

Border around each cell in a range

xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid

Is Python strongly typed?

The term "strong typing" does not have a definite definition.

Therefore, the use of the term depends on with whom you're speaking.

I do not consider any language, in which the type of a variable is not either explicitly declared, or statically typed to be strongly typed.

Strong typing doesn't just preclude conversion (for example, "automatically" converting from an integer to a string). It precludes assignment (i.e., changing the type of a variable).

If the following code compiles (interprets), the language is not strong-typed:

Foo = 1 Foo = "1"

In a strongly typed language, a programmer can "count on" a type.

For example, if a programmer sees the declaration,

UINT64 kZarkCount;

and he or she knows that 20 lines later, kZarkCount is still a UINT64 (as long as it occurs in the same block) - without having to examine intervening code.

'MOD' is not a recognized built-in function name

In TSQL, the modulo is done with a percent sign.

SELECT 38 % 5 would give you the modulo 3

member names cannot be the same as their enclosing type C#

Constructors don't return a type , just remove the return type which is void in your case. It would run fine then.

cleanup php session files

You can create script /etc/cron.hourly/php and put there:

#!/bin/bash

max=24
tmpdir=/tmp

nice find ${tmpdir} -type f -name 'sess_*' -mmin +${max} -delete

Then make the script executable (chmod +x).

Now every hour will be deleted all session files with data modified more than 24 minutes ago.

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

How to "pretty" format JSON output in Ruby on Rails

If you find that the pretty_generate option built into Ruby's JSON library is not "pretty" enough, I recommend my own NeatJSON gem for your formatting.

To use it:

gem install neatjson

and then use

JSON.neat_generate

instead of

JSON.pretty_generate

Like Ruby's pp it will keep objects and arrays on one line when they fit, but wrap to multiple as needed. For example:

{
  "navigation.createroute.poi":[
    {"text":"Lay in a course to the Hilton","params":{"poi":"Hilton"}},
    {"text":"Take me to the airport","params":{"poi":"airport"}},
    {"text":"Let's go to IHOP","params":{"poi":"IHOP"}},
    {"text":"Show me how to get to The Med","params":{"poi":"The Med"}},
    {"text":"Create a route to Arby's","params":{"poi":"Arby's"}},
    {
      "text":"Go to the Hilton by the Airport",
      "params":{"poi":"Hilton","location":"Airport"}
    },
    {
      "text":"Take me to the Fry's in Fresno",
      "params":{"poi":"Fry's","location":"Fresno"}
    }
  ],
  "navigation.eta":[
    {"text":"When will we get there?"},
    {"text":"When will I arrive?"},
    {"text":"What time will I get to the destination?"},
    {"text":"What time will I reach the destination?"},
    {"text":"What time will it be when I arrive?"}
  ]
}

It also supports a variety of formatting options to further customize your output. For example, how many spaces before/after colons? Before/after commas? Inside the brackets of arrays and objects? Do you want to sort the keys of your object? Do you want the colons to all be lined up?

Remove HTML Tags in Javascript with Regex

This is an old question, but I stumbled across it and thought I'd share the method I used:

var body = '<div id="anid">some <a href="link">text</a></div> and some more text';
var temp = document.createElement("div");
temp.innerHTML = body;
var sanitized = temp.textContent || temp.innerText;

sanitized will now contain: "some text and some more text"

Simple, no jQuery needed, and it shouldn't let you down even in more complex cases.

How many characters in varchar(max)

For future readers who need this answer quickly:

2^31-1 = 2.147.483.647 characters

Selecting specific rows and columns from NumPy array

USE:

 >>> a[[0,1,3]][:,[0,2]]
array([[ 0,  2],
   [ 4,  6],
   [12, 14]])

OR:

>>> a[[0,1,3],::2]
array([[ 0,  2],
   [ 4,  6],
   [12, 14]])

Create a function with optional call variables

I don't think your question is very clear, this code assumes that if you're going to include the -domain parameter, it's always 'named' (i.e. dostuff computername arg2 -domain domain); this also makes the computername parameter mandatory.

Function DoStuff(){
    param(
        [Parameter(Mandatory=$true)][string]$computername,
        [Parameter(Mandatory=$false)][string]$arg2,
        [Parameter(Mandatory=$false)][string]$domain
    )
    if(!($domain)){
        $domain = 'domain1'
    }
    write-host $domain
    if($arg2){
        write-host "arg2 present... executing script block"
    }
    else{
        write-host "arg2 missing... exiting or whatever"
    }
}

How to convert date in to yyyy-MM-dd Format?

Use this.

java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);

you will get the output as

2012-12-01

How can I define fieldset border color?

I added it for all fieldsets with

fieldset {
        border: 1px solid lightgray;
    }

I didnt work if I set it separately using for example

border-color : red

. Then a black line was drawn next to the red line.

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.

Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:

  1. start the 32 bits UDL wizard like this: C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)
  2. open the UDL file in Notepad or another text editor, it should more or less have this format:

[oledb] ; Everything after this line is an OLE DB initstring Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False

That should allow your app to start correctly.

Instantiating a generic class in Java

One option is to pass in Bar.class (or whatever type you're interested in - any way of specifying the appropriate Class<T> reference) and keep that value as a field:

public class Test {
    public static void main(String[] args) throws IllegalAccessException,
            InstantiationException {
        Generic<Bar> x = new Generic<>(Bar.class);
        Bar y = x.buildOne();
    }
}

public class Generic<T> {
    private Class<T> clazz;

    public Generic(Class<T> clazz) {
        this.clazz = clazz;
    }

    public T buildOne() throws InstantiationException, IllegalAccessException {
        return clazz.newInstance();
    }
}

public class Bar {
    public Bar() {
        System.out.println("Constructing");
    }
}

Another option is to have a "factory" interface, and you pass a factory to the constructor of the generic class. That's more flexible, and you don't need to worry about the reflection exceptions.

How to get a value from a cell of a dataframe?

For pandas 0.10, where iloc is unavalable, filter a DF and get the first row data for the column VALUE:

df_filt = df[df['C1'] == C1val & df['C2'] == C2val]
result = df_filt.get_value(df_filt.index[0],'VALUE')

if there is more then 1 row filtered, obtain the first row value. There will be an exception if the filter result in empty data frame.

How do I prevent DIV tag starting a new line?

use float:left on the div and the link, or use a span.

How to change Git log date formats

In addition to --date=(relative|local|default|iso|iso-strict|rfc|short|raw), as others have mentioned, you can also use a custom log date format with

--date=format:'%Y-%m-%d %H:%M:%S'

This outputs something like 2016-01-13 11:32:13.

NOTE: If you take a look at the commit linked to below, I believe you'll need at least Git v2.6.0-rc0 for this to work.

In a full command it would be something like:

git config --global alias.lg "log --graph --decorate 
-30 --all --date-order --date=format:'%Y-%m-%d %H:%M:%S' 
--pretty=format:'%C(cyan)%h%Creset %C(black bold)%ad%Creset%C(auto)%d %s'" 

I haven't been able to find this in documentation anywhere (if someone knows where to find it, please comment) so I originally found the placeholders by trial and error.

In my search for documentation on this I found a commit to Git itself that indicates the format is fed directly to strftime. Looking up strftime (here or here) the placeholders I found match the placeholders listed.

The placeholders include:

%a      Abbreviated weekday name
%A      Full weekday name
%b      Abbreviated month name
%B      Full month name
%c      Date and time representation appropriate for locale
%d      Day of month as decimal number (01 – 31)
%H      Hour in 24-hour format (00 – 23)
%I      Hour in 12-hour format (01 – 12)
%j      Day of year as decimal number (001 – 366)
%m      Month as decimal number (01 – 12)
%M      Minute as decimal number (00 – 59)
%p      Current locale's A.M./P.M. indicator for 12-hour clock
%S      Second as decimal number (00 – 59)
%U      Week of year as decimal number, with Sunday as first day of week (00 – 53)
%w      Weekday as decimal number (0 – 6; Sunday is 0)
%W      Week of year as decimal number, with Monday as first day of week (00 – 53)
%x      Date representation for current locale
%X      Time representation for current locale
%y      Year without century, as decimal number (00 – 99)
%Y      Year with century, as decimal number
%z, %Z  Either the time-zone name or time zone abbreviation, depending on registry settings
%%      Percent sign

In a full command it would be something like

git config --global alias.lg "log --graph --decorate -30 --all --date-order --date=format:'%Y-%m-%d %H:%M:%S' --pretty=format:'%C(cyan)%h%Creset %C(black bold)%ad%Creset%C(auto)%d %s'" 

Best way to get identity of inserted row?

I can't speak to other versions of SQL Server, but in 2012, outputting directly works just fine. You don't need to bother with a temporary table.

INSERT INTO MyTable
OUTPUT INSERTED.ID
VALUES (...)

By the way, this technique also works when inserting multiple rows.

INSERT INTO MyTable
OUTPUT INSERTED.ID
VALUES
    (...),
    (...),
    (...)

Output

ID
2
3
4

yii2 redirect in controller action does not work?

I struggled with redirect not working for very long, none of what mentioned above was working for me, until I tried this:

Change:

return $this->redirect('site/secure');

to:

return $this->redirect(['site/secure']);

In other words, needed to enclose it within [] brackets! I am using PHP 7, might be the reason why?

How to read/write from/to file using Go?

Let's make a Go 1-compatible list of all the ways to read and write files in Go.

Because file API has changed recently and most other answers don't work with Go 1. They also miss bufio which is important IMHO.

In the following examples I copy a file by reading from it and writing to the destination file.

Start with the basics

package main

import (
    "io"
    "os"
)

func main() {
    // open input file
    fi, err := os.Open("input.txt")
    if err != nil {
        panic(err)
    }
    // close fi on exit and check for its returned error
    defer func() {
        if err := fi.Close(); err != nil {
            panic(err)
        }
    }()

    // open output file
    fo, err := os.Create("output.txt")
    if err != nil {
        panic(err)
    }
    // close fo on exit and check for its returned error
    defer func() {
        if err := fo.Close(); err != nil {
            panic(err)
        }
    }()

    // make a buffer to keep chunks that are read
    buf := make([]byte, 1024)
    for {
        // read a chunk
        n, err := fi.Read(buf)
        if err != nil && err != io.EOF {
            panic(err)
        }
        if n == 0 {
            break
        }

        // write a chunk
        if _, err := fo.Write(buf[:n]); err != nil {
            panic(err)
        }
    }
}

Here I used os.Open and os.Create which are convenient wrappers around os.OpenFile. We usually don't need to call OpenFile directly.

Notice treating EOF. Read tries to fill buf on each call, and returns io.EOF as error if it reaches end of file in doing so. In this case buf will still hold data. Consequent calls to Read returns zero as the number of bytes read and same io.EOF as error. Any other error will lead to a panic.

Using bufio

package main

import (
    "bufio"
    "io"
    "os"
)

func main() {
    // open input file
    fi, err := os.Open("input.txt")
    if err != nil {
        panic(err)
    }
    // close fi on exit and check for its returned error
    defer func() {
        if err := fi.Close(); err != nil {
            panic(err)
        }
    }()
    // make a read buffer
    r := bufio.NewReader(fi)

    // open output file
    fo, err := os.Create("output.txt")
    if err != nil {
        panic(err)
    }
    // close fo on exit and check for its returned error
    defer func() {
        if err := fo.Close(); err != nil {
            panic(err)
        }
    }()
    // make a write buffer
    w := bufio.NewWriter(fo)

    // make a buffer to keep chunks that are read
    buf := make([]byte, 1024)
    for {
        // read a chunk
        n, err := r.Read(buf)
        if err != nil && err != io.EOF {
            panic(err)
        }
        if n == 0 {
            break
        }

        // write a chunk
        if _, err := w.Write(buf[:n]); err != nil {
            panic(err)
        }
    }

    if err = w.Flush(); err != nil {
        panic(err)
    }
}

bufio is just acting as a buffer here, because we don't have much to do with data. In most other situations (specially with text files) bufio is very useful by giving us a nice API for reading and writing easily and flexibly, while it handles buffering behind the scenes.


Note: The following code is for older Go versions (Go 1.15 and before). Things have changed. For the new way, take a look at this answer.

Using ioutil

package main

import (
    "io/ioutil"
)

func main() {
    // read the whole file at once
    b, err := ioutil.ReadFile("input.txt")
    if err != nil {
        panic(err)
    }

    // write the whole body at once
    err = ioutil.WriteFile("output.txt", b, 0644)
    if err != nil {
        panic(err)
    }
}

Easy as pie! But use it only if you're sure you're not dealing with big files.

Disable color change of anchor tag when visited

You can solve this issue by calling a:link and a:visited selectors together. And follow it with a:hover selector.

a:link, a:visited
{color: gray;}
a:hover
{color: skyblue;}

HTML table needs spacing between columns, not rows

This can be achieved by putting padding between the columns using CSS. You can either add padding to the left of all columns except the first, or add padding to the right of all columns except the last. You should avoid adding padding to the right of the last column or to the left of the first as this will insert redundant white space. You should also avoid being too prescriptive with classes to specify which columns should have the additional padding as this will make maintenance harder if you later add a new column.

The 'lobotomised owl selector' allows you to select all siblings, regardless of if they are a th, td or something else.

_x000D_
_x000D_
tr > * + * {
  padding-left: 4em;
}
_x000D_
<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Fetch: reject promise and catch the error if status is not OK?

For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable

Solution 1: Not throwing an error, handle the error ourselves

  async _fetch(request) {
    const fetchResult = await fetch(request); //Making the req
    const result = await fetchResult.json(); // parsing the response

    if (fetchResult.ok) {
      return result; // return success object
    }


    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    const error = new Error();
    error.info = responseError;

    return (error);
  }

Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:

  const userSaved = await apiCall(data); // calling fetch
  if (userSaved instanceof Error) {
    debug.log('Failed saving user', userSaved); // handle error

    return;
  }
  debug.log('Success saving user', userSaved); // handle success

Solution 2: Throwing an error, using try/catch

async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    let error = new Error();
    error = { ...error, ...responseError };
    throw (error);
  }

Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:

  try {
    const userSaved = await apiCall(data); // calling fetch
    debug.log('Success saving user', userSaved); // handle success
  } catch (e) {
    debug.log('Failed saving user', userSaved); // handle error
  }

Solution 3: Using customer error

  async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    throw new ClassError(result.message, result.data, result.code);
  }

And:

class ClassError extends Error {

  constructor(message = 'Something went wrong', data = '', code = '') {
    super();
    this.message = message;
    this.data = data;
    this.code = code;
  }

}

Hope it helped.

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

  1. First make sure sa is enabled
  2. Change the authontication mode to mixed mode (Window and SQL authentication)
  3. Stop your SQL Server
  4. Restart your SQL Server

How to create table using select query in SQL Server?

An example statement that uses a sub-select :

select * into MyNewTable
from
(
select 
  * 
from 
[SomeOtherTablename]
where 
  EventStartDatetime >= '01/JAN/2018' 
)
) mysourcedata
;

note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.

The database should reply with a message like: (9999 row(s) affected)

How to change the height of a <br>?

I just had this problem, and I got around it by using

<div style="line-height:150%;">
    <br>
</div>

PHP: merge two arrays while keeping keys instead of reindexing?

Two arrays can be easily added or union without chaning their original indexing by + operator. This will be very help full in laravel and codeigniter select dropdown.

 $empty_option = array(
         ''=>'Select Option'
          );

 $option_list = array(
          1=>'Red',
          2=>'White',
          3=>'Green',
         );

  $arr_option = $empty_option + $option_list;

Output will be :

$arr_option = array(
   ''=>'Select Option'
   1=>'Red',
   2=>'White',
   3=>'Green',
 );

estimating of testing effort as a percentage of development time

The only time I factor in extra time for testing is if I'm unfamiliar with the testing technology I'll be using (e.g. using Selenium tests for the first time). Then I factor in maybe 10-20% for getting up to speed on the tools and getting the test infrastructure in place.

Otherwise testing is just an innate part of development and doesn't warrant an extra estimate. In fact, I'd probably increase the estimate for code done without tests.

EDIT: Note that I'm usually writing code test-first. If I have to come in after the fact and write tests for existing code that's going to slow things down. I don't find that test-first development slows me down at all except for very exploratory (read: throw-away) coding.

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

I'm having the same issue here and I was a bit afraid of checking the last box, since I have no idea what the 3rd party SDK will do with the data collected and if they will respect the Limit Ad Settings.

But I found a post by a Google Admob programmer, Eric Leichtenschlag, on their forums:

The Google Mobile Ads SDK and the Google Conversion Tracking SDK utilize Apple's advertising identifier introduced in iOS 6 (IDFA). While each developer is responsible for how they access device data, the SDKs use IDFA under the guidelines laid out in the iOS developer program license agreement, including Limit Ad Tracking.

Including Limit Ad Tracking. This is what the last box is all about. So you must check the that box if you use AdMob. If you use other SDK I strongly recommend checking if they respect the guidelines as well.

Since I run only ads (Google AdMob), I checked the first (Serve ads...) and last box (I, ___, confirm...). App was approved and released, no issues.

Source: https://groups.google.com/forum/#!topic/google-admob-ads-sdk/BsGRSZ-gLmk

Is there a way to use PhantomJS in Python?

Now since the GhostDriver comes bundled with the PhantomJS, it has become even more convenient to use it through Selenium.

I tried the Node installation of PhantomJS, as suggested by Pykler, but in practice I found it to be slower than the standalone installation of PhantomJS. I guess standalone installation didn't provided these features earlier, but as of v1.9, it very much does so.

  1. Install PhantomJS (http://phantomjs.org/download.html) (If you are on Linux, following instructions will help https://stackoverflow.com/a/14267295/382630)
  2. Install Selenium using pip.

Now you can use like this

import selenium.webdriver
driver = selenium.webdriver.PhantomJS()
driver.get('http://google.com')
# do some processing

driver.quit()

How to list files inside a folder with SQL Server

Create a SQLCLR assembly with external access permission that returns the list of files as a result set. There are many examples how to do this, eg. Yet another TVF: returning files from a directory or Trading in xp_cmdshell for SQLCLR (Part 1) - List Directory Contents.

How to check if image exists with given url?

To handle the lazy loading with image existence check I followed this in jQuery-

$('[data-src]').each(function() {
  var $image_place_holder_element = $(this);
  var image_url = $(this).data('src');
  $("<div class='hidden-classe' />").load(image_url, function(response, status, xhr) {
    if (!(status == "error")) {
      $image_place_holder_element.removeClass('image-placeholder');
      $image_place_holder_element.attr('src', image_url);
    }
  }).remove();
});

Reason: if I am using $image_place_holder_element.load() method it will be adding the response to the element, so random div and removing it appeared me a good solution. Hope it works for someone trying to implement lazy loading along with url check.

gdb: how to print the current line or find the current line number?

Keep in mind that gdb is a powerful command -capable of low level instructions- so is tied to assembly concepts.

What you are looking for is called de instruction pointer, i.e:

The instruction pointer register points to the memory address which the processor will next attempt to execute. The instruction pointer is called ip in 16-bit mode, eip in 32-bit mode,and rip in 64-bit mode.

more detail here

all registers available on gdb execution can be shown with:

(gdb) info registers

with it you can find which mode your program is running (looking which of these registers exist)

then (here using most common register rip nowadays, replace with eip or very rarely ip if needed):

(gdb)info line *$rip

will show you line number and file source

(gdb) list *$rip

will show you that line with a few before and after

but probably

(gdb) frame

should be enough in many cases.

How to insert a file in MySQL database?

The BLOB datatype is best for storing files.

Solution to "subquery returns more than 1 row" error

use MAX in your SELECT to return on value.. EXAMPLE

INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT MAX(student_id) FROM student), (SELECT MAX(syr_id) FROM school_year))

instead of

INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT (student_id) FROM student), (SELECT (syr_id) FROM school_year))

try it without MAX it will more than one value

How to split a dos path into its components in Python

I'm not actually sure if this fully answers the question, but I had a fun time writing this little function that keeps a stack, sticks to os.path-based manipulations, and returns the list/stack of items.

def components(path):
    ret = []
    while len(path) > 0:
        path, crust = split(path)
        ret.insert(0, crust)
    return ret

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

This one has burned me many times. Arrays.asList creates an unmodifiable list. From the Javadoc: Returns a fixed-size list backed by the specified array.

Create a new list with the same content:

newList.addAll(Arrays.asList(newArray));

This will create a little extra garbage, but you will be able to mutate it.

Restore the mysql database from .frm files

Just might be useful for someone:

I could only recover frm files after a disaster, at least I could get the table structure from FRM files by doing the following:

1- create some dummy tables with at least one column and SAME NAME with frm files in a new mysql database.

2-stop mysql service

3- copy and paste the old frm files to newly created table's frm files, it should ask you if you want to overwrite or not for each. replace all.

4-start mysql service, and you have your table structure...

regards. anybudy

Catching an exception while using a Python 'with' statement

from __future__ import with_statement

try:
    with open( "a.txt" ) as f :
        print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
    print 'oops'

If you want different handling for errors from the open call vs the working code you could do:

try:
    f = open('foo.txt')
except IOError:
    print('error')
else:
    with f:
        print f.readlines()

Exporting the values in List to excel

The most straightforward way (in my opinion) would be to simply put together a CSV file. If you want to get into formatting and actually writing to a *.xlsx file, there are more complicated solutions (and APIs) to do that for you.

How do I detect a click outside an element?

As a variant:

var $menu = $('#menucontainer');
$(document).on('click', function (e) {

    // If element is opened and click target is outside it, hide it
    if ($menu.is(':visible') && !$menu.is(e.target) && !$menu.has(e.target).length) {
        $menu.hide();
    }
});

It has no problem with stopping event propagation and better supports multiple menus on the same page where clicking on a second menu while a first is open will leave the first open in the stopPropagation solution.

The difference in months between dates in MySQL

This depends on how you want the # of months to be defined. Answer this questions: 'What is difference in months: Feb 15, 2008 - Mar 12, 2009'. Is it defined by clear cut # of days which depends on leap years- what month it is, or same day of previous month = 1 month.

A calculation for Days:

Feb 15 -> 29 (leap year) = 14 Mar 1, 2008 + 365 = Mar 1, 2009. Mar 1 -> Mar 12 = 12 days. 14 + 365 + 12 = 391 days. Total = 391 days / (avg days in month = 30) = 13.03333

A calculation of months:

Feb 15 2008 - Feb 15 2009 = 12 Feb 15 -> Mar 12 = less than 1 month Total = 12 months, or 13 if feb 15 - mar 12 is considered 'the past month'

Python using enumerate inside list comprehension

Be explicit about the tuples.

[(i, j) for (i, j) in enumerate(mylist)]

IntelliJ - Convert a Java project/module into a Maven project/module

Just follow the steps:

  1. Right click to on any module pox.xml and then chose "Add as Maven Project"

enter image description here

  1. Next to varify it, go to the maven tab, you will see the project with all maven goal which you can use:

enter image description here

How do you import classes in JSP?

In case you use JSTL and you wish to import a class in a tag page instead of a jsp page, the syntax is a little bit different. Replace the word 'page' with the word 'tag'.

Instead of Sandman's correct answer

<%@page import="path.to.your.class"%>

use

<%@tag import="path.to.your.class"%>

how to install python distutils

If you are unable to install with either of these:

sudo apt-get install python-distutils
sudo apt-get install python3-distutils

Try this instead:

sudo apt-get install python-distutils-extra

Ref: https://groups.google.com/forum/#!topic/beagleboard/RDlTq8sMxro

How to control font sizes in pgf/tikz graphics in latex?

I found the better control would be using scalefnt package:

\usepackage{scalefnt}
...
{\scalefont{0.5}
\begin{tikzpicture}
...
\end{tikzpicture}
}

How to install grunt and how to build script with it

Some time we need to set PATH variable for WINDOWS

%USERPROFILE%\AppData\Roaming\npm

After that test with where grunt

Note: Do not forget to close the command prompt window and reopen it.